content
stringlengths
22
815k
id
int64
0
4.91M
def _metric_list_for_check(maas_store, entity, check): """ Computes the metrics list for a given check. Remote checks return a metric for each monitoring zone and each type of metric for the check type. Agent checks return a metric for each metric type on the check type. Check types that Mimic ...
5,342,900
def plot_MA_values(t,X,**kwargs): """ Take the numpy.ndarray time array (t) of size (N,) and the state space numpy.ndarray (X) of size (2,N), (4,N), or (8,N), and plots the moment are values of the two muscles versus time and along the moment arm function. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ **kwargs ~~~~~~~~~~~~~~~~...
5,342,901
def filter_pdf_files(filepaths): """ Returns a filtered list with strings that end with '.pdf' Keyword arguments: filepaths -- List of filepath strings """ return [x for x in filepaths if x.endswith('.pdf')]
5,342,902
def index_file(path: str) -> dict: """ Indexes the files and directory under a certain directory Arguments: path {str} - the path of the DIRECTORY to index Return: {dict} - structures of the indexed directory """ structure = {} # Represents the directory structure for dir...
5,342,903
def hue_quadrature(h: FloatingOrArrayLike) -> FloatingOrNDArray: """ Return the hue quadrature from given hue :math:`h` angle in degrees. Parameters ---------- h Hue :math:`h` angle in degrees. Returns ------- :class:`numpy.floating` or :class:`numpy.ndarray` Hue quadra...
5,342,904
def AddMigCreateStatefulIPsFlags(parser): """Adding stateful IPs flags to the parser.""" stateful_internal_ips_help = textwrap.dedent( """ Internal IPs considered stateful by the instance group. {} Use this argument multiple times to make more internal IPs stateful. At least one of the foll...
5,342,905
def compare(inputpath1: str, inputpath2: str, output: str, verbose: bool): """ Parse two RST-trees (or two sets of RST-tree pairs), \ from INPUTPATH1 and INPUTPATH2 respectively, compare their annotated \ relations, and create comparison tables. If INPUTPATH1 and INPUTPATH2 \ bot...
5,342,906
def aa_find_devices_ext (devices, unique_ids): """usage: (int return, u16[] devices, u32[] unique_ids) = aa_find_devices_ext(u16[] devices, u32[] unique_ids) All arrays can be passed into the API as an ArrayType object or as a tuple (array, length), where array is an ArrayType object and length is...
5,342,907
def decode_varint_in_reverse(byte_array, offset, max_varint_length=9): """ This function will move backwards through a byte array trying to decode a varint in reverse. A InvalidVarIntError will be raised if a varint is not found by this algorithm used in this function. The calling logic should check ...
5,342,908
def manager_version(request): """ Context processor to add the rhgamestation-manager version """ # Tricky way to know the manager version because its version lives out of project path root = imp.load_source('__init__', os.path.join(settings.BASE_DIR, '__init__.py')) return {'manager_version': ro...
5,342,909
def _get_blobs(im, rois): """Convert an image and RoIs within that image into network inputs.""" blobs = {'data' : None, 'rois' : None} blobs['data'], im_scale_factors = _get_image_blob(im) if not cfg.TEST.HAS_RPN: blobs['rois'] = _get_rois_blob(rois, im_scale_factors) #print ('lll: ', blobs['r...
5,342,910
def string_limiter(text, limit): """ Reduces the number of words in the string to length provided. Arguments: text -- The string to reduce the length of limit -- The number of characters that are allowed in the string """ for i in range(len(text)): if i ...
5,342,911
def in_ellipse(xy_list,width,height,angle=0,xy=[0,0]): """ Find data points inside an ellipse and return index list Parameters: xy_list: Points needs to be deteced. width: Width of the ellipse height: Height of the ellipse angle: anti-clockwise rotation angle in degrees ...
5,342,912
def test39(): """ test fetching a priority class list """ res = PriorityClassList.listPriorityClass() assert res.obj assert isinstance(res.obj, PriorityClassList) assert len(res.obj.items) > 0
5,342,913
def get_real_images(dataset, num_examples, split=None, failure_on_insufficient_examples=True): """Get num_examples images from the given dataset/split. Args: dataset: `ImageDataset` object. num_examples: Number of images to read. split: Split ...
5,342,914
def save_opt_state(opt, # optimizer epoch): # epoch to save the optimizer state of """ Save optimizer state to temporary directory and then log it with mlflow. Args: opt: Optimizer epoch: Epoch to save the optimizer state of """ # create temporary directory wit...
5,342,915
def wait_complete(): """ 等待当前音频播放完毕。 :param 空: :returns: 0: 成功,其他: 失败 :raises OSError: EINVAL """ pass
5,342,916
async def call(fn: Callable, *args, **kwargs) -> Any: """ Submit function `fn` for remote execution with arguments `args` and `kwargs` """ async with websockets.connect(WS_SERVER_URI) as websocket: task = serialize((fn, args, kwargs)) await websocket.send(task) message = await ...
5,342,917
def assert_frame_equal( left: pandas.core.frame.DataFrame, right: pandas.core.frame.DataFrame, check_dtype: bool, ): """ usage.dask: 1 """ ...
5,342,918
def wrap_array_func(func): """ Returns a version of the function func() that works even when func() is given a NumPy array that contains numbers with uncertainties. func() is supposed to return a NumPy array. This wrapper is similar to uncertainties.wrap(), except that it handles an array ...
5,342,919
def fx_cmd_line_args_clone_prefix(): """ Before: adds args_to_add to cmd line so can be accessed by ArgParsers Sets 2 args for clone, a workflow to clone and a new type for the workflow After: Set the cmd line args back to its original value """ original_cmd_line = copy.deepcopy(sys.argv) ...
5,342,920
def checkCrash(player, upperPipes, lowerPipes): """returns True if player collides with base or pipes.""" pi = player['index'] player['w'] = fImages['player'][0].get_width() player['h'] = fImages['player'][0].get_height() # if player crashes into ground if player['y'] + player['h'] >= nBaseY -...
5,342,921
def alter_subprocess_kwargs_by_platform(**kwargs): """ Given a dict, populate kwargs to create a generally useful default setup for running subprocess processes on different platforms. For example, `close_fds` is set on posix and creation of a new console window is disabled on Windows. ...
5,342,922
def convert_gwp(context, qty, to): """Helper for :meth:`convert_unit` to perform GWP conversions.""" # Remove a leading 'gwp_' to produce the metric name metric = context.split('gwp_')[1] if context else context # Extract the species from *qty* and *to*, allowing supported aliases species_fro...
5,342,923
def appdataPath(appname): """ Returns the generic location for storing application data in a cross platform way. :return <str> """ # determine Mac OS appdata location if sys.platform == 'darwin': # credit: MHL try: from AppKit import NSSearchPathForDirect...
5,342,924
def getAction(board, policy, action_set): """ return action for policy, chooses max from classifier output """ # if policy doesn't exist yet, choose action randomly, else get from policy model if policy == None: valid_actions = [i for i in action_set if i[0] > -1] if len(valid_action...
5,342,925
def f_assert_must_between(value_list, args): """ 检测列表中的元素是否为数字或浮点数且在args的范围内 :param value_list: 待检测列表 :param args: 范围列表 :return: 异常或原值 example: :value_list [2, 2, 3] :args [1,3] :value_list ['-2', '-3', 3] :a...
5,342,926
def annotate_muscle_zscore(raw, threshold=4, ch_type=None, min_length_good=0.1, filter_freq=(110, 140), n_jobs=1, verbose=None): """Create annotations for segments that likely contain muscle artifacts. Detects data segments containing activity in the frequency range given by ``fi...
5,342,927
def circ_dist2(a, b): """Angle between two angles """ phi = np.e**(1j*a) / np.e**(1j*b) ang_dist = np.arctan2(phi.imag, phi.real) return ang_dist
5,342,928
def print_hugo_install_instructions(): """Prints out instructions on how to install Hugo """ click.secho( ''' It appears that Hugo isn't installed, which is needed to launch the preview server. If you have Homebrew, you can install Hugo using "brew install hugo". Otherwise, you can ...
5,342,929
def hinge_loss(positive_scores, negative_scores, margin=1.0): """ Pairwise hinge loss [1]: loss(p, n) = \sum_i [\gamma - p_i + n_i]_+ [1] http://yann.lecun.com/exdb/publis/pdf/lecun-06.pdf :param positive_scores: (N,) Tensor containing scores of positive examples. :param negative_scores: (...
5,342,930
def build(req): """Builder for this format. Args: req: flask request Returns: Json containing the creative data """ errors = [] v = {} tdir = "/tmp/" + f.get_tmp_file_name() index = get_html() ext = f.get_ext(req.files["videofile"].filename) if ext != "mp4": return {"errors": ["Only ...
5,342,931
def add_s3(command_table, session, **kwargs): """ This creates a new service object for the s3 plugin. It sends the old s3 commands to the namespace ``s3api``. """ utils.rename_command(command_table, 's3', 's3api') command_table['s3'] = S3(session)
5,342,932
def reflect(old, centroid, new): """Reflect the old point around the centroid into the new point on the sphere. Parameters ---------- old : SPHER_T centroid : SPHER_T new : SPHER_T """ x = old['x'] y = old['y'] z = old['z'] ca = centroid['cosaz'] sa = centroid['sinaz'] ...
5,342,933
def search(query, data, metric='euclidean', verbose=True): """ do search, return ranked list according to distance metric: hamming/euclidean query: one query per row dat: one data point per row """ #calc dist of query and each data point if metric not in ['euclidean', 'hamming']: ...
5,342,934
def create_circle_widget(canvas: Canvas, x: int, y: int, color: str, circle_size: int): """create a centered circle on cell (x, y)""" # in the canvas the 1st axis is horizontal and the 2nd is vertical # we want the opposite so we flip x and y for the canvas # to create an ellipsis, we give (x0, y0) and ...
5,342,935
def _format_program_counter_relative(state): """Program Counter Relative""" program_counter = state.program_counter operand = state.current_operand if operand & 0x80 == 0x00: near_addr = (program_counter + operand) & 0xFFFF else: near_addr = (program_counter - (0x100 - operand)) & ...
5,342,936
def compile_program( program: PyTEAL, mode: Mode = Mode.Application, version: int = 5 ) -> bytes: """Compiles a PyTEAL smart contract program to the TEAL binary code. Parameters ---------- program A function which generates a PyTEAL expression, representing an Algorand program. mode ...
5,342,937
def fetch_url(url): """ Fetches a URL and returns contents - use opener to support HTTPS. """ # Fetch and parse logger.debug(u'Fetching %s', url) # Use urllib2 directly for enabled SSL support (LXML doesn't by default) timeout = 30 try: opener = urllib2.urlopen(url, None, timeout) ...
5,342,938
def predict(yolo_outputs, image_shape, anchors, class_names, obj_threshold, nms_threshold, max_boxes = 1000): """ Process the results of the Yolo inference to retrieve the detected bounding boxes, the corresponding class label, and the confidence score associated. The threshold value 'obj_threshold' serves to disca...
5,342,939
def get_event_details(entry, workday_user, demisto_user, days_before_hire_to_sync, days_before_hire_to_enable_ad, deactivation_date_field, display_name_to_user_profile, email_to_user_profile, employee_id_to_user_profile, source_priority): """ This function detects the...
5,342,940
def test_qamats_gadol_next_accent(): """`qamats` with first accent on syllable is `qamats-gadol` (qamats-gadol-next-accent)""" word = r"אָז֩" # az (Leviticus 26:34) parts = ["alef", "qamats-gadol", "zayin"] assert parts == Parser().parse(word).flat()
5,342,941
def kill_test_logger(logger): """Cleans up a test logger object by removing all of its handlers. Args: logger: The logging object to clean up. """ for h in list(logger.handlers): logger.removeHandler(h) if isinstance(h, logging.FileHandler): h.close()
5,342,942
def ae_model(inputs, train=True, norm=True, **kwargs): """ AlexNet model definition as defined in the paper: https://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf You will need to EDIT this function. Please put your AlexNet implementation here. N...
5,342,943
def filter_by_country(data, country=DEFAULT_COUNTRY): """ Filter provided data by country (defaults to Czechia). data: pandas.DataFrame country: str """ # Filter data by COUNTRY return data[data[COLUMN_FILTER] == country]
5,342,944
def draw_soil_maps(): """make four-panel map of soil COS fluxes and resulting drawdown The four panels show soil COS surface fluxes (top row) and the resulting STEM-simulated drawdowns (bottom row) for both the Whelan-Kettle "hybrid" fluxes (left panels) as well as Kettle et al (2002) fluxes (right...
5,342,945
def get_instance_id() -> str: """Returns the AWS instance id where this is running or "local".""" global INSTANCE_ID if INSTANCE_ID is None: if get_env_variable("RUNNING_IN_CLOUD") == "True": @retry(stop_max_attempt_number=3) def retrieve_instance_id(): return...
5,342,946
def test_array__sized_dump_too_small__unsized_iterable(): """Crash if writing a generator with too few values.""" field = fields.Array(fields.Int32(), count=100) with pytest.raises(errors.ArraySizeError) as err: field.to_bytes(x for x in range(6)) assert err.value.n_expected == 100 assert e...
5,342,947
def scans_from_csvs(*inps, names=None): """ Read from csvs. :param inps: file names of the csvs :param names: names of the Scans :return: list of Scans """ ns, temp_vals, heat_flow_vals = read_csvs(inps) names = ns if names is None else names return [Scan(*vals) for vals in zip(temp...
5,342,948
def part_b(puzzle_input): """ Calculate the answer for part_b. Args: puzzle_input (list): Formatted as the provided input from the website. Returns: string: The answer for part_b. """ return str(collect_letters(puzzle_input)[1])
5,342,949
def main(): """Driver Function.""" parser = argparse.ArgumentParser( description="ARMA Plotting Script for EPRI Data" ) parser.add_argument( "-t", "--add-tables", action="store_true", help="Add descriptive tables to plot margin.", ) parser.add_argument( ...
5,342,950
def data_encoder(data): """ Encode all categorical values in the dataframe into numeric values. @param data: the original dataframe @return data: the same dataframe with all categorical variables encoded """ le = preprocessing.LabelEncoder() cols = data.columns numcols = data._get_n...
5,342,951
def _search_settings(method_settings_keys, settings): """ We maintain a dictionary of dimensionality reduction methods in dim_settings_keys where each key (method) stores another dictionary (md) holding that method's settings (parameters). The keys of md are component ids and the values are paramete...
5,342,952
def svn_opt_resolve_revisions(*args): """ svn_opt_resolve_revisions(svn_opt_revision_t peg_rev, svn_opt_revision_t op_rev, svn_boolean_t is_url, svn_boolean_t notice_local_mods, apr_pool_t pool) -> svn_error_t """ return _core.svn_opt_resolve_revisions(*args)
5,342,953
def write_midi( path: Union[str, Path], music: "Music", backend: str = "mido", **kwargs: Any ): """Write a Music object to a MIDI file. Parameters ---------- path : str or Path Path to write the MIDI file. music : :class:`muspy.Music` Music object to write. backe...
5,342,954
def find_star_column(file, column_type, header_length) : """ For an input .STAR file, search through the header and find the column numbers assigned to a given column_type (e.g. 'rlnMicrographName', ...) """ with open(file, 'r') as f : line_num = 0 for line in f : line_num += 1 ...
5,342,955
def recalculate_bb(df, customization_dict, image_dir): """After resizing images, bb coordinates are recalculated. Args: df (Dataframe): A df for image info. customization_dict (dict): Resize dict. image_dir (list): Image path list Returns: Dataframe: Updated dataframe. ...
5,342,956
def free_port(): """Returns a free port on this host """ return get_free_port()
5,342,957
def gen_treasure_img(): """ Get National Treasure values and Tweet its image """ if len(db_schedule.get( 'date == "{}" AND category == "TD"'.format( datetime.today().strftime('%d/%m/%Y')))) == 0: status, treasure = Treasure().buy() if status == 200: image = Trea...
5,342,958
def test_unregister_non_existing_file_obj(psql_fixture): # noqa: F811 """Test unregistering not existing file object and expect corresponding error.""" non_existing_file_obj = psql_fixture.non_existing_file_infos[0] with pytest.raises(DrsObjectNotFoundError): psql_fixture.database.unregister_drs_...
5,342,959
async def websocket_lovelace_update_card(hass, connection, msg): """Receive lovelace card config over websocket and save.""" error = None try: await hass.async_add_executor_job( update_card, hass.config.path(LOVELACE_CONFIG_FILE), msg['card_id'], msg['card_config'], msg.get('...
5,342,960
def justify_to_box( boxstart: float, boxsize: float, itemsize: float, just: float = 0.0) -> float: """ Justifies, similarly, but within a box. """ return boxstart + (boxsize - itemsize) * just
5,342,961
def newton(oracle, x_0, tolerance=1e-5, max_iter=100, line_search_options=None, trace=False, display=False): """ Newton's optimization method. Parameters ---------- oracle : BaseSmoothOracle-descendant object Oracle with .func(), .grad() and .hess() methods implemented for comput...
5,342,962
def generate_hostname(domain, hostname): """If hostname defined, returns FQDN. If not, returns FQDN with base32 timestamp. """ # Take time.time() - float, then: # - remove period # - truncate to 17 digits # - if it happen that last digits are 0 (and will not be displayed, so # stri...
5,342,963
def symmetrize(M): """Return symmetrized version of square upper/lower triangular matrix.""" return M + M.T - np.diag(M.diagonal())
5,342,964
def process_checksums_get(storage_share, hash_type, url): """Run StorageShare get_object_checksum() method to get checksum of file/object. Run StorageShare get_object_checksum() method to get the requested type of checksum for file/object whose URL is given. The client also needs to sp If the Sto...
5,342,965
def train_model(model_path, epoch): """ Train the specified model. :param model_path: The path to save model. :param epoch: Number of iterations to train model. :return: Trained model. """ train_path = input("Please input the path of training data: ") if train_path[-1] != '/': tr...
5,342,966
def test_parser_nested_let_assign(): """ To validate the parser solves nested let. """ parser = Parser(Lexer(Scanner("let:\n let:\n a <- 1 + 2\n b <- a * 3\n\n"))) assign = parser() assert assign.name == NodeType.Let assert str(assign) == "Let(Let(MutableAssign(Name(a), Add(Num(1), Num...
5,342,967
def test_fake_corrupt_json_file(tmpdir): """ Creates a bad JSON file and tests the code responds properly""" try: d = tmpdir.mkdir("./testdir") bad_json = d.join("bad_json.txt") bad_json.write('{"test": }') filename = os.path.join(bad_json.dirname, bad_json.basename) json...
5,342,968
def prep_public_water_supply_fraction() -> pd.DataFrame: """calculates public water supply deliveries for the commercial and industrial sectors individually as a ratio to the sum of public water supply deliveries to residential end users and thermoelectric cooling. Used in calculation of public water supp...
5,342,969
def box3d_overlap_kernel(boxes, qboxes, rinc, criterion=-1, z_axis=1, z_center=1.0): """ z_axis: the z (height) axis. z_center: unified z (height) center of box. """ N...
5,342,970
def set_matchq_in_constraint(a, cons_index): """ Takes care of the case, when a pattern matching has to be done inside a constraint. """ lst = [] res = '' if isinstance(a, list): if a[0] == 'MatchQ': s = a optional = get_default_values(s, {}) r = gener...
5,342,971
def training_main(): """ main api to train a model. """ training_config = parse_training_args() # get training and validation sample names with open(training_config.train_fnames_path, "r", encoding="utf-8") as f: train_base_fnames = [line.strip() for line in f] if training_config.val_fna...
5,342,972
def istype(klass, object): """Return whether an object is a member of a given class.""" try: raise object except klass: return 1 except: return 0
5,342,973
def call(results): """Call results.func on the attributes of results :params result: dictionary-like object :returns: None """ results = vars(results) places = Places(config=results.pop('config'), messages=results.pop('messages')) func = results.pop('func') func(plac...
5,342,974
def _embed_from_mapping(mapping: Mapping[str, Any], ref: str) -> mapry.Embed: """ Parse the embed from the mapping. All the fields are parsed except the properties, which are parsed in a separate step. :param mapping: to be parsed :param ref: reference to the embeddable structure in the mapry ...
5,342,975
def generate_csv_from_pnl(pnl_file_name): """在.pnl文件的源路径下新生成一个.csv文件. 拷贝自export_to_csv函数. pnl_file_name需包含路径. """ pnlc = alib.read_pnl_from_file(pnl_file_name) pnl = pnlc[1] if pnl is None: print('pnl文件{}不存在!'.format(pnl_file_name)) pdb.set_trace() csv_file_name = pnl_file_nam...
5,342,976
def parse_number(text, allow_to_fail): """ Convert to integer, throw if fails :param text: Number as text (decimal, hex or binary) :return: Integer value """ try: if text in defines: return parse_number(defines.get(text), allow_to_fail) return to_number(text) exce...
5,342,977
def pick_vis_func(options: EasyDict): """Pick the function to visualize one batch. :param options: :return: """ importlib.invalidate_caches() vis_func = getattr( import_module("utils.vis.{}".format(options.vis.name[0])), "{}".format(options.vis.name[1]) ) return vis_func
5,342,978
def scale_quadrature(quad_func, order, lower, upper, **kwargs): """ Scale quadrature rule designed for unit interval to an arbitrary interval. Args: quad_func (Callable): Function that creates quadrature abscissas and weights on the unit interval. order (int): ...
5,342,979
def ask_for_region(self): """ask user for region to select (2-step process)""" selection = ["BACK"] choices = [] while "BACK" in selection: response = questionary.select( "Select area by (you can go back and combine these choices):", choices=["continents", "regions", "co...
5,342,980
def peakAlign(refw,w): """ Difference between the maximum peak positions of the signals. This function returns the difference, in samples, between the peaks position of the signals. If the reference signal has various peaks, the one chosen is the peak which is closer to the middle of the signal, ...
5,342,981
def get_games(by_category, n_games): """ This function imports the dataframe of most popular games and returns a list of game names with the length of 'n_games' selected by 'by_category'. Valid options for 'by_category': rank, num_user_ratings """ df = pd.read_csv('../data/popular_games_with_image_u...
5,342,982
def download_images(url_list, internal_id, auth): """ Download all images in a url list. The files are saved in a directory named with the uuid of the article. @param url_list: dict of files, in format {"filename" : "x.tiff", "url" : "y"} @type url_list: dict @param in...
5,342,983
def test_close_a_project(): """Close a created project -> create a zip file and delete the project folder""" runner = CliRunner() project_path = Path("temp/test1") # Run test isolated with runner.isolated_filesystem(): create_dummy_project(runner, project_path) # Close the project ...
5,342,984
def clean_hook(conduit): """ This function cleans the plugin cache file if exists. The function is called when C{yum [options] clean [plugins | all ]} is executed. """ global hostfilepath if hostfilepath and hostfilepath[0] != '/': hostfilepath = conduit._base.conf.cachedir + '/' + hostf...
5,342,985
def diurnalPDF( t, amplitude=0.5, phase=pi8 ): """ "t" must be specified in gps seconds we convert the time in gps seconds into the number of seconds after the most recent 00:00:00 UTC return (1 + amplitude*sin(2*pi*t/day - phase))/day """ if amplitude > 1: raise ValueError("amplitude ca...
5,342,986
def imap_workers(workers, size=2, exception_handler=None): """Concurrently converts a generator object of Workers to a generator of Responses. :param workers: a generator of worker objects. :param size: Specifies the number of workers to make at a time. default is 2 :param exception_handler: Callbac...
5,342,987
def output_time(time_this:float=None,end:str=" | ")->float: """输入unix时间戳,按格式输出时间。默认为当前时间""" if not time_this: time_this=time.time()-TIMEZONE print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(time_this)),end=end) # return time_this
5,342,988
def blend_color(color1, color2, blend_ratio): """ Blend two colors together given the blend_ration :param color1: pygame.Color :param color2: pygame.Color :param blend_ratio: float between 0.0 and 1.0 :return: pygame.Color """ r = color1.r + (color2.r - color1.r) * blend_ratio g = c...
5,342,989
def delete_video(video_id): """Permanently delete a video.""" _video_request('vimeo.videos.delete', 'POST', video_id=video_id, error_msg=('Error deleting video {video_id}: <{code} {msg}> ' '{expl}'))
5,342,990
def load_flickr25k_dataset(tag='sky', path="data", n_threads=50, printable=False): """Returns a list of images by a given tag from Flick25k dataset, it will download Flickr25k from `the official website <http://press.liacs.nl/mirflickr/mirdownload.html>`_ at the first time you use it. Parameters --...
5,342,991
def solve_a_star(start_id: str, end_id: str, nodes, edges): """ Get the shortest distance between two nodes using Dijkstra's algorithm. :param start_id: ID of the start node :param end_id: ID of the end node :return: Shortest distance between start and end node """ solution_t_start = perf_c...
5,342,992
def initialize_components(): """Initializes external interfaces and saved calibration data""" analysis.setup_calibration() interfaces.setup_interfaces()
5,342,993
def get_dhcp_relay_statistics(dut, interface="", family="ipv4", cli_type="", skip_error_check=True): """ API to get DHCP relay statistics Author Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) :param dut: :type dut: :param interface: :type interface: """ cli_type = st.get_ui_typ...
5,342,994
def _runcmd(cmd, proc): """Run a command""" cmdstr = proc.template(cmd, **proc.envs).render(dict(proc=proc, args=proc.args)) logger.info('Running command from pyppl_runcmd ...', proc=proc.id) logger.debug(' ' + cmdstr, proc=proc.id) cmd = cmdy.bash(c=cmdstr, _raise=False)...
5,342,995
def graph_to_raw(g, raw_directory, lines_per_file = 1000): """ Fills a directory with gzip files corresponding to the raw format. :param g: the graph :param raw_directory: the destination :param lines_per_file: how many lines per file (per gzip file) """ # ensure the directory is there ...
5,342,996
def check_rule_for_Azure_ML(rule): """Check if the ports required for Azure Machine Learning are open""" required_ports = ['29876', '29877'] if check_source_address_prefix(rule.source_address_prefix) is False: return False if check_protocol(rule.protocol) is False: return False i...
5,342,997
def text_cleanup(text: str) -> str: """ A simple text cleanup function that strips all new line characters and substitutes consecutive white space characters by a single one. :param text: Input text to be cleaned. :return: The cleaned version of the text """ text.replace('\n', '') return...
5,342,998
def geocode(): """ Call a Geocoder service """ if "location" in request.vars: location = request.vars.location else: session.error = T("Need to specify a location to search for.") redirect(URL(r=request, f="index")) if "service" in request.vars: service = r...
5,342,999