Best Python code snippet using lemoncheesecake
load.py
Source:load.py
...21 continue22 yield os.path.join(path, name)23 def _load_manifest(self, path):24 return ManifestParser(path)25 def load_project(self, build_opts, project_name):26 if "/" in project_name or "\\" in project_name:27 # Assume this is a path already28 return ManifestParser(project_name)29 for manifest in self._list_manifests(build_opts):30 if os.path.basename(manifest) == project_name:31 return ManifestParser(manifest)32 raise ManifestNotFound(project_name)33 def load_all(self, build_opts):34 manifests_by_name = {}35 for manifest in self._list_manifests(build_opts):36 m = self._load_manifest(manifest)37 if m.name in manifests_by_name:38 raise Exception("found duplicate manifest '%s'" % m.name)39 manifests_by_name[m.name] = m40 return manifests_by_name41class ResourceLoader(Loader):42 def __init__(self, namespace, manifests_dir):43 self.namespace = namespace44 self.manifests_dir = manifests_dir45 def _list_manifests(self, _build_opts):46 import pkg_resources47 dirs = [self.manifests_dir]48 while dirs:49 current = dirs.pop(0)50 for name in pkg_resources.resource_listdir(self.namespace, current):51 path = "%s/%s" % (current, name)52 if pkg_resources.resource_isdir(self.namespace, path):53 dirs.append(path)54 else:55 yield "%s/%s" % (current, name)56 def _find_manifest(self, project_name):57 for name in self._list_manifests():58 if name.endswith("/%s" % project_name):59 return name60 raise ManifestNotFound(project_name)61 def _load_manifest(self, path):62 import pkg_resources63 contents = pkg_resources.resource_string(self.namespace, path).decode("utf8")64 return ManifestParser(file_name=path, fp=contents)65 def load_project(self, build_opts, project_name):66 project_name = self._find_manifest(project_name)67 return self._load_resource_manifest(project_name)68LOADER = Loader()69def patch_loader(namespace, manifests_dir="manifests"):70 global LOADER71 LOADER = ResourceLoader(namespace, manifests_dir)72def load_project(build_opts, project_name):73 """ given the name of a project or a path to a manifest file,74 load up the ManifestParser instance for it and return it """75 return LOADER.load_project(build_opts, project_name)76def load_all_manifests(build_opts):77 return LOADER.load_all(build_opts)78class ManifestLoader(object):79 """ ManifestLoader stores information about project manifest relationships for a80 given set of (build options + platform) configuration.81 The ManifestLoader class primarily serves as a location to cache project dependency82 relationships and project hash values for this build configuration.83 """84 def __init__(self, build_opts, ctx_gen=None):85 self._loader = LOADER86 self.build_opts = build_opts87 if ctx_gen is None:88 self.ctx_gen = self.build_opts.get_context_generator()89 else:90 self.ctx_gen = ctx_gen91 self.manifests_by_name = {}92 self._loaded_all = False93 self._project_hashes = {}94 self._fetcher_overrides = {}95 self._build_dir_overrides = {}96 self._install_dir_overrides = {}97 def load_manifest(self, name):98 manifest = self.manifests_by_name.get(name)99 if manifest is None:100 manifest = self._loader.load_project(self.build_opts, name)101 self.manifests_by_name[name] = manifest102 return manifest103 def load_all_manifests(self):104 if not self._loaded_all:105 all_manifests_by_name = self._loader.load_all(self.build_opts)106 if self.manifests_by_name:107 # To help ensure that we only ever have a single manifest object for a108 # given project, and that it can't change once we have loaded it,109 # only update our mapping for projects that weren't already loaded.110 for name, manifest in all_manifests_by_name.items():111 self.manifests_by_name.setdefault(name, manifest)112 else:113 self.manifests_by_name = all_manifests_by_name114 self._loaded_all = True115 return self.manifests_by_name116 def manifests_in_dependency_order(self, manifest=None):117 """ Compute all dependencies of the specified project. Returns a list of the118 dependencies plus the project itself, in topologically sorted order.119 Each entry in the returned list only depends on projects that appear before it120 in the list.121 If the input manifest is None, the dependencies for all currently loaded122 projects will be computed. i.e., if you call load_all_manifests() followed by123 manifests_in_dependency_order() this will return a global dependency ordering of124 all projects. """125 # The list of deps that have been fully processed126 seen = set()127 # The list of deps which have yet to be evaluated. This128 # can potentially contain duplicates.129 if manifest is None:130 deps = list(self.manifests_by_name.values())131 else:132 assert manifest.name in self.manifests_by_name133 deps = [manifest]134 # The list of manifests in dependency order135 dep_order = []136 while len(deps) > 0:137 m = deps.pop(0)138 if m.name in seen:139 continue140 # Consider its deps, if any.141 # We sort them for increased determinism; we'll produce142 # a correct order even if they aren't sorted, but we prefer143 # to produce the same order regardless of how they are listed144 # in the project manifest files.145 ctx = self.ctx_gen.get_context(m.name)146 dep_list = sorted(m.get_section_as_dict("dependencies", ctx).keys())147 builder = m.get("build", "builder", ctx=ctx)148 if builder in ("cmake", "python-wheel"):149 dep_list.append("cmake")150 elif builder == "autoconf" and m.name not in (151 "autoconf",152 "libtool",153 "automake",154 ):155 # they need libtool and its deps (automake, autoconf) so add156 # those as deps (but obviously not if we're building those157 # projects themselves)158 dep_list.append("libtool")159 dep_count = 0160 for dep_name in dep_list:161 # If we're not sure whether it is done, queue it up162 if dep_name not in seen:163 dep = self.manifests_by_name.get(dep_name)164 if dep is None:165 dep = self._loader.load_project(self.build_opts, dep_name)166 self.manifests_by_name[dep.name] = dep167 deps.append(dep)168 dep_count += 1169 if dep_count > 0:170 # If we queued anything, re-queue this item, as it depends171 # those new item(s) and their transitive deps.172 deps.append(m)173 continue174 # Its deps are done, so we can emit it175 seen.add(m.name)176 dep_order.append(m)177 return dep_order178 def set_project_src_dir(self, project_name, path):179 self._fetcher_overrides[project_name] = fetcher.LocalDirFetcher(path)...
core.py
Source:core.py
...19l = logging.getLogger("angrdbg.core")20def get_logger():21 return logging.getLogger("angrdbg")22def get_registers():23 project = load_project()24 regs = {}25 26 for reg in sorted(project.arch.registers,27 key=lambda x: project.arch.registers.get(x)[1]):28 if reg in ("sp", "bp", "ip"):29 continue30 try:31 regs[reg] = debugger.get_reg(reg)32 except BaseException:33 pass34 35 return regs36def StateShot(regs={}, sync_brk=True, check_dbg=False, concrete_imports=[], **kwargs):37 debugger = get_debugger()38 if not check_dbg:39 if not debugger.is_active():40 raise RuntimeError(41 "The debugger must be active and suspended before calling StateShot")42 debugger.refresh_memory()43 project = load_project()44 debugger.before_stateshot()45 mem = SimSymbolicDbgMemory(46 memory_backer=project.loader.memory,47 permissions_backer=None,48 memory_id="mem")49 state = project.factory.blank_state(plugins={"memory": mem}, **kwargs)50 for reg in sorted(project.arch.registers,51 key=lambda x: project.arch.registers.get(x)[1]):52 if reg in ("sp", "bp", "ip", "pc"):53 continue54 try:55 if reg in regs:56 setattr(state.regs, reg, regs[reg])57 else:58 setattr(state.regs, reg, debugger.get_reg(reg))59 #print(reg, getattr(state.regs, reg), debugger.get_reg(reg))60 except BaseException:61 pass62 if project.simos.name == "Linux":63 # inject code to get brk if we are on linux x86/x86_6464 if sync_brk and project.arch.name in ("AMD64", "X86"):65 try:66 state.posix.set_brk(get_linux_brk(project.arch.bits))67 except angr.errors.SimMemoryError:68 l.warning("failed to sychronize brk")69 if get_memory_type() == SIMPROCS_FROM_CLE:70 # insert simprocs when possible or resolve the symbol71 state = build_mixed_got(project, state, concrete_imports)72 elif get_memory_type() == ONLY_GOT_FROM_CLE:73 # load the entire got from cle with stubs74 state = build_cle_got(project, state)75 elif get_memory_type() == GET_ALL_DISCARD_CLE:76 # angr must not execute loader code so all symbols must be resolved77 state = build_bind_now_got(project, state)78 79 elif project.simos.name == "Win32":80 if get_memory_type() == SIMPROCS_FROM_CLE:81 # insert simprocs when possible or resolve the symbol82 state = build_mixed_idata(project, state, concrete_imports)83 elif get_memory_type() == ONLY_GOT_FROM_CLE:84 # load the entire idata from cle with stubs85 state = build_cle_idata(project, state)86 87 debugger.after_stateshot(state)88 89 return state90class StateManager(object):91 def __init__(self, state=None, **kwargs):92 self.state = StateShot(**kwargs) if state is None else state93 self.symbolics = {}94 self.debugger = get_debugger()95 def sim(self, key, size=None):96 '''97 key: memory address(int) or register name(str)98 size: size of object in bytes99 '''100 project = load_project()101 if key in project.arch.registers:102 if size is None:103 size = project.arch.registers[key][1]104 size *= 8105 s = claripy.BVS("angrdbg_reg_" + str(key), size)106 setattr(self.state.regs, key, s)107 self.symbolics[key] = (s, size)108 elif isinstance(key, int) or isinstance(key, long):109 if size is None:110 size = project.arch.bits111 else:112 size *= 8113 s = claripy.BVS("angrdbg_mem_" + hex(key), size)114 self.state.memory.store(key, s)115 self.symbolics[key] = (s, size)116 elif isinstance(key, claripy.ast.bv.BV):117 key = self.state.solver.eval(key, cast_to=int)118 self.sim(key, size)119 else:120 raise ValueError(121 "key must be a register name or a memory address, not %s" % str(122 type(key)))123 return key124 def sim_from_set(self, simset):125 for key in simset.symbolics:126 if key in load_project().arch.registers:127 setattr(self.state.regs, key, simset.symbolics[key][0])128 else:129 self.state.memory.store(key, simset.symbolics[key][0])130 def __getitem__(self, key):131 if key in load_project().arch.registers:132 return getattr(self.state.regs, key)133 elif isinstance(key, int) or isinstance(key, long):134 return self.state.mem[key]135 elif isinstance(key, claripy.ast.bv.BV):136 return self.state.mem[key]137 else:138 raise ValueError("key must be a register name or a memory address")139 def __setitem__(self, key, value):140 if key in load_project().arch.registers:141 setattr(self.state.regs, key, value)142 elif isinstance(key, int) or isinstance(key, long) or isinstance(key, claripy.ast.bv.BV):143 self.state.memory[key] = value144 else:145 raise ValueError("key must be a register name or a memory address")146 def simulation_manager(self):147 return load_project().factory.simulation_manager(self.state)148 def get_symbolic(self, key):149 return self.symbolics.get(key)150 def get_state(self):151 return self.state152 def to_dbg(self, found_state):153 if isinstance(found_state, StateManager):154 return self.to_dbg(found_state.state)155 for key in self.symbolics:156 try:157 if key in load_project().arch.registers:158 r = found_state.solver.eval(159 self.symbolics[key][0], cast_to=int)160 self.debugger.set_reg(key, r)161 else:162 r = found_state.solver.eval(163 self.symbolics[key][0], cast_to=bytes)164 self.debugger.put_bytes(key, r)165 except Exception as ee:166 l.warning(" >> failed to write %s to debugger" % key)167 #print ee168 def concretize(self, found_state):169 if isinstance(found_state, StateManager):170 return self.concretize(found_state.state)171 ret = {}172 for key in self.symbolics:173 try:174 if key in load_project().arch.registers:175 r = found_state.solver.eval(176 self.symbolics[key][0], cast_to=int)177 ret[key] = r178 else:179 r = found_state.solver.eval(180 self.symbolics[key][0], cast_to=bytes)181 ret[key] = r182 except Exception as ee:183 l.warning(" >> failed to concretize %s" % key)184 #print ee185 return ret186 def print_symbolics(self):187 for key in self.symbolics:188 k = key...
growing_ca.py
Source:growing_ca.py
...29 project = Project.create_project(project_name)30 return url_for("get_project", project_name=project_name, tab="settings")31@app.route("/projects/<project_name>/replays/", methods=["POST"])32def record_replay(project_name):33 project = Project.load_project(project_name)34 if project is None:35 return abort(404)36 if "replay" in request.form:37 project.record_replay()38 return "recording replay"39 return "wrong input data"40@app.route("/projects/<project_name>/replay/<replay_name>/", methods=["GET"])41def get_project_replay_data(project_name, replay_name):42 log = logging.getLogger("PROJECT")43 log.debug("project_name = {} replay_name = {}".format(project_name, replay_name))44 project = Project.load_project(project_name)45 if project is None:46 return abort(404)47 json_data = convert_to_json(project.replay(replay_name))48 return json_data49@app.route("/projects/<project_name>/weight/<weight_name>/", methods=["GET"])50def get_project_weight_data(project_name, weight_name):51 project = Project.load_project(project_name)52 if project is None:53 return abort(404)54 json_data = convert_to_json(project.weight(weight_name))55 return json_data56@app.route("/projects/<project_name>/<tab>/", methods=["GET"])57def get_project(project_name, tab):58 project = Project.load_project(project_name)59 if project is None:60 return abort(404)61 if tab == "settings":62 return render_template("project_settings.jinja", project=project)63 elif tab == "replays":64 return render_template("project_replays.jinja", project=project)65 elif tab == "weights":66 return render_template("project_weights.jinja", project=project)67@app.route("/projects/<project_name>/", methods=["PUT"])68@app.route("/projects/<project_name>/settings/", methods=["PUT"])69def update_project_config(project_name):70 log = logging.getLogger("WICA")71 log.debug("trying update project {}".format(project_name))72 project = Project.load_project(project_name)73 if project is None:74 return abort(404)75 for option in request.form.keys():76 log.debug("form[{}] = {}".format(option, request.form[option]))77 project.update_config(request.form)78 project.save()79 return url_for("get_project", project_name=project_name, tab="settings")80@app.route("/projects/<project_name>/settings/", methods=["DELETE"])81def remove_project_field(project_name):82 log = logging.getLogger("WICA")83 log.debug("trying remove {} configuration field".format(project_name))84 project = Project.load_project(project_name)85 if project is None:86 return abort(404)87 if "option" not in request.form.keys():88 log.debug("removing section {}".format(request.form["section"]))89 project.remove_section(request.form["section"])90 else:91 log.debug("removing option {}.{}".format(request.form["section"], request.form["option"]))92 project.remove_option(request.form["section"], request.form["option"])93 project.save()94 return "successfully removed"95@app.route("/projects/<project_name>/", methods=["DELETE"])96def delete_project(project_name):97 log = logging.getLogger("WICA")98 log.debug("deleting project {}".format(project_name))99 project = Project.load_project(project_name)100 if project is None:101 return abort(404)102 project.delete()103 return url_for("get_projects")104@app.route("/projects/", methods=["GET"])105def get_projects():106 projects = Project.load_projects()107 return render_template("projects.jinja", projects=projects)108@app.route("/about/")109def about():110 return render_template("about.jinja")111@app.route("/documentation/")112def documentation():113 return render_template("documentation.jinja")...
WorkspaceTest.py
Source:WorkspaceTest.py
...38 op.network.Cubic(shape=[3, 3, 3], project=proj)39 s = self.ws.__str__().split('\n')40 assert 'OpenPNM Version' in s[1]41 self.ws.clear()42 def test_save_and_load_project(self):43 proj = self.ws.new_project('test_proj')44 net = op.network.Cubic(shape=[3, 3, 3], project=proj)45 op.phases.Air(network=net)46 self.ws.save_project(proj)47 assert proj.name in self.ws.keys()48 self.ws.close_project(proj)49 assert 'test_proj' not in self.ws.keys()50 assert proj.workspace == {}51 proj = self.ws.load_project(filename='test_proj.pnm')52 assert 'test_proj' in self.ws.keys()53 assert isinstance(proj, op.Project)54 assert_allclose(proj.network.shape, [3, 3, 3])55 self.ws.clear()56 try:57 os.remove('test_proj.pnm')58 except PermissionError:59 print('Could not delete test_proj.pnm')60 def test_load_project_with_name_conflict(self):61 self.ws.clear()62 proj = self.ws.new_project(name='test')63 pn = op.network.Cubic(shape=[3, 3, 3], project=proj)64 op.phases.Air(network=pn)65 self.ws.save_project(proj, filename='test.pnm')66 self.ws.load_project('test.pnm')67 assert set(self.ws.keys()) == set(['test', 'proj_01'])68 os.remove('test.pnm')69 # def test_save_and_load_project_from_pickled_list(self):70 # proj = self.ws.new_project()71 # pn = op.network.Cubic(shape=[3, 3, 3], project=proj)72 # air = op.phases.Air(network=pn)73 # pickle.dump([pn, air], open('test.pnm', 'wb'))74 # self.ws.clear()75 # self.ws.load_project('test.pnm')76 # self.ws.clear()77 # os.remove('test.pnm')78 # def test_save_and_load_project_from_pickled_object(self):79 # a = np.ones((10, ))80 # pickle.dump(a, open('single_object.pnm', 'wb'))81 # self.ws.clear()82 # with pytest.raises(Exception):83 # self.ws.load_project('single_object.pnm')84 # b = {'test': a}85 # pickle.dump(b, open('single_object.pnm', 'wb'))86 # self.ws.clear()87 # with pytest.raises(Exception):88 # self.ws.load_project('single_object.pnm')89 # os.remove('single_object.pnm')90 # def test_save_and_load_workspace(self):91 # self.ws.clear()92 # proj1 = self.ws.new_project('test_proj_1')93 # proj2 = self.ws.new_project('test_proj_2')94 # op.network.Cubic(shape=[3, 3, 3], project=proj1, name='net1')95 # op.network.Cubic(shape=[3, 3, 3], project=proj2, name='net2')96 # self.ws.save_workspace(filename='workspace_test')97 # self.ws.clear()98 # assert 'test_proj_1' not in self.ws.keys()99 # assert 'test_proj_2' not in self.ws.keys()100 # self.ws.load_workspace('workspace_test', overwrite=True)101 # assert 'test_proj_1' in self.ws.keys()102 # assert 'test_proj_2' in self.ws.keys()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!