content
stringlengths
22
815k
id
int64
0
4.91M
def _manually_create_user(username, pw): """ Create an *active* user, its server directory, and return its userdata dictionary. :param username: str :param pw: str :return: dict """ enc_pass = server._encrypt_password(pw) # Create user directory with default structure (use the server fun...
5,330,500
def update_geoscale(df, to_scale): """ Updates df['Location'] based on specified to_scale :param df: df, requires Location column :param to_scale: str, target geoscale :return: df, with 5 digit fips """ # code for when the "Location" is a FIPS based system if to_scale == 'state': ...
5,330,501
def plot_throughput_speedup_analysis(plot, input_data): """Generate the plot(s) with algorithm: plot_throughput_speedup_analysis specified in the specification file. :param plot: Plot to generate. :param input_data: Data to process. :type plot: pandas.Series :type input_data: InputData ...
5,330,502
def translate(text, from_lang="auto", to_lang="zh-CN"): """translate text, return the result as json""" url = 'https://translate.googleapis.com/translate_a/single?' params = [] params.append('client=gtx') params.append('sl=' + from_lang) params.append('tl=' + to_lang) params.append('hl=en-U...
5,330,503
def backproject_to_plane(cam, img_pt, plane): """Back an image point to a specified world plane""" # map to normalized image coordinates npt = np.matrix(npl.solve(cam[0], np.array(list(img_pt)+[1.0]))) M = cam[1].transpose() n = np.matrix(plane[:3]).flatten() d = plane.flat[3] Mt = M * cam[2...
5,330,504
def build_base(): """ Remotely build base python image with all installed packages on image-factory server """ with lcd(env.local_path): put('./requirements.txt', '/srv/build/requirements.txt') with cd('/srv/build'): run('docker build -t {base_image_name} .'.format( base...
5,330,505
def create_tables(engine): """ Create all tables according to metadata of Base. Args: engine(instance): _engine.Engine instance """ Base.metadata.create_all(engine)
5,330,506
def test_detail_attributes(factory: APIRequestFactory) -> None: """You can update primary data attributes.""" request = factory.put( reverse("artist-detail", kwargs={"pk": 1}), { "data": { "id": "1", "type": "artist", "attributes": {"fi...
5,330,507
def format_cell(cell, datetime_fmt=None): """Format a cell.""" if datetime_fmt and isinstance(cell, datetime): return cell.strftime(datetime_fmt) return cell
5,330,508
def optimize(gradients, optim, global_step, summaries, global_norm=None, global_norm_clipped=None, appendix=''): """Modified from sugartensor""" # Add Summary if summaries is None: summaries = ["loss", "learning_rate"] # if "gradient_norm" in summaries: # if global_norm is None: # ...
5,330,509
def p_stage_macro(p): """stage : MACRO""" p[0] = ParseTreeNode('STAGE') p[0].add_child(ParseTreeNode('MACRO', raw=p[1]))
5,330,510
def _get_desired_asg_capacity(region, stack_name): """Retrieve the desired capacity of the autoscaling group for a specific cluster.""" asg_conn = boto3.client("autoscaling", region_name=region) tags = asg_conn.describe_tags(Filters=[{"Name": "value", "Values": [stack_name]}]) asg_name = tags.get("Tags"...
5,330,511
def _default_geo_type_precision(): """ default digits after decimal for geo types """ return 4
5,330,512
def print_prog_bar(iteration, total, prefix='', suffix='', decimals=2, length=90, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix -...
5,330,513
def load_movietimes(filepath_timestamps, filepath_daq): """Load daq and cam time stamps, create muxer""" df = pd.read_csv(filepath_timestamps) # DAQ time stamps with h5py.File(filepath_daq, 'r') as f: daq_stamps = f['systemtime'][:] daq_sampleinterval = f['samplenumber'][:] # remov...
5,330,514
def is_valid_hotkey(hotkey: str) -> bool: """Returns True if hotkey string is valid.""" mode_opts = ["press", "click", "wheel"] btn_opts = [b.name for b in Button] wheel_opts = ["up", "down"] hotkeylist = hotkey[2:].split("_") if len(hotkeylist) == 0 or len(hotkeylist) % 2 != 0: return ...
5,330,515
def find_range_with_sum(values : list[int], target : int) -> tuple[int, int]: """Given a list of positive integers, find a range which sums to a target value.""" i = j = acc = 0 while j < len(values): if acc == target: return i, j elif acc < target: acc += values...
5,330,516
def output_AR1(outfile, fmri_image, clobber=False): """ Create an output file of the AR1 parameter from the OLS pass of fmristat. Parameters ---------- outfile : fmri_image : ``FmriImageList`` or 4D image object such that ``object[0]`` has attributes ``coordmap`` and ``shape`` cl...
5,330,517
def _sanity_check(module): """Run sanity checks that don't depend on info from the zone/record.""" overwrite = module.params['overwrite'] record_name = module.params['record'] record_type = module.params['type'] state = module.params['state'] ttl = module.params['ttl'] record_data = module....
5,330,518
def feature_bit_number(current): """Fuzz bit number field of a feature name table header extension.""" constraints = UINT8_V return selector(current, constraints)
5,330,519
def render_page(context, slot, payload): # pylint: disable=R0201,W0613 """ Base template slot """ chapter = request.args.get('chapter', '') module = request.args.get('module', '') page = request.args.get('page', '') try: if page: return render_template(f"{chapter.lower()}/{modul...
5,330,520
def add_stripe_customer_if_not_existing(f): """ Decorator which creates user as a customer if not already existing before making a request to the Stripe API """ @wraps(f) def wrapper(user: DjangoUserProtocol, *args, **kwargs): user = create_customer(user) return f(user, *args, **kwar...
5,330,521
def test_editor_rstrip_keypress(editorbot, input_text, expected_text, keys, strip_all): """ Test that whitespace is removed when leaving a line. """ qtbot, widget = editorbot widget.strip_trailing_spaces_on_modify = strip_all widget.set_text(input_text) cursor...
5,330,522
def debug(): """ Import the test utils module to be able to: - Use the trace tool and get context variables after making a request to Apigee """ return ApigeeApiTraceDebug(proxy=config.PROXY_NAME)
5,330,523
def FromModuleToDoc(importedMod,filDfltText): """ Returns the doc string of a module as a literal node. Possibly truncated so it can be displayed. """ try: docModuAll = importedMod.__doc__ if docModuAll: docModuAll = docModuAll.strip() # Take only the firs...
5,330,524
def noisify_patternnet_asymmetric(y_train, noise, random_state=None): """ mistakes in labelling the land cover classes in PatternNet dataset cemetery -> christmas_tree_fram harbor <--> ferry terminal Den.Res --> costal home overpass <--> intersection park.space --> park.lot runway_mark --> p...
5,330,525
def group_superset_counts(pred, label): """ Return TP if all label spans appear within pred spans :param pred, label: A group, represeted as a dict :return: A Counts namedtuple with TP, FP and FN counts """ if (pred["label"] != label["label"]): return Counts(0, 1, 1) for label_span i...
5,330,526
def other(): """ Queries all of the logged in user's Campaigns and plugs them into the campaigns template """ entities = db.session.query(Entity) entities = [e.to_dict() for e in entities] return render_template('other.html', entities=entities)
5,330,527
def test_limited_query(): """Test that result set limiting works.""" reader = EuropeanaSearchReader(os.environ['EUROPEANA_API_KEY'], 'Python', max_records=65) count = 0 for record in reader: assert record.id count = count + 1 assert reader.result_count > 0 assert count == 65
5,330,528
def rel_angle(vec_set1, vec_set2): """ Calculate the relative angle between two vector sets Args: vec_set1(array[array]): an array of two vectors vec_set2(array[array]): second array of two vectors """ return vec_angle(vec_set2[0], vec_set2[1]) / vec_angle(vec_set1[0], vec_set1[1]) ...
5,330,529
def check_position_axes(chgcar1: CHGCAR, chgcar2: CHGCAR) -> bool: """Check the cell vectors and atom positions are same in two CHGCAR. Parameters ----------- chgcar1, chgcar2: vaspy.CHGCAR Returns ------- bool """ cell1 = chgcar1.poscar.cell_vecs cell2 = chgcar2.poscar.cell_v...
5,330,530
def path_shortest(graph, start): """ Pythonic minheap implementation of dijkstra's algorithm """ # Initialize all distances to infinity but the start one. distances = {node: float('infinity') for node in graph} distances[start] = 0 paths = [(0, start)] while paths: current_distance, cu...
5,330,531
def test_issue5(): """https://github.com/nazrulworld/fhir.resources/issues/5""" from fhir.resources.codeableconcept import CodeableConcept from fhir.resources.coding import Coding coding1 = Coding(jsondict={'system': 'http://www.snomed.org/', 'code': '424144002'}) coding2 = Coding(jsondict={'system'...
5,330,532
def request(url, *args, **kwargs): """Requests a single JSON resource from the Wynncraft API. :param url: The URL of the resource to fetch :type url: :class:`str` :param args: Positional arguments to pass to the URL :param kwargs: Keyword arguments (:class:`str`) to pass to the URL :returns: T...
5,330,533
def test_status_success( mock_git_use_case: MockerFixture, mock_config_manager: MockerFixture, runner: CliRunner, ) -> None: """It calls status.""" runner.invoke(git_portfolio.__main__.main, ["status"], prog_name="gitp") mock_git_use_case.return_value.execute.assert_called_once_with( ["...
5,330,534
def destagger(var, stagger_dim, meta=False): """Return the variable on the unstaggered grid. This function destaggers the variable by taking the average of the values located on either side of the grid box. Args: var (:class:`xarray.DataArray` or :class:`numpy.ndarray`): A variable ...
5,330,535
def sms_whoami(msg): """ Check what the username is :param msg: A full telerivet message object :returns: Username associated with the phone number """ user_id = UserData.objects.get(phone=msg.connections[0].identity).user_id msg.respond('User: @{}'.format(get_user_model().objects.get(id=user_id...
5,330,536
def predict_pipeline_acceleration( data: arr_t, sampling_rate: float, convert_to_g: Optional[bool] = True, **kwargs ) -> Dict[str, Any]: """Apply sleep processing pipeline on raw acceleration data. This function processes raw acceleration data collected during sleep. The pipeline consists of the following ...
5,330,537
def create_blueprint(request_manager: RequestManager, cache: Cache, dataset_factory: DatasetFactory): """ Creates an instance of the blueprint. """ blueprint = Blueprint('metadata', __name__, url_prefix='/metadata') @cache.memoize() def _get_method_types_per_approach(): ...
5,330,538
def sides(function_ast, parameters, function_callback): """ Given an ast, parses both sides of an expression. sides(b != c) => None """ left = side(function_ast['leftExpression'], parameters, function_callback) right = side(function_ast['rightExpression'], parameters, function_callback) ...
5,330,539
def create_path_file(directory): """Writes out the path to images in a folder as a list""" # if save: # utils.list_path_to_files(directory,file="ds.txt", save=True) # # else: output = utils.list_path_to_files(directory) print(output)
5,330,540
def print_url(host, port, datasets): """ Prints a list of available dataset URLs, if any. Otherwise, prints a generic URL. """ def url(path = None): return colored( "blue", "http://{host}:{port}/{path}".format( host = host, port = por...
5,330,541
def test_ipv6_dns(ip): """Test known ip address.""" server = Server(ip) assert str(server) == ip assert server.check_service_v6(53, 5)
5,330,542
def load_records(es_app, filename, schema): """Try to index records.""" indexer = RecordIndexer() with es_app.test_request_context(): data_filename = pkg_resources.resource_filename("invenio_records", filename) records_data = load(data_filename) records = [] for item in recor...
5,330,543
def get_default_sample_path_random(data_path): """Return path to sample with default parameters as suffix""" extra_suffix = get_default_extra_suffix(related_docs=False) return get_default_sample_path(data_path, sample_suffix=extra_suffix)
5,330,544
def test_python_parse_error(python_contents): """Test that a python parse error yields a ProtocolAnalysisException.""" proto = """ there's nothing here """ with patch.object(contents, "get_protocol_contents", return_value=proto): r = analyze._analyze(python_contents) ...
5,330,545
def VectorShadersAddMaterialDesc(builder, materialDesc): """This method is deprecated. Please switch to AddMaterialDesc.""" return AddMaterialDesc(builder, materialDesc)
5,330,546
def phase_randomize(D, random_state=0): """Randomly shift signal phases For each timecourse (from each voxel and each subject), computes its DFT and then randomly shifts the phase of each frequency before inverting back into the time domain. This yields timecourses with the same power spectrum (and...
5,330,547
def test_changing_duration( service_registry: Contract, get_accounts: Callable, custom_token: Contract ) -> None: """The controller can change the registration period of ServiceRegistry""" new_duration = 90 * SECONDS_PER_DAY service_registry.functions.changeParameters( _price_bump_numerator=DEFA...
5,330,548
def monospaced(text): """ Convert all contiguous whitespace into single space and strip leading and trailing spaces. Parameters ---------- text : str Text to be re-spaced Returns ------- str Copy of input string with all contiguous white space replaced with ...
5,330,549
def molecule_block(*args, **kwargs): """ Generates the TRIPOS Mol2 block for a given molecule, returned as a string """ mol = Molecule(*args, **kwargs) block = mol.molecule_block() + mol.atom_block() + mol.bond_block() + '\n' return block
5,330,550
def setup_test_env(settings_key='default'): """Allows easier integration testing by creating RPC and HTTP clients :param settings_key: Desired server to use :return: Tuple of RPC client, HTTP client, and thrift module """ return RpcClient(handler), HttpClient(), load_module(settings_key)
5,330,551
def calculateCentroid( pointCloud : List[Tuple[float, float, float]] ) -> Tuple[float, float, float]: """Calculate centroid of point cloud. Arguments -------------------------------------------------------------------------- pointCloud (float 3-tuple list) -- list of xyz coordinates. R...
5,330,552
def timber_load(): """ Calculate Timber's IO load since the last call """ #io(read_count=454556, write_count=3456, read_bytes=110592, write_bytes=0) global timber_io_stat try: new_stat = p.get_io_counters() readCount = new_stat.read_count - timber_io_stat.read_count write...
5,330,553
def get_num_uniq_users(csv_file, userid_col): """ A Helper function to help get the number of unique users :param csv_file: path to CSV file :param userid_col: Column for user ID :return: """ # Read the CSV file using pandas df = pd.read_csv(csv_file) # Use the nunique() method to g...
5,330,554
def generate_graph_batch(n_examples, sample_length): """ generate all of the training data Parameters ---------- n_examples: int Num of the samples sample_length: int Length of the samples. # TODO we should implement samples of different lens as in the DeepMind example. ...
5,330,555
def administration(request): """Administration actions ((re)train acton predictor for a new survey) Parameters ---------- request: POST request Returns ------- render: django.shortcuts.render (a page to be rendered) """ from zooniverse_web.models import Survey, Quest...
5,330,556
def main(flow_id, git_tag): """ :param flow_id: 订单ID :param git_tag: Git Tag名字 :return: """ print('[INFO]: 这部分是用来在编译镜像,并且上传docker仓库') data = get_publish_data(flow_id) # 配置信息 obj = BuildImage(data, git_tag) # 初始化类 obj.build_image() # 编译镜像 obj.push_image()
5,330,557
def test_post_payments_error(client, jwt, app, payment_mock_error): """Assert that the endpoint returns 200.""" token = jwt.create_jwt(get_claims(), get_token_header()) headers = {'content-type': 'application/json', 'Authorization': f'Bearer {token}'} rv = client.post('/api/v1/payments', data=json.dumps...
5,330,558
def checkout(skus): """ Calculate the total amount for the checkout based on the SKUs entered in :param skus: string, each char is an item :return: int, total amount of the cart, including special offers """ total = 0 counter = Counter(skus) # got through the offers (biggest first), an...
5,330,559
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): """ Alternate warning printer which shows a traceback with the warning. To use, set *warnings.showwarning = warn_with_traceback*. """ traceback.print_stack() log = file if hasattr(file, '...
5,330,560
def func_tradeg(filename, hdulist=None, whichhdu=None): """Return the fits header value TELRA in degrees. """ hdulist2 = None if hdulist is None: hdulist2 = fits.open(filename, 'readonly') else: hdulist2 = hdulist telra = fitsutils.get_hdr_value(hdulist2, 'TELRA') if hdulis...
5,330,561
def minor(ctx, v): """ Increase minor version, tag and push """ try: new_value = v.next_minor() new_value = v.omit_prefix(new_value) click.echo(new_value) except GitCommandError as e: click.echo(str(e)) ctx.exit(1)
5,330,562
def column_indexes(column_names, row_header): """項目位置の取得 Args: column_names (str): column name row_header (dict): row header info. Returns: [type]: [description] """ column_indexes = {} for idx in column_names: column_indexes[idx] = row_header.index(column_names...
5,330,563
def dmx_psrs(caplog): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ caplog.set_level(logging.CRITICAL) psrs = [] for p in psr_names: with open(datadir+'/{0}_ng9yr_dmx_DE436_epsr.pkl'.format(p), 'rb') as fin: psrs.append(pickle.load(f...
5,330,564
def fit_stats(act_map, param, func=KentFunc): """Generate fitting statistics from scipy's curve fitting""" phi_grid, theta_grid = meshgrid(phi_arr, theta_arr) Xin = np.array([theta_grid.flatten(), phi_grid.flatten()]).T fval = act_map.flatten() fpred = func(Xin, *param) # KentFunc res = fval - ...
5,330,565
def prep_dyson( opt_in, ): """Runs lightspeed calculations from template files and traj object Params: opt_in - [dict], options to override defaults """ options = { # all paths must be absolute! "submit_input": None, # sbatch file to edit "submit_input2": "sbatch...
5,330,566
def conv2d_for_hpool_valid_width_wrapper(inputs,filters,strides,padding,**kwargs): """ Wraps tf.layers.conv2d to allow valid convolution across signal width and 'same' convolution across signal height when padding is set to "valid_time" Arguments: inputs (TF Tensor): Tensor input. filters (TF...
5,330,567
def resample_cells(tree, params, current_node = 'root', inplace = False): """ Runs a new simulation of the cell evolution on a fixed tree """ if not inplace: tree = copy.deepcopy(tree) for child in tree.successors(current_node): initial_cell = tree.nodes[current_node]['cell'].deepco...
5,330,568
def get_sql_query(table_name:str) -> str: """Fetch SQL query file for generation of dim or fact table(s)""" f = open(f'./models/sql/{table_name}.sql') f_sql_query = f.read() f.close() return f_sql_query
5,330,569
def run_cli( ctx: click.Context, pkgs: list[str], ) -> None: """A shortcut command to run pytest against a specific set of CLI-based integration tests It takes one or more test package names in a comma-separated list (PKGS) and forwards all other extra arguments and options (PYTEST_ARGS) to ...
5,330,570
def _map_args(call_node, function): """Maps AST call nodes to the actual function's arguments. Args: call_node: ast.Call function: Callable[..., Any], the actual function matching call_node Returns: Dict[Text, ast.AST], mapping each of the function's argument names to the respective AST node. "...
5,330,571
def sub_bases( motif ): """ Return all possible specifications of a motif with degenerate bases. """ subs = {"W":"[AT]", \ "S":"[CG]", \ "M":"[AC]", \ "K":"[GT]", \ "R":"[AG]", \ "Y":"[CT]", \ "B":"[CGT]", \ "D":"[AGT]", \ "H":"[ACT]", \ "V":"[ACG]", \ "N":"[ACGTN]"} for symbol,...
5,330,572
def test_PMC_003_pass(): """ Test that using df[col] does not result in an error. """ statement = "df[col]\ndf.loc[col]\ndf.sum().loc[col]" actual = _results(statement) expected = set() assert actual == expected
5,330,573
def interrogate_host(): """ CLI entry point for first usage in docstring. """ info = get_info() with open('%s.sysinfo.json' % info['hostname'], 'w') as f: json.dump(info, f, indent=2)
5,330,574
def parse(input_file_path): """ Parse input file :param input_file_path: input file path :return: Image list """ verticals, horizontals = 0, 0 logging.info("parsing %s", input_file_path) with open(input_file_path, 'r') as input_file: nb = int(input_file.readline()) # images nb ...
5,330,575
def DeleteMembership(name, release_track=None): """Deletes a membership from the GKE Hub. Args: name: the full resource name of the membership to delete, e.g., projects/foo/locations/global/memberships/name. release_track: the release_track used in the gcloud command, or None if it is not avail...
5,330,576
def char(ctx, number): """ Returns the character specified by a number """ return chr(conversions.to_integer(number, ctx))
5,330,577
async def get_character_name(gear_url, message): """ It is *sometimes* the case that discord users don't update their username to be their character name (eg for alts). This method renders the gear_url in an HTML session and parses the page to attempt to find the character's name. This assume...
5,330,578
def get_treant_df(tags, path='.'): """Get treants as a Pandas DataFrame Args: tags: treant tags to identify the treants path: the path to search for treants Returns: a Pandas DataFrame with the treant name, tags and categories >>> from click.testing import CliRunner >>> from too...
5,330,579
def gather_keypoints(keypoints_1, keypoints_2, matches): """ Gather matched keypoints in a (n x 4) array, where each row correspond to a pair of matching keypoints' coordinates in two images. """ res = [] for m in matches: idx_1 = m.queryIdx idx_2 = m.trainIdx pt...
5,330,580
def plot_dendrogram( x: Union[navis.TreeNeuron, navis.NeuronList], heal_neuron: bool = False, downsample_neuron: float = 0.0, plot_connectors: bool = True, connector_confidence: Tuple[float, float] = (0.0, 0.0), highlight_nodes: Optional = None, highlight_connectors: Optional = None, fra...
5,330,581
async def stop(): """ Stop any playing audio. """ Sound.stop() return Sound.get_state()
5,330,582
def test_sanitize_content_filename(filename, expected): """ Test inputs where the result is the same for Windows and non-Windows. """ assert sanitize_content_filename(filename) == expected
5,330,583
def is_numeric(X, compress=True): """ Determine whether input is numeric array Parameters ---------- X: Numpy array compress: Boolean Returns ------- V: Numpy Boolean array if compress is False, otherwise Boolean Value """ def is_float(val): try: float(v...
5,330,584
def figure_ellipse_fitting(img, seg, ellipses, centers, crits, fig_size=9): """ show figure with result of the ellipse fitting :param ndarray img: :param ndarray seg: :param [(int, int, int, int, float)] ellipses: :param [(int, int)] centers: :param [float] crits: :param float fig_size: ...
5,330,585
def fmt_bytesize(num: float, suffix: str = "B") -> str: """Change a number of bytes in a human readable format. Args: num: number to format suffix: (Default value = 'B') Returns: The value formatted in human readable format (e.g. KiB). """ for unit in ["", "Ki", "Mi", "Gi", "Ti",...
5,330,586
def get_kpoint_mesh(structure: Structure, cutoff_length: float, force_odd: bool = True): """Calculate reciprocal-space sampling with real-space cut-off.""" reciprocal_lattice = structure.lattice.reciprocal_lattice_crystallographic # Get reciprocal cell vector magnitudes abc_recip = np.array(reciprocal_...
5,330,587
def resnet_v1_101(inputs, num_classes=None, is_training=True, global_pool=True, output_stride=None, spatial_squeeze=True, reuse=None, scope='resnet_v1_101', **kwargs): """ResNet-101 model of...
5,330,588
def test_l2_vlan_bcast_ucast(npu, dataplane): """ Description: VLAN broadcast and known unicast test. Verify the broadcast packet reaches all ports in the VLAN and known unicast packet reaches specific port. Test scenario: 1. Create a VLAN 10 2. Add ports as untagged members to the VLAN ...
5,330,589
def is_package_authorized(package_name): """ get user information if it is authorized user in the package config Returns: [JSON string]: [user information session] """ authorized_users = get_package_admins(package_name) user_info = get_user_info() user_dict = j.data.serializers.json...
5,330,590
def submit_search_query(query_string, query_limit, query_offset, class_resource): """ Submit a search query request to the RETS API """ search_result = class_resource.search( query='%s' % query_string, limit=query_limit, offset=query_offset) return search_result
5,330,591
def extract_site_packages(archive, target_path, compile_pyc=False, compile_workers=0, force=False): """Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to. :param bool comp...
5,330,592
def one_hot_encode(df): """ desc : one hot encodes categorical cols args: df (pd.DataFrame) : stroke dataframe returns: df (pd.DataFrame) : stroke dataframe with one_hot_encoded columns """ # extract categorical columns stroke_data = df.copy() cat_cols = stroke_data....
5,330,593
def assert_increasing(a): """Utility function for enforcing ascending values. This function's handle can be supplied as :py:kwarg:`post_method` to a :py:func:`processed_proprty <pyproprop>` to enforce values within a :py:type:`ndarray <numpy>` are in ascending order. This is useful for enforcing ti...
5,330,594
def invalidate_users_QBT(user_id): """Mark the given user's QBT rows invalid (by deletion)""" QBT.query.filter(QBT.user_id == user_id).delete() db.session.commit()
5,330,595
def copy_to_device(device, remote_path, local_path='harddisk:', server=None, protocol='http', vrf=None, timeout=300, compact=False, use_kstack=False, ...
5,330,596
def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') ...
5,330,597
def decode_replay_header(contents): """Decodes and return the replay header from the contents byte string.""" decoder = VersionedDecoder(contents, protocol.typeinfos) return decoder.instance(protocol.replay_header_typeid)
5,330,598
def test_disabled_command(pkg): """Test command that has been disabled.""" npmpkg = NPMPackage(pkg, commands=['run-script']) pytest.raises(AttributeError, getattr, npmpkg, 'install')
5,330,599