content
stringlengths
22
815k
id
int64
0
4.91M
def si_unit_lookup_table(units=UNITS): """ Creates a lookup table from all possible input unit names and symbols to their corresponding SI unit. """ return { **{ u.name: (u.si_equivalent, u.coefficient) for u in units if u.name is not None}, **{ u.symbol: (u.si_equivalent...
49,400
def image_get_all(client, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc', member_status='accepted', is_public=None, admin_as_user=False): """ Get all images that match zero or more filters. :param filters: dict of filter k...
49,401
def monthsWeeksDays(): """print 'One year has 12 months, 52 weeks and 365 days.' """ str = "One year has {} months, {} weeks and {} days.".format(12, 52, 365) print(str)
49,402
def copy_collection(db, source, target, drop_source=False): """Copies a collection with server-side javascript. This is about twice as fast as roundtripping python in a forloop. Downside is possible locking. Meta data about the state of the collection is also updated. If source collection should be dele...
49,403
def Erzsol3Tohdf5( erz_folder: str, cmd_folder: str, h5_folder: str, h5_name: str, n_clusters: int, ns: int): """ This function writes out a single hdf5 file containing all information and the data that can be used for Machine learning and other Parameters ---------- er...
49,404
def send_configuration_item(connected_socket, item): """Sends one configuration item""" send_string(connected_socket, item.get("type", "")) send_string(connected_socket, item.get("name", "")) send_string(connected_socket, item.get("icon", "")) children = item.get("children", []) send_configurat...
49,405
def test_config_dir(): """Create a configuration directory if one doesn't exist. This creates a configuration directory in the virtual environment base to allow testing certain functions/methods that look for a user configuration directory otherwise defaulting to the site-wide configuration directory. ...
49,406
def handleDBS(reqmgrOutDsets, cmswebUrl): """ Get total number of lumi sections in each dataset """ if 'testbed' in cmswebUrl: dbsUrl = cmswebUrl + "/dbs/int/global/DBSReader/" else: dbsUrl = cmswebUrl + "/dbs/prod/global/DBSReader/" dbsOutput = {} for dataset in reqmgrOutDs...
49,407
def get_sub_folders(session, ds_browser, ds_path): """Return a set of subfolders for a path on a datastore. If the path does not exist then an empty set is returned. """ search_task = session._call_method( session._get_vim(), "SearchDatastore_Task", ds_browser, ...
49,408
def generate_report_across_params( runs_df, show_plots=False, save_to_pdf: bool or str = False, out_units="seconds", ): """Main function to generate plotting report of runtime versus params Note that different runs are plotted as different series on the plot. This is best for comparing how ...
49,409
def _tests(): """ Put some (sort of) unit tests in here to make sure the functions work as expected. """ test_lat = 30 test_z = np.logspace(0.1, 4, 50) # log depth distribution test_p = np.logspace(0.1, 4, 50) # log pressure distribution res_p1 = depth2pressure(test_z, test_lat) ...
49,410
def buffer(bufferlen, handlers): """Buffer and reorder incoming packets of data. Args: bufferlen ([type]): Length of buffer, in seconds. handlers (dict): Dictionary of str: generator. The key is a stream name, the value is an unprimed generator. Yields: tuple(str, data)...
49,411
def main(): """ fill the player_prediction db table """ parser = argparse.ArgumentParser(description="fill player predictions") parser.add_argument("--weeks_ahead", help="how many weeks ahead to fill", type=int) parser.add_argument("--gameweek_start", help="first gameweek to look at", type=int) ...
49,412
def stock_board_concept_cons_em(symbol: str = "车联网") -> pd.DataFrame: """ 东方财富-沪深板块-概念板块-板块成份 http://quote.eastmoney.com/center/boardlist.html#boards-BK06551 :param symbol: 板块名称 :type symbol: str :return: 板块成份 :rtype: pandas.DataFrame """ stock_board_concept_em_map = stock_board_conc...
49,413
def run_single_sb_algo(env, agent, settings): """ Runs a single experiment. Args: env: The environment. agent: The agent. setting: A dictionary containing experiment settings. """ exp = or_suite.experiment.sb_experiment.SB_Experiment(env, agent, settings) _ = exp.run() ...
49,414
def jittered_center_crop(frames, box_extract, box_gt, search_area_factor, output_sz, masks=None): """ For each frame in frames, extracts a square crop centered at box_extract, of area search_area_factor^2 times box_extract area. The extracted crops are then resized to output_sz. Further, the co-ordinates of the...
49,415
def bayesquad(fun, fun0, bounds, nevals=None, type="vanilla", **kwargs): """ One-dimensional Bayesian quadrature. Parameters ---------- fun : function Function to be integrated. fun0 : RandomProcess Stochastic process modelling the function to be integrated. bounds : ndarray...
49,416
def track(): """ RESTful CRUD controller """ if deployment_settings.get_security_map() and not shn_has_role("MapAdmin"): unauthorised() resource = request.function table = module + "_" + resource # Model options # used in multiple controllers, so defined in model # CRUD Strings ...
49,417
def files_download(urls, referer=None, cookies=None, fileinfo=None): """ 文件下载 :param urls: 文件连接[列表] :return: 上传后的地址列表 """ assert urls, "文件地址为空" uploads_paths = [] local_paths = [] for url in urls: if re.search(r"http[s]?://None", url): raise AssertionError("url格式...
49,418
def slice_or_index(index): """Return index or slice the array [:].""" return slice(None) if index is None else index
49,419
def get_driver(): """Returns current driver.""" return _driver
49,420
def comparecf(clist1, clist2=None, shift=0., fac=1., ploterrbar=True, fill=False, filtneg=False, label=None, plotratio=False, ratioxrange=None, color1=None, marker1=None, markers1=None, linestyle1=None, linewidth1=None, color2=None, marker2=None, markers2=None, linestyle2=No...
49,421
def transform_points(trans_01, points_1): """ Function that applies transformations to a set of points. """ if not (trans_01.device == points_1.device and trans_01.dtype == points_1.dtype): raise TypeError( "Tensor must be in the same device and dtype. " f"Got trans_...
49,422
def insert(*entities, **options): """ bulk inserts the given entities. note that entities must be from the same type. :param BaseEntity entities: entities to be inserted. :keyword int chunk_size: chunk size to insert values. after each chunk, store will be committed. ...
49,423
def given_a_dataset_with_location_id(t: Env): """show location id on all related screens""" prj = preset.project_created(t) ds = preset.dataset_created(t, prj) ds.meta.location_id = "aws" ds.meta.location_id_set = True t.given_events(prj, ds) t.scenario( when.view_dataset(ds.proje...
49,424
def test_rpc_direct_dtm(id_scene, index_x, index_y): """ Test direct localization on DTMIntersection """ vect_index = [index_x, index_y] data_folder = data_path() rpc_file = os.path.join(data_folder, "rpc", id_scene) fctrat = RPC.from_any(rpc_file, topleftconvention=True) id_scene = "P1...
49,425
def batch_resample(X, new_dim, mode="bilinear"): """ Resample each image (or similar grid-based 2D signal) in a batch to `new_dim` using the specified resampling strategy. Parameters ---------- X : :py:class:`ndarray <numpy.ndarray>` of shape `(n_ex, in_rows, in_cols, in_channels)` An i...
49,426
def register(request): """ Sets a session variable and redirects users to register for BCeID """ if settings.DEPLOYMENT_TYPE == 'localdev': return render(request, 'localdev/register.html') request.session['went_to_register'] = True return redirect(settings.REGISTER_BCEID_URL)
49,427
def get_bits(byte_size, number): """Returns last byte_size*8 bits from number.""" res = [] for i in range(byte_size * 8): res.append(str(number % 2)) number //= 2 res.reverse() return res
49,428
def greedy_find_path(entrance, exits, corridors): """ Find ANY path connecting input and output, """ print("corridors at start: ", corridors) #max_flow = float("inf") # Not the case. #if entrance in exits: # return 1/0 cur_pos = entrance path = [entrance] max_flows = [2...
49,429
def test_main_shutdown(capsys): """Test --shutdown""" sys.argv = ['', '--shutdown'] Globals.getInstance().set_args(sys.argv) mocked_node = MagicMock(autospec=Node) def mock_shutdown(): print('inside mocked shutdown') mocked_node.shutdown.side_effect = mock_shutdown iface = MagicMoc...
49,430
def blacklist_chat(chat_id: int, reason: str): """ BLACKLIST A CHAT """ c.execute( """ UPDATE chats SET blacklisted = 1 WHERE chat_id=? """, (chat_id,), ) c.execute( """ INSERT INTO reasons ...
49,431
def load_artefacts_from_file(file_path: Path) -> Artefacts: """ Load an artefacts file. Args: file_path: path to the artefacts file Returns: the artefacts created from the given file """ documents = load_yaml(file_path) version_header = VersionHeader(next(documents)) ve...
49,432
def date(date): """Return a date object representing the ISO 8601 date. :param date: The ISO 8601 date. :return: boolean """ return runner(date, r.dates)
49,433
def get_mean_var( array: np.ndarray, axis: Optional[int] = None, weights: Optional[np.ndarray] = None, ): """Calculate average and variance of an array.""" average = np.average(array, axis=axis, weights=weights) variance = np.average((array - average) ** 2, axis=axis, weights=weights) if 0 i...
49,434
def write_nxgraph_to_json(g, output): """ Write a networkx graph as JSON to the specified output Args: g (networkx.Graph): graph to write as JSON output (filelike): output to write to """ import json from networkx.readwrite import json_graph jsond = json_graph.node_link_dat...
49,435
def heterogeneous_length(chromosome, generator, probability): """Return a mutant made through point mutation that may grow or shrink. In this scheme, mutated alleles will be replaced with a value provided by calling ``generator``. It is suitable for use with list encoding. Be warned that this will lead...
49,436
def test_read_cpu_stats(input_filename): """Parses up to the CPU section.""" target_file = open(input_filename) test_dmi = parse_dmidecode.read_dmidecode(target_file) test_os = parse_operating_system.read_operating_system(target_file) test_cpu_stats = parse_cpu.read_cpu_stats(target_file) target...
49,437
def clean_eisenhower(raw_eisen: Optional[List[str]]) -> List[str]: """Clean the raw Eisenhower values from Notion.""" if raw_eisen is None: return [] return [e for e in raw_eisen if e != '']
49,438
def binary(num): """ calculate R, G, B components from bytes number :param num: int :return: list """ packed = struct.pack('!f', num) integers = [ord(c) for c in packed] return integers
49,439
def giou_loss(pred, target, eps=1e-6): """IoU loss. Computing the IoU loss between a set of predicted bboxes and target bboxes. The loss is calculated as negative log of IoU. Args: pred (Tensor): Predicted bboxes of format (x1, y1, x2, y2), shape (n, 4). target (Tensor): Co...
49,440
def raw(text): """Returns a raw string representation of text""" new_string='' for char in text: try: new_string+=escape_dict[char] except KeyError: new_string+=char return new_string
49,441
def queries_to_retract_from_unioned_dataset(project_id, dataset_id, sandbox_dataset_id, pid_table_id): """ Get list of queries to remove all records in all tables associated with supplied ids :param project_id: identifies associated project :param dataset_id: identifies associated dataset :param sa...
49,442
def from_waymo( data_path: str, output_dir: str, save_images: bool = False, use_lidar_labels: bool = False, nproc: int = NPROC, ) -> List[Frame]: """Function converting Waymo data to Scalabel format.""" if not os.path.exists(output_dir): os.mkdir(output_dir) func = partial(parse...
49,443
def SetAndConfirmGpuClocks(vm): """Sets and confirms the GPU clock speed. The clock values are provided in the gpu_pcie_bandwidth_clock_speeds flag. If a device is queried and its clock speed does not allign with what it was just set to, an expection will be raised. Args: vm: the virtual machine to oper...
49,444
def list_keys(key_prefix, n, marker=''): """ List keys that start with key_prefix (<> key_prefix itself) @n = number of items to return @marker = name of last item """ key_list = [] i = 0 for file in os.listdir(key_prefix): key_list.append(os.path.join(key_prefix, file)) ret...
49,445
def test_tag_get(patch_salt_globals_tag): """ Test get tag functionality """ tags = tagging.list_() if len(tags["tags"]) > 0: res = tagging.get(tags["tags"][0]) assert "urn:vmomi:InventoryServiceTag:" in res["tag"]["id"] else: pytest.skip("test requires at least one tag")
49,446
def test_BGP_GR_TC_9_p1(request): """ Test Objective : Verify that restarting nodes reset "F" bit while sending the BGP open messages after it's restarts, when BGP GR is **NOT** enabled. """ tgen = get_topogen() tc_name = request.node.name write_test_header(tc_name) # Check router stat...
49,447
def _add_cv(fp, f1, f2, p, i0, ncv): """ :param file fp: :param float f1: :param float f2: :param list p: :param int i0: :param int ncv: :return: """ i1 = i0 for m in range(ncv): fp.write(" ") for i in range(3): fp.write(" %.2f %.2f" ...
49,448
def get_instance_type(entity_name, instance_dict=None): """ :param entity_name: name of an entity; :param instance_dict: dictionary that contains the instance type of each entity; :return: the instance type of the provided entity; Get the instance type of a given entity, as specified by t...
49,449
def gather_doi (schol, graph, partition, pub): """ use `title_search()` across scholarly infrastructure APIs to identify this publication's DOI, etc. """ title = pub["title"] title_match = False for api in [schol.crossref, schol.openaire, schol.europepmc]: try: if api.ha...
49,450
def handleRemoveReadonly(func, path, exc): """ handle read only file delete """ excvalue = exc[1] if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES: os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) # 0777 func(path) else: raise
49,451
def test_read_old_lock_creates_backup(tmpdir): """When reading a version-1 lockfile, make sure that a backup of that file is created. """ mock_repo = MockPackageMultiRepo() y = mock_repo.add_package('y', [], []) with spack.repo.use_repositories(mock_repo): y = Spec('y') y.concre...
49,452
def usage(): """Print out the usage of this command.""" print """Usage: python test_autogrid4.py [-d <string>] [-e <string>] [-o <string>] where: -d, --gpf-directory specifies the directory containing the GPFs to be tested; this flag is optional; default is '.' -e, --executable ...
49,453
def file_keyword(request): """Return multiple possible styles for the bumpsemver:file keyword.""" return request.param
49,454
def process_jobreport(payload_report_file, job_scratch_path, job_communication_point): """ Copy job report file to make it accessible by Harvester. Shrink job report file. :param payload_report_file: name of job report (string). :param job_scratch_path: path to scratch directory (string). :param jo...
49,455
def test_about_route_gets_200_status_code(testapp): """Test that the about route gets 200 status code.""" response = testapp.get("/about") assert response.status_code == 200
49,456
def get_compound(name): """Get a workspace compound by name as a dictionary""" return get_object(name)
49,457
def fake_pocket_response(scope="module") -> MagicMock: # pylint: disable=unused-argument """Get fake Pocket response.""" response = MagicMock() fake_pocket_response_file = os.path.realpath( os.path.join(os.path.dirname(DATA_FILE), '..', 'tests', 'data', 'pocket.json') ) with open(fake_pock...
49,458
def parse_iso_date(date): """ Parses and returns a human-readable date from a ISO datetime. Args: date (string): ISO datetime. Returns: The date in a more human-readable format. """ if date is None: return "an unknown time" parsed = dateutil.parser.parse(date) ...
49,459
def run_tests(): """Main function, sends the predetermined list of messages """ from twisted.internet import reactor factory = MQTTClientFactory() hostname = 'localhost' port = 1883 print("{}:Starting repro run to {}:{}".format(calendar.timegm(time.gmtime()), hostname, port)) reactor.c...
49,460
def m_credential_create(node_name, credential_hash, participantDID): """Creates a credential. --- Definitions --- {"name": "node_name", "prompt": "Hierarchical node name", "default": "metrovacesa.deconfianza.pubcred"} {"name": "credential_hash", "prompt": "Credential hash", "default": "Hola que tal"} ...
49,461
def test_post_and_get_rawrefresco(self): """ Ensure we can create a new DroneCategory and then retrieve it """ data = { "anfp": "18505100", "dfp": "Description here", "bnfp": "448528", "pds": "2020-02-12", "pde": "2020-02-20", "jds": 43, "jde": 51,...
49,462
def deconvolve_tf(y: np.ndarray, x: np.ndarray, C: np.ndarray, kernel: np.ndarray, lam: float, gam: float, n_iters: int = 200, k: int = 3, natural: bool = True, clip: bool = False) -> np.ndarray: """ Perform deconvolut...
49,463
def cleanup_qt_environment() -> None: """ Clean up the linked Qt binaries in o3de python runtime environment """ if not is_qt_linked(): logger.info("Qt binaries have not been linked, skip Qt uninstall") return global old_os_env if old_os_env.get("QT_PLUGIN_PATH"): old_os_...
49,464
def test_main(): """Sample test for main command.""" with pytest.raises(SystemExit) as _: cli.main()
49,465
def get_bounds(features: list) -> Tuple[np.array, np.array]: """Given a list of feature names, generate a numpy array with the bounds for the optimization and the variable types. Args: features (list): List of feature names, following the convention from the LinearPolymer featurizer cla...
49,466
def findNeighbors(g, r, c): """ Check all neighbors of cell at row r, column c in grid g to find the count of all living neighbor cells """ nAlive = checkArray(g, r-1, c-1) + checkArray(g, r-1, c) + \ checkArray(g, r-1, c+1) + checkArray(g, r+1, c-1) + \ checkArray(g, r+1, c) + check...
49,467
def summarize_results(warmup_rewards, rewards): """ Print a summary of running a Bandit algorithm for a number of runs """ warmup_reward = warmup_rewards.sum() rewards = rewards.sum(axis=-1) r_mean = rewards.mean() r_std = rewards.std() r_total = r_mean + warmup_reward print(f"Expec...
49,468
def downgrade_from_blender2910(nodes): """ Blender 2.91 adds a new input to the BSDF node, emit strength in slot 18, moving the previous slot 18 up etc. Anything that connect to slot 18 or above from 2.91 or after will have it's slot number decreased by one. The input default values will also be updated...
49,469
def validate_rna_sequence(s: str) -> None: """ Validate RNA sequence. This ensures that it only containts supported bases. Supported bases are: "A", "U", "G", "C", "I". Supported bases can be accessed in graphein.rna.graphs.RNA_BASES :param s: Sequence to validate :type s: str :raises ValueErro...
49,470
def extract_zone(zone_url): """Given zone URL (as in instance['zone']) returns zone name.""" zone = zone_url[zone_url.rfind('/')+1:] assert is_valid_zone(zone), zone return zone
49,471
def test_train_property(): """Assert that the train property returns scaled data if needed.""" atom = ATOMClassifier(X_bin, y_bin, random_state=1) atom.run(["MNB", "LR"]) assert atom.train.equals(atom.mnb.train) assert check_scaling(atom.lr.train)
49,472
def forward_transfer_metrics(*, experience=False, stream=False): """ Helper method that can be used to obtain the desired set of plugin metrics. :param experience: If True, will return a metric able to log the forward transfer on each evaluation experience. :param stream: If True, will retu...
49,473
def tail(f, lines=10): """ Get the n last lines from file f """ if lines == 0: return "" BUFSIZ = 1024 f.seek(0, 2) bytes = f.tell() size = lines + 1 block = -1 data = [] while size > 0 and bytes > 0: if bytes - BUFSIZ > 0: # Seek back one whole BUFSIZ ...
49,474
def get_traffic_matrix(n, scale: float = 100, fixed_total: float = None) -> np.ndarray: """ Creates a traffic matrix of size n x n using the gravity model with independent exponential distributed weight vectors :param n: size of network (# communication nodes) :param scale: used for generating the expon...
49,475
def index_file(handle): """ index_file :param handle: :return: """ offset = 0 for line in handle: if line: yield offset for letter in line: offset += 1 if letter == ' ': yield offset
49,476
def rectMask(size, corner=[0,0], dimensions=[0,0], channels=3): """ Create a mask in the shape of a (non-rotated) rectangle, in which the inside of the rectangle is the desired region. Parameters ---------- size : [int, int] or [int, int, int] The size of the mask to be created (height...
49,477
def getCoursebycourseCredit(courseCredit): """ 根据学分查询课程 """ return generalGet('course', 0, 'courseCredit = \'{}\''.format(courseCredit))
49,478
def metadata_print(metadata): """Print out the metadata for verification Arguments: metadata = dict of metadata parameters from hiera Returns: None""" print('{0:<10} {1}'.format('parameter', 'value')) for key in metadata: print('{0:<10} {1}'.format(key, metadata[key]))
49,479
def main(brute_force=False, grid_width=3, sample_size=10000): """ :param brute_force: boolean - if True then grid width must be less than or equal to 3 :param grid_width: One dimension of a square grid - e.g. value of 3 = grid of 3x3 :param sample_size: sample size if using sampling - number of uni...
49,480
def get_E_beta_3(parameter, fid, did, N_data, N_flow): """ Predict the expected response for a set of combinations between different models and datasets Parameters ---------- parameter: numpy.ndarray The estimated parameters for the Beta-3 IRT model. fid: numpy.ndarray ...
49,481
def exercise_10(): """ Test minimal NCS operators """ from mmtbx.ncs import ncs_search pdb_inp = iotbx.pdb.input(source_info=None, lines=pdb_str_8) ph = pdb_inp.construct_hierarchy() # match_dict = ncs_search.search_ncs_relations( ph=ph, chain_similarity_threshold=0) # chains_info = ncs_search.g...
49,482
def download_truncated_ostrich_video(download_to_path=None): """Download additional testing video NOT FOR GENERAL USE; VIDEO MIGHT BE REMOVED WITHOUT WARNING :param download_to_path: path to save video to :return: None """ urlretrieve(REMOTE_TRUNCATED_OSTRICH_VID_PATH, download_to_path)
49,483
def l1_gradient(x: torch.Tensor, *, zero_tol: float = 0., subgradient_samples: np.ndarray = None) -> torch.Tensor: """ Compute all the possible gradient of the 1-norm |x|₁ Notice that when x(i)=0, the 1-norm is non-differentiable. We consider both the left...
49,484
def _is_visible_with_salt(ra: Quantity, dec: Quantity, t: datetime) -> bool: """ Checks whether a target is visible by SALT. Parameters ---------- ra: Quantity Right ascension. dec: Quantity Declination. t: datetime Time (must be timezone-aware). """ observ...
49,485
def sorted_date_list(df, col_collect: str): """ Builds a sorted list of every value for a date column in a given DataFrame :param df: data to analyze :param col_collect: column to analyze :return: list """ try: logger.info("Order Date List") return sorted([x.operation_date fo...
49,486
def get_tags(blog_id, username, password): """ wp.getTags(blog_id, username, password) => tag structure[] """ authenticate(username, password) return [tag_structure(tag) for tag in Tag.objects.usage_for_queryset( Post.is_publish.all(), counts=True)]
49,487
def add_scalebar( ax, left, right, label, fontsize=15, ax_y=-0.01, ): """ """ ax.hlines(ax_y, left, right, color='k', linewidth=3, transform=ax.get_xaxis_transform(), clip_on=False, ) ax.text(right, ax_y-0.01, label, va='top', ha='rig...
49,488
def delete_physical_locator(context, record_dict): """Delete physical locator that matches the supplied uuid.""" session = context.session with session.begin(subtransactions=True): if(record_dict['uuid']): session.query(models.PhysicalLocators).filter_by( uuid=record_dict...
49,489
def mol_wt_from_smiles(smiles, workers=1): """ Calculate molecular weights for molecules represented by SMILES strings. Args: smiles (list or str): List of SMILES strings. workers (int): Number of parallel threads to use for calculations. Returns: list or float: Molecular weig...
49,490
def fetch_imagery_uncurried(tup): """Fetch imagery using a (location, filename, output_directory) tuple This function exists so that something can be pickled and passed to pool.map, since downloads are costly, functions are only pickleable if they're defined at the top level of a module, and pool.map t...
49,491
def init_sync(recipe_id, yes_i_know): """Initialize index syncing.""" job_config = current_index_migrator.jobs[recipe_id] sync_job = job_config['cls'](**job_config['params']) recipe = sync_job.init(dry_run=True) click.secho( '******* Information collected for this migration *******', fg='gr...
49,492
def loadObject(self, name): """ Loads a cPickle object """ try: return cPickle.load(open(name)) except IOError: print >> sys.stderr, name + " file could not be found!" return None
49,493
def PolyArea(x, y): """Calculate area of polygon given (x,y) coordinates (Shoelace formula) :param x: np.ndarray(N, ) :param y: np.ndarray(N, ) :return: area """ return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
49,494
def find_keyword(URL, title, keywords): """ find keyword helper function of history_list """ for keyword in keywords: # case insensitive if len(keyword) > 0 and (URL is not None and keyword.lower() in URL.lower()) or (title is not None and keyword.lower() in title.lower()): return T...
49,495
def parsetypes(dtype): """ Parse the types from a structured numpy dtype object. Return list of string representations of types from a structured numpy dtype object, e.g. ['int', 'float', 'str']. Used by :func:`tabular.io.saveSV` to write out type information in the header. **Parameters...
49,496
def random_flip(image): """50% chance to flip the image for some variation""" if random.random() < 0.5: image = cv2.flip(image, 1) # 1 = vertical flip return image
49,497
def sites_only(exclude_isoforms=False): """Return PhosphositePlus data as a flat list of proteins and sites. Parameters ---------- exclude_isoforms : bool Whether to exclude sites for protein isoforms. Default is False (includes isoforms). Returns ------- list of tuples ...
49,498
def test_main_setPref_invalid_field_camel(capsys): """Test setPref() with a invalid field""" Globals.getInstance().set_camel_case() class Field: """Simple class for testing.""" def __init__(self, name): """constructor""" self.name = name prefs = MagicMock() ...
49,499