content
stringlengths
22
815k
id
int64
0
4.91M
def param_is_numeric_and_simple(p): """ Test whether a parameter is numeric and, if it is a string, that it doesn't contain scientific or uncommon notation. :param p: An input parameter :return: """ if isinstance(p, str): return str_is_numeric(p) else: return param_is_num...
60,700
def DefineNor(height, width): """ Generate Nor module I0 : Array(width, Bit), I1 : Array(n, Bit) -> O : Array(n, Bit) """ T = Array(width, Bit) class _Nor(Circuit): assert height > 1 and height <= 4 name = 'Nor%dx%d' % (height, width) if height == 2: IO ...
60,701
def _replace_admin_for_model(modeladmin, admin_site): """Replaces existing admin class registered for `modeladmin.model` with a subclass that includes version locking functionality. Doesn't do anything if `modeladmin` is already an instance of `VersionLockAdminMixin`. :param model: ModelAdmin inst...
60,702
def HMA(data, period=16): """ Hell's Moving Average HMA indicator is a common abbreviation of Hull Moving Average. The average was developed by Allan Hull and is used mainly to identify the current market trend. Unlike SMA (simple moving average) the curve of Hull moving average is considerably s...
60,703
def create_input(shape): """Create a random input tensor.""" return torch.rand(shape).float()
60,704
def input_thing(): """输入物品信息""" name_str, price_str, weight_str = input('物品名称,价格,重量: ').split() return name_str, int(price_str), int(weight_str)
60,705
def ip_pool_remove(cidrs, version): """ Remove the given CIDRs from the IP address allocation pool. :param cidrs: The pools to remove in CIDR format, e.g. 192.168.0.0/16 :param version: 4 or 6 :return: None """ for cidr in cidrs: # Get the existing IP Pool so that we can disable it,...
60,706
def perpendicular_vector(R, max_alt): """ Generates a viewing and tangent vectors perpendicular to a sphere of radius R """ return np.array([0, R+max_alt*2, 0]).reshape(3, 1), \ np.array([0.0, 0, 0]).reshape(3, 1)
60,707
def enroll(video): """ Params: video: base64 encoded data """ try: setup_directories() content = base64.b64decode(video) filename = frappe.session.user+".mp4" OUTPUT_VIDEO_PATH = frappe.utils.cstr(frappe.local.site)+"/private/files/user/"+filename with open(OUTPUT_VIDEO_PATH, "wb") as fh: ...
60,708
def nonzero_maximum_box(input: Image, flag_dst: Image, destination: Image = None) -> Image: """Apply a maximum filter (box shape) to the input image. The radius is fixed to 1 and pixels with value 0 are ignored. Note: Pixels with 0 value in the input image will not be overwritten in the output im...
60,709
def linear_layer(input_tensor, classes, train, summary=False, rf=1, data_format="NCHW"): """Builds a logit layer that we apply the softmax to, with variables Args: input_tensor: input tensor classes: Number of classes to classify in the output train: If we want to train this layer or no...
60,710
def upload(filename, uri, extra={}): """ Upload object to S3 uri (bucket + prefix), keeping same base filename """ s3 = boto3.client('s3') s3_uri = uri_parser(uri) bname = os.path.basename(filename) uri_out = 's3://%s' % os.path.join(s3_uri['bucket'], os.path.join(s3_uri['key'], bname)) key = os...
60,711
def get_information(key): """ Obtains a variety of runtime information about CMSElemental. """ key = key.lower() if key not in __info: raise KeyError(f"Information key '{key}' not understood.") return __info[key]
60,712
def hedge_portfolio(context, data): """ This function places an order for "context.index" in the amount required to neutralize the beta exposure of the portfolio. Note that additional leverage in the account is taken on, however, net market exposure is reduced. """ factors = get_alphas_and_...
60,713
def gene_text(number=6): """生成随机字符""" source = string.ascii_letters+string.digits return ''.join(random.sample(source,number))
60,714
def test_force(force_fix): """Test ``gander.indicators.force()``. :param force_fix: Callable to test helpers defined in pytest fixture ``macd_fix()`` """ df = force_fix df_out = calc_force(df, "close", "volume") print("\n\n", df_out) assert list(df_out["force"].dropna().values) == [10....
60,715
def radio_packet_handling(packet_text): """Handle packet.""" global start_time run_time = time.monotonic() - start_time print( "{: 3.1f}: " "{:+.1f}dbm" " " "'{}'" "".format( run_time, rfm69.rssi, packet_text, ), ) ...
60,716
def run_experiment(hparams): """Train the model then export it for tf.model_analysis evaluation. Args: hparams: Holds hyperparameters used to train the model as name/value pairs. """ estimator = train_and_maybe_evaluate(hparams) schema = read_schema(hparams.schema_file) # Save a model for tfma eval ...
60,717
def parse(message: str, scenario: Scenario) -> Tuple[Actions, object, Dict]: """Attempts to parse the player action into an action, target and arguments. Args: message - the incoming message from the player-action socket. scenario - the current scenario state. Returns - a Tuple of the pars...
60,718
def gen_snippet(snippet, config): """Renders a config snippet. "config" represents the portion of the YAML file applicable to this snippet""" template = ENV.get_template(snippet + ".j2") return template.render(config=config)
60,719
def get_info_from_notice(notice): """ # 글 제목, 글 작성자 if(str(notice).find('font')!=-1): print('정상작동') title = notice.find('font').text else: print('에러') writer = notice.find('td', attrs={'class':'bbs_writer'}).text """ [span.extract() for span in notice...
60,720
def plot_global_daily_counts(df): """Plots the daily global counts. Parameters ---------- df : pandas.DataFrame A DataFrame containing the global data. """ # Filter out rows with zero confirmed cases. df = df[df["confirmed"] > 0] # Resample the data by 1 day intervals and sum...
60,721
def update_heap_info(data): """ Update info when breakpoint reached """ print("emitting heap_changed: {}".format(data)) sio.emit("heap_changed", data, namespace="/gef")
60,722
def test_validate_input_value_real_real(real_space): """Test if real value passed to real space is validated properly""" namespace = "x" is_valid, casted_value = _validate_input_value("10.0", real_space, namespace) assert is_valid assert isinstance(casted_value, numbers.Number)
60,723
def update_param_name(param_name): """ Takes an abbreviated name and expands it so the user can type DISP or DISPLACEMENT and get the same answer Parameters ---------- param_name : str the parameter name to be standardized (e.g. DISP vs. DIPLACEMENT) .. todo:: not a complete list ...
60,724
def thead(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transl...
60,725
def test_cartesian_sanity(current_driver, set_target): """ A sanity check to see if the driver remember vectors in any random configuration in cartesian coordinates """ current_driver.cartesian(set_target) get_target = current_driver.cartesian() assert np.allclose(set_target, get_target) ...
60,726
def get_msf_session_id(session_name: str, plan_execution_id: Union[Type[int], int]) -> str: """ Get a Metasploit session ID by the defined session name :param str session_name: Session name provided in input file :param int plan_execution_id: ID of the desired plan execution :raises: Sessio...
60,727
def compute_margin( input_fn, root_dir, model_config, sess=None, batchsize=50, dataset_size=50000): """Compute the margins of a model on all input data. Loads a given model from given directory and load the parameters in the given scope. Iterates over the entire training dataset and computes the upper bo...
60,728
def in_notebook(): """Determine whether code is running in a Jupyter Notebook shell. Returns ------- ip : bool True if running in a notebook shell, False otherwise """ try: # See https://stackoverflow.com/questions/15411967 shell = get_ipython().__class__.__name__ ...
60,729
def groupby_agg( ddf, gb_cols, aggs_in, split_every=None, split_out=None, dropna=True, sep="___", sort=False, as_index=True, ): """ Optimized groupby aggregation for Dask-CuDF. This aggregation algorithm only supports the following options: - "count" - "...
60,730
def put_op(form): """Annotation for a callable function specifying that it is a PUT :class:`Op`.""" return op.Put(form)
60,731
async def open_report_dialog(action: Action, app: SirBot): """ Opens the message reporting dialog for the user to provide details. Adds the message that they're reporting to the dialog's hidden state to be pulled out when submitted. """ trigger_id = action["trigger_id"] response = {"trigger...
60,732
def str_to_tstamp(time_value): """ Convert date string to timestamp Args: time_value (Union[str, int]): date string in any format supported by dateutils.parser.parse Returns: int: timestamp """ if type(time_value) is int: # If we got int - consider it being timestamp already ...
60,733
def merge_UserInput_with_SourceDF(user_df: pd.DataFrame, source_df: pd.DataFrame): """ Reads the user feature dataset and merges that to the end of the source dataset. Removes the duplicates found in the source with the users dataset. It returns a tuple. first element is the merged dataset and the secon...
60,734
def get_effective_data_length(user_code, span_min=10, best_effort=False, exclude_capped=False, start_time=None, end_time=None, min_num_samples=100): """ To compute the length of the data by the user, based on `ActionLog`. Our system establishes a connection (from app to server) every minute. However...
60,735
def lorenz_curve(data: pd.Series) -> pd.Series: """ Calculates the values for the lorenz curve of the data. For more information see online `lorenz curve <https://en.wikipedia.org/wiki/Lorenz_curve>`_. Args: data: sorted series to calculate the lorenz curve for Returns: the va...
60,736
def cut_solid(solid, cutter): """ Performs a boolean cut of a solid with another solid or iterable of solids. Args: solid Shape: the Shape that you want to cut from cutter Shape: the Shape(s) that you want to be the cutting object Returns: Shape: the original shape cut with the c...
60,737
def sortfile(pathfilesout, pathfilesin): """Поиск даты в exif""" cou_folder = 0 cou_files = 0 cou = 0 cou_f = 0 pathall = [] for path, dirs, files in os.walk(pathfilesout): pathall.append(path) cou_folder = len(pathall) for pathfile in pathall: faile = os.listdir(...
60,738
def load_cytobands(resource, build, adapter): """Parse and load cytobands from file. Args: resource(str): path to cytobands file (either build 37 or 38) build(str): "37" or "38" adapter(MongoAdapter) """ cytobands = [] LOG.debug(f"Reading cytoband file for genome build {bui...
60,739
def pad_bitmap(bitmap, left, top, right, bottom, value, debug=False): """ Pads a bitmap with pixels on each side. The new cells are applied the value :param bitmap: A numpy array :param left: The number of pixels that should be added to the left :param top: The number of pixels that shou...
60,740
def _find_stub_degree(branch, bus_id): """Find degree of stubbiness, and stub branches. :param pandas.DataFrame branch: branch DataFrame from Grid object. :param int bus_id: index of bus to find subbiness of. :return: (*tuple*) -- tuple containing: stub_degree (*int*) -- How stubby (non-negativ...
60,741
def add_data_to_list(twitter_return): """ Extract the data from the twitter_return dictionary and place in a list """ twitter_dict = twitter_return ['response_dict'] # Grab the twitter data twitter_data_list=twitter_dict['data'] return twitter_data_list
60,742
def delete(ctx, include, exclude): """ Delete cube from store. """ cube = ctx.obj["cube"] store = ctx.obj["store"] all_datasets = set(ctx.obj["datasets"].keys()) delete_datasets = filter_items("dataset", all_datasets, include, exclude) delete_cube_bag(cube=cube, store=store, datasets=del...
60,743
def get_issue_by_url_seg(url_seg, url_seg_issue): """ Retorna um número considerando os parâmetros ``iid`` e ``kwargs``. - ``url_seg``: string, contém o seguimento da URL do Journal; - ``url_seg_issue``: string, contém o seguimento da URL do Issue,. """ journal = get_journal_by_url_seg(url_seg...
60,744
def negentropy(p): """ Entropy which operates on vectors of length N. """ # This works fine even if p is a n-by-1 cvxopt.matrix. return np.nansum(p * np.log2(p))
60,745
def check_n_files(subject, collector, keep, n_file=1): """ Organise download path per subject for the two sessions. If the number of total file is not the same as expected, drop the subject. Parameters ---------- subject: str Subject ID. collecter: dict Dictionary collecti...
60,746
def load_data(): """Load and return example data. Returns: log (List[List[str]]): example log. """ # file path absPath = os.path.abspath(__file__) fileDir = os.path.dirname(absPath) code = os.path.dirname(fileDir) data = os.path.join(code, "data") # load the first 2000 tr...
60,747
def remove_files(*patterns): """Remove all files that match any of the patterns.""" for pattern in patterns: for fname in glob.glob(pattern): os.remove(fname)
60,748
def curate_EPI_space(moco_target): """curate_EPI_space doubles the amount of timepoints of the moco target if it has only one. This is mandatory for the AFNI moco workflow. Parameters ---------- moco_target : string absolute path to moco file returns out_file : string ...
60,749
def test_run_code(console_plugin, capsys): """Test that the console runs code.""" shell = console_plugin.get_widget().shell # Run a simple code shell.insert_text('2+2', at_end=True) shell._key_enter() # Capture stdout and assert that it's the expected one sys_stream = capsys.readouterr() ...
60,750
def create_resource_id_tag(**kwargs): """ create tag via resource id """ session = kwargs.get('session', {}) resource_id = kwargs.get('resource_id', {}) tag_name = kwargs.get('tag_name', {}) tag_value = kwargs.get('tag_value', {}) try: tag_session = session.get_client_session(service='ec...
60,751
def ErrorReset(*args): """ErrorReset()""" return _gdal.ErrorReset(*args)
60,752
def get_noise_range_pcts(db_range_exps: dict, length: float) -> Dict[int, float]: """Calculates percentages of aggregated exposures to different noise levels of total length. Note: Noise levels exceeding 70 dB are aggregated and as well as noise levels lower than 50 dB. Returns: A dictionar...
60,753
def for_parallelogram(): """printing shape of'parallelogram' using for loop""" for row in range(5): for col in range(11): if row==0 and col not in(0,1,2,3) or row==4 and col not in(7,8,9,10) or row+col==4 or row+col==10: print("*",end=" ") else: ...
60,754
def update_info(): """ 用户信息更新 """ username = request.get_json()['username'] email = request.get_json()['email'] password = request.get_json()['password'] words_book = request.get_json()['words_book'] words_num = request.get_json()['words_num'] words_num = int(words_num) if words_num ...
60,755
def read_terminals(terminals_file=DEFAULT_TERMINALS_FILE): """Returns all terminals in order that they are coded in file_train. """ terminals = read_json(terminals_file)[:50000 - 1] return [EMPTY_TOKEN] + terminals + [UNKNOWN_TOKEN]
60,756
def _sync_engagement_db_dataset_to_coda(engagement_db, coda, coda_config, dataset_config, cache, dry_run=False): """ Syncs messages from one engagement database dataset to Coda. :param engagement_db: Engagement database to sync from. :type engagement_db: engagement_database.EngagementDatabase :para...
60,757
def test_get_render_env_failed(fixture_render_config): """Ensure we can catch the error message.""" with pytest.raises(ValueError): fixture_render_config.get_render_config("test_name")
60,758
def group_by_first(pairs): """Return a list of pairs that relates each unique key in the [key, value] pairs to a list of all values that appear paired with that key. this documentation should state why this should normally be used; what should this func normally be used for? Arguments: pairs -- a se...
60,759
def generate_scorecards(misp_data, directory, galaxy_type, entry_description, start_date, end_date): """ Generate a score card for each entry (e.g. threat actor or ransomware) misp_data - The events and attributes loaded from the MISP server directory - The name of the directory to store the output in ...
60,760
def accepts_environment(func): """Allows defining an action function that accepts only theTrailEnvironment and doesn't accept a context. Example: @accepts_environment def action_function_taking_only_environment(trail_env): # Do something with trail_env pass """ @wraps(func) ...
60,761
def film_layer(incoming, gamma, beta, name='film'): """ FiLM layer :param incoming: incoming tensor :param gamma: incoming gamma :param beta: incoming beta :param name: (string) name scope :return: """ with tf.name_scope(name): # get shape of incoming tensors: in_shap...
60,762
def _score_lcs(target_tokens, prediction_tokens): """Computes LCS (Longest Common Subsequence) rouge scores. Args: target_tokens: Tokens from the target text. prediction_tokens: Tokens from the predicted text. Returns: A Score object containing computed scores. """ if not target_tokens or not pr...
60,763
def reshape_t(x, shape): """Work around fact that x.reshape(()) doesn't work""" if shape != (): return x.reshape(shape) else: return x[0]
60,764
def ping_prices() -> None: """ returns: dictionary 'name: str' : 'a_price: float' for each item """ non_books, books = {}, {} links = REG.load_links()[0] # for each specified link the item_name and a_price is extracted, printed and returned data = analyze_items(links) for loops in range(len...
60,765
def make_shared_array(np_array: np.ndarray) -> mp.Array: """ shared array""" flat_shape = int(np.prod(np_array.shape)) shared_array_base = mp.Array(ctypes.c_float, flat_shape) shared_array = np.ctypeslib.as_array(shared_array_base.get_obj()) shared_array = shared_array.reshape(np_array.shape) sh...
60,766
def GenerateHeaderFile(file): """Generates gpu/vulkan/vulkan_function_pointers.h""" file.write(LICENSE_AND_HEADER + """ #ifndef GPU_VULKAN_VULKAN_FUNCTION_POINTERS_H_ #define GPU_VULKAN_VULKAN_FUNCTION_POINTERS_H_ #include <vulkan/vulkan.h> #include "base/compiler_specific.h" #include "base/native_library.h" #i...
60,767
def _create_core_state_space(optim_paras, options): """Create the core state space. The state space of the model are all feasible combinations of the period, experiences, lagged choices and types. Creating the state space involves two steps. First, the core state space is created which abstracts f...
60,768
def mean_coherencegram(perievent_lfp1, perievent_lfp2, dt, window, fs, extend=0.3): """ Computes the mean coherence over time between perievent slices (e.g. "coherencegram" because it's a combination of a coherence and a spectrogram) Parameters ---------- perievent_lfp1 : nept.AnalogSignal ...
60,769
def remove_backup(): """Remove the backup created by create_backup.""" try: os.remove(LOG_CONFIGS_BAK_PATH) except FileNotFoundError: pass
60,770
def calc_n_max_vehicle(n2v_g_vmax, v_max): """Calc `n_max3` of Annex 2-2.g from `v_max` (Annex 2-2.i). """ return n2v_g_vmax * v_max
60,771
def log_average_miss_rate(prec, rec, num_images): """ log-average miss rate: Calculated by averaging miss rates at 9 evenly spaced FPPI points between 10e-2 and 10e0, in log-space. output: lamr | log-average miss rate mr | miss rate ...
60,772
def get_access_token(session=None, username=None, password=None): """ Get the access token from the server. Return a (access_token, refresh_token) pair. """ if session is None: session = get_authenticated_session(username, password) # Request the authorization server for the code. re...
60,773
def mergeSmallRecords(city, directory, subpath, time): """ 通过逐行读取的方式合并记录数 :param city: :param directory: :param subpath: :param time: """ resString = [] baseurl = os.path.join(directory, subpath) for x in xrange(0, 20): with open(os.path.join(baseurl, 'rres-t%02d-ti%d' % (x, time)), 'rb') as stream...
60,774
def alarm_initialize(config): """ Initialize the alarm subsystem """ from nfv_common.alarm._alarm_thread import AlarmThread AlarmThread(config).start()
60,775
async def approve_application(uid: str, username=Depends(auth_handler.auth_wrapper)): """ Approve an Application Require: Admin-write """ logger.debug(f"{username} trying to offer (approve) an ApplicationForm") permission_ok = Access.is_admin_write(username) if not permission_ok: lo...
60,776
def gelu_jit(x): """OpenAI's gelu implementation.""" return gelu(x)
60,777
def read(fname): """Utility function to read the README file. Used for the long_description""" return open(os.path.join(os.path.dirname(__file__), fname)).read()
60,778
def create_file(file_name: str, shape: Tuple[int], dtype: np.dtype) -> None: """Creates a fits file without loading it into memory. This is a helper method to create large FITS files without loading an array into memory. The method follows the direction given at: http://docs.astropy.org/en/stable/genera...
60,779
def query_st_production(jobs: list[PackJob]) -> list[tuple[int, int, int]]: """Fetch production w.r.t time :returns: list[tuple[product_code, pack_code, production]] """ result = None cond = [] for job in jobs: cond.append( sa.and_( *[ S...
60,780
def rnd_position(seq, rates, model, mean_logs, sd_logs, sample=None): """Generates a list of mutation/indel sites by applying a random process specified by the model parameter.""" try: N_positions=[pos for pos, char in enumerate(seq) if char == 'N'] # finding position of N in the seq, it will be used in while _n<...
60,781
def savecompanyrow(table, companyrow, thecompany=None): """ :param table: :param companyrow: :param thecompany: :return: """ sqlstring = """ UPDATE Company SET ID=?, CompanyName = ?, WebAddress = ?, StreetAddress1 = ?, StreetAddress2 = ?, City ...
60,782
def filt_by_filetype(filetypes, value): """ filt the urls of filetypes """ for ftype in filetypes: if value.endswith(ftype): return True return False
60,783
def adoc_section_title(ast_type): """ Adds a ASCIIDoc section title. """ adoc.append(f'[[{ast_type.namespace.name}-{ast_type.name}]]') if not hasattr(ast_type, 'extends') or ast_type.extends is None: adoc.append(f'=== {ast_type.__class__.__name__} {ast_type.name}\n') else: adoc.append(f'...
60,784
def test_suite(): """Discover unittests""" test_loader = unittest.TestLoader() test_suite = test_loader.discover('str_analysis', pattern='*tests.py') return test_suite
60,785
def compute_zero_mask(imgarr, iterations=8, ext=0): """Find section from image with no masked out pixels and max total flux""" if isinstance(imgarr, str): img_mask = fits.getdata(imgarr, ext=0) else: img_mask = imgarr.copy() img_mask[img_mask > 0] = 1 img_mask = ndimage.binary_erosi...
60,786
def alarm_triggerd(alarm_active: dict): """Defines what to do when an alarm is triggered Finds out what the user requests to be read and then uses pyttsx3 to read that information When an alarm is triggerd a notification refresh is also performed""" global NOTIFICATIONS global ALARMS log...
60,787
def get_most_recent_daemon_timestamp(): """ Try to detect any last timestamp left by the daemon, for instance to get a hint on whether the daemon is running or not. :return: a datetime.datetime object with the most recent time. Return None if no information is found in the DB. """ import...
60,788
def increasing_train_set_size(root_mode, val_set_fractions): """ Evaluate learning of Healthy vs KC with increasing training set sizes. Run some cross-validation iteration on increasing training set size. Average results of each :type root_mode: Mode """ target_names_and_labels_for_ge...
60,789
def get_conf(base_dir): """ Get the actual configuration, built by merging the repository conf into the global user conf. """ user_conf = get_user_conf() repos_conf = get_repository_conf(base_dir) configspec_fname = op.join(THIS_DIR, 'confspec.ini') merged_conf = configobj.ConfigObj(conf...
60,790
def get_metadata(package, field): """ Return package data as listed in `__{field}__` in `init.py`. """ init_py = codecs.open(os.path.join(package, '__init__.py'), encoding='utf-8').read() return re.search("^__{}__ = ['\"]([^'\"]+)['\"]".format(field), init_py, re.MULTILINE).group(1)
60,791
def dla102x(**kwargs): """ DLA-X-102 model from 'Deep Layer Aggregation,' https://arxiv.org/abs/1707.06484. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' Location for keeping the mo...
60,792
def is_valid_iyr(iyr: str) -> bool: """ (Issue Year) - four digits; at least 2010 and at most 2020. :return: Status of field (true = valid). :rtype: bool """ iyr = int(iyr) if iyr < 2010 or iyr > 2020: return False return True
60,793
def conv_transpose3d_ncdhw(inputs, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1, out_dtype="float32"): """Convolution transpose 3d NCDHW layout Args: ----------------------------- inputs : GraphNode shape [batch, channel, depth, height, width] weight : Gra...
60,794
def start_http_server(port, address=''): """ Start a HTTP API server for airfilter prometheus collector. """ duration = Summary( 'airfilter_collection_duration_seconds', 'Duration of collections by the airfilter exporter', ) errors = Counter( 'airfilter_request_errors_to...
60,795
def build_readme_files_dict(app, repository, changeset_revision, metadata, tool_path=None): """ Return a dictionary of valid readme file name <-> readme file content pairs for all readme files defined in the received metadata. Since the received changeset_revision (which is associated with the received met...
60,796
async def vif_get_lock_by_uuid(cluster_id: str, vif_uuid: str): """Get VIF Lock by UUID""" try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) vif: VIF = VIF.get_by_uuid(session=session, uuid=vif_uuid) ret = dict(success=True...
60,797
def text_to_data(input_data, encoding='utf8'): """ Converts text data into (N,8) numpy array of bits""" # Convert to data to a list of bytes, represented as integers data_binary_stream = [int(x) for x in bytearray(input_data, encoding)] # Convert into numpy array of uint8 and convert to row vector d...
60,798
def group_bounding_box( group: Union[hou.EdgeGroup, hou.PointGroup, hou.PrimGroup] ) -> hou.BoundingBox: """Get the bounding box of the group. :param group: The group to get the bounding box for. :return: The bounding box for the group. """ group_type = utils.get_group_type(group) # Calcu...
60,799