content
stringlengths
22
815k
id
int64
0
4.91M
def test_success(database): """ Test that calculation works for equal values and for null """ value = Decimal('100.23') approp = AppropriationFactory(status_of_budgetary_resour_cpe=value, total_budgetary_resources_cpe=value) approp_null = AppropriationFactory(status_of_budgetary_resour_cpe=0, total_budg...
19,300
def get_pcap_path(name): """Given a pcap's name in the test directory, returns its full path.""" return os.path.join(PCAPS_DIR, name)
19,301
def text_dataset_construction(train_or_test, janossy_k, task, janossy_k2, sequence_len, all_data_size=0): """ Data Generation """ janossy_k = 1 janossy_k2 = 1 args = parse_args() task = str(args.task).lower() X = np.load('../data_'+str(task)+str(sequence_len)+'.npy') output_X = np.load('../label_'+str(task)+str(...
19,302
def run_illum(args): """Run illumination correction. Parameters ---------- args : argparse.Namespace The arguments parsed by the argparse library. """ if args.file_list is not None: args.images.extend([fn.rstrip() for fn in args.file_list]) il = pre.find_background_illuminat...
19,303
def neo_vis(task_id): """ Args: task_id: Returns: """ project = get_project_detail(task_id, current_user.id) return redirect( url_for( "main.neovis_page", port=project["remark"]["port"], pwd=project["remark"]["password"], ) )
19,304
def getfont( fontname=None, fontsize=None, sysfontname=None, bold=None, italic=None, underline=None): """Monkey-patch for ptext.getfont(). This will use our loader and therefore obey our case validation, caching and so on. """ fontname = fontname or ...
19,305
def append_medications(sms_message, end_date, patient): """ Queries all of the patients current medications as determined by the Medication.edn_date is null or after the 'end_date' parameter. Appends a new line to the message with the medication information as: name ...
19,306
def change_box(base_image,box,change_array): """ Assumption 1: Contents of box are as follows [x1 ,y2 ,width ,height] """ height, width, _ = base_image.shape new_box = [0,0,0,0] for i,value in enumerate(change_array): if value != 0: new_box[i] = box[i] + valu...
19,307
def fetchRepositoryFilter(critic, filter_id): """Fetch a RepositoryFilter object with the given filter id""" assert isinstance(critic, api.critic.Critic) return api.impl.filters.fetchRepositoryFilter(critic, int(filter_id))
19,308
def test_to_gbq_w_default_project(mock_bigquery_client): """If no project is specified, we should be able to use project from default credentials. """ import google.api_core.exceptions from google.cloud.bigquery.table import TableReference mock_bigquery_client.get_table.side_effect = google.api...
19,309
def load_it(file_path: str, verbose: bool = False) -> object: """Loads from the given file path a saved object. Args: file_path: String file path (with extension). verbose: Whether to print info about loading successfully or not. Returns: The loaded object. Raises: No...
19,310
def test_orderstorage__Orderstorage__down__3(storage): """It can move the given item `delta` positions down.""" storage.down('foo2', 'bar', 2) assert ['foo1', 'foo3', 'foo4', 'foo2'] == storage.byNamespace('bar')
19,311
def rename(): """ Rename all directories to [firstname lastname]. """ msg.info('Renaming...') moodle_sub_specifier = '_assignsubmission_file_' g = glob.glob(f'submission/*{moodle_sub_specifier}') while len(g) == 0: if msg.ask_yn('Directory names do not match, remove /submission and retry?...
19,312
def connect_contigs(contigs, align_net_file, fill_min, out_dir): """Connect contigs across genomes by forming a graph that includes net format aligning regions and contigs. Compute contig components as connected components of that graph.""" # construct align net graph and write net BEDs if align_net_fi...
19,313
def train(loader, model, crit, opt, epoch): """Training of the CNN. Args: loader (torch.utils.data.DataLoader): Data loader model (nn.Module): CNN crit (torch.nn): loss opt (torch.optim.SGD): optimizer for every parameters with True ...
19,314
def test_encrypt(): """Test encrypting a paste.""" p = create_paste("test_encrypt") key = p.encrypt() assert key is not None with pytest.raises(ValueError): p.encrypt()
19,315
async def create_add_ci_failure_summary(gh, context, comment_url, ci_link, shortId, pr_num, comment_list, commits_url): """gradually find failed CI""" hyperlink_format = '<a href="{link}">{text}</a>' failed_header = "## 🕵️ CI f...
19,316
def _h1_cmp_prnt_ ( h1 , h2 , head1 = '' , head2 = '' , title = '' , density = False , max_moment = 10 , exp_mo...
19,317
def add_scatter(x, scatter, in_place=False): """ Add a Gaussian scatter to x. Parameters ---------- x : array_like Values to add scatter to. scatter : float Standard deviation (sigma) of the Gaussian. in_place : bool, optional Whether to add the scatter to x in place...
19,318
def validate_job_state(state): """ Validates whether a returned Job State has all the required fields with the right format. If all is well, returns True, otherwise this prints out errors to the command line and returns False. Can be just used with assert in tests, like "assert validate_job_state(st...
19,319
def get_urls(session): """ Function to get all urls of article in a table. :param session: session establishes all conversations with the database and represents a “holding zone”. :type session: sqlalchemy.session :returns: integer amount of rows in table """ url = session.query(Article.url...
19,320
def iter_nonce_offsets(fh: BinaryIO, real_size: int = None, maxrange: int = 1024) -> Iterator[int]: """Returns a generator that yields nonce offset candidates based on encoded real_size. If real_size is None it will automatically determine the size from fh. It tries to find the `nonce offset` using the fol...
19,321
def check_min_package_version(package, minimum_version, should_trunc_to_same_len=True): """Helper to decide if the package you are using meets minimum version requirement for some feature.""" real_version = pkg_resources.get_distribution(package).version if should_trunc_to_same_len: minimum_version ...
19,322
def bboxes_protection(boxes, width, height): """ :param boxes: :param width: :param height: :return: """ if not isinstance(boxes, np.ndarray): boxes = np.asarray(boxes) if len(boxes) > 0: boxes[:, [0, 2]] = np.clip(boxes[:, [0, 2]], 0, width - 1) boxes[:, [1, 3]] ...
19,323
def ann_to_json(file_path, save_path, bbox_type='normalize'): """convert .mat annotation file into .json file Args: file_path (str): .mat file path Ex : relative path '../data/digitStruct.mat' or complete path 'C:/usr/local/data/digitStruct.mat' save_path (str): .json file directory *Otherthan ...
19,324
def mark_astroids(astroid_map): """ Mark all coordiantes in the grid with an astroid (# sign) """ astroids = [] for row, _ in enumerate(astroid_map): for col, _ in enumerate(astroid_map[row]): if astroid_map[row][col] == "#": astroid_map[row][col] = ASTROID ...
19,325
def ListAllBuckets(): """Lists all buckets.""" credentials = service_account.Credentials.from_service_account_file( './digitalcore-poc-67645bca1a2a.json') storage_client = storage.Client() buckets = storage_client.list_buckets() for bucket in buckets: print(bucket.name) blobs =...
19,326
def process_player_data( prefix, season=CURRENT_SEASON, gameweek=NEXT_GAMEWEEK, dbsession=session ): """ transform the player dataframe, basically giving a list (for each player) of lists of minutes (for each match, and a list (for each player) of lists of ["goals","assists","neither"] (for each mat...
19,327
def copy_to_table(_dal, _values, _field_names, _field_types, _table_name, _create_table=None, _drop_existing=None): """Copy a matrix of data into a table on the resource, return the table name. :param _dal: An instance of DAL(qal.dal.DAL) :param _values: The a list(rows) of lists(values) with values to be ...
19,328
def svn(registry, xml_parent, data): """yaml: svn Specifies the svn SCM repository for this job. :arg str url: URL of the svn repository :arg str basedir: location relative to the workspace root to checkout to (default '.') :arg str credentials-id: optional argument to specify the ID of cre...
19,329
def build_file_path(base_dir, base_name, *extensions): """Build a path to a file in a given directory. The file may have an extension(s). :returns: Path such as: 'base_dir/base_name.ext1.ext2.ext3' """ file_name = os.extsep.join([base_name] + list(extensions)) return os.path.expanduser(os.pa...
19,330
def lerarquivo(nome): """ -> Vai fazer a leitura do arquivo com os respectivos dados dos jogadores de uma forma mais apresentável ao usuário. """ titulo('LISTA DE JOGADORES') a = open(nome, 'r') for linha in a: dado = linha.split(';') dado[1] = dado[1].replace('\n', '') ...
19,331
def test_build_wfi_stac_item_keys(): """test_wfi_build_stac_item_keys""" meta = get_keys_from_cbers( "test/fixtures/CBERS_4A_WFI_20200801_221_156_" "L4_BAND13.xml" ) buckets = {"metadata": "cbers-meta-pds", "cog": "cbers-pds", "stac": "cbers-stac"} smeta = build_stac_item_keys(meta, buckets...
19,332
def test_default_suite(executed_docstring_source): """ >>> def test_default_suite_example(): ... pass """ assert_that(executed_docstring_source.allure_report, has_test_case("test_default_suite_example", has_parent_suite(anything()), # path to testd...
19,333
def Uni(A, b, x=None, maxQ=False, x0=None, tol=1e-12, maxiter=1e3): """ Вычисление распознающего функционала Uni. В случае, если maxQ=True то находится максимум функционала. Parameters: A: Interval Матрица ИСЛАУ. b: Interval Векто...
19,334
def boqa(alpha, beta, query, items_stat): """Implementation of the BOQA algorithm. Args: alpha (float): False positive rate. beta (float): False negative rate. query (dict): Dict of query terms (standard terms). Key: term name, value: presence value items_stat (dict): Dictionnar...
19,335
def test_issue_without_title(resolved_doctree, issue): """ Test resolval of issues without title. """ pytest.assert_issue_xref(resolved_doctree, issue, '#10')
19,336
def d2c(sys,method='zoh'): """Continous to discrete conversion with ZOH method Call: sysc=c2d(sys,method='log') Parameters ---------- sys : System in statespace or Tf form method: 'zoh' or 'bi' Returns ------- sysc: continous system ss or tf """ flag = 0 i...
19,337
def ipv4(value): """ Parses the value as an IPv4 address and returns it. """ try: return ipaddress.IPv4Address(value) except ValueError: return None
19,338
def test_from( fork: str, ) -> Callable[ [Callable[[], StateTest]], Callable[[str], Mapping[str, Fixture]] ]: """ Decorator that takes a test generator and fills it for all forks after the specified fork. """ fork = fork.capitalize() def decorator( fn: Callable[[], StateTest] ...
19,339
def get_hash_name(feed_id): """ 用户提交的订阅源,根据hash值生成唯一标识 """ return hashlib.md5(feed_id.encode('utf8')).hexdigest()
19,340
def _load_transition_probabilities(infile: TextIO) -> tuple[list, int]: """ For summary files with new syntax (post 2021-11-24). Parameters ---------- infile : TextIO The KSHELL summary file at the starting position of either of the transition probability sections. Returns ...
19,341
def merge_lineages(counts: Dict[str, int], min_count: int) -> Dict[str, str]: """ Given a dict of lineage counts and a min_count, returns a mapping from all lineages to merged lineages. """ assert isinstance(counts, dict) assert isinstance(min_count, int) assert min_count > 0 # Merge ra...
19,342
def test_std_remove_stereochemistry(mols): """Test if all stereochemistry centers (chiral and double bonds) are removed.""" # chirality assert Chem.FindMolChiralCenters(mols['stereo_chiral'], includeUnassigned=True) == [(5, 'S')] Chem.RemoveStereochemistry(mols['stereo_chiral']) # mol_ini is modified i...
19,343
def maybe_download_file(project_name, fname, dist_dir): """Verify the checksums.""" details = get_file_details(project_name, fname) if details['sha1']: sha1 = hashlib.sha1() dist_filename = os.path.join(dist_dir, fname) fin = open(dist_filename, 'rb') sha1.update(fin.read()) fin.close() he...
19,344
def test_invalid_operands(): """ Test that certain operators do not work with models whose inputs/outputs do not match up correctly. """ with pytest.raises(ModelDefinitionError): Rotation2D | Gaussian1D with pytest.raises(ModelDefinitionError): Rotation2D(90) | Gaussian1D(1, 0,...
19,345
def test_load_tarfile(): """ Registry can load a tar file. """ registry = Registry() with NamedTemporaryFile() as fileobj: build_tar(fileobj) fileobj.flush() schema_ids = registry.load(fileobj.name) assert_that(schema_ids, has_length(3)) assert_that(schema_i...
19,346
def str2bool(s): """特定の文字列をbool値にして返す。 s: bool値に変換する文字列(true, false, 1, 0など)。 """ if isinstance(s, bool): return s else: s = s.lower() if s == "true": return True elif s == "false": return False elif s == "1": ...
19,347
def no_header_csv_demo(): """ 无标题的csv使用示例 """ villains = [ ["doctor", "no"], ["rosa", "tony"], ["mister", "big"], ["auric", "goldfinger"], ["sophia", "blob"] ] # 写入 with open("./csv_no_header_test.txt", "wt") as f: csvout = csv.writer(f) ...
19,348
def merge_aoistats(main_AOI_Stat,new_AOI_Stat,total_time,total_numfixations): """a helper method that updates the AOI_Stat object of this Scene with a new AOI_Stat object Args: main_AOI_Stat: AOI_Stat object of this Scene new_AOI_Stat: a new AOI_Stat object ...
19,349
def catalog_xmatch_circle(catalog, other_catalog, radius='Association_Radius', other_radius=Angle(0, 'deg')): """Find associations within a circle around each source. This is convenience function built on `~astropy.coordinates.SkyCoord.search_around_sky`, ...
19,350
def show_map_room(room_id=None): """Display a room on a map.""" return get_map_information(room_id=room_id)
19,351
def color_enabled(): """Check for whether color output is enabled If the configuration value ``datalad.ui.color`` is ``'on'`` or ``'off'``, that takes precedence. If ``datalad.ui.color`` is ``'auto'``, and the environment variable ``NO_COLOR`` is defined (see https://no-color.org), then color is di...
19,352
def parse_line_regex(line): """Parse raw data line into list of floats using regex. This regex approach works, but is very slow!! It also requires two helper functions to clean up malformed data written by ls-dyna (done on purpose, probably to save space). Args: line (str): raw data line from...
19,353
def create_page_metadata(image_dir, image_dir_path, font_files, text_dataset, speech_bubble_files, speech_bubble_tags): """ This function creates page metadata for a single page. It inclu...
19,354
def __merge_results( result_list: tp.List[tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]] ) -> tp.Dict[str, tp.Dict[str, tp.Set[tp.Union[CVE, CWE]]]]: """ Merge a list of results into one dictionary. Args: result_list: a list of ``commit -> cve`` maps to be merged Return: t...
19,355
def compactness(xyz): """ Input: xyz Output: compactness (V^2/SA^3) of convex hull of 3D points. """ xyz = np.array(xyz) ch = ConvexHull(xyz, qhull_options="QJ") return ch.volume**2/ch.area**3
19,356
def get_things_saved(figa, store, store_short, file_name, suggested_name): """ get filename """ idir = file_name.rsplit('/', maxsplit=1)[0] sname = suggested_name.rsplit('.', maxsplit=1)[0] window_save = tk.Tk() window_save.withdraw() save_fn = asksaveasfilename(initialfile=sname, filetypes=[('A...
19,357
def is_posix(): """Convenience function that tests different information sources to verify whether the operating system is POSIX compliant. .. note:: No assumption is made reading the POSIX level compliance. :return: True if the operating system is MacOS, False otherwise. :rtype: bool ...
19,358
def guide(batch, z_dim, hidden_dim, out_dim=None, num_obs_total=None): """Defines the probabilistic guide for z (variational approximation to posterior): q(z) ~ p(z|q) :param batch: a batch of observations :return: (named) sampled z from the variational (guide) distribution q(z) """ assert(jnp.ndim(...
19,359
def trip2str(trip): """ Pretty-printing. """ header = "{} {} {} - {}:".format(trip['departureTime'], trip['departureDate'], trip['origin'], trip['destination']) output = [header] for subtrip in trip['trip']: originstr = u'...
19,360
def station_suffix(station_type): """ Simple switch, map specific types on to single letter. """ suffix = ' (No Dock)' if 'Planetary' in station_type and station_type != 'Planetary Settlement': suffix = ' (P)' elif 'Starport' in station_type: suffix = ' (L)' elif 'Asteroid' in statio...
19,361
def AddKmsKeyResourceArg(parser, resource, region_fallthrough=False, boot_disk_prefix=False): """Add a resource argument for a KMS key. Args: parser: the parser for the command. resource: str, the name of the resource that the cryptokey will be used to protect. region_fal...
19,362
def addprefixed(unitname, prefixrange='full'): """ Add prefixes to already defined unit Parameters ---------- unitname: str Name of unit to be prefixed, e.k. 'm' -> 'mm','cm','dm','km' prefixrange: str Range: 'engineering' -> 1e-18 to 1e12 or 'full' -> 1e-24 to 1e24 """ if ...
19,363
def temperatures_equal(t1, t2): """Handle 'off' reported as 126.5, but must be set as 0.""" if t1 == settings.TEMPERATURE_OFF: t1 = 0 if t2 == settings.TEMPERATURE_OFF: t2 = 0 return t1 == t2
19,364
def calc_cf(fname, standard='GC',thickness=1.0,plot=False,xmin=None,xmax=None,interpolation_type='linear'): """ Calculates the calibration factor by using different chosen standards like fname : filename containing the experimental data done on standard sample standard : 'GC' or '...
19,365
def import_capitals_from_csv(path): """Imports a dictionary that maps country names to capital names. @param string path: The path of the CSV file to import this data from. @return dict: A dictionary of the format {"Germany": "Berlin", "Finland": "Helsinki", ...} """ capitals = {} with open(pa...
19,366
def read_config(config_file='config.ini'): """ Read the configuration file. :param str config_file: Path to the configuration file. :return: """ if os.path.isfile(config_file) is False: raise NameError(config_file, 'not found') config = configparser.ConfigParser() config.read(co...
19,367
def deg_to_qcm2(p, deg): """Return the center-of-momentum momentum transfer q squared, in MeV^2. Parameters ---------- p_rel = float relative momentum given in MeV. degrees = number angle measure given in degrees """ return (p * np.sqrt( 2 * (1 ...
19,368
def i18n(request): """ Set client language preference, lasts for one month """ from django.conf import settings next = request.META.get('HTTP_REFERER', None) if not next: next = settings.SITE_ROOT lang = request.GET.get('lang', 'en') res = HttpResponseRedirect(next) re...
19,369
def plot_initial_density_profile(job): """Plot the initial plasma density profile.""" plot_density_profile( make_gaussian_dens_func, job.fn("initial_density_profile.png"), job )
19,370
def replace_suffix(input_filepath, input_suffix, output_suffix, suffix_delimiter=None): """ Replaces an input_suffix in a filename with an output_suffix. Can be used to generate or remove suffixes by leaving one or the other option blank. TODO: Make suffixes accept regexes. Can likely replace suff...
19,371
def normal222(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(bb3) idgirande=r...
19,372
def _convert_to_coreml(tf_model_path, mlmodel_path, input_name_shape_dict, output_names): """ Convert and return the coreml model from the Tensorflow """ model = tf_converter.convert(tf_model_path=tf_model_path, mlmodel_path=mlmodel_path, out...
19,373
def do_push_button(self, url, params, commit, req_body_params=None): """Push a button by following its url Args: self: Required for getting a cookiejar and pagetext. url (string): Target route that pushing the button would trigger. params (dict): Request queries that go after the url. ...
19,374
def xcode_select(xcode_app_path): """Switch the default Xcode system-wide to `xcode_app_path`. Raises subprocess.CalledProcessError on failure. To be mocked in tests. """ subprocess.check_call([ 'sudo', 'xcode-select', '-switch', xcode_app_path, ])
19,375
def _tavella_randell_nonuniform_grid(x_min, x_max, x_star, num_grid_points, alpha, dtype): """Creates non-uniform grid clustered around a specified point. Args: x_min: A real `Tensor` of shape `(dim,)` specifying the lower limit of the grid. x_max: A real `Tensor`...
19,376
def node(func): """Decorator for functions which should get currentIndex node if no arg is passed""" @functools.wraps(func) def node_wrapper(self, *a, **k): n = False keyword = True # Get node from named parameter if 'node' in k: n = k['node'] # Or from th...
19,377
def tourme_details(): """ Display Guides loan-details """ return render_template('tourme_details.html', id=str(uuid.uuid4()))
19,378
def gen_dot_ok(notebook_path, endpoint): """ Generates .ok file and return its name Args: notebook_path (``pathlib.Path``): the path to the notebook endpoint (``str``): an endpoint specification for https://okpy.org Returns: ``str``: the name of the .ok file """ ...
19,379
def sarig_methods_wide( df: pd.DataFrame, sample_id: str, element_id: str, ) -> pd.DataFrame: """Create a corresponding methods table to match the pivoted wide form data. .. note:: This requires the input dataframe to already have had methods mapping applied by running ``pygeochemtools.geoc...
19,380
def scan_torsion(resolution, unique_conformers=[]): """ """ # Load the molecule sdf_filename = "sdf/pentane.sdf" suppl = Chem.SDMolSupplier(sdf_filename, removeHs=False, sanitize=True) mol = next(suppl) # Get molecule information # n_atoms = mol.GetNumAtoms() atoms = mol.GetAtoms(...
19,381
def get_and_update_versions (): """ Gets current version information for each component, updates the version files, creates changelog entries, and commit the changes into the repository.""" try: get_comp_versions ("ACE") get_comp_versions ("TAO") get_comp_versions ("CIAO") ...
19,382
def vflip_box(box: TensorOrArray, image_center: TensorOrArray) -> TensorOrArray: """Flip boxes vertically, which are specified by their (cx, cy, w, h) norm coordinates. Reference: https://blog.paperspace.com/data-augmentation-for-bounding-boxes/ Args: box (TensorOrArray[B, 4]): Bo...
19,383
def example_data(): """Example data setup""" tdata = ( pathlib.Path(__file__).parent.absolute() / "data" / "ident-example-support.txt" ) return tdata
19,384
def add_ending_slash(directory: str) -> str: """add_ending_slash function Args: directory (str): directory that you want to add ending slash Returns: str: directory name with slash at the end Examples: >>> add_ending_slash("./data") "./data/" """ if directory[-...
19,385
def init_logging(): """ Initialize logging """ logger = logging.getLogger("") # Make sure the logging path exists, create if not logdir = os.path.dirname(CES_SETTINGS['logFile']) if logdir and not os.path.exists(logdir): print "Logging directory '%s' doesn't exist, creating it now." % logdi...
19,386
def antenna_positions(): """ Generate antenna positions for a regular rectangular array, then return baseline lengths. - Nx, Ny : No. of antennas in x and y directions - Dmin : Separation between neighbouring antennas """ # Generate antenna positions on a regular grid x = np.arange(Nx...
19,387
def main(): """ A simple program that plots phonon output. """ from numpy import zeros, log10 infile=raw_input('Infile name: ') fin=open(infile,'r') hdr=fin.readline().strip('\n').split() x1=float(hdr[0]) x2=float(hdr[1]) nxdim=int(hdr[2]) t1=float(hdr[3]) t2=float(hdr[4]) ntdim=int(hdr[5]) rbin=zeros(...
19,388
def folds_to_list(folds: Union[list, str, pd.Series]) -> List[int]: """ This function formats string or either list of numbers into a list of unique int Args: folds (Union[list, str, pd.Series]): Either list of numbers or one string with numbers separated by commas or ...
19,389
def predict_all(x, model, config, spline): """ Predict full scene using average predictions. Args: x (numpy.array): image array model (tf h5): image target size config (Config): spline (numpy.array): Return: prediction scene array average probabilities -------...
19,390
def pre_arrange_cols(dataframe): """ DOCSTRING :param dataframe: :return: """ col_name = dataframe.columns.values[0] dataframe.loc[-1] = col_name dataframe.index = dataframe.index + 1 dataframe = dataframe.sort_index() dataframe = dataframe.rename(index=str, columns={col_name: 'a...
19,391
def wDot(x,y,h): """ Compute the parallel weighted dot product of vectors x and y using weight vector h. The weighted dot product is defined for a weight vector :math:`\mathbf{h}` as .. math:: (\mathbf{x},\mathbf{y})_h = \sum_{i} h_{i} x_{i} y_{i} All weight vector components shou...
19,392
def dataframify(transform): """ Method which is a decorator transforms output of scikit-learn feature normalizers from array to dataframe. Enables preservation of column names. Args: transform: (function), a scikit-learn feature selector that has a transform method Returns: new_t...
19,393
def add_corrected_pages_summary_panel(request, items): """Replaces the Pages summary panel to hide variants.""" for index, item in enumerate(items): if item.__class__ is PagesSummaryItem: items[index] = CorrectedPagesSummaryItem(request)
19,394
def plot_map(self, map, update=False): """ map plotting Parameters ---------- map : ndarray map to plot update : Bool updating the map or plotting from scratch """ import matplotlib.pyplot as plt if update: empty=np.empty(np.shape(self.diagnostics[self.diagn...
19,395
def definition_activate(connection, args): """Activate Business Service Definition""" activator = sap.cli.wb.ObjectActivationWorker() activated_items = ((name, sap.adt.ServiceDefinition(connection, name)) for name in args.name) return sap.cli.object.activate_object_list(activator, activated_items, coun...
19,396
def extractCompositeFigureStrings(latexString): """ Returns a list of latex figures as strings stripping out captions. """ # extract figures figureStrings = re.findall(r"\\begin{figure}.*?\\end{figure}", latexString, re.S) # filter composite figures only and remove captions (preserving captions...
19,397
def osm_net_download( polygon=None, north=None, south=None, east=None, west=None, network_type="all_private", timeout=180, memory=None, date="", max_query_area_size=50 * 1000 * 50 * 1000, infrastructure='way["highway"]', ): """ Download OSM ways and nodes within s...
19,398
def _find_results_files(source_path: str, search_depth: int = 2) -> list: """Looks for results.json files in the path specified Arguments: source_path: the path to use when looking for result files search_depth: the maximum folder depth to search Return: Returns a list containing fou...
19,399