content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _real_freq_filter(rfft_signal, filters): """Helper function to apply a full filterbank to a rfft signal """ nr = rfft_signal.shape[0] subbands = filters[:, :nr] * rfft_signal return subbands
0bee4822ac1d6b5672e4ad89bb59f03d72828244
3,614,800
def _strip_extension(name, ext): """ Remove trailing extension from name. """ ext_len = len(ext) if name[-ext_len:] == ext: name = name[:-ext_len] return name
aa1e6f8c68e09597e2566ecd96c70d2c748ac600
3,614,801
def node_clique_number(G,nodes=None,cliques=None): """ Returns the size of the largest maximal clique containing each given node. Returns a single or list depending on input nodes. Optional list of cliques can be input if already computed. """ if cliques is None: if nodes is not None: ...
143fa46b1bd7365bc306489e77d697d5741701a4
3,614,802
def str_to_list(s): # type: (str) -> List[str] """Convert string to list.""" if isinstance(s, str): return s.split(',') return s
bdc59bfcfadf815ecce5adc599fbca98f9924fe6
3,614,803
import torch def get_online_seed_from_cam_sal_seg(cam: torch.Tensor, sal: torch.Tensor, seg_prob: torch.Tensor, cls_in_label: torch.Tensor, cam_thresh: float, sal_thresh: float, ignore_label: int) -> torch.Tensor: """Get online seed from CA...
96fd29570fef0fb352c8b32a4ac5d3bf49ae4dbe
3,614,804
import inspect def check_parameter(**kwargs): """Check dtype of the function's parameters. Parameters ---------- kwargs : Type or Tuple[Type] Map of each parameter with its expected dtype. Returns ------- _ : bool Assert if the array is well formatted. """ # get ...
597c205c091b207f529fd961cd808c5a99285b4f
3,614,805
def part1(data): """ >>> part1(read_input()) 192 """ return sum(is_valid(passport) for passport in data)
cd68c276151b540d2bb02aaca0f7eb039addc79d
3,614,806
def minimize(func, x0, args=(), *, method, tol=None, options=None): """Minimization of scalar function of one or more variables. This API for this function matches SciPy with some minor deviations: - Gradients of ``fun`` are calculated automatically using MindSpore's autodiff support when required. ...
d0affb1dc4bbe141504528fba55baf8a2fa29ae9
3,614,807
from mxnet.gluon.model_zoo.vision import get_model def get_network(name, batch_size): """Get the symbol definition and random weight of a network""" dtype = 'float32' input_shape = (batch_size, 3, 224, 224) output_shape = (batch_size, 1000) if "resnet" in name: n_layer = int(name.split("-...
1d874b32c7421f189a4cd47259875d02ba524eb1
3,614,808
from typing import Callable from typing import Dict def web_template() -> Callable[[Request, str], _TemplateResponse]: """Create a dependency which may be injected into a FastAPI app.""" def _template(request: Request, page: str, context: Dict = {}) -> _TemplateResponse: """Create a template from a r...
39e5b04dcbc586670b7a165444976e1beac178aa
3,614,809
def core_number(G): """Returns the core number for each vertex. A k-core is a maximal subgraph that contains nodes of degree k or more. The core number of a node is the largest value k of a k-core containing that node. Parameters ---------- G : NetworkX graph A graph or directed gr...
74e9852cac0e7ad321090e4959b1b6f88d8a55b7
3,614,810
def create_meeting( client, name: str, description: str = None, title: str = None, duration: int = 60000, # duration in mins ~6 weeks ): """Create a Zoom Meeting.""" body = { "topic": title if title else f"Situation Room for {name}", "agenda": description if description else...
a5157575a8921a612a09dc6cf9038f0c45513cd4
3,614,811
def hours(datetime): """ Returns the hours component for the given datetime value, in local time. """ return datetime.hour()
a88d932b49ded87e472cf902e39a1ca3c3e4ac2b
3,614,812
from typing import List from typing import Tuple import os def create_work_packages( inputs: List[Tuple[str, bool]], work_package_size: int, number_of_workers: int, already_processed: List[str] = [] ) -> Tuple[List[List[str]], List[str]]: """Create the work packages for the worker ...
fce778f27488ecbfb3df18f7d88c39901f32d113
3,614,813
def compute_checksum(filename): """Computes the MD5 checksum of the contents of a file. filename: string """ cmd = 'md5sum ' + filename return pipe(cmd)
b6fc037ac42c0f86bf196ff6f93fe7cb94bf45ea
3,614,814
def clean_text( raw_text, fix_unicode=True, to_ascii=False, lower=True, no_line_breaks=True, no_urls=True, no_emails=True, no_phone_numbers=True, no_numbers=False, no_digits=False, no_currency_symbols=True, no_punct=False, ...
d63d0c4eff28de4677c12e080a37d6f40309a395
3,614,815
def _get_s3_provider(): """ Gets S3 Config Provider :return: Instance of S3ConfigProvider :rtype: S3ConfigProvider """ return S3ConfigProvider( bucket=CONFIG_PROVIDERS['s3']['bucket'], config_base=CONFIG_PROVIDERS['s3']['base'] )
2192daa02b57a58267d34662294886aeb8f8bc1b
3,614,816
import os import tempfile import json def compile_html( input_path, html_path=None, *, props=None, precision=None, title=None, div_id=None, inline_js=None, svelte_to_js=None, js_path=None, js_name=None, js_lint=None ): """Compile Svelte or JavaScript to HTML. A...
36f8e9d9f4f92198ed7fffb0c36aed05a146e2f4
3,614,817
def is_path_fully_cached(path): """Returns true if all the bytes of the path are cached, false otherwise""" rc, stdout, stderr = exec_process("hdfs cacheadmin -listDirectives -stats -path %s" % path) assert rc == 0 caching_stats = stdout.strip("\n").split("\n")[-1].split() # Compare BYTES_NEEDED and BYTES_CAC...
2bcf4258b52d9e8f739ff5523f6b036d42013c4f
3,614,818
def find_camera_tracking_pts_topics(): """ Returns list of all tracking_pts topics associated with a camera """ topic_list = find_topics_w_ending('tracking_pts') topic_list = [topic for topic in topic_list if 'camera' in topic.split('/')] return topic_list
afd3de49187bdec69deab0418ea3bcc3c627f8e2
3,614,819
def get_batch_size(dataset: tf.data.Dataset, optimization_batch_size: int = BATCH_AUTO_TUNE) -> int: """Computes optimization batch size for processing steps in batches. Args: dataset: episodes or steps dataset. optimization_batch_size: user-provided hint for the batch size. Returns: ...
f437e6403031f879ffe3047bb008732cba4a5497
3,614,820
def get_uuid_from_url(url: str) -> str: """ Strip the URL from the string. Returns the UUID. """ return url.split('/')[-1]
d9e0ea9ed186d1ba19c40ead9d08108c45dbf850
3,614,821
def texFrac(frac): """ Tex render for Fractions""" return ["\\frac{" , str(frac._num) , "}{" , str(frac._denom) , "}"]
fd0ed6af8b50f8a4b89e0d83d7cb3e3c3a5f3a90
3,614,822
import os import shutil def build_plot_video(results, unique_id, json_data_dict): """Builds and writes a combined video of the plot of the knee angle and the angle video Args: results: dictionary of the downloaded files {'file_name': file} unique_id: the uuid that was given to the video ...
646cf48ae37facc9a2226317696cd61d2bb111df
3,614,823
def repeated_hindsight_gumbel_estimation( universe, probabilities, values, num_samples, normalize, repetitions): """Uses Hindsight Gumbel Estimation multiple times with different Gumbels.""" # Use the same samples for each repetition! results = ppswor_samples(universe, probabilities, num_samples) all_sampl...
6f6ad6e712d87350e34b397010eb0be86095ec9c
3,614,824
def get_progress_string(tag, epoch, minibatch, nbatches, cost, time, blockchar=u'\u2588'): """ Generate a progress bar string. Arguments: tag (string): Label to print before the bar (i.e. Train, Valid, Test ) epoch (int): current epoch to display minibatch (i...
23d7b5dfcc2fd11841a87a3c94f3e8f4d9840a36
3,614,825
def calcRingCentroidNormal(atomCoords): """ extract aromatic ring geometric info from a numpy array """ a1 = atomCoords[0] a2 = atomCoords[1] a3 = atomCoords[2] centroid = averageCoords(atomCoords) plane = calcPlane(a1, a2, a3) v1 = vector(centroid, a1) v2 = vector(centroid, a2) nor...
1c1719ef1bfe1564e6fbbe16c14507b9daf6149e
3,614,826
import copy def flip_horizontal(original: Image) -> Image: """Written by: Cameron Legree Student No. 101153496 Returns a copy of an image flipped along a horiontal line centered in the image. orginal_image must be loaded prior to passing it through the function. >>>flip_horizontal(miss_sull...
143a839c789ad26f5d7174bf25902b85936a4e13
3,614,827
from typing import List from typing import Optional def span_to_label(tokens: List[str], labeled_spans: dict, scheme: Optional[str] = 'BIO') -> List[str]: """ Convert spans to label :param tokens: a list of tokens :param labeled_spans: a list of tuples (start_idx, e...
dbd572d4c306f31202c93b5983f5dd4cdd237074
3,614,828
def expand_markup(abbr: str, config: Config) -> str: """ Expands given *markup* abbreviation (e.g. regular Emmet abbreviation that produces structured output like HTML) and outputs it according to options provided in config """ return stringify_markup(markup_abbreviation(abbr, config), config)
2af46f12fcecb0bedcc01b94aeb2b92dc51e3a7c
3,614,829
import argparse import os def build_args(): """ Constructs command line arguments for the vulndb tool """ parser = argparse.ArgumentParser( description="Fully open-source security audit for project dependencies based on known vulnerabilities and advisories." ) parser.add_argument( ...
ee24006780a225803cd503fb612264d49e37c7b2
3,614,830
def withinStdDevRange(a, b): """Returns the percent of samples within the std deviation range a, b""" if b < a: return 0; if a < 0: if b < 0: return (withinStdDev(-a) - withinStdDev(-b)) / 2; else: return (withinStdDev(-a) + withinStdDev(b)) / 2; else: return (withinStdDev(b) - with...
27b293805656b7e33af9843bab48b25ecfa98d47
3,614,831
import logging import requests def commit_email(): """Receive web hook from github and generate email.""" # Only look at push events. Ignore the rest. event = flask.request.headers['x-github-event'] logging.info('Received "{0}" event from github.'.format(event)) if event != 'push': loggin...
36e97fe8a52094c6d9274c58aa9dd69b10106573
3,614,832
def unimodal_converter(data): """ Returns ground truth labels when data is split modally to text and image data: dataframe object """ for column in ["string", "numeric"]: unimodal_image, unimodal_text = [], [] for i in range(len(data)): temp_val = data.loc...
623208e7b8ee9e4f1e494c95d7ec0c16558f85b9
3,614,833
def convert_ids_to_tokens(inv_vocab, ids): """Converts a sequence of ids into tokens using the vocab.""" output = [] for item in ids: output.append(inv_vocab[item]) return output
da1aa84d271fe46cedf530c2871ee54c57e676e2
3,614,834
import os def get_app_template_dirs(dirname, app_label=None, model_name=None): """ Return an iterable of paths of directories to load app templates from. dirname is the name of the subdirectory containing templates inside installed applications. Derived from django.template.utils.get_app_templat...
23e23cdf242b11e62d6f41106f529903e735a0f7
3,614,835
import aiohttp async def remove_device( ws_client: aiohttp.ClientWebSocketResponse, device_id: str, config_entry_id: str ) -> bool: """Remove config entry from a device.""" await ws_client.send_json( { "id": 1, "type": "config/device_registry/remove_config_entry", ...
095926990c48a5f61267eb059591a80c48f7e3eb
3,614,836
def build_senator_details(details): """Build the test data for a senator.""" data = build_us_details(details) data['terms'][-1]['state_rank'] = details[5] data['terms'][-1]['class'] = details[6] data['terms'][-1]['url'] = details[7] data['terms'][-1]['phone'] = details[8] return data
d1a12b12d48d1b05e0be343eaf0c4eb3a1d295bf
3,614,837
import array def normalize(y: ndarray, max_value: float) -> ndarray: """ Performs normalization of given values :param y: ndarray - numpy array of histogram values derived from TCSPC method :param max_value: float - maximal value in given data :return: ndarray - numpy array of normalized histogram...
d70ee12a6aefc49d53da265ab1d0cc120e392cec
3,614,838
import logging import pickle import time def load_obj(path): """ return the python object saved in the given path :param path: the path to be loaded :return: """ logger = logging.getLogger("load_obj") retry_count = 3 while retry_count > 0: try: with open(path, 'rb'...
d486846bdf284366a89a48e7d7ad0f86239b9f83
3,614,839
def xgboost_data_preparation(validation_list: list, dataframe: pd.DataFrame, target: np.array, key: str): """ xgboost data preparing for training The function transforms the data from a Pandas dataframe format to a xgboost-compatible format. :param list validation_list: The list that contains the data the...
8e88c4dc146e5a8e97ac8464411004115de3b80c
3,614,840
import argparse import os import sys import yaml def get_config_file(): """ Get config file. :return: config file for training or testing """ parser = argparse.ArgumentParser( description="parse key pairs into a dictionary for xt training or testing", usage="python train.py --conf...
e457ac526d5594adb552ae0c6c9d3b67459d31dd
3,614,841
def _url(url, params): """ Returns long url with parameters http://mydomain.com?param1=...&param2=... """ if params is not None and len(params) > 0: return url + "?" + urlencode(params) else: return url
7b13652682db17f61546834965cb00d3804688da
3,614,842
def UniProt_NCBI_TaxID_and_TaxName_for_autocomplete_UPS_FIN(fn_in, fn_out): """ e.g. of input file UP000464341 1408252 None bacteria 270 0 270 Escherichia coli R178 UP000000558 83334 ECO57 bacteria 5060 4 9234 Escherichia coli O157:H7 priority t...
a5ba2dc54f427ddfd5d521c257dea1dd74e3db43
3,614,843
def get_port() -> str: """Looks for ngrok processID. If found, scans the PID in `netstat` for an `activeListener` to skim the port number. Notes: Alternate is to run `echo {root_password} | sudo -S lsof -PiTCP -sTCP:LISTEN | grep ngrok` Returns: str: Local IP address and port numbe...
2baf2f10fdd5446101020fa5e6a24f29f4d124ef
3,614,844
from typing import Dict from typing import Union from typing import List from typing import Any from typing import Tuple def dict_to_aiohttp_tuples( d: Dict[str, Union[str, int, List[Any]]] ) -> List[Tuple[Any, Any]]: """aiohttp doesn't like dictionaries where the values are arrays. In particular, passin...
dc2f4ad0bff961062d6001096ebb6716aef0864d
3,614,845
def shapeToZip(inShape, outZip=None, allFiles=True): """Packs a shapefile to ZIP format. arguments -inShape - input shape file -outZip - output ZIP file (optional) default: <inShapeName>.zip in same folder as inShape (If full path not specified, o...
6ecbad65ee4f6b273b9d52539317e8d28b30be12
3,614,846
from pylagrit import PyLaGriT def build_refined_triplane( dem_raster: Raster, refinement_feature: Shape, min_edge_length: float, max_edge_length: float, delta: float = 0.75, slope: float = 2.0, refine_dist: float = 0.5, verbose: bool = False, outfile: str = None, ): # boundary:...
9f869fc3f6279feb850b61c7f486ce3e7b37b74e
3,614,847
def image_caption_correct(dataset, images_path): """Stream in images from a directory and pre-populate the text box with the model's predicted caption. The original caption is stored as "orig_caption", the potentially edited caption as "caption". """ encoder, decoder, vocab, transform = load_model()...
f93621d407ab4975754a765743a5bef561ff0df4
3,614,848
import logging from typing import Optional def init_stc( api: ApiType, logger: logging.Logger, install_dir: Optional[str] = None, rest_server: Optional[str] = None, rest_port: Optional[int] = 80, ) -> StcApp: """Helper function to create STC object. This helper supports only new sessions....
a8172dd43ace0f2d57d89baa8ec0fbb1929c8725
3,614,849
import importlib def _check_import(package_name): """Import a package, or give a useful error message if it's not there.""" try: return importlib.import_module(package_name) except ImportError: err_msg = ( f"{package_name} is not installed. " "It may be an optional ...
c4cb7c5a49071663d23e9530155bdee3304a5f72
3,614,850
from skimage.draw import polygon from skimage.measure import regionprops import numpy as np import tqdm def blobs_to_dict(blobs, img_shape, region_manager): """ outputs ground truth in a list of dicts like: {'0_angle_deg': 196.81771700655054, '0_major': 63.263008639602724, '0_minor': 14.997692...
8376ccfdf587ed3dec02775453d8e804a377773c
3,614,851
import json def get_tool_shed_repo_requirements(app, tool_shed_url, repositories=None, repo_info_dicts=None): """ Contact tool_shed_url for a list of requirements for a repository or a list of repositories. Returns a list of requirements, where each requirement is a dictionary with name and version as key...
5492703bf39bfb87c3217ddc1f87b9211566e2cd
3,614,852
import string def metadata(draw): """The "cu102" in "torch==1.8.1+cu102".""" # https://www.python.org/dev/peps/pep-0440/#local-version-identifiers alphabet = string.ascii_letters + string.digits + ".-_" return draw(st.text(alphabet=alphabet, min_size=1))
82e33b2c391b08eb1e5f7b4dba55f2226edb0c39
3,614,853
def getListConfiguration(request, params, visibility, order): """Returns the list data for the specified params. Args: visibility: determines which list will be used order: the order the data should be sorted in """ key_order, col_names = getKeyOrderAndColNames(params, visibility) conf_extra = para...
13bb030a37d37f1c80a7264db6ada39132aac06b
3,614,854
def compute_outcome_stats(df): """Compute statistics regarding the relative quanties of arrests, warnings, and citations""" n_total = len(df) n_warnings = len(df[df['stop_outcome'] == 'Written Warning']) n_citations = len(df[df['stop_outcome'] == 'Citation']) n_arrests = len(df[df['stop_outcome'] ==...
25dbdfbc15ddd5ac5b112d5fef0eec071bd573ad
3,614,855
def augment_data_sq(x, a, y, Theta): """ Augment the dataset so that the x carries an additional feature of theta Then also attach appropriate weights to each data point. Theta: Assume uniform grid Theta """ n = np.shape(x)[0] # number of original data points num_theta = len(Theta) wid...
b7b4186801a5a0eea45c95b6961a49ab833aeedc
3,614,856
def check_day_start(gtfs, desired_weekday): """ Assuming a weekly extract, gets the utc of the start of the desired weekday :param gtfs: :param day_start: :param desired_weekday: :return: """ day_start_add = 24 * 3600 day_start, _ = gtfs.get_day_start_ut_span() tz = gtfs.get_time...
fcaa2969be134f2e17bfa6948eba9f8df47c0666
3,614,857
import time def get_picasaweb_date(date_time): """Converts a date to PicasaWeb format (string). adjusted for 1/1/1970 or later (PicasaWeb does not recognize dates before 1/1/1970). Args: date_time: the datetime.datetime to convert Return: the date or 1/1/1970, in PicasaWeb format, whichever...
d6e101eb8729483cb181e626af81c015f8ade7cb
3,614,858
from typing import Any import click def confirm( cfg: Configuration, msg: str, force: bool, default: bool = False, abort: bool = False, ) -> Any: """Wrapped click.confirm function to print to stderr.""" assert cfg.logger is not None if force: return force if cfg.output_fo...
c47ff7893d32614b06d0e1a5bef4fff789c33052
3,614,859
def dumps_bdd_as_code( roots, bdd, lang='python', renaming=None): """Return code that computes root values from bits. @param roots: `dict` that maps each "output" bit to a BDD that depends on "input" bits @param bdd: BDD manager @param renaming: `dict` that maps ...
b713cd91b72125e996812d51c363c466b64afd23
3,614,860
def get_standard_name(uid): """ return CF standard name """ return dq.inx.uid[uid.vid].sn
20b59faded81c3975304f2f23e1b47ac7b6d117b
3,614,861
def get_null_reference_cdf( lowerlimit: np.float32, upperlimit: np.float32, numbins: int=1000, )->ModifiedECDF: """ This function will return a CDF to be used as a null reference. :param lowerlimit: lower bound for the CDF :param upperlimit: upperbound for the CDF :p...
4be8f7305d80fc0f8c8d5f83c187f71f232a12e3
3,614,862
import getpass def prompt(identifier) -> tuple: """Credential entry helper. Returns: Tuple of login_id, key """ login_id = input(f"API Login ID for {identifier}: ") key = getpass.getpass(f"API Transaction Key for {identifier}: ") return (login_id, key)
be0ed9be1a60c2c29753d6a9ca8b3f12294f183b
3,614,863
def _load_navigation(dataset: xr.Dataset, navigation_files: str): """Load navigation data from nmea, gpx or netcdf files. Returns the dataset with the added navigation data. Data from the navigation file are interpolated on the dataset time vector. Parameters ---------- dataset : Datas...
d021270738b96bcbb0a2811cd48748ad72eb8c5b
3,614,864
import argparse import pathlib import logging from datetime import datetime def write_to_image(): """Console script for xdr2img.""" base_parser = BaseArgs( "xvi2img reads folders, connects these to the underlying XDR files, and writes these to a directory " " in another medical imaging format....
5238cd6166354c311b9671f489ac7f193b174d73
3,614,865
import requests import logging def make_trace_data_requests( session_: requests.Session, bbox: str, conf: any ) -> list[list[dict]]: """ Makes the actual calls to Mapillary API to pull trace data for a given bbox string. :param session_: requests.Session() to persist session across API calls :par...
a53c65f24c8f20a51112e2ab8a2679e1f5a15a72
3,614,866
import torch def rotation_3d_in_axis(points, angles, axis=0): """Rotate points by angles according to axis. Args: points (torch.Tensor): Points of shape (N, M, 3). angles (torch.Tensor): Vector of angles in shape (N,) axis (int, optional): The axis to be rotated. Defaults to 0. R...
f9ae51e59e8531e25d376267b16746f5e88575e0
3,614,867
from typing import List def load_cabins() -> List[Cabin]: """ Load cabins from yaml file """ cabins = [] cabin_data = utils.get_cabin_data() for cabin in cabin_data: cabins.append(Cabin(cabin["class"], cabin["quality"])) return cabins
b75695ea66be77ad78e72f4d2ae17d29eda97942
3,614,868
def get_bod_class_start_quarter_after(term): """ Return the datetime object of the beginning of the first instruction day in the term after the give year and quarter. Only the summer full term is relevant. """ nterm = get_term_after(term) if nterm is None: return None return nter...
c251da89833d3dff4f5f0826fce5ec3c2d5c2e0d
3,614,869
import os import signal import time def display(conn: Connection) -> None: """Display Game of Life in the terminal Parameters ---------- conn: Connection Multiprocess pipe mainly used for receiving game of life states. The first value read from the pipe is the frame delay. Subsequent...
58d6320aa002caf40978b72166dc56718109cd73
3,614,870
import json import traceback def trigger_request(): """ Callback for IFTTT trigger bunq_request """ try: data = request.get_json() print("[trigger_request] input: {}".format(json.dumps(data))) if "triggerFields" not in data or \ "account" not in data["triggerFields"]: ...
1dc1c4ff88924f7d7af826016f9218a241164627
3,614,871
import pathlib def get_managed_environment_log_path(): """Path for charmcraft log when running in managed environment.""" return pathlib.Path("/tmp/charmcraft.log")
1d8c66d480094a728820ea80bdf1ad65a8859fe7
3,614,872
def get_chromsizes(bwpath): """ TODO: replace this with negspy Also, return NaNs from any missing chromosomes in bbi.fetch """ chromsizes = bbi.chromsizes(bwpath) chromosomes = natsorted(chromsizes.keys()) chrom_series = pd.Series(chromsizes)[chromosomes] return chrom_series
93384652e4f3cb0451aaf84a9a9808536b182042
3,614,873
def image_small_bokeh(an_image, a_title): """an_image is a skimage gray image""" rgb = cv2.cvtColor(img_as_ubyte(an_image),cv2.COLOR_GRAY2RGB) rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA) rgba_flipped = rgba[::-1, :] p = bokeh.plotting.figure(plot_width=256, plot_height=160, tools='box_zoom', title=a_title) ...
0282d0a9600f0f70d0b9b670c1b58a27e4b71a15
3,614,874
def create_volume_type_settings(volume_type): """ Returns a VolumeTypeSettings object :param volume_type: a SNAPS-OO VolumeType object """ control = None if volume_type.encryption: if (volume_type.encryption.control_location == ControlLocation.front_end.value): ...
a87cb6c7d1f14faed9c8903a358d82fd95bff252
3,614,875
import os from typing import OrderedDict def parse(repo, oauth_token): """ Parses and extracts cmd from `Testfile`. :param repo: Name of the cloned repository. :type repo: string :param oauth_token: Authoprization token for the user. :type oauth_token: string :return CMD: Dictonary of extracte...
6aa144551806832a6a6ea52d6a381d381930f804
3,614,876
def plot_3d_surface(axes, image, xdata=None, ydata=None, samples=None, clim=None, axlim='auto', **kwargs): """ Plot 2D image data as 3d surface :param axes: matplotlib figure or subplot axes, None uses current axe :param image: 2d array image data :param xdata: array data, 2d or 1d :param ydata:...
b056bd6cbe38c76881c763abe8f08162ebeaffa2
3,614,877
import functools from typing import Union from typing import List def per_ds(clz: type(Trace)): """A class annotation which will convert regular traces into dataset-sensitive traces. Args: clz: The base class to be converted. Returns: A dataset aware version of the class. Note that if th...
ac70f3d925d640cb3967a0d4b30aff25324792b1
3,614,878
def get_gpu_capability() -> tuple[float, ...]: """Gives CUDA capability for each GPU""" with _nvml(): handles = _get_device_handles() return *map(py3nvml.nvmlDeviceGetCudaComputeCapability, handles),
9f8e3a9cfff4b6ec77945574ec8723d2ca2d33a7
3,614,879
from typing import Optional from typing import Union import pathlib import socket def reconnecting_sftp(hostname: str, username: Optional[str] = None, password: Optional[str] = None, port: Optional[int] = None, private_key_file: O...
b78e887892d91c8e0a5b5e95e57fa86be9973a27
3,614,880
def pp_2(node, indentation): """"Lisp Style indentation, i.e. xxx yyy zzz """ if isinstance(node, TreeText): return node.unicode_ if len(node.children) <= 2: return "(" + " ".join(pp_flat(c) for c in node.children) + ")" my_arg_0 = "(" + pp_flat...
6e5e2b124d1a821df7eb73ba7928afd9c9ffa769
3,614,881
from unittest.mock import Mock from datetime import datetime def player_model_fixture(db_mock=Mock(), **kwargs): """ Get a player model fixture which can be manipulated at will All values passed will be set to the player fixture param unittest.mock db_mock: The mock object to use for the database obj...
67196bc8934428603e8a9297a1524187b3d4fd3c
3,614,882
def to_romaji(w): """カタカナ・ひらがなをローマ字書きに変換する 一般的なローマ字ではなく、IMEでの単体文字入力となる形に変換して予測候補を出しやすくする ref: http://developers.linecorp.com/blog/?p=367 """ def ctoromaji(c): c = c.group(0) # if RE_HIRAGANA.search(c): # c = chr(ord(c)+96) if c in ROMAJI_DICT: return ...
9c915b0b00e3c15b6d50e5ac330dd9621c31acf4
3,614,883
def setup_faiss_index(embedding_dim: int) -> faiss.Index: """Returns a simple `IndexFlatIP` FAISS index with a vector dimension size of `embedding_dim` and an ID map for cosine similarity searching. """ index = faiss.IndexFlatIP(embedding_dim) index = faiss.IndexPreTransform(faiss.NormalizationTrans...
05ca97680bed1468c99dcd28d89bfcad80e1279f
3,614,884
def mm_init_guess(runprops): """This function will produce the initial guess used in multimoon. Input: runprops- All run properties for the code. Will include the name of the init_guess dataframe csv file. Returns: params_df - A parameters dataframe with the same column n...
60a65507d2a9f12cb43c0a6f651f3d4f3f39972b
3,614,885
def add_ixn_decreases_phosphorylation(graph, ixn): """Adds an interaction that represents the chemical decreasing the phosphorylation of a protein :param pybel.BELGraph graph: A BEL graph :param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction :return: The hash of the added edge :r...
6c896e781a3eaa16db6aecb42a71653e1dbc77cb
3,614,886
import struct def set_wm_window_opacity(window, opacity): """ Sets the opacity of the current window. N.B. If your window manager uses decorations, you'll typically want to pass your client's *parent* window to this function. :param window: A window identifier. :param opacity: A float betwe...
5fcfdfb3aecef2f78e9f6ced8602258749ea2527
3,614,887
def parse_price_url(r): """ 解析重定向url, 构造价格的url :param r: post返回的response :return: """ jsonobj = r.json() price_url = jsonobj['data']['redirectUrl'] # price_url 的格式是/pc/index.html#/inquiry/6534929115267980857 # 截取url的inquiry后面的部分6534929115267980857 # TODO:存在无报价的情况 if "Noprice"...
1dce1621e12b6f4446230c35646f5864278f7ee2
3,614,888
def defer(fn, delay): """Defer a function call after a set period of time has elapsed (in seconds) Parameters ---------- fn : a callable that takes no args delay : int | float the time delay in seconds to wait before calling fn Returns ------- DeferRef a reference to th...
8540abd637381c3a1b2c47c6a561f16e7d2033c6
3,614,889
def proactive(ARG_defaultname: str="file"): """Use this function *before* generating data. Parameters ---------- ARG_defaultname : str, default is "file" The filename to save the data under, assuming the user does not choose another name. Returns ------- savebool : bool If ...
dc94f7f847842f644fafe26622ea4d8870d0b1ae
3,614,890
def _is_authorized(vdc): """Check if the user is authorized through BasicAuth or API Keys. """ auth_header = request.headers.get("Authorization") if auth_header: # Get vdc name and password from request Authorization header with Basic type name, password = parse_auth(auth_header) ...
6bb0adcd76ded8c22e10c48cc816a38059b4ccc2
3,614,891
def compute_distances_matrix(positions, max_distance, pixel_size=None): """Calculates Mutual Closest Neighbour distances between all channels and returns the values as """ module_logger.info('Computing distances between spots') if len(positions) < 2: raise Exception('Not enough dimensions to do...
0bc1ffc3c2cfddc66b4123b696f10be9bba924ef
3,614,892
def _extract_graph_summary(graph_def): """Extracts useful information from the graph and returns them.""" name_to_input_name = {} # Keyed by the dest node name. name_to_node = {} # Keyed by node name. # Keeps track of node sequences. It is important to still output the # operations in the original order. ...
8984faf6f95c847cd7d4c43654f96ef1ae44f460
3,614,893
def _compute_rank_down(start_nodes): """ Compute the rank of the down stream nodes. Args: start_nodes (list[NodeGraphQt.BaseNode]): (Optional) the start nodes of the graph. Returns: dict{NodeGraphQt.BaseNode: node_rank, ...} """ nodes_rank = {} for node in start...
0424b4b0e75af6e2710dfc139f70133c4587f164
3,614,894
import time def generate_timestamp(expire_after: float = 30) -> int: """ :param expire_after: expires in seconds. :return: timestamp in milliseconds """ return int(time.time() * 1000 + expire_after * 1000)
16f2fcd77de9edb1e167f1288e37a10491469c22
3,614,895
from typing import Counter import math def radius_of_gyration(positions, user): """ Returns the radius of gyration, the *equivalent distance* of the mass from the center of gravity, for all visited places. [GON2008]_ References ---------- .. [GON2008] Gonzalez, M. C., Hidalgo, C. A., & Baraba...
b71d82d30b28d16efa57943cb1a5b34578a8fd5a
3,614,896
def evaluate_manufactured_solution_result_at_step(filename,dof,list_of_functions,step=-1,meshname='connect1',rtol=1e-5): """ ======================================================= | evaluate_manufactured_solution_result_at_step | ======================================================= Evalua...
fb91cc2f6a84eebaec2d17796cfe9b68cfb2f9fd
3,614,897
import os import logging def get_available_devices_num(): """get available devives num.""" env_dic = os.environ try: return int(env_dic.get('DEVICE_TOTAL_NUM').lower()) if env_dic.get('DEVICE_TOTAL_NUM') else 1 except NameError as e: logging.error(e) return 1
ebaac1bf30061fe31123651471219c3b4960eba4
3,614,898
import base64 def b64e(s): """b64e(s) -> str Base64 encodes a string Example: >>> b64e("test") 'dGVzdA==' """ return base64.b64encode(s)
2562f5d18ac59bbe4e8a28ee4033eaa0f10fc641
3,614,899