content
stringlengths
22
815k
id
int64
0
4.91M
def get_backend(): """ Returns the currently used backend. Default is tensorflow unless the VXM_BACKEND environment variable is set to 'pytorch'. """ return 'pytorch' if os.environ.get('VXM_BACKEND') == 'pytorch' else 'tensorflow'
5,319,900
def _combine_concat_plans(plans, concat_axis: int): """ Combine multiple concatenation plans into one. existing_plan is updated in-place. """ if len(plans) == 1: for p in plans[0]: yield p[0], [p[1]] elif concat_axis == 0: offset = 0 for plan in plans: ...
5,319,901
def burn(lower_rgb, upper_rgb): """Apply burn blending mode of a layer on an image. """ return np.maximum(1.0 - (((1.0 + np.finfo(np.float64).eps) - lower_rgb) / upper_rgb), 0.0)
5,319,902
def pretty_print(data: DataRowsSet_t): """ Prints all the data available in a given measurement data :param data: e_nose sensor data """ for ts in data: print(ts, ":", data[ts]['channels'], ";label:", data[ts]['label'])
5,319,903
def count_neopixel(sel_mode, ldclr, lbl, magtag): """ # -------------------------------------- # Set the LED's at the top of the MagTag to show the binary value of the # integer parameter sel_mode. The range is 0 to 0x0F or 16 decimal # Accomodates LED numbering from right to left # 3 para...
5,319,904
def paramCheck(function: Callable[..., T], allow_none: bool = True) -> Callable[..., T]: """ Return a decorator that performs runtime checks on the input types. :param function: function to be checked against its typing annotations :param allow_none: whether None values are allowed :return: wrapped...
5,319,905
def test_scon_realm_when_defined(): """Test SConnect.realm property when pre-defined.""" sc = steelconnection.SConnect("some.realm", connection_attempts=0) assert sc.realm == "some.realm"
5,319,906
def test_inline_block_before(): """Test the inlining of a block before an operation.""" prog = \ """module() { %0 : !i1 = arith.constant() ["value" = 1 : !i1] scf.if(%0 : !i1) { %1 : !i32 = arith.constant() ["value" = 2 : !i32] } }""" expected = \ """module() { %0 : !i1 = arith.constant() ["value" ...
5,319,907
def fixture_org(context: RBContext, org_id: str) -> RBOrganization: """Get RBOrganization.""" return RBOrganization(context, org_id)
5,319,908
def load_proxies_from_csv(path_to_list): """ Функция, которая загружает прокси из CSV-файла в список.      Входные данные: путь к CSV-файлу, содержащему прокси, описываемый полями: «ip», «port», «protocol».      Выходы: список, содержащий прокси, хранящиеся в именованных кортежах. """ Proxy = namedtu...
5,319,909
def mpls_label_group_id(sub_type, label): """ MPLS Label Group Id sub_type: - 1: L2 VPN Label - 2: L3 VPN Label - 3: Tunnel Label 1 - 4: Tunnel Label 2 - 5: Swap Label """ return 0x90000000 + ((sub_type << 24) & 0x0f000000) + (label & 0x00ffffff)
5,319,910
def process_ap_features(file, doc): """Parse .xml files, extract features, and write the results to files""" features = doc.findall(".//feature[@name='artificial-plagiarism'][@translation='false'][@obfuscation='none']") uniq_sr = set() for el in features: uniq_sr.add(el.attrib['source_reference...
5,319,911
def compare_results(out_dict, known_problems_dict, compare_warnings): """Compare the number of problems and warnings found with the allowed number""" ret = 0 for key in known_problems_dict.keys(): try: if out_dict[key]['problems'] > known_problems_dict[key]['problems']: ...
5,319,912
def log_out(): """ The function executes when the user press the log out button. It will log him out from his account and set him offline. """ PrivateChat.in_chat_with = False PrivateChat.in_unread = False offline(0) deselect.set(0) global username username = None set_onlin...
5,319,913
def compute_accuracy(ground_truth, predictions, display=False, mode='per_char'): """ Computes accuracy :param ground_truth: :param predictions: :param display: Whether to print values to stdout :param mode: if 'per_char' is selected then single_label_accuracy = correct_predicted...
5,319,914
def is_decodable(s1): """ try hard to decode the input chemical formula useful for recognizing those strings from nist database """ for s in ['-','=','#',]: s1 = remove_element(s1, s) if ('(' in s1) and (')' in s1): while True: if not ('(' in s1): bre...
5,319,915
def ensure_int_vector(I, require_order = False): """Checks if the argument can be converted to an array of ints and does that. Parameters ---------- I: int or iterable of int require_order : bool If False (default), an unordered set is accepted. If True, a set is not accepted. Returns ...
5,319,916
def set_mw_dependencies(item, job, params): """ Inject MediaWiki dependencies based on a built-in hash. Reads MediaWiki dependencies for a repository and inject them as parameters EXT_DEPENDENCIES or SKIN_DEPENDENCIES. The map is configured via the 'dependencies' dictionary above. Extensions a...
5,319,917
def lgt_to_gt(lgt, la): """A method for transforming Local GT and Local Alleles into the true GT""" return hl.call(la[lgt[0]], la[lgt[1]])
5,319,918
def train_or_evaluate(model, shouldTrain, shouldEvaluate, inputFilename, modelName): """Trains or evaluates the given model with data from inputFilename. Arguments: model {} -- The model to train or evaluate. shouldTrain {bool} -- Wether or not we should train the model. shouldEvalu...
5,319,919
def ascat(scan_nb, scan_points=None): """ASCAT make two scans one to the left and one to the right of the sub-satellite track. """ if scan_points is None: scan_len = 42 # samples per scan scan_points = np.arange(42) else: scan_len = len(scan_points) scan_angle_inner =...
5,319,920
def ensure_csv( key: str, *subkeys: str, url: str, name: Optional[str] = None, force: bool = False, download_kwargs: Optional[Mapping[str, Any]] = None, read_csv_kwargs: Optional[Mapping[str, Any]] = None, ): """Download a CSV and open as a dataframe with :mod:`pandas`. :param key: ...
5,319,921
def __nothingFound( cmd_line_parser: argparse.ArgumentParser, date_str: str, tzolkin_number: int, tzolkin_day_number: int, ) -> None: """Exit with an error if no date has been found. Args: cmd_line_parser (argparse.ArgumentParser): The command line parser instance. date_str (str...
5,319,922
def energy_scan(sim_func, sim_kwargs, energies, parallel=False): """ This function provides a convenient way to repeat the same simulation for a number of different electron beam energies. This can reveal variations in the charge state balance due to weakly energy dependent ionisation cross sections or ...
5,319,923
def random_walk_memory(world_state, pose, visited): """ Returns a random valid neighboring cell that is not recently visited. Can return visited cells if there is no other option """ nbors = get_orthogonal_nbors(world_state, pose) # Get neighbors that aren't recently visited new_nbors = list(set...
5,319,924
def run_file_mask(fmask, fname, fbase=0): """extract temporal data from file name """ if fbase and fname.startswith(fbase): fname = fname[fname.index(fbase) + len(fbase) + 1:] output = { "year": "".join([x for x,y in zip(fname, fmask) if y == 'Y' and x.isdigit()]), "month": ""....
5,319,925
def get_spin_interp(zeta: torch.Tensor) -> torch.Tensor: """Compute spin interpolation function from fractional polarization `zeta`.""" exponent = 4.0 / 3 scale = 1.0 / (2.0 ** exponent - 2.0) return ((1.0 + zeta) ** exponent + (1.0 - zeta) ** exponent - 2.0) * scale
5,319,926
def test_tagger(test_tsv_untagged_file, pretrained_tagger: pos.Tagger): """Test all methods of the Tagger.""" # Tag a single sentence tags = pretrained_tagger.tag_sent(("Þetta", "er", "setning", ".")) assert tags == ("fahen", "sfg3en", "nven", "pl") # Tag a correctly formatted file. dataset = F...
5,319,927
def get_interpolator(func, varname, df, default_time, docstring): """Creates time interpolator with custom signature""" #extract source code from time_interpolator src = inspect.getsource(time_interpolator) #create variable-dependent signature new_src = (src \ .format(docstring = docstri...
5,319,928
def inverse_cdf_coupling(logits_1, logits_2): """Constructs the matrix for an inverse CDF coupling.""" dim, = logits_1.shape p1 = jnp.exp(logits_1) p2 = jnp.exp(logits_2) p1_bins = jnp.concatenate([jnp.array([0.]), jnp.cumsum(p1)]) p2_bins = jnp.concatenate([jnp.array([0.]), jnp.cumsum(p2)]) # Value in b...
5,319,929
def get_all_datasets(all_logdirs, legend=None, select=None, exclude=None): """ For every entry in all_logdirs, 1) check if the entry is a real directory and if it is, pull data from it; 2) if not, check to see if the entry is a prefix for a real directory, and pull data fr...
5,319,930
async def test_resolve(profile: Profile, resolver: IndyDIDResolver): """Test resolve method.""" assert await resolver.resolve(profile, TEST_DID0)
5,319,931
def certificate(): """ Certificates Controller """ mode = session.s3.hrm.mode def prep(r): if mode is not None: r.error(403, message=auth.permission.INSUFFICIENT_PRIVILEGES) return True s3.prep = prep if settings.get_hrm_filter_certificates() and \ not auth.s3_ha...
5,319,932
async def _run_given_tasks_async(tasks, event_loop=asyncio.get_event_loop(), executor=None): """ Given list of Task objects, this method executes all tasks in the given event loop (or default one) and returns list of the results. The list of the results are in the same order as the list of the input. ...
5,319,933
def test_pyramid_tiff(samples_path, tmp_path, monkeypatch): """Test pyramid generation using OpenCV to downsample.""" # Try to make a pyramid TIFF reader = readers.Reader.from_file(samples_path / "XYC.jp2") pyramid_downsamples = [2, 4] writer = writers.TIFFWriter( path=tmp_path / "XYC.tiff",...
5,319,934
def fileno(): """ Return the file number of the current file. When no file is currently opened, returns -1. """ if not _state: raise RuntimeError("no active input()") return _state.fileno()
5,319,935
def word_show(vol, guess, store): """ param vol: str, the word from def random_word param guess: str, the letter user guessed param store: str, the string showing correct letters user guessed return: str, answer """ answer = '' if guess == '': for i in vol: answer += ...
5,319,936
def convert_yt_music(input_url: str) -> str: """ Convert a YouTube Music link to a YouTube link. YouTube Music videos share the same `v` URL parameter as their YouTube counterparts and hence can be processed like YouTube URLs after making changes to the URL This function replaces the `music.youtube...
5,319,937
def get_feature_attributions(args, model_list, data_x_list, data_y_list, col_names, is_mgmc): """Get feature attributions. Get feature attributions for given list of saved Pipeline models and output dataset lists from get_train_test_dataset_list(). Args: args: ...
5,319,938
def bspline_fit(x,y,order=3,knots=None,everyn=20,xmin=None,xmax=None,w=None,bkspace=None): """ bspline fit to x,y Should probably only be called from func_fit Parameters ---------- x: ndarray y: ndarray func: str Name of the fitting function: polynomial, legendre, chebyshev, bsplin...
5,319,939
def request(s): """ Returns a :class:`Request` object for the given string. :param str s: The string containing the request line to parse :returns: A :class:`Request` tuple representing the request line """ try: method, s = s.split(' ', 1) except ValueError: raise ValueError...
5,319,940
def _gradual_sequence(start, end, multiplier=3): """Custom nodes number generator The function gives the list of exponentially increase/decrease integers from both 'start' and 'end' params, which can be later used as the number of nodes in each layer. _gradual_sequence(10, 7000, multiplier=5) gives ...
5,319,941
def get_group_clusters(group_name): """ Returns list of clusters administered by group :return: list """ access_token = get_user_access_token(session) query = {'token': access_token} group_clusters = requests.get( slate_api_endpoint + '/v1alpha3/groups/' + group_name + '/clusters', ...
5,319,942
def Q_continuous_white_noise(dim, dt=1., spectral_density=1.): """ Returns the Q matrix for the Discretized Continuous White Noise Model. dim may be either 2 or 3, dt is the time step, and sigma is the variance in the noise. Parameters ---------- dim : int (2 or 3) dimension for Q, whe...
5,319,943
def finalize(): """ Shutdown mpi """ # if we don't have runtime support if not libmpi: # bail return # get the groups from .Group import Group # ask each instance for group in Group.pyre_extent: # to forget its capsule group.capsule = None # get ...
5,319,944
def doKill(): """ Kill a node in the demo app (watches for kill file) """ path = os.path.abspath('./kill') open(path, 'w').close() print "Executing kill node request to demo app."
5,319,945
def write_log_msg(file_name: str = DEFAULT_LOGFILENAME, msg: str = '') -> None: """Opens a log file and write a message on it. Parameters ---------- file_name : str (default 'logfile.log') The file name to annotate the messages msg : str (default '') The message to be writt...
5,319,946
def timeit(func): """calculate time for a function to complete""" def wrapper(*args, **kwargs): start = time.time() output = func(*args, **kwargs) end = time.time() print('function {0} took {1:0.3f} s'.format( func.__name__, (end - start) * 1)) return outpu...
5,319,947
def create_alias(FunctionName=None, Name=None, FunctionVersion=None, Description=None): """ Creates an alias that points to the specified Lambda function version. For more information, see Introduction to AWS Lambda Aliases . Alias names are unique for a given function. This requires permission for the lamb...
5,319,948
def make_test_label_and_intensity_images_no_internal_2d() -> Tuple[ np.ndarray, np.ndarray, np.ndarray, np.ndarray ]: """Create 2D test data where label 2 has no internal pixels""" label_image = np.zeros((40, 40), dtype=int) label_image[10:20, 10:20] = 1 label_image[25:27, 25:27] = 2 label_image...
5,319,949
def get_mock_image(): """ Return a canned test image (1 band of original NetCDF raster) """ nc = os.path.join(script_dir, 'resources/HadGHCND_TXTN_anoms_1950-1960_15052015.nc') with open(nc, 'rb') as ncfile: return ncfile.read()
5,319,950
def get_database_acl(instance_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDatabaseAclResult: """ Gets information about the RDB instance network Access Control List. ## Example Usage ```python import pulumi import pulumi_scaleway a...
5,319,951
def run_suite(project, suite_name): """Run a suite. This is used when running suites from the GUI""" script_name = sys.argv[0] if script_name[-5:] != 'golem' and script_name[-9:] != 'golem.exe': if sys.platform == 'win32': script_name = 'golem' else: which_golem = sub...
5,319,952
def run_step(context): """Increment counter inside step.""" context['counter'] = context['counter'] + 1
5,319,953
def get_cancellations(es_cfg): """Calls external scheduler and returns task cancellations.""" req = plugin_pb2.GetCancellationsRequest() req.scheduler_id = es_cfg.id c = _get_client(es_cfg.address) resp = c.GetCancellations(req, credentials=_creds()) return resp.cancellations
5,319,954
def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 0 j = 0 len_n = len(nums) for i in range(len_n): if nums[j] != nums[i]: nums[j + 1] = nums[i] j += 1 return j + 1
5,319,955
def test_wnm_ess_disassoc_imminent_pmf(dev, apdev): """WNM ESS Disassociation Imminent""" params = hostapd.wpa2_params("test-wnm-rsn", "12345678") params["wpa_key_mgmt"] = "WPA-PSK-SHA256"; params["ieee80211w"] = "2"; params["bss_transition"] = "1" hostapd.add_ap(apdev[0]['ifname'], params) ...
5,319,956
def GetUserGender(user_url: str) -> int: """获取用户性别 Args: user_url (str): 用户个人主页 Url Returns: int: 用户性别,0 为未知,1 为男,2 为女 """ AssertUserUrl(user_url) AssertUserStatusNormal(user_url) json_obj = GetUserJsonDataApi(user_url) result = json_obj["gender"] if result == 3: #...
5,319,957
def do_menu_action(action): """Execute menu action!""" return { 'help': help, 'inventory': print_inventory, 'game': print_game_status, 'quit': save_game, }.get(action, (lambda: ''))()
5,319,958
def test_mixed_optimization(): """ Checks if variables with mixed constraints are optimized correctly together. """ def get_loss(mean): def loss(x, y, z): return (x + y + z - mean) ** 2 return loss # Fix seed tf.random.set_seed(42) # Create variables v1 =...
5,319,959
def SepConv_BN(x, filters, prefix, stride=1, kernel_size=3, rate=1, depth_activation=False, epsilon=1e-3): """ SepConv with BN between depthwise & pointwise. Optionally add activation after BN Implements right "same" padding for even kernel sizes Args: x: input tensor filters...
5,319,960
def set_player(bot, server_id, player): """Sets the voice player of the given server.""" data.add( bot, 'base', 'voice_player', player, server_id=server_id, volatile=True)
5,319,961
def test_good_transaction(): """successful runs automatically commit""" dsi = DatabaseStandIn() database.hub_registry.add(dsi) try: database.run_with_transaction(dsi.successful) assert dsi.successful_called assert dsi.committed assert dsi.ended finally: databa...
5,319,962
def dot_prod_numpy(T): """Calculate dot product over last two axis of a multi dimensional matrix""" # reverse along domain axis, see comment in next function return np.array([reduce(np.dot, Tn) for Tn in T[:, ::-1, ...]])
5,319,963
def create_pretrain_mask(tokens, mask_cnt, vocab_list): """ masking subwords(15% of entire subwords) - mask_cnt: len(subwords) * 0.15 - [MASK]: 80% of masking candidate token - original token: 10% of masking candidate token - another token: 10% of masking candidate token """ candidate_id...
5,319,964
def do_delete(cs, args): """Deletes an instance.""" cs.instances.delete(args.instance)
5,319,965
def string2token(t,nl,nt): """ This function takes a string and returns a token. A token is a tuple where the first element specifies the type of the data stored in the second element. In this case the data types are limited to numbers, either integer, real or complex, and strings. The types...
5,319,966
def fitness_func(loci, **kwargs): """ Return how fit the locus is to describe a quarter of circle. It is a minisation problem and the theorical best score is 0. Returns ------- float Sum of square distances between tip locus bounding box and a defined square. """ # Locu...
5,319,967
def write_country_data_to_file(data_by_country): """ function to get video elements, preprocess them and write to file """ country_data = [] country_data.append(",".join(header)) for i in data_by_country: video_id = i.get("id", "") published_time = i["snippet"].get("publishedAt",...
5,319,968
def get_div(integer): """ Return list of divisors of integer. :param integer: int :return: list """ divisors = [num for num in range(2, int(integer**0.5)+1) if integer % num == 0] rem_divisors = [int(integer/num) for num in divisors] divisors += rem_divisors divisors.append(...
5,319,969
async def on_shard_ready(shard_id): """When a shard starts print out that the shard has started. Args: shard_id (int): The ID of the shard that has started. (Starts from 0). """ print(f"{Style.BRIGHT}{Fore.CYAN}[SHARD-STARTED]{Fore.WHITE} Shard {Fore.YELLOW}{shard_id}{Fore.WHITE} has started!")
5,319,970
def test_trim_blocks(gen_paths: typing.Any, run_nnvg: typing.Callable) -> None: """ Ensure the --trim-blocks switch is hooked up and functional. """ testtype_path = get_path_to_TestType_0_2(gen_paths) nnvg_args0 = ['--templates', str(gen_paths.templates_dir), '-O', str(gen_paths.out_d...
5,319,971
def test_one_showtime(): """4:45 pm""" with open("./tests/data/afi-nov-21.html", "r") as webpage: data = webpage.read().encode("utf-8") soup = BeautifulSoup(data, "html.parser") start_date = datetime.date(2021, 11, 1) shows = parse(soup, start_date) howling = shows[4] assert howl...
5,319,972
def ifuse(inputs): """Fuse iterators""" value, extent = 0, 1 for i, ext in inputs: value = value * ext + i extent = extent * ext return (value, extent)
5,319,973
def filtered_list_gen(raw_response, term=None, partial_match=True): """ Iterates over items yielded by raw_response_gen, validating that: 1. the `path` dict key is a str 2. the `path` value starts with starts_with (if provided) >>> r = [{ >>> 'checksum': { >>> 'md5': 'd9...
5,319,974
def occlude_with_pascal_objects(im, occluders): """Returns an augmented version of `im`, containing some occluders from the Pascal VOC dataset.""" result = im.copy() width_height = np.asarray([im.shape[1], im.shape[0]]) im_scale_factor = min(width_height) / 256 count = np.random.randint(1, 8) ...
5,319,975
def check_job_access_permission(request, job_id): """ Decorator ensuring that the user has access to the job submitted to Oozie. Arg: Oozie 'workflow', 'coordinator' or 'bundle' ID. Return: the Oozie workflow, coordinator or bundle or raise an exception Notice: its gets an id in input and returns the full o...
5,319,976
def is_dict_type(tp): """Return True if tp is a Dict""" return ( get_origin(tp) is dict and getattr(tp, '_name', None) == 'Dict' )
5,319,977
def shape(pyshp_shpobj): """Convert a pyshp geometry object to a flopy geometry object. Parameters ---------- pyshp_shpobj : shapefile._Shape instance Returns ------- shape : flopy.utils.geometry Polygon, Linestring, or Point Notes ----- Currently only regular Polygons, LineStrin...
5,319,978
def compute_nbr(image, sensor): """ Compute nbr index NBR = (NIR-SWIR2)/(NIR+SWIR2) """ bands = cp.sensors[sensor]["bands"] nir = image.select(bands["nir"]) swir2 = image.select(bands["swir2"]) doy = ee.Algorithms.Date(ee.Number(image.get("system:time_start"))) yearday = ee.Number...
5,319,979
def show_FG_components(FG, figsize=None, dpi=None, savename=None): """ Display a factor graph structure, showing each connected component. Parameters ---------- FG: networkx Graph Factor graph where node type is distinguisehd with the 'bipartite' attribute. figsize: tuple ...
5,319,980
def unbroadcast(array): """ Given an array, return a new array that is the smallest subset of the original array that can be re-broadcasted back to the original array. See http://stackoverflow.com/questions/40845769/un-broadcasting-numpy-arrays for more details. """ if array.ndim == 0: ...
5,319,981
def get_boxes_info( boxes_thinned, retr_mode, approx_method=cv2.CHAIN_APPROX_SIMPLE): """ Retreive contours and return a list of lists, each area of the box, and coordinates of the box. Parameters ---------- boxes_thinned : numpy.array Array containing photographic informati...
5,319,982
def getMaxLen(fastaFilePath): """ Gets the length of the sequence that has maximum length in a fasta file. """ maxLen = 0 for val in fasta.getSequenceToBpDict(fastaFilePath).itervalues(): if maxLen < int(val): maxLen = int(val) return maxLen
5,319,983
def align_face(filepath, output_size=1024, transform_size=4096, enable_padding=True): """ :param filepath: str :return: PIL Image """ ensure_checkpoint_exists("models/dlibshape_predictor_68_face_landmarks.dat") predictor = dlib.shape_predictor("models/dlibshape_predictor_68_face_landmarks.dat")...
5,319,984
def get(): """ vert tasks get """ table: object = Table(box=SQUARE) table.add_column('ID') table.add_column('Name') table.add_column('Category') table.add_column('Status', justify='center') table.add_column('Date') rows: tuple[tuple] = Tasks.get() for row in rows: t...
5,319,985
def build_model(lr_source, scaling_factor=3, hr_target=None): """ build espcn model lr_source: source image batch tensor to be super resolved hr_target: target image batch as training labels in sub-pixel convolved shape, build a partial model for testing if hr_target is None scali...
5,319,986
def run_simulation(coordinates, box_length, cutoff, reduced_temperature, num_steps, max_displacement = 0.1, freq = 1000): """ Run a Monte Carlo simulation with the specified parameters. """ # Reporting information steps = [] energies = [] beta = 1 / reduced_temperature num_particles...
5,319,987
def sum_up_validation_dataset(dataset, batch_size, repeat=True, number_of_repetitions=0): """Define how the validation dataset is suppose to behave during training. This function is applied to the validation dataset just before the actual training process. The characteristics...
5,319,988
def moist_lift_parcel(parcel_pressure, parcel_temperature, to_pressure, step=1): """ Recursively determine the temperature of a parcel lifted from one pressure to another, assuming moist pseudoadiabatic processes. Arguments: parcel_pressure: The starting parcel pressure. parcel_tem...
5,319,989
def init_gpio(): """ Initialise the GPIO library """ GPIO.setwarnings(False) if MONITOR_PIN_NUMBERING == "BCM": logging.debug("Initialising GPIO using BCM numbering") GPIO.setmode(GPIO.BCM) else: logging.debug("Initialising GPIO using Board numbering") GPIO.setmod...
5,319,990
def has_rule(table, chain, rule_d, ipv6=False): """ Return True if rule exists in chain False otherwise """ iptc_chain = _iptc_getchain(table, chain, ipv6) iptc_rule = encode_iptc_rule(rule_d, ipv6) return iptc_rule in iptc_chain.rules
5,319,991
async def test_md_deploy_failed_status_code( mock_httpx_client, sf_client, ): """Test method for metadata deployment on Failure""" _, _, inner = mock_httpx_client bad_result = httpx.Response( 2599, request=httpx.Request("POST", f"{sf_client.metadata_url}deployRequest"), content=b...
5,319,992
def get_pings_measurements(ip): """ Performs a ping measurement to an IP or returns cached result :param ip: string ip address :return: dictionary {src: rtt} where src is the string ip address of the measurement source, and rtt is the minimum rtt recorded for a ping from that src to the ip addre...
5,319,993
def get_timestamp(date_time): """Return the Unix timestamp of an ISO8601 date/datetime in seconds. If the datetime has no offset, it is assumed to be an UTC datetime. :param date_time: the datetime string to return as timestamp :type date_time: str :returns: the timestamp corresponding to the date...
5,319,994
def vfunction_delete(cmd_ctx, cpc, partition, vfunction): """ Delete a virtual function. In addition to the command-specific options shown in this help text, the general options (see 'zhmc --help') can also be specified right after the 'zhmc' command name. """ cmd_ctx.execute_cmd(lambda: cm...
5,319,995
def test_get_obsids(): """ Test that archive.obspar.get_obsids gets a reasonable set of obsids. """ start = "2016:001:12:00:00" stop = "2016:005:12:00:00" mica_obs = obspar.get_obsids(start, stop) # from kadi.events.obsids.filter(start, stop) kadi_obsid_list = [51365, 18736, 18036, 18203...
5,319,996
def ssd_arg_scope(weight_decay=0.0005, data_format='NHWC'): """Defines the MobileNetV1 arg scope. Args: weight_decay: The l2 regularization coefficient. Returns: An arg_scope. """ with slim.arg_scope([slim.conv2d, slim.fully_connected], activation_fn=tf.nn.relu,...
5,319,997
def fntDoOneLine(mysLine, mynProc, mynLine): """Execute one single-line command. Input: single line of command. Output: tuple of the (Popen PIPE return code, command return code, list of output lines as strings. Contributes line(s) to be in log file. Input lines and the first line of ...
5,319,998
def _build_module_page(page_info: parser.ModulePageInfo, table_view: bool) -> str: """Constructs a markdown page given a `ModulePageInfo` object. Args: page_info: A `ModulePageInfo` object containing information that's used to create a module page. For example, see https://ww...
5,319,999