content
stringlengths
22
815k
id
int64
0
4.91M
def admin_user_detail(): """管理员信息编辑详情页""" if not g.user.is_admin: return redirect('/') if request.method == 'GET': # 获取参数 admin_id = request.args.get('admin_id') if not admin_id: abort(404) try: admin_id = int(admin_id) except Excepti...
5,332,700
def splitBinNum(binNum): """Split an alternate block number into latitude and longitude parts. Args: binNum (int): Alternative block number Returns: :tuple Tuple: 1. (int) Latitude portion of the alternate block number. Example: ``614123`` => ``614`` 2....
5,332,701
def load_model_from_params_file(model): """ case 0: CHECKPOINT.CONVERT_MODEL = True: Convert the model case 1: CHECKPOINT.RESUME = False and TRAIN.PARAMS_FILE is not none: load params_file case 2: CHECKPOINT.RESUME = True and TRAIN.PARAMS_FILE is not none: case 2a: if checkpoin...
5,332,702
def getPool(pool_type='avg', gmp_lambda=1e3, lse_r=10): """ # NOTE: this function is not used in writer_ident, s. constructor of # ResNet50Encoder params pool_type: the allowed pool types gmp_lambda: the initial regularization parameter for GMP lse_r: the initial regularization p...
5,332,703
def test_id_l071_id_l071_v(mode, save_output, output_format): """ TEST :Identity-constraint Definition Schema Component : Test valid XML for keyref definition, field xpath='attribute::*' , selector contains * """ assert_bindings( schema="msData/identityConstraint/idL071.xsd", ins...
5,332,704
def draw_transperency(image, mask, color_f, color_b): """ image (np.uint8) mask (np.float32) range from 0 to 1 """ mask = mask.round() alpha = np.zeros_like(image, dtype=np.uint8) alpha[mask == 1, :] = color_f alpha[mask == 0, :] = color_b image_alpha = cv2.add(image, alpha) ret...
5,332,705
def split_in_pairs(s, padding = "0"): """ Takes a string and splits into an iterable of strings of two characters each. Made to break up a hex string into octets, so default is to pad an odd length string with a 0 in front. An alternative character may be specified as the second argument. """ ...
5,332,706
def make_slicer_query_with_totals_and_references( database, table, joins, dimensions, metrics, operations, filters, references, orders, share_dimensions=(), ): """ :param dataset: :param database: :param table: :param joins: :param dimensions: :param m...
5,332,707
def corr_na(array1, array2, corr_method: str = 'spearmanr', **addl_kws): """Correlation method that tolerates missing values. Can take pearsonr or spearmanr. Args: array1: Vector of values array2: Vector of values corr_method: Which method to use, pearsonr or spearmanr. **addl_k...
5,332,708
def superCtx(*args, **kwargs): """ Flags: - attach : a (unicode) [] - exists : ex (bool) [] - image1 : i1 (unicode) [] - image2 : i2 (unicode) [] - image3 : i...
5,332,709
def directory_generator(dirname, trim=0): """ yields a tuple of (relative filename, chunking function). The chunking function can be called to open and iterate over the contents of the filename. """ def gather(collect, dirname, fnames): for fname in fnames: df = join(dirname...
5,332,710
def analyze_member_access(name: str, typ: Type, node: Context, is_lvalue: bool, is_super: bool, is_operator: bool, builtin_type: Callable[[str], Instance], ...
5,332,711
def close_gaps(in_path, out_path, threshold=0.1): """ Interpolates the holes (no data value) in the input raster. Input: in_path: {string} path to the input raster with holes threshold: {float} Tension Threshold Output: out_path: {string} path to the generated raster with closed ...
5,332,712
def has_global(node, name): """ check whether node has name in its globals list """ return hasattr(node, "globals") and name in node.globals
5,332,713
def make_generator_model(input_dim=100) -> tf.keras.Model: """Generator モデルを生成する Args: input_dim (int, optional): 入力次元. Defaults to 100. Returns: tf.keras.Model: Generator モデル """ dense_size = (7, 7, 256) conv2d1_channel = 128 conv2d2_channel = 64 conv2d3_channel = 1 ...
5,332,714
def shutdown(): """ Tell the arkouda server to delete all objects and shut itself down. """ global socket, pspStr, connected, verbose # send shutdown message to server message = "shutdown" if verbose: print("[Python] Sending request: %s" % message) socket.send_string(message) m...
5,332,715
def deploy_gradle(app, deltas={}): """Deploy a Java application using Gradle""" java_path = join(ENV_ROOT, app) build_path = join(APP_ROOT, app, 'build') env_file = join(APP_ROOT, app, 'ENV') env = { 'VIRTUAL_ENV': java_path, "PATH": ':'.join([join(java_path, "bin"), join(app, ".bin...
5,332,716
def find_badge_by_slug(slug: str) -> Optional[Badge]: """Return the badge with that slug, or `None` if not found.""" badge = db.session \ .query(DbBadge) \ .filter_by(slug=slug) \ .one_or_none() if badge is None: return None return _db_entity_to_badge(badge)
5,332,717
def start_bot(tasks): """run async loop with tasks list""" platforms=asyncio.gather(*tasks,loop=loop) loop.run_until_complete(platforms)
5,332,718
def reslice_ops(ops, aligned_op_slice_sizes, op_reg_manager): """Reslices ops according to aligned sizes. Args: ops: List of tf.Operation to slice. aligned_op_slice_sizes: List of integer slice sizes. op_reg_manager: OpRegularizerManager to keep track of slicing. """ for op_to_slice in ops: op_...
5,332,719
def extract_img_features( input_path, input_type, output_path, img=None, img_meta=None, feature_mask_shape="spot", ): """ Extract features from image. Works with IF or HE image from Visium tif files. For block feature, a square will be drawn around each spot. Since it is bigger than ...
5,332,720
def image_generator(files, batch_size): """ Generate batches of images for training instead of loading all images into memory :param files: :param batch_size: :return: """ while True: # Select files (paths/indices) for the batch batch_paths = np.random.choice(a=files, ...
5,332,721
def validate_color(color,default,color_type): """Validate a color against known PIL values. Return the validated color if valid; otherwise return a default. Keyword arguments: color: color to test. default: default color string value if color is invalid. color_type: string name for color type, used for alertin...
5,332,722
def save_dreams(basedir, agent, data, embed, image_pred, obs_type='lidar', summary_length=5, skip_frames=10): """ Perform dreaming and save the imagined sequences as images. `basedir`: base log dir where the images will be stored `agent`: instance of dreamer `embed`: tensor of embeds, shape...
5,332,723
def d_xx_yy_tt(psi): """Return the second derivative of the field psi by fft Parameters -------------- psi : array of complex64 for the field Returns -------------- cxx psi_xx+ cyy psi_yy + ctt psi_tt : second derivatives with respect to x """ # this function is to rem...
5,332,724
def test_classes(classes, expected_classes): """Test that classes are properly parsed. 1. Create an action parser for a dictionary with specific classes. 2. Parse classes. 3. Check the parsed classes. """ actual_classes = ActionParser(data={"class": classes}, parser=JSONParser()).parse_classes(...
5,332,725
def negate_objective(objective): """Take the negative of the given objective (converts a gain into a loss and vice versa).""" if isinstance(objective, Iterable): return (list)((map)(negate_objective, objective)) else: return -objective
5,332,726
def process_vm_size(file_name: str) -> Any: """ Extract VMs instance specification. :file_name (str) File name Return VMs specification object """ current_app.logger.info(f'Processing VM Size {file_name}...') file = open(file_name,) data = json.load(file) return data
5,332,727
def gen_key(password, salt, dkLen=BLOCKSIZE): """ Implement PBKDF2 to make short passwords match the BLOCKSIZE. Parameters --------- password str salt str dkLen int Returns ------- - str """ return KDF.PBKDF2(pas...
5,332,728
def _bytes_feature(value): """Wrapper for inserting bytes features into Example proto.""" if isinstance(value, six.string_types): value = six.binary_type(value, encoding='utf-8') return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
5,332,729
def test_success(database): """ BusinessFundsIndicator must contain one of the following values: REC or NON. Case doesn't matter """ det_award = DetachedAwardFinancialAssistanceFactory(business_funds_indicator="REC") det_award_2 = DetachedAwardFinancialAssistanceFactory(business_funds_indicator="non") ...
5,332,730
def parse_plot_set(plot_set_string): """ Given one of the string arguments to the --plot-sets option, parse out a data structure representing which conditions ought to be compared against each other, and what those comparison plots/tables should be called. The syntax of a plot set is [title:]c...
5,332,731
def check_types_excel(row: tuple) -> bool: """Returns true if row from excel file has correct types""" if not isinstance(row[1], (pd.Timestamp, str)): return False if not ((isinstance(row[2], dt.time) and isinstance(row[3], dt.time)) or (isinstance(row[2], str) and isinstance(row[3], str...
5,332,732
def add(num1, num2): """ Adds two numbers >>> add(2,4) 6 """ return num1 + num2
5,332,733
def is_palindrome1(str): """ Create slice with negative step and confirm equality with str. """ return str[::-1] == str
5,332,734
def number_generetor(view, form): """ Генератор номера платежа (по умолчанию) """ if is_py2: uuid_fields = uuid4().get_fields() else: uuid_fields = uuid4().fields return u'{:%Y%m%d}-{:08x}'.format(datetime.now(), uuid_fields[0])
5,332,735
def get_underlay_info(): """ :return: """ return underlay_info
5,332,736
async def get_guild_roles(id_: int): """ Get the roles of a guild :param id_: Guild ID :return: List of roles """ guild = await router.bot.rest.fetch_guild(id_) if guild is None: return status.HTTP_404_NOT_FOUND roles = await guild.fetch_roles() return [to_dict(role...
5,332,737
def prior_min_field(field_name, field_value): """ Creates prior min field with the :param field_name: prior name (field name initial) :param field_value: field initial properties :return: name of the min field, updated field properties """ name = field_name value = field_value.copy() ...
5,332,738
def checkpoint_save_config(): """Fixture to create a config for saving attributes of a detector.""" toolset = { "test_id": "Dummy_test", "saved_attributes": { "FeatureExtraction": [ "dummy_dict", "dummy_list", "dummy_tuple", ...
5,332,739
def matrix_sum_power(A, T): """Take the sum of the powers of a matrix, i.e., sum_{t=1} ^T A^t. :param A: Matrix to be powered :type A: np.ndarray :param T: Maximum order for the matrixpower :type T: int :return: Powered matrix :rtype: np.ndarray """ At = np.eye(A.shape[0]) ...
5,332,740
def mean_zero_unit_variance(arr, mean_vector=None, std_vector=None, samples_in='row'): """ Normalize input data to have zero mean and unit variance. Return the normalized data, the mean, and the calculated standard deviation which was used to normalize the data [normalized, meanvec, stddev] = mean_...
5,332,741
def soft_precision(scores: torch.FloatTensor, mask: torch.FloatTensor) -> torch.FloatTensor: """ Helper function for computing soft precision in batch. # Parameters scores : torch.FloatTensor Tensor of scores with shape: (num_refs, num_cands, max_ref_len, max_cand_len) ma...
5,332,742
def fit_sir(times, T_real, gamma, population, store, pathtoloc, tfmt='%Y-%m-%d', method_solver='DOP853', verbose=True, \ b_scale=1): """ Fit the dynamics of the SIR starting from real data contained in `pathtocssegi`. The initial condition is taken from the real data. The method assumes that in the ...
5,332,743
def prepare_es(app, db): """Prepare ES indices.""" return
5,332,744
def panelist_debuts_by_year(database_connection: mysql.connector.connect ) -> Dict: """Returns an OrderedDict of show years with a list of panelists' debut information""" show_years = retrieve_show_years(database_connection) panelists = retrieve_panelists_first_shows(database...
5,332,745
def _stirring_conditions_html(stirring: reaction_pb2.StirringConditions) -> str: """Generates an HTML-ready description of stirring conditions. Args: stirring: StirringConditions message. Returns: String description of the stirring conditions. """ if stirring.type == stirring.NONE:...
5,332,746
def load_action_plugins(): """ Return a list of all registered action plugins """ logger.debug("Loading action plugins") plugins = get_plugins(action, ActionPlugin) if len(plugins) > 0: logger.info("Discovered {n} action plugins:".format(n=len(plugins))) for ap in plugins: ...
5,332,747
def read_file_in_root_directory(*names, **kwargs): """Read a file.""" return io.open( os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get('encoding', 'utf-8') ).read().strip()
5,332,748
def set_effective_property_value_for_node( nodeId: dom.NodeId, propertyName: str, value: str ) -> dict: """Find a rule with the given active property for the given node and set the new value for this property Parameters ---------- nodeId: dom.NodeId The element id for which to set p...
5,332,749
def main(args, unit_test=False, path=''): """ Builds the HTML files path : str, optional Mainly for running the unit test """ from pypeit.core import qa # Flags flg_MF, flg_exp = False, False if args.type == 'MF': flg_MF = True elif args.type == 'exp': flg_exp = T...
5,332,750
async def _write_nlu_to_file( export_nlu_path: Text, events: List[Dict[Text, Any]] ) -> None: """Write the nlu data of the sender_id to the file paths.""" from rasa.nlu.training_data import TrainingData msgs = _collect_messages(events) msgs = _filter_messages(msgs) # noinspection PyBroadExcept...
5,332,751
def texas_job_centers(num_polygons = 4000): """ Choropleth of the percent of workers who work in their place of residence for Austin, Dallas, Houston """ # Get block geodata for all of Texas and calculate features block_data = boundaries.BlockBoundaries(['X08_COMMUTING', 'X01_AGE_AND_SEX'], cities = None) ...
5,332,752
def classroom_page(request,unique_id): """ Classroom Setting Page. """ classroom = get_object_or_404(Classroom,unique_id=unique_id) pending_members = classroom.pending_members.all() admins = classroom.special_permissions.all() members = admins | classroom.members.all() is_admin = classr...
5,332,753
async def remove(ctx, name): """Join the current interview practice.""" # Retrieve the current server server = get_server(ctx.guild.id) # Join the event on the server server.leave_event(name) # Send the join message await ctx.send(name + " has been removed from the interview practice.") ...
5,332,754
def notna(obj: pandas.core.indexes.numeric.Int64Index): """ usage.dask: 2 """ ...
5,332,755
def evaluate(flight_input, flight_target): """Evaluate between G1000 and phone GPS data flight_input : flight.FlightPruneData phone data flight_target : flight.FlightPruneData g1000 data """ STRATUX_LIST = ( '020918_00', '020918_01', '021318_00', '021318_01', '021...
5,332,756
def concat_hists(hist_array: np.array): """Concatenate multiple histograms in an array by adding them up with error prop.""" hist_final = hist_array[0] for hist in hist_array[1:]: hist_final.addhist(hist) return hist_final
5,332,757
def renorm_flux_lightcurve(flux, fluxerr, mu): """ Normalise flux light curves with distance modulus.""" d = 10 ** (mu/5 + 1) dsquared = d**2 norm = 1e18 # print('d**2', dsquared/norm) fluxout = flux * dsquared / norm fluxerrout = fluxerr * dsquared / norm return fluxout, fluxerrout
5,332,758
def retrieve(args: argparse.Namespace, file_handler: DataFilesHandler, homepath: Path) -> str: """Find an expression by name.""" name = NAME_MULTIPLEXOR.join(args.REGULAR_EXPRESSION_NAME) try: return file_handler.get_pattern(name) except KeyError: pass if args.local or (not file_ha...
5,332,759
def find_focus(stack): """ Parameters ---------- stack: (nd-array) Image stack of dimension (Z, ...) to find focus Returns ------- focus_idx: (int) Index corresponding to the focal plane of the stack """ def brenner_gradient(im): assert len(im.shape) == 2, 'Input ima...
5,332,760
def get_amr_line(input_f): """Read the amr file. AMRs are separated by a blank line.""" cur_amr=[] has_content=False for line in input_f: if line[0]=="(" and len(cur_amr)!=0: cur_amr=[] if line.strip()=="": if not has_content: continue else: ...
5,332,761
def getHwAddrForIp(ip): """ Returns the MAC address for the first interface that matches the given IP Returns None if not found """ for i in netifaces.interfaces(): addrs = netifaces.ifaddresses(i) try: if_mac = addrs[netifaces.AF_LINK][0]['addr'] if_ip = addrs[netifaces.AF_INET][0]['addr'] except Inde...
5,332,762
def main(): """Console script for {{cookiecutter.project_slug}}.""" args = _parse_args()
5,332,763
def rbf_multiquadric(r, epsilon=1.0, beta=2.5): """ multiquadric """ return np.sqrt((epsilon*r)**2 + 1.0)
5,332,764
def is_valid_sudoku(board): """ Checks if an input sudoku board is valid Algorithm: For all non-empty squares on board, if value at that square is a number, check if the that value exists in that square's row, column, and minor square. If it is, return False. """ ...
5,332,765
def lab_to_nwb_dict(lab_key): """ Generate a dictionary containing all relevant lab and institution info :param lab_key: Key specifying one entry in element_lab.lab.Lab :return: dictionary with NWB parameters """ lab_info = (lab.Lab & lab_key).fetch1() return dict( institution=lab_in...
5,332,766
def test__is_not_template_or_throws__throws_when_domain_doesnt_exists(): """Test that it throws when the domain doesn't exists at all""" with patch("qsm.dom0.exists_or_throws", side_effect=lib.QsmDomainDoesntExistError, autospec=True): with pytest.raises(lib.QsmDomainDoesntExistError): dom0....
5,332,767
def length(self: Set[A]) -> int: """ Returns the length (number of elements) of the set. `size` is an alias for length. Returns: The length of the set """ return len(self)
5,332,768
def timestamp(tdigits=8): """Return a unique timestamp string for the session. useful for ensuring unique function identifiers, etc. """ return str(time.clock()).replace(".", "").replace("-", "")[: tdigits + 1]
5,332,769
def hierarchical_mutation(original_individual: Individual, strength: float, **kwargs) -> List[Optional[Individual]]: # TODO: Double Check """Choose a node in the graph_manager, choose a parameter inside the node, mutate it. Each parameter has probability: `1/len(nodes) * 1/len(parameters in that node)`. ...
5,332,770
def is_wrapped_exposed_object(obj): """ Return True if ``obj`` is a Lua (lupa) wrapper for a BaseExposedObject instance """ if not hasattr(obj, 'is_object') or not callable(obj.is_object): return False return bool(obj.is_object())
5,332,771
def no_transform(image): """Pass through the original image without transformation. Returns a tuple with None to maintain compatability with processes that evaluate the transform. """ return (image, None)
5,332,772
def build_menu(buttons, n_cols, header_buttons=None, footer_buttons=None): """Builds a menu with the given style using the provided buttons :return: list of buttons """ menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, [header_b...
5,332,773
def askAgentAndExecLocalCode(agent, method, **k): """ agent, method, dict. of the parameters (may be empty)""" setLocalCode("") if common.debug: applyMethod(agent, method, **k) else: try: applyMethod(agent, method, **k) except SystemExit: print('method', ...
5,332,774
def dbbox2result(dbboxes, labels, num_classes): """ Convert detection results to a list of numpy arrays. :param dbboxes: (Tensor): shape (n, 9) :param labels: (Tensor): shape (n, ) :param num_classes: (int), class number, including background class :return: list (ndarray): dbbox results of each...
5,332,775
def SSderivative(ds): """ Given a time-step ds, and an single input time history u, this SS model returns the output y=[u,du/ds], where du/dt is computed with second order accuracy. """ A = np.array([[0]]) Bm1 = np.array([0.5 / ds]) B0 = np.array([[-2 / ds]]) B1 = np.array([[1.5 / d...
5,332,776
def sigterm_handler(_signo, _stack_frame): """Clean exit on SIGTERM signal (when systemd stops the process)""" sys.exit(0)
5,332,777
def clean_post(value): """Remove unwanted elements in post content""" doc = lxml.html.fragment_fromstring(value) doc.tag = 'div' # replaces <li> doc.attrib.clear() # remove comment owner info for e in doc.xpath('//div[@class="weblog_keywords"]'): e.drop_tree() return lxml.html.tost...
5,332,778
def test_get_headers(test_app): """ Checks if the default header values are correct and if it updates on params """ r = Requester('url', 'token') res = r._get_headers() assert res == { 'Authorization': 'Bearer token' } res_with_extra = r._get_headers({ 'Content-Type': 'application/json...
5,332,779
def get_houdini_version(as_string=True): """ Returns version of the executed Houdini :param as_string: bool, Whether to return the stiring version or not :return: variant, int or str """ if as_string: return hou.applicationVersionString() else: return hou.applicationVersion(...
5,332,780
def check_port_open(port: int) -> bool: """ Проверка на свободный порт port Является частью логики port_validation """ try: sock = socket.socket() sock.bind(("", port)) sock.close() print(f"Порт {port} свободен") return True except OSError: print(...
5,332,781
def view_all_recommended(): """View all recommended bets""" main_cur.execute("SELECT match_datetime, match_analysis.country_league_name, home_team_name, " "away_team_name, rec_bet, percentage_rec " "FROM match_analysis where bet_result isnull AND rec_bet <> 'Avoid...
5,332,782
def convert_date_to_tick_tick_format(datetime_obj, tz: str): """ Parses ISO 8601 Format to Tick Tick Date Format It first converts the datetime object to UTC time based off the passed time zone, and then returns a string with the TickTick required date format. !!! info Required Format ISO ...
5,332,783
def check_path(path: str): """Checks if a path exists and creates it if it doesn't Parameters ---------- path The string of the path to check/create """ if not os.path.exists(path): os.makedirs(path)
5,332,784
def measurement(resp, p): """model measurement effects in the filters by translating the response at each location and stimulus (first 3 axes of resp) toward the filterwise mean (4th axis) according to proportion p. p=1 means that all filters reduce to their respective means; p=0 does nothing; p<0 is po...
5,332,785
def irpf(salario,base=12.5,prorrateo=0): """Entra el salario y la base, opcionalmente un parametro para prorratear Si no se da el valor de la bas3e por defecto es 12.5""" if type(salario)==float and type(base)==float: if prorrateo==True: return (salario*(1+2/12))*(base/100) elif ...
5,332,786
def get2p3dSlaterCondonUop(Fdd=(9, 0, 8, 0, 6), Fpp=(20, 0, 8), Fpd=(10, 0, 8), Gpd=(0, 3, 0, 2)): """ Return a 2p-3d U operator containing a sum of different Slater-Condon proccesses. Parameters ---------- Fdd : tuple Fpp : tuple Fpd : tuple Gpd : tuple """ # Calculate F_d...
5,332,787
def read_meta_fs(filename: AnyStr): """ Read meta data from disk. """ settings.Path(filename).mkdir(parents=True, exist_ok=True) filepath = settings.pj(filename, "meta.pkl") with open(filepath, "rb") as fh: return pickle.load(fh)
5,332,788
def compile(model, ptr, vtr, num_y_per_branch=1): """Create a list with ground truth, loss functions and loss weights. """ yholder_tr = [] losses = [] loss_weights = [] num_blocks = int(len(model.output) / (num_y_per_branch + 1)) printcn(OKBLUE, 'Compiling model with %d outputs ...
5,332,789
def strip_clean(input_text): """Strip out undesired tags. This removes tags like <script>, but leaves characters like & unescaped. The goal is to store the raw text in the database with the XSS nastiness. By doing this, the content in the database is raw and Django can continue to assume that it's ...
5,332,790
def main(configs, project, bucket_path): """Loads metric config files and runs each metric.""" if not project: raise ValueError('project', project) if not bucket_path: raise ValueError('bucket_path', bucket_path) if 'VELODROME_INFLUXDB_CONFIG' in os.environ: influx = influxdb.Pu...
5,332,791
def setup(mu=MU, sigma=SIGMA, beta=BETA, tau=TAU, draw_probability=DRAW_PROBABILITY, backend=None, env=None): """Setups the global environment. :param env: the specific :class:`TrueSkill` object to be the global environment. It is optional. >>> Rating() trueskill.Rating(mu=2...
5,332,792
def _bytepad(x, length): """Zero pad byte string as defined in NIST SP 800-185""" to_pad = _left_encode(length) + x # Note: this implementation works with byte aligned strings, # hence no additional bit padding is needed at this point. npad = (length - len(to_pad) % length) % length return to...
5,332,793
def print_profile(command, max_ratio=1.0, filter_text=None): """ 集計します。 :param u command: 実行するコマンド ex. test() :param float max_ratio: 表示する上限 < 1.0 :rtype: None """ # 変数を初期化します。 logger = getLogger() prof = cProfile.Profile() # 速度を計測します。 prof = prof.run...
5,332,794
def str2bool(val): """enable default constant true arguments""" # https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse if isinstance(val, bool): return val elif val.lower() == 'true': return True elif val.lower() == 'false': return False else:...
5,332,795
def get_scalefactor(metadata): """Add scaling factors to the metadata dictionary :param metadata: dictionary with CZI or OME-TIFF metadata :type metadata: dict :return: dictionary with additional keys for scling factors :rtype: dict """ # set default scale factore to 1 scalefactors = {...
5,332,796
def alignmentEntropy(align, statistic='absolute', removeGaps=False, k=1, logFunc=np.log): """Calculates the entropy in bits of each site (or kmer) in a sequence alignment. Also can compute: - "uniqueness" which I define to be the fraction of unique sequences - "uniquenum" which is the number of...
5,332,797
def NodeToString(xml_node): """Returns an XML string. Args: xml_node: xml.dom.Node object Returns: String containing XML """ return xml_node.toxml()
5,332,798
def difference(data, interval): """ difference dataset parameters: data: dataset to be differenced interval: the interval between the two elements to be differenced. return: dataset: with the length = len(data) - interval """ return [data[i] - data[i ...
5,332,799