content
stringlengths
22
815k
id
int64
0
4.91M
def indent(elem, level=0): """ generate pretty looking XML, based upon: http://effbot.org/zone/element-lib.htm#prettyprint """ i = "\n" + level*" " if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for elem in elem: indent(elem...
5,294,700
def remove_indices_from_dict(obj): """ Removes indices from a obj dict. """ if not isinstance(obj, dict): raise ValueError(u"Expecting a dict, found: {}".format(type(obj))) result = {} for key, val in obj.items(): bracket_index = key.find('[') key = key[:bracket_index] i...
5,294,701
def relative_uri(base, to): """Return a relative URL from ``base`` to ``to``.""" if to.startswith(SEP): return to b2 = base.split(SEP) t2 = to.split(SEP) # remove common segments (except the last segment) for x, y in zip(b2[:-1], t2[:-1]): if x != y: break b2....
5,294,702
def MatrixChainMultiplicationDp(array, n): """ n is length of array """ dp = [[None for _ in range(n + 1)] for _ in range(n + 1)] for i in range(n + 1): for j in range(n + 1): if i == j: dp[i][j] = 0 else: dp[i][j] = sys.maxsize ...
5,294,703
def find_block(csv, name): """For an Illumina SampleSheet.csv, return a tuple of the index of the line containing the header specified by name, and the index of the line just past the end of the data block. `range(*r)` will index all lines for the block, starting at the header line. """ start = ...
5,294,704
def ootf_reverse_BT2100_HLG(F_D, L_B=0, L_W=1000, gamma=None): """ Defines *Recommendation ITU-R BT.2100* *Reference HLG* reverse opto-optical transfer function (OOTF / OOCF). Parameters ---------- F_D : numeric or array_like :math:`F_D` is the luminance of a displayed linear component ...
5,294,705
def _pauli_process_tomo_settings(qubits): """Yield settings over +-XYZ basis cross I,X,Y,Z operators Used as a helper function for generate_process_tomography_experiment :param qubits: The qubits to tomographize. """ for states in itertools.product([plusX, minusX, plusY, minusY, plusZ, minusZ], ...
5,294,706
def cancel_and_stop_intent_handler(handler_input): """Single handler for Cancel and Stop Intent.""" # type: (HandlerInput) -> Response speech_text = "Alla prossima!" return handler_input.response_builder.speak(speech_text).response
5,294,707
def main(): """ Defines the main entry point of the script. """ # Declare a constant to store the excel file name. WINE_DATA_SET_FILE = "DrinkDurationDataset.xlsx" # Loads and read file from excel data_sheet = load_wine_dataset_sheet(WINE_DATA_SET_FILE) # Cleans the loaded file ...
5,294,708
def make_twill_pattern(n:Union[int, tuple[int]] = 2, warp_n:int = 2, weft_n:int = 2) -> np.ndarray: """Returns twill pattern matrix extended for warp and weft patterns. n is the number of over-unders. With n = 1 we get a plain weave. Args: n (int, optional): specifies over-...
5,294,709
def assert_no_undefined_references( snapshot=None, soft=False, session=None, df_format="table" ): # type: (Optional[str], bool, Optional[Session], str) -> bool """Assert that there are no undefined references present in the snapshot. :param snapshot: the snapshot on which to check the assertion :pa...
5,294,710
def main() -> None: """Initialize and run bot. Notes: While this does check for presence of the necessary inis, it does not check for syntactical validity of any of the configs other than the logging config, as it is actually loaded right away. This may be changed later to load...
5,294,711
def divisors(number: int) -> List[int]: """ This function calculates and returns a list of all divisors that a given number has, e.g. f(number=24) -> [1, 2, 3, 4, 6, 8, 12, 24] :param number: The number whose divisors are to be calculated :return: A list of integer divisors """ if number < 1...
5,294,712
def sim_sym_resp(emotion, ti, tf, t_plot=None, dt=0.1, plot=True, n_periods=1, d_e=None, delay=0.0): """ :param emotion : string that define what emotion is simulated :param ti : time in seconds when eigenmotion starts :param dt : time step in seconds for the simulation ...
5,294,713
def timestamp_from_sbs(data): """Create new timestamp from SBS data Args: data (hat.sbs.Data): SBS data Returns: Timestamp: timestamp """ return Timestamp(s=data['s'], us=data['us'])
5,294,714
def _h1_cmp_costheta_ ( h1 , h2 , density = False ) : """Compare the 1D-historgams (as functions) Calculate the scalar product and get ``cos(theta)'' from it >>> h1 = ... ## the first histo >>> h2 = ... ## the second histo ...
5,294,715
def buff_exists(name): """ Return true or false if the buffer named `name` exists """ return buffwinnr(name) != -1
5,294,716
def plugin_selection(args): """ Selects the plugin to be used based on the parser :param args: parer arguments :return: """ if args.default: get_audit_report(args.api_key, args.user, args.password, args.cloud) elif args.version: print('zs_audit_report version 1.1') else: ...
5,294,717
def load_jsonl(filename): """Load json lines formatted file""" import json with open(filename, "r") as f: return list(map(json.loads, f))
5,294,718
def verify_prefix( node_list, prefix, prefix_len=64, stable=True, priority='med', on_mesh=False, slaac=False, dhcp=False, configure=False, default_route=False, preferred=True, ): """ This function verifies that the `prefix` is present on all the nodes in the `node_lis...
5,294,719
def send_u64(u64): """encode an int64 as two floats and send""" fs = struct.unpack('<ff', struct.pack('<Q', u64)) for f in fs: r.sendline(str(f))
5,294,720
def test_associate_attribute_to_page_instance_multiple_values(page): """Ensure multiple values in proper order are assigned.""" old_assignment = page.attributes.first() assert old_assignment is not None, "The page doesn't have attribute-values" assert old_assignment.values.count() == 1 attribute = ...
5,294,721
def IntCurveSurface_TheHCurveTool_FirstParameter(*args): """ :param C: :type C: Handle_Adaptor3d_HCurve & :rtype: float """ return _IntCurveSurface.IntCurveSurface_TheHCurveTool_FirstParameter(*args)
5,294,722
def _get_ecc608_certificate_template_file(ecc_serial_number, cert_type): """ Retrieves a template (/example) ECC608 certificate based :param ecc_serial_number: Serial number of ECC :type ecc_serial_number: binary :param cert_type: Type of certificate ('device' or 'signer') :type cert_type: str ...
5,294,723
def save_data(df, database_filename): """ Save Data function Arguments: df -> Clean data Pandas DataFrame database_filename -> database file (.db) destination path """ engine = create_engine('sqlite:///'+ database_filename) df.to_sql('merged', engine, index=False,if_exists='...
5,294,724
def CopyFile(source, destination): """Copies a file to the destination. Remove an old version if needed.""" if os.path.isfile(destination): # Remove the old one if exists. RemoveFile(destination) dest_dirname = os.path.dirname(destination) if not os.path.isdir(dest_dirname): os.makedirs(dest_dirname) ...
5,294,725
def synthesize_text(text, client): """Synthesizes speech from the input string of text.""" # input format input_text = texttospeech.types.SynthesisInput(text=text) # Note: the voice can also be specified by name. # Names of voices can be retrieved with client.list_voices(). voice = texttospeech.types.Voic...
5,294,726
def test_progress_bar_print_disabled(tqdm_write, mock_print, tmpdir): """ Test that printing in LightningModule goes through built-in print function when progress bar is disabled. """ model = PrintModel() bar = ProgressBar() trainer = Trainer( default_root_dir=tmpdir, num_sanity_val_step...
5,294,727
def plotPotentialObjectToFile(fileobj, lowx, highx, potentialObject, steps=10000): """Convenience function for plotting energy of pair interactions given by instances of :class:`atsim.potentials.Potential` obtained by calling `potential` `.energy()` method. Data is written to a text file as two columns (r and ...
5,294,728
def setup(): """ 生成默认配置文件. """ print("\nIt seems that you're running this for the first time.") while True: print("Install? (Y/N)", end=' ') op = input() if op == 'Y' or op == 'y': print("Installing...", end=' ') default_json = '{\n\t"ID": "type_your_...
5,294,729
def get_test_clinvar_record(): """The test file contains an extract of ClinVar XML for the record RCV000002127.""" return [r for r in clinvar_xml_utils.ClinVarDataset(test_clinvar_record_file)][0]
5,294,730
def random_genbank_accession(invalid_data): """ Generate Random GenBank Accession return: string formatted to imitate a GenBank submission accession for viral genome assemlby. """ # prefixs for GenBank direct submissions, excluding single letter 'U' option. prefix = ['AF', 'AY', 'DQ', 'EF', 'E...
5,294,731
def install(ctx, modules, py, requirement): # pragma: no cover """ Install a named module(s) onto the device. Multiple modules can be installed at once by providing more than one module name, each separated by a space. Option -r allows specifying a text file to install all modules listed in the...
5,294,732
def entropy(p): """Calculate the Entropy for a sample :param p: The probability or proportion of the samples belonging to a class :returns: The Entropy :rtype: float """ return -p * np.log2(p) - (1 - p) * np.log2(1 - p)
5,294,733
def get_rexpro(stype='sync'): """ Obtain the RexPro Socket, Connection and Connection Pool classes for the desired application Options include: - 'sync' - Default, Synchronous python sockets - 'gevent' - with gevent concurrency - 'eventlet' - with eventlet concurrency Example: .. co...
5,294,734
def to_xml(number): """Return the XML form of the ISAN as a string.""" number = format(number, strip_check_digits=True, add_check_digits=False) return '<ISAN root="%s" episode="%s" version="%s" />' % ( number[0:14], number[15:19], number[20:])
5,294,735
def extract_requirements(func) -> Set[str]: """TODO: extract PyPI name instead""" res = list() clean_namespace = loads(dumps(func)).__globals__ for obj in clean_namespace.values(): pkg = getpackage(obj) if pkg is not None: pkg_name = pkg.__name__ pkg_version = get...
5,294,736
def dict_findall(dictionary, element): """ Returns the keys whose values in `dictionary` are `element` or, if none exists, []. >>> d = {1:4, 3:4} >>> dictfindall(d, 4) [1, 3] >>> dictfindall(d, 5) [] """ res = [] for (key, value) in dictio...
5,294,737
def erastothenes(): # {{{1 """All prime numbers (generated using Sieve of Eratosthenes; adapted from Python Cookbook).""" composites = {} # maps composite ints to first found prime factor yield 2 for k in itertools.count(3, 2): p = composites.pop(k, None) if...
5,294,738
def set_union(a, b, validate_indices=True): """Compute set union of elements in last dimension of `a` and `b`. All but the last dimension of `a` and `b` must match. Example: ```python import tensorflow as tf import collections # [[{1, 2}, {3}], [{4}, {5, 6}]] a = collections.OrderedDict([ ...
5,294,739
def eq_assoc_args( op, a_args, b_args, n=None, inner_eq=eq, no_ident=False, null_type=etuple ): """Create a goal that applies associative unification to an operator and two sets of arguments. This is a non-relational utility goal. It does assumes that the op and at least one set of arguments are groun...
5,294,740
def account_edit(request, pk=None): """ """ return edit( request, report_model=Report, form_model=AccountForm, model=Account, pk=pk )
5,294,741
def preprocess_data(src, dst, src_meta, n_processes=15): """ Calls for distibuted preprocessing of the data. Parameters: ----------- src: string Path to data directory. dst: string Path to directory where preprocessed data shall be stored. stc_meta: stri...
5,294,742
def make_cammesa_url_v2(case,caseNum,dict_to_update,url_case=0): """ """ caseNum=int(caseNum) if url_case==0: base='https://aplic.cammesa.com/complemento-portal/descargar?type=csv&value=ChtDem_' end='.xml&header=datosDemandas' elif url_case==1: base='https://aplic.cammesa.com...
5,294,743
def oauth2_assertion_config(application_id, application_name, client_string, consumer_key, consumer_secret): """Convenience function for creating an OAuth2 assertion configuration. :param application_id: The unique identifier of the client applic...
5,294,744
def midiae_ld_summary(ld_feat, outputs, step, db_key='loudness_db'): """Makes plots to inspect loudness/velocity components of MidiAE. Args: ld_feat: The input loudness feature to the network. outputs: Output dictionary from the MidiAe net. step: The step that the optimizer is currently on db_key: ...
5,294,745
def drop_invalid_trip_durations(data_frame: pd.DataFrame) -> pd.DataFrame: """Remove rows where we couldn't calculate trip duration or it was over 90 minutes.""" data_frame = data_frame.dropna(subset=['trip_duration_minutes']) data_frame = data_frame[data_frame['trip_duration_minutes'] <= 90] return da...
5,294,746
def epidemic_163(indicator="实时"): """ 网易网页端-新冠状病毒-实时人数统计情况 国内和海外 https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other&#map_block https://news.163.com/special/epidemic/?spssid=93326430940df93a37229666dfbc4b96&spsw=4&spss=other& :return: 返回国内各地区和海外地区情况 ...
5,294,747
def getPartnerURL(request): """ 파트너 포인트 충전 URL을 반환합니다. - 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다. - https://docs.popbill.com/htcashbill/python/api#GetPartnerURL """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # CHRG-파트너 포인트충전 TOGO = "CHRG" url = htCashbil...
5,294,748
def test_zone102_zone102_v02_xml(mode, save_output, output_format): """ Test built-in type xs:dateTimeStamp restriction from xs:dateTimeStamp """ assert_bindings( schema="saxonData/Zone/zone102.xsd", instance="saxonData/Zone/zone101.v02.xml", class_name="Doc", version="1....
5,294,749
def merge( left: pandas.core.frame.DataFrame, right: pandas.core.frame.DataFrame, how: Literal["left"], left_on: Literal["e"], right_on: Literal["b"], ): """ usage.dask: 1 """ ...
5,294,750
def test_get_optimizer_not_dict(): """ Test assertion error raised if config passed not dict. """ with pytest.raises(AssertionError): optimizer.get_optimizer(["name"])
5,294,751
def _read_get_graph_source_citation_section(jcamp_dict: dict) -> List[str]: """ Extract and translate from the JCAMP-DX dictionary the SciData JSON-LD citations in the 'sources' section from the '@graph' scection. :param jcamp_dict: JCAMP-DX dictionary to extract citations from :return: List for ci...
5,294,752
def AddLoggingArg(parser): """Adds argument for specifying the logging level for an execution.""" log_level = base.ChoiceArgument( '--call-log-level', choices={ 'none': 'Perform no call logging.', 'log-all-calls': 'Log all calls to subworkflows or library ...
5,294,753
def list_components(): """ List the installed components """ _raise_error("Use 'az --version' to list component versions.")
5,294,754
def set_link_state(): """ Set link state :return: 201 if success, a new pending link if fail """ message = request.get_json() if message['state'] == 'crawled': db_manager.operate_on_link_relation('UPDATE_STATE', message['link'], ...
5,294,755
def test_get_environment_error(): """Raise an error if the path is incorrect.""" with pytest.raises(OSError): champollion.parser.fetch_environment("")
5,294,756
def join_marketing_funnel_with_brazilian_ecommerce() -> None: """ Joins the Marketing Funnel dataset with Brazilian E-Commerce Public Dataset by Olist, through sellers and order items, so we can get the sellers location and the products sold by these. """ show_files() write_log("Merging leads a...
5,294,757
def draw_circle_mask(canvas, center_x, center_y, outer_radius, colour, threshold, fill=True): """Draw circle mask on NumPy array. Apply algorithm for drawing anti-aliased circle. Draw points only when the alpha blending is above a set threshold. Only given _colour value is drawn. Intended usage is as a...
5,294,758
def main(): """Main program entry point.""" # argument parser and options parser = argparse.ArgumentParser( description="More comprehensive version of bjobs." ) exg = parser.add_mutually_exclusive_group() exg.add_argument( "-w", "--wide", help="show more detailed (wide) i...
5,294,759
def _datasets_since_(dataset, since, paths, recursive, recursion_limit): """Generator""" # rely on diff() reporting sequentially across datasets cur_ds = None ds_res = None for res in diff_dataset( dataset=dataset, fr=since, # we never touch unsaved content ...
5,294,760
def print_stdout(): """ whether or not to print to stdout """ return _flag(PRINT_STDOUT_KEY, 'print_stdout', 'p', msgs=('print log to stdout as well?',))
5,294,761
def read_input_lines(): """Open today's input data and return it as a list of lines Returns: [str] Lines in 'input.txt' """ with open('input.txt') as in_file: data = in_file.read().strip().splitlines() return data
5,294,762
def verify_abdominal_wall(x, y, frame, slice_id, target_path, type=AbdominalContourPart.anterior_wall): """ Allows to visually evaluate the detection of the specified abdominal cavity part by plotting abdominal cavity contour over the frame and the detected cavity part over the frame next to each other ...
5,294,763
def payToPubKeyHashScript(pkHash): """ payToAddrScript creates a new script to pay a transaction output to a the specified address. Args: pkHash (ByteArray): The pubkey hash to pay to. Returns: ByteArray: The script that pays to the pubkey hash. """ if len(pkHash) != crypto...
5,294,764
def deltaify_traces(traces, final_byte_duration=9999): """Convert absolute start times in traces to durations. Traces returned by `read_traces_csv` pair bytes with start times. This function computes how long each byte remains on the bus and replaces the start time with this value in its output. Note that the ...
5,294,765
def consume(iterator): """Consume an iterable at C speed.""" deque(iterator, maxlen=0)
5,294,766
def lonely_pixel(pixs, pos): """ pixs: image.load() pos: (x,y) """ x,y = pos xy = [-1,0,1] for i in xy: for j in xy: if i==0 and j==0: continue # pixel self try: p = pixs[x+i,y+j] except IndexError: ...
5,294,767
def embedding_lookup_sparse(params, sp_ids, sp_weights, partition_strategy="mod", name=None, combiner=None, max_norm=None): """Computes embeddings for...
5,294,768
def parse_ldap_file(file_name, entries=None): """ parse the LDAP results into a coherent form (this code is way too complex for what it needs to do ATM) """ f = open(file_name) entries = defaultdict(list) if entries is None else entries entry = {} for line in f: line = line.strip() if line !=...
5,294,769
def load(cookie: str) -> domain.Session: """Load a session by cookie value.""" return current_session().load(cookie)
5,294,770
def test_batch_05(): """ Test batch: batch_size=1 (minimum valid size), drop_remainder default """ logger.info("test_batch_05") # define parameters batch_size = 1 # apply dataset operations data1 = ds.TFRecordDataset(DATA_DIR, shuffle=ds.Shuffle.FILES) data1 = data1.batch(batch_size...
5,294,771
def trnsdeq_iter(h,T): """ Given """ new_h = _np.array([[[trnsdeq_step(h,T,i,j,k) for k in range(h.shape[2])] for j in (range(h.shape[1]))] for i in _tqdm(range(h.shape[0]))]) return new_h/_np.sum(new_h)
5,294,772
def coor2coor(srs_from, srs_to, x, y): """ Transform coordinates from srs_from to srs_to input: srs_from and srs_to are EPSG number (e.g., 4326, 3031) x and y are x-coord and y-coord corresponding to srs_from return: x-coord and y-coord in srs_to """ srs_from = pypro...
5,294,773
def rzpad(value, total_length): """ Right zero pad value `x` at least to length `l`. """ return value + b"\x00" * max(0, total_length - len(value))
5,294,774
def quantize_tempos(tempos: List[TempoChange], time_division: int, beat_res: int): """ Quantize the times of tempo change events. :param tempos: tempo changes to quantize :param time_division: MIDI time division / resolution, in ticks/beat (of the MIDI being parsed) :param beat_res: number of frames (t...
5,294,775
def getTestSuite(): """ set up composite test suite """ test_suite = unittest.TestSuite([]) test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestAzureP2P)) #test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestDocStrings)) return test_suite
5,294,776
def read_cube(infile, allow_huge=True): """ Read cube from CASA image file. Includes a switch for large cubes, where getchunk may fail. """ if allow_huge: casaStuff.exportfits(imagename=infile, fitsimage=infile + '.fits', stokeslast=Fals...
5,294,777
def visual_map(visual_type='color', visual_range=None, visual_text_color=None, visual_range_text=None, visual_range_color=None, visual_range_size=None, visual_orient='vertical', visual_pos="left", vis...
5,294,778
def calc_precision_recall(img_results): """Calculates precision and recall from the set of images Args: img_results (dict): dictionary formatted like: { 'img_id1': {'true_pos': int, 'false_pos': int, 'false_neg': int}, 'img_id2': ... ... ...
5,294,779
def compose(*funcs): """Returns a function that is the composition of multiple functions.""" def wrapper(x): for func in reversed(funcs): x = func(x) return x return wrapper
5,294,780
def svm_model(C=10**1.5, gamma='scale', kernel='rbf'): """SVM""" return svm.SVC(kernel=kernel, gamma=gamma, C=C, probability=True)
5,294,781
def fmgr_set_ha_mode(fmgr, paramgram): """ :param fmgr: The fmgr object instance from fortimanager.py :type fmgr: class object :param paramgram: The formatted dictionary of options to process :type paramgram: dict :return: The response from the FortiManager :rtype: dict """ # INIT A ...
5,294,782
def cinder_client(os_creds): """ Creates and returns a cinder client object :return: the cinder client """ return Client(version=os_creds.volume_api_version, session=keystone_utils.keystone_session(os_creds), region_name=os_creds.region_name)
5,294,783
def compose(*functions): """ Compose all the function arguments together :param functions: Functions to compose :return: Single composed function """ # pylint: disable=undefined-variable return reduce(lambda f, g: lambda x: f(g(x)), functions, lambda x: x)
5,294,784
def load(opt): """Select checkpoint to load.""" ckpt = opt.epochNum if ckpt == 0: print("".ljust(4) + "=> No checkpoint to load. Retrain the model.") return None else: if ckpt == -1: print("".ljust(4) + "=> Loading the latest checkpoint.") ckpt_path = os.p...
5,294,785
def mul_fft(f_fft, g_fft): """Multiplication of two polynomials (coefficient representation).""" deg = len(f_fft) return [f_fft[i] * g_fft[i] for i in range(deg)]
5,294,786
def read_info(options): """Load affine transforms and space info of other volumes""" def read_file(fname): o = struct.FileWithInfo() o.fname = fname o.dir = os.path.dirname(fname) or '.' o.base = os.path.basename(fname) o.base, o.ext = os.path.splitext(o.base) if...
5,294,787
def atr_cache_nb(high_ts, low_ts, close_ts, windows, ewms, adjust): """Caching function for `vectorbt.indicators.basic.ATR`.""" # Calculate TR here instead of re-calculating it for each param in atr_apply_nb tr = true_range_nb(high_ts, low_ts, close_ts) cache_dict = dict() for i in range(len(windows...
5,294,788
def custom_decode_labels(mask, num_images=1, num_classes=20): """Decode batch of segmentation masks. Args: mask: result of inference after taking argmax. num_images: number of images to decode from the batch. num_classes: number of classes to predict (including background). Returns: ...
5,294,789
def _merge_splitted_sheets(merge_dict, data_list): """ 获取被拆分的sheet后,将其合在一起 结果放在merge_dict里面 Args: merge_dict: [dict]合成结果, key为id, value为合成后的数据字典 data_list: [list]当前sheet的导表结果 Returns: None """ for data in data_list: if settings.ID_COLUMN_NAME not in data: ...
5,294,790
def populate_runtime_info_for_random_queries( impala, use_kerberos, candidate_queries, query_count, query_timeout_secs, results_dir ): """Returns a list of random queries. Each query will also have its runtime info populated. The runtime info population also serves to validate the query. """ start_time = da...
5,294,791
def clean_text(text): """ Cleans abstract text from scopus documents. Args: text (str): Unformatted abstract text. Returns: (str) Abstract text with formatting issues removed. """ if text is None: return None try: cleaned_text = re.sub("© ([0-9])\w* The Author(...
5,294,792
def web_context(req, resource=None, id=False, version=False, parent=False, absurls=False): """Create a rendering context from a request. The `perm` and `href` properties of the context will be initialized from the corresponding properties of the request object. >>> from trac.test impor...
5,294,793
def a_vs_b(ship_a, ship_b, trials, attack_range): """This uses a random agent to choose actions during attacks from ship_a to ship_b. Args: ship_a ((Ship, str)): Attacker and hull zone tuple. ship_b ((Ship, str)): Defender and hull zone tuple. trials (int): Number of trials in average calcula...
5,294,794
def activity_index(windowed_array): """ Compute activity index of windowed tri-axis accelerometer signal. Activity index defined here as: sqrt(mean(vx, vy, vz)) where vx, vy, vz are the variances in x, y, z Activity index accounting for device specific systematic variance is def...
5,294,795
def getPathToRoot(label): """ Returns all the nodes present in all the paths from node 'label' to root. """ path = [label] if len(labelDict[label]['parents'])==0: return path for item in labelDict[label]['parents']: path += getPathToRoot(item) return list(set(path))
5,294,796
def put_get_int64(table, rowkey, cf, qu, value): """ put/get int64 """ try: table.PutInt64(rowkey, cf, qu, value) print("i got:" + str(table.GetInt64(rowkey, cf, qu, 0))) except TeraSdkException as e: print(e.reason)
5,294,797
def macAddress(value): """Return true if mac-address is valid, otherwise - false.""" return False
5,294,798
def merge_channels(x): """ Takes a NxMx4 array and returns a 2Nx2M array by stacking the 4 2D images in a 2x2 grid. :param x: Input array :return: Output array """ return np.vstack((np.hstack((x[:, :, 0], x[:, :, 1])), np.hstack((x[:, :, 2], x[:, :, 3]))))
5,294,799