content
stringlengths
22
815k
id
int64
0
4.91M
def fluentd(): """Fluentd related packaging operations"""
45,300
async def test_entity_device_info_update(hass, mqtt_mock): """Test device registry update.""" await help_test_entity_device_info_update( hass, mqtt_mock, alarm_control_panel.DOMAIN, DEFAULT_CONFIG )
45,301
def _ValidateCandidateImageVersionId(current_image_version_id, candidate_image_version_id): """Determines if candidate version is a valid upgrade from current version.""" if current_image_version_id == candidate_image_version_id: return False parsed_curr = _ImageVersionIt...
45,302
def run_mc_sim(lattice, num_lattice_steps, data_dict, io_dict, simsetup, exosome_string=EXOSTRING, exosome_remove_ratio=0.0, ext_field_strength=FIELD_SIGNAL_STRENGTH, app_field=None, app_field_strength=FIELD_APPLIED_STRENGTH, beta=BETA, plot_period=LATTICE_PLOT_PERIOD, flag_...
45,303
def collisional_loss(electron_energy): """ Compute the energy dependant terms of the collisional energy loss rate for energetic electrons. Parameters ---------- electron_energy : `numpy.array` Array of electron energies at which to evaluate loss Returns ------- `numpy.array` ...
45,304
def getOrdererIPs(): """ returns list of ip addr """ client = docker.from_env() container_list = client.containers.list() orderer_ip_list = [] for container in container_list: if re.search("^orderer[1-9][0-9]*", container.name): out = container.exec_run("aw...
45,305
def repair_attribute_name(attr): """ Remove "weird" characters from attribute names """ import re return re.sub('[^a-zA-Z-_\/0-9\*]','',attr)
45,306
def get_xsd_file(profile_name, profile_version): """Returns path to installed XSD, or local if no installed one exists.""" if profile_name.lower() not in XSD_LOOKUP_MAP: raise ValueError( 'Profile %s did not match a supported profile: %s.\n' % (profile_name, sorted(XSD_FILES.keys()))) # Ensur...
45,307
def get_response(url: str) -> HTMLResponse: """ 向指定url发起HTTP GET请求 返回Response :param url: 目标url :return: url响应 """ session = HTMLSession() return session.get(url)
45,308
def minutesBetween(date_1, date_2): """Calculates the number of whole minutes between two dates. Args: date_1 (Date): The first date to use. date_2 (Date): The second date to use. Returns: int: An integer that is representative of the difference between two dates. "...
45,309
def find_whatrecord_submodules() -> Dict[str, ModuleType]: """Find all whatrecord submodules, as a dictionary of name to module.""" modules = {} package_root = str(MODULE_PATH.parent) for item in pkgutil.walk_packages(path=[package_root], prefix="whatrecord."): if item.name.endswith("__main__"):...
45,310
def neighbors(ipaddress, info_type, namespace): """Show IPv6 BGP neighbors""" if ipaddress is not None: if not bgp_util.is_ipv6_address(ipaddress): ctx = click.get_current_context() ctx.fail("{} is not valid ipv6 address\n".format(ipaddress)) try: actual_name...
45,311
def test_complete_multipart_upload(app, indexd_client): """ Test BlankIndex complete_multipart_upload """ uploader = MagicMock() blank_index = BlankIndex(uploader=uploader) assert blank_index with patch( "fence.blueprints.data.indexd.S3IndexedFileLocation.complete_multipart_upload" ...
45,312
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload FireServiceRota config entry.""" await hass.async_add_executor_job( hass.data[DOMAIN][entry.entry_id].websocket.stop_listener ) unload_ok = all( await asyncio.gather( *[ ...
45,313
def project_with_produced_data(app: Application) -> Iterator[Project]: """Fixture for opening ProjectWithProducedData. This is useful to improve test time by not opening/closing this project in every test. """ with copy_project("ProjectWithProducedData") as project_path: project = app.open_proj...
45,314
def HasPositivePatterns(test_filter): """Returns True if test_filter contains a positive pattern, else False Args: test_filter: test-filter style string """ return bool(len(test_filter) > 0 and test_filter[0] != '-')
45,315
def test_longest_substring(): """test longest substring""" test_cases = ( ("", 0), ("a", 1), ("ab", 2), ("aba", 2), ("bacdea", 5), ("abcabcbb", 3), ("bbbbb", 1), ("pwwkew", 3), ) for args, expected in test_cases: assert longest_sub...
45,316
def get_lr(lr_init, lr_end, lr_max, total_epochs, warmup_epochs, pretrain_epochs, steps_per_epoch, lr_decay_mode): """ generate learning rate array Args: lr_init(float): init learning rate lr_end(float): end learning rate lr_max(float): max learning rate total_epo...
45,317
def comptineN2(): """Generate the midi file of the comptine d'un autre été""" mid = MidiFile() trackl = MidiTrack() trackl.name = "Left hand" for i in range(8): trackl = comp_lh1(trackl) trackl = comp_lh1(trackl) trackl = comp_lh2(trackl) trackl = comp_lh2(trackl) ...
45,318
def create_source_archive(archive_path, packages=["pySPACE"], patterns=["*.py", "*.yaml"]): """ Store the source code of important packages Locates all files in the directory structure of the given :packages: that match the given :patterns:. Add these files to an archive that is ...
45,319
def xs_helper(monkeypatch): """ Provide a XenServerHelper instance and monkey-patch xenserver.tasks to use sessions from that instance instead of making real API calls. """ from xenserver import tasks from xenserver.tests.helpers import XenServerHelper xshelper = XenServerHelper() monkey...
45,320
def highest_palindrome_product(digits): """Returns the highest palindrome number resulting from the multiplication of two numbers with the given amount of digits. """ def is_palindrome(target): """Returns True if target (str or int) is a palindrome. """ string = str(target) ...
45,321
def is_ladder(try_capture, game_state, candidate, ladder_stones=None, recursion_depth=50): """Ladders are played out in reversed roles, one player tries to capture, the other to escape. We determine the ladder status by recursively calling is_ladder in opposite roles, providing suitable captur...
45,322
def instances(request, compute_id): """ :param request: :return: """ all_host_vms = {} error_messages = [] compute = get_object_or_404(Compute, pk=compute_id) if not request.user.is_superuser: all_user_vms = get_user_instances(request) else: try: all_host...
45,323
def seresnet101b_cub(classes=200, **kwargs): """ SE-ResNet-101 model with stride at the second convolution in bottleneck block from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- classes : int, default 200 Number of classification classes. ...
45,324
def get_template_dir(format): """ Given a format string return the corresponding standard template directory. """ return os.path.join(os.path.dirname(__file__), 'templates', format)
45,325
def dst(request): """Return a real temporary folder path which is unique to each test function invocation. This folder is deleted after the test has finished. """ dst = Path(mkdtemp()).resolve() request.addfinalizer(lambda: shutil.rmtree(str(dst), ignore_errors=True)) return dst
45,326
def calculate_one_moving_one_stationary_distancelimit( poly1, poly1_offset, poly1_velocity, poly2, poly2_offset, max_distance ): """ Determine if the moving polygon will intersect the stationary polygon within some distance. This is a step up, and very similar to the actual problem many any-an...
45,327
def getSentencesFromReview(reviewContent): """ INPUT: a single review consist of serveral sentences OUTPUT: a list of single sentences """ sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') sentences = sent_detector.tokenize(reviewContent) # split agglomerated sentences fo...
45,328
def projectCurve(q=1,e=1,cch=1,d="[linear, linear, linear]",dx="linear",dy="linear",dz="linear",nds="int",tol="linear",un=1,ch=1,n="string",o=1,rn=1): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/projectCurve.html ----------------------------------------- projectCurve is undoabl...
45,329
def set_indicators(doc): """Set 'Analysis Required' on rows as a helper for js color indicators.""" start_idx, fg_item = None, None last_idx = doc.items[-1].idx # get finished item first row start_idx = [row.idx for row in doc.items if row.is_finished_item][0] fg_item = doc.items[start_idx - 1].item_code templ...
45,330
def deploy(func: callable): """ Deploy function to Google Cloud Platform. """
45,331
def _PatchedSymbols(symbol_to_matching, profiled_symbols, max_outlined_index): """Internal computation of an orderfile. Args: symbol_to_matching: ({symbol name -> [symbols at same offset]}), as from _GroupSymbolsByOffset. profiled_symbols: ([symbol names]) as from the unpatched orderfile. max_out...
45,332
def run(): """requirement for task 1F""" stations = build_station_list() # call function from .station submodule to use built list of stations and also sort them alphabetically inconsistent_stations, inconsistent_data = inconsistent_typical_range_stations(stations) inconsistent_stations.sort()...
45,333
def gamma_vector_neutrino(m_med, g_l=0.0): """Function to calculate the neutrino width of a vector mediator :param m_med: mediator mass :type m_med: float :param g_l: lepton coupling, defaults to 0.0 :type g_l: float, optional """ return 3 * g_l**2 / (24 * math.pi) * m_med
45,334
def load_debugtalk_functions() -> Dict[Text, Callable]: """ load project debugtalk.py module functions debugtalk.py should be located in project root directory. Returns: dict: debugtalk module functions mapping { "func1_name": func1, "func2_name": fun...
45,335
def fifo_cdc(glbl, emesh_i, emesh_o): """ map the packet interfaces to the FIOF interface """ fifo_intf = FIFOBus(size=16, width=len(emesh_i.bits)) @always_comb def rtl_assign(): wr.next = emesh_i.access and not fifo_intf.full rd.next = not fifo_intf.empty and not emesh_i.wait ...
45,336
def eudora_bong(update, context): #1.2.1 """Show new choice of buttons""" query = update.callback_query bot = context.bot keyboard = [ [InlineKeyboardButton("Yes", callback_data='0'), InlineKeyboardButton("No", callback_data='00')], [InlineKeyboardButton("Back",callback_data='1...
45,337
def on_damage(self, tile, obj): """ダメージをうける。""" self.system.simple_damage_line(material=self) self.hp -= obj.power self.system.add_message('{}の攻撃!\n{}は{}のダメージを受けた!'.format(obj.name, self.name, obj.power)) if self.hp <= 0: self.die(tile, obj)
45,338
def get_wildcard_dir(path): """If given path is a dir, make it a wildcard so the JVM will include all JARs in the directory.""" ret = [] if os.path.isdir(path): ret = [(os.path.join(path, "*"))] elif os.path.exists(path): ret = [path] return ret
45,339
def scan_setup_py(): """Validate the contents of setup.py against Versioneer's expectations.""" found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if ...
45,340
def test_act_marker_multi_line(function: Function) -> None: """ Act marker can be at end of bunch of lines """ result = function.load_act_node() assert isinstance(result, ActNode) assert result.block_type == ActNodeType.marked_act assert get_first_token(result.node).line == ' validate_row...
45,341
def pattern(): """Start a pattern Expected arguments are: name, delay, pause """ if request.args.get('name') is None: return '' pattern = request.args.get('name') delay = float(request.args.get('delay', 0.1)) pause = float(request.args.get('pause', 0.5)) LightsController.start...
45,342
def smow(t): """ Density of Standard Mean Ocean Water (Pure Water) using EOS 1980. Parameters ---------- t : array_like temperature [℃ (ITS-90)] Returns ------- dens(t) : array_like density [kg m :sup:`3`] Examples -------- >>> # Data from UNESCO Tec...
45,343
def get_asgi_handler(fast_api: FastAPI) -> Optional[Mangum]: """Initialize an AWS Lambda ASGI handler""" if os.getenv("AWS_EXECUTION_ENV"): return Mangum(fast_api, enable_lifespan=False) return None
45,344
def generate_change_image_given_dlatent( dlatent: np.ndarray, generator: networks.Generator, classifier: Optional[MobileNetV1], class_index: int, sindex: int, s_style_min: float, s_style_max: float, style_direction_index: int, shift_size: float, label_size: int = 2, num_layer...
45,345
def count_nodes_of_type_on_path_of_type_to_label(source_name, source_label, target_label, node_label_list, relationship_label_list, node_of_interest_position, debug=False): """ This function will take a source node, look for paths along given node and relationship types to a certain target node, and then count the n...
45,346
def _build_square(A, B, C, D): """Build a matrix from submatrices A B C D """ return np.vstack(( np.hstack((A, B)), np.hstack((C, D)) ))
45,347
def main( argv: Sequence[str] = sys.argv[1:], loop: Optional[asyncio.AbstractEventLoop] = None ) -> None: """Parse argument and setup main program loop.""" args = docopt( __doc__, argv=argv, version=pkg_resources.require("easywave")[0].version ) level = logging.ERROR if args["-v"]: ...
45,348
def DataFrame_to_AsciiDataTable(pandas_data_frame,**options): """Converts a pandas.DataFrame to an AsciiDataTable""" # Set up defaults and pass options defaults={} conversion_options={} for key,value in defaults.items(): conversion_options[key]=value for key,value in options.items(): ...
45,349
def rewrite_jaraco(pkg_files, new_root): """ Rewrite imports in jaraco.functools to redirect to vendored copies. """ for file in pkg_files.glob('*.py'): text = file.read_text() text = re.sub(r' (more_itertools)', rf' {new_root}.\1', text) file.write_text(text) # required for ...
45,350
async def update_product(product_id: int, product_update: schemas.ProductPartialUpdate, db: DatabaseManagerBase = Depends(get_db)): """ Patches a product, this endpoint allows to update single or multiple values of a product - **title**: Title of the product - **description**: Description of the produ...
45,351
def TimeDist(times, cutoff, X, e, n1, k): """Translated from Rccp file ConleySE.cpp""" nrow = times.shape[0] assert n1 == nrow assert X.shape[1] == k dmat = np.ones((nrow, nrow)) v1 = np.empty(nrow) v2 = np.empty(nrow) for i in range(nrow): t_diff = times.copy() try: ...
45,352
def catch_signals(signals=None): """catch all possible signals and turn them into exceptions""" terminators = set([ SIGHUP, SIGINT, SIGPIPE, SIGALRM, SIGTERM, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGPROF, SIGUSR1, SIGUSR2, S...
45,353
def AddIPProtocols(parser, support_all_protocol, support_l3_default): """Adds IP protocols flag, with values available in the given version. Args: parser: The parser that parses args from user input. support_all_protocol: Whether to include "ALL" in the protocols list. support_l3_default: Whether to in...
45,354
def generate_fps_from_reaction_products(reaction_smiles, fp_data_configs): """ Generates specified fingerprints for the both reactive and non-reactive substructures of the reactant and product molecules that are the participating in the chemical reaction. """ # Generate the RDKit Mol representations of...
45,355
def count_acc(logits, label): """The function to calculate the . Args: logits: input logits. label: ground truth labels. Return: The output accuracy. """ pred = F.softmax(logits, dim=1).argmax(dim=1) if torch.cuda.is_available(): return (pred == label).type(torch.cuda.F...
45,356
def test_offset_not_none(): """Test reconstruction with valid offset parameter""" seed = cp.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0]) mask = cp.array([0, 8, 6, 8, 8, 8, 8, 4, 4, 0]) expected = cp.array([0, 3, 6, 6, 6, 6, 6, 4, 4, 0]) assert_array_almost_equal( reconstruction(seed, mask, method=...
45,357
def set_case_specific_tracks(display_obj, form): """Set up tracks from files that might be present or not at the case level (rhocall files, tiddit coverage files, upd regions and sites files) Args: display_obj(dict) dictionary containing all tracks info form(dict) flask request form dict...
45,358
def cuda_argmin(a, axis): """ Location of minimum GPUArray elements. Parameters: a (gpu): GPUArray with the elements to find minimum values. axis (int): The dimension to evaluate through. Returns: gpu: Location of minimum values. Examples: >>> a = cuda_argmi...
45,359
def _process_columns(validated_data, context): """Process the used_columns field of a serializer. Verifies if the column is new or not. If not new, it verifies that is compatible with the columns already existing in the workflow :param validated_data: Object with the parsed column items :param con...
45,360
def set_default_tool(tool): """Set the ECAD tool that will be used by default.""" skidl_cfg["default_tool"] = tool
45,361
def embedding_backward_stage1( batch : int, seq_len : int, hidden_size : int, grad_out : DevicePointer, # (batch * n, m) argsort_ids : DevicePointer, # (batch, n) sorted_ids : DevicePointer, # (batch, n) grad : DevicePointer, # (vocab_size...
45,362
def test_sync_firmware_resync(host, fake_local_firmware_file, revert_firmware): """Add some firmware, nuke the firmware dir, and then sync firmware and make sure it shows back up.""" # Add a fake piece of firmware. result = host.run(f"stack add firmware 1.2.3 make=mellanox model=m7800 source={fake_local_firmware_fil...
45,363
def module_of_callable(c): """Find name of module where callable is defined Arguments: c {Callable} -- Callable to inspect Returns: str -- Module name (as for x.__module__ attribute) """ # Ordinal function defined with def or lambda: if type(c).__name__ == 'function': ...
45,364
def lung_seg(input_shape, num_filters=[16,32,128], padding='same') : """Generate CN-Net model to train on CT scan images for lung seg Arbitrary number of input channels and output classes are supported. Arguments: input_shape - (? (number of examples), input image height (pixe...
45,365
def set_cluster_status(event, context): """Set the status of a cluster, ie active, inactive, maintainance_mode, etc""" try: cluster_status = event['queryStringParameters']['cluster_status'] except: return { "statusCode": 500, "body": {"message": f'Must provide a stat...
45,366
def rep(x, n): """ interpolate """ z = numpy.zeros(len(x) * n) for i in range(len(x)): for j in range(n): z[i * n + j] = x[i] return z
45,367
def insert_new_datamodel(database: Database, data_model): """Insert a new datamodel in the datamodels collection.""" if "_id" in data_model: del data_model["_id"] data_model["timestamp"] = iso_timestamp() return database.datamodels.insert_one(data_model)
45,368
async def infer_scatter_add( self, engine, input: lib.AbstractArray, dim: xtype.UInt[64], index: lib.AbstractArray, src: lib.AbstractArray, ): """Infer the return type of primitive `scatter_add`.""" return input
45,369
def parse_cmdline(argv): """ Returns the parsed argument list and return code. `argv` is a list of arguments, or `None` for ``sys.argv[1:]``. """ if argv is None: argv = sys.argv[1:] # initialize the parser object: parser = argparse.ArgumentParser(description='Creates a new version ...
45,370
def eintr_retry(exc_type, f, *args, **kwargs): """Calls a function. If an error of the given exception type with interrupted system call (EINTR) occurs calls the function again. """ while True: try: return f(*args, **kwargs) except exc_type as exc: if exc.errno !...
45,371
def dot2string(dot): """Return a string repr of dots.""" return "*" * int(dot)
45,372
def generate_visited_place( user_email: Optional[str] = None, place_uid: Optional[str] = None, place_id: Optional[int] = None, latitude: Optional[float] = None, longitude: Optional[float] = None, ) -> Dict[str, Any]: """ Создает и возвращает пользовательское посещенное место, автоматичес...
45,373
def parse_path(path, title_from_filename=True): """ Parse a path, returning a dictionary containing all derived information. @param path: Path for which to generate the URL, relative to the root of the site. @type path: str @return: Dictionary containing url, parent, date and inferred title, where...
45,374
def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if ...
45,375
def authenticate_key(api_key): """ Authenticate an API key against our database :param api_key: :return: authenticated username """ user_model = Query() user = db.search(user_model.api_key == api_key)[0] if user: return user["username"] return False
45,376
def verify_ospf3_neighbor_number(device, expected_interface=None, expected_number=None, expected_state=None, extensive=False, max_time=60, ...
45,377
def create_and_clone_vcs_repo(orgname, reponame, tmpdir, testname=None): """ Creates a VCS org Create a repo in that org Clones that repo into a subdirectory of tmpdir Returns the cloned repo directory path """ if testname == None: description = "Created by CMS VCS test library" ...
45,378
def graph(x, y, xerr=None, yerr=None): """Create a ROOT TGraph from array-like input. Parameters ---------- x, y : float or array-like, shape (n, ) The data positions. xerr, yerr : float or array-like, shape (n, ), optional Error bar sizes in the *x* and *y* directions. The default...
45,379
def qUri(x): """Resolve URI for librdf.""" return resolve_uri(x, namespaces=RDF_NAMESPACES)
45,380
async def test_refresh(eddi_fetch_data_fixture): """Test Zappi data""" eddi = Eddi({}, 16042300) await eddi.refresh() assert eddi.serial_number == 10088800 assert eddi.consumed_session == 8.2
45,381
def uninstall(): """Uninstaller for pimessage""" status = 0 try: shutil.rmtree(data_dir, ignore_errors=True) except OSError: print 'Error in removing ~/.pimessage' return 1 # Remove daemon from .profile try: _profile = os.path.join(utils.get_home_dir(), '.profile...
45,382
def extended_trading_splitter(dataframe, begin="9:30", end="15:59"): """Divide data into three segments: premkt, open, aftermkt. Parameters ---------- dataframe: pandas.core.frame.DataFrame """ pass
45,383
def regex(pattern: str) -> Parser: """Regex function. Returns a function that parses the beginning of the received string with the regular expression pattern. Parameters ---------- pattern: str a regular expression string. Example ------- >>> from simpleparser import regex...
45,384
def get_name_scope_name(name): """Returns the input name as a unique `tf.name_scope` name.""" if name and name[-1] == '/': return name name = strip_invalid_chars(name) with tf.name_scope(name) as unique_name: pass return unique_name
45,385
def read_and_filter_wfdb(filename, length=None): """ Reads and filters a signal in Physionet format and returns a numpy array :param filename: the name of the file :param length: the length of the file to return or None for max length :return: the filtered and cut signal as a numpy array """ ...
45,386
def test_format_date(): """Test date formatting. We trust what GitHub gives us, so just test length. input: 2014-05-01T02:26:28Z ouput: 2014-05-01 """ input = '2014-05-01T02:26:28Z' output = format_date(input) assert len(output) == 10 assert 'T' not in output assert output == '2...
45,387
def get_batch_id(create_batch_url, headers, dataset_id, data): """ Get the batchId by making a POST request to "/data/foundation/import/batches" :param create_batch_url: url :param headers: headers :param dataset_id: dataset id :param data: post request data :return: batch id """ da...
45,388
def new_host_log_path(root_log_dir): """ Return the host log path that will be used to make the new local logs dir. Format is like .elasticbeanstalk/logs/local/150318_132014410947/ :param root_log_dir: str: the root local logs directory :return: str """ return os.path.join(root_log_dir, ...
45,389
def true_thresholds_out(true_cde, z_delta, expected_prop): """ calculates thresholds for the cde to get desired HPD value Arguments: ---------- true_cde: numpy array (n, d) array of cde values for a range of y values conditional on a x value (the row value) z_delta : float, space betwee...
45,390
def build_fat_wheel(use_cached=True, output_dir=None): """ Builds wheel files for package and third party requirements (if given) and merges them into one big wheel file (with zip suffix). Returns the path to the created zip file. """ output_dir = output_dir or _get_output_dir(use_cached=use_cac...
45,391
def query_disc(nside, lon, lat, radius, **kwargs): """ Wrapper around healpy.query_disc to deal with old healpy implementation. nside : int The nside of the Healpix map. vec : float, sequence of 3 elements The coordinates of unit vector defining the disk center. radius : float The...
45,392
def ccc(channel=0, cc=0, forbidden=None): """ Generates channel and cc messages starting with the ones provided on construction. :param i: :param channel: :param cc: :return: """ if forbidden is None: forbidden = [] while channel <= 16: yield channel, cc ...
45,393
def prepare_audio_file(uploaded_file): """ A function to prepare the audio file uploaded by the user. Input: uploaded file passed by st.file_uploader Output: float32 numpy """ # use pydub to quickly prepare audio segment a = pydub.AudioSegment.from_file(file=uploaded_file, format=uploa...
45,394
def Train(sess, num_actions, feature_sizes, domain_sizes, embedding_dims): """Builds and trains the network. Args: sess: tensorflow session to use. num_actions: number of possible golden actions. feature_sizes: size of each feature vector. domain_sizes: number of possible feature ids in...
45,395
def get_item(obj,name): """Given a attribute item like 'robots[2].links[4].name', evaluates the value of the item in the object. Note: not secure! Uses eval() """ loc = {'_w':map(obj)} result = {} return eval('_w.'+name,globals(),loc)
45,396
def generate_bars_dict(H, neg_bars=False): """Generate a ground-truth dictionary W suitable for a std. bars test Creates H bases vectors with horizontal and vertival bars on a R*R pixel grid, (wth R = H // 2). The function thus returns a matrix storing H dictionaries of size D=R*R. :param H: Numb...
45,397
def add_node(uuid, state, manage_boot=True, **attributes): """Store information about a node under introspection. All existing information about this node is dropped. Empty values are skipped. :param uuid: Ironic node UUID :param state: The initial state of the node :param manage_boot: whether...
45,398
def read_from_hdf5(hdfFile,label,dof_map=None): """ Just grab the array stored in the node with label label and return it If dof_map is not none, use this to map values in the array If dof_map is not none, this determines shape of the output array """ assert hdfFile is not None, "requires hdf5 f...
45,399