How to use new_tmp_file method in localstack

Best Python code snippet using localstack_python

vpsolver.py

Source:vpsolver.py Github

copy

Full Screen

...34 """35 Wrapper for .vbp files.36 """37 def __init__(self, W, w, b, binary=False, vtype="I", verbose=False):38 self.vbp_file = VPSolver.new_tmp_file(".vbp")39 with open(self.vbp_file, "w") as fdst:40 print(len(W), file=fdst) # ndims41 print(" ".join(map(str, W)), file=fdst) # W42 print(len(w), file=fdst) # m43 for i in range(len(w)): # items44 row = list(w[i])+[b[i]]45 assert len(row) == len(W)+146 print(" ".join(map(str, row)), file=fdst)47 print("BINARY{{{:d}}};".format(binary), file=fdst)48 print("VTYPE{{{}}};".format(vtype), file=fdst)49 if verbose:50 print(utils.get_content(self.vbp_file))51 self.m = len(b)52 self.ndims = len(W)53 self.binary = binary54 self.vtype = vtype55 self.W, self.w, self.b = W, w, b56 self.labels = list(range(self.m))57 @classmethod58 def from_str(cls, content, verbose=False):59 lst = utils.get_instance_data(content)60 ndims = lst.pop(0)61 W = lst[:ndims]62 lst = lst[ndims:]63 m = lst.pop(0)64 w, b = [], []65 for i in range(m):66 w.append(lst[:ndims])67 lst = lst[ndims:]68 b.append(lst.pop(0))69 assert lst == []70 binary = bool(int(utils.get_opt("BINARY", content, False)))71 vtype = utils.get_opt("VTYPE", content, "I")72 return cls(W, w, b, binary, vtype, verbose)73 @classmethod74 def from_file(cls, vbp_file, verbose=False):75 return cls.from_str(utils.get_content(vbp_file), verbose=verbose)76 @property77 def filename(self):78 """Return the filename."""79 return self.vbp_file80 def weights(self):81 """Return the item weights."""82 return {i: tuple(self.w[i]) for i in range(self.m)}83 def capacities(self):84 """Return the bin capacities."""85 return [tuple(self.W)]86 def __del__(self):87 try:88 os.remove(self.vbp_file)89 except:90 pass91class MVP(object):92 """93 Wrapper for .mvp files.94 """95 def __init__(96 self, Ws, Cs, Qs, ws, b, binary=False, vtype="I", verbose=False):97 self.mvp_file = VPSolver.new_tmp_file(".mvp")98 with open(self.mvp_file, "w") as fdst:99 ndims = len(Ws[0])100 print(ndims, file=fdst) # ndims101 print(len(Ws), file=fdst) # nbtypes102 assert len(Ws) == len(Cs)103 assert len(Ws) == len(Qs)104 for Wi, Ci, Qi in zip(Ws, Cs, Qs): # Ws, Cs, Qs105 assert len(Wi) == ndims106 if Qi == utils.inf:107 Qi = -1108 print(" ".join(map(str, list(Wi)+[Ci]+[Qi])), file=fdst)109 assert len(ws) == len(b)110 print(len(ws), file=fdst) # m111 for i in range(len(ws)): # items112 print("{} {}".format(len(ws[i]), b[i]), file=fdst)113 for j, w in enumerate(ws[i]):114 assert len(w) == ndims115 print(" ".join(map(str, w)), file=fdst)116 print("BINARY{{{:d}}};".format(binary), file=fdst)117 print("VTYPE{{{}}};".format(vtype), file=fdst)118 if verbose:119 print(utils.get_content(self.mvp_file))120 self.m = len(b)121 self.ndims = ndims122 self.binary = binary123 self.vtype = vtype124 self.Ws, self.Cs, self.Qs = Ws, Cs, Qs125 self.ws, self.b = ws, b126 self.labels = [127 (i, j)128 for i in range(len(self.ws))129 for j in range(len(self.ws[i]))130 ]131 @classmethod132 def from_str(cls, content, verbose=False):133 lst = utils.get_instance_data(content)134 ndims = lst.pop(0)135 nbtypes = lst.pop(0)136 Ws, Cs, Qs = [], [], []137 for i in range(nbtypes):138 Ws.append(lst[:ndims])139 lst = lst[ndims:]140 Cs.append(lst.pop(0))141 Qs.append(lst.pop(0))142 m = lst.pop(0)143 ws, b = [], []144 for i in range(m):145 ws.append([])146 qi = lst.pop(0)147 bi = lst.pop(0)148 b.append(bi)149 for j in range(qi):150 ws[i].append(lst[:ndims])151 lst = lst[ndims:]152 assert lst == []153 binary = bool(int(utils.get_opt("BINARY", content, False)))154 vtype = utils.get_opt("VTYPE", content, "I")155 return cls(Ws, Cs, Qs, ws, b, binary, vtype, verbose)156 @classmethod157 def from_file(cls, mvp_file, verbose=False):158 return cls.from_str(utils.get_content(mvp_file), verbose=verbose)159 @property160 def filename(self):161 """Return the filename."""162 return self.mvp_file163 def weights(self):164 """Return the item weights."""165 return {166 (i, j): tuple(self.ws[i][j])167 for i in range(len(self.ws))168 for j in range(len(self.ws[i]))169 }170 def capacities(self):171 """Return the bin capacities."""172 return list(map(tuple, self.Ws))173 def __del__(self):174 try:175 os.remove(self.mvp_file)176 except:177 pass178class AFG(object):179 """180 Wrapper for .afg files.181 """182 def __init__(self, instance, verbose=None):183 if instance is not None:184 assert isinstance(instance, (VBP, MVP))185 self.instance = instance186 self.afg_file = VPSolver.new_tmp_file(".afg")187 self.output = VPSolver.vbp2afg(188 instance, self.filename, verbose=verbose189 )190 @classmethod191 def from_file(cls, afg_file, verbose=None):192 obj = cls(None)193 obj.instance = MVP.from_file(afg_file)194 obj.afg_file = VPSolver.new_tmp_file(".afg")195 shutil.copyfile(afg_file, obj.afg_file)196 return obj197 def graph(self):198 """Return the graph as an AFGraph object."""199 content = utils.get_content(self.filename)200 labels = self.instance.labels201 S = int(utils.get_opt("S", content))202 Ts = list(map(int, utils.get_opt("Ts", content).split(",")))203 arcs = list(map(int, utils.get_opt("ARCS", content).split()))204 LOSS = int(utils.get_opt("LOSS", content))205 V, A = set([]), []206 for i in range(0, len(arcs), 3):207 u, v, i = arcs[i:i+3]208 V.add(u)209 V.add(v)210 A.append((u, v, labels[i] if i != LOSS else LOSS))211 graph = AFGraph(V, A, S, Ts, LOSS)212 lbls = {S: "S"}213 if len(Ts) == 1:214 lbls[Ts[0]] = "T"215 else:216 for t, new in zip(Ts, ["T{}".format(i+1) for i in range(len(Ts))]):217 lbls[t] = new218 graph.relabel(lambda u: lbls.get(u, u))219 return graph220 def draw(self, svg_file, lpaths=False, graph_attrs=None, verbose=False):221 """Draw the arc-flow graph in .svg format."""222 if lpaths:223 weights = self.instance.weights()224 capacities = self.instance.capacities()225 else:226 weights = None227 capacities = None228 self.graph().draw(229 svg_file, weights=weights, capacities=capacities, lpaths=lpaths,230 graph_attrs=graph_attrs, verbose=verbose231 )232 @property233 def filename(self):234 """Return the filename."""235 return self.afg_file236 def __del__(self):237 try:238 os.remove(self.afg_file)239 except:240 pass241class MPS(object):242 """243 Wrapper for .mps files.244 """245 def __init__(self, graph, verbose=None):246 assert isinstance(graph, AFG)247 self.afg_graph = graph248 self.mps_file = VPSolver.new_tmp_file(".mps")249 self.output = VPSolver.afg2mps(250 graph.filename, self.filename, verbose=verbose251 )252 @property253 def filename(self):254 """Return the filename."""255 return self.mps_file256 def __del__(self):257 try:258 os.remove(self.mps_file)259 except:260 pass261class LP(object):262 """263 Wrapper for .lp files.264 """265 def __init__(self, graph, verbose=None):266 assert isinstance(graph, AFG)267 self.afg_graph = graph268 self.lp_file = VPSolver.new_tmp_file(".lp")269 self.output = VPSolver.afg2lp(270 graph.filename, self.filename, verbose=verbose271 )272 @property273 def filename(self):274 """Return the filename."""275 return self.lp_file276 def __del__(self):277 try:278 os.remove(self.lp_file)279 except:280 pass281class VPSolver(object):282 """283 Tools to interact with VPSolver binaries and scripts.284 """285 VPSOLVER_EXEC = "vpsolver"286 VBP2AFG_EXEC = "vbp2afg"287 AFG2MPS_EXEC = "afg2mps"288 AFG2LP_EXEC = "afg2lp"289 VBPSOL_EXEC = "vbpsol"290 TMP_DIR = tempfile.mkdtemp()291 TMP_CNT = 0292 PLIST = []293 VERBOSE = True294 @staticmethod295 def set_verbose(verbose):296 """Enable/disable verbose output."""297 if verbose is not None:298 VPSolver.VERBOSE = verbose299 @staticmethod300 def new_tmp_file(ext="tmp"):301 """Create a temporary file."""302 if not ext.startswith("."):303 ext = ".{}".format(ext)304 fname = "{}/{}{}".format(VPSolver.TMP_DIR, VPSolver.TMP_CNT, ext)305 VPSolver.TMP_CNT += 1306 if not os.path.exists(VPSolver.TMP_DIR):307 os.makedirs(VPSolver.TMP_DIR)308 return fname309 @staticmethod310 @atexit.register311 def clear():312 """Delete temporary files and kills child processes."""313 for p in VPSolver.PLIST:314 try:315 os.killpg(p.pid, signal.SIGTERM)316 except:317 pass318 try:319 shutil.rmtree(VPSolver.TMP_DIR)320 except:321 pass322 @staticmethod323 def log(msg, verbose=None):324 """Log a message."""325 if verbose is None:326 verbose = VPSolver.VERBOSE327 if verbose:328 print(msg)329 @staticmethod330 def run(cmd, tee=None, grep=None, grepv=None, verbose=None):331 """Run a system command."""332 if verbose is None:333 verbose = VPSolver.VERBOSE334 proc = subprocess.Popen(335 cmd, shell=True,336 stdout=subprocess.PIPE,337 stderr=subprocess.STDOUT,338 preexec_fn=os.setsid339 )340 VPSolver.PLIST.append(proc)341 def pipe_output(fin, fout_list, grep=None, grepv=None):342 while True:343 line = fin.readline().decode("utf-8")344 if not line:345 break346 if grep is not None and grep not in line:347 continue348 if grepv is not None and grepv in line:349 continue350 for f in fout_list:351 if f is sys.stdout and line.startswith("PYSOL="):352 continue353 f.write(line)354 f.flush()355 if tee is None:356 if verbose:357 pipe_output(proc.stdout, [sys.stdout], grep, grepv)358 else:359 with open(tee, "w") as ftee:360 if verbose:361 pipe_output(proc.stdout, [sys.stdout, ftee], grep, grepv)362 else:363 pipe_output(proc.stdout, [ftee], grep, grepv)364 exit_code = proc.wait()365 proc.stdout.close()366 if exit_code != 0:367 raise RuntimeError("failed to run '{}'".format(cmd))368 @staticmethod369 def parse_vbpsol(vpsol_output):370 """Transform 'vbpsol' solutions into python data."""371 marker = "PYSOL="372 if marker in vpsol_output:373 vpsol_output = vpsol_output[vpsol_output.find(marker)+len(marker):]374 vpsol_output = vpsol_output[:vpsol_output.find("\n")]375 obj, sol = eval(vpsol_output)376 return obj, sol377 else:378 return None379 @staticmethod380 def vbpsol(afg_file, sol_file, print_inst=False, pyout=True, verbose=None):381 """Call 'vbpsol' to extract a vector packing solution."""382 if isinstance(afg_file, AFG):383 afg_file = afg_file.filename384 out_file = VPSolver.new_tmp_file()385 opts = "{print_inst:d} {pyout:d}".format(386 print_inst=print_inst, pyout=pyout387 )388 VPSolver.run(389 "{} {} {} {}".format(390 VPSolver.VBPSOL_EXEC, afg_file, sol_file, opts391 ),392 tee=out_file,393 verbose=verbose394 )395 output = utils.get_content(out_file)396 os.remove(out_file)397 return VPSolver.parse_vbpsol(output)398 @staticmethod399 def vpsolver(instance_file, print_inst=False, pyout=True, verbose=None):400 """Call 'vpsolver' to solve .vbp instances."""401 if isinstance(instance_file, (VBP, MVP)):402 instance_file = instance_file.filename403 content = utils.get_content(instance_file)404 method = int(utils.get_opt("METHOD", content, -3))405 binary = int(utils.get_opt("BINARY", content, 0))406 vtype = utils.get_opt("VTYPE", content, "I")407 out_file = VPSolver.new_tmp_file()408 opts = "{method:d} {binary:d} {vtype} {print_inst:d} {pyout:d}".format(409 method=method, binary=binary, vtype=vtype,410 print_inst=print_inst, pyout=pyout411 )412 VPSolver.run(413 "{} {} {}".format(VPSolver.VPSOLVER_EXEC, instance_file, opts),414 tee=out_file,415 verbose=verbose416 )417 output = utils.get_content(out_file)418 os.remove(out_file)419 return output, VPSolver.parse_vbpsol(output)420 @staticmethod421 def vbp2afg(instance_file, afg_file, opts="", verbose=None):422 """Call 'vbp2afg' to create an arc-flow graph for a .vbp instance."""423 if isinstance(instance_file, (VBP, MVP)):424 instance_file = instance_file.filename425 out_file = VPSolver.new_tmp_file()426 VPSolver.run(427 "{} {} {} {}".format(428 VPSolver.VBP2AFG_EXEC, instance_file, afg_file, opts429 ),430 tee=out_file,431 verbose=verbose432 )433 output = utils.get_content(out_file)434 os.remove(out_file)435 return output436 @staticmethod437 def afg2mps(afg_file, mps_file, opts="", verbose=None):438 """Call 'afg2mps' to create a .mps model for an arc-flow graph."""439 if isinstance(afg_file, AFG):440 afg_file = afg_file.filename441 out_file = VPSolver.new_tmp_file()442 VPSolver.run(443 "{} {} {} {}".format(444 VPSolver.AFG2MPS_EXEC, afg_file, mps_file, opts445 ),446 tee=out_file,447 verbose=verbose448 )449 output = utils.get_content(out_file)450 os.remove(out_file)451 return output452 @staticmethod453 def afg2lp(afg_file, lp_file, opts="", verbose=None):454 """Call 'afg2lp' to create a .lp model for an arc-flow graph."""455 if isinstance(afg_file, AFG):456 afg_file = afg_file.filename457 out_file = VPSolver.new_tmp_file()458 VPSolver.run(459 "{} {} {} {}".format(460 VPSolver.AFG2LP_EXEC, afg_file, lp_file, opts461 ),462 tee=out_file,463 verbose=verbose464 )465 output = utils.get_content(out_file)466 os.remove(out_file)467 return output468 @staticmethod469 def afg2svg(afg_file, svg_file, verbose=None):470 """Draw a .afg arc-flow graph in .svg format."""471 if isinstance(afg_file, AFG):472 afg_file = afg_file.filename473 AFG.from_file(afg_file).draw(svg_file)474 @staticmethod475 def script(script_name, arg1=None, arg2=None, options=None, pyout=True,476 verbose=None):477 """Call a VPSolver script and return a vector packing solution."""478 cmd = script_name479 for arg in [arg1, arg2]:480 if isinstance(arg, MPS):481 cmd += " --mps {}".format(arg.filename)482 elif isinstance(arg, LP):483 cmd += " --lp {}".format(arg.filename)484 elif isinstance(arg, AFG):485 cmd += " --afg {}".format(arg.filename)486 elif isinstance(arg, VBP):487 cmd += " --vbp {}".format(arg.filename)488 elif isinstance(arg, MVP):489 cmd += " --mvp {}".format(arg.filename)490 elif isinstance(arg, six.string_types):491 if arg.endswith(".mps"):492 cmd += " --mps {}".format(arg)493 elif arg.endswith(".lp"):494 cmd += " --lp {}".format(arg)495 elif arg.endswith(".afg"):496 cmd += " --afg {}".format(arg)497 elif arg.endswith(".vbp"):498 cmd += " --vbp {}".format(arg)499 elif arg.endswith(".mvp"):500 cmd += " --mvp {}".format(arg)501 else:502 raise Exception("Invalid file extension!")503 if options is not None:504 cmd += " --options \"{}\"".format(options)505 if pyout is True:506 cmd += " --pyout"507 out_file = VPSolver.new_tmp_file()508 VPSolver.run(cmd, tee=out_file, verbose=verbose)509 output = utils.get_content(out_file)510 os.remove(out_file)511 return output, VPSolver.parse_vbpsol(output)512 @staticmethod513 def script_wsol(script_name, model, options=None, verbose=None):514 """Call a solver script and return the solution."""515 from pympl import Tools516 if verbose is None:517 verbose = VPSolver.VERBOSE518 if isinstance(model, (LP, MPS)):519 model = model.filename520 return Tools.script(521 script_name=script_name, model=model, options=options,...

Full Screen

Full Screen

test_vpsolver.py

Source:test_vpsolver.py Github

copy

Full Screen

...21 """Test vbpsolver."""22 from pyvpsolver import VPSolver23 from pyvpsolver.solvers import vbpsolver24 W, w, b = (1,), [(1,)], [1]25 lp_file = VPSolver.new_tmp_file(".lp")26 mps_file = VPSolver.new_tmp_file(".mps")27 svg_file = VPSolver.new_tmp_file(".svg")28 solution = vbpsolver.solve(W, w, b, script="vpsolver_glpk.sh")29 vbpsolver.print_solution(solution)30 obj, patterns = solution31 assert obj == 132 solution = vbpsolver.solve(33 W, w, b, lp_file=lp_file, mps_file=mps_file, svg_file=svg_file,34 script="vpsolver_glpk.sh"35 )36 vbpsolver.print_solution(solution)37 obj, patterns = solution38 assert obj == 139 vbpsolver.print_solution(obj, patterns)40def test_mvpsolvers():41 """Test mvpsolvers."""42 from pyvpsolver import VPSolver43 from pyvpsolver.solvers import mvpsolver2013, mvpsolver201644 Ws = [(100, 75), (75, 50), (75, 50), (100, 100)]45 Cs = [3, 2, 3, 100]46 Qs = [inf, -1, -1, -1]47 ws = [[(75, 50)], [(40, 75), (25, 25)]]48 b = [2, 1]49 for mvpsolver in [mvpsolver2013, mvpsolver2016]:50 solution = mvpsolver.solve(51 Ws, Cs, Qs, ws, b, script="vpsolver_glpk.sh"52 )53 mvpsolver.print_solution(solution)54 obj, patterns = solution55 assert obj == 556 lp_file = VPSolver.new_tmp_file(".lp")57 mps_file = VPSolver.new_tmp_file(".mps")58 svg_file = VPSolver.new_tmp_file(".svg")59 solution = mvpsolver.solve(60 Ws, Cs, Qs, ws, b, lp_file=lp_file, mps_file=mps_file,61 svg_file=svg_file, script="vpsolver_glpk.sh", verbose=True62 )63 mvpsolver.print_solution(solution)64 obj, patterns = solution65 assert obj == 566 mvpsolver.print_solution(obj, patterns)67def test_scripts():68 """Test scripts."""69 from pyvpsolver import VPSolver, VBP, MVP, AFG, LP, MPS70 VPSolver.clear()71 vbp = VBP(W=(1,), w=[(1,)], b=[1], verbose=True)72 mvp = MVP(Ws=[(1,)], Cs=[1], Qs=[inf], ws=[[(1,)]], b=[1], verbose=True)73 for instance in [vbp, mvp]:74 afg = AFG(instance, verbose=True)75 lp = LP(afg, verbose=True)76 mps = MPS(afg, verbose=True)77 VPSolver.set_verbose(False)78 output, solution = VPSolver.script(79 "vpsolver_glpk.sh", instance, options="--seed 1234"80 )81 assert solution[0] == 182 if isinstance(instance, (VBP, MVP)):83 instance_file = instance.filename84 output, solution = VPSolver.script("vpsolver_glpk.sh", instance_file)85 assert solution[0] == 186 output, solution = VPSolver.script("vpsolver_glpk.sh", afg)87 assert solution[0] == 188 output, solution = VPSolver.script("vpsolver_glpk.sh", afg, lp)89 assert solution[0] == 190 output, solution = VPSolver.script("vpsolver_glpk.sh", afg, mps)91 assert solution[0] == 192 output, solution = VPSolver.script("vpsolver_glpk.sh", lp)93 assert solution is None94 output, solution = VPSolver.script("vpsolver_glpk.sh", mps)95 assert solution is None96 output, solution = VPSolver.script("vpsolver_glpk.sh", afg.filename)97 assert solution[0] == 198 output, solution = VPSolver.script("vpsolver_glpk.sh", lp.filename)99 assert solution is None100 output, solution = VPSolver.script("vpsolver_glpk.sh", mps.filename)101 assert solution is None102def test_vbpsol():103 """Test vbpsol."""104 from pyvpsolver import VPSolver, VBP, MVP, AFG, LP, MPS105 vbp = VBP(W=(1,), w=[(1,)], b=[1], verbose=True)106 afg = AFG(vbp, verbose=True)107 lp = LP(afg, verbose=True)108 sol_file = VPSolver.new_tmp_file(".sol")109 output, solution = VPSolver.script_wsol("vpsolver_glpk.sh", lp)110 assert isinstance(solution, dict)111 with open(sol_file, "w") as f:112 lst = []113 for var, value in solution.items():114 lst.append(str(var))115 lst.append(str(value))116 print(" ".join(lst), file=f)117 obj, patterns = VPSolver.vbpsol(afg, sol_file)118 assert obj == 1119def test_draw():120 """Test scripts."""121 from pyvpsolver import VPSolver, VBP, MVP, AFG122 vbp = VBP(W=(1,), w=[(1,)], b=[1])123 mvp = MVP(Ws=[(1,)], Cs=[1], Qs=[inf], ws=[[(1,)]], b=[1])124 svg_file = VPSolver.new_tmp_file(".svg")125 for instance in [vbp, mvp]:126 afg = AFG(instance)127 try:128 afg.draw(129 svg_file, lpaths=True, graph_attrs={"size": "8,8"}130 )131 except Exception as e:132 print(repr(e))133 try:134 VPSolver.afg2svg(afg, svg_file)135 except Exception as e:136 print(repr(e))137 try:138 VPSolver.afg2svg(afg.filename, svg_file)139 except Exception as e:140 print(repr(e))141def test_lowlevel():142 """Test low-level API."""143 from pyvpsolver import VPSolver, VBP, MVP, AFG144 vbp = VBP(W=(1,), w=[(1,)], b=[1])145 mvp = MVP(Ws=[(1,)], Cs=[1], Qs=[inf], ws=[[(1,)]], b=[1])146 afg_file = VPSolver.new_tmp_file(".afg")147 lp_file = VPSolver.new_tmp_file(".lp")148 mps_file = VPSolver.new_tmp_file(".mps")149 svg_file = VPSolver.new_tmp_file(".svg")150 VPSolver.vbp2afg(vbp, afg_file)151 VPSolver.vbp2afg(mvp, afg_file)152 VPSolver.vbp2afg(vbp.filename, afg_file)153 VPSolver.vbp2afg(mvp.filename, afg_file)154 VPSolver.afg2lp(afg_file, lp_file)155 VPSolver.afg2mps(afg_file, mps_file)156 VPSolver.afg2lp(AFG(vbp), lp_file)157 VPSolver.afg2mps(AFG(mvp), mps_file)158if __name__ == "__main__":159 test_vbpsolver()160 test_mvpsolvers()161 test_scripts()162 test_vbpsol()163 test_draw()...

Full Screen

Full Screen

tools.py

Source:tools.py Github

copy

Full Screen

...35 """Enable/disable verbose output."""36 if verbose is not None:37 Tools.VERBOSE = verbose38 @staticmethod39 def new_tmp_file(ext="tmp"):40 """Create temporary files."""41 if not ext.startswith("."):42 ext = ".{0}".format(ext)43 fname = "{0}/{1}{2}".format(Tools.TMP_DIR, Tools.TMP_CNT, ext)44 Tools.TMP_CNT += 145 if not os.path.exists(Tools.TMP_DIR):46 os.makedirs(Tools.TMP_DIR)47 return fname48 @staticmethod49 @atexit.register50 def clear():51 """Delete temporary files and kill child processes."""52 for p in Tools.PLIST:53 try:54 os.killpg(p.pid, signal.SIGTERM)55 except:56 pass57 try:58 shutil.rmtree(Tools.TMP_DIR)59 except:60 pass61 @staticmethod62 def log(msg, verbose=None):63 """Log function."""64 if verbose is None:65 verbose = Tools.VERBOSE66 if verbose:67 print(msg)68 @staticmethod69 def run(cmd, tee=None, grep=None, grepv=None, verbose=None):70 """Run a system command."""71 if verbose is None:72 verbose = Tools.VERBOSE73 proc = subprocess.Popen(74 cmd, shell=True,75 stdout=subprocess.PIPE,76 stderr=subprocess.STDOUT,77 preexec_fn=os.setsid78 )79 Tools.PLIST.append(proc)80 def pipe_output(fin, fout_list, grep=None, grepv=None):81 while True:82 line = fin.readline().decode("utf-8")83 if not line:84 break85 if grep is not None and grep not in line:86 continue87 if grepv is not None and grepv in line:88 continue89 for f in fout_list:90 f.write(line)91 f.flush()92 if tee is None:93 if verbose:94 pipe_output(proc.stdout, [sys.stdout], grep, grepv)95 else:96 with open(tee, "w") as ftee:97 if verbose:98 pipe_output(proc.stdout, [sys.stdout, ftee], grep, grepv)99 else:100 pipe_output(proc.stdout, [ftee], grep, grepv)101 exit_code = proc.wait()102 proc.stdout.close()103 if exit_code != 0:104 raise RuntimeError("failed to run '{0}'".format(cmd))105 @staticmethod106 def script(script_name, model, options=None, verbose=None):107 """Call a solver script and returns the solutions."""108 cmd = script_name109 if model.endswith(".mps"):110 cmd += " --mps {0}".format(model)111 elif model.endswith(".lp"):112 cmd += " --lp {0}".format(model)113 else:114 raise Exception("Invalid file extension!")115 if options is not None:116 cmd += " --options \"{0}\"".format(options)117 out_file = Tools.new_tmp_file()118 sol_file = Tools.new_tmp_file(".sol")119 Tools.run(120 "{0} --wsol {1}".format(cmd, sol_file),121 tee=out_file,122 verbose=verbose123 )124 with open(out_file) as f:125 output = f.read()126 os.remove(out_file)127 try:128 with open(sol_file) as f:129 sol = f.read().split()130 values = {}131 assert len(sol) % 2 == 0132 for i in range(0, len(sol), 2):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful