content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from pandas import read_fwf def load_dataframe(fobj, compression='gzip'): """Given an open file for `hip_main.dat.gz`, return a parsed dataframe. If your copy of ``hip_main.dat`` has already been unzipped, pass the optional argument ``compression=None``. """ try: except ImportError: ...
662738a84f315761d0e2d27f98a15df7c83eb325
3,617,600
import os import sys def generate_passphrase(passphrase_length, word_list): """Generate the passphrase string. For each word, read 2 bytes from the kernel-space CSPRNG via ``os.urandom`` and convert them to an integer which serves as a list index. A list of 65,536 words is probably enough so we don'...
dc6aa86392f1c49f47c6f169ec98ef5e555f9451
3,617,601
def enum(*sequential, **named): """ Handy way to fake an enumerated type in python. Example ------- >>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three' Source ------ "http://stackoverflow.com/questions/36...
3bcce013c8111fccda6e3dd08d40a0128fcdb3d8
3,617,602
def get_granted_queue_consumer_config(group_id, topic, version, cluster_type, is_pattern): """ 获取已经授权的producer记录 :param group_id: 需要授权的topic :param topic: queue队列 topic :param version 版本号 :param cluster_type 集群类型 :param is_pattern 是否为正则表示的topic :return: {list} db中对应的完整记录列表 """ if...
954b392f5b8c75b286ef771434c2d28c5df7afa8
3,617,603
def getUnitType(index): """ Returns the <index>th UnitType. """ try: return UNITS[index] except IndexError: BugUtil.error("ReligionUtil - invalid unit type %i", index) return None
70ef993160698031ef438c473e2f125e8f69997d
3,617,604
def get_account_history(): """ get_account_history """ account = request.args.get('account', None) if account is None: return jsonify({}) token = request.args.get('token', None) limit = request.args.get('limit', 100) offset = request.args.get('offset', 0) hist_type = request...
5b386c8c7eb1fe5943f8a04c7b81b97f33b507d6
3,617,605
def token_view(request, token): """Show form to let user set password. """ i = get_object_or_404(Invitation, token=token) if i.is_expired(): raise Http404 if request.method == 'GET': try: user = User.objects.get(email=i.accepter) if user.is_active is True: ...
998ced088759d44974c6275861b174e147df7f9e
3,617,606
def _match_by_tag(inp, params): """Match joints by tags. Use Munkres algorithm to calculate the best match for keypoints grouping. Note: number of keypoints: K max number of a image: M L: 2 if use flip test else 1 Args: inp(tuple): tag_k (np.ndarray[KxMxL]):...
f04dcf485d2b24b8cda4395d45ff6a03337aa96b
3,617,607
def mean_(x, dimension, track_types = True, **kwargs): """Calculate the mean of a set of values. Parameters ---------- x : :obj:`xarray.DataArray` The data cube to be reduced. dimension : :obj:`str` Name of the dimension to apply the reduction function to. track_types : :obj:`bool` ...
f5c76000736139eb5ff71b54fffede14e0b62760
3,617,608
import six import yaml def UpdateThresholdRules(ref, args, req): """Add threshold rule to budget.""" messages = GetMessagesModule() client = apis.GetClientInstance('billingbudgets', 'v1beta1') budgets = client.billingAccounts_budgets get_request_type = messages.BillingbudgetsBillingAccountsBudgetsGetRequest...
9f4bde1b600719f454a66d7d0f3b400c3e4d2fbe
3,617,609
from typing import Callable import json def synonym( string: str, threshold: float = 0.5, top_n=5, cleaning=augmentation_textcleaning, **kwargs ): """ augmenting a string using synonym, https://github.com/huseinzol05/Malaya-Dataset#90k-synonym Parameters ---------- string: str...
225dbefe6fa1e39a2bf8141f2167d0c13d49f590
3,617,610
from pathlib import Path from typing import Tuple def get_path(dir_path: Path, dir_name: str = "movie", counting_format: str = "%03d", file_pattern: str = "") -> Tuple[Path, int, str, str]: """ Looks up all directories with matching dir_name and counting format in di...
4e508e52ebb7768bbdad9f849ffff55ce476ac74
3,617,611
import typing import textwrap import yaml def _update_yaml_write_lines( lines: typing.List[str], configs: typing.Dict[str, typing.Any], block: YamlBlock, parent: YamlBlock, ) -> typing.List[str]: """ Replace the specified block within the YAML file lines object with the new configs. This ...
f9e70015c2622cf09ef07b185836ec8fec237df9
3,617,612
import random def get_manufacturerid() -> str: """ Get manufacturer id from MANUFACTURER_ID list :return: id """ return MANUFACTURER_ID["manufacturer_" + str(random.randint(0, N_MANUFACTURERS - 1))]
cef941f409cbdadd168c03ea542331ebf2d7f803
3,617,613
import copy def _get_args_for_wrapping(wrapped, new_sig, func_name, doc, qualname, module_name, attrs): """ Internal method used by @wraps and create_wrapper :param wrapped: :param new_sig: :param func_name: :param doc: :param qualname: :param module_name: :param attrs: :retur...
600794f744c2afe123656f82f66fba5645590ccf
3,617,614
def generate_next_step(flat_model, model_curr_conf): """ Generate next conf to try """ todo_quants = [deepcopy(model_curr_conf) for _ in range(len(flat_model))] for index, conf in enumerate(todo_quants): conf[index] -=1 todo_quants = list(filter( lambda x: not 1 in x ,todo_quan...
130ebe2a2ca18b209950141303242c43f3534a62
3,617,615
def build_train_op(loss): """Sets up the training Ops. Args: loss: Loss tensor, from build_loss(). Returns: train_op, global_step, learning_rate. """ global_step = tf.Variable(0, name='global_step', trainable=False) learning_rate = tf.train.exponential_decay(INIT_LEARNING_RATE, glo...
a6dff882ff455732ff9fff1756ef1407a44997af
3,617,616
import os def get_local_apps(category=CATEGORY_ALL): """Returns a list of apps that can be found in the apps folder""" apps = [App(folder_name) for folder_name in os.listdir("apps") if filesystem.is_dir("apps/" + folder_name)] return [app for app in apps if app.matches_category(category)]
84e6c15cfcde25e445bdb3cccb3693b8f5d4016d
3,617,617
import os, random def getRandom(): """ Download a random PDB and return the path name. Returns path name of downloaded file """ URL = "ftp://ftp.rcsb.org/pub/pdb/data/structures/all/pdb/" pdblines = os.popen("ncftpls %s" % URL).readlines() pdbline = pdblines.join() pdbline ...
c1cea0d937cd5165c7ebd3d46cf4764e28d7748b
3,617,618
def logistic_sigmoid(x, a): """Computes so-called logistic curve, a sigmoidal function used in modelling population growth etc. In this implementation, the parameter a regulates the slope or 'growth rate' of the sigmoid's rising portion. When a=0, the function collapses to the identity function y=x. ...
5984767c317cb40629097fd8941eb54d0e8c4717
3,617,619
def first_deriv_partials(dts, q, n_segments=1, n_simpson_intervals_per_segment=2, order=4): """ This method provides the Jacobian of a temporal first derivative A "segment" is defined as a portion of the quantity vector q with a constant delta t (or delta x, etc). This routine is designed to be use...
a107994d5496de3c53072ffab720be88fd269ab3
3,617,620
import os def processed_file_path(source_path, asset_roots, target_directory, target_extension): """Take the path to an asset and convert it to target path. Args: source_path: Path to the source file. asset_roots: List of potential root directories each input file. target_dire...
749bda062d90dae1763d802f2a557d50682e8a4d
3,617,621
def zoom(scale, center, group): """zoom(scale, center, group) -> float Change the zoom and pan of a group's display. The scale argument is the new zoom factor. If the scale is given, but not the center, the zoom is set to that factor and the view is positioned so the cursor is pointing at the same place it was bef...
fe6c5cafed738d5e53a043fa86e66b22cab0a6af
3,617,622
def _border_type(player, tile, adj_tile): """ Used by map drawing routine. Checks if 'adj_tile' is connected to and can be seen from 'tile' :param text_game_maker.player.player.Player player: player object :param text_game_maker.tile.tile.Tile tile: first tile :param text_game_maker.tile.tile.T...
b8f27e11d02f134a42b1eacc45164fa9602ffddc
3,617,623
import argparse def parse_args(): """ Load command line args """ parser = argparse.ArgumentParser() parser.add_argument('--inf', metavar="<file>", help=('Credible set json'), type=str, required=True) parser.add_argument('--outf', metavar="<str>", help=("Output"), type=str, required=True) args = pa...
4d07ed1993759bbce97f280a6cf1d3b869482986
3,617,624
def _log_calculate(beta): # pragma: no cover """ TODO: Replace this with more efficient algorithm alpha in GF(p^m) and generates field beta in GF(p^m) gamma = log_primitive_element(beta), such that: alpha^gamma = beta """ # Naive algorithm result = 1 for i in range(0, ORDER - 1): ...
ac974cc88d78acb7320e22448e9a4ba6c6b10941
3,617,625
def partion(arr, start, end): """ 将元素以基准元素进行分区,基准元素左边都小于等于它,右边都大于等于他 :param arr: :param start: :param end: :return: """ key = arr[start] while start < end: while start < end and arr[end] >= key: end -= 1 swap(arr, start, end) while start < end ...
d71b568fd2d07edbdb836267040e718a6dba239f
3,617,626
def map_fbs_flows(fbs, from_fba_source, v, **kwargs): """ Identifies the mapping file and applies mapping to fbs flows :param fbs: flow-by-sector dataframe :param from_fba_source: str Source name of fba list to look for mappings :param v: dictionary, The datasource parameters :param kwargs: incl...
4995566bb1538b5c6b706850075b99d3b0563442
3,617,627
from pathlib import Path def _parse_collection_dir(directory: Path) -> list: """ Parse Ansible collection :param directory: Collection directory :return: List of parsed Ansible tasks that are prepared for scanning """ parsed_collection = [] for role in (list((directory / "roles").rglob("*"...
4238848fd6856efcbd1cd8a722567c4b11490475
3,617,628
def adda_hyperparams(lr_target=1e-5, lr_discriminator=1e-4, wd=5e-5, scheduler=False): """ Return a dictionary of hyperparameters for the ADDA algorithm. Default parameters are the best ones as found through a hyperparameter search. Arguments: ---------- lr_target: float Learning rate f...
af7cf7402485f4af4fd7c6a1a2ffb5fcd753cf93
3,617,629
import logging import pathlib def get_system_library_path(): """return the path to the system Photos library as string""" """ only works on MacOS 10.15 """ """ on earlier versions, returns None """ _, major, _ = _get_os_version() if int(major) < 15: logging.debug( f"get_system_...
399a4f2da70ebf72f4134f5e890e3dd1bd5adce2
3,617,630
import urllib import sys import json def testServerAPIAddCreator(serverURL): """ Create a creator and listen for a 200 response Note the UUID """ method = moduleName + '.' + 'testServerAPIAddCreator' Graph.logQ.put( [logType , logLevel.DEBUG , method , "entering"]) testResult = Tru...
73e1a5c57e8935a4b4a016b761bbc104b7e0fe29
3,617,631
import os def calicoupgrade(command, prompt_resp='yes'): """ Convenience function for abstracting away calling the calicoctl-upgrade command. :param command: The calicoctl-upgrade command line parms as a single string. :return: The output from the command with leading and trailing whitespac...
1e3c0d07bb6169fc8af35274075b7ca860c25a2b
3,617,632
import numpy def get_topic_terms(model, topicid, topn, id2token): """ Return a list of `(word_id, probability)` 2-tuples for the most probable words in topic `topicid`. Only return 2-tuples for the topn most probable words (ignore the rest). """ topic = model.state.get_lambda()[topicid] to...
b0ca1fd35fb7e8ce89a497c37bfd82b9dd884027
3,617,633
def gmv(cov): """ Returns the weights of the Global Minimum Vol portfolio given covariace matrix """ n = cov.shape[0] return msr(0, np.repeat(1, n), cov)
24b1362dad13be80e13d6caecc470907f4d685a6
3,617,634
import json def placement_rest_api(): """Perform placement optimization after validating the request and fetching policies Make a call to the call-back URL with the output of the placement request. Note: Call to Conductor for placement optimization may have redirects, so account for them """ reque...
dd850c802d86dcfa343abfded8b109b881fecde2
3,617,635
def ecef_to_teme(ecef: np.array, jd: float, t_tt: float, lod: float, xp: float, yp: float, eqeterms: int): """ Earth-Centered, Earth-Fixed (ECEF) to True Equator, Mean Equinox frame coordinate system conversion. TEME frame is used for the NORAD two-line elements. TODO: Vectorize Args: ecef (n...
4aa95c59f3778009e37b77d243625feb1e51ddcd
3,617,636
def account(): """Account and update account route """ form = UpdateAccountForm() if form.validate_on_submit(): # if form.picture.data: # picture_file = save_picture(form.picture.data) # current_user.image_file = form.picture.data current_user.image_file = form.pictur...
f8e4c90e525e5f3d05b8afcf9a719044853774a1
3,617,637
import warnings def keep_corelated_data(data: DataFrameOrArrayGeneric, threshold: float = 0.5) -> DataFrameOrArrayGeneric: """Remove columns that are not corelated enough to predicted columns. Predicted column is supposed to be 0. Args: data (DataFrameOrArrayGeneric): Time series data. thresh...
3d082b026641aedabc26d071bbed6f7be3810267
3,617,638
def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pool...
8e38f5d72a35ee206aada709a93152db04a232f7
3,617,639
def _find_gd_env_buf(gd_address: int, gd_mem: bytes, new_gd_offset: int, arch): """ Search for `struct global_data.env_buf` in `gd_mem`. If found, the offset of this field into `gd_mem` is returned. Otherwise a `ValueError` is raised. """ search_offset = new_gd_offset + arch.word_size searc...
30fcf142290add7764ee76020570c316b5d84367
3,617,640
import operator def give_recom_result(user_vec, item_vec, userid): """ user lfm model result give fix userid recom result :param user_vec: lfm model result :param item_vec: lfm model result :param userid: user :return: list :[(itemid,score),(itemid1,score1)] """ fix_num = 80 if u...
fe796936916b403523b96627f520f16464eb94e3
3,617,641
import requests def save_file(fileName): """Saves a file of a given name, and returns the json response.""" return requests.post(BASEURL+"documents",headers=HEADS,files={'requester.py': open('requester.py', 'rb')})
12e227f5fa0b5684b34c38c3c6c4543c1bb63ca5
3,617,642
import json def load_label(label_path): """ Loads a label from a JSON file """ with open(label_path, 'r') as label_file: label = json.load(label_file) return label
f6a2873abee024d64ede78f18a96f0a1b95abd0b
3,617,643
def get2d23d(depth, camera_pose, K, pt1, pt2, znear, zfar, width=480, height=640): """ input: depth: image depth(in coordinate) camera_pose: orign camera_pose K: camera intrinsic pt1: orign 2d Point pt2: matchinfg 2d point znear,zfar: depth clip range retur...
dace3aa40b0c9792d005b974347200f4f1812896
3,617,644
import copy def clip_image(image,roi=[],rotangle=0.0,cp=False): """ Clip an image given the roi Parameters: ----------- * roi is a list [c1,r1,c2,r2] = [x1,y1,x2,y2] Note take x as the horizontal image axis index (col index), and y as vertical axis index (row index). Therefore,...
4fe385cf7a15fac59f0a4989970b1523a922deb6
3,617,645
from platypush.backend import Backend from typing import Optional import re def get_backend_name_by_class(backend) -> Optional[str]: """Gets the common name of a backend (e.g. "http" or "mqtt") given its class. """ if isinstance(backend, Backend): backend = backend.__class__ class_name = backen...
13fc8c76df9446ded5c81d7f6db1ae52cc8214e4
3,617,646
import time import torch def run_one_epoch( epoch, loader, model, criterion, optimizer, meters, phase='train', ema=None, scheduler=None, eta=None, epoch_dict=None, single_sample=False): """run one epoch for train/val/test/cal""" t_start = time.time() assert phase in ['train', 'val', 'test', 'cal']...
40aae97098058122fe70acb518bbe531d1928874
3,617,647
import sys def query_yes_no(question, default='yes'): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. "default" is the presumed answer if the user just hits <Enter>. It must be "yes" (the default), "no" or None (meaning ...
4ea47d555bdbfc818067a911246af09cc8c25c61
3,617,648
def load_signature_library(filename): """ Load a signature library from a .sig file. :param filename: input filename :return: instance of `TrieNode`, the root of the signature trie. """ with open(filename, 'rb') as f: buf = f.read() return SignatureLibraryReader().deserialize(buf)
ae8d639473ef0424688d315acc82c67a0b19aa09
3,617,649
def create_random_datetime(start, end): """ This function will return a random datetime between two datetime objects. Borrowed from: http://bit.ly/gM45o4 """ delta = end - start int_delta = (delta.days * 24 * 60 * 60) + delta.seconds random_second = randrange(int_delta) return (sta...
3d71be3bfe19bdbb0c0e4eca7c3a25b15733b3da
3,617,650
import yaml def get_task_config(task_name, is_remote): """Return powercycle task config.""" if is_remote: config_location = powercycle.abs_path( f"{powercycle_constants.REMOTE_DIR}/{POWERCYCLE_TASKS_CONFIG}") else: config_location = powercycle.abs_path(POWERCYCLE_TASKS_CONFIG)...
b03c6d3e3690d543c82b3780b4a8a72861cd11cd
3,617,651
import os def construct_data_reader(run_args): """ Construct Protobuf message for Python data reader. The Python data reader will import this Python file to access the sample access functions. """ module_file = os.path.abspath(run_args.data_module_file) os.environ["DATA_CONFIG"] = os.pa...
5eae0b8c3635a322bd47c1d5fdb73a079d686bc5
3,617,652
def resize(anns, size, output_size): """ Parameters ---------- anns : List[Dict] Sequences of annotation of objects, containing `bbox` of [l, t, w, h]. size : Sequence[int] Size of the original image. output_size : Union[Number, Sequence[int]] Desired output size. If size...
800135ac9d65f55ae96d04fc645ac0d2b913b76c
3,617,653
def get_league_entries_by_summoner(summoner_ids): """ https://developer.riotgames.com/api/methods#!/985/3356 Args: summoner_ids (int | list<int>): the summoner ID(s) to get league entries for Returns: dict<str, list<League>>: the summoner(s)' league entries """ # Can only have ...
7e0b72e8502a59e8ae1728830497988a4e2a88be
3,617,654
def scheduler() -> BackgroundScheduler: """Retrieve the scheduler, intended mostly for unit testing purposes.""" if not _SCHEDULER: raise EngineError("Scheduler is not available") return _SCHEDULER
a45993a2806725fd315fa4d9926adfa6cc50c65d
3,617,655
def toDiscrete(m): """ Args: - m (m,n) : np.array with the occupancy grid Returns: - discrete_m : thresholded m """ y_size, x_size = m.shape m_occupied = np.zeros(m.shape) m_free = np.zeros(m.shape) m_occluded = np.zeros(m.shape) #Handpicked occupied_value = 0.8...
9d045d09a338ccf5dcd4a3a816f5eb0af77fdec6
3,617,656
def has_overlap(x0, xd, y0, yd): """Return True if the ranges overlap. Parameters ---------- x0, y0 : float The min values of the ranges xd, yd : float The widths of the ranges """ return x0 + xd >= y0 and y0 + yd >= x0
6b2a6eff892e28376ed08bf8f60c67f49cdeff44
3,617,657
def _ecdf_vals(data, formal=False): """ Get x, y, values of an ECDF for plotting. Parameters ---------- data : ndarray One dimensional Numpay array with data. formal : bool, default False If True, generate x and y values for formal ECDF (staircase). If False, generate x ...
1bae53fbbeeea51add956e1f4e6e7eb434b7ade0
3,617,658
def add_classification(hw_data, index): """ Add a column at the end of the data to capture wind severity. 0 if wind speed is < 50 1 if wind speed is >= 50 """ sev_wind = hw_data[:, index] >= 50 sev_wind = sev_wind.astype(int) sev_wind = sev_wind.reshape(len(sev_wind), 1) hw_data = ap...
c855043f1ba5b762b7abe347672c924209de648e
3,617,659
from typing import List import re def check_airflow_versions_in_quick_start_guide() -> List[DocBuildError]: """Check that a airflow version is presented in example in the quick start guide for Docker.""" build_errors = [] build_error = assert_file_contains( file_path=f"{DOCS_DIR}/apache-airflow/s...
4b775e8f1d84574e2fea8419fe7bf5065d5c9af0
3,617,660
def load(filename): """ Load nifti1 single or pair from `filename` Parameters ---------- filename : str filename of image to be loaded Returns ------- img : Nifti1Image or Nifti1Pair nifti1 single or pair image instance Raises ------ ImageFileError: if `filenam...
22d10861ea273d18a15f1ff385a8e9ae4a26b288
3,617,661
import attr def test_input_spec_func_1b_except(use_validator): """ the function w/o annotated, but input_spec is used metadata checks raise an error """ @mark.task def testfunc(a): return a my_input_spec = SpecInfo( name="Input", fields=[ ( ...
89c27fcd7fb6443fa950bb31acee4b19f42ce487
3,617,662
import itertools import math def corr1(xydata): """corr1(xydata) -> float Calculate an estimate of the Pearson's correlation coefficient with a single pass over iterable xydata. See also the function corr which may be more accurate but requires multiple passes over the data. >>> data = zip([0, 5...
a22261826b45b2cbbc48cba8c18dbff241865db3
3,617,663
from typing import Tuple def vehicle_capacity_is_respected(solution: Solution) -> Tuple[bool, str]: """ Verifies the vehicle capacities are respected by each tour of the solution. """ problem = Problem() for route in solution.routes: if any(stacks.used_capacity() > problem.capacity ...
0edb3c7d8ab464827e732c19d9d0bb2230872156
3,617,664
import os def find_doctests(suffix, ignore_suffix=None): """Find doctests matching a certain suffix.""" doctest_files = [] # Match doctests against the suffix. if resource_exists('lazr.restfulclient', 'docs'): for name in resource_listdir('lazr.restfulclient', 'docs'): if ignore_su...
778909af84e30b0a62888af0fb74b735c4101b46
3,617,665
def get_pwn_cutoff(ra,dec,rad_search=2., deathline = 1.e34): """ Set cutoff for PWN based on association with pulsars in ATNF catalog Only pulsars with Edot > 1.e34 erg/s are considered, because cutoffs at ~1 TeV should have already been detected :param ra: R.A. of PWN center, deg :param dec: De...
23cb431ff933575ed537e5afbdc1b0df52291749
3,617,666
def _any(series, values): """ Returns the index of rows from series containing any of the given values. Parameters ---------- series : pandas.Series The data to be queried values : list-like The values to be tested Returns ------- index : pandas.index The i...
fb663895f97a2456e144e070ed2b09fd2308a13b
3,617,667
def parse_hhcc(self, data: str, source_mac: str, rssi: float): """HHCC parser""" if len(data) == 13: device_type = "HHCCJCY10" hhcc_mac = source_mac xvalue_1 = data[4:7] xvalue_2 = data[7:10] xvalue_3 = data[10:13] packet_id = data[4:13].hex() (moist, temp...
879591a3f65bea671a186542445b6a605770b4db
3,617,668
def CIFAR10(train=True, path=None): """Thin wrapper around torchvision.datasets.CIFAR10 """ mean, std = [0.491, 0.482, 0.447], [0.247, 0.243, 0.262] normalize = transforms.Normalize(mean=mean, std=std) if train: preproc = [transforms.RandomHorizontalFlip(), transforms.RandomCrop(32, 4)] ...
94e5a57a32786caa49746b754b1d961a6edf1731
3,617,669
def get_app_base_url(): """ Returns the QRadar app proxy prefix. """ return app_qpylib.get_app_base_url()
10fdac9e547ecae4bcdd99be8ef1b0338c264bb7
3,617,670
def create_plotgroup(template_plot_type='bitmap',**params): """ Create a new PlotGroup and add it to the plotgroups list. Convenience function to make it simpler to use the name of the PlotGroup as the key in the plotgroups list. template_plot_type: Whether the plots are bitmap images or curves ...
45cbb35054e44436e191b274ed0f4b88ae49c29a
3,617,671
import hashlib def create_file_map(directory_dict): """ Create a dictionary that maps the hash value of each unique file to a list of the full paths of each copy of that file, even if those files have different names. :param directory_dict: dictionary mapping directory -> list of files :retur...
f977a5a6737ba66965f630f3c230505a1fa442e9
3,617,672
def get_dc_token(region_name=constants.SYSTEM_CONTROLLER_REGION): """Get token for the dcmanager user. Note: Although region_name can be specified, the token used here is a "project-scoped" token (i.e., not specific to the subcloud/region name). A token obtained using one region_name can be re-used acr...
7dd77025b4e4ef40b616466cb233cb67b5b78a24
3,617,673
def calculate_multiplier(aggregate_add_on, value, RC): """ Calculates multiplier depending on Replacement Cost (RC). Returns ------- Multiplier. """ market_value = calculate_market_value(value) if RC > 0: multiplier = 1 return multiplier else: floor = 0.05 ...
710a228bfa3be2bd495aece19308dfff04175e5d
3,617,674
def gen_col_list(num_signals): """ Given the number of signals returns a list of columns for the data. E.g. 3 signals returns the list: ['Time','Signal1','Signal2','Signal3'] """ col_list = ['Time'] for i in range(1, num_signals + 1): col = 'Signal' + str(i) col_list.append(c...
35fe1457c9e256f90f7695e066dcc3202f212d98
3,617,675
def calculate_eigenspaces(kr_max, theta, phi, rad): """Calculate the eigenspaces for the corresponding eigenfrequencies of the sphere Parameters ---------- k_max : float The largest wave number to be included theta : array, float Azimuth angle phi : array, float Elev...
cb835533f65716336d3bc157c70d20a19743077c
3,617,676
def get_sequence(message, message_object_list, sequence_list, sequence=None, index=None): """Returns a sequence i.e. more than 2 messages""" if not sequence: sequence = [] index = 0 if message not in sequence and not any(message in s for s in sequence_list) is True: message[3] = True...
fcbc4b70839fbff9bdac4e30878a2e78ae9c2127
3,617,677
def fit_moffat(arr): """ Params ------ arr (2d np array of odd sizes) Return ------ model (astropy model object) """ # sanity check of input data type if isinstance(arr, ac.kernels.Kernel): arr = arr.array elif isinstance(arr, np.ndarray): pass else: raise Exception("[psfmatch] input needs to be a ...
fd630be0338f52735a457c6a1c6e0dbf4ed68c18
3,617,678
import random import calendar def date_generator( num_dates: int = 1, start_year: int = 1950, end_year: int = current_year, as_list: bool = False, ): """ Function to generate date(s). Specify the number of dates (num_dates, defaults to 1),\n start year (start_year, defaults to 1950),\n ...
888f1d10d29a2767a463ccc1e57f11b3a7a149b9
3,617,679
import requests def test_batch_create(requests_mock): """ Test batch creation """ metadata = Gen3Metadata("https://example.com") metadata_list = [ {"guid": "3c42c819-1dfe-4c3e-8d46-c3ec7eb99bf4", "data": {"foo": "bar"}}, {"guid": "dfa1a1dc-98f4-46be-ba8f-ae9b42b0ee50", "data": {"fo...
e4db6a3771dfcbd803b6f653223fecde9eca302e
3,617,680
def f_isASCII(*args): """f_isASCII(flags_t F, void ?) -> bool""" return _idaapi.f_isASCII(*args)
3fec966271398b648dc1dc5912a3a048e70523b7
3,617,681
def generate_ical_string(key: str) -> str: """generates iCalendar string from testdata and returns it""" c = Calendar() for row in _testdata["iCalendar"].get(key, []): c.events.add( Event( name=row["name"], begin=row["begin"], end=row["end"...
3b8bfb25b8d310eeb80c1c88c69d60cd79b054d3
3,617,682
import os def read_parfile(parfile): """load a pest-compatible .par file into a pandas.DataFrame Parameters ---------- parfile : str pest parameter file name Returns ------- pandas.DataFrame : pandas.DataFrame """ assert os.path.exists(parfile), "Pst.parrep(): parfile no...
e66fe741ae3671fac916d0c15826de5c5c20db03
3,617,683
def int_to_bytes(int_: int, architecture: int = None) -> Bytes: """Get Bytes object :param int_: number integer to convert to Bytes :type: int :param architecture: bytes length :type: int :return: bytes representation :type: Bytes """ bin_ = f'{bin(int_)[2:]}' bytes...
de16ba99ea770c34e6631532882d07f7f55da39f
3,617,684
import sys async def login_headless(root: Root, url: URL) -> None: """ Log into Neuro Platform from non-GUI server environment. URL is a platform entrypoint URL. The command works similar to "neuro login" but instead of opening a browser for performing OAuth registration prints an URL that s...
02c1e5b67dc3054df614c07fe25787bc8d015677
3,617,685
from pybullet_planning.interfaces.env_manager.pose_transformation import all_between from pybullet_planning.interfaces.robots.joint import set_joint_positions, get_custom_limits from pybullet_planning.interfaces.robots.link import get_self_link_pairs, get_moving_links from pybullet_planning.interfaces.debug_utils.debug...
28c829f87c9f7f179559cc19af23683e888ebfce
3,617,686
import builtins def decode_bytes(b): """Tries to decode the bytes using XONSH_ENCODING if available, otherwise using sys.getdefaultencoding(). """ session = getattr(builtins, "__xonsh__", None) env = os_environ if session is None else getattr(session, "env", os_environ) enc = env.get("XONSH_EN...
b82fe9012d5a6f0ba5707bc6f0a04017f87a60cd
3,617,687
import numpy def cropobjects_merge_bbox(cropobjects): """Computes the bounding box of a CropObject that would result from merging the given list of CropObjects.""" # Find extremes. This will define the output cropobject. t, l, b, r = numpy.inf, numpy.inf, -1, -1 for c in cropobjects: t = m...
559e96dda48cb5e733c59a3168032037e0eb06e4
3,617,688
import psutil def starttime(pid): """starttime(pid) -> float Arguments: pid (int): PID of the process. Returns: The time (in seconds) the process started after system boot """ return psutil.Process(pid).create_time() - psutil.boot_time()
eda12b68605eb9602469f74884b812cdeb0abf26
3,617,689
def generate_nested_list(root,nodes): """ Generates a nested list representation of the tree with specified node as root. Useful for checking equality of trees or subtrees. To do: make the nested list form a property that is computed when needed. """ nl = [] if root.children is None: r...
fa75493c8ccc4b720ee404baa9eb3996ce78f3eb
3,617,690
def build_group_objects(env1, admin_api_key1, group_links): """ Builds a list of Group objects that will be used to more quickly check for users in groups """ Groups_List = [] # initialize a python list of objects if not (group_links is None): for i in np.arange(0, np.shape(group_links)[0])...
4438c3aae7e544091bbf463df0cf36a8381c6378
3,617,691
def queryset_filter_tag(queryset, **kwargs): """ template tag which allows queryset filtering. Usage: {% filter_tag books author=author as mybooks %} {% for book in mybooks %} {% endfor %} """ return queryset.filter(**kwargs)
5959285ec8b19945003a98f910028eb35d75299c
3,617,692
import torch def render(H, W, focal, cx, cy, chunk=1024*32, rays=None, c2w=None, ndc=True, near=0., far=1., use_viewdirs=False, c2w_staticcam=None, **kwargs): """Render rays Args: H: int. Height of image in pixels. W: int. Width of image in pixels. focal: flo...
1dba826206df1d951f10c3ab8aac7018cdd15d69
3,617,693
def abstract(func): """ An abstract decorator. Raises a NotImplementedError if called. :param func: The function. :return: The wrapper function. """ # noinspection PyUnusedLocal # pylint: disable=unused-argument def wrapper(*args, **kwargs): raise NotImplementedError('{} has...
3497ae41c4987499cddc610e518a8a9251cadb31
3,617,694
def is_greyscale_image(image: np.ndarray) -> bool: """ A function that checks if an image is a greyscale image (an image where pixels are a number - has 1 color channel) :param image: the image to be checked, a numpy array """ return len(image.shape) == 2
72df92a91b2720138f73aa8817a7ad7a8803685f
3,617,695
def __get_site_amp_ratio(pga: float, db_vs30: float, user_vs30: float, im: IM): """ Calculates a PGA_1100 estimate; uses it to calculate a site amplification ratio for the difference in vs30 between the user and the modelled vs30 Scaling is only defined for pSA and PGA otherwise no scaling is applied -...
31c0bc41beb92c6595019283a40f600be046c520
3,617,696
def cosineXform(a, b, c): """ Spherical trig transform to take alpha, beta, gamma to expressions for cos(alpha*). See ref below. [1] R. J. Neustadt, F. W. Cagle, Jr., and J. Waser, ``Vector algebra and the relations between direct and reciprocal lattice quantities''. Acta Cryst. (1968)...
537cf31ceb59189b71b1394598ca3b89ee5de40a
3,617,697
import pandas def load_escolas(): """Load and return the dadosabertos.poa.br escolas dataset. The escolas dataset is a public open dataset from Prefeitura de Porto Alegre, Rio Grande do Sul, Brazil. Examples -------- >>> from dyrapy.datasets import load_escolas >>> cadastro, matriculas = loa...
7f9f265564fb1ce18f4871bf124b3b14ed62b0ce
3,617,698
def svn_fs_node_created_path(*args): """svn_fs_node_created_path(svn_fs_root_t * root, char const * path, apr_pool_t pool) -> svn_error_t""" return _fs.svn_fs_node_created_path(*args)
aecc149c53665815960a95966c20681e23cc9a93
3,617,699