Пример #1
0
	def convert_to_txt(self):
		converter = Converter(self.file_name+".pdf",self.target_name,self.path)
		converter.convert()
		reader = Reader(self.target_name,self.pg_count,self.path)
		extracted_text = reader.get_text()
		extracted_text = os.linesep.join([s for s in extracted_text.splitlines() if s])
		writer = Writer((self.target_name+".txt"),extracted_text,self.path)
		writer.write()
Пример #2
0
 def run(self):
     total_num = len(self.model_ls)
     for idx, (model, cfg) in enumerate(zip(self.model_ls, self.cfg_ls)):
         print(
             "-------------------[{}/{}]: Begin Converting {}--------------"
             .format(idx + 1, total_num, model))
         converter = Converter(model, cfg, self.get_onnx_path(model),
                               self.get_libtorch_path(model),
                               self.get_onnx_sim_path(model))
         converter.convert()
Пример #3
0
 def __init__(self):
     super(UnitsWorkflow, self).__init__()
     self.currencies_file = os.path.join(self.cache_dir, 'currencies.txt')
     self.load_currencies()
     self.separator = self.config.get('separator') or '>'
     self.precision = self.config.get('precision') or None
     self.config['separator'] = self.separator
     self.config['precision'] = self.precision
     self.converter = Converter(self.currencies_file,
                                separator=self.separator,
                                precision=self.precision)
Пример #4
0
def convert(options, args):

    if options.test_mode:

        import pkg_resources
        print 'Entering testmode'

        for fn in ('test1.html', 'test2.html', 'test3.html'):
            tmpf = newTempfile()
            print fn
            print '-' * len(fn)
            file(tmpf + '.html', 'wb').write(
                pkg_resources.resource_string('zopyx.convert2.tests.data', fn))

            for name in registry.availableConverters():
                cls = registry.converter_registry[name]
                print '%s: %s.html -> %s.%s' % (name, tmpf, tmpf,
                                                cls.output_format)
                C = Converter(tmpf + '.html', verbose=True)
                try:
                    result = C(name,
                               output_filename=tmpf + '.' + cls.output_format)
                    print result
                except Exception, e:
                    print 'FAILED (%s)' % e

            print
Пример #5
0
    def run_custom(self, input_path_list, output_path):

        # aggregate
        print('-' * 20)
        outfiles = [output_path + 'aggregated.xml']
        from aggregate import Aggregator
        options = input_path_list + ['-o', outfiles[-1]]
        Aggregator.run(options)

        # convert shorthands
        print('-' * 20)
        outfiles += [output_path + 'converted.xml']
        from convert import Converter
        options = [outfiles[-2]] + ['-o', outfiles[-1]]
        Converter.run(options)

        # validate conversion
        print('-' * 20)
        from validate import Validator
        options = [outfiles[-1]] + ['-o', output_path + 'validation.log']
        Validator.run(options)

        if self.convert_only:
            return

        # tokenise
        print('-' * 20)
        outfiles += [output_path + 'tokenised.xml']
        from tokenise import TEITokeniser
        options = [outfiles[-2]] + ['-o', outfiles[-1]]
        TEITokeniser.run(options)

        # kwic.xml
        print('-' * 20)
        outfiles += [output_path + 'kwic.xml']
        from kwic import KWICList
        options = [outfiles[-2]] + ['-o', outfiles[-1]]
        if self.para_string:
            options += ['-r', self.para_string]
        KWICList.run(options)

        # kwic.html
        print('-' * 20)
        outfiles += [output_path + 'kwic.html']
        from kwic_html import KwicHtml
        options = [outfiles[-2]] + ['-o', outfiles[-1]]
        KwicHtml.run(options)
Пример #6
0
class VolumeTestCase(unittest.TestCase):
        def setUp(self):
                self.conversion = Converter(value=6.25, initial_unit='gallons', desired_unit='cups', student_response=100)

        def test_check_class_initialised(self):
                self.assertTrue(isinstance(self.conversion, Converter))

        def test_convert_volume(self):
                self.assertEqual(self.conversion.convert_volume(), self.conversion.student_response)

        def test_is_unit_volume_convertible(self):
                self.assertTrue(self.conversion.is_unit_volume_convertible())

        def test_is_not_temperature_unit(self):
                self.assertFalse(self.conversion.is_unit_temp_convertible())

        def test_compare_answer(self):
                self.assertTrue(self.conversion.compare_answer(self.conversion.student_response))
Пример #7
0
 def __init__(self):
     super(UnitsWorkflow, self).__init__()
     self.currencies_file = os.path.join(self.cache_dir, 'currencies.txt')
     self.load_currencies()
     self.separator = self.config.get('separator') or '>'
     self.precision = self.config.get('precision') or None
     self.config['separator'] = self.separator
     self.config['precision'] = self.precision
     self.converter = Converter(self.currencies_file,
         separator=self.separator, precision=self.precision)
Пример #8
0
def video_upload(update, context):
    user = update.message.from_user
    chat_id = update.message.chat.id
    video_file = update.message.video.get_file()
    video_file.download(f'{chat_id}_video.mp4')

    logger.info("Video upload successful %s", user.first_name)

    logger.info(
        f"chat_id:{chat_id} │ Got video from {user.first_name} {chat_id}_video.jpg"
    )
    # api.set_data('/set')
    api.set_video(video_file.download_as_bytearray(), chat_id)

    logger.info("Video of %s: %s", user.first_name, f'{chat_id}_video.mp4')
    update.message.reply_text(
        'Perfect! Now, wait, we are processing your request. Please wait, processing can last longer than 30 seconds'
    )
    res = api.set_data('/inference', chat_id)

    bot = update.message.bot
    c = Converter(base64.b64encode(video_file.download_as_bytearray()),
                  res['video'],
                  result=f"{chat_id}_final.mp4")
    c.convert()

    with open(f"{chat_id}_final.gif", "wb") as fh:
        fh.write(base64.b64decode(res['video']))

    bot.send_video(chat_id,
                   video=open(f'{chat_id}_final.mp4', 'rb'),
                   caption="Here's what I have for you.")
    logger.info(
        f"chat_id:{chat_id} │ Got video from {user.first_name}: {chat_id}_video.mp4"
    )
    logger.info(f"chat_id:{chat_id} │ Send final result {user.first_name}")
    update.message.reply_text(
        'Hope you enjoyed the result.\n\nTo start over message me with /start.',
        reply_markup=ReplyKeyboardRemove())
    logger.info(
        f"chat_id:{update.message.chat.id} │ User {user.first_name} ended the conversation"
    )
    return ConversationHandler.END
Пример #9
0
class UnitsWorkflow(Workflow):
    def __init__(self):
        super(UnitsWorkflow, self).__init__()
        self.currencies_file = os.path.join(self.cache_dir, 'currencies.txt')
        self.load_currencies()
        self.separator = self.config.get('separator') or '>'
        self.precision = self.config.get('precision') or None
        self.config['separator'] = self.separator
        self.config['precision'] = self.precision
        self.converter = Converter(self.currencies_file,
            separator=self.separator, precision=self.precision)

    def load_currencies(self):
        import datetime

        lines = []
        last_refresh = None
        today = datetime.date.today()

        if os.path.exists(self.currencies_file):
            with open(self.currencies_file, 'rt') as cf:
                lines = cf.readlines()

        if len(lines) > 0 and lines[0].startswith('# date:'):
            last_refresh = lines[0].split(':')[1].strip()
            last_refresh = datetime.datetime.strptime(last_refresh, '%Y-%m-%d').date()

        if not last_refresh or last_refresh != today:
            import yfinance
            rates = yfinance.get_rates(CURRENCIES)
            with open(self.currencies_file, 'wt') as cf:
                cf.write('# date: ' + today.strftime('%Y-%m-%d') + '\n')
                cf.write('USD = [currency] = usd\n')
                for k, v in rates.items():
                    cf.write('{0} = USD / {1} = {2}\n'.format(k, v, k.lower()))

    def _convert(self, query):
        query = query.strip()
        try:
            value, text = self.converter.convert(query)
        except Exception, e:
            LOG.exception('Error converting')
            if e.message.startswith('Parse error in query'):
                return [Item('Waiting for input...')]
            else:
                try:
                    int(e.message)
                    return [Item('Waiting for input...')]
                except:
                    pass
            raise e

        return [Item(text, arg=str(value), valid=True,
                              subtitle='Action this item to copy %s to the '
                                       'clipboard' % value)]
Пример #10
0
    def setUpClass(cls):
        cls.cache_dir = "/tmp/histogram_revision_cache"
        cls.schema_filename = "./telemetry/telemetry_schema.json"
        assert not os.path.exists(cls.cache_dir)

        schema_file = open(cls.schema_filename, "r")
        cls.schema = TelemetrySchema(json.load(schema_file))
        schema_file.close()
        cls.cache = revision_cache.RevisionCache(cls.cache_dir,
                                                 'hg.mozilla.org')
        cls.converter = Converter(cls.cache, cls.schema)
Пример #11
0
def process_options(argv):
	parser = argparse.ArgumentParser(description='VerilogScript processor')
	parser.add_argument('-e', '--execute', help="Command to execute Verilog compiler")
	parser.add_argument('file', nargs='+')
	args = parser.parse_args(argv)
	if args.execute:
		exec_params = args.execute.split()
	else:
		exec_params = [False]
	conv = Converter()
	for file in args.file:
		if not os.path.isfile(file):
			raise FileNotFound(file)
		if file.endswith('.v'):
			exec_params.append(file)
		elif file.endswith('.vs'):
			target_file = file[:-1] #remove ending 's'
			if not os.path.exists(target_file) or \
					os.path.getmtime(target_file) < os.path.getmtime(file):
				conv.convert_vs(file, target_file)
			exec_params.append(target_file)
		else:
			raise WrongFileType(file)
	if exec_params[0]:
		p = subprocess.Popen(exec_params, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		for line in p.stdout:
			print(line, end="")
		error = False
		for line in p.stderr:
			error = True
			line = line.rstrip()
			parts = line.split(':',2)
			if len(parts) > 2 and parts[1][0].isdigit():
				parts[0], parts[1] = conv.convert_error(parts[0], int(parts[1]))
				print('%s:%d:%s' %(parts[0], parts[1], parts[2]))
			else:
				print(line)
		if error:
			sys.exit(-1)
Пример #12
0
 def test_approx_to_tenth(self):
     self.assertEqual(Converter.approx_to_tenth(self=None, value=123.454),
                      123.5)
     self.assertEqual(Converter.approx_to_tenth(self=None, value=123.145),
                      123.1)
     self.assertEqual(Converter.approx_to_tenth(self=None, value=999.99),
                      1000)
     self.assertEqual(Converter.approx_to_tenth(self=None, value=305.15),
                      305.1)
     self.assertNotEqual(Converter.approx_to_tenth(self=None, value=999.99),
                         999.9)
     self.assertNotEqual(
         Converter.approx_to_tenth(self=None, value=123.456), 123.46)
 def test_result_is_invalidd(self):
     self.assertEqual(
         str(
             Converter(value=73.12,
                       initial_unit='gallons',
                       desired_unit='Kelvin',
                       student_response=19.4)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=200,
                       initial_unit='Celsius',
                       desired_unit='cups',
                       student_response=19.4)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=180.12,
                       initial_unit='Kelvin',
                       desired_unit='tablespoons',
                       student_response=19.4)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=-750.12,
                       initial_unit='gallons',
                       desired_unit='Kelvin',
                       student_response=19.4)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=-100,
                       initial_unit='Kelvin',
                       desired_unit='cups',
                       student_response=19.4)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=34,
                       initial_unit='dog',
                       desired_unit='cups',
                       student_response=86)), 'invalid')
     self.assertEqual(
         str(
             Converter(value=-25,
                       initial_unit='Kelvin',
                       desired_unit='cats',
                       student_response=19.4)), 'invalid')
 def test_result_is_incorrect(self):
     self.assertEqual(
         str(
             Converter(value=42,
                       initial_unit='Kelvin',
                       desired_unit='Celsius',
                       student_response=874)), 'incorrect')
     self.assertEqual(
         str(
             Converter(value=90,
                       initial_unit='Fahrenheit',
                       desired_unit='Celsius',
                       student_response=38.2)), 'incorrect')
     self.assertEqual(
         str(
             Converter(value=1.23,
                       initial_unit='Kelvin',
                       desired_unit='Rankine',
                       student_response=34.2)), 'incorrect')
     self.assertEqual(
         str(
             Converter(value=54.54,
                       initial_unit='gallons',
                       desired_unit='liters',
                       student_response=84.1)), 'incorrect')
     self.assertEqual(
         str(
             Converter(value=45,
                       initial_unit='cups',
                       desired_unit='gallons',
                       student_response=0)), 'incorrect')
     self.assertEqual(
         str(
             Converter(value=-839,
                       initial_unit='Kelvin',
                       desired_unit='Celsius',
                       student_response=89.93)), 'incorrect')
 def test_liters_to_gallon(self):
     self.assertEqual(str(Converter(value=100, initial_unit='liters', desired_unit='gallons', student_response=26.4)), 'correct')
 def test_liters_to_tablespoons(self):
     self.assertEqual(str(Converter(value=100, initial_unit='liters', desired_unit='tablespoons', student_response=6762.8)), 'correct')
Пример #17
0
def main():
  if args.inp == None:
    print "\nPlease enter input path\n"
    exit(1)

  if args.out == None:
    print "\nPlease enter output PDF path\n"
    exit(1)

  fns = glob(args.inp)

  if len(fns) == 0:
    print "\nNo input file found, please check input path\n"
    exit(1)

  pdf_gen = PdfGen(args.out, args.csv)

  for index, fn in enumerate(fns):
    pdf_gen.writePdfName(fn)

    try:
      img = Converter().convertPDF(fn)

      rectangles = PlotRectangles().getRectangles(img)

      x_axis = XAxis(img.copy())
      y_axis = YAxis(img.copy())
      plot_name = PlotName(img.copy())
      

      #iterating over tables
      for i, rectangle in enumerate(rectangles):
        plotFilename = '/tmp/plot.png'
        x1,y1 = rectangle[0]
        x2,y2 = rectangle[2]
        cv2.imwrite(plotFilename, img[y1:y2, x1:x2].copy())

        try:
          ret = x_axis.findXScale(rectangle, i, args.no_interrupt)
        except:
          ret = [100, 10, 0, 100]

        xLabelPath, mx = x_axis.findXLabel(rectangle, ret[1], i, index)
        xScale = ret[0]
        xStart = ret[2]
        xDelta = ret[3]

        try:
          ret = y_axis.findYScale(rectangle, i, args.no_interrupt)
        except:
          ret = [100, 10, 0, 100]

        yLabelPath = y_axis.findYLabel(rectangle, ret[1], i, index)
        yScale = ret[0]
        yStart = ret[2]
        yDelta = ret[3]

        plotNamePath = plot_name.getPlotName(rectangle, i, index, mx)

        legends = Legends(rectangle, img)
        legendItemImagePaths, colorMap = legends.getLegend(i, index)
        
        data = Data().getData(plotFilename, xStart, xDelta, xScale, yStart, yDelta, yScale, colorMap)

        table_headers = [xLabelPath] + legendItemImagePaths
        pdf_gen.add_table(plotNamePath, yLabelPath, table_headers, data)

    except:
      print "Could not process ", fn

  pdf_gen.print_file()
Пример #18
0
 def setUp(self):
     super().setUp()
     self.converter = Converter('old-test.txt', 'new-test.txt')
     self.converter.convert()
     self.data['test_key_convert'] = {
         "/Scripts/Key Bindings/GUI/Key":
         52,
         "/GUI/Key":
         52,
         "/Key Bindings/Script Bindings/GUI/Key":
         52,
         "/.FAIO/7. dodgeIT/3. Dangerous enemy skills/Table 1/chaos_knight_chaos_bolt {{dodger}}":
         1,
         "/Scripts/Script Options/.FAIO/7. dodgeIT/3. Dangerous enemy skills/Table 1/chaos_knight_chaos_bolt {{dodger}}":
         1,
         "/Scripts/Script Options/.FAIO/2. Item Usage/1. Offensive items/1. Combo usage/Items/Use Item Shivas Guard":
         1,
         "/.FAIO/2. Item Usage/1. Offensive items/1. Combo usage/Items/Use Item Shivas Guard":
         1,
         "/.FAIO/6. Last hitter/7. Push key {{lasthit}}":
         36,
         "/Key Bindings/Script Bindings/.FAIO/6. Last hitter/7. Push key {{lasthit}}":
         36,
         "/Scripts/Key Bindings/.FAIO/6. Last hitter/7. Push key {{lasthit}}":
         36,
         "/Scripts/Script Options/.FAIO/3. Hero Scripts/3. Intelligence heroes/Tinker/3. Push mode/1. Tinker push mode":
         1,
         "/.FAIO/3. Hero Scripts/3. Intelligence heroes/Tinker/3. Push mode/1. Tinker push mode":
         1,
         "/.FAIO/3. Hero Scripts/3. Intelligence heroes/Tinker/3. Push mode/2. Tinker push key {{tinker}}":
         58,
         "/Key Bindings/Script Bindings/.FAIO/3. Hero Scripts/3. Intelligence heroes/Tinker/3. Push mode/2. Tinker push key {{tinker}}":
         58,
         "/Scripts/Key Bindings/.FAIO/3. Hero Scripts/3. Intelligence heroes/Tinker/3. Push mode/2. Tinker push key {{tinker}}":
         58,
         "/Utility/Translate/My Text To":
         5,
         "/Utility/Translate/Their Text To":
         2,
         "/Awareness/ESP/Illusion ESP":
         1,
         "/Awareness/ESP/Illusion ESP/Illusion ESP":
         1,
         "/Awareness/ESP/Illusion ESP/Illusion ESP: Hero Floats":
         1,
         "/Awareness/ESP/Illusion ESP/Illusion ESP: Show on MiniMap":
         1,
         "/Awareness/ESP/Illusion ESP/Illusion ESP: Unselectable":
         0,
         "/Hero Specific/Shadow Fiend/Shadowraze Key":
         36,
         "/Key Bindings/Shadowraze Key":
         36,
         "/.FAIO/3. Hero Scripts/3. Intelligence heroes/Invoker/5. Fast skills/Chaos meteor/2. Activation key {{invoker Chaos meteor}}":
         4,
         "/Key Bindings/Script Bindings/.FAIO/3. Hero Scripts/3. Intelligence heroes/Invoker/5. Fast skills/Chaos meteor/2. Activation key {{invoker Chaos meteor}}":
         4,
         "/Scripts/Key Bindings/.FAIO/3. Hero Scripts/3. Intelligence heroes/Invoker/5. Fast skills/Chaos meteor/2. Activation key {{invoker Chaos meteor}}":
         4,
         "/Scripts/Script Options/Awareness/Show Hidden Spells Plus/Invoker - EMP":
         1
     }
Пример #19
0
 def test_is_input_negative(self):
     self.assertTrue(Converter.is_input_negative(self=None, value=-100))
     self.assertFalse(Converter.is_input_negative(self=None, value=100))
     self.assertFalse(Converter.is_input_negative(self=None, value=0))
Пример #20
0
            "1) If you use an on premise installation, use bw config to set the url: bw config server <url>"
        )
        print(
            "2) execute bw login once, as this script uses bw unlock only: bw login <user>"
        )
        print(" ")

        while confirm != "y" and confirm != "n":
            confirm = input(
                "Confirm that you have set up bw cli [y/n]: ").lower()

        if confirm == "n":
            print("exiting...")
            sys.exit(2)

    # stdin password
    kp_pw = _read_password(args.kp_pw,
                           "Please enter your KeePass 2.x db password: "******"Please enter your Bitwarden password: "******" ")
    print("All done.")
Пример #21
0
 def setUp(self):
         self.conversion = Converter(value=6.25, initial_unit='gallons', desired_unit='cups', student_response=100)
Пример #22
0
import random
from geolocation import Geolocate
from stats import Stats
from convert import Converter
from animal import Predictor

load_dotenv('secrets.env')
discordToken = os.getenv('DISCORD_TOKEN')
geocodeToken = os.getenv('GEOCODE_TOKEN')
statPassword = os.getenv('METEOMATICS_PASSWORD')
statUsername = os.getenv('METEOMATICS_USERNAME')

animalPredictor = Predictor()
geolocator = Geolocate(geocodeToken=geocodeToken)
statloader = Stats(username=statUsername, password=statPassword)
converter = Converter()
client = discord.Client()
commandKey = '#sea'


@client.event
async def on_ready():
    print("Bot Started")


@client.event
async def on_message(message):

    #prevent self-response
    if message.author == client.user:
        return
 def test_liters_to_cubic_inches(self):
     self.assertEqual(str(Converter(value=100, initial_unit='liters', desired_unit='cubic_inches', student_response=6102.4)), 'correct')
 def test_Kelvin_to_Celsius(self):
     self.assertEqual(str(Converter(value=100, initial_unit='Kelvin', desired_unit='Celsius', student_response=-173.1)), 'correct')
Пример #25
0
def main():
    if args.inp == None:
        print "\nPlease enter input path\n"
        exit(1)

    if args.out == None:
        print "\nPlease enter output PDF path\n"
        exit(1)

    fns = glob(args.inp)

    if len(fns) == 0:
        print "\nNo input file found, please check input path\n"
        exit(1)

    pdf_gen = PdfGen(args.out, args.csv)

    for index, fn in enumerate(fns):
        pdf_gen.writePdfName(fn)

        try:
            img = Converter().convertPDF(fn)

            rectangles = PlotRectangles().getRectangles(img)

            x_axis = XAxis(img.copy())
            y_axis = YAxis(img.copy())
            plot_name = PlotName(img.copy())

            #iterating over tables
            for i, rectangle in enumerate(rectangles):
                plotFilename = '/tmp/plot.png'
                x1, y1 = rectangle[0]
                x2, y2 = rectangle[2]
                cv2.imwrite(plotFilename, img[y1:y2, x1:x2].copy())

                try:
                    ret = x_axis.findXScale(rectangle, i, args.no_interrupt)
                except:
                    ret = [100, 10, 0, 100]

                xLabelPath, mx = x_axis.findXLabel(rectangle, ret[1], i, index)
                xScale = ret[0]
                xStart = ret[2]
                xDelta = ret[3]

                try:
                    ret = y_axis.findYScale(rectangle, i, args.no_interrupt)
                except:
                    ret = [100, 10, 0, 100]

                yLabelPath = y_axis.findYLabel(rectangle, ret[1], i, index)
                yScale = ret[0]
                yStart = ret[2]
                yDelta = ret[3]

                plotNamePath = plot_name.getPlotName(rectangle, i, index, mx)

                legends = Legends(rectangle, img)
                legendItemImagePaths, colorMap = legends.getLegend(i, index)

                data = Data().getData(plotFilename, xStart, xDelta, xScale,
                                      yStart, yDelta, yScale, colorMap)

                table_headers = [xLabelPath] + legendItemImagePaths
                pdf_gen.add_table(plotNamePath, yLabelPath, table_headers,
                                  data)

        except:
            print "Could not process ", fn

    pdf_gen.print_file()
 def test_cubic_inches_to_cubic_feet(self):
     self.assertEqual(str(Converter(value=100, initial_unit='cubic_inches', desired_unit='cubic_feet', student_response=0.1)), 'correct')
 def setUp(self):
     self.conversion = Converter(value=100,
                                 initial_unit='Celsius',
                                 desired_unit='Kelvin',
                                 student_response=373.15)
Пример #28
0
 def test_config_parser_exceptions(self):
     with self.assertRaises(ConfigParserException):
         Converter('fakename.txt', 'fakename2.txt')
Пример #29
0
    if min_val < 0:
        raise ValueError("min value is zero")
    if min_val == 0:
        print("Min value 0 spotted")
        exit()
    mybins = np.logspace(np.log10(min_val), 0, 11)
    # res = np.histogram(arr, mybins)
    res = np.histogram(arr, bins=mybins, density=False)
    # print(np.sum(res[0]))
    temp = [str(np.round(x, 3)) for x in res[0]]
    log = "," + ",".join(["{:.1e}".format(x) for x in res[1]]) + "\n"
    log += ckt_name + "," + ",".join(temp)
    print(log)

elif args.func in ["deltaP", "deltaHTO"]:
    conv = Converter(ckt_name, "EPFL")
    # TODO: be cautious about passing args
    ops = OPI(circuit, args.func, count_op=args.opCount, args=args)
    fname = "../data/observations/" + ckt_name + "_" + args.func + "_B-" + str(
        args.Bth)
    fname += "_Count-" + str(args.opCount) + ".op"

    conv.nodes2tmax_OP(ops, fname)
    print("Stored Synopsys readable results in {}".format(fname))
    print(ops)
    for op in ops:
        print(op + "\t" + conv.n2g(op))

elif args.func == "gen_stil":
    # Does not generate the test patterns but reads them, and creates stil file
    # generate a test pattern file in 658 format and save it in ../data/patterns/
 def test_should_convert(self):
     input = '{"_id": {"$oid": "607164b5c7846b9a1e3af89e"}, "x": 1.0}'
     converter = Converter()
     itemAsJson = converter.toJson(input)
     converter.write(itemAsJson)
     self.assertEqual(itemAsJson['x'], 1.0)
Пример #31
0
import os
import revision_cache
import shutil
import simplejson as json
from telemetry_schema import TelemetrySchema
from convert import Converter

cache_dir = "/tmp/histogram_revision_cache"
schema_filename = "./telemetry/telemetry_schema.json"
assert not os.path.exists(cache_dir)

schema_file = open(schema_filename, "r")
schema = TelemetrySchema(json.load(schema_file))
schema_file.close()
cache = revision_cache.RevisionCache(cache_dir, 'hg.mozilla.org')
converter = Converter(cache, schema)

revision = "http://hg.mozilla.org/mozilla-central/rev/26cb30a532a1"
histograms = {
  "STARTUP_CRASH_DETECTED": {
    "sum_squares_hi": 0, # what about log_sum and log_sum_squares?
    "sum_squares_lo": 0,
    "sum": 0,
    "values": {
      "1": 0,
      "0": 1
    },
    "histogram_type": 3,
    "bucket_count": 3,
    "range": [
      1,
Пример #32
0
    # bw confirmation
    if not args.skip_confirm:
        confirm = None
        print("Do you have bw cli installed and is it set up?")
        print("1) If you use an on premise installation, use bw config to set the url: bw config server <url>")
        print("2) execute bw login once, as this script uses bw unlock only: bw login <user>")
        print(" ")

        while(confirm != "y" and confirm != "n"):
            confirm = input("Confirm that you have set up bw cli [y/n]: ").lower()

        if confirm == "n":
            print("exiting...")
            sys.exit(2)

    # stdin password
    kppw = args.kppw
    if not kppw:
        kppw = getpass.getpass(prompt="Please enter your KeePass 2.x db password: "******"Please enter your Bitwarden password: "******" ")
    print("All done.")
 def test_liters_to_cups(self):
     self.assertEqual(str(Converter(value=100, initial_unit='liters', desired_unit='cups', student_response=422.7)), 'correct')
Пример #34
0
 def test_is_respose_incorrect(self):
     self.assertEqual(Converter.response(self=None, is_correct=False),
                      "incorrect")
     self.assertNotEqual(Converter.response(self=None, is_correct=True),
                         "incorrect")
source_directory = "/home/ubuntu/src/test_sort_rewrite/kernel/"
source_file_name = "test_sort_backup.c"
target_file_name = "test_sort_rewrite.c"
full_source_path = source_directory + source_file_name
full_target_path = source_directory + target_file_name

print("Converting " + source_file_name)
print("Input file path: " + full_source_path)
print("Output path: " + full_target_path)

# |----------------------------------------------|
# | Conversion rules for "test_sort_rewrite.c" |
# |----------------------------------------------|

test_sort_rules_2 = {
    "test_functions": ["test_sort_init"],
    "test_suite_name": "test_sort_rewrite",
    "blacklist": ["cmpint"],
    "replacements": [("return err;", "ASSERT_INT_EQ(err, 0);")],
    "should_add_new_main": True
}

state = Converter(full_source_path, full_target_path, test_sort_rules_2, True)
state.add_include_code() \
    .add_init_code_to_main() \
    .add_exit_code() \
    .convert_to_test_common_args() \
    .use_replacements() \
    .result()
Пример #36
0
            "1) If you use an on premise installation, use bw config to set the url: bw config server <url>"
        )
        print(
            "2) execute bw login once, as this script uses bw unlock only: bw login <user>"
        )
        print(" ")

        while (confirm != "y" and confirm != "n"):
            confirm = input(
                "Confirm that you have set up bw cli [y/n]: ").lower()

        if confirm == "n":
            print("exiting...")
            sys.exit(2)

    # stdin password
    kppw = args.kppw
    if not kppw:
        kppw = getpass.getpass(
            prompt="Please enter your KeePass 2.x db password: "******"Please enter your Bitwarden password: "******" ")
    print("All done.")