content
stringlengths
22
815k
id
int64
0
4.91M
def process_scene_ard(config_file, sensor, scene_id): """ A function which runs the process of converting the specified scene to an ARD product. :param config_file: The EODataDown configuration file path. :param sensor: the string name of the sensor :param scene_id: :return: """ # Create...
5,330,100
def save_associations(resource, form, descriptors, resource_existed): """Save associations from the forms received by 'create' and 'edit' route handlers to the database.""" # first delete all the associations for this resource if it already # existed (to handle the "empty" case) if resource_existed:...
5,330,101
def game_get_state(): """The ``/game/state`` endpoint requires authentication and expects no other arguments. It can be reached at ``/game/state?secret=<API_SECRET>``. It is used to retrieve the current state of the game. The JSON response looks like:: { "state_id": int, ...
5,330,102
def new(key, mode, iv=None): """Return a `Cipher` object that can perform ARIA encryption and decryption. ARIA is a block cipher designed in 2003 by a large group of South Korean researchers. In 2004, the Korean Agency for Technology and Standards selected it as a standard cryptographic technique. ...
5,330,103
def keggapi_info(database, verbose=True, force_download=False, return_format = None, return_url = False): """KEGG REST API interface for INFO command Displays information on a given database for further info read https://www.kegg.jp/kegg/rest/keggapi.html Parameters ---------- database...
5,330,104
def round_to_thirty(str_time): """STR_TIME is a time in the format HHMM. This function rounds down to the nearest half hour.""" minutes = int(str_time[2:]) if minutes//30 == 1: rounded = "30" else: rounded = "00" return str_time[0:2] + rounded
5,330,105
def mkdir(path, reset=False): """Checks if directory exists and if not, create one. Parameters ---------- reset: erase the content of the directory if exists Returns ------- the path """ if reset and os.path.exists(path): shutil.rmtree(path) try: os.makedirs(path...
5,330,106
def write_jsonl(filepath, values): """Writes List[Dict] data to jsonlines file. Args: filepath: file to write to values: list of dictionary data to write Returns: """ with open(filepath, "w") as out_f: for val in values: out_f.write(ujson.dumps(val) + "\n") ...
5,330,107
def remove_uoms(words): """ Remove uoms in the form of e.g. 1000m 1543m3 Parameters ---------- words: list of words to process Returns ------- A list of words where possible uom have been removed """ returnWords=[] for word in words: word=word.replace('.', '', 1) ...
5,330,108
def raise_if_not_datetime_ta(candidate: Any) -> None: """Raise an exception if the given value is not a timezone aware datetime. """ if not isinstance(candidate, datetime): raise PeriodError("Given value is not strictly a datetime") if candidate.tzinfo is None: raise PeriodError('G...
5,330,109
def parse_region(reg: str) -> tuple: """ Return a pair of slices (slice1, slice2) corresponding to the region give as input in numpy slice string format If the region can't be parsed sys.exit() is called """ try: slices = str_to_slices(reg) except ValueError as ve: logging.er...
5,330,110
async def create_wall_connector_entry( hass: HomeAssistant, side_effect=None ) -> MockConfigEntry: """Create a wall connector entry in hass.""" entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "1.2.3.4"}, options={CONF_SCAN_INTERVAL: 30}, ) entry.add_to_hass(hass) ...
5,330,111
def _normalize(data): """ Normalizes the data (z-score) :param data: Data to be normalized :return: Nomralized data """ mean = np.mean(data, axis=0) sd = np.std(data, axis=0) # If Std Dev is 0 if not sd: sd = 1e-7 return (data - mean) / sd
5,330,112
def test_xml_filters_change_bars(): """Test the use a xml filter""" plot = Bar(legend_at_bottom=True, explicit_size=True, width=800, height=600) A = [60, 75, 80, 78, 83, 90] B = [92, 87, 81, 73, 68, 55] plot.add("A", A) plot.add("B", B) plot.add_xml_filter(ChangeBarsXMLFilter(...
5,330,113
def test_file_corrupt(datagram_small, tmpdir): """This tests DatagramInputFile's handling of a corrupt size header.""" dg, verify = datagram_small p = tmpdir.join('datagram.bin') filename = core.Filename.from_os_specific(str(p)) dof = core.DatagramOutputFile() dof.open(filename) dof.put_da...
5,330,114
def showResultOnImage(result, img): """ Display obtained results onto input image """ img = img[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12,12)) ax.imshow(img, aspect='equal') lines = result['recognitionResult']['lines'] # assign the 'lines' value at lv 1 for i in range(len(l...
5,330,115
def addi(registers, a, b, c): """(add immediate) stores into register C the result of adding register A and value B.""" registers[c] = registers[a] + b
5,330,116
def also_provides(context): """ add settings to control panel""" if context.readDataFile('medialog.subskins.install.txt') is None: # Not your add-ons install profile return alsoProvides(IGooglefontsSettings, IMedialogControlpanelSettingsProvider)
5,330,117
def test_transform_disabled(doctree): """ Test that no reference is inserted if transforming is disabled. """ assert not doctree.next_node(pending_xref)
5,330,118
def test_config_duplicate_daily_avg_no_int_min_seen_days(): """Test Depot not known yet. Verify that config parser only int _min_seen_days for duplicate_daily_avg dimension. """ conditions_config = [{'label': 'duplicate_mk1', 'reason': 'Duplicate IMEI detected', ...
5,330,119
def merge_target_airport_configs( weather_flight_features: pd.DataFrame, configs: pd.DataFrame, parameters: Dict[str, Any], )-> pd.DataFrame: """ This function merges actual airport configuration values to the main data frame. Multiple future configuration values are added as defined...
5,330,120
def add_macro(config: str, macros: str, params: Union[List[str], str], macro: str = "params"): """Create new params macro, infer new references in config. Look for keys in dictionaries of both macros and config that are in params, and for each param, store the existing value, replace it by a macro refe...
5,330,121
def test_2d_freq(): """ reading 2D freq domain files """ # read the text, binary, xreim, and rawbin data text_dic, text_data = simpson.read(os.path.join(DD_2D, '2d_text.spe')) bin_dic, bin_data = simpson.read(os.path.join(DD_2D, '2d.spe')) xyreim_units, xyreim_data = simpson.read( os.path.jo...
5,330,122
def chunks(chunkable, n): """ Yield successive n-sized chunks from l. """ chunk_list = [] for i in xrange(0, len(chunkable), n): chunk_list.append( chunkable[i:i+n]) return chunk_list
5,330,123
def handle_withdraw(exporter, elem, txinfo, index=0): """ withdraw nft or sell proceeds from randomearth.io """ wallet_address = txinfo.wallet_address execute_msg = util_terra._execute_msg(elem) # Check if wallet is sender (can be receiver of later transfer_nft msg) sender = elem["tx"]["value"]["ms...
5,330,124
def test_switch_config_leaf_bmc(): """Test that the `canu generate switch config` command runs and returns valid leaf-bmc config.""" leaf_bmc = "sw-leaf-bmc-001" with runner.isolated_filesystem(): with open(sls_file, "w") as f: json.dump(sls_input, f) result = runner.invoke( ...
5,330,125
def pass_generate(): """ Стартовая процедура генератора паролей. """ func = generate_pass_block param = {'min_len': 4, 'max_len': 6} return f'{func(**param)}-{func(**param)}-{func(**param)}'
5,330,126
def lineSpectrum(pos, image, data, width, scale=1, spacing=3, mode="dual"): """ Draw sepectrum bars. :param pos: (x, y) - position of spectrum bars on image :param image: PIL.Image - image to draw :param data: 1D array - sound data :param width: int - widht of spectrum on image :param scale: number - scal...
5,330,127
def _unique_arXiv(record, extra_data): """Check if the arXiv ID is unique (does not already exist in Scoap3)""" arxiv_id = get_first_arxiv(record) # search through ES to find if it exists already if arxiv_id: result = current_search_client.search( 'scoap3-records-record', ...
5,330,128
def profile(username): """ Профиль пользователя. Возможность изменить логин, пароль. В перспективе сохранить свои любимые ссылки. """ if username != current_user.nickname: return redirect(url_for('index')) types = Types.manager.get_by('', dictionary=True) return render_template('au...
5,330,129
def had_cell_edge(strmfunc, cell="north", edge="north", frac_thresh=0.1, cos_factor=False, lat_str=LAT_STR, lev_str=LEV_STR): """Latitude of poleward edge of either the NH or SH Hadley cell.""" hc_strengths = had_cells_strength(strmfunc, lat_str=lat_str, l...
5,330,130
def make_score_fn(data): """Returns a groupwise score fn to build `EstimatorSpec`.""" context_feature_columns, example_feature_columns = data.create_feature_columns() def _score_fn(context_features, group_features, mode, unused_params, unused_config): """Defines the network to score a group of documents...
5,330,131
def getSummaryHtml(): """ Gives a HTML summary of the sent emails (calls the getSummary method). It uses the shelve-file given as parameter 'logpath'. """ import cgi, cgitb cgitb.enable() #print "Content-type: text/html\n\n" f = cgi.FieldStorage() logPath = f["logpath"].value...
5,330,132
def unicode2str(obj): """ Recursively convert an object and members to str objects instead of unicode objects, if possible. This only exists because of the incoming world of unicode_literals. :param object obj: object to recurse :return: object with converted values :rtype:...
5,330,133
def test_elim_cast_same_dtype(tag): """ test_elim_cast_same_dtype """ fns = FnDict() cast = P.Cast() @fns def fp32_cast_fp32(x, y): return cast(x, y) @fns def after(x, y): return x return fns[tag]
5,330,134
def bdd_to_coco(src_path, dst_path, img_dir, include, ignore_occluded=False, time_of_day=None): """Convert BDD100K det format to MS COCO format. Parameters ---------- src_path : str The path to the BDD100K d...
5,330,135
def getRepository(): """ Determine the SVN repostiory for the cwd """ p = Ptyopen2('svn info') output, status = p.readlinesAndWait() for line in output: if len(line) > 3 and line[0:3] == 'URL': return line[5:].rstrip() raise Exception('Could not determine SVN reposi...
5,330,136
def replaceInternalLinks(text): """ Replaces internal links of the form: [[title |...|label]]trail with title concatenated with trail, when present, e.g. 's' for plural. See https://www.mediawiki.org/wiki/Help:Links#Internal_links """ # call this after removal of external links, so we need n...
5,330,137
def make_table(rows: List[List[Any]], labels: Optional[List[Any]] = None, centered: bool = False) -> str: """ :param rows: 2D list containing objects that have a single-line representation (via `str`). All rows must be of the same length. :param labels: List containing the column labels. If present, the...
5,330,138
def mock_connection( aioclient_mock: AiohttpClientMocker, host: str = HOST, port: int = PORT, ssl: bool = False, base_path: str = BASE_PATH, conn_error: bool = False, conn_upgrade_error: bool = False, ipp_error: bool = False, no_unique_id: bool = False, parse_error: bool = False,...
5,330,139
def format_value(v): """ Formats a value to be included in a string. @param v a string @return a string """ return ("'{0}'".format(v.replace("'", "\\'")) if isinstance(v, str) else "{0}".format(v))
5,330,140
def worst_solvents(delta_d, delta_p, delta_h, filter_params): """Search solvents on the basis of RED (sorted descending) with given Hansen parameters, and with a formatted string indicating filter parameters. See the function parse_filter_params for details of filter parameters string.""" results_list...
5,330,141
def log(msg, *args, dialog=False, error=False, **kwargs): """ Generate a message to the console and optionally as either a message or error dialog. The message will be formatted and dedented before being displayed, and will be prefixed with its origin. """ msg = textwrap.dedent(msg.format(*args,...
5,330,142
def write2file(filename, NPCorpsList, NPCorps, names): """将获得的lp兑换结果写入文件 每lp价格计算公式: (吉他价*数量-兑换消耗isk)/数量 需要物品的每lp价格计算公式:(吉他价*数量-兑换消耗isk-∑(依赖物品价格i*需要数量i))/数量 输出格式 军团名-物品名-isk花费-lp花费-数量-吉他收价-吉他卖价-收价折合isk-卖价折合isk-扣去购买素材后折合isk Args: filename: 文件名 NPCorpLis...
5,330,143
async def async_test_matrix_inverse(testcase: Tuple[Matrix, Any]) -> None: """ Test that checks whether the secure application of the matrix inverse returns the same result as the regular matrix inverse up to a certain margin. :param testcase: tuple of a matrix and its correct inverse """ matri...
5,330,144
def test_individual_file_convenience(): """Accessing individual file via om.read works""" data = om.read(path=persist, channel='testing', key='file1') assert_false(data == {}) data = om.read(persist, 'testing', 'NON_EXISTANT') assert_equals(data, None)
5,330,145
def build_frustum_lineset(K, l, t, r, b): """Build a open3d.geometry.LineSet to represent a frustum Args: pts_A (np.array or torch.tensor): Point set in form (Nx3) pts_B (np.array or torch.tensor): Point set in form (Nx3) idxs (list of int): marks correspondence between A[i] and B[id...
5,330,146
def _config_file_exists(): """ Checks if the configuration file exists. :return: Returns True if the configuration file exists and False otherwise. :rtype: bool """ if os.path.isfile(DEFAULT_CONFIG_FILE): return True return False
5,330,147
def postagsget(sent): """ sent: Sentence as string """ string = "" ls = pos_tag(list(sent.split())) for i in ls: string += i[1] + " " return string
5,330,148
def try_convert_to_list_of_numbers(transform_params): """ Args: transform_params: a dict mapping transform parameter names to values This function tries to convert each parameter value to a list of numbers. If that fails, then it tries to convert the value to a number. For example, if transf...
5,330,149
def from_tensorflow(graph): """ Load tensorflow graph which is a python tensorflow graph object into nnvm graph. The companion parameters will be handled automatically. Parameters ---------- graph : GraphDef object Tensorflow GraphDef Returns ------- sym : nnvm.Symbol ...
5,330,150
def isequal(q1, q2, tol=100, unitq=False): """ Test if quaternions are equal :param q1: quaternion :type q1: array_like(4) :param q2: quaternion :type q2: array_like(4) :param unitq: quaternions are unit quaternions :type unitq: bool :param tol: tolerance in units of eps :type t...
5,330,151
def init_tables(): """Init the data tables. """ if not os.path.isdir(base_config.data.table_dir): os.makedirs(base_config.data.table_dir) # if not os.path.isfile(base_config.data.file_table_path): # open(base_config.data.file_table_path, 'w', encoding='utf-8').write(f'path{sep}remark\n')...
5,330,152
def MMOE(dnn_feature_columns, num_tasks, task_types, task_names, num_experts=4, expert_dnn_units=[32,32], gate_dnn_units=[16,16], tower_dnn_units_lists=[[16,8],[16,8]], l2_reg_embedding=1e-5, l2_reg_dnn=0, seed=1024, dnn_dropout=0, dnn_activation='relu', dnn_use_bn=False): """Instantiates the ...
5,330,153
def greater(self, other): """ Equivalent to the > operator. """ return _PropOpB(self, other, numpy.greater, numpy.uint8)
5,330,154
def load_translation_data(dataset, src_lang='en', tgt_lang='vi'): """Load translation dataset Parameters ---------- dataset : str src_lang : str, default 'en' tgt_lang : str, default 'vi' Returns ------- """ common_prefix = 'IWSLT2015_{}_{}_{}_{}'.format(src_lang, tgt_lang, ...
5,330,155
def objective_function(decision_variables, root_model, mode="by_age", country=Region.UNITED_KINGDOM, config=0, calibrated_params={}): """ :param decision_variables: dictionary containing - mixing multipliers by age as a list if mode == "by_age" OR - location multipliers...
5,330,156
def kick(code, input): """ kick <user> [reason] - Kicks a user from the current channel, with a reason if supplied. """ text = input.group(2).split() if len(text) == 1: target = input.group(2) reason = False else: target = text[0] reason = ' '.join(text[1::]) if not ...
5,330,157
def check_invalid(string,*invalids,defaults=True): """Checks if input string matches an invalid value""" # Checks string against inputted invalid values for v in invalids: if string == v: return True # Checks string against default invalid values, if defaults=True if defaults ...
5,330,158
def drawline(betaset,df1_distinct,j,x_axis,y_axis,linecolor): """Draw a line between points from different beta sets that share the same ori-dest coordination""" plt.plot([df1_distinct['{}_base'.format(x_axis)][j],df1_distinct['{}_set{}'.format(x_axis,betaset)][j]], [df1_distinct['{}_base'.format(y...
5,330,159
def sse_content(response, handler, **sse_kwargs): """ Callback to collect the Server-Sent Events content of a response. Callbacks passed will receive event data. :param response: The response from the SSE request. :param handler: The handler for the SSE protocol. """ # An SS...
5,330,160
def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param client: client t...
5,330,161
def get_more_spec_pos(tokens): """Return frequencies for more specific POS""" # adverbs and preps, particles adverbs = [t for t in tokens if t.full_pos == 'ADV'] apprart = [t for t in tokens if t.full_pos == 'APPRART'] postpos = [t for t in tokens if t.full_pos == 'APPO'] circum_pos = [t fo...
5,330,162
def build_first_db(): """ Populate a small db with some example entries. """ db.drop_all() db.create_all() anonymous = Role(name = u'Anonymous', description = u'匿名用户') admin = Role(name = u'Admin', description = u'管理员') develop = Role(name = 'Develop', description = u'开发人员') test = ...
5,330,163
def reconcile_suggest_property(prefix: str = ""): """Given a search prefix, return all the type/schema properties which match the given text. This is used to auto-complete property selection for detail filters in OpenRefine.""" matches = [] for prop in model.properties: if not prop.schema.is...
5,330,164
def make_boxes(df_data, category, size_factor, x, y, height, width, pad=[1,1], main_cat=None): """Generates the coordinates for the boxes of the category""" totals = df_data[size_factor].groupby(df_data[category]).sum() box_list = totals.sort_values(ascending=False).to_frame() box_list.columns = [...
5,330,165
def hash_codeobj(code): """Return hashed version of a code object""" bytecode = code.co_code consts = code.co_consts consts = [hash_codeobj(c) if isinstance(c, types.CodeType) else c for c in consts] return joblib.hash((bytecode, consts))
5,330,166
def us_census(): """Data Source for the US census. Arguments: None Returns: pandas.DataFrame """ df = us_census_connector() return us_census_formatter(df)
5,330,167
def get_notebook_path(same_config_path, same_config_file_contents) -> str: """Returns absolute value of the pipeline path relative to current file execution""" return str(Path.joinpath(Path(same_config_path).parent, same_config_file_contents["notebook"]["path"]))
5,330,168
def get_path_from_dependency( recipe_dependency_value: str, recipe_base_folder_path: str ) -> str: """ Searches the base folder for a file, that corresponse to the dependency passed. :param recipe_dependency_value: Value of the "From:" section from a reci...
5,330,169
def about_us(): """ The about us page. """ return render_template( "basic/about_us.html", )
5,330,170
def sfb1d_atrous(lo, hi, g0, g1, mode='periodization', dim=-1, dilation=1, pad1=None, pad=None): """ 1D synthesis filter bank of an image tensor with no upsampling. Used for the stationary wavelet transform. """ C = lo.shape[1] d = dim % 4 # If g0, g1 are not tensors, make them....
5,330,171
def flatten(iterable): """Flatten an arbitrarily deep list""" # likely not used iterable = iter(iterable) while True: try: item = next(iterable) except StopIteration: break if isinstance(item, str): yield item continue try...
5,330,172
def preprocess(image, size): """ pre-process images with Opencv format""" image = np.array(image) H, W, _ = image.shape image = nd.zoom(image.astype('float32'), (size / H, size / W, 1.0), order=1) image = image - mean_pixel image = image.transpose([2, 0, 1]) image = np.expand_dims(image, ax...
5,330,173
def test_get_route_info_input(): """ Test results for various URLs """ transport_proxy = YandexTransportProxy(SERVER_HOST, SERVER_PORT) # URL is None with pytest.raises(Exception): url = None transport_proxy.get_route_info(url) # URL is Gibberish with pytest.raises(Excep...
5,330,174
def delete_notebook(notebook_id: str) -> tuple[dict, int]: """Delete an existing notebook. The user can call this operation only for their own notebooks. This operation requires the following header with a fresh access token: "Authorization: Bearer fresh_access_token" Request parameters: ...
5,330,175
def log_time(logger): """ Decorator to log the execution time of a function """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() _log_time(logger, func.__n...
5,330,176
def assert_weights(w1, w2): """Assert that two tuple-to-weight dictionaries are equal.""" assert convert_dict_of_weights(w1) == convert_dict_of_weights(w2)
5,330,177
def compute_avg_merge_candidate(catavg, v, intersection_idx): """ Given intersecting deltas in catavg and v, compute average delta one could merge into running average. If one cat is an outlier, picking that really distorts the vector we merge into running average vector. So, effectively merge usin...
5,330,178
def plot_annotations(img, bbox, labels, scores, confidence_threshold, save_fig_path='predicted_img.jpeg', show=False, save_fig=True): """ This function plots bounding boxes over image with text labels and saves the image to a particualr location. """ # Default colors and mappin...
5,330,179
def main(): """Demo of the base 64 encoding utility functions""" print("\n----------------------------------------------------") print("--Base 64 Encoding/decoding utility functions demo--") print("----------------------------------------------------") print("\n------------Encode data to base 64------------...
5,330,180
def test_get_dataframe_from_xml(): """Verify that we can gerate a dataframe from the XML elements. """ data = read_xml(get_test_data_stream("input.xml")) table = get_populated_table(data) assert len(table) == 5 assert len(table.Limit.unique()) == 2
5,330,181
def record_object(obj1): """If the object of given version is already processed, skip it.""" seen = Seen() seen.obj = obj_signature(obj1) seen.save()
5,330,182
def get_registry_image_tag(app_name: str, image_tag: str, registry: dict) -> str: """Returns the image name for a given organization, app and tag""" return f"{registry['organization']}/{app_name}:{image_tag}"
5,330,183
def save_wind_generated_waves_to_subdirectory(args): """ Copy the wave height and wave period to the outputs/ directory. Inputs: args['wave_height'][sector]: uri to "sector"'s wave height data args['wave_period'][sector]: uri to "sector"'s wave period data args['prefix']...
5,330,184
def process_file(filename): """ Handle a single .fits file, returning the count of checksum and compliance errors. """ try: checksum_errors = verify_checksums(filename) if OPTIONS.compliance: compliance_errors = verify_compliance(filename) else: comp...
5,330,185
def test_markersizes_allclose(axis): """Are the markersizes almost correct?""" err = 1e-12 markersize = 1 axis.plot([1, 2.17, 3.3, 4], [2.5, 3.25, 4.4, 5], markersize=markersize + err) pc = LinePlotChecker(axis) with pytest.raises(AssertionError): pc.assert_markersizes_equal([markersize...
5,330,186
def draw_status_bar(stdscr): """ Draw status bar """ # subwin: window shares memory with parent (no need for its repainting) n_rows_stdscr, n_cols_stdscr = stdscr.getmaxyx() y_statusbar = n_rows_stdscr - 1 window = stdscr.subwin(1, n_cols_stdscr, y_statusbar, 0) window.attron(curses.colo...
5,330,187
def numeric_summary(tensor): """Get a text summary of a numeric tensor. This summary is only available for numeric (int*, float*, complex*) and Boolean tensors. Args: tensor: (`numpy.ndarray`) the tensor value object to be summarized. Returns: The summary text as a `RichTextLines` object. If the ty...
5,330,188
def solveq(K, f, bcPrescr, bcVal=None): """ Solve static FE-equations considering boundary conditions. Parameters: K global stiffness matrix, dim(K)= nd x nd f global load vector, dim(f)= nd x 1 bcPrescr 1-dim integer array containing prescribed ...
5,330,189
def get_output_names(hf): """ get_output_names(hf) Returns a list of the output variables names in the HDF5 file. Args: hf: An open HDF5 filehandle or a string containing the HDF5 filename to use. Returns: A sorted list of the output variable names in the HDF5 file. """ ...
5,330,190
def gene_trends( adata: AnnData, model: _input_model_type, genes: Union[str, Sequence[str]], lineages: Optional[Union[str, Sequence[str]]] = None, backward: bool = False, data_key: str = "X", time_key: str = "latent_time", time_range: Optional[Union[_time_range_type, List[_time_range_typ...
5,330,191
def create_hostclass_snapshot_dict(snapshots): """ Create a dictionary of hostclass name to a list of snapshots for that hostclass :param list[Snapshot] snapshots: :return dict[str, list[Snapshot]]: """ snapshot_hostclass_dict = {} for snap in snapshots: # build a dict of hostclass+e...
5,330,192
def refund_order(id): """ List all departments """ check_admin() order = Order.query.filter_by(id=id).first() payment_id = order.payment_id try: payment = Payment.find(payment_id) except ResourceNotFound: flash("Payment Not Found", "danger") return redirect(...
5,330,193
def process_sign_in_or_up(firebase_id_token: str, **kwargs): """ Processes the sign in or sign up request. :param firebase_id_token: The firebase id token of the user. :param kwargs: if User Sign in/up: {sso_token: str, sso_provider: str} elif Store Sign up: {pos_numb...
5,330,194
def test_univariate_robust_scale(): """ A scale estimator which is robust to outliers Testing against R code [R version 3.6.0 (2019-04-26)] > library(robustbase) # All code has the default argument: "finite.corr=TRUE" > robustbase::Sn(c(0, 1)) # 0.8861018: FAILS in our impleme...
5,330,195
def get_dprime_from_regions(*regions): """Get the full normalized linkage disequilibrium (D') matrix for n regions. This is a wrapper which determines the correct normalized linkage function to call based on the number of regions. Only two-dimensional normalized linkage matrices are currently suppo...
5,330,196
def get_nav_class_state(url, request, partial=False): """ Helper function that just returns the 'active'/'inactive' link class based on the passed url. """ if partial: _url = url_for( controller=request.environ['pylons.routes_dict']['controller'], action=None, id=...
5,330,197
def needs_htcondor(test_item): """ Use a decorator before test classes or methods to only run them if the HTCondor Python bindings are installed. """ test_item = _mark_test('htcondor', test_item) try: import htcondor htcondor.Collector(os.getenv('TOIL_HTCONDOR_COLLECTOR')).query(cons...
5,330,198
def tile_image( image: Image.Image, tile_size: Tuple[int, int], overlap: int ) -> Tuple[torch.Tensor, List[Tuple[int, int]]]: """Take in an image and tile it into smaller tiles for inference. Args: image: The input image to tile. tile_size: The (width, height) of the tiles. overlap:...
5,330,199