content
stringlengths
22
815k
id
int64
0
4.91M
def extract_text(arg: Message_T) -> str: """ 提取消息中的纯文本部分(使用空格合并纯文本消息段)。 参数: arg (nonebot.typing.Message_T): """ arg_as_msg = Message(arg) return arg_as_msg.extract_plain_text()
5,342,600
def test_consolidate_elemental_array_(): """ Tests that _consolidate_elemental_array_() returns a consolidates array of compositions for both whole number and decimal values """ input_array = [ {"symbol": "N", "occurances": 2}, {"symbol": "H", "occurances": 8}, {"symbol": "Pt", "...
5,342,601
def check_package_for_ext_mods(path, target_python): """Walk the directory path, calling :func:`check_ext_mod` on each file. """ for dirpath, dirnames, filenames in os.walk(path): for filename in filenames: check_ext_mod(os.path.join(path, dirpath, filename), target_python)
5,342,602
def dtw(x, y, dist, warp=1): """ Computes Dynamic Time Warping (DTW) of two sequences. :param array x: N1*M array :param array y: N2*M array :param func dist: distance used as cost measure :param int warp: how many shifts are computed. Returns the minimum distance, the cost matrix, the accum...
5,342,603
def format_line_count_break(padding: int) -> str: """Return the line count break.""" return format_text( " " * max(0, padding - len("...")) + "...\n", STYLE["detector_line_start"] )
5,342,604
def identify_generic_specialization_types( cls: type, generic_class: type ) -> Tuple[type, ...]: """ Identify the types of the specialization of generic class the class cls derives from. :param cls: class which derives from a specialization of generic class. :param generic_class: a generic class. ...
5,342,605
def Metadata(): """Get a singleton that fetches GCE metadata. Returns: _GCEMetadata, An object used to collect information from the GCE metadata server. """ def _CreateMetadata(unused_none): global _metadata if not _metadata: _metadata = _GCEMetadata() _metadata_lock.lock(function=_Crea...
5,342,606
def pa11y_counts(results): """ Given a list of pa11y results, return three integers: number of errors, number of warnings, and number of notices. """ num_error = 0 num_warning = 0 num_notice = 0 for result in results: if result['type'] == 'error': num_error += 1 ...
5,342,607
def parse_properties(df, columns_to_integer=None, columns_to_datetime=None, columns_to_numeric=None, columns_to_boolean=None, columns_to_string = None, dt_unit = 'ms', boolean_dict = {'true': True, 'false': False, '': None}): """ Parse string columns to other formats. This function is used in hubspot routine, it...
5,342,608
def http_request(method, url, headers, data=None): """ Request util :param method: GET or POST or PUT :param url: url :param headers: headers :param data: optional data (needed for POST) :return: response text """ response = requests.request(method, url, headers=headers, data=data) ...
5,342,609
def beNice(obj): """Be nice : exponential backoff when over quota""" wait = 1 while wait : try : return_value = obj.execute() wait = 0 except : #FIXME : we should test the type of the exception print("EXCEPT : Wait for %d seconds" % wait) time....
5,342,610
def asisted_singer_label(label_path): """ Assisted parser of labels :param label_path: CSV file containing labels exported by parse_dataset.py script :return: """ df = pd.read_csv(label_path) unique_artists = list(set(df['artist'])) unique_labels = [] for artist in unique_artists: ...
5,342,611
def parse_title(line): """if this is title, return Tuple[level, content], @type line: str @return: Optional[Tuple[level, content]] """ line = line.strip() if not line.startswith('#'): return None sharp_count = 0 for c in line: if c == '#': sharp_count += 1 ...
5,342,612
def issubtype(cls: type, clsinfo: type) -> bool: """ Return whether ``cls`` is a subclass of ``clsinfo`` while also considering generics. :param cls: the subject. :param clsinfo: the object. :return: True if ``cls`` is a subclass of ``clsinfo`` considering generics. """ info_generic_type...
5,342,613
def delete_status(id): """Delete an existing status The status to be deleted should be posted as JSON using 'application/json as the content type. The posted JSON needs to have 2 required fields: * user (the username) * api_key An example of the JSON:: { "user": "r1ck...
5,342,614
def process_data(data): """ Change labels, group by planner and format for latex.""" data = data.replace( { "grid_run_1": "Grid", "prm_run_1": "PRM A", "prm_run_2": "PRM B", "prm_run_3": "PRM C", } ) data = data.rename( columns={"n...
5,342,615
def detect_outlier(TS, samples_wind=60, order=3): """Find outliers in TS by interpolate one sample at a time, measure diff. between rec. sample and interpolated, and getting the peaks in the int diff across recording. Parameters ------------- TS : array (x, y) x n_samples Times ser...
5,342,616
def postprocess(backpointers, best_tag_id): """Do postprocess.""" best_tag_id = best_tag_id.asnumpy() batch_size = len(best_tag_id) best_path = [] for i in range(batch_size): best_path.append([]) best_local_id = best_tag_id[i] best_path[-1].append(best_local_id) for b...
5,342,617
def carnatic_string_to_ql_array(string_): """ :param str string_: A string of carnatic durations separated by spaces. :return: The input string converted to a quarter length array. :rtype: numpy.array. >>> carnatic_string_to_ql_array('oc o | | Sc S o o o') array([0.375, 0.25 , 0.5 , 0.5 , 1.5 , 1. , 0.25 , ...
5,342,618
async def test_button_error( hass: HomeAssistant, init_integration: MockConfigEntry, mock_wled: MagicMock, ) -> None: """Test error handling of the WLED buttons.""" mock_wled.reset.side_effect = WLEDError with pytest.raises(HomeAssistantError, match="Invalid response from WLED API"): aw...
5,342,619
def draw_fixations(fixations, dispsize, imagefile=None, durationsize=True, durationcolour=True, alpha=0.5, savefilename=None): """Draws circles on the fixation locations, optionally on top of an image, with optional weigthing of the duration for circle size and colour arguments fixations - a list of fixation...
5,342,620
def makedirs(path): """Replacement for Python's built-in "mkdirs" from the os module This version of makedirs makes sure that all directories created are world-writable. This is necessary because the MAR CC Dserver writes from a different computer with a different user id (marccd=500) than then user...
5,342,621
def get_examples(fpath, doc_dir, max_seq_len=-1, max_sent_num=200, sent_level=True): """ Get data from tsv files. Input: fpath -- the file path. Assume number of classes = 2 Output: ts -- a list of strings (each contain the text) ys -- float32 np array (num_exam...
5,342,622
def login_redirect(request: HttpRequest) -> HttpResponse: """ Redirects the user to the Strava authorization page :param request: HttpRequest :return: HttpResponse """ strava_uri = get_strava_uri() return redirect(strava_uri)
5,342,623
def f(p, x): """ Parameters ---------- p : list A that has a length of at least 2. x : int or float Scaling factor for the first variable in p. Returns ------- int or float Returns the first value in p scaled by x, aded by the second value in p. Examples ...
5,342,624
def get_contributors_users(users_info) -> list: """ Get the github users from the inner PRs. Args: users_info (list): the response of get_inner_pr_request() Returns (list): Github users """ users = [] for item in users_info: user = item.get('login') github_profile =...
5,342,625
def euler2mat(roll, pitch, yaw): """ Create a rotation matrix for the orientation expressed by this transform. Copied directly from FRotationTranslationMatrix::FRotationTranslationMatrix in Engine/Source/Runtime/Core/Public/Math/RotationTranslationMatrix.h ln 32 :return: """ angles = _TORAD ...
5,342,626
def remove_articles(string: str, p: float = 1.0) -> str: """Remove articles from text data. Matches and removes the following articles: * the * a * an * these * those * his * hers * their with probability p. Args: string: text p: probability of removin...
5,342,627
def _remove_overlaps(in_file, out_dir, data): """Remove regions that overlap with next region, these result in issues with PureCN. """ out_file = os.path.join(out_dir, "%s-nooverlaps%s" % utils.splitext_plus(os.path.basename(in_file))) if not utils.file_uptodate(out_file, in_file): with file_tra...
5,342,628
def _get_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments ...
5,342,629
def test_repr(functional_group): """ Test :meth:`.FunctionalGroup.__repr__`. Parameters ---------- functional_group : :class:`.FunctionalGroup` The functional group whose representation is tested. Returns ------- None : :class:`NoneType` """ other = eval(repr(function...
5,342,630
def test_smooth_n_pt_9_units(): """Test the smooth_n_pt function using 9 points with units.""" hght = np.array([[5640., 5640., 5640., 5640., 5640.], [5684., 5676., 5666., 5659., 5651.], [5728., 5712., 5692., 5678., 5662.], [5772., 5748., 5718., 5697., ...
5,342,631
def pairs_of_response(request): """pairwise testing for content-type, headers in responses for all urls """ response = requests.get(request.param[0], headers=request.param[1]) print(request.param[0]) print(request.param[1]) return response
5,342,632
def load_gtdb_tax(infile, graph): """ loading gtdb taxonomy & adding to DAG """ # url or file download/open try: inF = gtdb2td.Utils.get_url_data(infile) except (OSError,ValueError) as e: try: ftpstream = urllib.request.urlopen(infile) inF = csv.re...
5,342,633
def setup(): """ The setup wizard screen """ if DRIVER is True: flash(Markup('Driver not loaded'), 'danger') return render_template("setup.html")
5,342,634
def ldns_pkt_set_edns_extended_rcode(*args): """LDNS buffer.""" return _ldns.ldns_pkt_set_edns_extended_rcode(*args)
5,342,635
def sim_spiketrain_poisson(rate, n_samples, fs, bias=0): """Simulate spike train from a Poisson distribution. Parameters ---------- rate : float The firing rate of neuron to simulate. n_samples : int The number of samples to simulate. fs : int The sampling rate. Ret...
5,342,636
def getHausdorff(labels, predictions): """Compute the Hausdorff distance.""" # Hausdorff distance is only defined when something is detected resultStatistics = sitk.StatisticsImageFilter() resultStatistics.Execute(predictions) if resultStatistics.GetSum() == 0: return float('nan') # E...
5,342,637
def _filesizeformat(file_str): """ Remove the unicode characters from the output of the filesizeformat() function. :param file_str: :returns: A string representation of a filesizeformat() string """ cmpts = re.match(r'(\d+\.?\d*)\S(\w+)', filesizeformat(file_str)) return '{} {}'.format...
5,342,638
def radec_to_lb(ra, dec, frac=False): """ Convert from ra, dec to galactic coordinates. Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by Bradley W. Carroll, Dale A. Ostlie (Eq. 24.16 onwards). NOTE: This function is not as accurate as the astropy conversion, nor as the J...
5,342,639
def status_codes_by_date_stats(): """ Get stats for status codes by date. Returns: list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks. """ def date_counter(queryset): return dict(Counter(map( lambda dt: ms_since_epoch(datetime.combine( ...
5,342,640
def do_server_monitor(client, args): """ Show monitor info of a virtual server """ guest = client.guests.get_specific(args.id, 'monitor', command=args.cmd) print(guest['results'])
5,342,641
def r8_y1x ( t ): """ #*****************************************************************************80 # #% R8_Y1X evaluates the exact solution of the ODE. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 30 August 2010 ...
5,342,642
def test_lockedmove_vs(): """Make sure lockedmove is handled properly.""" dragonite = Pokemon(name="dragonite", moves=["outrage"]) aggron_target = Pokemon(name="aggron", moves=["recover"]) outrage = VolatileStatusMove(**MOVE_DATA["outrage"]) outrage.apply_volatile_status(dragonite, aggron_target) ...
5,342,643
def urlhause(query): """ The URLHause us a very nice threat feed site, which can be used to see which website delivers which malware. That being said, they only provide API to download csv dumps of their registered malicious domain and currently the API can not be used to query for information directly. While downl...
5,342,644
def verdi_process(): """Inspect and manage processes."""
5,342,645
def clear_channels(header, channels=None): """Utility function for management of channel related metadata.""" bitmask = BitmaskWrapper(header['channel_mask']) if channels is not None: _verify_channels(channels) bitmask.clear([channel-1 for channel in channels]) else: bitmask.clea...
5,342,646
def get_target_model_ops(model, model_tr): """Get operations related to the target model. Args: * model: original model * model_tr: target model Returns: * init_op: initialization operation for the target model * updt_op: update operation for the target model """ init_ops, updt_ops = [], [] for v...
5,342,647
def gotit(): """ function to react to silver token found """ R.grab() print("Gotcha!") turn(25, 2.35) drive(20,1) R.release() drive(-20,2) turn(-25,2.35)
5,342,648
def next_count(start: int = 0, step: int = 1): """Return a callable returning descending ints. >>> nxt = next_count(1) >>> nxt() 1 >>> nxt() 2 """ count = itertools.count(start, step) return functools.partial(next, count)
5,342,649
def show_locale(key_id: int): """Get a locale by ID""" return locales[key_id]
5,342,650
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() update_db() DB.session.commit() records = Record.query.all() return render_template('aq_base.html', title='Refreshed!', records=records)
5,342,651
def get_similar_taxa(): """ Get a list of all pairwise permutations of taxa sorted according to similarity Useful for detecting duplicate and near-duplicate taxonomic entries :return: list of 2-tuples ordered most similar to least """ taxa = Taxon.objects.all() taxon_name_set = set([t.name f...
5,342,652
def make_img_id(label, name): """ Creates the image ID for an image. Args: label: The image label. name: The name of the image within the label. Returns: The image ID. """ return json.dumps([label, name])
5,342,653
def col2rgb(color): """ Convert any colour known by matplotlib to RGB [0-255] """ return rgb012rgb(*col2rgb01(color))
5,342,654
def quick_select_median(values: List[tuple], pivot_fn=random.choice, index=0) -> tuple: """ Implementation quick select median sort :param values: List[tuple] :param pivot_fn: :param index: int :return: tuple """ k = len(values) // 2 return quick_select(values, k, pivot_fn, index=ind...
5,342,655
def get_admin_token(key, previous=False): """Returns a token with administrative priviledges Administrative tokens provide a signature that can be used to authorize edits and to trigger specific administrative events. Args: key (str): The key for generating admin tokens previous (bool,...
5,342,656
def modSymbolsFromLabelInfo(labelDescriptor): """Returns a set of all modiciation symbols which were used in the labelDescriptor :param labelDescriptor: :class:`LabelDescriptor` describes the label setup of an experiment :returns: #TODO: docstring """ modSymbols = set() for labelSt...
5,342,657
def vulnerability_weibull(x, alpha, beta): """Return vulnerability in Weibull CDF Args: x: 3sec gust wind speed at 10m height alpha: parameter value used in defining vulnerability curve beta: ditto Returns: weibull_min.cdf(x, shape, loc=0, scale) Note: weibull_min.pdf...
5,342,658
def _find_best_deals(analysis_json) -> tuple: """Finds the best deal out of the analysis""" best_deals = [] for deal in analysis_json: if _get_deal_value(analysis_json, deal) > MINIMUM_ConC_PERCENT: best_deals.append(deal) best_deals.sort(key=lambda x: _get_deal_value(analysis_jso...
5,342,659
def deserialize(s_transform): """ Convert a serialized :param s_transform: :return: """ if s_transform is None: return UnrealTransform() return UnrealTransform( location=s_transform['location'] if 'location' in s_transform else (0, 0, 0), rotation=s_transform['rotatio...
5,342,660
def game(key): """Handles key events in the game""" direction = DIRECTIONS.get(key) if direction: move(maze, direction, "player")
5,342,661
def spectrum(x, times=None, null_hypothesis=None, counts=1, frequencies='auto', transform='dct', returnfrequencies=True): """ Generates a power spectrum from the input time-series data. Before converting to a power spectrum, x is rescaled as x - > (x - counts * null_hypothesis) / sqrt(co...
5,342,662
def CalculatePercentIdentity(pair, gap_char="-"): """return number of idential and transitions/transversions substitutions in the alignment. """ transitions = ("AG", "GA", "CT", "TC") transversions = ("AT", "TA", "GT", "TG", "GC", "CG", "AC", "CA") nidentical = 0 naligned = 0 ndifferent...
5,342,663
def render_ellipse(center_x, center_y, covariance_matrix, distance_square): """ Renders a Bokeh Ellipse object given the ellipse center point, covariance, and distance square :param center_x: x-coordinate of ellipse center :param center_y: y-coordinate of ellipse center :param covariance_matrix: Nu...
5,342,664
def flow_to_image(flow): """Transfer flow map to image. Part of code forked from flownet. """ out = [] maxu = -999. maxv = -999. minu = 999. minv = 999. maxrad = -1 for i in range(flow.shape[0]): u = flow[i, :, :, 0] v = flow[i, :, :, 1] idxunknow = (abs(u...
5,342,665
def test_api_homeassistant_stop(hassio_handler, aioclient_mock): """Test setup with API HomeAssistant stop.""" aioclient_mock.post( "http://127.0.0.1/homeassistant/stop", json={'result': 'ok'}) assert (yield from hassio_handler.stop_homeassistant()) assert aioclient_mock.call_count == 1
5,342,666
def joint_dataset(l1, l2): """ Create a joint dataset for two non-negative integer (boolean) arrays. Works best for integer arrays with values [0,N) and [0,M) respectively. This function will create an array with values [0,N*M), each value representing a possible combination of values from l1 and l...
5,342,667
def dump_refs(args): """ Output a list of all repositories along with their checked out branches and their hashes. """ man = load_manifest() first = True for (name, project) in man.projects.items(): if not first: print() first = False print("Project %s:" % name) repo = project.git_repo ...
5,342,668
def parse(asset, image_data, product): """ Parses the GEE metadata for ODC use. Args: asset (str): the asset ID of the product in the GEE catalog. image_data (dict): the image metadata to parse. product (datacube.model.DatasetType): the product information from the ODC index. Retur...
5,342,669
def install_conan_dependencies(build_type: str, *additional_args: Iterable[str]): """Install dependent Conan packages. Args: build_type (str): Type of build. additional_args (List[str]): Additional command line arguments. """ build_path = make_build_path(build_type) os.makedirs(bu...
5,342,670
def scale(pix, pixMax, floatMin, floatMax): """ scale takes in pix, the CURRENT pixel column (or row) pixMax, the total # of pixel columns floatMin, the min floating-point value floatMax, the max floating-point value scale returns the floating-point value that corresp...
5,342,671
def most_distinct(df): """ :param df: data frame :return: """ headers = df.columns.values dist_list = [] # list of distinct values per list for idx, col_name in enumerate(headers): col = df[col_name] col_list = col.tolist() # if len(col_list) == 0: # dist...
5,342,672
def walk_trees(store, tree_ids,prune_identical=False): """Recursively walk all the entries of N trees. Iteration is depth-first pre-order, as in e.g. os.walk. :param store: An ObjectStore for looking up objects. :param trees: iterable of SHAs for N trees :param prune_identical: If True, identical ...
5,342,673
def make_set(value): """ Takes a value and turns it into a set !!!! This is important because set(string) will parse a string to individual characters vs. adding the string as an element of the set i.e. x = 'setvalue' set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'} make_set(x) ...
5,342,674
def import_from_file(pipe, src): """ Basic example how to import from file or file-like object opened in binary mode """ if not hasattr(src, 'read'): src = open(src, 'rb') shutil.copyfileobj(src, pipe, 65535)
5,342,675
def _get_parent_cache_dir_url(): """Get parent cache dir url from `petastorm.spark.converter.parentCacheDirUrl` We can only set the url config once. """ global _parent_cache_dir_url # pylint: disable=global-statement conf_url = _get_spark_session().conf \ .get(SparkDatasetConverter.PARENT_...
5,342,676
def make_variable(data, variances=None, **kwargs): """ Make a Variable with default dimensions from data while avoiding copies beyond what sc.Variable does. """ if isinstance(data, (list, tuple)): data = np.array(data) if variances is not None and isinstance(variances, (list, tuple)): ...
5,342,677
def print_emails(emails: list): """ Prints the email info for emails in a list. :param emails: A list of emails to print. """ counts = collections.Counter([email.subject for email in emails]) size = bytesto(sum(email.size for email in emails), "m") for email in emails: print(f"{emai...
5,342,678
def run_energy(save_figure: bool = False): """Run energy workflow.""" # define a molecule mol = Molecule() # make it by hand mol.add_atom("C", 0, 0, 0) mol.add_atom("O", 1.2, 0, 0) # or read it from existing file # mol.readXYZfile('CO.xyz') # get a DFTGWBSE object dft = DFTGWB...
5,342,679
def create_subtasks(task, qs, chunk_size, countdown=None, task_args=None): """ Splits a task depending on a queryset into a bunch of subtasks of the specified chunk_size, passing a chunked queryset and optional additional arguments to each.""" if task_args is None: task_args = () job = ...
5,342,680
def gh_event_repository(db, repo, payload, actor): """Process GitHub RepositoryEvent (with commits) https://developer.github.com/v3/activity/events/types/#repositoryevent :param db: Database to store repository data :type db: ``flask_sqlalchemy.SQLAlchemy`` :param repo: Repository related to event...
5,342,681
def dt642epoch(dt64): """ Convert numpy.datetime64 array to epoch time (seconds since 1/1/1970 00:00:00) Parameters ---------- dt64 : numpy.datetime64 Single or array of datetime64 object(s) Returns ------- time : float Epoch time (seconds since 1/1/1970 00:00:00) ...
5,342,682
def rpn_losses(anchor_labels, anchor_boxes, label_logits, box_logits): """ Calculate the rpn loss for one FPN layer for a single image. The ground truth(GT) anchor labels and anchor boxes has been preprocessed to fit the dimensions of FPN feature map. The GT boxes are encoded from fast-rcnn paper ht...
5,342,683
def calc_val_resize_value(input_image_size=(224, 224), resize_inv_factor=0.875): """ Calculate image resize value for validation subset. Parameters: ---------- input_image_size : tuple of 2 int Main script arguments. resize_inv_factor : float Resize inv...
5,342,684
def fetch_http(url, location): """ Return a `Response` object built from fetching the content at a HTTP/HTTPS based `url` URL string saving the content in a file at `location` """ r = requests.get(url) with open(location, 'wb') as f: f.write(r.content) content_type = r.headers.ge...
5,342,685
def youtube_dl(url, uid): """ Modd i'r defnyddwyr defnyddio dolen yn lle ffeiliau. Lawrlwytho ffeil o gwasanaeth streamio fel YouTube fel wav efo enw uuid4 rhedeg transcribe_audio() yn syth """ cmd = "youtube-dl -x --audio-format wav " + url + \ " -o data/" + uid + ".wav" os.system(...
5,342,686
def mat_normalize(mx): """Normalize sparse matrix""" rowsum = np.array(mx.sum(1)) r_inv = np.power(rowsum, -0.5).flatten() r_inv[np.isinf(r_inv)] = 0. r_mat_inv = sp.diags(r_inv) mx = r_mat_inv.dot(mx).dot(r_mat_inv) return mx
5,342,687
def runjcast(args): """ main look for jcast flow. :param args: parsed arguments :return: """ # Get timestamp for out files now = datetime.datetime.now() write_dir = os.path.join(args.out, 'jcast_' + now.strftime('%Y%m%d%H%M%S')) os.makedirs(write_dir, exist_ok=True) # Main lo...
5,342,688
def user_syntax_error(e, source_code): """Returns a representation of the syntax error for human consumption. This is only meant for small user-provided strings. For input files, prefer the regular Python format. Args: e: The SyntaxError object. source_code: The source code. Returns: A multi-li...
5,342,689
def check_comment(comment, changed): """ Check the commit comment and return True if the comment is acceptable and False if it is not.""" sections = re.match(COMMIT_PATTERN, comment) if sections is None: print(f"The comment \"{comment}\" is not in the recognised format.") else: indic...
5,342,690
def test_remove_group_dependency(job_scripts): """add and remove jobgroup dependency.""" jg1 = pyani_jobs.JobGroup("1d-sweep", "cat", arguments=job_scripts[0].params) jg2 = pyani_jobs.JobGroup("2d-sweep", "myprog", arguments=job_scripts[1].params) jg2.add_dependency(jg1) dep = jg2.dependencies[0] ...
5,342,691
def GetBankTaskSummary(bank_task): """ Summarizes the bank task params: bank_task = value of the object of type bank_task_t returns: String with summary of the type. """ format_str = "{0: <#020x} {1: <16d} {2: <#020x} {3: <16d} {4: <16d} {5: <16d} {6: <16d} {7: <16d}" out_string = forma...
5,342,692
def deploy(environment): """Deploy to defined environment.""" token = get_token() if not token: click.echo("no token found - running configure") configure() token = get_token() click.confirm(f"Are you sure you want to deploy {environment}?", abort=True) if environment == "p...
5,342,693
def main(): """Main Function Refrences all other functions and accepts user input""" db.connect() menu.main_menu() while True: command_main = input("Please choose a menu: ").rstrip() if command_main == "script": menu.display_menu() while True: comm...
5,342,694
def angle(o1,o2): """ Find the angles between two DICOM orientation vectors """ o1 = np.array(o1) o2 = np.array(o2) o1a = o1[0:3] o1b = o1[3:6] o2a = o2[0:3] o2b = o2[3:6] norm_a = np.linalg.norm(o1a) * np.linalg.norm(o2a) norm_b = np.linalg.norm(o1b) * np.linalg.norm...
5,342,695
def get_project_id_v3(user_section='user'): """Returns a project ID.""" r = authenticate_v3_config(user_section, scoped=True) return r.json()["token"]["project"]["id"]
5,342,696
def get_platform_arches(pkgs_info, pkg_name): """.""" package_info = get_package_info(pkgs_info, pkg_name) platforms_info = package_info.get('platforms', {}) platform_arches = platforms_info.get('arches', []) return platform_arches
5,342,697
def get_preview_images_by_proposal(proposal): """Return a list of preview images available in the filesystem for the given ``proposal``. Parameters ---------- proposal : str The five-digit proposal number (e.g. ``88600``). Returns ------- preview_images : list A list of...
5,342,698
def unformat_number(new_str: str, old_str: Optional[str], type_: str) -> str: """Undoes some of the locale formatting to ensure float(x) works.""" ret_ = new_str if old_str is not None: if type_ in ("int", "uint"): new_str = new_str.replace(",", "") new_str = new_str.replace...
5,342,699