content
stringlengths
22
815k
id
int64
0
4.91M
def reweight_distribution(original_distribution, temperature = 0.5): """ :param original_distribution: 概率值组成的一维 Numpy 数组,数据之和等于1 :param temperature: 用于定量描述输出分布的熵的因子 :return: 将加权生的分布归一化,保证数组之和为1 """ distribution = np.exp(np.log(original_distribution) / temperature) return distribution / np.s...
62,500
def test_merge_blob(): """Test the merge funtion in class DensityBlob""" densityObj.density[:20, :20, :20] = 0 centerXYZ = densityObj.header.crs2xyzCoord([10, 10, 10]) densityCutoff = 3 * densityObj.header.rmsd # Set up one green and one red blob densityObj.density[11:13, 11:13, 11:13] = 1 ...
62,501
def resnet152_dropout(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ block = functools.partial(DropoutBottleneck, dropout=args.dropout, pre_d...
62,502
def list_s3_buckets( profile=None, access_key_id=None, access_key_secret=None): """List S3 buckets.""" aws_profile = utils.get_profile(profile, access_key_id, access_key_secret) try: buckets = s3_jobs.fetch_all(aws_profile) except PermissionDenied: msg = "You don...
62,503
def test_PushoverAPI_raises_error_on_bad_receipt_cancel(PushoverAPI): """Test the cancelling of a bad receipt value.""" url_re = re.compile('https://api\.pushover\.net/1/receipts/r[a-zA-Z0-9]*/cancel\.json') responses.add_callback( responses.POST, url_re, callback=receipt_cancel_call...
62,504
def _validate_client_data(client_data, challenge, typ, valid_facets): """ Validate the client data. clientData = { "typ": string, "challenge": string, //b64 encoded challenge. "origin": string, //Facet used } """ if client_data.typ != typ: raise ValueError("Wron...
62,505
async def yolov5_weights() -> List[str]: """ Get available weights options for model. Returns: List[str] of all YOLOv5 model weights files currently available to use. """ return [Path(f).as_posix().rsplit('/', maxsplit=1)[-1].split('.')[0] for f in glob.glob("model_weights/yolov...
62,506
def load_celeba(input_size=224, num_workers=2, trainsize=10000, testsize=1000, batch_size=32, transform_type='normalize'): """Load CelebA dataset""" if transform_type == 'normalize': transform = transforms.Compose([ transforms.RandomResizedCrop(input_size), transforms.RandomHori...
62,507
def pass_if(expression, exc_type, exc_val=_const.CHAR_EMPTY): """ Raises an error of type *err_type* when *expression* is **falsy** and silently passes otherwise. Opposite of :func:`raise_if`. :param expression: An expression or value to evaluate. :param exc_type: The error to raise when *expre...
62,508
def parse_min_max_info(requirements_string): """ Get min max info from a requirements string. """ assert "MAXNUM" in requirements_string, "missing MAXNUM" assert "MINNUM" in requirements_string, "missing MINNUM" min_num_search = re.search( r"MINNUM(\d+)", requirements_string ...
62,509
def dfs_iterative(graph: Graph, strategy: DFSStrategy, roots: Iterable[Vertex]) -> Iterable[Vertex]: """Iterative depth-first search algorithm. :param graph: a graph :param strategy: a searching strategy :param roots: starting vertices :return: iterable object of visited vertices""" reached = {...
62,510
def get_fields_from_template(template): """ Get list from {item} items of template string :param template: a "template" string (a string with {item} items -- the kind that is used to mark token for str.format) :return: a list of the token items of the string, in the order they appear >>> get_fi...
62,511
def sra_ids_to_srrs(ids): """Convert SRA IDs (which is a number) to SRRs. :param id: list of SRA IDs :type id: list :return: list of SRR accessions :rtype: list """ # TODO: use cached get. Can't be used currently because dictionaries can # not be hashed. response = requests.get( ...
62,512
def make_my_v1_running_example_dataset(num_items_per_dataset = 10, num_labels_per_item=10, minimal=False, include_hard_classifier=False, include_soft_classifier=False)->SyntheticDataset: """ Four states: stronghigh = 90/10, weakhigh = 70/30, weaklow = 30/70; stronglow = 10/90 ...
62,513
def get_3d_bbox(actor_, camera_actor): """Get the 8 point coordinates of the actor in the camera view.""" # 1. get the 8 vertices of the actor box vertices = np.zeros((8, 4), dtype="float") extent = actor_.bounding_box.extent # x, y, z extension from the center vertices[0, :] = np.array([extent.x, extent.y, ...
62,514
def launch_scenario_process( db_path, scenarios_directory, scenario_id, solver, solver_executable ): """ :param db_path: :param scenarios_directory: :param scenario_id: integer, the scenario_id from the database :param solver: string, the solver name :param solver_executable: string, the sol...
62,515
def smt_curve(sig_df, window = 49, order = 1, PLOT = False): """ smoothe a noisy signal curve using multi-step savgol_filter Parameters ---------- sig_df : Pandas.Series the sigal to be smoothed window : int, optional maximum window size. The default is 49. order: int, optio...
62,516
def backpropagation(network, x, y): """ Calculate delta values of a network for array inputs x and outputs y. Return gradw and gradb of the cost function as lists of matrices for each layer. """ # Initialize lists to store gradwJ(W,b,x,y) = d(l+1)*a(l)t and gradbJ(W,b,x,y) = d(l+1) with each item in lis...
62,517
def vms_list(request): """Show the list of VMs""" liste = [] for server in Server.objects.filter(is_proxmox=True).exclude(proxmox_node_name='').all(): retour = gimme_prox_cox(server.ip_for_proxmox()).getNodeContainerIndex(server.proxmox_node_name) vm_list = [] vm_servers_linked = ...
62,518
def add_examples(cls): """ Add all build.xml files as a test case to the class """ for root, _, files in os.walk(EXAMPLE_DIR): for filename in files: if filename == 'build.xml': fullfilename = os.path.join(root, filename) add_test(cls, fullfilename) return...
62,519
def load_school_collections() -> pd.DataFrame: """Load monthly tax collections for the School District.""" # Get the path to the files to load dirname = SchoolTaxCollections.get_data_directory("processed") files = dirname.glob("*-tax.csv") return _load_monthly_collections(files, total_only=True)
62,520
def get_curve(name): """Node Groupに作成したCurve Nodeを返す""" node_name = "MRGPEN_NODE_{}".format(name) node_groups = bpy.data.node_groups nodes = None if node_name in node_groups: nodes = node_groups[node_name].nodes else: nodes = node_groups.new( name=node_name, ...
62,521
def allcloseSS(SS1, SS2): """ Verify that two suff stat bags have indistinguishable data. """ # Both A and B better give the same answer for key in list(SS1._FieldDims.keys()): arr1 = getattr(SS1, key) arr2 = getattr(SS2, key) print(key) if isinstance(arr1, float): ...
62,522
def parse_read(read): """parse bioseq to fastq.""" # dele = "-" dele = "" # check if there is MD tag # check whether query sequence is exist if not read.has_tag("MD") or (query_seq := read.query_sequence) is None: return None query_qual = read.query_qualities # init matched r...
62,523
def update_policy(data, policy_id): """ Args: data: Dictionary with data to be updated policy_id: Policy's ID Returns: Update operation status wrapped on dictionary """ class UpdatePolicyError(Exception): pass try: policy_obj = Policy.objects.get(id=policy_id...
62,524
def apply_bg_correction(mean_values, params): """ this function won't work with float16 in practice. limits use to float32 """ if not isinstance(params, BackgroundCorrectionParams): raise ValueError('params is not a BackgroundCorrectionParams instance') bg_mean = params.bg_mean bg_mad = params....
62,525
def parse_args(): """ parse_args parses command line arguments and returns argparse.Namespace object Returns ------- argparse.Namespace Namespace that contains all command line arguments with their corresponding values """ parser = argparse.ArgumentParser(description="Context encode...
62,526
def run_state_evolution(x_ids, model, **algo_kwargs): """ Run state evolution for a given model. Parameters ---------- - x_ids : ids of the variables to infer (signals) - model : model that can be used in StateEvolution Returns ------- - records : list of x_id, v, n_iter """ ...
62,527
def test_lin_interp_from_only_corners(): """Test that I can linear interpolate from a very course mesh (only 6 sc per assembly) to a finer one""" sc_per_asm0 = 6 sc_per_asm1 = 24 xc, yc, xf = mock_quad(sc_per_asm0, sc_per_asm1) y_fine = dassh.mesh_functions.interpolate_lin(xc, yc, xf) # b/c...
62,528
def connect_inline(target, source): """Connects a target node in between source and all dependent nodes. Args: target : (<nuke.Node>) The Nuke node to connect inline between source and all of source's dependent nodes. source : (<nuke.Node>) The Nuke node tha...
62,529
def open(self): """获取开盘价序列""" return self.openArray[-self.size:]
62,530
def match_candidates_by_order(images, exifs, max_neighbors): """Find candidate matching pairs by sequence order.""" if max_neighbors <= 0: return set() n = (max_neighbors + 1) / 2 pairs = set() for i, image in enumerate(images): a = max(0, i - n) b = min(len(images), i + n) ...
62,531
def g(s): """ :type s: unicode """
62,532
def _bind_property_with_delta_bidirectional( object1: GObject.Object, object2: GObject.Object, property_name: str, delta: float, ) -> None: """Binds a property with a simple addition transformation. Args: object1: One of the objects to bind a property on. object2...
62,533
def meshTensor(value): """**meshTensor** takes a list of numbers and tuples that have the form:: mT = [ float, (cellSize, numCell), (cellSize, numCell, factor) ] For example, a time domain mesh code needs many time steps at one time:: [(1e-5, 30), (1e-4, 30), 1e-3] Means take 30 ...
62,534
def attr(*args, **kwargs): """Decorator wrapper for the nose 'attrib' attr decorator. This attr decorator recognizes the 'user' attribute when assigned and calls the `credentials_for` method of the TestTypePad class to apply the appropriate OAuth credentials. This wrapper also attempts to deri...
62,535
def get_module_info_from_code(path): """Get imports, based on given filepath. Credit: https://stackoverflow.com/a/9049549/2448495 """ with open(path) as fh: root = ast.parse(fh.read(), path) for node in ast.iter_child_nodes(root): # or potentially ast.walk ? if isinstance(...
62,536
def imperative_grad( vspace, target, sources, output_gradients=None): """Computes gradients from the imperatively defined tape on top of the stack. Works by filtering the tape, computing how many downstream usages are of each tensor and entry, and repeatedly applying backward functions until we h...
62,537
def itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type): """ Convert cartesian coordinates of targets in ITRF to spherical coordinates in topocentric reference frame for a specific station. Usage: az,alt,r = itrs2horizon(station,ts,ts_quasi_mjd,positions,coord_type) Inputs: station ...
62,538
def SoftmaxRanker(temperature, values, seed=None): """The operator that implements iterative softmax ranker Args: """ pass
62,539
def load_utf8_to_str(rel_path): """Load file, decode from UTF-8 and return as str.""" logging.debug('Loading test file. rel_path="{}"'.format(rel_path)) utf8_path = get_abs_test_file_path(rel_path) with codecs.open(utf8_path, encoding="utf-8", mode="r") as f: unicode_str = f.read() return un...
62,540
def ease(style, x): """ Though available as a general-purpose function, this logic is usually accessed through something like the `.progress` function on an animation or timeable. Return two values — the first is the easing result at a given time x; the second is the tangent to that, if calculable (is not,...
62,541
def getAllBlogs(con=None, cur=None, db=None): """ gets all blog details Returns: - rows: all blogs as list - [] : if no blogs are present in db """ sql = "SELECT * FROM blogs ORDER BY id ASC" rows = [] db(sql, ( )) rows = cur.fetchall() return rows or []
62,542
def advanced_search(post_query): """ Perform advanced search using OFF search engine """ post_query['json'] = '1' url = utils.build_url(service='cgi', resource_type='search.pl', parameters=post_query) return utils.fetch(url, json_file=False)
62,543
def S03_get_yob_from_DNI(*args):# {{{ """ STEP: S02_get_age_from_DNI In this step, age is computed from the DNI number if DNI is present but age is not. Returns: D: DataFrame containing the data Columns replaced: / yob Notes: When the year of birth is not available, a relacion bet...
62,544
async def cortx_s3_upload_resume(ack, say, command, payload): """Uploading a resume to Slack to process it and add it to the resume-data.csv file""" await ack() file_name = command['text'] user_id = payload["user_id"] channel_id = payload["channel_id"] isFileFound = await get_file_from_s3(s3_cl...
62,545
def read_frame(input, frame_num=None, frame_time=None, video_data=None, force_grayscale=False): """ Code taken and adapted from zplib.image.ffmpeg Efficiently locates the desired frame and returns it, looping through every previous frame. Return specific frame from an input video via ffmpeg. Parameters:...
62,546
def configure_streams(jobid, server): """Capture STDOUT and STDERR writes and post them to the /server/""" sys.stdout = JobServerStream(jobid, server, sys.stdout) sys.stderr = JobServerStream(jobid, server, sys.stderr)
62,547
def generate_percentiles(results, percentiles=DEFAULT_PERCENTILES): """Percentage distribution of the results. I.e. At what point had 50%, 75% and 90% of results completed? """ data = [] total = len(results) cur_index = 0 if not results: return data for percentile in percentil...
62,548
def get_policy(name: str) -> Policy: """Returns the Policy with the given name, None if there is none""" return _registry.get(name)
62,549
def build_patch200_succeeded_ignore_headers_request( *, json: Any = None, content: Any = None, **kwargs: Any ) -> HttpRequest: """Long running put request, service returns a 200 to the initial request with location header. We should not have any subsequent calls after receiving this first response. See...
62,550
def htmlpage(): """For testing: Example HTML page, if you want to use templates.""" # just some data for the template clock = datetime.datetime.now() return render_template('example.html', clock=clock)
62,551
def test_fallback_abs_float(): """ Feature: JIT Fallback Description: Test abs(float) in graph mode Expectation: No exception """ @ms_function def foo(): x = -1.0 return abs(x) assert math.isclose(foo(), 1.0, abs_tol=1e-5)
62,552
def test_tool_plugin_command_exists_shortpath_valid(monkeypatch): """Test that command_exists works correctly (only filename given, command is on PATH). """ # Monkeypatch the environment to clear PATHEXT monkeypatch.delenv('PATHEXT', raising=False) # Make a temporary directory which will be part of th...
62,553
def get_all_blob_ids_for_two_commits(cve_commit1, cve_commit2, blobs_db): """ Get all the source blob IDs for two CVE commits. commit1 must be ancestor of commit2. :param cve_commit1: earlier commit, dict of {"commit": commit_id, "src_files": list_of_files} :param cve_commit2: later commit, dict of {"co...
62,554
def stop_scan(): """ Use a thread event to cause the scan loop to gracefully exit. It may not be a robust solution at the moment, depending on how exceptions are handled and various other things. Requires testing. """ _log.debug('Stopping scan in background thread') while ...
62,555
def sensAnalysis(locator, extraCosts, extraCO2, extraPrim, solarFeat, ntwFeat, gen): """ :param locator: path to input locator :param extraCosts: costs calculated before optimization of specific energy services (process heat and electricity) :param extraCO2: green house gas emissions calculated bef...
62,556
def account_addresses_assets(self, stake_address: str, **kwargs): """ Obtain information about assets associated with addresses of a specific account. Be careful, as an account could be part of a mangled address and does not necessarily mean the addresses are owned by user as the account. https://docs...
62,557
def _get_logger(logger_name): """根据名称获取日志器""" __ = logging.getLogger(logger_name) _ = LogProxy(__) loggers.append(_) return _
62,558
def detect_resolution(d1: datetime, d2: datetime) -> int: """ Detects the time difference in milliseconds between two datetimes in ms :param d1: :param d2: :return: time difference in milliseconds """ delta = d1 - d2 return int(delta.total_seconds() * 1e3)
62,559
def a_volume_that_is_published(volume_ctx): """a volume that is published.""" volume_ctx[VOLUME_CTX_KEY] = publish_volume()
62,560
def parse_image_spec(path: str) -> typing.Tuple[str, utils.ArgDict, typing.Optional[str]]: """ Parses out a Publ-Markdown image spec into a tuple of path, args, title """ title: typing.Optional[str] = None # Parse out the title.. match = re.match(r'(.+)\s+\"(.*)\"\s*$', path) if match: pat...
62,561
def test_filter_array(): """Test filtering an array.""" for data in (np.zeros((11, 1, 10)), np.zeros((9, 1, 10))): filter_data(data, 512., 8, 12, method='iir', iir_params=dict(ftype='butterworth', order=2))
62,562
def make_dirs() -> None: """Creates the directories to store creates images and their corresponding json data. If the folders already exist, skips and continues. """ print('Creating build directories') build_dirs = ['build', 'build/images', 'build/json'] for _dir in build_dirs: _dir = P...
62,563
def create_indicates_relationships( created_by: Identity, sources: List[_DomainObject], targets: List[_DomainObject], confidence: int, object_markings: List[MarkingDefinition], start_time: Optional[datetime] = None, stop_time: Optional[datetime] = None, ) -> List[Relationship]: """Create...
62,564
def preprocess_doc(doc: str): """ Preprocessing of the string Args: doc str: document as string, e.g span Returns: []: tokenized and processed str """ return simple_preprocess(doc, deacc=True)
62,565
def create_folders(directories, Downloads): """ This function creates the folders in <Downloads> where the files will be moved to. """ for key in directories: if key not in os.listdir(Downloads): os.mkdir(os.path.join(Downloads, key)) if "OTHER" not in os.listdir(Downloads): ...
62,566
def _transform_datasets(metadata: dict) -> pd.DataFrame: """Transform datasets metadata into a formatted DataFrame.""" df = pd.DataFrame.from_dict(metadata.get("dataSets")) df = df[ [ "id", "code", "shortName", "name", "periodType", ...
62,567
def extract_relevant_sentences(tweet, cfg): """Extracts all relevant sentences :param tweet: :param cfg: configuration map :returns: dict with keys `in_tweet` and `in_linked_doc` The first returns a list of sentences extracted from the tweet text proper, possibly cleaned. `in_linked_doc` has a...
62,568
def read(socket, freq_start, freq_end, rbw, video, atten, with_data): """Return list of satis data.""" socket.send(get_string({ Key.Request: 5, Key.Start: freq_start, Key.End: freq_end, Rbw.name: rbw, Key.Video: video, Attenuation.name: atten, Mode.name: Mode.Single, ...
62,569
def request_issues_by_sprint(cfg): """Request all issues associated with given sprint""" issues = [] sprint_issues_url = cjm.request.make_cj_agile_url( cfg, "sprint/{0:d}/issue".format(cfg["sprint"]["id"])) start_at = 0 max_results = 50 while True: response = cjm.request.make_...
62,570
def connectRandomNodes(Graph, M=4000): """ :param - Graph: snap.PUNGraph object representing an undirected graph :param - M: number of edges to be added return type: snap.PUNGraph return: Graph object with additional M edges added by connecting M randomly selected pairs of nodes not already...
62,571
def SimulateIntervals(daily, iters=101, func=RunLinearModel): """Run simulations based on different subsets of the data. daily: DataFrame of daily prices iters: number of simulations func: function that fits a model to the data returns: list of result objects """ result_seq = [] starts...
62,572
def sheva_nah_after_short_vowel(last_vowel, guess): """`sheva` after short vowel is `sheva-nah` Source: [Simanim] 3.5 > According to the opinion of the _Minchat Shai_, after a short vowel it > is a `sheva-nah` even when there is a `meteg` near the short vowel. Source: [HaMillon] 2.16.3 > `shev...
62,573
def test_interface(): """Test the abstract class Interface.""" assert Interface()
62,574
def create_event( service: Client, database_id: str, event: Event ) -> dict: """ Creates a new event in a given Notion database. """ service.pages.create( parent={ "database_id": database_id }, **event.to_notion_page() )
62,575
def Reinstall(vm, version='4.7'): """Install specific version of gcc. Args: vm: VirtualMachine object. version: string. GCC version. """ if vm.OS_TYPE != os_types.DEBIAN: return for pkg in ('gcc', 'gfortran', 'g++'): version_string = _GetVersion(vm, pkg) if version in version_string: ...
62,576
def send_nick(nick): """Send NICK to IRC.""" con.send(bytes("NICK {}\r\n".format(nick), "UTF-8"))
62,577
def min(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin """SQL ``MIN`` function (aggregation) :param col: the column to find min .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition...
62,578
def trigger_build(project_name, branch_name): """ This task runs our CircleCI builds. If you look at our "celeryconfig.py" file you would see that we have CircleCI builds that are scheduled for every 15 minutes, etc. This basically is responsible for building all of our projects and uploading th...
62,579
def total_distance(solution, distanceMap): """ Calculate the total distance among a solution of cities. Uses a dictionary to get lookup the each pairwise distance. :param solution: A list of cities in random order. :distanceMap: The dictionary lookup tool. :return: The total distance betwe...
62,580
def download_resource(resource: Resource) -> None: """Downloads a single mp3 file and logs it""" filename = get_valid_filename(f"{resource.formatted_date}-{resource.title}") full_filename = f"./downloads/{filename}.mp3" with session.get(resource.url, stream=True) as r: r.raise_for_status() ...
62,581
def get_design_condition(lineIn): """ """ key = {"hydrotest": r"\b(hydro(test)?)\b", "operating": r"\b(op(erating)?)\b", "ultimate": r"\b((ultimate|user))\b"} keyWord, lineOut, _match = search_line(lineIn, key) return keyWord
62,582
def minidump_ships(ships): """Debug logging: dump all the ships in the fight and their state""" for ship in ships: if ship['hp'] <= 0: comment = 'DEAD' elif ship['skipuntil']: comment = 'SKIP' elif ship['hasfired']: comment = 'X' else:...
62,583
def get_tite_box(box_in, px_coord=[100, 0]): """ Get tight box, px_coord for determine left right border """ BORDER = 0 mid_xp = 0 if px_coord[0] < px_coord[1]: BORDER = 1 mid_xp = (px_coord[1]+px_coord[0])/2 out_boxes = [] ycord, xcord, _ = np.where(box_in == 1) ...
62,584
def py_float2float(val, be=False): """ Converts Python float to 4 bytes (double) """ sig = '>f' if be else '<f' return struct.pack(sig, val)
62,585
def runPmv(*argv, **kw): """The main function for running PMV """ import sys if type(argv) is tuple: if len(argv) == 0: argv = None elif len(argv) == 1: argv = argv[0] if type(argv) is not list: argv = [argv] else: argv ...
62,586
def setup_logging(log_level=None, log_file=None): """ Set up logging for the whole program and return a log handler Parameters ---------- log_level: str valid log level to set logging to log_file: str name of the log file to log to Returns ------- log handler to use...
62,587
def arg_name(name): """Convert snake case argument name to a command line name. :param str name: The argument parameter name. :returns: str """ return "--" + name.replace('_', '-')
62,588
def plot_wf_mesh_mesh_vert(redvox_id: str, wf_panel_2_sig: np.ndarray, wf_panel_2_time: np.ndarray, mesh_time: np.ndarray, mesh_frequency: np.ndarray, mesh_panel_1_trf: np.ndarray, ...
62,589
def test_sophos_central_alert_search_command(requests_mock) -> None: """ Scenario: Search for specific alerts. Given: - User has provided valid credentials. - Headers and JWT token have been set. When: - sophos_central_alert_search is called. Then: - Ensure number of ite...
62,590
def stack_str(offset=0, fmt=None, sep=None): """ It creates a string representing calling stack from where this function is called. Args: offset: remove the lowest `offset` frames. Because usually one does not need the frame of the `k3log.stack_str` line. ...
62,591
def main(args=None): """Except for the custom dfile, this is stolen directly from py_compile. Compile all of the given filename arguments. This custom version replaces /ms/dev in the path with /ms/dist to match our environment usage. """ if args is None: args = sys.argv[1:] dev_re = r...
62,592
def topic_create(client, to_delete): """Create a topic.""" TOPIC_NAME = 'topic_create-%d' % (_millis(),) # [START topic_create] topic = client.topic(TOPIC_NAME) topic.create() # API request # [END topic_create] to_delete.append(topic)
62,593
def get_latest_model_version(city: str) -> int: """Returns the version number of the latest model belonging to the passed city. Parameters ---------- city: str Name of the city. Returns ------- latest_version: int Latest model version. """ trained_model_query = ( ...
62,594
def delete_event(request, event_id): """Event deletion view. Delete the event specified by the event ID and redirect the user to the events list. Arguments: request - Django object containing request information. event_id (int) - ID of Event to delete. Returns: redirect - Django funct...
62,595
def pack_binaries(prefix: str, name: str, output: str): """ Packs all binaries generated by the build_single function into a single .tar.xz with e9 compression level :param prefix: the same folder passed to the build_single function :param name: name of the output tar.xz (without extension) :par...
62,596
def single_window( landsat_band_10: np.ndarray, landsat_band_4: np.ndarray, landsat_band_5: np.ndarray, lst_method: str = "mono-window", emissivity_method: str = "avdan", unit: str = "kelvin", ) -> np.ndarray: """Provides an interface to compute land surface temperature from landsat ...
62,597
def get_cosine(vec1, vec2): """Get cosine for two given vectors""" OPS = get_current_ops() v1 = OPS.to_numpy(OPS.asarray(vec1)) v2 = OPS.to_numpy(OPS.asarray(vec2)) return numpy.dot(v1, v2) / (numpy.linalg.norm(v1) * numpy.linalg.norm(v2))
62,598
def notch(waves, calcs, f_notch, Q, wfin="wf_blsub", wfout="wf_notch", test=False): """ apply notch filter with some quality factor Q TODO: apply multiple notches (f_notch, Q could be lists) """ wfs = waves[wfin] clk = waves["settings"]["clk"] # Hz f_nyquist = 0.5 * clk num, den = signa...
62,599