content
stringlengths
22
815k
id
int64
0
4.91M
def PBH_HASH_FIELD(db): """ Show the PBH hash field configuration """ header = [ "NAME", "FIELD", "MASK", "SEQUENCE", "SYMMETRIC", ] body = [] table = db.cfgdb.get_table(pbh_hash_field_tbl_name) for key in natsort.natsorted(table): entry = tab...
5,306,000
def parseFloat(value, ret=0.0): """ Parses a value as float. This function works similar to its JavaScript-pendant, and performs checks to parse most of a string value as float. :param value: The value that should be parsed as float. :param ret: The default return value if no integer could be pa...
5,306,001
def metadataview(request, container, objectname=None): """ Return object/container/pseudofolder metadata. """ storage_url = get_endpoint(request, 'adminURL') headers = {'X-Storage-Token': get_token_id(request)} url = '{0}/{1}'.format(storage_url, container) if objectname: url = '{0}/{1}'.f...
5,306,002
def count_call_alleles(ds: Dataset, merge: bool = True) -> Dataset: """Compute per sample allele counts from genotype calls. Parameters ---------- ds : Dataset Genotype call dataset such as from `sgkit.create_genotype_call_dataset`. merge : bool, optional If True (the defaul...
5,306,003
def dense_block(x, n_filters): """ Construct a Densely Connected Residual Block x : input to the block n_filters: number of filters in convolution layer in residual block """ # Remember input tensor into residual block shortcut = x # BN-RE-Conv pre-activation form of con...
5,306,004
def error(update, context): """Log Errors caused by Updates.""" logger.warning('Update "{}" caused error "{}"\n\n'.format(update, context.error))
5,306,005
def turn_on(hass, entity_id=ENTITY_MATCH_ALL): """Turn all or specified switch on.""" hass.add_job(async_turn_on, hass, entity_id)
5,306,006
def get_fetcher(conf: MappingNode, build_dir: str, generator: ninja_syntax.Writer): """Construct and return RepoFetcher object""" return RepoFetcher(conf, build_dir, generator)
5,306,007
def config_measure_resistance(k2400, nplc=1, voltage=21.0, auto_range=True): """Configures the measurement of resistance. (Courtesy of pymeasure, see link below) args: k2400 (pyvisa.instrument): Keithley 2400 nplc (float or int): Number of power line cycles (NPLC) from 0.01 to 10 ...
5,306,008
def close_session(exception=None): """ Close the database connection. :param exception: whether an exception was thrown or not during the request """ db_session.remove()
5,306,009
def atomic_refresh_device_tracking(glue_client, refresh_df, database, table, sub_path=None, remove_aged_output_thresh_time_delta=datetime.timedelta(days=1)): """ This process atomically replaces the device tracking table by writing to a new directory and then updating the Glue Data Catalog table storage loc...
5,306,010
def text_box_search_folder(path, tag, search_term): """applies the text_box_search() method to a full folder Arguments: path [string]: absolute of relative path to folder tag [string]: element type search_term[string]: search term to find element Returns: [named tuples]: ...
5,306,011
def discard_inserted_documents(error_documents, original_documents): """Discard any documents that have already been inserted which are violating index constraints such documents will have an error code of 11000 for a DuplicateKey error from https://github.com/mongodb/mongo/blob/master/src/mongo/base/...
5,306,012
def epcr_primer_file(formattedprimers, forward_dict, reverse_dict, minampliconsize=0, maxampliconsize=0): """ Create the ePCR-compatible primer file from the dictionaries of primer combinations :param formattedprimers: Name and path of ePCR-formatted primer file to be created :param forward_dict: Dictio...
5,306,013
def include_amp_css(path: str): """ Inserts CSS content into a Django template, stripping illegal CSS rules and keywords. """ actual_path = finders.find(path) with open(actual_path, 'r', encoding='UTF-8') as f: content = f.read() content = content.replace('!important', '') return mar...
5,306,014
def get_target_no_match(mirna_sequence, length): """Given a miRNA sequence, return a random target sequence without 4 nt of contiguous pairing""" rc = rev_comp(mirna_sequence[1:8]) + 'A' off_limits = [rc[ix:ix + 4] for ix in range(5)] while True: target = generate_random_seq(length) keep...
5,306,015
def validate_package(platform_names): """ Install mssql-scripter wheel package locally. """ root_dir = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) # Local install of mssql-scripter. mssqlscripter_wheel_dir = os.listdir(utility.MSSQLSCRIPTER_DIST_DIRECTORY) current_plat...
5,306,016
def test_degrees_input(): """Make sure an error is returned if n and m aren't seperated by two""" assert_raises(ValueError, degrees2noll, 1, 2)
5,306,017
def list_folder(drive, folder_id): """ Lists contents of a GoogleDriveFile that is a folder :param drive: Drive object to use for getting folders :param folder_id: The id of the GoogleDriveFile :return: The GoogleDriveList of folders """ _q = {'q': "'{}' in parents and trashed=false".format(...
5,306,018
def media_100_fixture(): """Load media payload for item 100 and return it.""" return load_fixture("plex/media_100.xml")
5,306,019
def define_options(port: int, config_file: str) -> None: """ define Tornado global variables """ define("port", default=port) define("config_file", default=config_file)
5,306,020
def plot_good_coils(raw, t_step=1., t_window=0.2, dist_limit=0.005, show=True, verbose=None): """Plot the good coil count as a function of time.""" import matplotlib.pyplot as plt if isinstance(raw, dict): # fit_data calculated and stored to disk t = raw['fit_t'] counts ...
5,306,021
def Stop(): """stop the experiment. This method performs final book-keeping, closes the output streams and writes the final log messages indicating script completion. """ if global_options.loglevel >= 1 and global_benchmark: t = time.time() - global_starting_time global_options.std...
5,306,022
def ascii_encode_dict(data): """Encodes dict keywords to regular strings. Needed because of bug in Python 2.6 which causes fail when passing unicode keyword to _Substitute().""" ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x return dict(map(ascii_encode, pair) for pair in data.ite...
5,306,023
def test_filter_comments(): """Remove all comments from content""" content = ( "'use strict'; /* a beautiful comment */\n" "\n" "/*\n" "a long comment that can take a lot of places so\n" "we put it on several lines.\n" "*/\n" "\n" "// a data docstr...
5,306,024
def normalize_place_name(value): """Quick and dirty conversion of common verbiage around placenames""" query_value = value query_value = re.sub(r"^Place \w+:", "", query_value) query_value = re.sub(r"^Cultural Place:", "", query_value) query_value = query_value.strip() return query_value
5,306,025
def plot_calibration_curve(y_true, y_pred_prob, model_name, title, n_bins=5, normalize=False): """ Returns a matplotlib figure containing the plotted calibration plot. Args: y_true: array-like of shape (n_samples,) of true target y_pred_prob: array-like of shape (n_samples,) probabiliti...
5,306,026
def boxplot( df: DataFrame, groupby: List[str], metrics: List[str], whisker_type: PostProcessingBoxplotWhiskerType, percentiles: Optional[ Union[List[Union[int, float]], Tuple[Union[int, float], Union[int, float]]] ] = None, ) -> DataFrame: """ Calculate boxplot statistics. For e...
5,306,027
def pow_mid(p, max_denom=1024): """ Return (x,1,t) power tuple t <= x^p 1^(1-p) user wants the epigraph variable t """ assert 0 < p < 1 p = Fraction(p).limit_denominator(max_denom) return p, (p, 1-p)
5,306,028
def search_vulnerabilities_version(word_list, db_table): """ Search vulnerabilities for version number. :param word_list: the list of words searched by the user. :param db_table: the database table in which perform the search. :return: the list containing the results of the performed search. """...
5,306,029
def htons(cpu_context, func_name, func_args): """ Convert the provided 16-bit number in host byte order (little-endian) to network byte order (big-endian) """ le_port = func_args[0] port_data = struct.pack("<H", le_port) return struct.unpack(">H", port_data)[0]
5,306,030
def load_data(dataset): """Load data.""" names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph'] objects = [] for i in range(len(names)): with open("data/ind.{}.{}".format(dataset, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.append(pkl.load(f, encod...
5,306,031
def write_files(protein, pocket, pair_path, target, index): """ Writes cleaned structure files for protein, ligand, and pocket. :param protein: (Biopython Structure object) receptor protein :param pocket: (set of Biopython Residue objects) set of key binding site residues :param pair_path: (string) ...
5,306,032
def post_call_back(request, result): """get post callback function, result is the post object""" print(result.url) print(result.download_count)
5,306,033
def _split_columns(df, columns, delimiter, converter=identity): """Split column string values into tuples with the given delimiter.""" return df.update_columns( **{column: ignoring_exceptions(lambda s: tuple(converter(x) for x in s.split(delimiter)), (), (AttributeError)) for column in make_iterable(col...
5,306,034
def read_well_list(stream): """Read the well-list.""" retval = {} for line in stream: line = line.rstrip() if line.startswith("Row"): continue tokens = line.split("\t") wbc = tokens[5] retval[wbc] = { "row": tokens[0], "column": tok...
5,306,035
def bayes_compare_language(l1, l2, ngram_range=(1, 3), prior=.01, cv=None, counts_mat=None): """ Parameters ---------- l1, l2 : Iterable[str] list of strings from each language sample ngram_range : Tuple[int, int], default=(1,3) an integer describing up to what n-gram you want to co...
5,306,036
def main(range_start: float, range_end: float, range_length: int) -> None: """Integrate function using Simpson method. Range is set by user or default range is used. """ values = np.linspace(range_start, range_end, range_length) result = simps(function(values), values) max_forth_derivative = ca...
5,306,037
def find_asn(string: str): """ Returns a autonomous system number or None :param str string: String :return: int or None """ match = re.search(PATTERN_ASN, string) if match: return int(match.group(1)) return None
5,306,038
def load_solvers(path): """Load a suite of solvers.""" logger.info("loading solver suite from %s", path) return imp.load_source("borg.suite_{0}".format(uuid.uuid4().hex), path)
5,306,039
def cross_derivative(expr, dims, fd_order, deriv_order, **kwargs): """ Arbitrary-order cross derivative of a given expression. Parameters ---------- expr : expr-like Expression for which the cross derivative is produced. dims : tuple of Dimension Dimensions w.r.t. which to diffe...
5,306,040
def starting_node_random_walk(bipartite,weights_x, min_weight=100, max_dim=10 ): """ Sample random node in X (from bipartite graph X-Y) with the restriction that it does not connect to more than "max_dim" nodes in Y and that its weight is more than "min_weight" Parameters ---------- bipartite :...
5,306,041
def play_marbles(players, start_marble, limit_points): """Play marbles with number of players and limit_points.""" cur_marble = start_marble cur_points = 1 cur_player = 0 while cur_points <= limit_points: if cur_points % 23 == 0: for _ in range(7): cur_marble = cu...
5,306,042
def get_extension_name(id: str, version: str) -> str: """Returns the 'name' of a Chrome extension by finding the correct source. Args: id: An extension identifier string. version: The extension version that is used to search file paths. Returns: A string for the 'name' of a Chrome ...
5,306,043
def metered_stream(fn): """ Display a progress meter to standard out for a stream. """ def wrapped(*args, **kargs): meter = _use_and_del(kargs, 'meter', True) freq = _use_and_del(kargs, 'meter_freq', 10000) stream = fn(*args, **kargs) # Hijack the stream and keep count of the items if me...
5,306,044
def filter_data(data): """ Setup the filter in use by the listen() function. It will take the rsvp event JSON string, and return a JSON string subset of that data. :param: json string :return: json string """ try: result = json.dumps({ 'CITY': data['group']['group_city'], ...
5,306,045
def _to_distiller_modulelist(model): """Replaces all instances of torch.nn.ModuleList in a model with DistillerModuleList instances Args: model (torch.nn.Module): Model to convert """ def convert_container(container): # To maintain a similar order of registered modules compared to the o...
5,306,046
def noted_under(key: str) -> Any: """Gets a noted value from the director. Examples:: the_actor.should( See.the( Text.of_the(WELCOME_MESSAGE), ContainsTheText(noted_under("first name")) ), ) """ try: return Director().looks_up(key) ex...
5,306,047
def department_page(school_name): """ Renders the page where the user selects their department. """ school = School.query.filter(School.name == school_name).first() if school is None: return default_error, 400 return render_template('departments.html', departments=school.departments.all())
5,306,048
def download_isolated_file(h, workdir, isolate_server, namespace): """Download the isolated file with the given hash and return its contents.""" dst = os.path.join(workdir, h) if not os.path.isfile(dst): subprocess.check_call([ 'python', 'isolateserver.py', 'download', '-I', isolate_server, '-...
5,306,049
def add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params): """ Update all_data array by appending the new data. The new data contains the data from all freq bands Syntax: all_data = add_feat_data_to_array(all_data, new_data, feat_pd_names, feat_name, params) Inputs: all_...
5,306,050
def distance_matrix_dict_fixture(): """The expected distances between the example cities defined in tests/conftest.py""" return { 'euclidean': np.array([ [0, 1118, 2236], [1118, 0, 1118], [2236, 1118, 0] ]), 'manhattan': np.array([ [0, 1500...
5,306,051
def get_global_config_definition(context, config, value): """Get config definitions included with Mycroft. Arguments: context: behave test context config: config value to fetch from the file value: predefined value to fetch Returns: Patch dictionary or None. """ con...
5,306,052
def interp_sw_levels_xr(sw_xr_var): """takes swoosh data xarray Dataarray (one var) and interpolate it vertically to MERRA GCM pressure levels""" # *levels is other optional pressure levels from scipy.interpolate import interp1d from scipy.interpolate import UnivariateSpline import numpy as np ...
5,306,053
def f_create_result_folder(secondarypath): """ Perform EDMF analysis with all uploaded files and intermediate results Developed by : WANG Ze-Zhou (ETH Singapore) Contact : e0054291@u.nus.edu Date: August 04, 2021 INPUTS: ...
5,306,054
def ordinal_number(n: int): """ Returns a string representation of the ordinal number for `n` e.g., >>> ordinal_number(1) '1st' >>> ordinal_number(4) '4th' >>> ordinal_number(21) '21st' """ # from https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1...
5,306,055
def rgamma(alpha, beta, size=None): """ Random gamma variates. """ return np.random.gamma(shape=alpha, scale=1. / beta, size=size)
5,306,056
def get_metadata_from_xml_tree(tree, get_issns_from_nlm=False, get_abstracts=False, prepend_title=False, mesh_annotations=True): """Get metadata for an XML tree containing PubmedArticle elements. Documentation on the XML structure can be found at: ...
5,306,057
def aodh_client(conf): """Get an instance of aodh client""" try: ao_client = driver_module('aodh') client = ao_client.Client( conf.aodh_version, session=keystone_client.get_session(conf)) LOG.info('Aodh client created') return client except Exception: ...
5,306,058
def config_editor_command(ctx, application, blocking, process_name, clear): """Set the editor to use for record editing""" if clear is True: application = None blocking = False process_name = None if clear is not True and application is None: raise KsmCliException("Either a ...
5,306,059
def import_data(wave): """brings 2 dataframes with all the features and series with y (panelpat)""" # we predict particular wave attrition based on previous one, therefore we subtract 1 from wave number wave = str(int(wave) - 1) political = pd.read_csv(f'data/data_online_political_w{wave}.csv') pers...
5,306,060
def loadAndTransform(imageFile): """this if statement is added because there is a corrupted file in the IAM database and deleting that file everytime is very tedious""" if imageFile == "a01-117-05-02.png" or imageFile == "r06-022-03-05.png": return imageArray = cv2.imread(imageFile) ...
5,306,061
def _ensure_success(result: Any, attr: Optional[str], fail_msg: str) -> Any: """ Ensures that *status* is ``GattCommunicationStatus.SUCCESS``, otherwise raises ``BleakError``. Args: result: The result returned by a WinRT API method. attr: The name of the attribute containing the result....
5,306,062
def purge_review_teams( assignment_names: Iterable[str], students: Iterable[plug.StudentTeam], api: plug.PlatformAPI, ) -> None: """Delete all review teams associated with the given assignment names and student teams. Args: assignment_names: Names of assignments. students: An it...
5,306,063
def get_jaccard_sim(wordlist_a, wordlist_b): """Receive info for two documents and return jaccard similarity""" # Get info from documents cardinality_a = wordlist_a['cardinality'] cardinality_b = wordlist_b['cardinality'] # Bag of words bag_of_words_a = wordlist_a['bag_of_words'] bag_of_word...
5,306,064
def valid_us_phone_number(node, value): """Checks if a phone number looks like a valid US mobile number after normalization. :raise: colander.Invalid on error """ assert type(value) == str, "Phone number must be string type" normalized = normalize_us_phone_number(value) if not normalized.sta...
5,306,065
def tree_depth(t): """What is the max depth of t?""" # n.b. car is always length 1 the way trees are currently parsed subdepth = 0 for subtree in tree_cdr(t): subdepth = max(subdepth, tree_depth(subtree)) return subdepth + 1
5,306,066
def vector_angle(pairs): """ Find the angles between pairs of unit vectors. Parameters ---------- pairs : (n, 2, 3) float Unit vector pairs Returns ---------- angles : (n,) float Angles between vectors in radians """ pairs = np.asanyarray(pairs, dtype=np.float64) ...
5,306,067
def alert_warning(message): """ Shows a warning message. """ flask.flash(message, 'warning')
5,306,068
def main(): """ Create a Market Order in an Account based on the provided command-line arguments. """ parser = argparse.ArgumentParser() # # Add the command line argument to parse to the v20 config # common.config.add_argument(parser) # # Add the command line arguments req...
5,306,069
async def get_contestants(token: str, event_id: str) -> List[dict]: """Get the contestants in the event.""" try: contestants = await EventsAdapter.get_contestants(token, event_id) except ContestantsNotFoundException as e: raise e from e if not contestants or len(contestants) == 0: ...
5,306,070
def findVariantsInRange(vcfFname, chrom, start, end, strand, minFreq): """ find variants that overlap the position. varDb is a tuple of label, vcfFname return as a dict relative position -> (chrom, pos, refAllele, altAllele, list of info-dicts) special position is "label" which is the label of the varia...
5,306,071
def end_event(name, context): """Signal the end of a custom timing event Use to add arbitrary "events" anywhere in the code to isolate sources of slowness during profiling. This function terminates the given event name and immediately begins the next (as yet unnamed) event. Requires the `TimingPlug...
5,306,072
def limpieza_basica(texto, quitar_numeros=True): """Limpieza básica del texto. Esta función realiza una limpieza básica del texto de entrada, \ transforma todo el texto a letras minúsculas, quita signos de puntuación y caracteres \ especiales, remueve espacios múltiples dejando solo espacio sencillo y carac...
5,306,073
def texture(data): """ Compute the texture of data. Compute the texture of the data by comparing values with a 3x3 neighborhood (based on :cite:`Gourley2007`). NaN values in the original array have NaN textures. (Wradlib function) Parameters: ========== data : :class:`numpy:numpy.ndarra...
5,306,074
def config_locator(): """ Returns the path to the file containing your LAtools configurations. """ return pkgrs.resource_filename('latools', 'latools.cfg')
5,306,075
def resnet50_fpn_backbone(pretrain_path="", norm_layer=FrozenBatchNorm2d, # FrozenBatchNorm2d的功能与BatchNorm2d类似,但参数无法更新 trainable_layers=3, returned_layers=None, extra_blocks=None): """ 搭建resnet50_fpn——backbo...
5,306,076
def hasroyalflush(hand: list): """ Check if hand has royal flush Royal Flush is a straight flush that consists of A, 10, J, Q, K Parameters: hand (list): The poker cards Returns: bool: True if hand is a Royal Flush """ if len(hand) == 5: isroyal = False ...
5,306,077
def get_lambda_config_property(context, property_name=None): """ Extract JSON properties from the JSON encoded description. Return the value for the property, None if not found, all properties if no name given. """ aws_lambda = boto3.client('lambda') function_arn = context.invoked_function_...
5,306,078
def resolve_doi(doi): """ Takes as input a DOI and returns the internal HydroShare identifier (pid) for a resource. This method will be used to get the HydroShare pid for a resource identified by a doi for further operations using the web service API. REST URL: GET /resolveDOI/{doi} Parameter...
5,306,079
def shift_preds(preds): """Returns uniformly shift preds so minimum is at 0 to avoid underflow. Args: preds: Tensor of shape [batch_size]. """ preds_min = tf.reduce_min(preds) shift = tf.where(preds_min < 0, -preds_min, 0) return preds + shift
5,306,080
def test_multihop_receiver_on_success(vo, did_factory, root_account, core_config_mock, caches_mock, metrics_mock): """ Verify that the receiver correctly handles successful multihop jobs """ receiver_thread = threading.Thread(target=receiver, kwargs={'id_': 0, 'full_mode': True, 'all_vos': True, 'total_...
5,306,081
def get_stagein_logfile_names(): """ Get the proper names for the redirected stage-in logs. :return: stagein_stdout (string), stagein_stderr (string). """ stagein_stdout = config.Container.middleware_stagein_stdout if not stagein_stdout: stagein_stdout = 'stagein_stdout.txt' stagei...
5,306,082
def update_targets(target, original): """Weighted average update of the target network and original network Inputs: target actor(critic) and original actor(critic)""" for targetParam, orgParam in zip(target.parameters(), original.parameters()): targetParam.data.copy_((1 - TAU)*t...
5,306,083
def mylinearregression(x, y, confidence_level = 95, show_plots = False, report = False): """ function to calculate simple linear regression inputs: x,y-data pairs and a confidence level (in percent) outputs: slope = b1, intercept = b0 its confidence intervals and R (+squared) """ #Basic stat...
5,306,084
def test_file_lifecycle(m): """Tests creating, modifying and deleting a file.""" # Test local file creation. shutil.copy(resources + "/file.txt", m.test_folder_local) wait_for_idle(m) assert_exists(m, m.test_folder_dbx, "file.txt") assert_child_count(m, m.test_folder_dbx, 1) assert_synce...
5,306,085
def _check_fd_or_path(fd: Optional[int], path: Optional[Path]) -> None: """Ensure either ``fd`` or ``path`` is given. >>> _check_fd_or_path(None, None) Traceback (most recent call last): ... ValueError: Either fd or path must be given >>> _check_fd_or_path(0, Path("/")) Traceback (most rec...
5,306,086
def communicating_pairs_iter(automata, indices_to_ignore=None): """ automata is a list of automata. The function returns a list of pairs (i1, i2) such that automata[i1] and automata[i2] write and read some common message """ indices = range(len(automata)) if indices_to_ignore is not None...
5,306,087
def create_db(*args, **kwargs): """Creates database with the name. """ with app.app_context(): url = current_app.extensions['sqlalchemy'].db.engine.url if not database_exists(url): create_database(url)
5,306,088
def mode_batch_size(mode, hparams): """Returns the batch size for a given mode (train or eval). Args: mode: Either 'train' or 'eval'. hparams: Hyperparameters. Returns: Integer batch size. Raises: ValueError: If mode is not 'train' or 'eval'. """ if mode == 'train': return hparams.bat...
5,306,089
def read_cli_args() -> argparse.Namespace: """Read the command line arguments.""" parser = argparse.ArgumentParser("ceiba") parser.add_argument( '-f', "--file", required=True, type=exists, help="File with the allow users") parser.add_argument('-m', '--mongo_url', default="localhost") parser....
5,306,090
def path_with_ext(dialog, wildcards): """Append extension if necessary.""" _, ext = os.path.splitext(dialog.GetPath()) if not ext: ext = wildcards[dialog.GetFilterIndex()][1] # use first extension ext = ext[1:] # remove leading '*' if ext == '.*': ...
5,306,091
def vector_heading(p): """Returns heading angle of a 2-D vector p, in radians clockwise from the y-axis ('north').""" from math import asin theta = asin(p[0] / norm(p)) if p[1] < 0: theta = np.pi - theta if theta < 0: theta += 2. * np.pi elif theta > 2. * np.pi: theta -= 2. * np.pi retur...
5,306,092
def import_file(conn, curs, filename): """Import data to sales from target file.""" date = getdate(filename) if fileindb(conn, curs, filename): print '[IMPORT] Already imported: ', filename return print "[IMPORT]", filename, "wait ...", # read data from xmls file ws = getws(fi...
5,306,093
def find_route_energy_left(bundle_size=None, contact_plan=None, current_time=0, nodes_state=None, source=None, target=None, preferred_path=None): """ In this protocol, a vehile i selects the imediate neighbor j (i > j) that 1) has a direct conn...
5,306,094
def stock_last(offset): """ View X number of stock items """ rs = Stock.objects.all().order_by("-id")[:offset] data = [] for row in rs: data.append({ "id": row.id, "trx_no":row.tno, "name": row.cat.name, "units_balance": row.unit_bal, "total_units":row.unit_total, "unit_cost": "Kshs. {:,.2f}"...
5,306,095
def _parse_type_comment( type_comment: Optional[str], ) -> Optional[ast.expr]: """ Attempt to parse a type comment. If it is None or if it fails to parse, return None. """ if type_comment is None: return None try: # pyre-ignore[16]: the ast module stubs do not have full detai...
5,306,096
def sylpos_inword_f(sylitem): """ position of the current syllable in the current word (forward) """ return itempos_inparent_f(sylitem, "SylStructure")
5,306,097
def generate_trials(exp): """Yield trial and pulse train info.""" # Build the full experimental design constraints = Bunch(exp.p.design_constraints) all_trials, all_pulses = generate_block(constraints, exp.p) for i in range(exp.p.blocks - 1): trial_part, pulse_part = generate_block(cons...
5,306,098
def from_Haser(coma, mol_data, aper=25 * u.m): """ Calculate production rate for `GasComa` Parameters ---------- coma : `sbpy.activity.gas.GasComa` Gas coma model for ratio calculation of production rate, the production rate `Q` that the gas coma model expects should be an e...
5,306,099