content
stringlengths
22
815k
id
int64
0
4.91M
def UnlinkKongregate(request, callback, customData = None, extraHeaders = None): """ Unlinks the related Kongregate identifier from the user's PlayFab account https://docs.microsoft.com/rest/api/playfab/client/account-management/unlinkkongregate """ if not PlayFabSettings._internalSettings.ClientSes...
5,338,200
def validate_options(options): """Validate supplied options to ensure basic idea is ok. This doesnt perform a fine-grained check, just whether or not the arguments seem consistent or complete so we can fail fast. """ for configurator in CONFIGURATOR_LIST: configurator.validate_options(options)
5,338,201
def menu(request): """ A View to return the menu.html where all menu images are returned in a carousel. """ menus = MenuImages.objects.all() context = { 'menus': menus } return render(request, 'menu/menu.html', context)
5,338,202
def wav_process(PATH, i): """ 音频处理,在路径下读取指定序号的文件进行处理 Args: PATH (str): 音频文件路径 i (int): 指定序号 Returns: float: 计算得到的音源角度(单位:°) """ # 读取数据 wav, sr = read_wav(PATH, i + 1) # 进行降噪 wav_rn = reduce_noise(wav) # 计算角度 angle_list = estimate_angle(wav_rn, sr) ...
5,338,203
def extract_vuln_id(input_string): """ Function to extract a vulnerability ID from a message """ if 'fp' in input_string.lower(): wordlist = input_string.split() vuln_id = wordlist[-1] return vuln_id else: return None
5,338,204
def britannica_search(text): """ Search on Britannica (https://www.britannica.com) Parameters ----------- text:- The query which you want to search about (str) """ britannica=f"https://www.britannica.com/search?query={text}" open(britannica)
5,338,205
def _test(): """Self-test.""" print("Self-test for the Package modul") import random apt_pkg.init() progress = apt.progress.text.OpProgress() cache = apt.Cache(progress) pkg = cache["apt-utils"] print("Name: %s " % pkg.name) print("ID: %s " % pkg.id) print("Priority (Candidate): ...
5,338,206
def ensure_paths_for_args(args): """ Ensure all arguments with paths are absolute & have simplification removed Just apply os.path.abspath & os.path.expanduser :param args: the arguments given from argparse :returns: an updated args """ args.seqs_of_interest = os.path.abspath( os....
5,338,207
def compare_images(img1, img2): """Expects strings of the locations of two images. Will return an integer representing their difference""" with Image.open(img1) as img1, Image.open(img2) as img2: # Calculate a difference image that is the difference between the two images. diff = ImageChops.diff...
5,338,208
def bytes_to_nodes(buf): """ Return a list of ReadNodes corresponding to the bytes in buf. @param bytes buf: a bytes object @rtype: list[ReadNode] >>> bytes_to_nodes(bytes([0, 1, 0, 2])) [ReadNode(0, 1, 0, 2)] """ lst = [] for i in range(0, len(buf), 4): l_type = buf...
5,338,209
def require_captcha(function, *args, **kwargs): """Return a decorator for methods that require captchas.""" raise_captcha_exception = kwargs.pop('raise_captcha_exception', False) captcha_id = None # Get a handle to the reddit session if hasattr(args[0], 'reddit_session'): reddit_sess...
5,338,210
def list_unnecessary_loads(app_label=None): """ Scan the project directory tree for template files and process each and every one of them. :app_label: String; app label supplied by the user :returns: None (outputs to the console) """ if app_label: app = get_app(app_label) else:...
5,338,211
async def test_subscribe_idempotence( event_log: EventLog, first_topic, second_topic ) -> None: """Check that multiple subscriptions does not result in multiple notifications.""" called = asyncio.Event() async def call(low: Timestamp, high: Timestamp, events: List[Event]) -> None: nonlocal call...
5,338,212
def _element( html_element: str, html_class: str, value: Any, is_visible: bool, **kwargs, ) -> dict: """ Template to return container with information for a <td></td> or <th></th> element. """ if "display_value" not in kwargs: kwargs["display_value"] = value return { ...
5,338,213
def create_app(test_config=None): """ This method creates a flask app object with a given configuration. Args: test_config (dict): Defaults to None. Returns: app (Flask): Flask app object. """ app = Flask(__name__) Bootstrap(app) # check environment variables to see...
5,338,214
def lovasz_hinge_loss(pred, target, crop_masks, activation='relu', map2inf=False): """ Binary Lovasz hinge loss pred: [P] Variable, logits at each prediction (between -\infty and +\infty) target: [P] Tensor, binary ground truth labels (0 or 1) """ losses = [] for m, p, t in zip(crop_mask...
5,338,215
def get_gene_summary(gene): """Gets gene summary from a model's gene.""" return { gene.id: { "name": gene.name, "is_functional": gene.functional, "reactions": [{rxn.id: rxn.name} for rxn in gene.reactions], "annotation": gene.annotation, "notes...
5,338,216
def prompt_choice_list(msg, a_list, default=1, help_string=None): """Prompt user to select from a list of possible choices. :param msg:A message displayed to the user before the choice list :type msg: str :param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc') "typ...
5,338,217
def random_permutation_matrix(size): """Random permutation matrix. Parameters ---------- size : int The dimension of the random permutation matrix. Returns ------- random_permutation : array, shape (size, size) An identity matrix with its rows random shuffled. """ ...
5,338,218
def test_pyramid_handles_none_and_empty_inputs(): """Test that pyramid handles none and empty inputs.""" assert watch_pyramid_from_the_side(None) is None assert watch_pyramid_from_above(None) is None assert count_visible_characters_of_the_pyramid(None) == -1 assert count_all_characters_of_the_pyrami...
5,338,219
def matched(captured: Optional[Capture], groups_count: int) -> MatchedType: """ Construct the matched strings transversing\ given a captured structure The passed Capture has the last captured char\ and so the sequence is transversed in reverse Sub-matches are put in their group index Repe...
5,338,220
def tle_fmt_float(num,width=10): """ Return a left-aligned signed float string, with no leading zero left of the decimal """ digits = (width-2) ret = "{:<.{DIGITS}f}".format(num,DIGITS=digits) if ret.startswith("0."): return " " + ret[1:] if ret.startswith("-0."): return "-" + ret[2:...
5,338,221
def pack(name=None, prefix=None, output=None, format='infer', arcroot='', dest_prefix=None, verbose=False, force=False, compress_level=4, n_threads=1, zip_symlinks=False, zip_64=True, filters=None, ignore_editable_packages=False): """Package an existing conda environment into an archive f...
5,338,222
def rasterize(points): """ Return (array, no_data_value) tuple. Rasterize the indices of the points in an array at the highest quadtree resolution. Note that points of larger squares in the quadtree also just occupy one cell in the resulting array, the rest of the cells get the no_data_value. "...
5,338,223
def parse_aedge_layout_attrs(aedge, translation=None): """ parse grpahviz splineType """ if translation is None: translation = np.array([0, 0]) edge_attrs = {} apos = aedge.attr['pos'] # logger.info('apos = %r' % (apos,)) end_pt = None start_pt = None # if '-' in apos: ...
5,338,224
def test_decrypt_v2_good_commitment(): """Tests forwards compatibility with message serialization format v2.""" client = aws_encryption_sdk.EncryptionSDKClient() provider = StaticRawMasterKeyProvider( wrapping_algorithm=WrappingAlgorithm.AES_256_GCM_IV12_TAG16_NO_PADDING, encryption_key_type...
5,338,225
def load_class_by_path(taskpath): """ Given a taskpath, returns the main task class. """ return getattr(importlib.import_module(re.sub(r"\.[^.]+$", "", taskpath)), re.sub(r"^.*\.", "", taskpath))
5,338,226
def run_http_parser_req(req: bytes): """Run the stream.HTTPParser on the specified request.""" parser = HTTPParser() parser.process(req)
5,338,227
def test_build_models(name, build_model, params): """ Smoke test: ensure we can build the each model with nothing crashing. """ model = build_model(params["default"]) assert type(model) is StratifiedModel
5,338,228
def test_atomic_g_month_day_enumeration_3_nistxml_sv_iv_atomic_g_month_day_enumeration_4_5(mode, save_output, output_format): """ Type atomic/gMonthDay is restricted by facet enumeration. """ assert_bindings( schema="nistData/atomic/gMonthDay/Schema+Instance/NISTSchema-SV-IV-atomic-gMonthDay-enu...
5,338,229
def simplex_edge_tensors(dimensions, # type: int centers_in, # type: List[List[int]] centers_out, # type: List[List[int]] surrounds_in, # type: List[List[int]] surrounds_out, # type: List[List[int]] ...
5,338,230
def do_token_submit_password(sc, args): """ Submit this token to set or update your password. """ json_data = {'password': args.password} _token_submit(sc, args, json_data)
5,338,231
def hashtoaddress(PARAMETER): """ Converts a 160-bit hash to an address. [PARAMETER] is required and should be an address hash. """ d = urllib2.urlopen(blockexplorer('hashtoaddress') + '/' + str(PARAMETER)) return d.read()
5,338,232
def marks_plot(ppg, marks, title='PPG Signal with Marks', label_ppg='PPG Signal', label_marks='Marks', y_axis='Amplitude', x_axis=None, figure_path=None): """ Plots PPG signals with marks. Parameters ---------- ppg : pandas.Series or ndarray The PPG signal. ...
5,338,233
def get_all_objects(line: str, frame: types.FrameType) -> ObjectsInfo: """Given a (partial) line of code and a frame, obtains a dict containing all the relevant information about objects found on that line so that they can be formatted as part of the answer to "where()" or they can be used during the an...
5,338,234
def magenta(msg): """Return colorized <msg> in magenta""" return __fore(msg, 'magenta')
5,338,235
def request_latest_news(): """ This Method queries the last item of the database and convert it to a string. :return: A String with the last item of the database """ article = News.query.order_by(News.id.desc()).first() return format_latest_article(article, request.content_type)
5,338,236
def test_values_for_tag(mock_s3, mock_get_url): """ Args: mock_s3: mock_get_url: """ mock_s3.return_value = _get_mock_s3() mock_get_url.return_value = "s3://bucket/grid.zinc" with get_provider("shaystack.providers.url", {}) as provider: result = provider.values_for_tag("c...
5,338,237
def is_vulgar(words, sentence): """Checks if a given line has any of the bad words from the bad words list.""" for word in words: if word in sentence: return 1 return 0
5,338,238
def edges_cross(graph, nodes1, nodes2): """ Finds edges between two sets of disjoint nodes. Running time is O(len(nodes1) * len(nodes2)) Args: graph (nx.Graph): an undirected graph nodes1 (set): set of nodes disjoint from `nodes2` nodes2 (set): set of nodes disjoint from `nodes1...
5,338,239
def basket_view(func): """ Returns rendered page for basket """ @jinja2_view('basket.html', template_lookup=[TEMPLATES_DIR]) def _basket_view_call(*args, **kwargs): func(*args, **kwargs) return {'col_mapping': COLUMN_MAPPING, 'product_list': _format_products_for_web(get_basket_products())} ...
5,338,240
def py2to3(target_path, interpreter_command_name="python", is_transform=False, is_del_bak=False, is_html_diff=False, is_check_requirements=False): """ The main entrance of the 2to3 function provides a series of parameter entrances. The main functions ar...
5,338,241
def _norm_path(path): """ Decorator function intended for using it to normalize a the output of a path retrieval function. Useful for fixing the slash/backslash windows cases. """ def normalize_path(*args): return os.path.normpath(path(*args)) return normalize_path
5,338,242
def solve(puzzle_class, output_stream, settings): """Find and record all solutions to a puzzle. Report on `output_stream`.""" start = datetime.now() puzzle = puzzle_class(settings.start_position) solver = puzzler.exact_cover_modules[settings.algorithm].ExactCover( puzzle.matrix) try: ...
5,338,243
def _get_hash_aliases(name): """ internal helper used by :func:`lookup_hash` -- normalize arbitrary hash name to hashlib format. if name not recognized, returns dummy record and issues a warning. :arg name: unnormalized name :returns: tuple with 2+ elements: ``(hashlib_name, ia...
5,338,244
def dirac_2d_v_and_h(direction, G_row, vec_len_row, num_vec_row, G_col, vec_len_col, num_vec_col, a, K, noise_level, max_ini, stop_cri): """ used to run the reconstructions along horizontal and vertical directions in parallel. """ if direction == 0: # row recon...
5,338,245
def Matrix(*args, **kwargs): """*Funktion zur Erzeugung von Matrizen mit beliebiger Dimension""" h = kwargs.get("h") if h in (1, 2, 3): matrix_hilfe(h) return elif isinstance(h, (Integer, int)): matrix_hilfe(1) return Vektor = i...
5,338,246
def afw_word_acceptance(afw: dict, word: list) -> bool: """ Checks if a **word** is accepted by input AFW, returning True/False. The word w is accepted by a AFW if exists at least an accepting run on w. A run for AFWs is a tree and an alternating automaton can have multiple runs on a given inpu...
5,338,247
def get_following(): """ endpoint: /release/following method: GET param: "[header: Authorization] Token": str - Token received from firebase response_type: array response: id: 1 created: 123456789 vol: 1 chapter: 1 title: Chapter titles url: /chapter/1 ...
5,338,248
def matchNoSpaces(value): """Match strings with no spaces.""" if re.search('\s', value): return False return True
5,338,249
def test_invalid_driver(): """ Test invalid driver. """ code = 'Tiff' with pytest.raises(ValueError, match = '.*driver.*') as info: results = drivers.validate(code)
5,338,250
def test_dirac(): """ Feature: Test dirac initializer. Description: Initialize input tensor with the Dirac delta function. Expectation: The Tensor is correctly initialized. """ tensor3_1 = initializer(Dirac(groups=1), [6, 2, 3], mindspore.float32) tensor3_2 = initializer(Dirac(groups=2), [6,...
5,338,251
def collect_inline_comments(list_of_strings,begin_token=None,end_token=None): """Reads a list of strings and returns all of the inline comments in a list. Output form is ['comment',line_number,string_location] returns None if there are none or tokens are set to None""" if begin_token in [None] and end_toke...
5,338,252
def get_df_ads(): """ """ #| - get_df_ads # ##################################################### # import pickle; import os path_i = os.path.join( os.environ["PROJ_irox_oer"], "dft_workflow/job_analysis/collect_collate_dft_data", "out_data/df_ads.pickle") # with op...
5,338,253
def is_categorical_dtype(arr_or_dtype: List[int]): """ usage.seaborn: 1 """ ...
5,338,254
def cli_list(apic, args): """Implement CLI command `list`. """ # pylint: disable=unused-argument instances = apic.get_instances() if instances: print('\n'.join(apic.get_instances())) return 0
5,338,255
def is_symmetric(a: np.array): """ Check whether the matrix is symmetric :param a: :return: """ tol = 1e-10 return (np.abs(a - a.T) <= tol).all()
5,338,256
def get_number(line, position): """Searches for the end of a number. Args: line (str): The line in which the number was found. position (int): The starting position of the number. Returns: str: The number found. int: The position after the number found. """ word = ...
5,338,257
def load(f: TextIO) -> Config: """Load a configuration from a file-like object f""" config = yaml.safe_load(f) if isinstance(config["diag_table"], dict): config["diag_table"] = DiagTable.from_dict(config["diag_table"]) return config
5,338,258
def levelize_smooth_or_improve_candidates(to_levelize, max_levels): """Turn parameter in to a list per level. Helper function to preprocess the smooth and improve_candidates parameters passed to smoothed_aggregation_solver and rootnode_solver. Parameters ---------- to_levelize : {string, tuple...
5,338,259
def get_max_num_context_features(model_config): """Returns maximum number of context features from a given config. Args: model_config: A model config file. Returns: An integer specifying the max number of context features if the model config contains context_config, None otherwise """ meta_ar...
5,338,260
def hashname(name, secsalt): """Obtain a sha256 hash from a name.""" m = hashlib.sha256() m.update((name + secsalt).encode("utf-8")) return m.hexdigest()
5,338,261
def test_combinations3_task( infiles, outfile, prefices, subpath, subdir): """ Test combinations with k-tuple = 3 """ with open(outfile, "w") as outf: outf.write(prefices + ",")
5,338,262
def company_detail(request, stock_quote: int) -> HttpResponse: """ Return a view to Company details """ try: company = Company.objects.get(quote=str(stock_quote)) # TODO(me): Implement company detail view logic except Company.DoesNotExist: raise Http404("Company with releated quote d...
5,338,263
def parse_encoding_header(header): """ Break up the `HTTP_ACCEPT_ENCODING` header into a dict of the form, {'encoding-name':qvalue}. """ encodings = {'identity':1.0} for encoding in header.split(","): if(encoding.find(";") > -1): encoding, qvalue = encoding.split(";") ...
5,338,264
def _plot_results(novelty_dict, narr_predictor_names, test_index, top_output_dir_name): """Plots results of novelty detection. :param novelty_dict: Dictionary created by `novelty_detection.do_novelty_detection`. :param narr_predictor_names: length-C list of predictor names. :p...
5,338,265
def test_files(): """Test a shellfunction that specifies positional CLI arguments that are interpolated by the ``kwargs``.""" content_a = 'content_a' content_b = 'content_b' files = { 'file_a': SinglefileData(io.StringIO(content_a)), 'file_b': SinglefileData(io.StringIO(content_b)), ...
5,338,266
def opf_consfcn(x, om, Ybus, Yf, Yt, ppopt, il=None, *args): """Evaluates nonlinear constraints and their Jacobian for OPF. Constraint evaluation function for AC optimal power flow, suitable for use with L{pips}. Computes constraint vectors and their gradients. @param x: optimization vector @param...
5,338,267
def iou3d_kernel(gt_boxes, pred_boxes): """ Core iou3d computation (with cuda) Args: gt_boxes: [N, 7] (x, y, z, w, l, h, rot) in Lidar coordinates pred_boxes: [M, 7] Returns: iou3d: [N, M] """ intersection_2d = rotate_iou_gpu_eval(gt_boxes[:, [0, 1, 3, 4, 6]], pred_boxe...
5,338,268
def get_final_metrics(raw_metrics, summarized=False): """ Calculates final metrics from all categories. :param summarized: True if the result should contain only final metrics (precision recall, f1 and f0.5) False if the result should contain all the per category metrics too. :param raw_metrics: A d...
5,338,269
def get_health_feed(): """ Parse BBC news health feed and remove articles not related to COVID-19. """ feed = parse("http://feeds.bbci.co.uk/news/health/rss.xml") # log parsed feed for debugging purposes logger.debug(pprint(feed.entries)) logger.debug(f"Feed items before removal: {len(feed.e...
5,338,270
def get_data_meta_path(either_file_path: str) -> tuple: """get either a meta o rr binary file path and return both as a tuple Arguments: either_file_path {str} -- path of a meta/binary file Returns: [type] -- (binary_path, meta_path) """ file_stripped = '.'.join(either_file_path....
5,338,271
def group(name): """ Allow to create a group with a default click context and a class for Click's ``didyoueamn`` without having to repeat it for every group. """ return click.group( name=name, context_settings=CLICK_CONTEXT_SETTINGS, cls=AliasedGroup)
5,338,272
def get_files(target_files, config): """Retrieve files associated with the potential inputs. """ out = [] find_fn = _find_file(config) for fname in target_files.keys(): remote_fname = find_fn(fname) if remote_fname: out.append(remote_fname) return out
5,338,273
def test_version_type_yyyyw(): """ Test yyyyw verison type """ version_type = version_recommend.VersionTypeYyyyW() maintain_version = version_type.maintain_version(YYYY_W_VERSION_LIST, YYYY_W_VERSION_LIST[2], 0) assert maintain_version == "2020.3" latest_version = version_type.lates...
5,338,274
def cmd(func, *args, **kwargs): """Takes a function followed by its arguments""" def command(*a, **ka): return func(*args, **kwargs) return command
5,338,275
def flow_accumulation(receiver_nodes, baselevel_nodes, node_cell_area=1.0, runoff_rate=1.0, boundary_nodes=None): """Calculate drainage area and (steady) discharge. Calculates and returns the drainage area and (steady) discharge at each node, along with a downstream-to-upstream ordere...
5,338,276
def extract_ids(response_content): """Given a result's content of a research, returns a list of all ids. This method is meant to work with PubMed""" ids = str(response_content).split("<Id>") ids_str = "".join(ids) ids = ids_str.split("</Id>") ids.remove(ids[0]) ids.remove(ids[len(ids) - 1]) ...
5,338,277
def gatorosc(candles: np.ndarray, sequential=False) -> GATOR: """ Gator Oscillator by Bill M. Williams :param candles: np.ndarray :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] jaw = sh...
5,338,278
def program_item(prog_hash): """ GET,DELETE /programs/<prog_hash>: query programs :prog_hash: program checksum/identifier :returns: flask response """ if request.method == 'GET': with client.client_access() as c: prog = c.user_programs.get(prog_hash) return respond_js...
5,338,279
def lambda_handler(event, context): """ Federate Token Exchange Lambda Function """ if not "body" in event: return helper.build_response( {"message": "You do not have permission to access this resource."}, 403 ) input_json = dict() input_json = json.loads(event["bod...
5,338,280
def find_domain_field(fields: List[str]): """Find and return domain field value.""" field_index = 0 for field in fields: if field == "query:": field_value = fields[field_index + 1] return field_value field_index += 1 return None
5,338,281
def placeValueOf(num: int, place: int) -> int: """ Get the value on the place specified. :param num: The num :param place: The place. 1 for unit place, 10 for tens place, 100 for hundreds place. :return: The value digit. """ return lastDigitOf(num // place)
5,338,282
def prepare_polygon_coords_for_bokeh(countries): """Prepares the country polygons for plotting with Bokeh. To plot series of polygons, Bokeh needs two lists of lists (one for x coordinates, and another for y coordinates). Each element in the outer list represents a single polygon, and each elemen...
5,338,283
def get_incident_ids_as_options(incidents): """ Collect the campaign incidents ids form the context and return them as options for MultiSelect field :type incidents: ``list`` :param incidents: the campaign incidents to collect ids from :rtype: ``dict`` :return: dict with th...
5,338,284
def get_result(dir_path: str) -> List[float]: """試合のログ(csv)から勝敗データを抽出する Args: file_path (str): 抽出したい試合のログが格納されているパス Returns: List[float]: 勝率データ """ files = glob.glob(dir_path + "*.csv") result = [] for file in files: csv_file = open(file, "r") csv_data = c...
5,338,285
def get_internal_energies( compounds: dict, qrrho: bool = True, temperature: float = 298.15 ): """Obtain internal energies for compounds at a given temperature. Parameters ---------- compounds : dict-like A descriptor of the compounds. Mostly likely, this comes from a parsed input f...
5,338,286
def load_folder(folder: str) -> Tuple[Dict[str, Iterable[List[str]]], Dict[str, Any]]: """ Loads data from the folder output using neurips_crawler output/data_<year>/papers_data.jsons output/data_<year>/pdfs/<files> where - <year> is a 4 digits year associated to the year of the Neurips confe...
5,338,287
def get_local_info(hass): """Get HA's local location config.""" latitude = hass.config.latitude longitude = hass.config.longitude timezone = str(hass.config.time_zone) elevation = hass.config.elevation return latitude, longitude, timezone, elevation
5,338,288
def if_present_phrase(src_str_tokens, phrase_str_tokens): """ :param src_str_tokens: a list of strings (words) of source text :param phrase_str_tokens: a list of strings (words) of a phrase :return: """ match_pos_idx = -1 for src_start_idx in range(len(src_str_tokens) - len(phrase_str_token...
5,338,289
def fit_2D_xanes_non_iter(img_xanes, eng, spectrum_ref, error_thresh=0.1): """ Solve equation of Ax=b, where: Inputs: ---------- A: reference spectrum (2-colume array: xray_energy vs. absorption_spectrum) X: fitted coefficient of each ref spectrum b: experimental 2D XANES data Outputs...
5,338,290
def cli(env, crt, csr, icc, key, notes): """Add and upload SSL certificate details.""" template = { 'intermediateCertificate': '', 'certificateSigningRequest': '', 'notes': notes, } with open(crt, encoding="utf-8") as file_crt: template['certificate'] = file_crt.read() ...
5,338,291
def plot_sse_comparison(clustering_data, max_n): """ Plots a comparison of homogeneity, completeness, or v-measure. This plot is very specific to present the results in the paper in a clean way. Please adapt for further use. Clustering_alg is a list of dicts of which each dict contains information on: ...
5,338,292
def get_cmap(n_fg): """Generate a color map for visualizing foreground objects Args: n_fg (int): Number of foreground objects Returns: cmaps (numpy.ndarray): Colormap """ cmap = cm.get_cmap('Set1') cmaps = [] for i in range(n_fg): cmaps.append(np.asarray(cmap(i))[:3]) cmaps = n...
5,338,293
def GetBasinOutlines(DataDirectory, basins_fname): """ This function takes in the raster of basins and gets a dict of basin polygons, where the key is the basin key and the value is a shapely polygon of the basin. IMPORTANT: In this case the "basin key" is usually the junction number: this function will us...
5,338,294
def get_ventilation_status(): """ Command: 0x00 0xCD """ status_data = {"IntakeFanActive": {0: False, 1: True}} packet = create_packet([0x00, 0xCD]) data = serial_command(packet) debug_data(data) try: if data is None: warning_msg("get_ventilation_status function cou...
5,338,295
def detect_park(frame, hsv): """ Expects: HSV image of any shape + current frame Returns: TBD """ #hsv = cv2.cvtColor(frame, cfg.COLOUR_CONVERT) # convert to HSV CS # filter mask = cv2.inRange(hsv, lower_green_park, upper_green_park) # operations mask = cv2.morphologyEx(mask, cv2...
5,338,296
def normalize(mx): """Row-normalize sparse matrix""" mx = np.array(mx) rowsum = mx.sum(axis=1) r_inv = np.power(rowsum, -1.0).flatten() #use -1.0 as asym matrix r_inv[np.isinf(r_inv)] = 0. r_mat_inv = np.diag(r_inv) a = np.dot(r_mat_inv, mx) #a = np.dot(a, r_mat_inv) #skip for asym matri...
5,338,297
def th_allclose(x, y): """ Determine whether two torch tensors have same values Mimics np.allclose """ return th.sum(th.abs(x-y)) < 1e-5
5,338,298
def _check_h5_installed(strict=True): """Aux function.""" try: import h5py return h5py except ImportError: if strict is True: raise RuntimeError('For this functionality to work, the h5py ' 'library is required.') else: re...
5,338,299