content
stringlengths
22
815k
id
int64
0
4.91M
def run_simulation(num_rounds: int, num_clients: int, fraction_fit: float): """Start a FL simulation.""" # This will hold all the processes which we are going to create processes = [] # Start the server server_process = Process( target=start_server, args=(num_rounds, num_clients, fraction_...
65,900
async def main(): """Main method.""" forceQuit = False while not forceQuit: async with ClientSession(headers={'Connection': 'keep-alive'}) as session: print('') print('########################################') print('# Logging on to Skoda Connect #') ...
65,901
def build_tx_cigar(exons, strand): """builds a single CIGAR string representing an alignment of the transcript sequence to a reference sequence, including introns. The input exons are expected to be in transcript order, and the resulting CIGAR is also in transcript order. >>> build_tx_cigar([], 1)...
65,902
def train(train_dir, model, dataset_builder, initializer, num_train_steps, hps, rng, eval_batch_size, eval_num_batches, eval_train_num_batches, eval_frequency, checkpoint_steps, eval_steps=None, ...
65,903
def get_toeplitz_dictionary( n_samples=20, n_features=30, rho=0.3, seed=0): """This function returns a toeplitz dictionnary phi. Maths formula: S = toepltiz(\rho ** [|0, n_features-1|], \rho ** [|0, n_features-1|]) X[:, i] sim mathcal{N}(0, S). Parameters ---------- n_samples: int ...
65,904
async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock, CLIMATE_DOMAIN, DEFAULT_CONFIG )
65,905
def DictionaryofDate_valuetoArrays(Date_value): """Returns (array): date, value """ date = Date_value.keys() date.sort() value = [] for d in date: value.append(Date_value[d]) return date, value
65,906
def song_html_file_path(song: Song) -> Path: """Return absolute artist song HTML file path. Parameters ---------- song Song. Returns ------- :cod:`Path` Absolute artist song HTML file path. """ song_file_name = re.sub(r"[\s/]", "_", song.song_title) return artis...
65,907
def _in_load_test_mode(): """Returns True if the default values should be used instead of the server provided bot_config.py. This also disables server telling the bot to restart. """ return os.environ.get('SWARMING_LOAD_TEST') == '1'
65,908
def train_logistic_regression(): """Train a logistic regression model on the saved data. baseline: 0.792 logistic regression (no regularization): 0.871 """ (x_train, y_train), (x_val, y_val) = prepare_data() model = Sequential() model.add(Dense(1, input_dim=x_train.shape[1])) model.add(A...
65,909
def save_to_standard_HDF(df, name, target_path, mode='w'): """ Saves a DataFrame in a standard HDF format using h5py. """ import h5py # import here to avoid an issue on Stampede2 df = df.T hf = h5py.File(target_path, mode) #try: if True: # save each row (i.e., column of FG_df...
65,910
def area_separate(cnt): """ Calculates the total area of a list of contours. Args: * cnt - list of contours, as returned by cv2.findContours Returns: * total area """ return sum([cv2.contourArea(x) for x in cnt])
65,911
def get_id_from_cache(username: str) -> str: """Check if username exists in cache, return their slack_id. Args: username: slack username Returns: slack_id """ dynamodb = boto3.resource("dynamodb") if not CACHE_USERS_TABLE: raise Exception( "env var CACHE_USERS...
65,912
def configure_main_thread(): """ break/interrupt a time.sleep() in python https://stackoverflow.com/questions/5114292/break-interrupt-a-time-sleep-in-python """ global g_is_already_running g_is_already_running = True # Reset the internal flag to false. Subsequently, threads calling ...
65,913
def animate_aux(i, bg_int, faces, face_lines): """perform animation step""" bg_int.sample() for k, f in enumerate(face_lines): f.set_data(face_position(bg_int, k, faces)) ## Fix for multi face animations. #line.set_data(face_position(bg_int, 0, faces)) #line2.set_data(face_position(bg_in...
65,914
def cassini_time(time): """Parse Cassini time. Parameters ---------- time: str, int or float Cassini time. Returns ------- float Parsed Cassini time as float. Raises ------ ValueError If the input time pattern is invalid. Examples -------- ...
65,915
def _onset_by_mfcc(input, framesize=1024, hopsize=512, fs=44100): """ Onset detection by delta MFCC Parameters: inData: ndarray input signal framesize: int framesize of MFCC hopsize: int hopsize of MFCC fs: int samplingrate Returns: ...
65,916
def _ClientDataContainer_GetClientObject(self): """ Alias for :meth:`GetClientData` """ return self.GetClientData()
65,917
def main(): """Main function""" module = GcpModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), table_reference=dict(type='dict', options=dict(dataset_id=dict(type='str'), project_id=dict(type='str'), table_id=dict(type='str'))),...
65,918
def kabsch(test, ref, wgt=None, refl=True): """Returns the Kabsch rotational matrix to map a test geometry onto a reference. If weights are provided, they are used to weight the test vectors before forming the covariance matrix. This minimizes the weighted RMSD between the two geometries. If refl=T...
65,919
def _create_run_config(): """Creates a TPU RunConfig if FLAGS.use_tpu is True, else a RunConfig.""" session_config = tf.ConfigProto(allow_soft_placement=True) run_config_kwargs = { "save_summary_steps": FLAGS.save_summary_steps, "save_checkpoints_steps": FLAGS.save_checkpoints_steps, "save_check...
65,920
def send_email(eml): """发送邮件""" message = Message('修改密码',recipients=[eml]) code = ''.join(sample(ascii_letters+digits, 6)) message.body = '【51商城】验证码:{}\t{}\n{}'.format(code, '此次验证码有效期为5分钟', '如果非本人操作,请忽略!') mail.send(message) # TODO 应该存入redis 然后设置过期时间为3分钟 session['code']=code
65,921
def pods_by_uid(pods): """Construct a dict of pods, keyed by pod uid""" return {pod["metadata"]["uid"]: pod for pod in pods}
65,922
def main(): """Example showing how to extract h264 data.""" parser = argparse.ArgumentParser(description=main.__doc__) parser.add_argument( '--mp4-file', dest='mp4_file', required=True, type=str, help='mp4 file to extract h264 data from.') parser.add_argument( ...
65,923
def _tags_conform_to_filter(tags, filter): """Mirrors Bazel tag filtering for test_suites. This makes sure that the target has all of the required tags and none of the excluded tags before we include them within a test_suite. For more information on filtering inside Bazel, see com.google.devtools....
65,924
def async(startDelaySeconds=None, name=None, maxAllowedRuntime=None, killSwitch=None, ensureOnlyOne=False): """Decorate a function with this to make it run in another thread asynchronously! If defined with a value, it will wait that many seconds before firing. If a name is provided the thread will be named. Handy fo...
65,925
def convert_data(csv_data: pd.DataFrame, subset: str = 'all', exclude: Optional[List[str]] = None) -> Dict[str, Dict]: """ :param csv_data: dataframe with columns "mode", "split", "Structure", "seriesId" or "Patient", and "Dice" :param subset: if "all", use all rows, else use only rows whose "mode" value ca...
65,926
def get_custom_line_item(arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetCustomLineItemResult: """ A custom line item is an one time charge that is applied to a specific billing group's bill. :param str arn: ARN """ __args__ = dict() ...
65,927
def boot(name=None, kwargs=None, call=None): """ Boot a Linode. name The name of the Linode to boot. Can be used instead of ``linode_id``. linode_id The ID of the Linode to boot. If provided, will be used as an alternative to ``name`` and reduces the number of API calls to ...
65,928
def get_model_json_file_or_return_default_values(config, device, camera_id): """ Check if the json file exists and return the information about the ML model within said file. In case the file does not exist, return defaults values from "Detector" in config file. """ base_path = os.path.join(get_sour...
65,929
def create_rating_definition(*, creator: str, bestrating: int, worstrating: int, name: str = None): """Return a mutation for making a Rating definition. A Rating (https://schema.org/Rating) is an evaluation on a numeric scale. A Rating definition describes the structure that a rating can take. It is used so...
65,930
def generate_clothoid_paths(start_point, start_yaw_list, goal_point, goal_yaw_list, n_path_points): """ Generate clothoid path list. This function generate multiple clothoid paths from multiple orientations(yaw) at start points to multiple orientations...
65,931
def getppid(space): """ getppid() -> ppid Return the parent's process id. """ return space.newint(os.getppid())
65,932
def parse_classes(api_classes): """Parse the API classes data into the format required, a list of dict.""" parsed_classes = [] for entry in api_classes: class_ = {} class_[ATTR_ID] = entry["id"] class_[ATTR_CONFIDENCE] = round(entry["score"] * 100.0, 2) parsed_classes.append(...
65,933
def mesh_update_attributes(mesh): """Update the attributes of a mesh. Parameters ---------- mesh : compas.datastructures.Mesh A mesh object. Returns ------- bool ``True`` if the update was successful. ``False`` otherwise. See Also -------- * :func:`mesh...
65,934
def remove_all(link, value): """Remove all the nodes containing value. Assume there exists some nodes to be removed and the first element is never removed. >>> l1 = Link(0, Link(2, Link(2, Link(3, Link(1, Link(2, Link(3))))))) >>> print(l1) <0 2 2 3 1 2 3> >>> remove_all(l1, 2) >>> print(l1...
65,935
def gather_full_backbone(backbone_map: dict): """ Collect all blocks that are part of the backbone Args: backbone_map (dict): map of {state value => backbone block} Returns: set: All BasicBlocks involved in any form in the backbone """ # Get the immediately known blocks from the ma...
65,936
def get(objectid, worker=global_worker): """Get a remote object or a list of remote objects from the object store. This method blocks until the object corresponding to objectid is available in the local object store. If this object is not in the local object store, it will be shipped from an object store that ...
65,937
def _print_forward_selection_results(forward_selection_dict): """Prints results of any forward-selection algorithm to command window. :param forward_selection_dict: Dictionary returned by `feature_selection.sequential_forward_selection`, `feature_selection.sfs_with_backward_steps`, or `...
65,938
def plot_rboxes_on_image(img, boxes, color=[0, 255, 0], thickness=2): """ 旋转的boxes的结构为外接矩形四个点坐标,boxes=[n,8] or [n,4,2] """ if len(boxes.shape) == 2: h,l = boxes.shape boxes = tf.reshape(boxes,shape=[h,4,2]).numpy() boxes = boxes.astype(int) canvas = np.copy(img) for i in rang...
65,939
def download_file(remote_url, cache_path, filename=None, timeout=10.*u.second, show_progress=True, block_size=2**16, overwrite=False): """ This is a modified version of `~astropy.utils.data.download_file` that allows the user to specify the cache path. Accepts a URL, downloads and cac...
65,940
def convertGaiaToXYZUVWDict(astr_file): """ Supposed to generate XYZYVW dictionary for input to GroupFitter Doesn't work on whole Gaia catalogue... too much memory I think TODO: Sort out a more consistent way to handle file names... """ hdul = fits.open(astr_file)#, memmap=True) means, cov...
65,941
def get_options(): """define options for this script and interpret the command line""" optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() r...
65,942
def getPixelsForInterp(img): """ Calculates a mask of pixels neighboring invalid values - to use for interpolation. """ # mask invalid pixels invalid_mask = np.isnan(img) + (img == 0) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)) # dilate to mark borders around invali...
65,943
def set_max_results(uri, max): """Set max-results parameter if it is not set already.""" max_str = str(max) if uri.find('?') == -1: return uri + '?max-results=' + max_str else: if uri.find('max-results') == -1: return uri + '&max-results=' + max_str else: return uri
65,944
def cosine_similarity(a,b): """ Measure of similarity between two vectors in an inner product space. Used for comparing n-gram frequency of e.g. english with the n-gram frequency of a given text, and thus getting a measure of how close the text is to english. """ return dot(a,b) / (norm(a) * nor...
65,945
def round_frequency(frequency: float) -> int: """Returns the nearest audiologically meaningful frequency. Parameters ---------- frequency : float The frequency to be snapped to the nearest clinically meaningful frequency. Returns ------- float A ``snapped`` frequency value. """ ...
65,946
def delete_registry_attr(request, rattr, **kwargs): """ arguments: request, rattr, **kwargs implements: DELETE /api/registry/(RATTR).(FMT) returns: an empty envelope """ m = Registry.get(key=rattr) m.delete() return Envelope(request, result=0)
65,947
def ensure_folder_exists(path, permissions=0o775, create_placeholder_file=False): """ Helper method - creates a folder and parent folders if such do not already exist. :param path: path to create :param permissions: Permissions to use when folder is created :param create_placeholder_file: If true, ...
65,948
def candidates(plist,flist,x,y,dimz,stepsize): """Function to return a list xy-coordinates that indicate which pixels are likely microplastics based on reflectance differences. This function takes the list of pixels with a positive reflectance difference, the whole list of .csv files, the x and y coordi...
65,949
def kronecker(mat1, mat2): """ kronecker product between 2 2D tensors :param mat1: 2d torch.Tensor :param mat2: 2d torch.Tensor :return: kronecker product of mat1 and mat2 """ s1 = mat1.size() s2 = mat2.size() return torch.ger(mat1.view(-1), mat2.view(-1)).reshape(*(s1 + s2)).permute([0, 2, 1, 3]).reshape(s1[0...
65,950
def test_unknown_size_inputs(session_tf): """ Test for #725 and #734. When the shape of the Gaussian's mean had at least one unknown parameter, `gauss_kl` would blow up. This happened because `tf.size` can only output types `tf.int32` or `tf.int64`. """ mu_ph = tf.placeholder(settings.float_type...
65,951
def banner(): """Display the banner. C'mon, life is too short to use boring text, let's spice it up! """ # Credits: http://www.ascii-art.de/ascii/pqr/rockets.txt print(r""" ,: ,' | ...
65,952
def init_subparser(subparsers): """Initialize the run CLI subparser.""" parser = subparsers.add_parser('run', help='run a GeneFlow workflow') parser.add_argument( 'workflow', type=str, help='GeneFlow workflow definition or package directory' ) parser.add_argument( '-j...
65,953
def test_ffmpeg_resizing(): """Test FFmpeg resizing, to include downscaling.""" video_file = "media/big_buck_bunny_432_433.webm" target_resolutions = [(128, 128), (128, None), (None, 128), (None, 256)] for target_resolution in target_resolutions: video = VideoFileClip(video_file, target_resoluti...
65,954
def default_fields_validator(name: str, value: bool) -> None: """Raises validation error when specified field have incorrect is_default value. :param name: Predictions table field name. :param value: True if marked as is_default, otherwise False. """ if name in DEFAULT_PREDICTIONS_TABLE_FIELDS ...
65,955
def from_smile_txt(line_tokens, scale=1): """ line_tokens: a tuple of tokens on a "create" line of a SMILE demo txt file """ kwargs = {"name": line_tokens[2]} def lookup(key): return line_tokens[line_tokens.index(key)+1] if "category" in line_tokens: kwargs["category"] = lookup("category") if "bboxx...
65,956
def test_make_aware_timezone(): """Test the :func:`aiida.common.timezone.make_aware` function passing an explicit timezone.""" dt = timedelta(hours=2) naive = datetime(1970, 1, 1) aware = make_aware(naive, timezone(dt)) assert is_aware(aware) assert aware.tzinfo.utcoffset(aware) == dt
65,957
def execute_rule_post(rule_name): """ Use this endpoint to execute the rule engine for a rule for a fact set. --- tags: - Execute Rule Engine parameters: - name: rule_name in: path type: string required: true description: Rule name - na...
65,958
def get_mid_geno(np_array, cargs_obj): """ return the genotype with highest probability in the central. """ a_count, b_count, miss_count = _count_genos(np_array) ab_count = a_count + b_count if ab_count > cargs_obj.win_size//2: a_ex_prob = binom.pmf(b_count, ab_count, cargs_obj.error_a) ...
65,959
def register_models(): """Rmiperter Models and create metadata. Called from miper.db.sqlalchemy.__init__ as part of loading the driver, it will never need to be called explicitly elsewhere unless the connection is lost and needs to be reestablished. """ from sqlalchemy import create_engine ...
65,960
def cleanup(ser, mqtt): """Called on exit to close serial and disconnect MQTT""" print("Ending and cleaning up") ser.close() mqtt.loop_stop()
65,961
def current_version(): """Provides version name(not code) : 1.0""" return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName # return "1.0"
65,962
def n2str(num): """ convert a number into a short string""" if abs(num) < 1 and abs(num) > 1e-50 or abs(num) > 1E4: numFormat = ".2e" elif abs(round(num) - num) < 0.001 or abs(num) > 1E4: numFormat = ".0f" elif abs(num) > 1E1: numFormat = ".1f" else: numFormat = ".2f...
65,963
def null_fks(page, data): """ Nullifies foreign keys within all supplied fields. Arguments: page -- Page object. data -- Page object in dictionary format. Returns: N/A. Overwrites the argument. """ # Loop through all fields. for field in page._meta.get_fields(): ...
65,964
def StringCompression(s: str) -> str: """Compresses the specified string using counts of repeated characters. >>> StringCompression("") '' >>> StringCompression("a") 'a' >>> StringCompression("ab") 'ab' >>> StringCompression("abc") 'abc' >>> StringCompression("aba") 'aba...
65,965
def load_config_events( run_id: str, source: Optional[Literal["azurebatch", "azureml", "local"]] = None, workspace_name: Optional[str] = None, azureml_run_id: Optional[str] = None, **kwargs, ): """ Try to load config and events locally. If this fails, try to download the result from Blob...
65,966
def _get_json_content(obj): """Event mixin to have methods that are common to different Event types like CloudEvent, EventGridEvent etc. """ msg = "Failed to load JSON content from the object." try: # storage queue return json.loads(obj.content) except ValueError as err: ...
65,967
def test_docker_4_dockerflag(plugin, tmpdir): """ task reads the file that is bounded to the container specifying bindings, using ShellComandTask with container_info=("docker", image, bindings) """ with open(tmpdir.join("file_pydra.txt"), "w") as f: f.write("hello from pydra") c...
65,968
def angle(crd, i, j, k): """ Calculate i-j-k angle in rad unit. """ pass
65,969
def compute_target( answers_dset, ans2label, name, dataset, cache_root="data/OK-VQA/cache" ): """Augment answers_dset with soft score as label ***answers_dset should be preprocessed*** Write result into a cache file """ target = [] for ans_entry in answers_dset: answers = ans_entry...
65,970
def form_description(elastic_apartment: ElasticApartment) -> Optional[str]: """ Fetch link to apartment presentation and add it to the end of project description """ optional_text = "Tarkemman kohde-esittelyn sekä varaustilanteen löydät täältä:" main_text = getattr(elastic_apartment, "project_descri...
65,971
def extractlocalfeature(point_cloud, is_training, bn_decay=None): """ Classification PointNet, input is BxNx3, output Bx40 """ batch_size = point_cloud.get_shape()[0].value num_point = point_cloud.get_shape()[1].value input_image = tf.expand_dims(point_cloud, -1) # input_image BxNx3x1 with tf.vari...
65,972
def get_reaction_type(name, path = './data', output_format = 'array'): """to retrieve the type of reactions for reaction dataset Args: name (str): dataset name path (str, optional): dataset path output_format (str, optional): output format in dataframe or in raw array format Returns: pd.DataF...
65,973
def beavrsMaterials(): """Dictionary of materials from the BEAVRS specification Currently provides: fuel32 -> 3.2 wt% enriched UO2 air -> air zirc4 -> zircaloy 4 cladding water -> unborated water helium -> helium bglass -> boroscillicate glass ss304 -> s...
65,974
async def DatagramSender( manager: ManagerAPI, outbound_datagram_receive_channel: ReceiveChannel[OutboundDatagram], sock: SocketType, ) -> None: """Take datagrams from a channel and send them via a socket to their designated receivers.""" logger = get_extended_debug_logger("ddht.DatagramSender") ...
65,975
def possibly_fix_width(text): """Heuristic to possibly mark-up text as monospaced if it looks like a URL, or an environment variable name, etc.""" if text in ['', '--']: return text # stringify the arguments if type(text) not in [type('string'), type(u'Unicode')]: text = "%r" % ...
65,976
def show_config(): """Print the configuration """ conf.show()
65,977
def get_topo(makeplots=False): """ Retrieve the topo file from the GeoClaw repository. """ from clawpack.geoclaw import topotools, etopotools topo_fname = 'etopo1_-140_-60_-60_10_10min.tt3' if os.path.exists(topo_fname): print "*** Not regenerating dtopo file (already exists): %s" \ ...
65,978
def animate_baselines(source, antenna, filename, fps=5): """ Create gif to animate change of baselines during an observation Parameters ---------- source: source class object class object containing source position antenna: antenna class object class object with antenna position...
65,979
def test_with_hardclip_not_spanning_clv_from_after_edgecase_2(mock_apautils): """ TT |└GTGA <-bridge read ATTCGTGA <-bridge contig (hardcipped), chimeric /// <-hardclip mask 012345678 <-contig coord icb^ ^cc ...ATTCGTGA...
65,980
def dfify_clusters(cols: Dict[str, np.ndarray], df: pd.DataFrame) -> pd.DataFrame: """Concatenate cluster ids with their input features. Args: cols (Dict[str, np.ndarray]): Columns to prepend to df. df (pd.DataFrame): inputrecord ids and their features. Returns: pd.DataFrame: clust...
65,981
def board(): """ Simple menu """ global classifier # Check if dataset is loaded if dataset is None: load_dataset() # Classifier classifier = Classifier(dataset) while True: # Print parent menu print '1. Compare accuracies' print '2. Show t...
65,982
def weighted_score(raw_earned, raw_possible, weight): """ Returns a tuple that represents the weighted (earned, possible) score. If weight is None or raw_possible is 0, returns the original values. When weight is used, it defines the weighted_possible. This allows course authors to specify the exa...
65,983
def run(once=False, threads=1, sleep_time=60): """ Starts up the Judge-Clean threads. """ setup_logging() if rucio.db.sqla.util.is_old_db(): raise exception.DatabaseException('Database was not updated, daemon won\'t start') client_time, db_time = datetime.utcnow(), get_db_time() ma...
65,984
def get_coderef_from(vw, va): """ return first code `tova` whose origin is the specified va return None if no code reference is found """ xrefs = vw.getXrefsFrom(va, REF_CODE) if len(xrefs) > 0: return xrefs[0][XR_TO] else: return None
65,985
def test_failed(): """Re-run tests which failed on last run.""" build() test_setup() sh("%s %s --last-failed" % (PYTHON, RUNNER_PY))
65,986
def test_materialize_from_remote(tmpdir): """ Verify loading data and mainfest transforms from S3. """ with patch('botocore.client.BaseClient._make_api_call', new=mock_make_api_call): with open(REMOTE_MANIFEST) as fd: pkg = Package.load(fd) with patch('t4.data_transfer._download_file...
65,987
def search(word: str) -> str: """查询es中朗文4的example """ if not USE_ES or not CONNECTED_ES: return "" dsl = { "query": { "match": { "han": word } } } res = esClt.search(index=INDEX, body=dsl) html = """<span>朗文4相关例句</span><link re...
65,988
def tempDiffRestrict(primerInfo, maxTempDiff=MAX_TEMP_DIFF): """Checks the differnce in annealing temperatures between two primers. Difference should not be greater than 5 degrees.""" for key in primerInfo.copy(): if abs(primerInfo[key][0][1] - primerInfo[key][1][1]) > maxTempDiff: de...
65,989
def download_url(url, save_dir): """Download a url to `save_dir`.""" filename = url.split("/")[-1] save_dir = Path(save_dir) save_dir.mkdir(parents=True, exist_ok=True) with DownloadProgressBar( unit="B", unit_scale=True, miniters=1, desc=url.split("/")[-1] ) as t: urllib.reque...
65,990
def get_compiler_dir(compiler_name): """ Try to figure out the compiler directory based on the input compiler name. This is fragile and really should be done at the distutils level inside the compiler. I think it is only useful on windows at the moment. """ compiler_type = choose_c...
65,991
def PairOHLCSchema(pair): """helper function to embed OHLC data frame parsing into a field with any name... returns a new instance of the class, creating the class if needed """ def build_model(self, data, **kwargs): assert len(data.get('error', [])) == 0 # Errors should have raised except...
65,992
def sum_GaussLorentz(x, centers, amplitudes, widths, shapes, baselevels): """add mixed Gauss-Lorentzian curves together Parameters ---------- x : list-like centers, amplitudes, widths, shapes : list-like, 1-dimensional parameters for the individual curves. Lists have lenght n for n curves. ...
65,993
def randn(*size, **kwarg): """Returns an array of standard normal random values. Each element of the array is normally distributed with zero mean and unit variance. All elements are identically and independently distributed (i.i.d.). Args: size (ints): The shape of the array. dtype...
65,994
def hdf5_to_tfrecords( hdf5_path: PathLike, feature_dataset: str, label_dataset: str, tfrecord_path: str, feature_dtype=np.uint8, label_dtype=np.uint8, chunksize=10000, gzip=True, first_shard=0, verbose=1, ) -> None: """Convert data in HDF5 to TFRecord format. Data in fe...
65,995
def is_registered(subject, license_uri, metadata): """ Checks for work registration assertions """ # shorthand accessor triples = metadata['triples'] # first check for a has_owner assertion if subject not in metadata['subjects'] or \ not triples[subject].has_key(SIOC('has_owner')): ...
65,996
def list_images(): """Obtain a list of available version of OneFS nodes that can be created :Returns: List """ images = os.listdir(const.VLAB_ONEFS_IMAGES_DIR) images = [convert_name(x, to_version=True) for x in images] return images
65,997
def stddev_from_average(timeseries): """ A timeseries is anomalous if the absolute value of the average of the latest three datapoint minus the moving average is greater than three standard deviations of the average. This does not exponentially weight the MA and so is better for detecting anomalies ...
65,998
def call_base_class_method_with_same_name(obj): """ Run base class method. :param obj: class object which methods will be decorated. :return: class object with decorated methods """ if hasattr(obj, "__dict__"): if obj.__dict__.items(): for attributeName in dir(obj): ...
65,999