Example #1
0
 def _is_installed_notify():
     try:
         sp.call(['notify-send','--help'],stdout=sp.PIPE)
         return True
     except:
         Colour.print('notify-send seems not working, please install notify-send',Colour.RED)
         return False
Example #2
0
    def show(self):
        browser = RoboBrowser(parser = 'html.parser')
        browser.open('http://codeforces.com/enter')
        enter_form = browser.get_form('enterForm')
        enter_form['handleOrEmail'] = self.username
        enter_form['password'] = self.password
        browser.submit_form(enter_form)

        try:
            checks = list(map(lambda x: x.getText()[1:].strip(),
                browser.select('div.caption.titled')))
            if self.username not in checks:
                Colour.print('Login Failed.. Wrong password.', Colour.RED)
                return
        except Exception as e:
            Colour.print('Login Failed.. Maybe wrong id/password.', Colour.RED)
            return

        browser.open('http://codeforces.com/friends')
        soup = browser.parsed()[0] # no need of soup
        ftable = soup.findAll('div',{'class':'datatable'})[0].findAll('table')[0].findAll('tr')[1:]

        friends = [x.findAll('td')[1].getText().strip() for x in ftable]
        for f in friends:
            print(f)
Example #3
0
    def show(self):
        browser = RoboBrowser(parser = 'html.parser')
        browser.open('http://codeforces.com/enter')
        enter_form = browser.get_form('enterForm')
        enter_form['handleOrEmail'] = self.username
        enter_form['password'] = self.password
        browser.submit_form(enter_form)

        try:
            checks = list(map(lambda x: x.getText()[1:].strip(),
                browser.select('div.caption.titled')))
            if self.username not in checks:
                Colour.print('Login Failed.. Wrong password.', Colour.RED)
                return
        except Exception as e:
            Colour.print('Login Failed.. Maybe wrong id/password.', Colour.RED)
            return

        browser.open('http://codeforces.com/contest/'+self.c_name+'/standings/friends/true')
        soup = browser.parsed()[0] # no need of soup
        ftable = soup.findAll('table',{'class':'standings'})[0].findAll('tr')[1:-1]
        tableh = soup.findAll('table',{'class':'standings'})[0].findAll('tr')[0].findAll('th')

        table_data = [[x.getText().strip() for x in tableh]]
        for friend in ftable:
            row = [x.getText().strip() for x in friend.findAll('td')]
            table_data += [row]

        tt = texttable.Texttable()
        tt.add_rows(table_data)
        tt.set_cols_valign(["b"]*len(tableh))
        print(tt.draw())
Example #4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-v",
                        "--version",
                        action='store_true',
                        help='Display version number')
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-b",
                       "--branch",
                       action="store_true",
                       help="full result of your branch")
    group.add_argument("-y",
                       "--year",
                       action="store_true",
                       help="full result of your year")
    group.add_argument("-a",
                       "--all",
                       action="store_true",
                       help="full result of college")
    group.add_argument("-m",
                       "--mtech",
                       action="store_true",
                       help="result of dual degree mtech")
    # parser.add_argument("roll",nargs=1,help="your roll number") # this is for exactly one, it returns array of 1 elem
    parser.add_argument("roll", nargs='?', help="your roll number"
                        )  # this is for one or none, it doesnot return array

    autocomplete(parser)
    args = parser.parse_args()

    if (args.version):
        print(__mod_name__ + '==' + __version__)
        sys.exit()

    if (args.roll):
        roll = args.roll.lower()
        print(roll)
    else:
        roll = input('Enter your roll number : ')
        if roll == '':
            roll = '15mi535'
    std = Student(roll)
    std.fetch_data()
    print(std)

    try:
        if (args.branch):
            full_class(roll)
        if (args.year):
            full_year(roll)
        if (args.all):
            full_college()
        if (args.mtech):
            full_mtech()
        if (args.all or args.branch or args.year or args.mtech):
            Colour.print("written into files in result folder....\n\n",
                         Colour.GREEN)
    except KeyboardInterrupt:
        Colour.print('Exiting on KeyboardInterrupt ...', Colour.YELLOW)
Example #5
0
 def try_schedule(self, output_path):
     try:
         self._schedule(output_path)
         Colour.print('Final adv value is ' + str(self.adv), Colour.YELLOW)
         Colour.print('Final seed value is ' + str(self.seed),
                      Colour.YELLOW)
         return True
     except EmptyQueue:
         return False
 def _verified_file(file_path):
     if not file_path:
         return None
     file_path = abs_path(file_path)
     if not os.path.isfile(file_path):
         Colour.print('No such file : ' + Colour.END + file_path,
                      Colour.RED)
         sys.exit()
     return file_path
Example #7
0
    def get_user_list(file_path):
        if(not file_path):
            return []

        user_list = []
        if(not os.path.isfile(file_path)):
            Colour.print('path not found '+file_path,Colour.RED)
            sys.exit(1)
        with open(file_path,'r') as fin:
            lines = fin.readlines()
        user_list = [user.strip() for user in lines]
        return user_list
Example #8
0
    def validate_args(parser):
        if parser.clean:
            if parser.file or parser.other or parser.test:
                Colour.print('no other argument is required with -c/--clean',Colour.YELLOW)
            return
        if parser.legacy: # legacy way
            new_args = [parser.file,parser.other,parser.test,parser.num,parser.id,parser.sec]
            if len(parser.legacy) > 0:
                parser.file = parser.legacy[0]
                Args.verify_file(parser.file)
            if len(parser.legacy) > 1:
                parser.other = parser.legacy[1]
                Args.verify_file(parser.other)
            if len(parser.legacy) > 2:
                parser.test = parser.legacy[2]
                Args.verify_file(parser.test)

        if not parser.file or not parser.other or not parser.test:
            if not parser.file:
                Colour.print('please provide input file name using -f/--file',Colour.RED)
            if not parser.other:
                Colour.print('please provide tester file name using -o/--other',Colour.RED)
            if not parser.test:
                Colour.print('please provide test generator name using -t/--test',Colour.RED)
            sys.exit(1)
Example #9
0
def main():
    args = get_parser()
    if args.version:
        print(__mod_name__ + '==' + __version__)
        sys.exit()

    if args.vr:
        Verifier.verify_room_list(args.vr)
        sys.exit()
    if args.vs:
        Verifier.verify_schedule_list(args.vs)
        sys.exit()
    if args.vt:
        Verifier.verify_teachers_list(args.vt)
        sys.exit()
    if args.vw:
        Verifier.verify_work_ratio(args.vw)
        sys.exit()

    if args.seed <= 0:
        Colour.print(
            'seed value should be a positive integer, got : ' + str(args.seed),
            Colour.RED)
        sys.exit(1)

    global default_output_xlsx_path
    if args.output: default_output_xlsx_path = args.output

    if args.reserved < 0:
        Colour.print(
            'Reserved number should be a non-negative integer, got : ' +
            str(args.reserved), Colour.RED)
        sys.exit(1)

    try:
        scheduler = Scheduler(int(args.seed), int(args.reserved))
        if args.debug: scheduler.debug = True
        scheduler._configure_paths()  # done manually
        res = scheduler.compileall()
        if not res:
            Colour.print('Error during compilation', Colour.RED)
            print(res)
            sys.exit(1)
        scheduler.schedule(default_output_xlsx_path)
        Colour.print(
            'Output written to : ' + Colour.END + default_output_xlsx_path,
            Colour.BLUE)
    except KeyboardInterrupt:
        Colour.print('Exiting on KeyboardInterrupt ...', Colour.YELLOW)
Example #10
0
 def get_latest_verdict(user):
     req = 'http://codeforces.com/api/user.status?'+'handle='+user+'&from=1&count=1'
     r = requests.get(req)
     js = r.json()
     if 'status' not in js or js['status'] != 'OK':
         Colour.print("unable to connect, try it yourself : "+req,Colour.RED)
         raise ConnectionError('Cannot connect to codeforces!')
     try:
         result = js['result'][0]
         id_ = result['id']
         verdict_ = result.get('verdict',None)
         time_ = result['timeConsumedMillis']
         memory_ = result['memoryConsumedBytes'] / 1000
         passedTestCount_ = result['passedTestCount']
     except Exception as e:
         raise ConnectionError('Cannot get latest submission, error')
     return id_, verdict_, time_, memory_, passedTestCount_
Example #11
0
 def print_failed_test(self):
     failed_test = Code_tester.get_output('.case' + self.idd + '.tester')
     if (len(failed_test.split('\n')) < 30):
         Colour.print('---------Failed Test Case----------', Colour.YELLOW)
         print(failed_test)
         Colour.print('')
         Colour.print('---------End of Test Case----------', Colour.YELLOW)
     else:
         Colour.print('Testcase file having more than 30 lines',
                      Colour.YELLOW)
    def _configure_paths(self):
        def configure_path(var_name):
            if not getattr(self, var_name):
                if not config_json[var_name]:
                    path = input('Please provide ' + var_name + ' file : ')
                    path = Scheduler._verified_file(path)
                    config_json[var_name] = path
                    setattr(self, var_name, config_json[var_name])
                else:
                    setattr(self, var_name, config_json[var_name])
            else:
                config_json[var_name] = getattr(self, var_name)

        var_list = ['room_list', 'teacher_list', 'schedule_list']
        for var_name in var_list:
            configure_path(var_name)
            Colour.print(
                'Using ' + var_name + ' : ' + Colour.END +
                getattr(self, var_name), Colour.GREEN)
Example #13
0
    def get_sessions(matrix, room_data):
        '''
        input matrix should be a Tabular object, or a path
        room_data should be a tabular object or a path
        '''
        if type(matrix) is str:
            Verifier.verify_schedule_list(matrix)
            temp = Tabular()
            temp.load_xls(matrix, strict=True)
            matrix = temp
        if type(room_data) is str:
            room_data = Room.get_rooms(room_data)

        room_json = {}
        for room in room_data:
            room_json[room.name] = room

        ret = []
        header = matrix[0][1:]  # remove first elem from header
        cols = len(header) + 1
        if (cols < 2):
            raise Exception('too few columns')
        for i in range(1, len(matrix)):
            row = matrix[i]
            room_list = []
            for room in header:
                need = row[room]
                if need == 'y' or need == 'Y':
                    if room in room_json:
                        room_list.append(room_json[room].copy())
                    else:
                        # raise Exception('Room ' +room+ ' not present in rooms file')
                        Colour.print(
                            'Room ' + room + ' not present in room list',
                            Colour.RED)
                        sys.exit()

            temp = Session(row[0], room_list)
            ret.append(temp)

        return ret
Example #14
0
def main():
    args = get_parser()
    if args.version:
        print(__mod_name__+'=='+__version__)
        sys.exit()

    if args.vr:
        Verifier.verify_room_list(args.vr)
        sys.exit()
    if args.vs:
        Verifier.verify_schedule_list(args.vs)
        sys.exit()
    if args.vt:
        Verifier.verify_teachers_list(args.vt)
        sys.exit()

    global default_output_xlsx_path
    if args.output: default_output_xlsx_path = args.output

    if args.reserved < 0:
        Colour.print('Reserved number should not be negative', Colour.RED)
        sys.exit(1)

    try:
        Scheduler().schedule(default_output_xlsx_path,int(args.reserved))
        Colour.print('Output written to : ' + Colour.END + default_output_xlsx_path, Colour.BLUE)
    except KeyboardInterrupt:
        Colour.print('Exiting on KeyboardInterrupt ...',Colour.YELLOW)
Example #15
0
 def print_verdict(last_id,username,max_time = 100,notify_installed = True):
     hasStarted = False
     while True:
         id_, verdict_, time_, memory_, passedTestCount_ = Submit.get_latest_verdict(username)
         if id_ != last_id and verdict_ != 'TESTING' and verdict_ != None:
             if verdict_ == 'OK':
                 message = 'OK - Passed ' + str(passedTestCount_) + ' tests'
                 color = Colour.GREEN
             else:
                 message = verdict_ + ' on ' + str(passedTestCount_+1) + ' test'
                 color = Colour.RED
             if(Submit.notify_installed): sp.call(['notify-send','Codeforces',message])
             elif(Submit.force_stdout): Colour.print(message,color)
             break
         elif verdict_ == 'TESTING' and (not hasStarted):
             message = 'Judgement has begun'
             if(Submit.notify_installed): sp.call(['notify-send','Codeforces',message])
             elif(Submit.force_stdout): Colour.print(message,Colour.GREEN)
             hasStarted = True
         time.sleep(0.5)
         max_time -= 1
         if(max_time < 0):
             message = 'Time out'
             if(Submit.notify_installed): sp.call(['notify-send','Codeforces',message])
             elif(Submit.force_stdout): Colour.print(message,Colour.YELLOW)
             break
Example #16
0
    def _configure_paths(self):
        '''
        to be called manually, not to be used in library
        '''
        from .configurations import config_json

        def configure_path(var_name):
            if not getattr(self, var_name):
                if not config_json[var_name]:
                    path = input('Please provide ' + var_name + ' file : ')
                    path = Scheduler._verified_file(path)
                    config_json[var_name] = path
                    setattr(self, var_name, config_json[var_name])
                else:
                    setattr(self, var_name, config_json[var_name])
            else:
                config_json[var_name] = getattr(self, var_name)

        var_list = [
            'room_list', 'teachers_list', 'schedule_list', 'work_ratio'
        ]
        for var_name in var_list:
            configure_path(var_name)
            Colour.print(
                'Using ' + var_name + ' : ' + Colour.END +
                getattr(self, var_name), Colour.GREEN)
        Colour.print('Using seed value : ' + Colour.END + str(self.seed),
                     Colour.GREEN)
        Colour.print(
            'Using reserved value : ' + Colour.END + str(self.reserved),
            Colour.GREEN)
Example #17
0
    def schedule(self, output_path):
        _seed = self.seed  # make a copy of it
        if True:  # change it to false if you want normal way
            while self.adv >= 1:
                Colour.print('Trying adv as ' + str(self.adv), Colour.YELLOW)
                for self.seed in range(_seed,
                                       _seed + (2 if self.adv > 3 else 3)):
                    if self.try_schedule(output_path):
                        return
                self.adv -= 3 if self.adv > 8 else 2 if self.adv > 4 else 1

        # last hope default case
        self.adv = 0  # can change it to tweek and debug
        self.seed = _seed
        Colour.print('Running in base Case', Colour.CYAN)
        Colour.print('Final adv value is ' + str(self.adv), Colour.YELLOW)
        Colour.print('Final seed value is ' + str(self.seed), Colour.YELLOW)
        self._schedule(output_path)
Example #18
0
    def submit(self):
        last_id, b, c, d, e = Submit.get_latest_verdict(self.username)

        browser = RoboBrowser(parser = 'html.parser')
        browser.open('http://codeforces.com/enter')
        # todo check if it takes time
        enter_form = browser.get_form('enterForm')
        enter_form['handleOrEmail'] = self.username
        enter_form['password'] = self.password
        browser.submit_form(enter_form)

        try:
            checks = list(map(lambda x: x.getText()[1:].strip(),
                browser.select('div.caption.titled')))
            if self.username not in checks:
                Colour.print('Login Failed.. Wrong password.', Colour.RED)
                return
        except Exception as e:
            Colour.print('Login Failed.. Maybe wrong id/password.', Colour.RED)
            return

        # todo check if it takes time
        browser.open('http://codeforces.com/contest/'+self.c_name+'/submit')
        submit_form = browser.get_form(class_ = 'submit-form')
        submit_form['submittedProblemIndex'].value = self.p_name
        submit_form['sourceFile'] = self.inputfile

        browser.submit_form(submit_form)
        print(browser.url)
        # if browser.url[-6:] != 'status': # it was used when submitting from problemset
        if not 'my' in browser.url:
            Colour.print('Failed submission, probably you have submit the same file before', Colour.RED)
            return

        Submit.print_verdict(last_id,self.username,100)
        Colour.print('[{0}] submitted ...'.format(self.inputfile), Colour.GREEN)
Example #19
0
    def fetch_data(self):
        cache = SrbJson(cache_path, template={"nith_results":
                                              {}})  # load cache
        if (self.roll_num in cache):
            item = cache[self.roll_num]
            self.set_cached_data(item['Name'], item['Gender'], item['Sgpa'],
                                 item['Cgpa'], item['Points'])
            if (self.name != '-' and self.cgpa != '0'):
                Colour.print('got chached ' + self.roll_num, Colour.BLUE)
                return self.get_cache()
            else:
                Colour.print('Bad chached ' + self.roll_num, Colour.YELLOW)

        url = "http://59.144.74.15/" + Student.get_c_id(
            self.roll_num) + self.batch + "/studentresult/details.asp"
        try:
            page = requests.post(url,
                                 data={'RollNumber': self.roll_num},
                                 proxies=Student.proxyDict,
                                 verify=False)
            soup = BeautifulSoup(page.text, 'html.parser')
            try:
                self.all_data = soup.find_all(class_='ewTable')
                self.name = self.all_data[0].find_all('tr')[0].find_all(
                    'td')[1].text.strip()
                self.name = self.name.upper()
                res = self.all_data[-1].find_all('tr')[1].find_all('td')
                self.sgpa = res[0].text.strip().split("=")[1]
                cgpa_ = res[2].text.strip()
                self.points = cgpa_.split("/")[0]
                self.cgpa = cgpa_.split("=")[1]
                cache[self.roll_num] = self.get_cache()  # store cache
                Colour.print('fetched successfully ' + self.roll_num,
                             Colour.BLUE)
                return self.get_cache()
            except KeyboardInterrupt:
                raise KeyboardInterrupt
            except:
                self.name = '-'
                self.sgpa = self.points = self.cgpa = '0'
                Colour.print('Unable to parse, ' + self.roll_num, Colour.RED)
                if (debug):
                    Colour.print(
                        'possibly roll number doesnot exist or site design changed\n'
                        +
                        'contact [email protected] in case the roll number is availabe on site',
                        Colour.RED)
                return None
        except KeyboardInterrupt:
            raise KeyboardInterrupt
        except:
            self.name = '-'
            self.sgpa = self.points = self.cgpa = '0'
            Colour.print(
                'Unable to fetch ' + self.roll_num +
                ', Please check your internet connection', Colour.RED)
            return None
Example #20
0
def install_dependencies(dependency_map, verbose=False):
    supported_distros = _get_supported_distros(dependency_map)
    distro = _recognise_distro(supported_distros)
    if (verbose):
        if (not distro):
            Colour.print(
                'unrecognised distro, please contact [email protected] for support',
                Colour.RED)
        else:
            Colour.print('Distro detected to be ' + distro + ' based',
                         Colour.GREEN)

    all_installed = True

    for d in dependency_map.keys():
        if is_installed(d):
            continue
        rules = dependency_map[d]
        if distro and distro in rules.keys():
            Colour.print('installing ' + d + ' dependency', Colour.GREEN)
            os.system(rules[distro])
            if not is_installed(d):
                Colour.print('please install ' + d + ' dependency manually',
                             Colour.YELLOW)
                Colour.print('try command : ' + rules[distro], Colour.YELLOW)
                all_installed = False
        else:
            Colour.print('Please install ' + d + ' dependency manually',
                         Colour.YELLOW)
            all_installed = False

    return all_installed
Example #21
0
    def dump_output(self, teachers_list, session_list, output_path):
        matrix = [["Name of Faculty Member", "Info"]]
        if debug:
            matrix[0].extend(['_rank', '_total', '_res',
                              '_credits'])  # srbdebug

        dmap = {}  # map to contain count of avg duties of some rank
        rmap = {}  # map to contain count of teachers of some rank
        for teacher in teachers_list:
            rmap[teacher.rank] = 0
            dmap[teacher.rank] = 0
        for teacher in teachers_list:
            rmap[teacher.rank] += 1
            dmap[teacher.rank] += teacher.duties

        def divide(a, b):
            a = int((a * 1000) / b)
            return a / 1000

        for rank in rmap:
            dmap[rank] = divide(dmap[rank], rmap[rank])

        tmap = {}  # map to contain count of room types
        for session in session_list:
            matrix[0].append(session.name)
            for room in session.room_list:
                if room.reserved:
                    continue
                if room.get_type() in tmap:
                    tmap[room.get_type()] += 1
                else:
                    tmap[room.get_type()] = 1

        matrix[0].append("Total")
        matrix[0].append("mail")
        same_day_duties = self._get_same_day_multiple_duties(teachers_list)
        if (same_day_duties): matrix[0].append("s_d_m_d")

        for teacher in teachers_list:
            teachers_row = [teacher.name, teacher.info]
            if teacher.duties != len(teacher.alloted) - len(
                    teacher.alloted_res):
                print(
                    'ERROR: teacher unable to get enough slots as anticipated')
                print(teacher)
                raise Exception(
                    'ERROR: teacher unable to get enough slots as anticipated')
            if debug:
                teachers_row.extend([
                    teacher.rank,
                    len(teacher.alloted),
                    len(teacher.alloted_res),
                    int(teacher._credits),
                ])
            for session in session_list:
                if session.name in teacher.alloted:
                    teachers_row.append(teacher.alloted[session.name])
                else:
                    teachers_row.append('-')
            teachers_row.append(len(teacher.alloted))
            teachers_row.append(teacher.mail)
            if (same_day_duties):
                same_day_duties_t = 0  # compute same day duties per teacher
                sess_set = set()
                for session_name in teacher.alloted.keys():
                    if Session.get_base(session_name) in sess_set:
                        same_day_duties_t += 1
                        continue
                    sess_set.add(Session.get_base(session_name))
                teachers_row.append(same_day_duties_t)
            matrix.append(teachers_row)

        lmap = json.dumps(rmap, indent=3, sort_keys=True)
        Colour.print('rank count : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        lmap = json.dumps(dmap, indent=3, sort_keys=True)
        Colour.print('average duties : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        lmap = json.dumps(tmap, indent=3, sort_keys=True)
        Colour.print('type of rooms : ', Colour.CYAN, end='')
        Colour.print(lmap, Colour.GREEN)

        matrix.extend([[], [], ['', 'rank', 'count', 'avg duties']])
        for key in sorted(rmap):
            matrix.append(['', key, rmap[key], dmap[key]])

        matrix.extend([[], [], ['', 'type of room', 'number']])
        for key in sorted(tmap):
            matrix.append(['', key, tmap[key]])

        if same_day_duties > 0:
            Colour.print('Got ' + str(same_day_duties) + ' same-day-duties',
                         Colour.YELLOW)
            matrix.extend(
                [[], [],
                 ['', 'WARNING:', 'Adv-algo value was ' + str(self.adv)]])
            matrix.extend(
                [['', '', 'You may get teacher duty multiple in a day']])
            matrix.extend(
                [['', '', 'We got ' + str(same_day_duties) + ' such cases']])
            matrix.extend([[
                '', '',
                'Please visit s_d_m_d(same-day-multiple-duties) column for number of such cases per teacher'
            ]])

        matrix.extend(
            [[], [],
             [
                 '', 'Help:',
                 'In case help required please visit help section on website'
             ]])
        matrix.extend([[
            '', '',
            'In case of unsatisfactory results please contact [email protected]'
        ]])
        matrix.extend([[], [], ['', '', 'a srbcheema1 Production']])

        sheet = Tabular(matrix)
        sheet.write_xls(output_path)
Example #22
0
 def verify_file(file_path):
     if(not os.path.exists(file_path)):
         Colour.print('file not found : '+file_path,Colour.RED)
         sys.exit(1)
Example #23
0
    def test(self):
        times = 0
        try:
            while (True):
                if (times % 100 == 0 and times > 0):
                    Colour.print("tested " + str(times), Colour.CYAN)
                elif (times % 10 == 0):
                    Colour.print("tested " + str(times),
                                 Colour.GREEN,
                                 end='\r')

                p = sp.Popen(self.timeout + self.exec3 + ' > .case' +
                             self.idd + '.tester',
                             shell=True)
                p.wait()
                status = p.returncode
                if status == 124:
                    Colour.print('test_gen timed out', Colour.RED)
                    sys.exit(0)
                if status != 0:
                    Colour.print('test_gen runtime_error', Colour.RED)
                    sys.exit(0)

                p = sp.Popen(self.timeout + self.exec1 + ' < .case' +
                             self.idd + '.tester > ' + self.out1,
                             shell=True)
                p.wait()
                status = p.returncode
                if status == 124:
                    Colour.print(self.code1 + ' timed out', Colour.RED)
                    self.print_failed_test()
                    sys.exit(0)
                if status != 0:
                    Colour.print(self.code1 + ' runtime_error', Colour.RED)
                    self.print_failed_test()
                    sys.exit(0)

                p = sp.Popen(self.timeout + self.exec2 + ' < .case' +
                             self.idd + '.tester > ' + self.out2,
                             shell=True)
                p.wait()
                status = p.returncode
                if status == 124:
                    Colour.print(self.code2 + ' timed out', Colour.RED)
                    self.print_failed_test()
                    sys.exit(0)
                if status != 0:
                    Colour.print(self.code2 + ' runtime_error', Colour.RED)
                    self.print_failed_test()
                    sys.exit(0)

                output1 = Code_tester.get_output(self.out1)
                output2 = Code_tester.get_output(self.out2)

                ret, size_diff = comp_files(self.out1, self.out2)
                if size_diff:
                    Colour.print('Output files differ in size', Colour.PURPLE)
                if ret > -1 or size_diff:
                    Colour.print('Difference detected in outputs',
                                 Colour.PURPLE)
                    self.print_failed_test()
                    Colour.print("first difference in line " + str(ret),
                                 Colour.PURPLE)
                    self.print_outputs(output1, output2, ret)
                    self.git_diff()
                    sys.exit(0)

                times += 1
                if (self.maxlim > 0 and times > self.maxlim):
                    Colour.print("passed " + str(self.maxlim) + " testcases ",
                                 Colour.GREEN)
                    break

        except KeyboardInterrupt:
            Colour.print("tested " + str(times), Colour.GREEN)
            Colour.print('exiting safely', Colour.GREEN)
Example #24
0
    def compile_code(self, code):
        base, ext = code.split('\\')[-1].split('/')[-1].split('.')
        binary = '.' + '-'.join(relative_path(code).split('/')[1:]) + '.tester'

        if os_name == 'windows':
            if not ext in ['c', 'cpp', 'java', 'py', 'rb', 'exe', 'txt']:
                Colour.print(
                    'Supports only C, C++, Python, Java, Ruby and cpp-binary as of now.',
                    Colour.RED)
                sys.exit(1)

            compiler = {
                'txt': None,
                'py': None,
                'rb': None,
                'exe': None,
                'c': 'gcc -DONLINE_JUDGE -o ' + binary,
                'cpp': 'g++ -DONLINE_JUDGE -std=c++14 -o ' + binary,
                'java': 'javac -d .'
            }[ext]

            # COMPILE
            if not compiler is None:
                compile_status = os.system(compiler + ' "' + code +
                                           '"')  #spaces in path
                if compile_status != 0:
                    Colour.print('Compilation error.', Colour.RED)
                    os.system(compiler + ' "' + code + '"')  #spaces in path
                    sys.exit(1)

            execute_command = {
                'txt':
                'type "' + code + '"',
                'py':
                'python "' + code + '"',
                'rb':
                'ruby "' + code + '"',
                'exe':
                code,
                'c':
                binary,
                'cpp':
                binary,
                'java':
                'java -DONLINE_JUDGE=true -Duser.language=en -Duser.region=US -Duser.variant=US '
                + base
            }[ext]

        else:  # Not windows
            if not ext in ['c', 'cpp', 'java', 'py', 'rb', 'out', 'txt']:
                Colour.print(
                    'Supports only C, C++, Python, Java, Ruby and cpp-binary as of now.',
                    Colour.RED)
                sys.exit(1)
            compiler = {
                'txt':
                None,
                'py':
                None,
                'rb':
                None,
                'out':
                None,
                'c':
                'gcc -static -DONLINE_JUDGE -g -fno-asm -lm -s -O2 -o ' +
                binary,
                'cpp':
                'g++ -static -DONLINE_JUDGE -g -lm -s -x c++ -O2 -std=c++14 -o '
                + binary,
                'java':
                'javac -d .'
            }[ext]

            # COMPILE
            if not compiler is None:
                compile_status = os.system(compiler + ' \'' + code +
                                           '\'')  #spaces in path
                if compile_status != 0:
                    Colour.print('Compilation error.', Colour.RED)
                    os.system(compiler + ' \'' + code + '\'')  #spaces in path
                    sys.exit(1)

            execute_command = {
                'txt':
                'cat "' + code + '"',
                'py':
                'python3 \'' + code + '\'',
                'rb':
                'ruby \'' + code + '\'',
                'out':
                './' + code,
                'c':
                './' + binary,
                'cpp':
                './' + binary,
                'java':
                'java -DONLINE_JUDGE=true -Duser.language=en -Duser.region=US -Duser.variant=US '
                + base
            }[ext]

        return execute_command