def test_2_curves_v2(): p = Plotter(-1, 1, width=50, symbols='sc') from math import sin, cos, pi from numpy import linspace tp = linspace(0, 6 * pi, 6 * 8 + 1) s = '' for t in tp: s += '%s\n' % (p.plot(t, sin(t), cos(t))) ans = dd("""\ | c | s c | c | c s | s c | s c | s c | s c | c s | c | s c | s | s | c s | c s | c | c | s c | c | c s | s c | s c | s c | s c | c s | c | s c | s | s | c s | c s | c | c | s c | c | c s | s c | s c | s c | s c | c s | c | s c | s | s | c s | c s | c | c """) assert ans == s
def __str__(self): ctx = dict( var=self.var, iter=self.iter, body=iblock(4, str(self.body)), ) return dd(self.__doc__).format(**ctx)
def compile_data(self, comments: bool, errors: bool) -> str: """Return a formatted string of data points. Args: comments: Flag to control the output of comments. errors: Flag to control the output of errors. """ # Compile cook data and stage info header. output = '\n'.join(( ('\n' + f"File: {self.NAME}".center(79)), (self._wrapper("[Cook Info]")), (dd(f""" Product: {self.PRODUCT} Lot: {self.LOT} Oven: {self.OVEN} Program {self.PROGRAM} Start: {self.START_TIME} Starting Temps: {self.START_TEMPS} End: {self.END_TIME} Ending Temps: {self.END_TEMPS} Duration: {self.DURATION} minutes [{self._to_hours(self.DURATION)}] In-weight: {self._check_val(self.IN_WEIGHT)} Out-weight: {self._check_val(self.OUT_WEIGHT)} Yield: {self._check_val(self.COOK_YIELD)} \ """)), (self._wrapper("[Stage Info]", '=')), ('') # Add a blank space between 'Stage Info' header and data )) # Compile stage data. for stage, duration in self.STAGES.items(): output += f"\n{stage}: {int(duration)} minutes" # TODO Implement comments and error output return output + '\n'
def __str__(self): ctx = dict( var = self.var, iter = self.iter, body = iblock(4, str(self.body)), ) return dd(self.__doc__).format(**ctx)
def fmt_msgs(msgs): """ Handles lines and indentation! cli.echo( ''' line indented ''', 'inline', ' inline indented', ''' different indent ''' ) Output: line indented inline inline indented different indent """ return str.strip(dd("\n".join(map(fmt, msgs))))
def calc(expresión=0, precisión=1000): ''' Calculadora de expresiones con números complejos. expresión: expresión númerica válida. precisión: precisión de la simplificación. Uso: >>> from calc_comp import calc >>> from numpy import conjugate as c >>> z1 = 3-2j >>> z2 = -5-6j >>> z3 = -4+2j >>> exp = ((z1 - c(z2)) / z2) * ((2*z1) / z3) >>> calc(exp) (-0.49836065573770494-2.281967213114754j) = -152 -696 ------------- + ------------- i 305 305 ''' z = expresión frac_real = F.from_float(z.real).limit_denominator(precisión) frac_imag = F.from_float(z.imag).limit_denominator(precisión) print(dd('''\ {0} = {1} {2} ------------- + ------------- i {3} {4}'''.format(expresión, frac_real.numerator, frac_imag.numerator, frac_real.denominator, frac_imag.denominator)))
def main(): """ The main function that accepts and sanitize the input options from the user and then calls the check function """ banner = dd("""\ =============================== Log Miner (version 1.1) ===============================""") print(banner) parser = optparse.OptionParser("%prog -s <search string> -i <input-file>" " -o <output file> -v <1 verbose, 0 silent>") parser.add_option('-i', dest='inputFile', type='string', help='specify File to open (/var/log/syslog)') parser.add_option('-s', dest='stringx', type='string', help='specify string to search') parser.add_option('-o', dest='outputFile', type='string', help='specify output file (optional)') parser.add_option('-v', dest='verbosity', type='int', help='1 for verbose, 0 for silent (optional)') options, args = parser.parse_args() inputFile = options.inputFile stringx = options.stringx outputFile = options.outputFile screen = options.verbosity if not inputFile: inputFile = "/var/log/syslog" # doesn't work with systemd print("[+] Loading.. %s" % inputFile) if not outputFile: outputFile = "data/dump.log" if not stringx: print("[-] Nothing to do! Use -h or --help for help") exit(0) try: # ensures files are closed allways! even if exceptions are raised with open(inputFile) as inFile: # 'r' is default with open(outputFile, 'a') as outFile: if screen: miner(stringx, inFile, outFile, screen=screen) else: miner(stringx, inFile, outFile) except IOError as e: # print to standard error stream print('[!] ERROR: {0}'.format(e), file=sys.stderr)
def __str__(self): ctx = dict( name=self.name, args=', '.join(str(arg) for arg in self.args), ret=self.ret, body=iblock(4, str(self.body)), ) return dd(self.__doc__).format(**ctx)
def __str__(self): ctx = dict( name = self.name, args = ', '.join(str(arg) for arg in self.args), ret = self.ret, body = iblock(4, str(self.body)), ) return dd(self.__doc__).format(**ctx)
def _wrapper(self, header: str, border: str = '=') -> str: """Return a centered header, wrapped with a border. Args: header: The header to wrap. border: The border symbol to wrap the header with. """ wrap = border * 79 return dd(f""" {wrap} {header.center(79)} {wrap}""")
def banner(): print(dd( r""" _____ ________ ___________.___ _________ / _ \ \______ \ \_ _____/| |/ _____/ / /_\ \ | | \ | __) | |\_____ \ / | \| ` \| \ | |/ \ \____|__ /_______ /\___ / |___/_______ / \/ \/ \/ \/ May the "Donut Fairy" NOT be with you! """ ))
def main(): # prompt = chr(10144) # cmd.exe es tan patetico... while True: clear() cadena_in = input(dd('''\ Escriba una expresion para numeros flotantes, su validez sera evaluada: (S/SALIR, para finalizar) => '''.format_map(vars()))) if cadena_in.lower() in ['s', 'salir']: sys.exit() else: prueba = primera_validacion(cadena_in) if prueba: segunda_validacion(prueba) input('\nPresione ENTER para continuar.')
def main(entero='1337', dec='007'): n = Numero(entero, dec) nd = n.a_float() n2 = n.a_base(2) n8 = n.a_base(8) n10 = n.a_base(10) n16 = n.a_base(16) print(dd(''' Number:\t\t{0} Float:\t\t{1} Binario:\t{2} Octal:\t\t{3} Decimal:\t{4} Hexadecimal:\t{5}'''.format(n, nd, n2, n8, n10, n16)))
def primera_validacion(cadena): if cadena.lower() in ['inf', 'infinity', 'nan']: return cadena coincidencia = patron.search(cadena) if coincidencia: _coincidencia = coincidencia.groups() print(dd(''' coincidencia: {_coincidencia} signo : {_coincidencia[0]} entero : {_coincidencia[1]} punto : {_coincidencia[2]} decimal : {_coincidencia[3]} marca_exp : {_coincidencia[4]} signo_exp : {_coincidencia[5]} exponente : {_coincidencia[6]} '''.format_map(vars()))) return coincidencia.group() else: print(eval(error))
def _demo(): from numpy import linspace, exp, sin, pi x = linspace(-2, 2, 31) y = exp(-0.5 * x ** 2) * sin(2 * pi * x) data = dd(""" from numpy import linspace, exp, sin, pi x = linspace(-2, 2, 31) y = exp(-0.5*x**2)*sin(2*pi*x) """) cmd = ["plot(x, y)", "plot(x, y, draw_axes=False)", "plot(x, y, plot_slope=False)", "plot(x, y, plot_labels=False)", "plot(x, y, dot='o', plot_slope=False)", "p = plot(x, y, output=str)", "print(p)" ] print(data) for c in cmd: print('\n\n', c) exec(c)
def run_yosys(self) -> bool: run_script = os.path.join(self.run_dir, "run.sh") makefile = self.openroad_flow_makefile_path() design_config = self.design_config_path() synth_script = self.synth_script_path() self.validate_openroad_installation() self.setup_openroad_rundir() self.create_design_config() with open(run_script, "w") as f: f.write( dd("""\ #!/bin/bash cd "{rundir}" mkdir -p results/{tech}/{name} make DESIGN_CONFIG={conf} SYNTH_SCRIPT={script} -f {make} synth\ """.format(rundir=self.run_dir, tech=self.get_setting("vlsi.core.technology"), name=self.top_module, conf=design_config, script=synth_script, make=makefile))) os.chmod(run_script, 0o755) if bool(self.get_setting("synthesis.yosys.generate_only")): self.logger.info("Generate-only mode: command-line is " + \ " ".join(args)) else: # Temporarily disable colors/tag to make run output more readable # TODO: think of a more elegant way to do this? HammerVLSILogging.enable_colour = False HammerVLSILogging.enable_tag = False self.run_executable([run_script]) # TODO: check for errors HammerVLSILogging.enable_colour = True HammerVLSILogging.enable_tag = True return True
def run_openroad(self) -> bool: run_script = os.path.join(self.run_dir, "par.sh") self.validate_openroad_installation() self.setup_openroad_rundir() with open(run_script, "w") as f: f.write( dd("""\ #!/bin/bash cd "{rundir}" mkdir -p logs/{tech}/{name} mkdir -p objects/{tech}/{name} mkdir -p reports/{tech}/{name} mkdir -p results/{tech}/{name} """.format( rundir=self.run_dir, tech=self.get_setting("vlsi.core.technology"), name=self.top_module, ))) f.write("\n".join(self.cmds)) os.chmod(run_script, 0o755) if bool(self.get_setting("par.openroad.generate_only")): self.logger.info("Generate-only mode: command-line is " + \ " ".join(args)) else: # Temporarily disable colors/tag to make run output more readable # TODO: think of a more elegant way to do this? HammerVLSILogging.enable_colour = False HammerVLSILogging.enable_tag = False self.run_executable([run_script]) # TODO: check for errors HammerVLSILogging.enable_colour = True HammerVLSILogging.enable_tag = True return True
from functools import reduce from textwrap import dedent as dd from timeit import repeat sources = ["canada", "citm_catalog", "citylots", "twitter"] min_times = [] for source in sources: s = dd(f"""\ with open("../data/{source}.json") as f: json.load(f)""") times = repeat(stmt=s, setup="import json", repeat=3, number=1) t = reduce(min, times) print(f"{source} {t:0.06f} seconds") min_times.append(t) geo_mean = reduce(lambda a, b: a * b, min_times)**(1 / len(min_times)) print(f"Total (G.M): {geo_mean:0.06f}")
def __str__(self): return dd(self.__doc__) % (self.name, self.ty)
'Touch'), ('Height', 'Weight'), ('Physique',) ) # TODO: Figure out how to determine chosen race and give stat info # http://cloud-3.steamusercontent.com/ugc/320124788920141475/83A5568F35B91FC2BD926876D7757487797911CF/ extra_info = { 'Intelligence': dd( ''' Intelligence primarily affects how quickly you train skills. The following skills are governed by this stat: Agriculture, Building, Herblore, Physician, Ritual, Trapping, Weatherlore ''' ), 'Will': dd( ''' Will affects your ability to stay awake when exhausted and your abiliity to force yourself to eat raw meat and fish (and then throwing up). The following skills are governed by this stat: Agriculture, Fishing,
def main(): """ The main function that accepts and sanitize the input options from the user and then calls the check function """ banner = dd("""\ =============================== Log Miner (version 1.1) ===============================""") print(banner) parser = optparse.OptionParser( "%prog -s <search string> -i <input-file>" " -o <output file> -v <1 verbose, 0 silent>") parser.add_option('-i', dest='inputFile', type='string', help='specify File to open (/var/log/syslog)') parser.add_option('-s', dest='stringx', type='string', help='specify string to search') parser.add_option('-o', dest='outputFile', type='string', help='specify output file (optional)') parser.add_option('-v', dest='verbosity', type='int', help='1 for verbose, 0 for silent (optional)') options, args = parser.parse_args() inputFile = options.inputFile stringx = options.stringx outputFile = options.outputFile screen = options.verbosity if not inputFile: inputFile = "/var/log/syslog" # doesn't work with systemd print("[+] Loading.. %s" % inputFile) if not outputFile: outputFile = "data/dump.log" if not stringx: print("[-] Nothing to do! Use -h or --help for help") exit(0) try: # ensures files are closed allways! even if exceptions are raised with open(inputFile) as inFile: # 'r' is default with open(outputFile, 'a') as outFile: if screen: miner(stringx, inFile, outFile, screen=screen) else: miner(stringx, inFile, outFile) except IOError as e: # print to standard error stream print('[!] ERROR: {0}'.format(e), file=sys.stderr)
def __str__(self): if self.val == None: return "var %s %s" % (self.ty, self.name) else: return dd(self.__doc__) % (self.ty, self.name, self.val)
def __str__(self): return dd(self.__doc__) % self.val
port = int(app.config.get('PORT') or options.get('port')) app.run(host=host, port=port, debug=debug) return app if __name__ == '__main__': import sys from textwrap import dedent as dd # Catch if local system doesn't have docopt installed try: from docopt import docopt except ImportError as e: err_msg = dd(''' ERROR: Docopt is not installed. Please install to proceed. > pip install docopt ''') print(err_msg, file=sys.stderr) sys.exit() options = {k.lstrip('--'): v for k, v in docopt(__doc__).items()} config_mapping = { 'dev': DevConfig, 'demo': DemoConfig, 'local': LocalDemoConfig } options['config'] = config_mapping.get(options['config'], DemoConfig) options['_run_'] = True main(**options)
def __str__(self): return dd(self.__doc__) % (self.target, self.value)
def test_2_curves_v1(): p_sin = Plotter(-1, 1, width=25, symbols='s') p_cos = Plotter(-1, 1, width=25, symbols='c') from math import sin, cos, pi from numpy import linspace tp = linspace(0, 6 * pi, 6 * 8 + 1) s = '' for t in tp: s += '%s %s\n' % (p_sin.plot(t, sin(t)), p_cos.plot(t, cos(t))) ans = dd("""\ | | c | s | c | s | c | s | c | s | | s c | | s c | | s c | |s c | s | c | s | c | s | c | s | | s | | c s | | c s | | c | | c | s | c | s | c | s | c | s |c | s c | | s c | | s c | |s c | s | c | s | c | s | c | s | | s | | c s | | c s | | c | | c | s | c | s | c | s | c | s |c | s c | | s c | | s c | |s c | s | c | s | c | s | c | s | | s | | c s | | c s | | c | | c """) assert ans == s
def __str__(self): return dd(self.__doc__) % (self.inf, self.sup)
""" import optparse from textwrap import dedent as dd import logging import subprocess logging.basicConfig(level=logging.DEBUG) op = optparse.OptionParser() op.add_option('-i', dest='infile', help='Input GFF file.') op.add_option('-o', dest='outfile', help='Output GFF file, suitable for use with TopHat') op.add_option('--index', dest='index', help=dd(''' index name for Bowtie index. bowtie-inspect and the index must be on your path.''')) op.add_option('--no-auto-chr',dest='noautochr', default=False, action='store_true', help="""Disable automatic prepending of "chr" to output file chromosome names if not already present.""") options,args = op.parse_args() p = subprocess.Popen('bowtie-inspect --names %s' % options.index, shell=True, stdout=subprocess.PIPE) chroms = p.communicate()[0] chroms = chroms.split('\n') chroms = [i for i in chroms if len(i) > 0] logging.debug('chromosomes found in bowtie index %s were \n\t%s' \ % (options.index, '\n\t'.join(chroms)))
def test_sin(): a = 0.2 p = Plotter(-1 - a, 1 + a, width=50) from math import sin, pi from numpy import linspace num_periods = 2 resolution_per_period = 22 s = '' tp = linspace(0, num_periods * 2 * pi, num_periods * resolution_per_period + 1) for t in tp: y = (1 + a * sin(0.5 * t)) * sin(t) s += 't=%5.2f %s %5.2f\n' % (t, p.plot(t, y), y) ans = dd("""\ t= 0.00 | 0.00 t= 0.29 | * 0.29 t= 0.57 | * 0.57 t= 0.86 | * 0.82 t= 1.14 | * 1.01 t= 1.43 | * 1.12 t= 1.71 | * 1.14 t= 2.00 | * 1.06 t= 2.28 | * 0.89 t= 2.57 | * 0.64 t= 2.86 | * 0.34 t= 3.14 | 0.00 t= 3.43 * | -0.34 t= 3.71 * | -0.64 t= 4.00 * | -0.89 t= 4.28 * | -1.06 t= 4.57 * | -1.14 t= 4.86 * | -1.12 t= 5.14 * | -1.01 t= 5.43 * | -0.82 t= 5.71 * | -0.57 t= 6.00 * | -0.29 t= 6.28 | -0.00 t= 6.57 | * 0.27 t= 6.85 | * 0.51 t= 7.14 | * 0.69 t= 7.43 | * 0.81 t= 7.71 | * 0.86 t= 8.00 | * 0.84 t= 8.28 | * 0.76 t= 8.57 | * 0.62 t= 8.85 | * 0.44 t= 9.14 | * 0.23 t= 9.42 | 0.00 t= 9.71 * | -0.23 t=10.00 * | -0.44 t=10.28 * | -0.62 t=10.57 * | -0.76 t=10.85 * | -0.84 t=11.14 * | -0.86 t=11.42 * | -0.81 t=11.71 * | -0.69 t=12.00 * | -0.51 t=12.28 * | -0.27 t=12.57 | -0.00 """) assert ans == s
def create_design_config(self) -> bool: """ the design-config is the main configuration for the OpenROAD built-in scripts. initially, we are using OpenROAD's tool scripts as-is, so we need to create a design-config that their scripts understand. the synthesis tool is the only tool that will write this """ design_config = self.design_config_path() # Load input files and check that they are all Verilog. if not self.check_input_files([".v", ".sv"]): return False abspath_input_files = list( map(lambda name: os.path.join(os.getcwd(), name), self.input_files)) # Add any verilog_synth wrappers (which are needed in some # technologies e.g. for SRAMs) which need to be synthesized. abspath_input_files += self.technology.read_libs( [hammer_tech.filters.verilog_synth_filter], hammer_tech.HammerTechnologyUtils.to_plain_item) # Generate constraints input_sdc = os.path.join(self.run_dir, "input.sdc") unit = self.get_time_unit().value_prefix + self.get_time_unit().unit with open(input_sdc, "w") as f: f.write("set_units -time {}\n".format(unit)) f.write(self.sdc_clock_constraints) f.write("\n") f.write(self.sdc_pin_constraints) # TODO: i am blindly reading in all libs for all corners. but this is # not a performance issue for nangate45 extra_lefs = list( set( filter( lambda x: x is not None, map(lambda x: x.library.lef_file, self.technology.get_extra_libraries())))) extra_libs = list( set( filter( lambda x: x is not None, map(lambda x: x.library.nldm_liberty_file, self.technology.get_extra_libraries())))) with open(design_config, "w") as f: f.write( dd(""" export DESIGN_NICKNAME = {design} export DESIGN_NAME = {design} export PLATFORM = {node} export VERILOG_FILES = {verilogs} export SDC_FILE = {sdc} export ADDITIONAL_LEFS = {extra_lefs} export ADDITIONAL_LIBS = {extra_libs} # These values must be multiples of placement site, which is # (x=0.19 y=1.4) for nangate45 export DIE_AREA = {die_area} export CORE_AREA = {core_area} export CLOCK_PERIOD = {period} """.format( design=self.top_module, node=self.get_setting("vlsi.core.technology"), verilogs=" ".join(abspath_input_files), sdc=input_sdc, extra_lefs=" ".join(extra_lefs), extra_libs=" ".join(extra_libs), die_area=self._floorplan_bbox(), core_area=self._floorplan_bbox(), period=self._clock_period_value(), ))) return True