content
stringlengths
22
815k
id
int64
0
4.91M
def _update_PlotbandFrame_Plots(self, parentFrame: Frame) -> None: """ Description ----------- Method for displaying the plots of the FreiStat Parameters ---------- `parentFrame` : Frame Parent frame in which the plot band frame is embedded """ # Clear the listbox widget fo...
5,294,400
def highlight_min(dsty, bg_color="#ffd700", axis=0, df_slice=None): """FIXME! briefly describe function :param dsty: :param bg_color: :param axis: 0=index,1=column, None=all elements :returns: :rtype: """ res = dsty.highlight_min(color=bg_color, axis=axis, subset=df_slice) retu...
5,294,401
def create_layer_points(ds: ogr.DataSource, srs: osr.SpatialReference, layer_name: str) -> None: """ Creates layer within `ds` with `srs` Spatial Reference System and `layer_name` name with `ogr.wkbPoint` geometry type. Parameters ---------- ds : ogr.DataSource `ogr.DataSource` to creat...
5,294,402
def analyzeDependency(indentCount,package): """ 依存関係を解析する """ printDependencyPackage(indentCount,package) #依存関係取得 dependPackages = getDependencyPackages(package) if len(dependPackages) > 0: for dependPackage in dependPackages: if dependPackage not in memo: #メモに追加 memo.append(de...
5,294,403
def summary_stats(tile_summary): """ Obtain various stats about the slide tiles. Args: tile_summary: TileSummary object. Returns: Various stats about the slide tiles as a string. """ return "Original Dimensions: %dx%d\n" % (tile_summary.orig_w, tile_summary.orig_h) + \ "Original Tile Siz...
5,294,404
def soundnet5_model_params(model_filename=None, num_classes=None, scope='SoundNet'): """ Load model parameters from Torch file. """ def retrieve_if_not_none(local_net, layer_num, var_name): return None if local_net is None else \ local_net['modules'][layer_num][var_name] def transpose_if_n...
5,294,405
def landsat457_cloud_mask_func(img): """Apply basic ACCA cloud mask to a daily Landsat 4, 5, or 7 image""" cloud_mask = ee.Algorithms.Landsat.simpleCloudScore(img).\ select(['cloud']).lt(ee.Image.constant(50)) return img.mask(cloud_mask.mask(cloud_mask))
5,294,406
def check_if_in_team(api, team_id, person): """ Checks if a person is in a given team :param api: CiscoSparkAPI instance to query Spark with. :param team_id: The ID of the team to check for :param person: The person to check against the team """ team_memberships = api.team_memberships.list(te...
5,294,407
def handle_public_events(iterable): """Report private repositories being made public, and new releases.""" lines = [] unused = iterable # Private -> Public Transitions events, unused = partition_type('PublicEvent', unused) for event in events: tmpl = 'made {} public' lines.appen...
5,294,408
def generate_sub_tetrahedrons(a, b, c, d): """ Generate sub-tetrahedrons. Returns tuple of tetrahedrons. ARGUMENTS: a, b, c, d - vertices of tetrahedron """ sub_tetra = [] sub_tetra.append((a, midpoint(a, b), midpoint(a, c), midpoint(a, d))) sub_tetra.append((midpoint(a, b), b, midpoin...
5,294,409
def check_true(expression: bool, exception: Exception) -> NoReturn: """ Checks that given expression is true, otherwise raises the given exception. """ if not expression: raise exception
5,294,410
def ExtractMemoryDumpIds(trace_builder): """Get a list with the ids of 'GlobalMemoryDump' events found in a trace. Args: trace_builder: A TraceDataBuilder object; trace data is extracted from it and the builder itself is cleaned up. """ event_ids = _SerializeAndProcessTrace( trace_builder, _GET...
5,294,411
def get_vm_format_secret(secrets, certificate_store=None): """ Format secrets to be used in `az vm create --secrets` :param dict secrets: array of secrets to be formatted :param str certificate_store: certificate store the secret will be applied (Windows only) :return: formatted secrets as an array ...
5,294,412
def instance(type_cls, cls): """ Decorator for creating a typeclass instance. Examples: >>> from abc import ABC, abstractmethod >>> from pycats import typeclass, instance >>> >>> @typeclass ... class Functor(ABC): ... ... @abstractmethod ... ...
5,294,413
def test_md003_atxclosed_all_samples(): """ Test to make sure we get the expected behavior after scanning the files in the test/resources/rules/md003 directory with an "atx closed" configuration. """ # Arrange scanner = MarkdownScanner() supplied_configuration = {"plugins": {"md003": {"styl...
5,294,414
def get_inputs(seq_len: int) -> tensorflow.Tensor: """Get input layers. See: https://arxiv.org/pdf/1810.04805.pdf Args seq_len: Length of the sequence or None. """ names = ['Token', 'Segment'] # , 'Masked'] return [ keras.layers.Input( shape=(None,), ...
5,294,415
def validate(obj, obj_type): """Validate a dictionary, list, or graph object as 'obj_type'. This will not alter the 'obj' referenced in the call signature. It will raise an error if the 'obj' reference could not be instantiated as a valid 'obj_type' graph object. """ # TODO: Deprecate or move....
5,294,416
def replace_self_attention_layer_with_sparse_self_attention_layer( config, layers, # SparsityConfig parameters needs to be set accordingly sparsity_config=SparsityConfig(num_heads=4)): """This function replaces the self attention layers in attention layer with sparse self attention. For sparsity...
5,294,417
def mape(y_true: pd.Series, y_pred: pd.Series) -> float: """Compute Mean Absolute Percentage Error (MAPE) Args: y_true (pd.Series): actual values y_pred (pd.Series): predict values Returns: float: mape value """ return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
5,294,418
def list_mutations(context): """ :type context: Context """ assert context.mutation_id == ALL mutate(context) return context.performed_mutation_ids
5,294,419
def test01(): """ 爬虫有时候需要登陆后才能获取数据,不建议使用cookie, 因为cookie的话会暴露自己的账号,会导致该账号因为爬虫被永久封禁 1- 不要使用cookie 2- 降低数据采集速度 """ url = 'http://www.renren.com/474692517' headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.7...
5,294,420
def tag(version_number): """ Set the version to deploy to `version_number`. """ execute(pydiploy.prepare.tag, version=version_number)
5,294,421
def split_data(x_all, y_all, test_percent=0.01): """ split the data to train set and test set :param x_all: all the x : (count,n_features) :param y_all: all the y : (count,1) :param percent: the percent of the test set [0,1] :return: (x_train, y_train), (x_test, y_test) """ total_count ...
5,294,422
async def make_keyboard_from_json(query: str, message: Message) -> Optional[Message]: """ Запрос в конструктор из json формата :param query: JSON запрос :param message: Объект сообщения пользователя """ try: data = json.loads(query) return await ConstructorManager.from_json(data,...
5,294,423
def group_per_category(bkgs): """ Groups a flat list of datasets into sublists with the same category E.g. [ ttjet, ttjet, ttjet, qcd, qcd ] --> [ [ttjet, ttjet, ttjet], [qcd, qcd] ] """ cats = list(set(bkg.get_category() for bkg in bkgs)) cats.sort() return [ [ b for b in bkgs if b.get_cate...
5,294,424
def subtract_params(param_list_left: list, param_list_right: list): """Subtract two lists of parameters :param param_list_left: list of numpy arrays :param param_list_right: list of numpy arrays :return: list of numpy arrays """ return [x - y for x, y in zip(param_list_left, param_list_right)]
5,294,425
def rebin_or(newbins, oldbins, oldvalues): """Deprecated as of 2015-02-15. Use rebin instead.""" return rebin(newbins, oldbins, oldvalues, method='or')
5,294,426
def handle(name, cloud_config, cloud, log, args): """Cloud-init processing function""" tag = MODULE_NAME enabled = False if tag in cloud_config: try: enabled = bool(cloud_config[tag]['enabled']) except Exception: LOG.error("%s missing enabled attribute", tag) ...
5,294,427
def get_groups_of_molec(molec, groups:dict, df_in, ind:int): """Function to that looks for a variety of functional groups, defined in "groups" within a specific molecule. Will add this data into the dataframe, df at index, ind. Inputs: ------- molec - An RDKit molecule...
5,294,428
def mkrefpath(r:DRef, items:List[str]=[])->RefPath: """ Construct a [RefPath](#pylightnix.types.RefPath) out of a reference `ref` and a path within the stage's realization """ assert_valid_dref(r) return [str(r)]+items
5,294,429
def resize(url, width): """ Return a url to a resized version of the given image at the url -- only works for files hosted on your MEDIA_ROOT --- CACHE THIS HEAVILY """ width = int(width) regex = get_media_url_regex() # check to see if the url is one we can handle, otherwise just r...
5,294,430
async def me( request: Request, scopedTo: ScopedTo = ScopedTo( [UserScope.admin, UserScope.auditor, UserScope.guardian, UserScope.voter] ), ) -> UserInfo: """ Get user info for the current logged in user. """ token_data = scopedTo(request) if token_data.username is None: ...
5,294,431
def test_main_invalid_resolution_skipped( runner: click.testing.CliRunner, mock_file_handler_get_filenames: Mock, mock_pdf_splitter_pdfsplitter: Mock, ) -> None: """It exits with a status code of zero.""" mock_pdf_splitter_pdfsplitter.return_value.validate_resolution.return_value = False result ...
5,294,432
def crop_center(image): """Returns a cropped square image.""" shape = image.shape new_shape = min(shape[1], shape[2]) offset_y = max(shape[1] - shape[2], 0) // 2 offset_x = max(shape[2] - shape[1], 0) // 2 image = tf.image.crop_to_bounding_box( image, offset_y, offset_x, new_shape, new_s...
5,294,433
def load_video(video_data, *, config=VideoLoaderConfig()): """Load a video into the database""" video_id = video_data.pop("video_id") platform = video_data.pop("platform") topics_data = video_data.pop("topics", None) offered_bys_data = video_data.pop("offered_by", None) with transaction.atomic(...
5,294,434
async def is_float(obj: Union[Message, CallbackQuery]) -> bool: """ Checks if message text can be converted to float :return: True if so """ obj = await _to_message(obj) return obj.text and obj.text.isnumeric()
5,294,435
def _context_license_spdx(context, value): """convert a given known spdx license to another one""" # more values can be taken from from https://github.com/hughsie/\ # appstream-glib/blob/master/libappstream-builder/asb-package-rpm.c#L76 mapping = { "Apache-1.1": "ASL 1.1", "Apache-2.0...
5,294,436
def html_header(): """ Global & common html header. SHould be used everywhere Returns: -------- out: str """ return """ <!DOCTYPE html> <head> <link rel="stylesheet" type="text/css" href="css/finkstyle.css"> <title>Mon programme test</title> </head> <body> ...
5,294,437
def executeCommand(command, cwd=None, env=None, input=None, timeout=0): """ Execute command ``command`` (list of arguments or string) with * working directory ``cwd`` (str), use None to use the current working directory * environment ``env`` (dict), use None for none ...
5,294,438
def test_hist_append(hist, xonsh_builtins): """Verify appending to the history works.""" xonsh_builtins.__xonsh_env__['HISTCONTROL'] = set() hf = hist.append({'inp': 'still alive', 'rtn': 0}) assert hf is None assert 'still alive' == hist.buffer[0]['inp'] assert 0 == hist.buffer[0]['rtn'] as...
5,294,439
def enqueue_ide_reap_stale(*args): """Reap stale ide resources""" rpc_enqueue(reap_stale_theia_sessions, queue='theia', args=args)
5,294,440
def build_repository_type_select_field( trans, repository=None, name='repository_type' ): """Called from the Tool Shed to generate the current list of supported repository types.""" if repository: selected_type = str( repository.type ) else: selected_type = None repository_type_select_fi...
5,294,441
def wrf_cloudtemp(data_pstag, data_tstag, data_qstag, data_cloudstag, data_zstag, data_mapfc, data_icestag): """Function to compute ``ctt`` using wrf-python. Args: data_pstag (Xarray data array): Total pressure (P0+PB) (3d). data_tstag (Xarray data array): Temperature (3d). dat...
5,294,442
def get_boolean_value(file_location, section, key): """ Searches an INI Configuration file for a section & key and returns it as a string. :param file_location: The file to get a key value from :param section: The section to find the key value :param key: The key that can contain a value to retriev...
5,294,443
def lucyrichardson(files, psf_path, **kwargs): """lucyrichardson command Parameters ---------- files psf_kernel kwargs : dict """ psf_kernel = None if psf_path != "": psf_kernel = imread(psf_path, value_norm=False)[0] psf_kernel = psf_kernel.astype(numpy.float32, co...
5,294,444
def net_connections(kind='inet'): """Return system-wide connections as a list of (fd, family, type, laddr, raddr, status, pid) namedtuples. In case of limited privileges 'fd' and 'pid' may be set to -1 and None respectively. The 'kind' parameter filters for connections that fit the following cri...
5,294,445
def db_check(): """ Performs a basic check on the database by performing a select query on a simple table :return: True or False according to successful retrieval """ try: HealthCheck.objects.get(health_check_field=True) return HealthStatus.OK except Exception as e: captu...
5,294,446
def get_report(readings_file): """ Prepares a report and returns it as a string. Report includes starting and ending readings, amount consumed and cost of each utility, as well as the total, how much if any was paid, and the amount outstanding. """ with open(readings_file) as csvfile: ...
5,294,447
def doMiscMovieInfo(): """Files with information on a single line about movies.""" for dataf in (('certificates.list.gz', CER_START), ('color-info.list.gz', COL_START), ('countries.list.gz', COU_START), ('genres.list.gz', GEN_START), ('keyw...
5,294,448
def parse_template(template: WorkflowTemplate, arguments: Dict) -> Tuple[List[ContainerStep], Dict, List[str]]: """Parse a serial workflow template to extract workflow steps and output files. The expected schema of the workflow specification is as follows: .. code-block:: yaml workflow: ...
5,294,449
def to_file(game, filename, *args, **kwargs): """Write the game data to a file, based on a filename. If filename ends with .p8.png, the output is a .p8.png file. If the output file exists, its label is reused, otherwise an empty label is used. The label can be overridden by the caller with the 'lab...
5,294,450
def int_df_two_segments(int_df_one_segment) -> pd.DataFrame: """Generate dataframe with simple targets for lags check.""" df_1 = int_df_one_segment.reset_index() df_2 = int_df_one_segment.reset_index() df_1["segment"] = "segment_1" df_2["segment"] = "segment_2" df = pd.concat([df_1, df_2], ign...
5,294,451
def get_user_agent(request): """ Checks if the given user agent string matches one of the valid user agents. """ name = request.META.get('HTTP_USER_AGENT', None) if not name: return False for platform, regex in settings.USER_AGENTS.iteritems(): if re.compile(regex).search(nam...
5,294,452
def test_scan_hpss(monkeypatch, caplog, tmp_path, mock_call): """Test scan_hpss() using an existing cache. """ d = MockFile(True, 'subdir') f = MockFile(False, 'name') ff = MockFile(False, 'subname') ld = mock_call([[d, f], [ff]]) i = mock_call([False]) monkeypatch.setattr('hpsspy.os._os...
5,294,453
def configure(ctx, **kwargs): """ Generate Kubernetes manifests from a template source. This command is only useful to view the manifests with your configuration applied. To send the manifests to a cluster, see the 'apply' command. """ manifests, _ = configure_impl(**kwargs) print(manifests)
5,294,454
def indent(element, level=0): """ Indents an XML root object from ElementTree. Parameters ---------- element : ElementTree.Element The XML root object to manipulate and indent. level : int, optional I guess at which level of indentation it should start. Can be ignored and u...
5,294,455
def test_no_index_error(suppressor_implementation): """ Passes test if `IndexError` not occurs. """ with suppressor_implementation(IndexError): _ = [0, 0, 0][2]
5,294,456
def train_collate_fn(batch): """ # collate_fn这个函数的输入就是一个list,list的长度是一个batch size,list中的每个元素都是__getitem__得到的结果 """ imgs, pids, _, _, = zip(*batch) pids = torch.tensor(pids, dtype=torch.int64) return torch.stack(imgs, dim=0), pids
5,294,457
def level_4(f): """ Decorate routes to require level 4 previleges (Super Admin). IMPORTANT: Place this decorator in after @login_required Documentation here: http://flask.pocoo.org/docs/1.0/patterns/viewdecorators/ """ @wraps(f) def decorated_function(*args, **kwargs): if session...
5,294,458
def validate_permission_list_ggrb(token, num=0): """ check if the user from auth provider has the permission to list global role bindings """ user_client = get_client_for_token(token) clusters = user_client.list_global_role_binding().data assert len(clusters) == num
5,294,459
def plot_best_model(): """Plot the best model found yet.""" space_best_model = load_best_hyperspace(name=MODEL_NAME) if space_best_model is None: print("No best model to plot. Continuing...") return print("Best hyperspace yet:") print_json(space_best_model) plot(space_best_model...
5,294,460
def distance_to_border(logicarray, maxdist=65535): """ Returns the eucledian distance to the border of a binary logical array. Positive distances mean distance to the next negative (false) pixel, negative distance the distance to the next positive (true) pixel. :logicarray a binary array :maxdis...
5,294,461
def matching(file, pattern): """ 正则匹配 :param file: :param pattern: :return: """ strArray = [] # 输出每一段的内容 for para in file.paragraphs: testArr = re.findall(pattern, ''.join(para.text.split("、"))) if len(testArr): for i in testArr: for j in i...
5,294,462
def test_transformer_attribute_type(): """ Check that Transformer mapper attrs are the correct type. """ ui_dict = create_user_item_dict() t = Transformer(ui_dict) assert isinstance(t.item_inv_mapper, dict) assert isinstance(t.user_mapper, dict)
5,294,463
def encrypt_string(enabled, string, config): # type: (bool, str, dict) -> str """Encrypt a string :param bool enabled: if encryption is enabled :param str string: string to encrypt :param dict config: configuration dict :rtype: str :return: encrypted string if enabled """ if enabled:...
5,294,464
def split_data(X, y, problem_type, problem_configuration=None, test_size=.2, random_seed=0): """Splits data into train and test sets. Arguments: X (ww.DataTable, pd.DataFrame or np.ndarray): data of shape [n_samples, n_features] y (ww.DataColumn, pd.Series, or np.ndarray): target data of length...
5,294,465
def eval_mode(cfg): """Runs the evaluation-only loop.""" if cfg.VIS_TEST: assert cfg.USE_WANDB is True, "Visualizations use Wandb, therefore, it must be enabled" trainer = CSDTrainerManager(cfg) trainer.resume_or_load(resume=False) res = trainer.test(cfg, trainer._trainer.model) if com...
5,294,466
def test_push_message(log, clear_log): """Register listeners that receive messages.""" calls = list() def listener_a(x, y, z=calls): calls.append(1) def listener_b(x, y, z=calls): calls.append(1) LogObserver.register_listener(listener_a) LogObserver.register_listener(listener_b) LogObserver...
5,294,467
def get_invites_for_account(account, timeout=5): """ Gets a users invites for any gsr groups. Return invites along with details about the gsr group (color, name, group id) """ x_authorization = request.headers.get("X-Authorization") authorization = request.headers.get("Authorization") if n...
5,294,468
def test_app_group_cmd2_help_1(capsys) -> None: """Help statement printed to <stdout> with `-h`.""" status = Group.main([CMD2, '-h']) captured = capsys.readouterr() assert captured.out.strip() == CMD2_HELP.strip() assert status == exit_status.success
5,294,469
async def test_setup_timeout(hass, mock_request): """Test we give up when there is a timeout.""" with patch('aiohue.Bridge.create_user', side_effect=asyncio.TimeoutError): await MockBridge(hass).async_setup() assert len(mock_request.mock_calls) == 0
5,294,470
def handle_orphan_edges(edge_img, sobel_sig, bpm=None, flux_valid=True, buffer=0, copy=False): """ In the case of single left/right traces and multiple matching traces, pick the most significant matching trace and remove the others. If *no* left and/or right edge is present, this will add one using...
5,294,471
def convertfortdir(outputtype,nplots='fort.nplot',outputname='fort.q',\ components='all',outdir=None,fortdir=None,**kwargs): """ convert an entire directory of fort.q files to another form arguments: --------- nplots: integer for the number of plots, list of plots or fort.nplot filename ...
5,294,472
async def format_tweak_page(ctx, entries, current_page, all_pages): """Formats the page for the tweak embed. Parameters ---------- entries : List[dict] "The list of dictionaries for each tweak" all_pages : list "All entries that we will eventually iterate through" current_page :...
5,294,473
def test_setup_callables(base_driver, test_data): """Assert _setup_callables raises exceptions if provided args are not callable""" input_data = test_data with pytest.raises(ScrapliTypeError): base_driver._setup_callables(*input_data)
5,294,474
def _parse_opts(): """Parse the command line options. :param list argv: List of arguments to process. If not provided then will use optparse default :return: options,args where options is the list of specified options that were parsed and args is whatever arguments are left after parsing al...
5,294,475
def test_get_ngrams_excludes_puncuation(grammer_instance: Grammer) -> None: """It returns most frequent term with value.""" grammer_instance.term_list = [ "best, thing", "it's 'the' best, thing, ever", "best ! day ! ever!", "not, the? best thing ever", ] result = grammer_...
5,294,476
def encode2(valeur,base): """ float*int -->String avec 16 décimales hypothèse : base maxi = 16 """ chaine="" for n in range (1,17) : valeur=valeur*base calcul = int(valeur) if (calcul)>9: if calcul==10: bit='A' if calcul==11: ...
5,294,477
def get_stacktrace(gdb_output): """Returns the stacktrace and the exit signal """ if not "#0" in gdb_output: error("gdb output error") stacktrace = Stacktrace() # Get the exit Signal from the gdb-output exit_signal = re.search(_exit_signal_re, gdb_output) if exit_signal: exit_sig...
5,294,478
def index(): """ Basic index route. """ return {"msg": "Hi! This is an API by Mariia Sizova"}
5,294,479
def pretty_size(size): """ Pretty prints a torch.Size object By user machinethink: https://forums.fast.ai/t/gpu-memory-not-being-freed-after-training-is-over/10265/7 """ assert(isinstance(size, torch.Size)) return " × ".join(map(str, size))
5,294,480
def main(): """指定されたタグからlayer_config.jsonを作成するツール"""
5,294,481
def getwikidata(id='Q43229'): """Load WIKIDATA organization data""" startCollect(id)
5,294,482
def merge_rest_docs( prnt_doc: T.Optional[str] = None, child_doc: T.Optional[str] = None, method: T.Union[Literal["merge"], Literal["replace"]] = "replace", ) -> str: """See custom_inherit.style_store.reST for details.""" prnt_sections = parse_rest_doc(prnt_doc) child_sections = parse_rest_doc(c...
5,294,483
def faidx_targets(): """Creates .fai index files of the targets, which are necessary for the conversion of sorted BAM files to fastq files.""" for file in targets: faidxFile = "%s.fai" % file faidxPath = "%s/targets/faidxFiles" % path make_path(faidxPath) if not os.path.isfil...
5,294,484
def get_recipe_intent_handler(request): """ You can insert arbitrary business logic code here """ return alexa.create_response(message="Hello stranger!")
5,294,485
def path_splitter(s, _d_match=re.compile(r"\.\d").match): """ Split a string into its path components. Assumes a string is a path or is path-like. Parameters ---------- s : str | pathlib.Path Returns ------- split : tuple The path split by directory components and extensio...
5,294,486
def convert_time(time: str, ampm: str) -> Tuple[int, int]: """Convert time given "HH:MM" to 24h format. Args: time (str): a time like "12:00" without ampm ampm (str): either "am" or "pm" Returns: Tuple[int, int]: (hour, minute) in 24h time format """ hour, minute = [int(n)...
5,294,487
def proportional_allocation_by_location_and_activity(df, sectorcolumn): """ Creates a proportional allocation within each aggregated sector within a location :param df: df with sector columns :param sectorcolumn: str, sector column for which to create allocation ratios :return: df, with 'FlowAmountR...
5,294,488
def Cov_bb_Das(Cb, α, A, β, B, γ, C, τ, D): """Compute analytic errorbars. A, B, C, D correspond to frequencies, α, β, γ, τ correspond to seasons """ N = 0.0 term0 = 2 * Cb**2 / nu_b term1 = 0.0 term2 = 0.0 for i in range(n_d[0]): for j in range(n_d[1]): for k in...
5,294,489
def join_(table, on_str, **kwargs): """ join_(table='items', on_str='items.id=topic_item.item_id', status=1) """ join_str = ' JOIN `' + table + '` on ' + on_str re_str, values = _rebuild_argv(kwargs, table=table) return join_str, re_str, values
5,294,490
def optimize_glm(x, y, distri): """Apply Bayesian Optimization to select enet parameters.""" def function(alpha, reg_lambda): return glm_train(alpha=alpha, reg_lambda=reg_lambda, x=x, y=y, distri=distri) optimizer = BayesianOptimization( f=function, pbounds={"alpha": (1e-6, 1), "reg...
5,294,491
def upload_webcam(request): """ Generate a random name for the photo and save it to disk, then crop it and extract information """ name = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(10)) + ".png" path = os.path.join(settings.MEDIA_ROOT, name) f = open(path, "wb")...
5,294,492
def project_duals(dual_vars, dual_types): """Projects dual variables to satisfy dual constraints.""" make_pos = lambda v: None if v is None else jnp.maximum(v, 0) _project = lambda v, t: make_pos(v) if t == DualVarTypes.INEQUALITY else v return jax.tree_multimap(_project, dual_vars, dual_types)
5,294,493
def column_equality(series, col1, col2, comparison='equal', pos_return_val=1, neg_return_val=0): """ Apply to a dataframe row to return a binary feature depending on equality or inequality E.g. df.apply(lambda s: column_match(s, 'day_of_week', 'day_of_sale'), axis=1) to for matching the two. Result is ...
5,294,494
def test_csv_with_complex_headers(): """https://github.com/DrorHarari/csvjson#csv-with-complex-headers """ csv = r"""{"field":"id","type":"int"},{"field":"name","type":"string"},{"field":"address","type":"string"},{"field":"regular","type":"boolean"} 1,"John","12 Totem Rd. Aspen",true 2,"Bob",null,...
5,294,495
def destroy_sns_event(app_name, env, region): """ Destroys all Lambda SNS subscription Returns: boolean: True if subscription destroyed successfully """ session = boto3.Session(profile_name=env, region_name=region) sns_client = session.client('sns') lambda_subscriptions = get_sns_subsc...
5,294,496
def SS_workflow(scope="function"): """SS_workflow. Simple workflow including StartToStart dependency. """ task1 = BaseTask("task1") task2 = BaseTask("task2") task3 = BaseTask("task3") task2.append_input_task(task1, task_dependency_mode=BaseTaskDependency.SS) task3.append_input_task(task...
5,294,497
def assert_keys(data, expected): """ This method ensures that the keys of the ``data`` match up to the keys of ``expected``. It covers the (extremely) common case where you want to make sure the keys of a response match up to what is expected. This is typically less fragile than testing the ful...
5,294,498
def removeStopwords(text): """Se eliminan palabras que carecen de significado Args: text: Texto del que se desea eliminar las palabras sin significado. """ stopw = nltk.corpus.stopwords.words('spanish') stopw = stopw + ["juguete", "juguetes", "edad", "máxima", "recomendada", "incluye...
5,294,499