content
stringlengths
22
815k
id
int64
0
4.91M
def getprofileimgtag(request): """ Function to form the img tag for profile image based on whether the user has a profile image or not. """ db = get_mongo_client() if request.COOKIES.has_key('sessioncode'): sesscode = request.COOKIES['sessioncode'] else: sesscode = "" if ...
5,299,100
def where2d(image): """ numpy.where for 2D matrices. :param image: Input images :return: Coordinate list where image is non-zero >>> where2d(np.array([[ 0, 0, 0], ... [ 0, 1, 1], ... [ 0, 0, 0]])) array([[1, 1], [1, 2]]) """ ...
5,299,101
def mapSmallRNAReadsToGenomeUsingBowtie1(mutant,timepoint,replicate,organism): """ This function maps the reads to the genome. There are 90 samples in our panel. Please check the .error file to see how many reads mapped to the genome. Please do not issue a samtools flagstat command. The output isn't as ...
5,299,102
def continue_prompt(message=''): """Continue prompt to verify that a user wants to continue or not. This prompt's purpose is to prevent accidental changes that are difficult to reverse. Keyword Args: message (str): The message to display to the user Returns: bool: If the user want...
5,299,103
def split_validation(dataset, val_fraction, _rnd): """Randomly split a dataset into two non-overlapping new datasets. Arguments: dataset (Dataset): Dataset to be split val_fraction: Fraction of dataset that should be in the validation split _rnd: Random state to determine sp...
5,299,104
def get_file_format(infile): """ get cap file format by magic num. return file format and the first byte of string :type infile:io.BufferedReader """ buf = infile.read(4) if len(buf) == 0: # EOF print("empty file", file=sys.stderr) sys.exit(-1) if len(buf) < 4: ...
5,299,105
def pl_to_eng(unit: str) -> str: """Converts Polish terminology to English""" switcher = { "pikinier": "spear", "miecznik": "sword", "topornik": "axe", "lucznik": "archer", "zwiadowca": "spy", "lekki kawalerzysta": "light", "lucznik na koniu": "marcher", ...
5,299,106
def main(): """ eCALHDF5 Write & Read Sample Step 1: create hdf5 file and add some data Step 2: read data from newly created file """ ENTRY_COUNT = 30 MAX_ENTRY_DATA_SIZE = 32767 # Step 1: create hdf5 file and add some data # File properties output_dir = "ecalhdf5_rw_meas_folder" file_name ...
5,299,107
def is_meta_resource_type_mutable(context, meta_resource_type): """Return True if the meta_resource_type is mutable in this context.""" if context.is_admin: return True if context.owner is None: return False # (lakshmiS): resource type can exist without an association with # namesp...
5,299,108
def has_at_least_one_key(*keys): """Validator that at least one key exists.""" def validate(obj): """Test keys exist in dict.""" if not isinstance(obj, dict): raise vol.Invalid('expected dictionary') for k in obj.keys(): if k in keys: return obj ...
5,299,109
def count_files_in_dir(dir_name): """ After do_activity, check the directory contains a zip with ds_zip file name """ file_names = glob.glob(dir_name + os.sep + "*") return len(file_names)
5,299,110
def get_site_data(site_code, parameter_code, as_dataframe=True, start_date=None, end_date=None, dam_site_location='head'): """Fetches site's parameter data Parameters ---------- site_code : str The LCRA site code (four chars long) of the site you want to query data for....
5,299,111
def remove_if_exists(fnm): """ Remove the file if it exists (doesn't return an error). """ if os.path.exists(fnm): os.remove(fnm)
5,299,112
def mosaic(data, index=None, ax=None, horizontal=True, gap=0.005, properties=lambda key: None, labelizer=None, title='', statistic=False, axes_label=True, label_rotation=0.0): """Create a mosaic plot from a contingency table. It allows to visualize multivariate categorical data...
5,299,113
def process_pos_tags(corp, path): """ Take the newly created corpus and extract the part-of-speech tags from the gloss in order to train a classifier. :param corp: :param path: """ f = open(path, 'w', encoding='utf-8') for inst in corp: gloss_pos = inst.find(id='gw-pos') ...
5,299,114
async def test_file_denied_dir(hass): """Test that the file only service fails to read an image in a dir not explicitly allowed.""" service_data = { ATTR_PATH: "/path/to/a/dir/not/allowed/image.png", ATTR_ENTITY_ID: LIGHT_ENTITY, # Standard light service data which we pass ATTR_B...
5,299,115
async def test_on_reaction_add_to_message(): """Adds the selected role from a role message.""" cog, mock_bot, reaction_for_role_message = init_mocks() reaction_for_role_message.message_id = tosurnament_mock.DEFAULT_MESSAGE_MOCK.id reaction_for_role_message.emojis = "🛎️" reaction_for_role_message.ro...
5,299,116
def get_auth_realm(url, auth_info, scheme=None): """Determine an authentication realm identifier from a HTTP response. Examples -------- Robustly determine a realm identifier for any URL:: >>> url, props = probe_url('https://fz-juelich.sciebo.de/...') >>> get_auth_realm(url, props.get('a...
5,299,117
def plot_mpl(forecast, timestamp_col, target_col, var_id=0, actual=None, history=None, forecast_interval=None, show_forecast_interval=False, include_history=False, figsize=None, grid=True): ...
5,299,118
def pdf(data, x, bins=10, normalize=True, *args, **kwargs): """ Plot a probability density function (pdf) from a dataframe column. If hue is provided, plot many overlayed pdf, one per value of the data[hue] column. Parameters ---------- data: pandas.DataFrame dataframe to plot ...
5,299,119
def is_ok(resp: Response) -> bool: """ is_ok returns True is the API responded with 200 and the content type is JSON. """ return ( resp.headers["content-type"] == "application/json" and resp.status_code == codes.ok )
5,299,120
def main(file_arg=""): # type: (str) -> None """Main entry point.""" # Set working dir to script's current os.chdir(dirname(realpath(__file__))) # Script arguments testcase_arg = "" if len(sys.argv) > 1 and sys.argv[1].startswith("--"): # Will allow to pass custom args like --debug...
5,299,121
def pretty_size(size, sep: str = ' ', lim_k: int = 1 << 10, lim_m: int = 10 << 20, plural: bool = True, floor: bool = True) -> str: """Convert a size into a more readable unit-indexed size (KiB, MiB) :param size: integral value to convert :param sep: the separator char...
5,299,122
def export_summary(request, qid, answer_filter=None): """ For a given questionnaire id, generate a CSV containing a summary of answers for all subjects. qid -- questionnaire_id answer_filter -- custom filter for the answers. If this is present, the filter must manage access. """ if answer_fi...
5,299,123
def get_net(config): """Given the configuration, call a function to create the network object.""" if 'Six_Bus' in config.env_name: return six_bus(config.vn_high, config.vn_low, config.length_km, config.std_type, config.battery_locations, config.init_soc, con...
5,299,124
def last_bracket(tokens: List[tokenize.TokenInfo], index: int) -> bool: """Tells whether the given index is the last bracket token in line.""" return only_contains( tokens[index + 1:], NEWLINES.union({tokenize.COMMENT}), )
5,299,125
def run_kernel_pca(X_train: np.ndarray, X_test: np.ndarray, kernel: str, d: int, sigma: float ) -> Tuple[np.ndarray, float]: """ Run Kernel PCA experiment. Parameters ---------- X_train : numpy.ndarray, 2d ...
5,299,126
def _create_documents(connection, object_type, table_name): """Create documents and prepare relationships for insert.""" sql = """ INSERT INTO temp_url (object_id, url, modified_by_id, parent_created_at, parent_updated_at, context_id, directive_typ...
5,299,127
def validate_matching_number_of_samples( data_a: np.ndarray, label_data_a: str, data_b: np.ndarray, label_data_b: str ): """Validates the number of samples of two given datasets. :param data_a: Dataset a to be validated. :param label_data_a: Label for `data_a` to provide an understandable exception mes...
5,299,128
def test_overfit_pypaddle_class( create_easy_data_class, model, n_cls: int, dim: int, n_epochs: int, loss: BaseLoss, distance: str, ): """This test makes sure that we can overfit the model to a small amount of data. We use an over-parametrized model (a few thousand weights for <100 ...
5,299,129
async def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback ) -> None: """Set up the buienradar platform.""" config = entry.data latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude)...
5,299,130
def run_paths_test(profile=None, provider=None, credentials=None): """ Test that the path management works against the given provider. """ # Get the client for this test client = cloudless.Client(profile, provider, credentials) # Get a somewhat unique network name network_name = generate_u...
5,299,131
def lint(path_list, excludes=''): """Runs pylint on all files in path list and returns results dictionary CATCHES: AssertionError - raised or thrown by _lint_file due to unexpected pylint output Args: path_list ------ a list of pathlib.Path objects representin...
5,299,132
def reduce_array(x, reduction='mean', axis=2, weights=None): """ Auxiliary method to perform one of the following operations: nanmean, nanmax, nanmedian, nanmin, nanstd, and, or, wmean. Args: ---- x: `ndarray` input array in which to perform the operation reduction: `str` re...
5,299,133
def jacobi_weights(roots, n, alpha, beta): """Calculate the weight of each root Args: n: the order of the polynomial alpha: the alpha parameter in Jacobi polynomials beta: the beta parameter in Jacobi polynomials """ jacobi_check(n, alpha, beta) jacobi_roots_check(roots, n, ...
5,299,134
def write(file, iterable, sep=None): """ Write anything on the iterable to a file. Args: file: file path or STDOUT if None iterable: values to write sep (string, optional): split values with this separator. Provide only if the iterable returns multiple items each time """ i...
5,299,135
def test_logging_capture_warnings(caplog): """ This tests that the `logging.captureWarnings(True)` line has been executed in the `aclient` module. This must be run with the `-p no:warnings` option provided to `pytest`. As a result, it is skipped by default. See `/conftest.py` for options. """...
5,299,136
def _get_current_unhelpful(old_formatted): """Gets the data for the past week and formats it as return value.""" final = {} cursor = connection.cursor() cursor.execute( """SELECT doc_id, yes, no FROM (SELECT wiki_revision.document_id as doc_id, SUM(limitedvo...
5,299,137
def _serialize_objects(f_parameters): """ Infer COMPSs types for the task parameters and serialize them. WARNING: Updates f_parameters dictionary :param f_parameters: <Dictionary> - Function parameters :return: Tuple of task_kwargs updated and a dictionary containing if the objects ar...
5,299,138
def train(model, dataset_dir, subset = None): """Train the model.""" # Training dataset. dataset_train = f_things_dataset() dataset_train.load_fthings(dataset_dir,'train') dataset_train.prepare() # Validation dataset dataset_val = f_things_dataset() dataset_val.load_fthings(dataset_dir,...
5,299,139
def reboot(config, log): """Funcia de reboot""" log.write("S-a terminat procedura de instalare\n") dictionar = config['after_install'][0] method = dictionar['reboot']['method'] log.write("Sistemul se va restarta\n") if method == "soft": os.system("shutdown -r") else: os.syste...
5,299,140
def enforceStringFormat(prompt, regex = None, minLength = None, maxLength = None): """ Enforces a string at a prompt Args: prompt: String for user input prompt regex: regular expression the string should conform to minLength: minimum valid string length maxValue: maximum val...
5,299,141
def print_last_14_days(dataframe): """ Function to print last 14 days worth of records :param dataframe: :return: Last 14 days of records from dataframe """ pd.options.display.width = 0 print(dataframe[dataframe['timestamp'] > (dt.now() - td(days=14)).strftime('%Y-%m-%d %H:%M...
5,299,142
def render_hist( df: pd.DataFrame, x: str, meta: ColumnMetadata, plot_width: int, plot_height: int, ) -> Figure: """ Render a histogram """ if is_dtype(meta["dtype"], Nominal()): tooltips = [ (x, "@x"), ("Count", "@count"), ("Label", "@label"), ] ...
5,299,143
def build_new_list(source_path, list_title='Empty Name', recursive=False, show_source=False): """ Searches for image files on your hard drive and creates a list with their names and properties. :param source_path: Search directory :param list_title: File list name :param recursive: Enable recursive...
5,299,144
def RegexFilterPageGenerator(generator, regex): """Yield pages from another generator whose titles match regex.""" reg = re.compile(regex, re.I) for page in generator: if reg.match(page.title(withNamespace=False)): yield page
5,299,145
def describe(a, axis=0, ddof=0, bias=True): """ Computes several descriptive statistics of the passed array. Parameters ---------- a : array_like Data array axis : int or None, optional Axis along which to calculate statistics. Default 0. If None, compute over the whole ...
5,299,146
def get_translated_text( text: typing.Optional[typing.Union[str, typing.Dict[str, str]]], language_code: typing.Optional[str] = None, default: str = '' ) -> str: """ Return the text in a given language from a translation dictionary. If the language does not exist in text, the return...
5,299,147
def proc_imgur_url(starturl): """ Process an imgur link """ # If imgur is not in the link, skip it if "imgur.com" not in starturl: return starturl finishedurl = [] regex = r"href\=\"https://i\.imgur\.com\/([\d\w]*)(\.jpg|\.png|\.gif|\.mp4|\.gifv)" try: imgurHTML = reque...
5,299,148
def handler(service, action): """ Handler method for service operations. """ cmd = 'systemctl {} {}'.format(action, service) return sudo(cmd, pty=False)
5,299,149
def classification(training_df: DataFrame, test_df: DataFrame, clusterer: Clustering, job: Job) -> (dict, dict): """main classification entry point train and tests the classifier using the provided data :param clusterer: :param training_df: training DataFrame :param test_df: testing DataFrame ...
5,299,150
def write_commands_instructions( commands_instructions: Dict[str, List[str]], scene_path: Path, index: int ) -> Path: """*Deprecated, use `write_yaml_instructions` instead.* Writes a command instruction `yaml` file. These are the files that [`runner`](github.com/TrickyTroll/good-bot-runner) takes ...
5,299,151
def replace_simultaneous(s: str, r0: str, r1: str) -> str: """ Replace all instances of `r0` in `s` with `r1` and vice versa. This method does the replacements simultaneously so that, e.g., if you call `replace_simultaneous("apple banana", "apple", "banana")` the result will be `"banana apple"` ins...
5,299,152
def run(rss_api, title_queue, args, configuration): """Main loop.""" while True: try: monitor_rss(rss_api, title_queue, args, configuration) except KeyboardInterrupt: sys.exit(1) except Exception as error: # pylint: disable=broad-except print_time_mes...
5,299,153
def merge_gt_feat(gt_filen, feat_filen, train_filen): """ @brief Read the files containing ground truths and features and merge them to be used for classification @param gt_filen The ground truths filename @param feat_filen The features filename """ utils....
5,299,154
def initiate_archive_download(ctx, archive_info, vault_name=None, account_id=None, region=None): """Initiate the archive donwload job. After the job has completed (3-5h), the archive can be downloaded with download-archive task. Output file of this task is the input of download-archive archive-inf...
5,299,155
def _is_sound_file(name): """Return: True if name is the name of an font file""" if type(name) != str: return False return os.path.exists(SOUND_PATH+'/'+name)
5,299,156
def multiple_best_intervals(arg, duration, number): """Compute multiple best intervals TODO: This function should return a list of {'start_index': v, 'stop_index': v, 'index': v, 'value': v} Parameters ---------- arg : pd.Stream duration : number number : int Returns ------- nd...
5,299,157
def _print_cluster_info(cluster, out_format): """print queue info""" headers = [ 'cluster id', 'cluster name', 'description', 'endpoint', 'source', 'cluster type', 'version', 'status', 'setting', 'namespace list', 'create time', 'update time' ] data = [[ cluster.clusterid...
5,299,158
def ransac_fundamental_matrix(matches_a, matches_b): """ Find the best fundamental matrix using RANSAC on potentially matching points. Your RANSAC loop should contain a call to estimate_fundamental_matrix() which you wrote in part 2. If you are trying to produce an uncluttered visualization of epip...
5,299,159
def statement_uri_query(db, needle): """Filter Statements by searching for mathich uris. Return value can be used as subquery. """ Statement = db.entities["Statement"] query = orm.select(st for st in Statement for uri in st.uris if uri.uri == needle) return query
5,299,160
def partition_into_cells(mesh): """ Resolve all-intersections of the input mesh and extract cell partitions induced by the mesh. A cell-partition is subset of the ambient space where any pair of points belonging the partition can be connected by a curve without ever going through any mesh faces. A...
5,299,161
def reshape_2d_scan_for_axis(scan, axis): """Reshape 2d scan for given axis into an actual 2d object. This reshapes images with shape `(398, 1, 430)` into shape `(398, 430)` etc.""" axis = axis_str_to_int(axis) scan = np.copy(scan) if axis == 1: scan = scan.reshape((scan.shape[0], ...
5,299,162
def _list_tgz(filename): """ Prints all of the files in a .tar.gz file """ tf = tarfile.open(filename, 'r:gz') for name in tf.getnames(): print(' %s' % name)
5,299,163
def get_positive_samples_in_source_plate(source_plate_uuid: str) -> Optional[List[SampleDoc]]: """Attempt to get a source plate's Result=Positive samples. Arguments: source_plate_uuid {str} -- The source plate UUID for which to get positive samples. Returns: {List[SampleDoc]} -- A list of ...
5,299,164
def server_is_exception(server, new_channel): """ Check if server is an exception """ if smtools.CONFIGSM['maintenance']['exception_sp']: for key, value in smtools.CONFIGSM['maintenance']['exception_sp'].items(): if key == new_channel: for server_exception in value: ...
5,299,165
def get_coin_symbol_by_index(coin_index): """ Retrieves a coin SYMBOL when passed a coin INDEX Returns: String """ coin_symbol = coin_symbol_by_index.get(coin_index) if coin_symbol is not None: return coin_symbol # need to do a real lookup coins_reverse = global_enum...
5,299,166
def setup_topo1(topology): """ Build a topology of one switch and four hosts. Connect the hosts to the switch. """ global p1 global p2 global p3 global p4 global vlan_result global hs1ipv6 global hs2ipv6 global hs3ipv6 global hs4ipv6 global opstop global swmac...
5,299,167
def test_benchmarks_main_big(monkeypatch, capfd): """ This does a FASTQ benchmark and a BAM benchmark and checks that they produce the same output, which they should since they're the same file. """ import sys with monkeypatch.context() as m: m.setattr(sys, 'argv', [sys.argv[0]] + "b...
5,299,168
def _parse(data): """Recursively convert a json into python data types""" if not data: return [] elif isinstance(data, (tuple, list)): return [_parse(subdata) for subdata in data] # extract the nested dict. ex. {"tournament": {"url": "7k1safq" ...}} d = {ik: v for k in data.keys() ...
5,299,169
def get_speed(x, y): """ Compute speed at each frame from XY coordinates, somehow its missing for paws in database """ rawspeed = ( np.hstack([[0], np.sqrt(np.diff(x) ** 2 + np.diff(y) ** 2)]) * 60 ) return convolve_with_gaussian(rawspeed, 9)
5,299,170
def commit_stage(context): """ Run commit stage tasks :param context: invoke.Context instance """ unit_tests(context) static_code_analysis(context)
5,299,171
def calculate_iv_curve(effective_irradiance, temperature, module_parameters, ivcurve_pnts=200): """ :param effective_irradiance: :param temperature: :param module_parameters: :param ivcurve_pnts: :return: """ photocurrent, saturation_current, resistance_series, re...
5,299,172
def gz_file(request): """ get the full path of the test fixture """ return os.path.join(request.fspath.dirname, 'source/mc3/tcga_gz-test.maf.gz')
5,299,173
def fsa(C,u10,SP,T,*,slp=1.0,gas=None,param="W14",rh=1): """ DESCRIPTION ------------- Diffusive gas flux across the air-sea interface in mol m-2 s-1 F = k (C - Ceq_slp) INPUTS: ---------- C Surface dissolved gas concentration [mol m-3 == mmol L-1] u10...
5,299,174
def get_train_img(): """ 获取输入数据 :return: """ cwd=os.getcwd() mi_dir=cwd+'/dataset/train/mi/' shu_dir=cwd+'/dataset/train/shu/' file1=os.listdir(mi_dir) file0=os.listdir(shu_dir) # file1.sort(key=lambda x: int(x[:-4])) # file0.sort(key=lambda x: int(x[:-4])) mi_img_list=np...
5,299,175
def calc_cos(v_i,v_j): """ Calculate the cos theta between two vectors """ return np.dot(v_i/np.linalg.norm(v_i),v_j/np.linalg.norm(v_j))
5,299,176
def upload_an_image(admin_browser): """Upload an image in the CMS. Note: Duplicate of the same helper function in base_functional_tests. """ admin_browser.find_by_text('Choose an image').click() click_obscured(admin_browser, admin_browser.find_by_text('Upload').first) admin_browser.fil...
5,299,177
def main(args): """Main training function.""" torch.cuda.set_device(args.device_id) if args.distributed: args.distributed_rank = args.device_id distributed_init(args) if args.seed is not None: np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch....
5,299,178
def _add_ema(model, decay): """Create ops needed to track EMA when training. :param model: The model with a `.sess` we want to track. :param decay: float, Decay to use in the EMA :returns: ema_op: The update op. This applies the ema to each variable. Should be set as a control depen...
5,299,179
def retry_http(response): """Retry on specific HTTP errors: * 429: Rate limited to 50 reqs/minute. Args: response (dict): Dynatrace API response. Returns: bool: True to retry, False otherwise. """ retry_codes = [429] code = int(response.get('error', {}).get('code', 200)) ...
5,299,180
def _box_cox_transform(values, standard=True): """ Performs the Box-Cox transformation, over different ranges, picking the optimal one w. respect to normality. """ a = sp.array(values) if standard: vals = (a - min(a)) + 0.1 * sp.var(a) else: vals = a sw_pvals = [] lambdas...
5,299,181
def bst_check(now=None): """ Determine whether the specified date lies within the British Summer Time period. Args: n (tuple): An 8-tuple indicating the request date (see http://docs.micropython.org/en/latest/library/utime.html?highlight=localtime#utime.localtime). Returns: ...
5,299,182
def local_genus_symbol(self, p): """ Returns the Conway-Sloane genus symbol of 2 times a quadratic form defined over ZZ at a prime number p. This is defined (in the Genus_Symbol_p_adic_ring() class in the quadratic_forms/genera subfolder) to be a list of tuples (one for each Jordan component p^...
5,299,183
def extract_events(line, ngram_base = 'words', ngram_size = 1, outcomes_provided = True, not_symbol_pattern = not_symbol_pattern_en, remove_weird_words = False, sep_words = "#", sep_ngrams = '_', mark_word_boundary = True, lowercase = True, remove_duplicates =...
5,299,184
def p_expression(p): """ expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression """ p[0] = (p[2], p[1], p[3])
5,299,185
def test_history_creation_remote_errors( rotkehlchen_server_with_exchanges, accountant, ): """Test that during history creation, remote errors are detected and errors are returned""" server = rotkehlchen_server_with_exchanges rotki = server.rotkehlchen rotki.accountant = accountant k...
5,299,186
def reduce_parenthesis(text_in: str) -> List[str]: """ reduce parenthesis Called recursively. Removes one layer of parenthesis and breaks the string into parts. Parameters ---------- text_in: str Returns ------- list_text: list[str] Examples -------- "(aaaaa)" --> "aa...
5,299,187
def set_obj_from_module(module: types.ModuleType, obj_name: str, value: Any) -> Any: """Traverses the object name and returns the last (rightmost) python object.""" if obj_name == '': return module obj = module parts = obj_name.replace('/', '.').split(".") last = parts.pop() for part in parts: obj =...
5,299,188
def write_tikzpicture(fname, title, xlabel, ylabel, data, xlog, barplot): """stores the data in a local tikzpicture tex file""" xlabel = '\t\txlabel={' + xlabel + '},' ylabel = '\t\tylabel={' + ylabel + '},' title = '\t\ttitle={' + title + '},' xmode = '\t\txmode=log,' if xlog else '\t\txmode=normal...
5,299,189
def convert(prototxt_path, caffemodel_path, phase='test', output_model_name='freeze_graph_model.pb'): """ 'def_path', 'Model definition (.prototxt) path' 'caffemodel', 'Model data (.caffemodel) path' 'phase', default='test','The phase to convert: test (default) or train' 'output_model_name', saved t...
5,299,190
def _sparsify_matrix_kernel(matrix_input, epsilon=1): """ The matrix sparsification procedure. See https://www.researchgate.net/publication/221462839_A_Fast_Random_Sampling_Algorithm_for_Sparsifying_Matrices :param matrix_input: a matrix to be sparsified :param epsilon: approximation constant. :ret...
5,299,191
def __bit_string_to_int(BitStr): """Transforms a string of the form '01001001' into an integer which represents this byte. TESTED <frs> """ BitStr = BitStr.replace(".", "") BitArray = map(lambda x: x, BitStr) BitArray.reverse() n = 0 sum = 0 for bit in BitArray: if bit...
5,299,192
def map_samples(options, reference_gbk_file, input_dir, outdir): """ """ ## set it as variable contig_option = False pd_samples_retrieved_merge = pd.DataFrame() pd_samples_retrieved = pd.DataFrame() ## all_data // only_project_data if (options.all_data or options.only_project_...
5,299,193
def parse_args(args): """ Parses command line arguments and sets global options :returns: operands (list of regexes) """ global ignore_case try: options, arguments = getopt.getopt( args, 'vhi', ["version", "help", "ignore-case"]) for o, a in o...
5,299,194
def expensesByTail(update: Update, context: CallbackContext): """ Start the flow for listing the previous N expenses """ text = ("Please select an option or type in the number of most recently recorded expenses to show.") reply_markup = reply_markups.backnHomeInlineMarkup context.bot.send_me...
5,299,195
def include_categories(f): """Return an object with all categories (decorator).""" @wraps(f) def decorated_function(*args, **kwargs): categories = c.query(Category).all() # pass along the categories object to the next function kwargs['categories'] = categories return f(*args,...
5,299,196
def shuffle_array(*args): """ Shuffle the given data. Keeps the relative associations arr_j[i] <-> arr_k[i]. Params ------ args: (numpy arrays tuple) arr_1, arr_2, ..., arr_n to be shuffled. Return ------ X, y : the shuffled arrays. """ # Assert that there is at least on...
5,299,197
def circular_wetted_perimeter(angle, diameter): """Returns circle wetted perimeter. :param angle: angle in radians from angle_in_partial_filled_pipe function :param diameter: diameter of pipe [m] """ return angle * diameter
5,299,198
def refresh_geneinfo_mgimapping(): """Refresh the ``SmallVariantSummary`` materialized view.""" with connection.cursor() as cursor: with transaction.atomic(): cursor.execute("REFRESH MATERIALIZED VIEW geneinfo_mgimapping")
5,299,199