Exemplo n.º 1
0
def main():
    inp = []
    prof = []
    print(sys.argv)
    for index in range(1, len(sys.argv)):
        inp.append(int(sys.argv[index]))
    conn = sqlite3.connect('db.sqlite3')
    data = conn.execute("SELECT * FROM UserProfiles")
    for row in data:
        if row[0] == inp[0] or row[0] == inp[1]:
            prof.append(row)
    pdict = load_obj('policy')
    ud = []
    for p in prof:
        hk = catnhack(p[3])
        pl = parse(p[4])
        db = parse(p[5])
        aoi = parse(p(6))
        lt = [p[2], pl, db, aoi, hk]
        ud.append(lt)
    if ud[0] <= ud[1]:
        c = ud[0]
        ud[0] = ud[1]
        ud[1] = c
    pdict[tuple(ud[0], ud[1])].backprop(inp[2])
    save_obj(pdict, 'policy')    
Exemplo n.º 2
0
def classify_business():
    businessesDirectory = settings.APP_DATA_HTML
    url = json.loads(request.args["business_name"]).lower() 

    for root, dirs, files in os.walk(businessesDirectory):
        for filename in files:
            originalFileName = filename = filename.lower()           
            if(filename.endswith(".txt")):
                filename = filename[:-4]
            if filename == url:

                business = main.parse(url)

                return json.dumps({
                    "name": business.name,
                    "type": {
                        "label": business.type.label, 
                        "probability": business.type.probability
                    },
                    "labels": business.labels
                })

    # Here we know that no match has been found so crawl the website
    business = main.parse(url)

    return json.dumps({
        "name": business.name,
        "type": {
            "label": business.type.label, 
            "probability": business.type.probability
        },
        "labels": business.labels
    })
Exemplo n.º 3
0
 def test_expressions(self):
     self.assertEqual(parse_expression("three plus four"), "3 + 4")
     self.assertEqual(
         parse("space greater than five and number of cars less than four"),
         "space > 5 "
         "and "
         "number_of_cars "
         "< 4")
     self.assertEqual(
         parse(
             "three plus four is less than number of cars and x is greater than five"
         ), "3 + 4 < number_of_cars and x > 5")
     self.assertEqual(parse("index or number of times"),
                      "index or number_of * ")
     self.assertEqual(parse_expression("three mod four division two"),
                      "3 % 4 / 2")
     self.assertEqual(
         parse(
             "space greater or equal to five and number of cars less or equal to four"
         ), "space >= 5 "
         "and "
         "number_of_cars "
         "<= 4")
     self.assertEqual(
         parse(
             "space greater or equal to one hundred and number of cars less or equal to four"
         ), "space >= 100 "
         "and "
         "number_of_cars "
         "<= 4")
Exemplo n.º 4
0
def test_file(file):
    if "fail_" in file:
        cm = pytest.raises(ValidationError)
    else:
        cm = nullcontext()

    with cm: 
        parse(filename=file)
Exemplo n.º 5
0
def pre_parse(url, pack):
    try:
        parse(url, pack)
    except:
        print("!!!ERROR!!!")
        for driver in drivers:
            driver.close()
            drivers.remove(driver)
        pre_parse(url, pack)
Exemplo n.º 6
0
def main():
    parser = ArgumentParser(description='Parse a LaTeX sting and attempt to compute a result.')
    parser.add_argument('-a', action='store_true', help='Return exact or approximate value')
    parser.add_argument('-s', action='store_true', help='Return as approximate to nearest power of 10')
    parser.add_argument('-l', action='store_true', help='Return as plaintext or LaTeX')
    parser.add_argument('string', type=str, help='String to parse', nargs='+')
    args = parser.parse_args()
    if args.s and not args.a:
        raise ArgumentTypeError("-a must be enabled for -s")
    parse(raw(" ".join(args.string)).strip(),**{"approx":args.a,"latex":args.l, "sci":args.s})
Exemplo n.º 7
0
 def test_part_two(self):
     data = main.parse(io.StringIO('1\n17,x,13,19'))
     self.assertEqual(main.part_two(data), 3417)
     data = main.parse(io.StringIO('1\n67,7,59,61'))
     self.assertEqual(main.part_two(data), 754018)
     data = main.parse(io.StringIO('1\n67,x,7,59,61'))
     self.assertEqual(main.part_two(data), 779210)
     data = main.parse(io.StringIO('1\n67,7,x,59,61'))
     self.assertEqual(main.part_two(data), 1261476)
     data = main.parse(io.StringIO('1\n1789,37,47,1889'))
     self.assertEqual(main.part_two(data), 1202161486)
Exemplo n.º 8
0
    def test_parse_method(self):
        import main

        for candidate, response in TEST_CASES:
            self.assertTrue(main.parse(candidate), response)

        for candidate, weekday, hour, minute in WEEKDAY_CASES:
            day = main.parse(candidate)
            self.assertTrue(day.weekday() == weekday)
            self.assertTrue(day.hour == hour)
            self.assertTrue(day.minute == minute)
Exemplo n.º 9
0
def test_parse():
    if main.parse(["1b ->. b1"]) != [['1b', 'b1', 1]]:
        print("Error test_parse")
    if main.parse([" ->. |"]) != [['', '|', 1]]:
        print("Error test_parse")
    if main.parse([" ->. 111\n", "123 -> 4"]) != [['', '111', 1], ['123', '4', 0]]:
        print("Error test_parse")
    if main.parse([" -> "]) != [['', '', 0]]:
        print("Error test_parse")
    if main.parse([" ->. \n"]) != [['', '', 1]]:
        print("Error test_parse")
Exemplo n.º 10
0
def test_main():
    output = subprocess.Popen([
        "C:\\Users\\Admin\\Desktop\\university\\dva339\\lab2\\lab2.1\\Test2.1\\Test21.exe",
        "./false.bat", "1"
    ],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE).communicate()[0].decode(
                              )
    p = output[output.find(")") + 1:].strip()
    pretty_parse_p = str(parse(lex(p))[0])
    pretty_parse_pretty_parse_p = str(parse(lex(pretty_parse_p))[0])
    return equals_program(p, pretty_parse_p), equals_program(
        pretty_parse_p, pretty_parse_pretty_parse_p), p
Exemplo n.º 11
0
def test_parse():
    assert parse("1-3 a: abcde") == {"low": 1, "high": 3, "letter": "a", "pw": "abcde"}
    assert parse("1-3 b: cdefg") == {"low": 1, "high": 3, "letter": "b", "pw": "cdefg"}
    assert parse("2-9 c: ccccccccc") == {
        "low": 2,
        "high": 9,
        "letter": "c",
        "pw": "ccccccccc",
    }
    assert parse("2-10 c: ccccccccc") == {
        "low": 2,
        "high": 10,
        "letter": "c",
        "pw": "ccccccccc",
    }
Exemplo n.º 12
0
 def test_1_attack_2(self):
     units = parse("\n".join(["G....", "..G..", "..EG.", "..G..", "...G."]))
     units[3].hitpoints = 10
     e = [u for u in units if u.type == 'E'][0]
     r = e.tick(1, units)
     self.assertTrue(r)
     self.assertEqual(7, units[3].hitpoints)
Exemplo n.º 13
0
def test_one_node():
    result = {
        'type': 'node',
        'op': 'OR',
        'left': {
            'type': 'node',
            'op': 'AND',
            'left': {
                'type': 'leaf',
                'op': '=',
                'id': 'Пол',
                'literal': "М"
            },
            'right': {
                'type': 'leaf',
                'op': '>',
                'id': 'Возраст',
                'literal': 25
            }
        },
        'right': {
            'type': 'leaf',
            'op': '>',
            'id': 'Стаж',
            'literal': 0.5
        },
    }

    assert parse('Пол="М" AND Возраст>25 OR Стаж>.5') == result
Exemplo n.º 14
0
 def test_all_yes(self):
     data = main.parse(io.StringIO(self.data))
     self.assertEqual(main.all_yes(data[0]), 3)
     self.assertEqual(main.all_yes(data[1]), 0)
     self.assertEqual(main.all_yes(data[2]), 1)
     self.assertEqual(main.all_yes(data[3]), 1)
     self.assertEqual(main.all_yes(data[4]), 1)
Exemplo n.º 15
0
 def test_parse_string(self):
     with self.assertRaises(Exception):
         main.parse("a1")
     with self.assertRaises(Exception):
         main.parse("1a")
     with self.assertRaises(Exception):
         main.parse("1.a")
     with self.assertRaises(Exception):
         main.parse("a.1")
Exemplo n.º 16
0
    def test_parse_ignores_titles_authors_and_bibs(self):
        with open('tests/abstracts_test_file.txt') as test_file:
            abstract_parses = main.parse(test_file)

        expected_text_of_ab_5 = "one-dimensional transient heat conduction into a double-layer\nslab subjected to a linear heat input for a small time\ninternal ."

        self.assertEqual(abstract_parses.get('5'), expected_text_of_ab_5,
            "Text should not contain author or bibliographic information.")
Exemplo n.º 17
0
    def test_parse(self):
        
        first  = "Booker T., Washington, 87360, 373 781 7380, yellow"
        second = "James Murphy, yellow, 83880, 018 154 6474"
        blank  = ""

        expected_first     = dict([('color', "yellow"), ('firstname', "Booker T."), ('lastname', "Washington"), 
                ('phonenumber', "373-781-7380"), ('zipcode', "87360")])

        expected_second = dict([('color', "yellow"), ('firstname', "James"), ('lastname', "Murphy"), 
                ('phonenumber', "018-154-6474"), ('zipcode', "83880")])
        
        expected_third = 1
    
        self.assertEqual(main.parse(first, 0), expected_first)
        self.assertEqual(main.parse(second, 0), expected_second)
        self.assertEqual(main.parse(blank, 1), expected_third)
Exemplo n.º 18
0
def upload(request):
	if request.method == 'GET':
		if request.GET.get('token', '') != settings.VERIFY_TOKEN:
			raise Http404('')
		return render(request, 'upload_form.html', {'method': 'GET'})
	else:
		url = request.POST.get('url', None)
		verdict = False
		error = ''
		if url:
			from main import parse
			try:
				parse(url)
				verdict = True
			except Exception as e:
				error = e.__str__()
				pass
		return render(request, 'upload_form.html', {'success': verdict, 'method': 'POST', 'error': error})
Exemplo n.º 19
0
 def test_parse_1val(self):
     with self.assertRaises(Exception):
         main.parse("1;")
     with self.assertRaises(Exception):
         main.parse("1")
     with self.assertRaises(Exception):
         main.parse("")
Exemplo n.º 20
0
def main(sys_args):
    parser = argparse.ArgumentParser(
        description='Parsing helper for DeNSe parser.')

    parser.add_argument('--test_file',
                        type=str,
                        required=True,
                        help='test data')
    parser.add_argument('--output_file',
                        type=str,
                        default=None,
                        help='output file')
    parser.add_argument('--model_dir',
                        type=str,
                        default='model',
                        help='folder of the model')
    parser.add_argument('--data_model',
                        type=str,
                        default='data.pkl',
                        help='data model file')
    parser.add_argument('--classifier_model',
                        type=str,
                        default='model.pkl',
                        help='classifier model file')
    parser.add_argument('--best_model',
                        type=str,
                        default='best.pkl',
                        help='best classifier model file')

    parser.add_argument('--buffer_size',
                        type=int,
                        default=5000,
                        help='buffer size')
    parser.add_argument('--batch_size',
                        type=int,
                        default=50,
                        help='mini-batch size')

    args = parser.parse_args(sys_args)
    parse(args)
Exemplo n.º 21
0
def alarm(context):
    result = parse()
    to_string = ''.join(result).replace("'", '')
    try:
        pattern = re.compile(r'[{|}}]')
        sentences = filter(lambda t: t,
                           [t.strip() for t in pattern.split(to_string)])
        for s in sentences:
            # update.message.reply_text(f'{s}')
            context.bot.send_message(chat_id=context.job.context, text=f'{s}')
    except:
        # update.message.reply_text(result)
        context.bot.send_message(chat_id=context.job.context, text=result)
Exemplo n.º 22
0
 def runlist_parser(queue, url, pool):
     try:
         result = main.parse(url, types="list", parsers_name=["iqiyilistparser.IQiYiAListParser",
                                                              "iqiyilistparser.IQiYiLibMListParser",
                                                              "iqiyilistparser.IQiYiVListParser"],
                             pool=pool)[0]
         if (result is not None) and (result != []) and (result["data"] is not None) and (
                     result["data"] != []):
             queue.put({"result": result, "url": url})
     except IndexError:
         pass
     except Exception as e:
         # continue
         logging.exception("twice parse %s failed" % url)
Exemplo n.º 23
0
def classify_business():
    businessesDirectory = settings.APP_DATA_HTML
    businessName = json.loads(request.args["business_name"]).lower()

    for root, dirs, files in os.walk(businessesDirectory):
        for filename in files:
            originalFileName = filename = filename.lower()
            if (filename.endswith(".txt")):
                filename = filename[:-4]
            if filename == businessName:
                business = main.parse(
                    os.path.join(settings.APP_DATA_HTML, originalFileName),
                    filename)

                return json.dumps({
                    "name": business.name,
                    "type": {
                        "label": business.type.label,
                        "probability": business.type.probability
                    },
                    "labels": business.labels
                })

    # Here we know that no match has been found so crawl the website
    print businessName
    business = main.parse(os.path.join(settings.APP_DATA_HTML, businessName),
                          businessName)

    return json.dumps({
        "name": business.name,
        "type": {
            "label": business.type.label,
            "probability": business.type.probability
        },
        "labels": business.labels
    })
Exemplo n.º 24
0
    def test_parse(self):
        parsed = main.parse(io.StringIO(self.data))
        self.assertEqual(len(parsed), 4)

        first_passport = {
            'ecl': 'gry',
            'pid': '860033327',
            'eyr': '2020',
            'hcl': '#fffffd',
            'byr': '1937',
            'iyr': '2017',
            'cid': '147',
            'hgt': '183cm'
        }
        self.assertDictEqual(parsed[0], first_passport)
Exemplo n.º 25
0
    def test_parse(self):
        input = [('a', (0, 0)), ('b', (1, 1)), ('c', (0, 2)), ('d', (1, 3))]
        root_node = {
            'children': [],
            'id': None,
            'side': 'left',
            'text': 'root'
        }
        mind_map = [root_node]
        expected = [{
            'children': [{
                'children': [{
                    'children': [],
                    'id': None,
                    'side': 'left',
                    'text': 'b'
                }],
                'id':
                None,
                'side':
                'left',
                'text':
                'a'
            }, {
                'children': [{
                    'children': [],
                    'id': None,
                    'side': 'left',
                    'text': 'd'
                }],
                'id':
                None,
                'side':
                'left',
                'text':
                'c'
            }],
            'id':
            None,
            'side':
            'left',
            'text':
            'root'
        }]

        self.assertEqual(expected, main.parse(input, mind_map))
Exemplo n.º 26
0
 def runlist_parser(queue, url, pool):
     try:
         result = main.parse(
             url,
             types="list",
             parsers_name=[
                 "iqiyilistparser.IQiYiAListParser",
                 "iqiyilistparser.IQiYiLibMListParser",
                 "iqiyilistparser.IQiYiVListParser"
             ],
             pool=pool)[0]
         if (result is not None) and (result != []) and (
                 result["data"]
                 is not None) and (result["data"] != []):
             queue.put({"result": result, "url": url})
     except IndexError:
         pass
     except Exception as e:
         # continue
         logging.exception("twice parse %s failed" % url)
Exemplo n.º 27
0
def test_main():
    output = subprocess.Popen(
        ["..\\..\\lab2.1\\Test2.1\\Test21.exe", "./false.bat", "1"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE).communicate()[0].decode()
    p = output[output.find(")") + 1:].strip()
    # remove comments
    lines = ""
    p = re.split(r'\r\n|\r|\n', p.strip())
    for line in p:
        start = re.search("//", line)
        if start:
            lines += line[:start.span()[0]] + "\n"
        else:
            lines += line + "\n"
    # ---------------------------------------------------
    p = lines
    print(p)
    pretty_parse_p = str(parse(lex(p))[0])
    # pretty_parse_pretty_parse_p = str(parse(lex(pretty_parse_p))[0])
    # return equals_program(p, pretty_parse_p), equals_program(pretty_parse_p, pretty_parse_pretty_parse_p), p
    return True, True, None
Exemplo n.º 28
0
    def test_examples(self):
        for input_file, output_file in self.CASEFILES:
            with self.subTest(input_file=input_file, output_file=output_file):

                with open(input_file, 'r') as fd:
                    case_iter = iter(fd.read().splitlines())
                with patch('builtins.input', iter(case_iter).__next__):
                    inputs = parse()

                print("INPUTS>>>")
                print(inputs)

                actual_out = io.StringIO()
                with redirect_stdout(actual_out):
                    solve(*inputs)

                print("OUTPUTS>>>")
                print(actual_out.getvalue())

                with open(output_file, 'r') as fd:
                    actual = actual_out.getvalue().split('\n')[:-1]
                    expect = fd.read().splitlines()
                    self.assertEqual(actual, expect)
Exemplo n.º 29
0
 def test_parser(self):
     response = parse('example.csv')
     self.assertEqual(response, string_value)
Exemplo n.º 30
0
def test_one():
    input = "FBFBBFFRLR"
    (row, column) = parse(input)
    assert row == 44
    assert column == 5
    assert 357 == gen_seat_id(row, column)
Exemplo n.º 31
0
def test_four():
    input = "BBFFBBFRLL"
    (row, column) = parse(input)
    assert row == 102
    assert column == 4
    assert 820 == gen_seat_id(row, column)
Exemplo n.º 32
0
def test_three():
    input = "FFFBBBFRRR"
    (row, column) = parse(input)
    assert row == 14
    assert column == 7
    assert 119 == gen_seat_id(row, column)
Exemplo n.º 33
0
def test_two():
    input = "BFFFBBFRRR"
    (row, column) = parse(input)
    assert row == 70
    assert column == 7
    assert 567 == gen_seat_id(row, column)
Exemplo n.º 34
0
 def test_part_two(self):
     data = main.parse(io.StringIO(self.data2))
     self.assertEqual(main.part_two(data), 4)
Exemplo n.º 35
0
Arquivo: test.py Projeto: rozap/arb
        super(ParametrizedTestCase, self).__init__(methodName)
        self.settings = settings

    @staticmethod
    def parametrize(testcase_klass, settings=None):
        """ Create a suite containing all tests taken from the given
            subclass, passing them the parameter 'param'.
        """
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_klass)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_klass(name, settings=settings))
        return suite


if __name__ == "__main__":
    from exchanges import *
    from watcher import TestWatcher
    from api import *

    args = parse()
    settings = load_settings(args.settings)

    suite = unittest.TestSuite()
    suite.addTest(ParametrizedTestCase.parametrize(TestBitstamp, settings=settings))
    suite.addTest(ParametrizedTestCase.parametrize(TestCoinbase, settings=settings))
    suite.addTest(ParametrizedTestCase.parametrize(TestWatcher, settings=settings))

    unittest.TextTestRunner().run(suite)
Exemplo n.º 36
0
def test_multi():
    assert main.parse(open('test.hatena').read()) == open('test.html').read()
Exemplo n.º 37
0
from main import parse, train, report
from src.DRHGCN.model import DRHGCN

if __name__ == "__main__":
    # os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
    args = parse(print_help=True)
    train(args, DRHGCN)
    # report("runs")
Exemplo n.º 38
0
    def test_parse_keys_match_doc_ids(self):
        with open('tests/query_test_file.qry') as test_file:
            abstract_parses = main.parse(test_file)

        expected_keys = ['041', '049', '050']
        self.assertEqual(set(expected_keys), set(abstract_parses.keys()))
Exemplo n.º 39
0
 def test_valid_passport(self):
     data = main.parse(io.StringIO(self.data))
     self.assertTrue(main.valid_passport(data[0]))
     self.assertFalse(main.valid_passport(data[1]))
     self.assertTrue(main.valid_passport(data[2]))
     self.assertFalse(main.valid_passport(data[3]))