content
stringlengths
22
815k
id
int64
0
4.91M
def register_new_face( face_encoding, face_image ) : """ Add a new person to our list of known faces """ # Add the face encoding to the list of known faces known_face_encodings.append(face_encoding) # Add a matching dictionary entry to our metadata list. # We can use this to keep track of ho...
33,600
def get_files_recurse(path: Path) -> Set: """Get all files recursively from given :param:`path`.""" res = set() for p in path.rglob("*"): if p.is_dir(): continue res.add(p) return res
33,601
def img_after_ops(img: List[str], ops: List[int]) -> List[str]: """Apply rotation and flip *ops* to image *img* returning the result""" new_img = img[:] for op in ops: if op == Tile.ROTATE: new_img = [cat(l)[::-1] for l in zip(*new_img)] elif op == Tile.FLIP: new_img ...
33,602
def authenticated(method): """Decorate methods with this to require that the user be logged in. Fix the redirect url with full_url. Tornado use uri by default. """ @functools.wraps(method) def wrapper(self, *args, **kwargs): user = self.current_user if not us...
33,603
def ring_samp_ranges(zma, rng_atoms): """ Set sampling range for ring dihedrals. :param zma: Z-Matrix :type zma: automol.zmat object :param rng_atoms: idxs for atoms inside rings :type rng_atoms: list """ samp_range_dct = {} ring_value_dct = ring_dihedrals(zma, rng_atom...
33,604
def users_key(group='default'): """ Returns the user key """ return db.Key.from_path('users', group)
33,605
def pool(data, batch_size, key, batch_size_fn=lambda new, count, sofar: count, random_shuffler=None, shuffle=False, sort_within_batch=False, bucket_size= 1000): """Sort within buckets, then batch, then shuffle batches. Partitions data into chunks of size 100*batch_size, sorts examples within each ch...
33,606
def movefiles(names, dest): """ """ for name in names: copyfile(name.strip('\n'), dest+'/'+name.split("/")[-1].strip('\n')) return
33,607
def fit_classifiers(): """ API to get fit classifiers for training *Language independent :raise: Exception containing: message: - "OK" for success status_code: - 200 for success """ language = request.args.get('lang', None) status_code, message =...
33,608
def VolumetricFlow(self): """Volumetric flow (m^3/hr).""" stream, mol = self.data m = mol[0] if m: c = self.name # c = compound c.T = stream.T c.P = stream.P c.phase = stream._phase return c.Vm * m * 1000 else: return 0.
33,609
def build_queue_adapter(workflow_client, logger=None, **kwargs): """Constructs a queue manager based off the incoming queue socket type. Parameters ---------- workflow_client : object ("distributed.Client", "fireworks.LaunchPad") A object wrapper for different distributed workflow types log...
33,610
def configure_parser(parser): """Configure parser for this action """ qisys.parsers.worktree_parser(parser) qitoolchain.parsers.toolchain_parser(parser) parser.add_argument("package_name", metavar='NAME', help="The name of the package to remove")
33,611
def pad_sents(sents, pad_token, return_tensor = False): """ Pad list of sentences according to the longest sentence in the batch. The paddings should be at the end of each sentence. @param sents (list[list[str]]): list of sentences, where each sentence is represented ...
33,612
def _take_along_axis(array, indices, axis): """Takes values from the input array by matching 1D index and data slices. This function serves the same purpose as jax.numpy.take_along_axis, except that it uses one-hot matrix multiplications under the hood on TPUs: (1) On TPUs, we use one-hot ...
33,613
def send_envelope( adfs_host: str, envelope: str, ) -> requests.Response: """Send an envelope to the target ADFS server. Arguments: adfs_host: target ADFS server envelope: envelope to send Returns: ADFS server response """ url = f"http://{adfs_host}/adfs/services/po...
33,614
def display_main(choice): """ Link option To main board """ return main(choice)
33,615
def test_html_blocks_extra_03a(): """ Test case extra 03: variation of 3 with LRD """ # Arrange source_markdown = """- <script> [foo]: /url </script> """ expected_tokens = [ "[ulist(1,1):-::2:: ]", "[html-block(1,3)]", "[text(1,3):<script>\n[foo]::]", "[end-h...
33,616
def generate_network_table(seed=None): """ Generates a table associating MAC and IP addressed to be distributed by our virtual network adapter via DHCP. """ # we use the seed in case we want to generate the same table twice if seed is not None: random.seed(seed) # number of IPs per net...
33,617
def loss_mGLAD(theta, S): """The objective function of the graphical lasso which is the loss function for the meta learning of glad loss-meta = 1/B(-log|theta| + <S, theta>) Args: theta (tensor 3D): precision matrix BxDxD S (tensor 3D): covariance matrix BxDxD (dim=D) Returns:...
33,618
def parse_remote_path(remote_path): """ Wrapper around the utils function - checks for the right protocol """ protocol, bucket, key = utils.parse_remote_path(remote_path) assert protocol == "s3:", "Mismatched protocol (expected AWS S3)" return bucket, key
33,619
def version1_check(info): """ Creates a report for SAP HANA instances running on version 1 """ found = {} for instance in info.instances: if _manifest_get(instance.manifest, 'release') == '1.00': _add_hana_details(found, instance) if found: detected = _create_detected_instan...
33,620
def operations(func: Callable) -> Callable: """Allows developers to specify operations which should not be called in the fuzzing process. Examples: Ignoring operations specified by operation ids in lists >>> @fuzz_lightyear.exclude.operations ... def b(): ... ...
33,621
def _gen_dfa_table(t: UxsdComplex) -> str: """Generate a 2D C++ array representing DFA table from an UxsdComplex's DFA. The array is indexed by the state and input token value, such that table[state][input] gives the next state. """ assert isinstance(t.content, UxsdDfa) dfa = t.content.dfa out = "" out += "con...
33,622
def get_heat_capacity_derivative(Cv, temperature_list, plotfile='dCv_dT.pdf'): """ Fit a heat capacity vs T dataset to cubic spline, and compute derivatives :param Cv: heat capacity data series :type Cv: Quantity or numpy 1D array :param temperature_list: List of temperatures used in repli...
33,623
def do_mon_show(cs, args): """Shows details info of a mon.""" mon = _find_mon(cs, args.mon) _print_mon(mon)
33,624
def cfgfile_cl1(db200_static_file): """Return path to configfile for compliance level 1. This fixture not only configures the server, but also creates a mock database with 200 factoids in the temporary directory where the configfile is written to. As compliance level 1 is read only by default, we ...
33,625
def get_gradients_of_activations(model, x, y, layer_names=None, output_format='simple', nested=False): """ Get gradients of the outputs of the activation functions, regarding the loss. Intuitively, it shows how your activation maps change over a tiny modification of the loss. :param model: keras compile...
33,626
def gJoin(gl1, gl2): """Return gl1+gl2, i.e [gl1[0],...,gl1[n],gl2[0],...] Apparently only useful when gl1 is finite. """ for x in gl1: yield x for x in gl2: yield x
33,627
def string_to_screens_and_lines(source, allowed_width, allowed_height, f, pixels_between_lines = None, end_screens_with = (), do_not_include = ()): """ Convert a string to screens and lines. Pygame does not allow line breaks ("\n") when rendering text. The purpose of this function is to break a str...
33,628
def trim_spectrum(self, scouse, flux): """ Trims a spectrum according to the user inputs """ return flux[scouse.trimids]
33,629
def test_sin_2ndord_2vars(): """ Function testing 2nd order derivative for sin with two-variable input """ x, y = fwd.Variable(), fwd.Variable() f = fwd.sin(x/y) df_dxdy = lambda x, y: -(y*np.cos(x/y) - x*np.sin(x/y))/y**3 assert equals(f.derivative_at((x, x), {x: 1.5, y:2.5}, order=2), ...
33,630
def test_bitwise_and(a, b): """ >>> test_bitwise_and(0b01, 0b10) 0L >>> test_bitwise_and(0b01, 0b11) 1L >>> test_bitwise_and(0b01, 2.0) Traceback (most recent call last): ... NumbaError: 27:15: Expected an int, or object, or bool >>> test_bitwise_and(2.0, 0b01) Tracebac...
33,631
def main(): """Post reminders about open CodeCommit pull requests to slack.""" open_pull_requests = get_open_pull_requests() post_message(open_pull_requests)
33,632
def flagFunction(method, name=None): """ Determine whether a function is an optional handler for a I{flag} or an I{option}. A I{flag} handler takes no additional arguments. It is used to handle command-line arguments like I{--nodaemon}. An I{option} handler takes one argument. It is used to ...
33,633
def azure_blob(Config, file_name, dump_path, db): """ upload file to azure blob container. Parameters: Config (sectionproxy): database details from configparser file_name (str): local file name, to set as blob name dump_path (str): local b...
33,634
def envnotfound(env): """`'Env "my-venv" not found. Did you mean "./my-venv"?'`""" msg = f'Env "{env}" not found.' if arg_is_name(env) and Path(env).exists(): msg += f'\nDid you mean "./{env}"?' return msg
33,635
def random_translation_along_x(gt_boxes, points, offset_range): """ Args: gt_boxes: (N, 7), [x, y, z, dx, dy, dz, heading, [vx], [vy]] points: (M, 3 + C), offset_range: [min max]] Returns: """ offset = np.random.uniform(offset_range[0], offset_range[1]) points[...
33,636
def predband(xd,yd,a,b,conf=0.95,x=None): """ Calculates the prediction band of the linear regression model at the desired confidence level, using analytical methods. Clarification of the difference between confidence and prediction bands: "The 2sigma confidence interval is 95% sure to contain the best-fit regressio...
33,637
def orient_edges(G): """Orient remaining edges after colliders have been oriented. :param G: partially oriented graph (colliders oriented) :returns: maximally oriented DAG """ undir_list = [edge for edge in G.edges() if G.is_undir_edge(edge)] undir_len = len(undir_list) idx = ...
33,638
def _create_deserialize_fn(attributes: dict, globals: dict, bases: tuple[type]) -> str: """ Create a deserialize function for binary struct from a buffer The function will first deserialize parent classes, then the class attributes """ lines = [] # For this class bases for parent in bases:...
33,639
def blck_repeat(preprocessor: Preprocessor, args: str, contents: str) -> str: """The repeat block. usage: repeat <number> renders its contents one and copies them number times""" args = args.strip() if not args.isnumeric(): preprocessor.send_error("invalid-argument", "invalid argument. Usage: repeat [uint > 0]"...
33,640
def is_prime(n: int) -> bool: """Determines if the natural number n is prime.""" # simple test for small n: 2 and 3 are prime, but 1 is not if n <= 3: return n > 1 # check if multiple of 2 or 3 if n % 2 == 0 or n % 3 == 0: return False # search for subsequent prime factors aro...
33,641
def annotate(number_of_scans): # annotation starting from scan 1 """ Annotate the data form 3DIrcad1 dataset, starting from scan 1, up to scan passed in param. Save the labels to an excel file 'tabulka.xlsx'. """ df = pd.DataFrame( columns=[ "Ircad ID", "Mark 1 ...
33,642
def test_envset_returns_false(): """Env set returns false if env>set doesn't exist..""" # Deliberately have 1 pre-existing $ENV to update, and 1 unset so can # create it anew as part of test os.environ['ARB_DELETE_ME2'] = 'arb from pypyr context ARB_DELETE_ME2' context = Context({ 'key1': '...
33,643
def get_word_prob(): """Returns the probabilities of all the words in the mechanical turk video labels. """ import constants as c import cPickle data = cPickle.load(open(c.datafile)) # Read in the words from the labels wordcount = dict() totalcount = 0 for label in data: for word...
33,644
def angDistance(ra, dec, df, raCol='fieldRA', decCol='fieldDec'): """ """ df['dist'] = angSep(ra, dec, df[raCol], df[decCol]) idx = df.dist.idxmin() rval = df.loc[idx] df.drop('dist', axis=1, inplace=True) return rval
33,645
def test_login(test_client): """Make sure login and logout works.""" response = login(test_client, 'aa@gmail.com', 'b') assert b"Email does not exist." in response.data response = login(test_client, 'jay@gmail.com', 'b') assert b"Incorrect password, try again." in response.data response = log...
33,646
def offer_in_influencing_offers(offerId, influencing_offers): """ Find if a passed offerId is in the influencing_offers list Parameters ---------- offerId: Offer Id from portfolio dataframe. influencing_offers : List of offers found for a customer Returns ------- 1 if of...
33,647
def setupVortexServer(portNum=8345, wsPortNum=8344): """ Setup Site Sets up the web site to listen for connections and serve the site. Supports customisation of resources based on user details @return: Port object """ defer.setDebugging(True) # Register the test tuple from vortex.test ...
33,648
def identity_block(filters, stage, block): """The identity block is the block that has no conv layer at shortcut. # Arguments filters: integer, used for first and second conv layers, third conv layer double this value stage: integer, current stage label, used for generating layer names b...
33,649
def renderscene(): """This function litterally prints the scene.""" global xrot, yrot global X, Y, Z global quater global rotx, roty, rotz global maxx, maxy, maxz global mesg1 global mesg2 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) glPushMatrix() indic = -1 f...
33,650
def filebeat_service_running(): """ Checks if the filebeat service is currently running on the OS. :return: True if filebeat service detected and running, False otherwise. """ result = False try: filebeat_service = psutil.win_service_get('filebeat') filebeat_service_info = filebe...
33,651
def unhandled_request_message(request, cassette): """Generate exception for unhandled requests.""" return UNHANDLED_REQUEST_EXCEPTION.format( url=request.url, cassette_file_path=cassette.cassette_name, cassette_record_mode=cassette.record_mode, cassette_match_options=cassette.match_optio...
33,652
def logout(request): """ Logs out the user and displays 'You are logged out' message. """ if request.method == 'GET': return _new_api_403() from django.contrib.auth import logout as auth_logout auth_logout(request)
33,653
def compara_dv(cpf, primeiro_dv, segundo_dv): """Valida se dígitos verificadores calculados são iguais aos inseridos.""" return "válido" if primeiro_dv == int(cpf[9]) and segundo_dv == int(cpf[10]) else "inválido"
33,654
def write_file(file_name, data, line_length): """ Writes the results to a text file using a name based on file_name input: string, list returns: int """ pos = file_name.rfind('.') fn_o = file_name[:pos] + '.OUT' + file_name[pos:] f = open(fn_o, "w") for fsn, sequence in data: ...
33,655
def handle_duplicates(df, cutoff=5, agg_source_col='multiple'): """Aggregates duplicate measurements in a DataFrame. Parameters ---------- df : pandas DataFrame DataFrame with required columns: 'smiles', 'solvent', 'peakwavs_max' cutoff : int Wavelength cutoff in nm. Duplicate meas...
33,656
def splitData(features, target, trainFraction=0.25): """ Split the data into test and train data Inputs: > features: the model feature data (DataFrame) > target: the target data (Series) > trainFraction (0.25 by default): fraction of events to use for training Outputs: ...
33,657
def poisson_moment( k, n): """ returns the moment of x**n with expectation value k CURRENTLY A SET OF HARD CODED EXPRESSIONS! VERY FRAGILE! --> would be *much* better if we could do this algorithmically """ if n==0: return 1 elif n==1: return k elif n==2: ret...
33,658
def save_results(annot_bundles_df, intensity_matrix, params, rel_points): """ Function: Save results to a pickle file Inputs: - annot_bundles_df - intensity_matrix - params - rel_points Outputs: output_data as adictionary saved in output folder - component of output_data: category_id, sample_id, region_id, s...
33,659
def drug_encoder(input_smiles): """ Drug Encoder Args: input_smiles: input drug sequence. Returns: v_d: padded drug sequence. temp_mask_d: masked drug sequence. """ temp_d = drug_bpe.process_line(input_smiles).split() try: idx_d = np.asarray([drug_idx[i] for...
33,660
def resp_graph(dataframe, image_name, dir='./'): """Response time graph for bucketed data :param pandas.DataFrame dataframe: dataframe containing all data :param str image_name: the output file name :param str dir: the output directory :return: None """ fig = pygal.TimeLine(x_title='Elapsed...
33,661
def load_mapping_files(): """Load local and remote mapping files.""" mappings = {} local = ["properties", "countries", "professions", "latin_countries", "latin_languages"] remote = ["selibr"] for title in local: f = os.path.join(MAPPINGS, '{}.json'.format(title)) mapping...
33,662
def optimise_acqu_func_mledr(acqu_func, bounds, X_ob, func_gradient=True, gridSize=10000, n_start=5): """ Optimise acquisition function built on GP- model with learning dr :param acqu_func: acquisition function :param bounds: input space bounds :param X_ob: observed input data :param func_gradi...
33,663
def get_path_from_pc_name(pc_name): """Find out path of a template Parameters ---------- pc_name : string Name of template. Returns ------- tplPath : string Path of template """ tplPath = pc_name + '.json' # change path to template if in subdir for i in p...
33,664
def eq(*, alpha=None, omega): """Define dyadic comparison function equal to. Dyadic case: 3 = 2 3 4 0 1 0 """ return int(alpha == omega)
33,665
def generate_days(year): """Generates all tuples (YYYY, MM, DD) of days in a year """ cal = calendar.Calendar() days = [] for m in range(1,13): days.extend(list(cal.itermonthdays3(year, m))) days = [d for d in set(days) if d[0] == year] days.sort() return days
33,666
def nounClassifier(word): """Classifies noun as actor o object Parameters ---------- word : str Lematized noun to be classified (case-insensitive). """ word = word.lower() response_raw = requests.get( f"{API_URL}senses/search?lemma={word}&&&partOfSpeech=noun&&&&&&" ) ...
33,667
def svn_repos_post_lock_hook(*args): """svn_repos_post_lock_hook(svn_repos_t repos, apr_pool_t pool) -> char""" return _repos.svn_repos_post_lock_hook(*args)
33,668
def delete_folder(path): """ Deletes a whole test folder. """ command = ['rm', '-rf', TEST_DIR] file_operation(path, command)
33,669
def libdmtx_function(fname, restype, *args): """Returns a foreign function exported by `libdmtx`. Args: fname (:obj:`str`): Name of the exported function as string. restype (:obj:): Return type - one of the `ctypes` primitive C data types. *args: Arguments - a sequence of `ctype...
33,670
def make_plot(title: str, safe_ratios: Dict[AgentType, List[float]]): """Generate a plot for a single BenchResult""" plt.figure() for typ, ratios in safe_ratios.items(): plt.plot([x * 100 for x in ratios], color=AGENT_COLORS[typ.name]) plt.title(title) plt.xlabel("Time") plt....
33,671
async def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" control_unit: ControlUnit = hass.data[DOMAIN][config_entry.entry_id] diag: dict[str, Any] = { "config": async_redact_data(config_entry.as...
33,672
def test_stage_function_one_function_stage_two_output_success(): """ Feature: test servable_config.py stage Description: Test stage with one input, two outputs Expectation: Serving server work ok. """ servable_content = r""" import numpy as np from mindspore_serving.server import register tensor...
33,673
async def instance_set_name_inurl(cluster_id: str, vm_uuid: str, new_name: str): """ Set Instance (VM/Template) Name """ try: try: session = create_session( _id=cluster_id, get_xen_clusters=Settings.get_xen_clusters() ) except KeyError as key_error: ...
33,674
def key_released(key): """ Takes a key, that's either a keycode or a character, and says if it was released this frame. """ keycode = _to_keycode(key) return (keycode not in current_frame_held_buttons) and \ (keycode in last_frame_held_buttons)
33,675
def main(): """ Entry point. """ unittest.main()
33,676
def trim_snakes_old(lcs,ref,Nb,Ne,dat,Mb,Me): """Previously found matches can cause problems if they are not optimal. In such a case sticking with the matches as found prevents subsequent more advanced diff routines from recovering from an early sub-optimal choice. To counter this all snakes and pseudo...
33,677
def render_mov(fname, steps, fps=30): """ Load a saved SafeLifeGame state and render it as an animated gif. Parameters ---------- fname : str steps : int The number of steps to evolve the game state. This is the same as the number of frames that will be rendered. fps : float...
33,678
def test_getitem(posterior): """Getitem performs as expected.""" np.testing.assert_allclose(posterior[0].mean, posterior.states[0].mean) np.testing.assert_allclose(posterior[0].cov, posterior.states[0].cov) np.testing.assert_allclose(posterior[-1].mean, posterior.states[-1].mean) np.testing.assert...
33,679
async def start(actual_coroutine): """ Start the testing coroutine and wait 1 second for it to complete. :raises asyncio.CancelledError when the coroutine fails to finish its work in 1 second. :returns: the return value of the actual_coroutine. :rtype: Any """ try: return aw...
33,680
def breadthIterArgs(limit=1000, testFn='<function isIterable>', *args): """ iterator doing a breadth first expansion of args """ pass
33,681
def get_node(path): """Returns a :class:`Node` instance at ``path`` (relative to the current site) or ``None``.""" try: current_site = Site.objects.get_current() except Site.DoesNotExist: current_site = None trailing_slash = False if path[-1] == '/': trailing_slash = True try: node, subpath = Node.obj...
33,682
def new_post(blog_id, username, password, post, publish): """ metaWeblog.newPost(blog_id, username, password, post, publish) => post_id """ user = authenticate(username, password, 'zinnia.add_entry') if post.get('dateCreated'): creation_date = datetime.strptime( post['dateCre...
33,683
def upload(userid, filedata): """ Creates a preview-size copy of an uploaded image file for a new avatar selection file. """ if filedata: media_item = media.make_resized_media_item(filedata, (600, 500), 'FileType') orm.UserMediaLink.make_or_replace_link(userid, 'avatar-source', media...
33,684
def print_warning(port: int) -> None: """Prints a message on screen to run an app or api on the specific port. Args: port: Port number. """ sys.stdout.write(f'\rRun an application on the port {port} to start tunneling.') sleep(5) sys.stdout.flush() sys.stdout.write('\r')
33,685
def autoconfig( rewrite_asserts=default, magics=default, clean=default, addopts=default, run_in_thread=default, defopts=default, display_columns=default, ): """Configure ``ipytest`` with reasonable defaults. Specifically, it sets: {defaults_docs} See :func:`ipytest.config`...
33,686
def get_account_2_json(usr, pwd): """ 将从环境变量获取的账号密码拼接成json :return: 字典 """ username = os.popen("env | grep {}".format(usr)) password = os.popen("env | grep {}".format(pwd)) username_list = username.read().split() password_list = password.read().split() username_dict = str2dict(";".jo...
33,687
def browse(bot, update): """/browse command. Displays a keyboard/buttons UI for navigation. Catalog-like UI where the user can browse through different categories of pictograms. Args: bot(object): the bot instance. update(object): the message sent by the user. """ # 1st level k...
33,688
def time_dconv_bn_nolinear(nb_filter, nb_row, nb_col, stride=(2, 2), activation="relu"): """ Create time convolutional Batch Norm layer in decoders. Parameters: --------- filter_num : int number of filters to use in convolution layer. row_num : int n...
33,689
def ___generate_random_row_major_GM___(i, j, s=None): """Make a random row major sparse matrix of shape (i,j) at sparsity=s. :param i: :param j: :param s: :return: """ if s is None: s = random.uniform(0, 0.1) if s < 0.02: s = 0 if rAnk == mAster_rank: random_lis...
33,690
def link_control_policy_maker(intersight_api_key_id, intersight_api_key, policy_name, admin_state="Enabled", mode="Normal", policy_description="", ...
33,691
def set_level(self, level): """Set logging level""" if not level: self.setLevel(0) return level = _get_level_number(level) self.setLevel(level)
33,692
def parse_tuple(value: Tuple[Any, ...]) -> RGBA: """ Parse a tuple or list as a color. """ if len(value) == 3: r, g, b = [parse_color_value(v) for v in value] return RGBA(r, g, b, None) elif len(value) == 4: r, g, b = [parse_color_value(v) for v in value[:3]] return R...
33,693
def find_path( start_path: pathlib.Path = pathlib.Path("."), ) -> Optional[pathlib.Path]: """Traverse the file system looking for the config file .craftier.ini. It will stop earlier at the user's home directory, if it encounters a Git or Mercurial directory, or if it traversed too deep. """ hom...
33,694
def crop_point_data_to_base_raster(raster_name, raster_directory, csv_file, EPSG_code = 0): """ This function create a new csv file cropped to the base raster. It can lower the processing time if your point data is on a significantly larger area than the base raster. """ print("ok let me load your datas...
33,695
def test_gen_ipv6_3(): """Generate a IPv6 address with custom prefix.""" result = gen_ipaddr(ipv6=True, prefix=['e2d3']) assert len(result.split(':')) == 8 assert result.startswith('e2d3:')
33,696
def generate_schedule_report_data(pools_info, pools_allocated_mem): """ Generate the schedule report data. :param pools_info: (dict) The information about the configuration and statistics of the pool participating in the scheduling. :param pools_allocated_mem: (dict) The allocated memory of the...
33,697
def create_feature_rule_json(device, feature="foo", rule="json"): """Creates a Feature/Rule Mapping and Returns the rule.""" feature_obj, _ = ComplianceFeature.objects.get_or_create(slug=feature, name=feature) rule = ComplianceRule( feature=feature_obj, platform=device.platform, conf...
33,698
def test_returns_specified_plugin(application): """Verify we get the plugin we want.""" desired = mock.Mock() execute = desired.execute application.formatting_plugins = { 'default': mock.Mock(), 'desired': desired, } with mock.patch.object(app.LOG, 'warning') as warning: ...
33,699