content
stringlengths
22
815k
id
int64
0
4.91M
def render_heat_table(frame: pd.DataFrame) -> None: """ renders a dataframe as a heatmap :param frame: the frame to render :return: None """ cm = mpl.cm.get_cmap('RdYlGn') styled = frame.style.background_gradient(cmap=cm, axis=0).format('{:.2f}').set_properties( **{'text-align': 'cen...
35,800
def test_arguments(): """Test arguments passed to bermuda.""" args = get_arguments(['--config', 'path/to/config']) config_dir = args.config assert config_dir == 'path/to/config'
35,801
def reservation_rollback(context, reservations, project_id=None, user_id=None): """Roll back quota reservations.""" return IMPL.reservation_rollback(context, reservations, project_id=project_id, user_id=user_id)
35,802
def encrypt( security_control: SecurityControlField, system_title: bytes, invocation_counter: int, key: bytes, plain_text: bytes, auth_key: bytes, ) -> bytes: """ Encrypts bytes according the to security context. """ if not security_control.encrypted and not security_control.aut...
35,803
def leftmost_turn(((x0, y0), (x1, y1)), (x, y), zs): """Find the line segment intersecting at the leftmost angle relative to initial segment. Arguments: (x0, y0) – where we started (x1, x2) – direction travelling in (x, y) – where intersected one or more alternative line segments ...
35,804
def _merge_timeseries(rows, cols, params): """ Merge time series output """ log.info("Merging timeseries output") shape, tiles, ifgs_dict = _merge_setup(rows, cols, params) # load the first tsincr file to determine the number of time series tifs tsincr_file = join(params[cf.TMPDIR], 'tsincr...
35,805
def maya_window(): """Get Maya MainWindow as Qt. Returns: QtWidgets.QWidget: Maya main window as QtObject """ return to_qwidget("MayaWindow")
35,806
def soap2Dict(soapObj): """A recursive version of sudsobject.asdict""" if isinstance(soapObj, sudsobject.Object): return {k: soap2Dict(v) for k, v in soapObj} elif isinstance(soapObj, list): return [soap2Dict(v) for v in soapObj] return soapObj
35,807
def generate_sequential_BAOAB_string(force_group_list, symmetric=True): """Generate BAOAB-like schemes that break up the "V R" step into multiple sequential updates E.g. force_group_list=(0,1,2), symmetric=True --> "V0 R V1 R V2 R O R V2 R V1 R V0" force_group_list=(0,1,2), symmetric=False --> ...
35,808
def _get_active_tab(visible_tabs, request_path): """ return the tab that claims the longest matching url_prefix if one tab claims '/a/{domain}/data/' and another tab claims '/a/{domain}/data/edit/case_groups/' then the second tab wins because it's a longer match. """ matching_...
35,809
def path_normalize(path, target_os=None): """Normalize path (like os.path.normpath) for given os. >>> from piecutter.engines.jinja import path_normalize >>> path_normalize('foo/bar') 'foo/bar' >>> path_normalize('foo/toto/../bar') 'foo/bar' Currently, this is using os.path, i.e. the separa...
35,810
def fit_scale_heights(data, masks, min_lat = None, max_lat = None, deredden = False, fig_names = None, return_smoothed = False, smoothed_width = None, xlim = None, ylim = None, robust = True, n_boot = 10000): """ Fits scale height data and returns slopes Parameters ---------- data: `...
35,811
def _check_meas_specs_still_todo( meas_specs: List[_MeasurementSpec], accumulators: Dict[_MeasurementSpec, BitstringAccumulator], stopping_criteria: StoppingCriteria, ) -> Tuple[List[_MeasurementSpec], int]: """Filter `meas_specs` in case some are done. In the sampling loop in `measure_grouped_sett...
35,812
def get_aircon_mock(said): """Get a mock of an air conditioner.""" mock_aircon = mock.Mock(said=said) mock_aircon.connect = AsyncMock() mock_aircon.fetch_name = AsyncMock(return_value="TestZone") mock_aircon.get_online.return_value = True mock_aircon.get_power_on.return_value = True mock_air...
35,813
def mutation(individual): """ Shuffle certain parameters of the network to keep evolving it. Concretely: - thresh, tau_v, tau_t, alpha_v, alpha_t, q """ individual[0].update_params() return individual,
35,814
async def test_migrate_entry(hass): """Test successful migration of entry data.""" legacy_config = { axis.CONF_DEVICE: { axis.CONF_HOST: "1.2.3.4", axis.CONF_USERNAME: "username", axis.CONF_PASSWORD: "password", axis.CONF_PORT: 80, }, axis....
35,815
def truncate_repeated_single_step_traversals_in_sub_queries( compound_match_query: CompoundMatchQuery, ) -> CompoundMatchQuery: """For each sub-query, remove one-step traversals that overlap a previous traversal location.""" lowered_match_queries = [] for match_query in compound_match_query.match_querie...
35,816
def intersect(list1, list2): """ Compute the intersection of two sorted lists. Returns a new sorted list containing only elements that are in both list1 and list2. This function can be iterative. """ result_list = [] idx1 = 0 idx2 = 0 while idx1 < len(list1) and idx...
35,817
def get_parent_project_ids(project_id: int, only_if_child_can_add_users_to_parent: bool = False) -> typing.List[int]: """ Return the list of parent project IDs for an existing project. :param project_id: the ID of an existing project :param only_if_child_can_add_users_to_parent: whether or not to only ...
35,818
def get_all_object_names(bucket, prefix=None, without_prefix=False): """ Returns the names of all objects in the passed bucket Args: bucket (str): Bucket path prefix (str, default=None): Prefix for keys withot_prefix (bool, default=False) Returns: lis...
35,819
def integral_length(v): """ Compute the integral length of a given rational vector. INPUT: - ``v`` - any object which can be converted to a list of rationals OUTPUT: Rational number ``r`` such that ``v = r u``, where ``u`` is the primitive integral vector in the direction of ``v``. EXAM...
35,820
def load_classification_pipeline( model_dir: str = "wukevin/tcr-bert", multilabel: bool = False, device: int = 0 ) -> TextClassificationPipeline: """ Load the pipeline object that does classification """ try: tok = ft.get_pretrained_bert_tokenizer(model_dir) except OSError: tok =...
35,821
def rest_target_disable(args): """ :param argparse.Namespace args: object containing the processed command line arguments; need args.target :raises: IndexError if target not found """ for target in args.target: rtb, rt = _rest_target_find_by_id(target) rtb.rest_tb_target_disabl...
35,822
def skew_image(img, angle): """ Skew image using some math :param img: PIL image object :param angle: Angle in radians (function doesn't do well outside the range -1 -> 1, but still works) :return: PIL image object """ width, height = img.size # Get the width that is to be added to the i...
35,823
def delete_empty_folders(logger, top, error_dir): """ This function recursively walks through a given directory (`top`) using depth-first search (bottom up) and deletes any directory that is empty (ignoring hidden files). If there are directories that are not empty (except hidden files), it wil...
35,824
def test_process_bto_order_high_risk(monkeypatch, capsys, caplog): """BTO order should be correctly processed with high risk flag set """ caplog.set_level(logging.INFO) monkeypatch.setitem(USR_SET, "high_risk_ord_value", 1000) monkeypatch.setitem(USR_SET, "buy_limit_percent", 0.03) monkeypatch.setit...
35,825
def _load_tests_from_module(tests, module, globs, setUp=None, tearDown=None): """Load tests from module, iterating through submodules. """ for attr in (getattr(module, x) for x in dir(module) if not x.startswith("_")): if isinstance(attr, types.ModuleType): suite = doctest.DocTestSuite( ...
35,826
def p_expr_comment(p): """expr : COMMENT """ p[0] = Comment(p[1])
35,827
def setup_node(config, envs): """ Install node dependencies language: node_js node_js: - "0.12" """ for version in listify(config.get('node_js', [])): setup = [] envs.append(setup) setup.append(apt_get('ca-certificates', 'curl')) setup.append( ...
35,828
def run(command, *args): """Application caller wrap console call 'command args' """ args_str = " " + " ".join(str(s) for s in list(args[0])) if len(args_str) > 0 : command += " " + args_str print "Running", command retcode = check_call(command, shell=True) if retcode < 0: ...
35,829
def info(ctx, objects): """ Obtain all kinds of information """ if not objects: status(ctx) for obj in objects: process_object(ctx, obj)
35,830
def pp(): """Payback Period""" a = input("For Payback with Equal Annual Net Cash Inflows Press 1\nFor Payback with Unequal Net Cash Inflows Press 2: ") if (a == 1): b = float(input("Please Enter Total Amount Invested: ")) c = float(input("Please Enter Expected Annual Net Cash Inflow: ")...
35,831
def calculate_full_spectrum(xs, cp, ep=None, betas=(0,0), data=None): """Direct solution of the k-eigenvalue problem in integral transport by the collision probability method. Input data are the xs list and the collision probabilities in cp. Only isotropic scattering is allowed. A relation of albedo for...
35,832
def plot_confusion_matrix(cm, classes, normalize=False, cmap=None): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if cmap is None: cmap = plt.cm.Blues if normalize: cm = cm.astype('float') / cm.sum(axis=1)[...
35,833
def get_connectors_by_type(type : str): """ Convenience method for `get_connectors()`. """ return get_connectors(type)
35,834
def test_heart_get_params(withings_api: WithingsApi) -> None: """Test function.""" responses_add_heart_get() withings_api.heart_get(signalid=1234567) assert_url_query_equals( responses.calls[0].request.url, {"signalid": "1234567"}, ) assert_url_path(responses.calls[0].request.url, "/v2...
35,835
def test_scipy_dense_solvers_num_argument(): """ By default, the Scipy dense solvers compute all eigenpairs of the eigenproblem. We can limit the number of solutions returned by specifying the 'num' argument, either directly when instantiating the solver or when calling the eigenproblem.solve() meth...
35,836
def crawl(alphabet, initial, accepts, follow): """ Create a new FSM from the above conditions. """ states = [initial] accepting = set() transition = dict() i = 0 while i < len(states): state = states[i] if accepts(state): accepting.add(i) transitio...
35,837
def mpncovresnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = MPNCOVResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_ur...
35,838
def cathegory_encoder(data, labelCathegory=labelCathegory): """ Encode cathegorical labels """ for k in labelCathegory: encoder = sklearn.preprocessing.LabelEncoder() encoder.fit(list(data[k].values)) data[k] = encoder.transform(list(data[k].values)) return data
35,839
def _make_symbols_cg_df(symbols, benchmark): """ 相关性金融数据收集,子进程委托函数,子进程通过make_kl_df完成主进程委托的symbols个 金融数据收集工作,最终返回所有金融时间序列涨跌幅度pd.DataFrame对象 :param symbols: 可迭代symbols序列,序列中的元素为str对象 :param benchmark: 进行数据收集使用的标尺对象,数据时间范围确定使用,AbuBenchmark实例对象 :return: 所有金融时间序列涨跌幅度pd.DataFrame对象 """ # 子进程金...
35,840
def split_dataset(args, dataset): """Split the dataset Parameters ---------- args : dict Settings dataset Dataset instance Returns ------- train_set Training subset val_set Validation subset test_set Test subset """ train_ratio, v...
35,841
def test_join_smart_url_with_path_and_basename(): """Test join_smart functionality.""" CORRECT = "gsiftp://gridftp.zeuthen.desy.de:2811/pnfs/ifh.de/acs/icecube/archive/data/exp/IceCube/2015/filtered/level2/0320/fdd3c3865d1011eb97bb6224ddddaab7.zip" assert join_smart_url(["gsiftp://gridftp.zeuthen.desy.de:28...
35,842
def test_ky_mat_update(params): """ check ky_mat_update function """ hyps, name, kernel, cutoffs, \ kernel_m, hyps_list, hyps_mask_list = params # prepare old data set as the starting point n = 5 training_data = flare.gp_algebra._global_training_data[name] flare.gp_algebra....
35,843
async def test_multi_level_wildcard_topic_not_matching(hass, mock_device_tracker_conf): """Test not matching multi level wildcard topic.""" dev_id = "paulus" entity_id = ENTITY_ID_FORMAT.format(dev_id) subscription = "/location/#" topic = "/somewhere/room/paulus" location = "work" hass.conf...
35,844
def depthwise_conv2d_nchw(inputs, weight, bias=None, stride=1, padding=0, dilation=1): """Depthwise convolution 2d NCHW layout Args: ----------------------------- inputs : tvm.te.tensor.Tensor shape [batch, channel, height, width] weight : tvm.te.tensor.Tensor shape [in_channel, f...
35,845
def xtransformed(geo, transformation): """Returns a copy of the transformed Rhino Geometry object. Args: geo (:class:`Rhino.Geometry.GeometryBase`): a Rhino Geometry object transformation (:class:`Transformation`): the transformation. Returns: (:class:`Rhino.Geometry.GeometryBase`)...
35,846
def function_calls(libfuncs): """ libfuncs is the list of library functions called in script. Returns ths list of all library functions required in script """ libfuncs2 = set() while libfuncs: func = libfuncs.pop() libfuncs2.add(func) for func in called_functions(func): ...
35,847
def test_stack_component_dict_only_contains_public_attributes( stub_component, ): """Tests that the `dict()` method which is used to serialize stack components does not include private attributes.""" assert stub_component._some_private_attribute_name == "Also Aria" expected_dict_keys = {"some_publi...
35,848
def preprocess_yaml_config(config: SimpleNamespace, prefix_keys=False) -> SimpleNamespace: """ Preprocess a simple namespace. Currently, - prepend the prefix key to all the configuration parameters - change 'None' strings to None values :param config: The SimpleNamespace containing the configuration...
35,849
def TerminateProcess(hProcess, uExitCode): """ Terminates the specified process and all of its threads. .. seealso:: https://msdn.microsoft.com/en-us/library/ms686714 :param pywincffi.wintypes.HANDLE hProcess: A handle to the process to be terminated. :param int uExitCode: ...
35,850
def gisinf(x): """ Like isinf, but always raise an error if type not supported instead of returning a TypeError object. Notes ----- `isinf` and other ufunc sometimes return a NotImplementedType object instead of raising any exception. This function is a wrapper to make sure an exception...
35,851
def do_configuration_list(cs, args): """Lists all configuration groups.""" config_grps = cs.configurations.list(limit=args.limit, marker=args.marker) utils.print_list(config_grps, [ 'id', 'name', 'description', 'datastore_name', 'datastore_version_name'])
35,852
def make_const(g, # type: base_graph.BaseGraph name, # type: str value, # type: np.ndarray uniquify_name=False # type: bool ): """ Convenience method to add a `Const` op to a `gde.Graph`. Args: g: The graph that the node should be added to name:...
35,853
def find_maxima(x): """Halla los índices de los máximos relativos""" idx = [] N = len(x) if x[1] < x[0]: idx.append(0) for i in range(1, N - 1): if x[i-1] < x[i] and x[i+1] < x[i]: idx.append(i) if x[-2] < x[-1]: idx.append(N - 1) return idx
35,854
def _transform_rankings(Y): """Transform the rankings to integer.""" Yt = np.zeros(Y.shape, dtype=np.int64) Yt[np.isfinite(Y)] = Y[np.isfinite(Y)] Yt[np.isnan(Y)] = RANK_TYPE.RANDOM.value Yt[np.isinf(Y)] = RANK_TYPE.TOP.value return Yt
35,855
async def lumberjack(ctx): """a class that Dylan wanted to play as for some reason""" if ctx.invoked_subcommand is None: embed=discord.Embed(title="LUMBERJACK", url="https://docs.google.com/document/d/1ZpodR2KdgA-BPQdYwoeiewuONXkjLt3vMwlK6JHzB_o/edit#bookmark=id.j8e62xi5b8cu", description=":evergreen...
35,856
def get_config(key=None, default=None, raise_error=False): """Read expyfun preference from env, then expyfun config Parameters ---------- key : str The preference key to look for. The os environment is searched first, then the expyfun config file is parsed. default : str | None ...
35,857
def check_exist(path, mode, flag_exit=True): """ function to check for file existence @param path(str): target file path @param mode(int): 1(existence) / 2(existence for file) / 3(existence for dir) @param flag_exit(bool): Exit if not present (Default: True) @param (bool) or exit(None) """ if mode == 1: if no...
35,858
def convert_pf_patch_to_cg_patch(p, simnum): """Converts a pfpatch p to a CG patch.""" # Print patch info LOGGER.info("Macro patch is:") LOGGER.info(str(p)) LOGGER.info("Patch id = {}".format(p.id)) LOGGER.info("Protein bead ids = {}".format(p.protein_ids)) LOGGER.info("Protei...
35,859
def find_error_detect(image_path): """ 给一张图片,判断是否检查正确,错误则保存下来。 :param image_path: :return: """ save_path = './ctpn_detect_error.txt' image = cv2.imread(image_path) # 传输给服务器的数据 data = {'fname': image_path, 'img_str': _img_to_str_base64(image)} # test by EAST mode res_east_d...
35,860
def MPS_SimRemoveRule(rule_id: int) -> None: """Removes a simulation rule Parameters ---------- rule_id : int Rule identifier """ _check_limits(c_uint32, rule_id, 'rule_id') CTS3Exception._check_error(_MPuLib.MPS_SimRemoveRule( c_uint8(0), c_uint32(0), c_uint...
35,861
def appendItem(): """Includes product into invoice and redirect""" app.logger.debug('This is appendItem to PO process') if request.method == 'POST': (prod_properties, check_up) = checkProduct(request.form) if check_up: appendProduct(prod_properties, session['userID']) session...
35,862
def gzip_bytes(bytes_obj): """byte: Compress a string as gzip in memory. """ if isinstance(bytes_obj, (str,)): bytes_obj = bytes_obj.encode() out_ = io.BytesIO() with gzip.GzipFile(fileobj=out_, mode='w') as fo: fo.write(bytes_obj) return out_
35,863
def ones_like(other_ary): """ Create a PitchArray with all entry equal 1, whose shape and dtype is the same as other_ary """ result = PitchArray(other_ary.shape, other_ary.dtype) result.fill(1) return result
35,864
def inference_multiview(views, n_classes, keep_prob): """ views: N x V x W x H x C tensor """ n_views = views.get_shape().as_list()[1] # transpose views : (NxVxWxHxC) -> (VxNxWxHxC) views = tf.transpose(views, perm=[1, 0, 2, 3, 4]) view_pool = [] for i in xrange(n_views): # set...
35,865
def trueReturn(data, msg): """ 操作成功结果 """ result = { "status": True, "data": data, "msg": msg } return JSONResponse(content=result)
35,866
def active_power_from_waveform(t, V, I, sampling_rate, ts): """ :param t: time vector (numpy) :param V: voltage vector (numpy) :param I: current vector (numpy) :param sampling_rate - sampling rate (int) :param ts - test script with logging capabilities :return: : avg_P - Average active ...
35,867
def parse_slurm_times(job_id: str, path: Path = Path.cwd()) -> float: """Performs the parsing of the file slurm-{job_id}.out by returning in milliseconds the time measured by Slurm. Args: out_file (str): The job slurm output file path to parse. path (Path): The path where to look for the sl...
35,868
def bprl(positive: torch.Tensor, negative: torch.Tensor) -> torch.Tensor: """ Bayesian Personalized Ranking Loss https://arxiv.org/ftp/arxiv/papers/1205/1205.2618.pdf """ dist = positive - negative return -F.logsigmoid(dist).mean()
35,869
def select2_js_url(): """ Return the full url to the Select2 JavaScript library Default: ``None`` # Example {% select2_js_url %} """ return sl2.select2_js_url()
35,870
def _SharedSuffix(pattern1, pattern2): """Returns the shared suffix of two patterns.""" return _SharedPrefix(pattern1[::-1], pattern2[::-1])[::-1]
35,871
def run(args): """Handle credstash script.""" parser = argparse.ArgumentParser( description=("Modify Home Assistant secrets in credstash." "Use the secrets in configuration files with: " "!secret <name>")) parser.add_argument( '--script', choices=['c...
35,872
def cromwell_version(host): """Return the version of this Cromwell server""" client = CromwellClient(host) data = call_client_method(client.version) click.echo(data)
35,873
def test_transform_section_data() -> None: """ Test transform_section_data """ expected = CON333_LEC2001 actual = a2_part4.transform_section_data(CON333_LEC2001_RAW) assert actual == expected
35,874
def export_urls(urls, file_path): """[summary] Arguments: urls {[list]} -- [extracted urls] file_path {[str]} -- [result text file path] """ with open(file_path.replace(".txt", "_links.txt"), "w") as f: f.write("\n".join(urls))
35,875
def handle_request_files_upload(request): """ Handle request.FILES if len(request.FILES) == 1. Returns tuple(upload, filename, is_raw, mime_type) where upload is file itself. """ # FILES is a dictionary in Django but Ajax Upload gives the uploaded file # an ID based on a random number, so it can...
35,876
def vgg16(num_class): """VGG 16-layer model (configuration "D") with batch normalization """ model = VGG(make_layers(cfg['D'], batch_norm=True), num_classes=num_class) return model
35,877
def setup_logging( config_path="logging.yaml", config_path_env="LOG_CFG_PATH" ): """Setup the python logger Args: config_path (str): Path to a default config file config_path_env (str): Env variable to specify alternate logging config """ config_override = os.getenv(conf...
35,878
def test_eval_dlM_dm_02(): """ Tests evaluation of derivative of log M w.r.t. mu for k = 0, l = 2. """ (N, U) = (6, 5) C = fcdiff.util.N_to_C(N) norm = rand_prob((C, U)) mix = rand_prob((C, U)) mu = 0.14 sigma = 0.02 epsilon = 0.07 eta = 0.29 act_dlM_dm = fcdiff.fit._eva...
35,879
def __update_dict(orig, update): """Deep update of a dictionary For each entry (k, v) in update such that both orig[k] and v are dictionaries, orig[k] is recurisvely updated to v. For all other entries (k, v), orig[k] is set to v. """ for (key, value) in update.items(): if (key in orig...
35,880
def EMA(moving_average_model: nn.Module, current_model: nn.Module, beta: float): """Exponential Moving Average""" for c_params, ma_params in zip(current_model.parameters(), moving_average_model.parameters()): ma_weight, c_weight = ma_params.data, c_params.data ma_params.data = beta*ma_weight + (...
35,881
def IFS(*args) -> Function: """ Evaluates multiple conditions and returns a value that corresponds to the first true condition. Learn more: https//support.google.com/docs/answer/7014145 """ return Function("IFS", args)
35,882
def idwt_joined_(w, rec_lo, rec_hi, mode): """Computes single level discrete wavelet reconstruction """ n = len(w) m = n // 2 ca = w[:m] cd = w[m:] x = idwt_(ca, cd, rec_lo, rec_hi, mode) return x
35,883
def _get_pattern_nts(rule): """ Return a list of NT names present in given rule. """ nt_names = [] for bt in rule.ipattern.bits: if bt.is_nonterminal(): nt_name = bt.nonterminal_name() nt_names.append(nt_name) return nt_names
35,884
def collision_time(results_dir): """Calculate the time of the collision.""" out_file = results_dir + '/collision_time.txt' if os.path.isfile(out_file): return print("Calculating collision time in directory " + results_dir) import yt # Load all the output files in the output director...
35,885
async def on_message(msg): """Ignore messages not sent via DM or in the bot's designated channel.""" if msg.guild is None or msg.channel.id == ANNOUNCEMENTS_CHANNEL_ID: await bot.process_commands(msg)
35,886
def do_extend(cs, args): """Increases the size of an existing share.""" share = _find_share(cs, args.share) cs.shares.extend(share, args.new_size)
35,887
def stopping_player(bot, state): """ A Player that just stands still. """ return bot.position
35,888
def check_continue(transformer: transformer_class.Transformer, check_md: dict, transformer_md: dict, full_md: dict) -> tuple: """Checks if conditions are right for continuing processing Arguments: transformer: instance of transformer class Return: Returns a tuple containining the return code...
35,889
def getFlatten(listToFlat): """ :param listToFlat: anything ,preferably list of strings :return: flatten list (list of strings) #sacred """ preSelect=mc.ls(sl=True,fl=True) mc.select(cl=1) mc.select(listToFlat) flatten = mc.ls(sl=True, fl=True) mc.select(preSelect) return...
35,890
def can_exit_room(state: State, slot: int) -> bool: """ Return True if amphipod can escape a room because all amphipods are in their place Not exhaustive! If there are amphipods above it, it may still be stuck """ amphipod = state[slot] assert amphipod != EMPTY_SLOT room = slot // 4 bott...
35,891
def square_matrix(square): """ This function will calculate the value x (i.e blurred pixel value) for each 3*3 blur image. """ tot_sum = 0 # Calculate sum of all teh pixels in a 3*3 matrix for i in range(3): for j in range(3): tot_sum += square[i][j] return tot_sum/...
35,892
def create_continuous_plots(df: pd.DataFrame, reporting_features: List[str], model_config: Dict[str, Any]) -> None: """Create line plot to show how target varies according to feature. No returns; saves assets to model folder. Args: df: Full, feature rich dataframe, must contain config specified ...
35,893
def before_after_text(join_set, index, interval_list): """ Extracts any preceeding or following markup to be joined to an interval's text. """ before_text, after_text = '', '' # Checking if we have some preceeding or following markup to join with. if join_set: if index > 0: ...
35,894
def validate_kubernetes_tag(config): """ Checks the presence of Kubernetes tag """ logger.info("checking kubernetes tag") validate_dict_data(config, consts.K8S_KEY)
35,895
def run_unpack(target_archive: str, target_folder: str, *target_files: str): """ creates target_folder where it unpacks listed target_files from target_archive then exits program :param target_archive: the path to an already created archive :param target_folder: the path to the unpack location dire...
35,896
def calculate_platform_symmetries(cfg): """Calculate the Automorphism Group of a Platform Graph This task expects three hydra parameters to be available. **Hydra Parameters**: * **platform:** the input platform. The task expects a configuration dict that can be instantiated to a ...
35,897
def load_data(outputpath): """Load the numpy data as stored in directory outputpath. Parameters ---------- outputpath : str directory where the numpy files are stored Returns ------- x_train y_train_binary x_val y_val_binary x_test y_test_binary """ ext ...
35,898
def create_server_ssl(addr, port, backlog): """ """ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((addr, port)) server.listen(backlog) context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) context.load_default_certs() wrap = context.wrap_socket(server, do_hand...
35,899