content
stringlengths
22
815k
id
int64
0
4.91M
def reduce_dict(input_dict, average=True): # ref: https://github.com/pytorch/vision/blob/3711754a508e429d0049df3c4a410c4cde08e4e6/references/detection/utils.py#L118 """ Args: input_dict (dict): all the values will be reduced average (bool): whether to do average or sum Reduce the values ...
48,600
def dataId_to_dict(dataId): """ Parse an LSST dataId to a dictionary. Args: dataId (dataId): The LSST dataId object. Returns: dict: The dictionary version of the dataId. """ return dataId.to_simple().dict()["dataId"]
48,601
def norm_max(tab): """ Short Summary ------------- Normalize an array or a list by the maximum. Parameters ---------- `tab` : {numpy.array}, {list} input array or list. Returns ------- `tab_norm` : {numpy.array}, {list} Normalized array. """ tab_norm = t...
48,602
def getHoliday(holidayName): """Returns a specific holiday. Args: holidayName (str): The name of the holiday to return. Case-sensitive. Returns: HolidayModel: The holiday, as a HolidayModel object, or None if not found. """ print(holidayName) return None
48,603
def draw_object(obj, bb: "BBLike" = None, ax=None): """ Draw easymunk object using matplotlib. """ options = DrawOptions(ax or plt.gca(), bb=bb) options.draw_object(obj) return ax
48,604
def hash_mod(text, divisor): """ returns the module of dividing text md5 hash over given divisor """ if isinstance(text, six.text_type): text = text.encode('utf8') md5 = hashlib.md5() md5.update(text) digest = md5.hexdigest() return int(digest, 16) % divisor
48,605
def roll_next_challenge(state, hmac_key, inner_dict): """ When we have the HMAC-SHA1 key in clear, generate a random challenge and compute the expected response for that challenge. hmac_key is a 20-byte bytestring """ if len(hmac_key) != 20 or not isinstance(hmac_key, bytes): hmac_key = ...
48,606
def normalize_mac_address_table(input_string): """ :param input_string: cli string has been get from network device by command like "show mac-address table" :return: {(mac_address', 'vlan'): 'l2_interface'} """ res = {} same_local_mac_address_count: int = 0 mac_address_number: int = 0 ...
48,607
def _get_exploration_memcache_key(exploration_id): """Returns a memcache key for an exploration.""" return 'exploration:%s' % exploration_id
48,608
def corr_filter( corrs: np.ndarray, value_range: Optional[Tuple[float, float]] = None, k: Optional[int] = None, ) -> Tuple[np.ndarray, np.ndarray]: """ Filter correlation values by k and value_range """ assert (value_range is None) or ( k is None ), "value_range and k cannot be ...
48,609
def isValid(text): """ Returns True if the input is related to jokes/humor. Arguments: text -- user-input, typically transcribed speech """ return bool(re.search(r'WATCH|OUT', text, re.IGNORECASE))
48,610
def set_brevet(): """ sets the brevet distance """ app.logger.debug("Got a JSON request"); calculate.brevet = request.args.get('brevet', 0, type=int) return jsonify(result=calculate.brevet)
48,611
def pairs_from_array(a): """ Given an array of strings, create a list of pairs of elements from the array Creates all possible combinations without symmetry (given pair [a,b], it does not create [b,a]) nor repetition (e.g. [a,a]) :param a: Array of strings :return: list of pairs of strings """ pairs = l...
48,612
def bump_pre(filename, prebase='pre'): """ Bump the "pre" portion of the version from the input YAML filename """ v = semver.VersionInfo.parse(emit_version(filename)) if v.prerelease is None: new_ver = str(v.replace(prerelease=prebase+'.1')) else: new_ver = str(v.bump_prerelease(...
48,613
def test_boxscore_summary(): """ tests the boxscoresummaryv2 endpoint of the Boxscore class """ example_boxscore = BoxScore(headers=HEADERS, endpoint='boxscoresummaryv2', game_id='0021500002') table_names = example_boxscore.data.keys() ...
48,614
def cleanse_comments(line): """Removes //-comments and single-line C-style /* */ comments. Args: line: A line of C++ source. Returns: The line with single-line comments removed. """ comment_position = line.find('//') if comment_position != -1 and not is_cpp_string(line[:comment_pos...
48,615
def get_next_document_id(request, document_id): """Gets the id of the next document, by the current document's id Gets the id of the next document, by the current document's id The function is accessible for users with 'read_project' permission of the project and the owner of the project. Args: ...
48,616
def is_merged(request): """Makes tests try both merged and closed pull requests.""" return request.param
48,617
def patchy_fluidsub(kdry, mu, kfls, vfrac): """Patch fluid substitution for non-homogenous fluid mixing Args: kdry (array_like): dry frame rock bulk modulus mu (array_like): rock shear modulus kfls (array_like): list or array of length M fluid moduli vfrac (array_like): l...
48,618
def is_table(base_url: str, token: str) -> bool: """check if service layer is a table""" params: Dict[str, str] = init_params(token) type_layer = cast(Dict[str, str], request(base_url.rstrip('/'), params))['type'] return type_layer.lower() == 'table'
48,619
def shared_options(option_list): """Define decorator for common options.""" def _shared_options(func): for option in reversed(option_list): func = option(func) return func return _shared_options
48,620
def test_writeOldFormat(newFormatRootNode, tmpdir): """ code to parse behavior.xar and get root looking for no throw and root not None """ generator = xar_format_generator.XarFormatGenerator(newFormatRootNode) generator.export_to_xar(str(tmpdir))
48,621
def complex_key(c: complex) -> Any: """Defines a sorting order for complex numbers.""" return c.real != int(c.real), c.real, c.imag
48,622
def test_param_construct(): """Test constructing Message objects""" msg = Message(None, None, "PRIVMSG", "#channel", "Message thing") assert str(msg) == "PRIVMSG #channel :Message thing" msg = Message(None, None, "PRIVMSG", ["#channel", "Message thing"]) assert str(msg) == "PRIVMSG #channel :Messag...
48,623
def make_raw_query_nlist_test_set(box, points, query_points, mode, r_max, num_neighbors, exclude_ii): """Helper function to test multiple neighbor-finding data structures. Args: box (:class:`freud.box.Box`): Simulation box. points ((:math:`N_{points...
48,624
def runs_new_in_exp(exp='xpptut15', procname='pixel_status', verb=0) : """Returns list of (4-char str) runs which are found in xtc directory and not yet listed in the log file, e.g. ['0059', '0060',...] """ runs_log = runs_in_log_file(exp, procname) runs_xtc = runs_in_xtc_dir(exp) runs_new = ...
48,625
def cart_pole(): """Generate Robot instance of classical CartPole dynamic system.""" #TODO: bring it to the new notation with 0-frame robo = Robot('CartPole', 2, 2, 2, False) robo.ant = (-1, 0, 1) robo.sigma = (0, 1, 0) robo.alpha = (0, pi/2, pi/2) robo.d = (0, 0, 0) robo.theta = (0, pi/...
48,626
def pytest_runtest_makereport(item, call): """ Captures the test results for later reporting. This will also halt testing if a base failure is encountered (can be overridden with continue-on-failure) """ outcome = yield if outcome.get_result().when != "call": return # only capture resu...
48,627
def get_targets( initial_positions, trajectory_target_positions): """Returns the averaged particle mobilities from the sampled trajectories. Args: initial_positions: the initial positions of the particles with shape [n_particles, 3]. trajectory_target_positions: the absolute positions of the ...
48,628
def test_remove_nodes_from(atoms, bonds, interactions, removed, expected): """ Test whether molecule.remove_nodes_from also removes the corresponding interactions """ molecule = vermouth.molecule.Molecule() molecule.add_nodes_from(atoms) molecule.add_edges_from(bonds) for type_, atoms, p...
48,629
def get_campaign_goal(campaign, goal_identifier): """Returns goal from given campaign and Goal_identifier. Args: campaign (dict): The running campaign goal_identifier (string): Goal identifier Returns: dict: Goal corresponding to goal_identifer in respective campaign """ i...
48,630
def main(): """The entry point for the program.""" stone_path = os.path.abspath('stone') print(stone_path) generator_path = os.path.abspath('generator') print(generator_path) spec_path = os.path.abspath('spec') print(spec_path) specs = glob.glob(spec_path + '/*.stone') # Arbitrary sorti...
48,631
def vox2mm(ijk, affine): """ Convert matrix subscripts to coordinates. .. versionchanged:: 0.0.8 * [ENH] This function was part of `nimare.transforms` in previous versions (0.0.3-0.0.7) Parameters ---------- ijk : (X, 3) :obj:`numpy.ndarray` Matrix subscripts for coordinates b...
48,632
def getChanprofIndex(chanprof, profile, chanList): """ List of indices into the RTTOV chanprof(:) array corresponding to the chanlist. NB This assumes you've checked the chanlist against chanprof already. """ ilo = sum(map(len, chanprof[:profile-1])) ichanprof = [] for c in chanList: ...
48,633
def test_horodecki_invalid_dim(): """Tests for invalid dimension inputs.""" with np.testing.assert_raises(ValueError): horodecki(0.5, [3, 4])
48,634
def _get_blob_size_string(blob_key): """Return blob size string.""" blob_size = blobs.get_blob_size(blob_key) if blob_size is None: return None return utils.get_size_string(blob_size)
48,635
def parse_args(): """Accepts path arguments for eml or directory.""" outpath = "C:\\Utilities\\Logs" parser = argparse.ArgumentParser() parser.add_argument("-f", "--file", help="Path to EML file", required=False) parser.add_argument("-p", "--path", help="Directory holding eml...
48,636
def main(): """ main """ module = AnsibleModule( argument_spec=dict( state=dict(default='present', choices=['present']), url=dict(required=True), api_key=dict(required=True), password_list_id=dict(required=False), match_field=dict(required=Fals...
48,637
def masked_softmax_full(input_layer, n_nodes, batch_size): """ A Lambda layer to compute a lower-triangular version of the full adjacency. Each row must sum up to one. We apply a lower triangular mask of ones and then add an upper triangular mask of a large negative number. After that we return the...
48,638
def match_backends_and_tasks(backends, tasks): """Returns tuples of matching (backend, task) pairs, as matched by IP and port. Each backend will be listed exactly once, and each task will be listed once per port. If a backend does not match with a task, (backend, None) will be included. If a task's port doe...
48,639
def _drop_path(x, keep_prob): """ Drops out a whole example hiddenstate with the specified probability. """ batch_size = tf.shape(x)[0] noise_shape = [batch_size, 1, 1, 1] random_tensor = keep_prob random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32) binary_tensor = tf.f...
48,640
def read_pipeline_definition(file_path): """Function reads the yaml pipeline definitions. Function reads the yaml pipeline definitions. We also remove the variables key as that was only used for yaml placeholders. Args: file_path (str): Path to the pipeline definition. Returns: dict: ...
48,641
def detect_text(path): """Detects text in the file.""" client = vision.ImageAnnotatorClient() with io.open(path, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.text_detection(image=image) texts = response.text_a...
48,642
def test_water_clustering_production(): """ Tests water clustering running from YAML. """ yaml = os.path.join(test_path, "clustering_xtc", "water_clustering.yaml") parameters = main.run_platform_from_yaml(yaml) # Checking if water indices to track are correctly parsed assert parameters.wate...
48,643
def find_dataset_ind(windows_ds, win_ind): """Taken from torch.utils.data.dataset.ConcatDataset. """ return bisect.bisect_right(windows_ds.cumulative_sizes, win_ind)
48,644
def from_moment(w): """Converts a moment representation w to a 3D rotation matrix.""" length = vectorops.norm(w) if length < 1e-7: return identity() return rotation(vectorops.mul(w,1.0/length),length)
48,645
def add_menu(data): """ 新增 :param data: :return: """ i = SysMenu.insert(data).execute() return i
48,646
def program( path: str, entrypoint: str, channel: str = "TEST", memory: int = settings.DEFAULT_VM_MEMORY, private_key: Optional[str] = settings.PRIVATE_KEY_STRING, private_key_file: Optional[str] = settings.PRIVATE_KEY_FILE, print_messages: bool = False, p...
48,647
def compute_distance_matrix(m1: np.ndarray, m2: np.ndarray, dist_func: np.ndarray, row_wise: bool = False) \ -> np.ndarray: """ Function for computing the pair-wise distance matrix between two arrays of vectors. Both matrices must have the same number ...
48,648
def term_table( strings: List[str], row_wise: bool = False, filler: str = "~" ) -> Iterator[Any]: """ :param strings: :param row_wise: :param filler: :return: """ max_str_len = max(len(str) for str in strings) + 5 terminal_cols = get_terminal_size((80, 20)).columns n_cols = term...
48,649
def create_pipelines_lingspam(): """Reproduces the pipelines evaluated in the LingSpam paper. I. Androutsopoulos, J. Koutsias, K.V. Chandrinos, George Paliouras, and C.D. Spyropoulos, "An Evaluation of Naive Bayesian Anti-Spam Filtering". In Potamias, G., Moustakis, V. and van Someren, M. (Eds.), ...
48,650
def data_init_backups(storage_class, location): """ Initialize bucket for backups""" if current_app.config['QUETZAL_DATA_STORAGE'] != 'GCP': click.secho('No bucket initialization performed: storage is not GCP.') return data_bucket = current_app.config['QUETZAL_GCP_BACKUP_BUCKET'] click...
48,651
def band_dos_plain_spin_polarized( band_folder, dos_folder, output='band_dos_plain_sp.png', up_color='black', down_color='red', linewidth=1.25, up_linestyle='-', down_linestyle=':', figsize=(6, 3), width_ratios=[7, 3], erange=[-6, 6], kpath=None, custom_kpath=None, ...
48,652
def _unsigned16(data, littleEndian=False): """return a 16-bit unsigned integer with selectable Endian""" assert len(data) >= 2 if littleEndian: b0 = data[1] b1 = data[0] else: b0 = data[0] b1 = data[1] val = (b0 << 8) + b1 return val
48,653
def train_ensemble( model_class, model_name, run_id, ensemble_folds, epochs, train_set, val_set, log, data_params, setup_params, restart_params, model_params, ): """ Train multiple models """ train_generator = DataLoader(train_set, **data_params) if ...
48,654
def app(): """ Main app """ put_markdown("""# A utility for analyzing a CSV file ## [Dr. Tirthajyoti Sarkar](https://www.linkedin.com/in/tirthajyoti-sarkar-2127aa7/) You can upload a data file (CSV) and, - display histograms of the data coulmns - download the summary statistics as a file. "...
48,655
def calculate_term_frequencies(tokens): """Given a series of `tokens`, produces a sorted list of tuples in the format of (term frequency, token). """ frequency_dict = {} for token in tokens: frequency_dict.setdefault(token, 0) frequency_dict[token] += 1 tf = [] for token...
48,656
def extract_from_directory(path_in, path_out): """Run Eidos on a set of text files in a folder. The output is produced in the specified output folder but the output files aren't processed by this function. Parameters ---------- path_in : str Path to an input folder with some text files...
48,657
def max(*l): """ Element-wise max of each of the input tensors (with Numpy-style broadcasting support). Args: *x (a list of Tensor): List of tensors for max. Returns: Tensor, the output """ return Max()(*l)[0]
48,658
def _plot_scores_as_grid( score_matrix, colour_map_object, min_colour_value, max_colour_value, x_tick_labels, x_axis_label, x_axis_text_colour, y_tick_labels, y_axis_label, y_axis_text_colour, title_string, output_file_name): """Plots model scores as 2-D grid. M = number of rows in grid...
48,659
def _edr_peak_trough_mean(ecg: pd.Series, peaks: np.array, troughs: np.array) -> np.array: """Estimate respiration signal from ECG based on `peak-trough-mean` method. The `peak-trough-mean` method is based on computing the mean amplitude between R peaks (`peaks`) and minima before R peaks (`troughs`). ...
48,660
def feature_stacking(n_splits=CV, random_state=None, use_proba=False, verbose=False, drop_words=0.): """ Args: n_splits: n_splits for KFold random_state: random_state for KFlod use_proba: True to predict probabilities of labels instead of labels verbose: True to print more info ...
48,661
def data(request): """ [メソッド概要] アクション履歴画面の一覧表示 """ logger.logic_log('LOSI00001', 'none', request=request) msg = '' lang = request.user.get_lang_mode() ita_flg = False mail_flg = False servicenow_flg = False filter_info = { 'tblname' : None, 'rulename' : None...
48,662
def get_default(): """Get the configuration from the source code""" return {name: dict(block()._asdict()) for name, _, block in triples}
48,663
def run(train_file, test_file, images_dir, masks_dir, dataset_dir): """Runs the download and conversion operation. """ if not tf.gfile.Exists(dataset_dir): tf.gfile.MakeDirs(dataset_dir) _EXPECTED_HEADER=('dataset;split;image;image_type;diagnosis;diagnosis_method;' 'diagnosis_difficulty...
48,664
def npulses(image_number,passno=0): """How many X-ray bursts to send to the sample as function of image number. image_number is 1-based, passno is 0-based. """ # When using sample translation the exposure may be boken up # into several passes. if passno != None: npulses = npulses_of_pass(image_n...
48,665
def power(base, exponent): """ This function takes 2 (two) arguments, the first being the base number, the second being the exponent. The base number is then raised to the power of the expoenent number, and this number is assigned to the "power" variable. """ power = base ** exponen...
48,666
def topk__dynamic(ctx, input: torch.Tensor, k: int, dim: Optional[int] = None, largest: bool = True, sorted: bool = True): """Rewrite `topk` for default backend. Cast k to tensor and makesure k is smaller than input.shape...
48,667
def GetLocalNodeId() -> int: """Returns the current local node id. If none has been set, a default is set and used.""" global _local_node_id if _local_node_id is None: SetLocalNodeId(DEFAULT_LOCAL_NODE_ID) return _local_node_id
48,668
def setup_logger(args): """Setup logger format and level""" level = logging.WARNING if args.quiet: level = logging.ERROR if args.quiet > 1: level = logging.CRITICAL if args.verbose: level = logging.INFO if args.verbose > 1: level = logging.DEBUG ...
48,669
def get_dlons_from_case(case: dict): """pull list of latitudes from test case""" dlons = [geo[1] for geo in case["destinations"]] return dlons
48,670
def account_info(info): """Extract user information from IdP response""" return dict( user=dict( email=info['User.email'][0], profile=dict( username=info['User.FirstName'][0], full_name=info['User.FirstName'][0])), external_id=info['User.em...
48,671
async def createrole(ctx, *, role): """Create a mentionable role.""" role_colors = [discord.Color.orange(), discord.Color.from_rgb(54, 57, 63)] guild = get_guild() role_name = ascii_only(role).lower().replace(" ", "_") role = get_role(role_name) if role != None: if role.color in role_col...
48,672
def add_conversion_fn(cls, module_fn_name=None) -> None: """Add to `format2fn` a mapping from a conversion type and builtin-class to a conversion method. The conversion type is determined form the module name. For example, in module mathics.format.svg the conversion type is "svg". The conversi...
48,673
def MangoYOLO(inputs, num_anchors, num_classes, **kwargs): """Create Tiny YOLO_v3 model CNN body in keras.""" x1 = compose( DarknetConv2D_BN_Leaky(16, (3,3), **kwargs), DarknetConv2D_BN_Leaky(16, (3, 3), strides=2, **kwargs), DarknetConv2D_BN_Leaky(32, (3,3), **kwargs), DarknetConv2D_BN_Leaky(32, (3, 3), stri...
48,674
def zone_max_matching(plan_a, plan_b): """ Determines the optimal bipartite matching of districts in plan_a to districts in plan_b to maximize the total population overlap. Both plans should have districts indexed from 1 to k, where k is some positive integer. Based on the concept of "...
48,675
def dyn_sim_feedback_discrete_time(A, Bu, Bd, x0, u, d, t_series, K): """ Simulate discrete-time ODE Args: A: discrete-time A Bu: discrete-time B for control Bd: discrete-time B for disturbance x0: Initial condition in numpy array nx*1 u: Control signal in numpy array...
48,676
def main(): """Create PowerMax Snapshot object and perform action on it based on user input from playbook""" obj = PowerMaxSnapshot() obj.perform_module_operation()
48,677
def test_binarytree_breadth_first(given_list, capsys): """ do we get correct order for breadth_first root, row of root children, row of those children, etc """ expected = [20, 18, 40, 12, 19, 31, 11, 14, 22, 33] given_list.breadth_first() out, err = capsys.readouterr() actual = [int(i) fo...
48,678
def cutter_indexes(shape, tile_shape): """ Make indexes for cutting. shape: shape of cutted data tile_shape: shape of tile """ # TODO přepis r1? # r0 = range(0, shape[0] - tile_shape[0] + 1, tile_shape[0]) # r1 = range(1, shape[1] - tile_shape[1] + 1, tile_shape[1]) # r2 = range(2,...
48,679
def get_recordings(mysql, symbol_id): """ Parameters ---------- mysql : dict Connection information symbol_id : int ID of a symbol on write-math.com Returns ------- list : A list of HandwrittenData objects """ connection = pymysql.connect(host=mysql['host...
48,680
def horiLine(lineLength, lineWidth=None, lineCharacter=None, printOut=None): """Generate a horizontal line. Args: lineLength (int): The length of the line or how many characters the line will have. lineWidth (int, optional): The width of the line or how many lines of text the line will take spa...
48,681
def decrypt(content, salt=None, key=None, private_key=None, dh=None, auth_secret=None, keyid=None, keylabel="P-256", rs=4096, version="aes128gcm"): """ Decrypt a data block :param content: Data to be decrypted :type content: str :param salt: Encryption salt :...
48,682
def _rescale_read_counts_if_necessary(n_ref_reads, n_total_reads, max_allowed_reads): """Ensures that n_total_reads <= max_allowed_reads, rescaling if necessary. This function ensures that n_total_reads <= max_allowed_reads. If n_total_reads is <= max_allowed_reads, n_ref_re...
48,683
def encode_log_entry_to_json(logEntry): """ Transform the log entry to jason format dict to store into MongoDB """ if logEntry.action == "Query_Success" or "Commit_Success": # Common fileds for query and commit log entry json_dict= {"date": logEntry.utcTimestamp, ...
48,684
def test8(): """ Test active_slice. Hayward with slice outside horizons. """ import xhorizon2 as xh ## print "\nTEST 8\n" ## define func and region func = xh.mf.hayward() reg = xh.reg.MAXreg(func,rlines=True) ## set input params U0 = lambda r: - np.pi**(-1) * np.arctan(r) V0 = lambda r: np.pi**(-1) * np....
48,685
def getFilesFromPath(path): """returns all files corresponding to path parameter""" raw = os.listdir(Path(path)) files_to_return = list() for i in raw: if i != ".DS_Store": files_to_return.append(i) return files_to_return
48,686
def update_point( angle, data ): """Updates the view of a sample. Takes the angle (an int, from 0 to 359) and the list of four bytes of data in the order they arrived. """ (dist_mm, is_bad_data, is_low_quality) = parse_point_data(angle, data) angle_rad = angle * math.pi / 180.0 c = math.cos(an...
48,687
def run_backward_rnn(sess, test_idx, test_feat, num_lstm_units): """ Run backward RNN given a query.""" res_set = [] lstm_state = np.zeros([1, 2 * num_lstm_units]) for test_id in reversed(test_idx): input_feed = np.reshape(test_feat[test_id], [1, -1]) [lstm_state, lstm_output] = rnn_one_step( ...
48,688
def preprocess_xarray(func): """Decorate a function to convert all DataArray arguments to pint.Quantities. This uses the metpy xarray accessors to do the actual conversion. """ @functools.wraps(func) def wrapper(*args, **kwargs): args = tuple(a.metpy.unit_array if isinstance(a, xr.DataArray...
48,689
def _get_verticalalignment(angle, location, side, is_vertical, is_flipped_x, is_flipped_y): """Return vertical alignment along the y axis. Parameters ---------- angle : {0, 90, -90} location : {'first', 'last', 'inner', 'outer'} side : {'first', 'last'} is_vertica...
48,690
def get_work_dir() -> str: """Retrieve the ambianic working directory""" env_work_dir = os.environ.get('AMBIANIC_DIR', os.getcwd()) if not env_work_dir: env_work_dir = DEFAULT_WORK_DIR return env_work_dir
48,691
def update_metadata_rois(dcms): """Reread rois from disk Looks for ROIs in a directory called 'roi' in the same directory as the dicom file. ROIs are lazily loaded so this should have minimal impact on performance. """ roi_reader = ROIReader() for dcm in dcms: rois_dir = os.path.join(os....
48,692
def get_pages(root_path): """ Reads the content folder structure and returns a list of dicts, one per page. Each page dict has these keys: path: list of logical uri path elements uri: URI of the final rendered page as string file_path: physical path of the file, as valid from within...
48,693
def load_dict(path): """ Load a dictionary and a corresponding reverse dictionary from the given file where line number (0-indexed) is key and line string is value. """ retdict = list() rev_retdict = dict() with open(path) as fin: for idx, line in enumerate(fin): text = line.stri...
48,694
def hsplit(ary, indices_or_sections): """ Split an array into multiple sub-arrays horizontally (column-wise). Please refer to the `split` documentation. `hsplit` is equivalent to `split` with ``axis=1``, the array is always split along the second axis regardless of the array dimension. See Al...
48,695
def is_valid_ipv6_addr(input=""): """Check if this is a valid IPv6 string. Returns ------- bool A boolean indicating whether this is a valid IPv6 string """ assert input != "" if _RGX_IPV6ADDR.search(input): return True return False
48,696
def might_need_auth(f): """Decorate a CLI function that might require authentication. Catches any UnauthorizedException raised, prints a helpful message and then exits. """ @wraps(f) def wrapper(cli_args): try: return_value = f(cli_args) except UnauthorizedException ...
48,697
def intersection_k(is_k_acceptable_func, *lists_of_interesting_parts): """ Segments, where intersects k parts, where is_k_acceptable_func(k) is True. For example for is_k_acceptable_func = lamda k: k >= 1 this function returns segments where there is at laest on part i.e. union of segments. This fun...
48,698
def calc_TEC( maindir, window=4096, incoh_int=100, sfactor=4, offset=0.0, timewin=[0, 0], snrmin=0.0, ): """ Estimation of phase curve using coherent and incoherent integration. Args: maindir (:obj:`str`): Path for data. window (:obj:'int'): Window length in samp...
48,699