content
stringlengths
22
815k
id
int64
0
4.91M
def _is_disk_larger_than_max_size(device, node_uuid): """Check if total disk size exceeds 2TB msdos limit :param device: device path. :param node_uuid: node's uuid. Used for logging. :raises: InstanceDeployFailure, if any disk partitioning related commands fail. :returns: True if total disk...
27,500
def getLines(filename): """Return list of lines from file""" with open(filename, 'r', errors='ignore') as ff: return ff.readlines()
27,501
def bbox_next_frame_v3(F_first, F_pre, seg_pre, seg_first, F_tar, bbox_first, bbox_pre, temp, name): """ METHOD: combining tracking & direct recognition, calculate bbox in target frame using both first frame and previous frame. """ F_first, F_pre, seg_pre, seg_first, F_tar = squeeze_all(F_fi...
27,502
async def test_duplicate_bridge_import(hass): """Test that creating a bridge entry with a duplicate host errors.""" entry_mock_data = { CONF_HOST: "1.1.1.1", CONF_KEYFILE: "", CONF_CERTFILE: "", CONF_CA_CERTS: "", } mock_entry = MockConfigEntry(domain=DOMAIN, data=entry_...
27,503
def hough_lines(img, rho=2, theta=np.pi / 180, threshold=20, min_line_len=5, max_line_gap=25, thickness=3): """Perform a Hough transform on img Args: img (numpy.ndarray): input image rho (float, optional): distance resolution in pixels of the Hough grid theta (float, optional): angular ...
27,504
def multi_dev_init(params): """ Function to be invoked when executing data loading pipeline on multiple machines Parameters: ----------- params : argparser object argparser object providing access to command line arguments. """ #init the gloo process group here. dist.init_prces...
27,505
def verify_package_version(ctx, config, remote): """ Ensures that the version of package installed is what was asked for in the config. For most cases this is for ceph, but we also install samba for example. """ # Do not verify the version if the ceph-deploy task is being used to # inst...
27,506
def convert_file(): """Setup code to create a groceries cart object with 6 items in it""" local_path = os.path.join('data', '2017-07-31_072433.txt') fixture_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), local_path, ) files = glob.glob(fixture_path) for file_ in file...
27,507
def decrypt(v1: int, v2: int): """funcao desencriptadora""" palavra_encriptada = int(v1) ^ int(v2) desencriptada = palavra_encriptada.to_bytes((palavra_encriptada.bit_length() + 7) // 8, 'big') return desencriptada.decode()
27,508
def enforce_mixture_consistency_time_domain(mixture_waveforms, separated_waveforms, mix_weights=None, mix_weights_type=''): """Projection implementing mixture consistency in time domain....
27,509
def MatchNormsLoss(anchor_tensors, paired_tensors): """A norm on the difference between the norms of paired tensors. Gradients are only applied to the paired_tensor. Args: anchor_tensors: batch of embeddings deemed to have a "correct" norm. paired_tensors: batch of embeddings that will be pushed to the n...
27,510
def notice_baseball(): """ Czas na kopaninkę :return: None """ logging.info("Och, czas na kopaninkę!")
27,511
def get_ei(xx_tf, yn_tf, gp): """ :param xx_tf: A tensor giving the new point to evaluate at. :param yn_tf: A tensor giving all previously observed responses. :param gp: A gp used to predict. GP should be trained on the locations yn_tf was observed. """ N, P = gp.index_points.numpy().shape ...
27,512
def authenticate_begin(username, **_): """ Begin authentication procedure Variables: username user name of the user you want to login with Arguments: None Data Block: None Result example: <WEBAUTHN_AUTHENTICATION_DATA> """ user = STORAGE.user.get(username, as_obj=...
27,513
def calculate_aspect_ratios(apps, schema_editor): """ Assignes every projector one aspect ratio of the ones, that OS supported until this migration. If no matching ratio was found, the default of 16:9 is assigned. """ Projector = apps.get_model("core", "Projector") ratio_environment = 0.05 ...
27,514
def tempSHT31(): """Read temp and humidity from SHT31""" return sht31sensor.get_temp_humi()
27,515
def dog(argv, params): """Returns a slack attachment with a picture of a dog from thedogapi""" # Print prints logs to cloudwatch # Send response to response url dogurl = 'https://api.thedogapi.com/v1/images/search?mime_types=jpg,png' dogr = requests.get(dogurl) url = dogr.json()[0].get('url') ...
27,516
def get_public_suffix (domain): """ get_public_suffix("www.example.com") -> "example.com" Calling this function with a DNS name will return the public suffix for that name. Note that if the input does not contain a valid TLD, e.g. "xxx.residential.fw" in which "fw" is not a valid TLD, ...
27,517
def interpol(data,x): """ Resamples data by given factor with interpolation """ from scipy.interpolate import interp1d # Resamples data by given factor by interpolation x0 = np.linspace(0, len(data)-1, len(data)) x1 = np.linspace(0, len(data)-1, len(data)*x-(x-1)) f = interp1d(x0, data)...
27,518
def test_excess_verbosity(parser, verbosity): """ Verbosity saturates / maxes out. """ with pytest.raises(SystemExit): parser.parse_args([VERBOSITY_OPTNAME, str(verbosity)])
27,519
def game_summary(game_score: int, game_max_score: int, secret_word: str, user_won: bool, wrong_guesses: List[str]): """Give a game summary to the user after the game. Args: game_score (int): The score of the game. game_max_score (int): The maximum potential score for the game. ...
27,520
def test_server_json_pretty(monkeypatch): """Test whole server""" data = _test_server(monkeypatch, query_string='fmt=json_pretty', port=9004) assert data.startswith('{\n')
27,521
def convert_to_torch_tensors(X_train, y_train, X_test, y_test): """ Function to quickly convert datasets to pytorch tensors """ # convert training data _X_train = torch.LongTensor(X_train) _y_train = torch.FloatTensor(y_train) # convert test data _X_test = torch.LongTensor(X_test) _y_...
27,522
def api_auth(func): """ If the user is not logged in, this decorator looks for basic HTTP auth data in the request header. """ @wraps(func) def _decorator(request, *args, **kwargs): authentication = APIAuthentication(request) if authentication.authenticate(): return ...
27,523
def object_miou(y_true, y_pred, num_classes=cfg.num_classes): """ 衡量图中目标的iou :param y_true: 标签 :param y_pred: 预测 :param num_classes: 分类数量 :return: miou """ confusion_matrix = get_confusion_matrix(y_true, y_pred, num_classes) # Intersection = TP Union = TP + FP + FN # IoU = TP / ...
27,524
def post_discussion(title: str, content: str, path: str, top: bool, private: bool = False): """ 发送讨论 参数: title:str 讨论题目 content:str 内容 path:str 路径 top:bool 是否置顶 返回 { "code":-1,//是否成功执行 "discussion_id":"成功执行时的讨论ID", "message":"错误信息" } """ if not ses...
27,525
def logs_handler(request): """Return the log file on disk. :param request: a web requeest object. :type request: request | None """ log.info("Request for logs endpoint made.") complete_log_path = 'genconf/state/complete.log' json_files = glob.glob('genconf/state/*.json') complete_log = ...
27,526
def _get_fields_usage_data(session): """ Obtaining metrics of field usage in lingvodoc, the metrics are quantity of all/deleted dictionary perspectives using this field (also with URLs) and quantity of lexical entries in such dictionary perspectives Result: dict { (client_id, ob...
27,527
def output_is_new(output): """Check if the output file is up to date. Returns: True if the given output file exists and is newer than any of *_defconfig, MAINTAINERS and Kconfig*. False otherwise. """ try: ctime = os.path.getctime(output) except OSError as exception: if...
27,528
def test_merge_batch_grad_transforms_same_key_same_trafo(): """Test merging multiple ``BatchGradTransforms`` with same key and same trafo.""" def func(t): return t bgt1 = BatchGradTransformsHook({"x": func}) bgt2 = BatchGradTransformsHook({"x": func}) merged = Cockpit._merge_batch_grad_tr...
27,529
def main(selected_ssids, sample_interval, no_header, args=None): """ Repeatedly check internet connection status (connected or disconnected) for given WiFi SSIDs. Output is writen as .csv to stdout. """ wireless_connections = [ c for c in NetworkManager.Settings.Connections if '802-...
27,530
def test_get_funcs_invalid_syntax(tmp_path: Path): """ Atom IDE flake8 plugin can call flake8 with AST with correct syntax but with path to code with invalid syntax. In that case, we should ignore the file and fallback to the passed AST. """ path = tmp_path / 'test.py' path.write_text('1/') ...
27,531
def getNarrowBandULAMIMOChannel(azimuths_tx, azimuths_rx, p_gainsdB, number_Tx_antennas, number_Rx_antennas, normalizedAntDistance=0.5, angleWithArrayNormal=0, pathPhases=None): """This .m file uses ULAs at both TX and RX. - assumes one beam per antenna element the first co...
27,532
def get_pybricks_reset_vector(): """Gets the boot vector of the pybricks firmware.""" # Extract reset vector from dual boot firmware. with open("_pybricks/firmware-dual-boot-base.bin", "rb") as pybricks_bin_file: pybricks_bin_file.seek(4) return pybricks_bin_file.read(4)
27,533
def nSideCurve(sides=6, radius=1.0): """ nSideCurve( sides=6, radius=1.0 ) Create n-sided curve Parameters: sides - number of sides (type=int) radius - radius (type=float) Returns: a list with lists of x,y,z coordinates fo...
27,534
def _get_corr_mat(corr_transform, n_dim): """ Input check for the arguments passed to DirectionalSimulator""" if corr_transform is None: return np.eye(n_dim) if not isinstance(corr_transform, np.ndarray) or corr_transform.ndim < 2: err_msg = "corr_transform must be a 2-D numpy array" ...
27,535
def get_flowline_routing(NHDPlus_paths=None, PlusFlow=None, mask=None, mask_crs=None, nhdplus_crs=4269): """Read a collection of NHDPlus version 2 PlusFlow (routing) tables from one or more drainage basins and consolidate into a single pandas DataFrame, returning the `FROMCOMID` an...
27,536
def df_wxyz( time_slot_sensor: Sensor, test_source_a: BeliefSource, test_source_b: BeliefSource ) -> Callable[[int, int, int, int, Optional[datetime]], BeliefsDataFrame]: """Convenient BeliefsDataFrame to run tests on. For a single sensor, it contains w events, for each of which x beliefs by y sources each ...
27,537
def not_posted(child, conn) -> bool: """Check if a post has been already tooted.""" child_data = child["data"] child_id = child_data["id"] last_posts = fetch_last_posts(conn) return child_id not in last_posts
27,538
def prepend_path(path, paths): """Prepends a path to the list of paths making sure it remains unique""" if path in paths: paths.remove(path) paths.insert(0, path)
27,539
def test_having_multiple_conditions(): """ Test having clause :return: """ my_frame = query( "select min(temp) from forest_fires having min(temp) > 2 and " "max(dc) < 200 or max(dc) > 1000" ) pandas_frame = FOREST_FIRES.copy() pandas_frame["_col0"] = FOREST_FIRES["temp"] ...
27,540
def _fill_area_map(area_map, record_dict): """ 填充三级区划(区级)地名,包括简称 :param area_map: AddrMap, dict :param record_dict: dict :return: area_map """ area_name = record_dict[3] pca_tuple = (record_dict[1], record_dict[2], record_dict[3]) area_map.append_relational_addr(area_name, pca_tuple...
27,541
def test_parallel(): """Test the parallel activity.""" simulation_start = 0 env = simpy.Environment(initial_time=simulation_start) registry = {} reporting_activity = model.BasicActivity( env=env, name="Reporting activity", registry=registry, duration=0, ) su...
27,542
def parse_img_name(path): """parse image by frame name :param name [str] :output img_lists """ code = path.split('\\')[-1].split('.')[0] vid_id = path.split('\\')[-2] rcp_id = path.split('\\')[-3] seg_id = int(code[:4]) frm_id = int(code[4:]) return rcp_id, vid_id, seg_...
27,543
def get_bspline_kernel(x, channels, transpose=False, dtype=tf.float32, order=4): """Creates a 5x5x5 b-spline kernel. Args: num_channels: The number of channels of the image to filter. dtype: The type of an element in the kernel. Returns: A tensor of shape `[5, 5, 5, num_channels, num_channels]`. """...
27,544
def gen_prot_dict(): """ :param input_list: :return: """ from .protocols import Stock_solution,MonoDispensing_type1,MonoDispensing_type2,MultiBase,SMTransfer,ReactionQC,QCSolubilise,DMATransfer,\ PostWorkupTransfer,Workup,PostWorkupQCAndTransfer,PostWorkupDMSOAddition,BaseT3PMulti, PoisedRea...
27,545
def f(x): """ 예측해야 하는 함수입니다. """ return np.matmul(x * np.absolute(np.sin(x)), np.array([[2], [1]]))
27,546
def create_frame_coords_list(coords_path): """ :param coords_path: [int] :type coords_path: list :return: int, [int] :rtype: tuple """ id_number = coords_path[0] fr_coordinates = [None]*int((len(coords_path) - 1) / 3) # excluding the index 0 (which is the id) the number of triples ...
27,547
def parse_args(): """ Parses command-line arguments and returns a run configuration """ runconfig = types.SimpleNamespace() runconfig.ssl = False runconfig.port = None runconfig.connection_string = None i = 1 try: while i < len(sys.argv): arg = sys.argv[i] ...
27,548
def arcToolReport(function=None, arcToolMessageBool=False, arcProgressorBool=False): """This decorator function is designed to be used as a wrapper with other GIS functions to enable basic try and except reporting (if function fails it will report the name of the function that failed and its arguments. If a re...
27,549
async def test_async_get_server_version(client_session, ws_client, url, version_data): """Test the get server version helper.""" ws_client.receive_json.return_value = version_data version_info = await async_get_server_version(url, client_session) assert client_session.ws_connect.called assert clie...
27,550
def pes_events_scanner(pes_json_filepath): """Entrypoint to the library""" installed_pkgs = get_installed_pkgs() transaction_configuration = get_transaction_configuration() events = get_events(pes_json_filepath) arch = api.current_actor().configuration.architecture arch_events = filter_events_by...
27,551
def check_for_pattern(input_string): """ Check a string for a recurring pattern. If no pattern, return False. If pattern present, return smallest integer length of pattern. Warning: equal_divisions discards the remainder, so if it doesn't fit the pattern, you will get a false postive...
27,552
def get_xml_namespace(file_name,pkg_type): """Get xml's namespace. Args: file_name: The path of xml file. Returns: xml_namespace: The namespace of xml. for example: xml file content: ... <config xmlns="urn:ietf:params:xml:ns:netconf:base:1....
27,553
def build_successors_table(tokens): """Return a dictionary: keys are words; values are lists of successors. >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.'] >>> table = build_successors_table(text) >>> sorted(table) [',', '.', 'We', 'an...
27,554
def _rolling_nanmin_1d(a, w=None): """ Compute the rolling min for 1-D while ignoring NaNs. This essentially replaces: `np.nanmin(rolling_window(T[..., start:stop], m), axis=T.ndim)` Parameters ---------- a : numpy.ndarray The input array w : numpy.ndarray, default None ...
27,555
def get_model_init_fn(train_logdir, tf_initial_checkpoint, initialize_last_layer, last_layers, ignore_missing_vars=False): """Gets the function initializing model variables from a checkpoint. Args: train_logdir: Log direc...
27,556
def tokenize_protein(text): """ Tokenizes from a proteins string into a list of strings """ aa = ['A','C','D','E','F','G','H','I','K','L', 'M','N','P','Q','R','S','T','V','W','Y'] N = len(text) n = len(aa) i=0 seq = list() timeout = time.time()+5 for i in range(N): ...
27,557
def read_xml_string() -> Callable[[int, int, str], str]: """Read an XML file to a string. Subsection string needs to include a prepending '-'.""" def _read_xml_string(number: int, year: int, subsection: str) -> str: xmlfile = f"tests/data/xmls/session-{number:03}-{year}{subsection}.xml" with op...
27,558
def main(): """ Entrypoint for events processor agent. :return: """ # operator should pass the name of the events channel that this events agent should subscribe to. # ch_name = os.environ.get('events_ch_name') idx = 0 while idx < 3: try: if ch_name: ...
27,559
def compute_mean_std_data(filelist): """ Compute mean and standard deviation of a dataset. :param filelist: list of str :return: tuple of floats """ tensor_list = [] for file in filelist: img = Image.open(file) img_np = np.array(img).ravel() tensor_list.append(img_np....
27,560
def delete(file, key): """ Delete a larry from a HDF5 archive. Parameters ---------- file : str or h5py.File Filename or h5py.File object of the archive. key : str Name of larry. Returns ------- out : None Nothing is returned, just None. ...
27,561
def ConstVal(val): """ Creates a LinComb representing a constant without creating a witness or instance variable Should be used carefully. Using LinCombs instead of integers where not needed will hurt performance """ if not isinstance(val, int): raise RuntimeError("Wrong type for ConstVal") ...
27,562
def filter_required_flat_tensor_spec(flat_tensor_spec): """Process a flat tensor spec structure and return only the required subset. Args: flat_tensor_spec: A flattened sequence (result of flatten_spec_structure) with the joined string paths as OrderedDict. Since we use OrderedDicts we can safely c...
27,563
def callback(photolog_id): """ twitter로부터 callback url이 요청되었을때 최종인증을 한 후 트위터로 해당 사진과 커멘트를 전송한다. """ Log.info("callback oauth_token:" + request.args['oauth_token']); Log.info("callback oauth_verifier:" + request.args['oauth_verifier']); # oauth에서 twiter로 부터 넘겨받은 인증토큰을 세션으로 부터 가져온다. ...
27,564
def calc_adjusted_pvalues(adata, method='fdr_by'): """Calculates pvalues adjusted per sample with the given method. :param data: AnnData object annotated with model fit results. :param method: Name of pvalue adjustment method (from statsmodels.stats.multitest.multipletests). :return: AnnData ob...
27,565
def create_model(model_type='mobilenet'): """ Create a model. :param model_type: Must be one of 'alexnet', 'vgg16', 'resnet50' or 'mobilenet'. :return: Model. """ if model_type is 'alexnet': net = mdl.alexnet(input_shape, num_breeds, lr=0.001) elif model_type is 'vgg16': net ...
27,566
def generate_voter_groups(): """Generate all possible voter groups.""" party_permutations = list(permutations(PARTIES, len(PARTIES))) voter_groups = [VoterGroup(sequence) for sequence in party_permutations] return voter_groups
27,567
def add_image_fuzzy_pepper_noise(im, ration=0.1, rand_seed=None): """ generate and add a continues noise to an image :param ndarray im: np.array<height, width> input float image :param float ration: number means 0 = no noise :param rand_seed: random initialization :return ndarray: np.array<height, ...
27,568
def generator(fields, instance): """ Calculates the value needed for a unique ordered representation of the fields we are paginating. """ values = [] for field in fields: neg = field.startswith("-") # If the field we have to paginate by is the pk, get the pk field name. ...
27,569
def token_hash(token: Any, as_int: bool = True) -> Union[str, int]: """Hash of Token type Args: token (Token): Token to hash as_int (bool, optional): Encode hash as int Returns: Union[str, int]: Token hash """ return _hash((token.text, token.start, token.end, token.id), as_...
27,570
def generate_totp_passcode(secret): """Generate TOTP passcode. :param bytes secret: A base32 encoded secret for TOTP authentication :returns: totp passcode as bytes """ if isinstance(secret, six.text_type): secret = secret.encode('utf-8') while len(secret) % 8 != 0: secret = sec...
27,571
def all_ndcubes(request): """ All the above ndcube fixtures in order. """ return request.getfixturevalue(request.param)
27,572
def _create_root_content(): """ Make empty files and directories for msids, msids.pickle """ empty = set() if not os.path.exists(f"{ENG_ARCHIVE}/logs"): os.makedirs(f"{ENG_ARCHIVE}/logs") if not os.path.exists(f"{ENG_ARCHIVE}/archive"): os.makedirs(f"{ENG_ARCHIVE}/archive") ...
27,573
def read_xmu(fpath: Path, scan: str='mu', ref: bool=True, tol: float=1e-4) -> Group: """Reads a generic XAFS file in plain format. Parameters ---------- fpath Path to file. scan Requested mu(E). Accepted values are transmission ('mu'), fluorescence ('fluo'), or None. The de...
27,574
def filter_order_by_oid(order, oid): """ :param order: :type order: :class:`tests.testapp.testapp.trading.models.Order` :param oid: Order ID :type oid: int """ return order.tid == oid
27,575
def start_recognition(rec_data, language): """start bidirectional streaming from microphone input to speech API""" client = speech.SpeechClient() if "language == 'kor'": config = speech.RecognitionConfig( encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, sample_rate...
27,576
def process_pwdump_loot(loot_list=[], msf=None): """ Takes an array of loot records in loot_list, downloads the pwdump file and adds the users. """ from skaldship.passwords.utils import process_password_file, insert_or_update_acct db = current.globalenv['db'] #cache = current.globalenv['cac...
27,577
def has_poor_grammar(token_strings): """ Returns whether the output has an odd number of double quotes or if it does not have balanced parentheses. """ has_open_left_parens = False quote_count = 0 for token in token_strings: if token == '(': if has_open_left_parens: ...
27,578
def save_blend_scene(path: str): """Saves the scene to a .blend file""" bpy.ops.wm.save_as_mainfile(filepath=path)
27,579
def run(main, *, debug=False): """ Since we're using asyncio loop to run wait() in irder to be compatible with async calls, here we also run each wait in a different thread to allow nested calls to wait() """ thread = RunnerThread(main, debug=debug) thread.start() thread.join() if thread...
27,580
def test_backref_thumbnail_div(): """Test if the thumbnail div generates the correct string""" html_div = sg._thumbnail_div('fake_dir', 'test_file.py', 'test formating', is_backref=True) reference = """ .. raw:: html <div class="sphx-glr-thumbcontainer" tooltip="test ...
27,581
def csv_dataset_reader(path): """ This function reads a csv from a specified path and returns a Pandas dataframe representation of it, and renames columns. :param path: Path to and name of the csv file to read. :return: A Pandas dataframe. """ import pandas as pd data = pd.read_csv(path,...
27,582
def get_daily_blurb_info(): """Get daily blurb info.""" html, ss_image_1day_file, ss_image_1year_file = _scrape() return _parse(html, ss_image_1day_file, ss_image_1year_file)
27,583
def generate_random_ring_element(size, ring_size=(2 ** 64), **kwargs): """Helper function to generate a random number from a signed ring""" # TODO (brianknott): Check whether this RNG contains the full range we want. rand_element = torch.randint( -(ring_size // 2), (ring_size - 1) // 2, size, dtype=...
27,584
def Move(args, callback): """Move all files a pattern to a directory.""" assert len(args) == 2 pattern = args[0] dest = args[1] res_src = store_utils.ParseFullPath(pattern) res_dst = store_utils.ParseFullPath(dest) assert res_src is not None and res_dst is not None, 'Source or destination not part of a r...
27,585
def otsu_binarization(img): """ Method to perform Otsu Binarization :param img: input image :return: thresholded image """ ret2, th2 = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) return th2
27,586
def main(tablefile, args=None): """Maps the nodes for the source:alias tablefile. This takes the path to an tablefile (see table_utilities.main) and maps the nodes in it using the Redis DB. It then outputs a status files in the format (table_hash, n1, n2, edge_type, weight, edge_hash, line_hash, st...
27,587
def rosstack_depends_1(s): """ @param s: stack name @type s: str @return: A list of the names of the stacks which s depends on directly @rtype: list """ return rosstackexec(['depends1', s]).split()
27,588
def load_db_dump(dump_file): """Load db dump on a remote environment.""" require('environment') temp_file = os.path.join(env.home, '%(environment)s.sql' % env) put(dump_file, temp_file, use_sudo=True) sudo('psql -d %s -f %s' % (env.db, temp_file), user=env.project_user)
27,589
def _config_file_is_to_update(): """ Ask the user if the configuration file should be updated or not. :return: Returns True if the user wants to update the configuration file and False otherwise. :rtype: bool """ if yes_or_no_input("Do you want to save the account on the configuration file?") ==...
27,590
def _save_predictions(drug_disease_assocs, store, key_name): """ Saves the predictions into an HDFStore using the key_name as key. """ predictions_data = ( drug_disease_assocs.unstack() .reset_index() .rename(columns={"level_0": "trait", "perturbagen": "drug", 0: "score"}) ) ...
27,591
def countbam(sortedbam, outdir): """calculates the raw counts from a BAM index parameters ---------- sortedbam string, the name of the sorted bam file outdir string, the path of the output directory returns ---------- counts_file = file containing the counts """ c...
27,592
def funcScrapeTableWunderground(html_tree, forecast_date_str): """ """ # This will get you the Wunderground table headers for future hour conditions columns = html_tree.xpath("//table[@id='hourly-forecast-table']/thead//button[@class='tablesaw-sortable-btn']") rows = html_tree.xpath("//table[@i...
27,593
def as_finite_diff(derivative, points=1, x0=None, wrt=None): """ Returns an approximation of a derivative of a function in the form of a finite difference formula. The expression is a weighted sum of the function at a number of discrete values of (one of) the independent variable(s). Parameters...
27,594
def is_prime(pp: int) -> bool: """ Returns True if pp is prime otherwise, returns False Note: not a very sophisticated check """ if pp == 2 or pp == 3: return True elif pp < 2 or not pp % 2: return False odd_n = range(3, int(sqrt(pp) + 1), 2) return not any(not pp % ...
27,595
def createChromosome( totQty, menuData ): """ Creates the chromosome with Qty assigned to Each Dish such that sum of all Qty equals to the number of dishes to be ordered totQty = Number of Dishes to be Ordered returns chromosome of dish id and corresponding quantity """ chromosome = [] ...
27,596
def add_residual(transformed_inputs, original_inputs, zero_pad=True): """Adds a skip branch to residual block to the output.""" original_shape = original_inputs.shape.as_list() transformed_shape = transformed_inputs.shape.as_list() delta = transformed_shape[3] - original_shape[3] stride = int(np.ceil(origina...
27,597
def test_load_database_from_path(tmp_path): """Test that database is generated because it does not exist.""" path = tmp_path / "test.db" database = load_database(path=path) assert isinstance(database, sqlalchemy.MetaData) assert database.bind is not None
27,598
def _find_bad_channels_in_epochs(epochs, picks, use_metrics, thresh, max_iter): """Implements the fourth step of the FASTER algorithm. This function attempts to automatically mark bad channels in each epochs by performing outlier detection. Additional Parameters --------------------- use_metri...
27,599