def test_srbbank_strict(): if (not on_travis): return a = SrbJson('hello', {'test': { 'debug': False, 'password': None }}, strict=True) a['debug'] = True a['password'] = '******' try: a['help'] = 'it will fail' del a['debug'] assert (False) # it should not reach here except: pass try: b = SrbJson( 'hello', {'test': { 'debug': False, 'password': None, 'good': False }}, strict=True) assert (False) # it should not reach here except: pass
def init_repo(args={},debug=False,init=False): ''' initilize a repo as coolkit repo with default configuration if any parent repo is already initilized then we will just copy the config from there ''' cwd = abs_path(os.getcwd()) home_loc = abs_path('~') root_loc = abs_path('/') now = cwd while(now != home_loc and now != root_loc): if('.coolkit' in os.listdir(now) and os.path.isdir(os.path.join(now,'.coolkit'))): if(debug): print('got .coolkit at ',now) break now = abs_path(os.path.join(now,os.pardir)) if(now == root_loc): Colour.print('Coolkit should be run in path under home directory',Colour.RED) sys.exit(1) if(now == home_loc): SrbJson(cwd+'/.coolkit/config',srbjson.local_template) Colour.print('initialized empty CoolKit repository in '+cwd+'/.coolkit/',Colour.GREEN) elif(now != cwd): verify_folder(cwd+'/.coolkit/') shutil.copy(now+'/.coolkit/config',cwd+'/.coolkit/config') Colour.print('initialized empty CoolKit repository in '+cwd+'/.coolkit/',Colour.GREEN) else: if(init): Colour.print('Already a coolkit repo',Colour.YELLOW) if(not 'c_name' in args or not args['c_name']): contest_name = get_contest_name(cwd.split('/')[-1]) if(not contest_name): args['c_name'] = None else: args['c_name'] = contest_name SrbJson.dump_data(args,cwd+'/.coolkit/config',srbjson.local_template)
def dump_problem(self): ''' dump data, including io ''' for i, inp in enumerate(self.inputs): filename = os.path.join(self.dir, 'io', 'Input' + str(i+1)) verify_file(filename) with open(filename, 'w') as handler: handler.write(inp) for i, out in enumerate(self.outputs): filename = os.path.join(self.dir, 'io', 'Output' + str(i+1)) verify_file(filename) with open(filename, 'w') as handler: handler.write(out) self.hash = path_hash(self.dir +'/io') SrbJson.dump_data({ "hash":self.hash, "is_good":self.is_good, "mult_soln":self.mult_soln, "num_test":self.num_test, "p_title":self.p_title, 'subm':self.subm, 'time_limit':self.time_limit, "h_desc":self.h_desc, "i_desc":self.i_desc, "o_desc":self.o_desc, "p_desc":self.p_desc }, self.dir + "/config", srbjson.prob_template)
def dump_contest(self): SrbJson.dump_data( { "ann_arr": self.announce_arr, "c_title": self.c_title, "is_good": self.is_good, "num_prob": self.num_prob, "p_name_list": self.p_name_list }, self.dir + "/config", srbjson.contest_template)
def _load_problem(self): data = SrbJson(self.dir+'/config',srbjson.prob_template) self.hash = data['hash'] self.is_good = data['is_good'] self.mult_soln = data['mult_soln'] self.num_test = data['num_test'] self.p_title = data['p_title'] self.subm = data['subm'] self.time_limit = data['time_limit'] self.h_desc = data['h_desc'] self.i_desc = data['i_desc'] self.o_desc = data['o_desc'] self.p_desc = data['p_desc'] verify_folder(self.dir + '/io') now_hash = path_hash(self.dir +'/io') if(self.hash != now_hash and self.hash != ""): Colour.print('Warning prob '+self.p_name+' has been modified', Colour.END) self.hash = now_hash self.is_good = False SrbJson.dump_data({"is_good":self.is_good}, self.dir + "/config",srbjson.prob_template) io = os.listdir(self.dir+'/io') if(len(io) != 2* self.num_test): if(len(io)!=0): Colour.print(self.p_name + ' testcases corrupt' + str(io), Colour.RED) self.is_good = False SrbJson.dump_data({"is_good":self.is_good}, self.dir + "/config",srbjson.prob_template) if(self.is_good): # load i/o self.inputs = [''] * self.num_test self.outputs = [''] * self.num_test test_loc = self.dir + '/io' for i in range(self.num_test): with open(os.path.join(test_loc, 'Input' + str(i+1)), 'r') as in_handler: orig_input = in_handler.read().strip().split('\n') orig_input = '\n'.join( [line.strip() for line in orig_input]) self.inputs[i] = orig_input with open(os.path.join(test_loc, 'Output' + str(i+1)), 'r') as out_handler: orig_output = out_handler.read().strip().split('\n') orig_output = '\n'.join( [line.strip() for line in orig_output]) self.outputs[i] = orig_output
def fetch_data(self): cache = SrbJson(cache_path, template={"nith_results": {}}) # load cache if (self.unique_id in cache): item = cache[self.unique_id] self.set_cached_data(item['Name'], item['Gender'], item['Sgpa'], item['Cgpa'], item['Points']) if (self.name != '-' and self.cgpa != '0'): Colour.print('got cached ' + self.unique_id, Colour.BLUE) return self.get_cache() else: Colour.print('Bad cached ' + self.unique_id, Colour.YELLOW) url = "http://" + base_url + "/" + Student.get_c_id( self.roll_num, self.mtech) + 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')[1].find_all('td')[1].text.strip() self.name = self.all_data[0].find_all( 'td')[-1].text.strip() # FIX, bug in site 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.unique_id] = self.get_cache() # store cache Colour.print('fetched successfully ' + self.unique_id, 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.unique_id, 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
def test_srbbank(): if (not on_travis): return a = SrbJson('hello', {'test': {'debug': False, 'password': None}}) a['debug'] = True a['password'] = '******' b = SrbJson('hello', {'test': {'debug': False, 'password': None}}) assert (b['debug'] == True) assert (b['password'] == 'helloworld') a['password'] = '******' assert (b.data['password'] == 'helloworld' ) # it gets updated in file and data of a but not in data of b assert ( b['password'] == 'hello' ) # it gets updated automatically. while accesssing data using operators remove('hello') assert ( b['debug'] == False ) # it gets False value as the file was deleted and it is regenerated again
class Config: MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 587 MAIL_USE_TLS = True conf = SrbJson('~/.config/iblog/config.json') SQLALCHEMY_DATABASE_URI = conf.get('SQLALCHEMY_DATABASE_URI', '') SECRET_KEY = conf.get('SECRET_KEY', 'its_a_secret_i_wont_tell_you') MAIL_USERNAME = conf.get('MAIL_USERNAME', '*****@*****.**') MAIL_PASSWORD = conf.get('MAIL_PASSWORD', '') GOOGLE_OAUTH_CLIENT_ID = conf.get('GOOGLE_OAUTH_CLIENT_ID', '') GOOGLE_OAUTH_CLIENT_SECRET = conf.get('GOOGLE_OAUTH_CLIENT_SECRET', '')
def __init__(self,p_name,c_name,c_type='contest',p_title="",subm=-1): # trivially cached self.c_name = str(c_name) self.c_type = c_type self.p_name = p_name # fetchable variables self.hash = "" self.is_good = False self.mult_soln = False self.num_test = 0 self.p_title = p_title self.subm = subm # cant be fetched from prob page, needs to be done by contest self.time_limit = "" # fetchable long variables self.h_desc = "" self.i_desc = "" self.o_desc = "" self.p_desc = "" # file cached self.inputs = [] self.outputs = [] self.soup = None # non cached self.link = "https://codeforces.com/"+self.c_type+"/"+self.c_name+"/problem/"+self.p_name self.dir = Const.cache_dir + '/'+self.c_type+'/' + self.c_name + "/prob/" + self.p_name SrbJson.dump_data({ "c_name":self.c_name, "c_type":self.c_type, "p_name":self.p_name }, self.dir + "/config", srbjson.prob_template) self._load_problem()
def set_local_config(args={},debug=False): ''' set config to config file. parent config if found creates init if not ''' if(not Args.check_init()): Args.init_repo() cwd = abs_path(os.getcwd()) home_loc = abs_path('~') root_loc = abs_path('/') now = cwd while(now != home_loc and now != root_loc): if('.coolkit' in os.listdir(now) and os.path.isdir(os.path.join(now,'.coolkit'))): if(debug): print('got .coolkit at ',now) break now = abs_path(os.path.join(now,os.pardir)) if(now == root_loc): Colour.print('Coolkit should be run in path under home directory',Colour.RED) sys.exit(1) SrbJson.dump_data(args,now+'/.coolkit/config',srbjson.local_template)
def fetch_data_from_local_config(): Args._verify_init() cwd = abs_path(os.getcwd()) home_loc = abs_path('~') root_loc = abs_path('/') now = cwd while(now != home_loc and now!= root_loc): if('.coolkit' in os.listdir(now) and os.path.isdir(os.path.join(now,'.coolkit'))): break now = abs_path(os.path.join(now,os.pardir)) if(now == root_loc): Colour.print('Coolkit should be run in path under home directory',Colour.RED) sys.exit(1) return SrbJson(now+'/.coolkit/config',srbjson.local_template).data
def dump_data(data,file_name): """ take a LIST of Students and burn it into json file create RAW data from LIST creates totally new file """ jfile = SrbJson(file_name,[]) jfile.data = [] jfile._burn_data_to_file() # force empty rank = 1 for item in data: info = create_info_dict(rank,item) jfile.data.append(info) # using jfile.data instead of jfile to speed up rank +=1 jfile._burn_data_to_file() # required if we are using jfile.data
def _load_contest(self): ''' loads contest from cache if exists else create an empty contest and loads it up also cleans useless folders in prob folder if they aren't in config of p_name_list ''' data = SrbJson(self.dir + 'config', srbjson.contest_template).data self.announce_arr = data['ann_arr'] self.c_title = data['c_title'] self.hash = data['hash'] self.is_good = data['is_good'] self.num_prob = data['num_prob'] self.p_name_list = data['p_name_list'] # problems path = self.dir + '/prob/' verify_folder(path) good_probs = 0 prob_dir_list = [(a if os.path.isdir(path + a) else None) for a in os.listdir(path)] prob_dirs = [] for prob in prob_dir_list: # keep only folders if (prob): prob_dirs += [prob] for a in prob_dirs: self.prob_mapp[a] = Problem(a, self.c_name, self.c_type) if (self.prob_mapp[a].is_good and a in self.p_name_list): # remove waste folders good_probs += 1 else: Colour.print('Removed Bad Problem : ' + a, Colour.RED) shutil.rmtree(self.prob_mapp[a].dir) del self.prob_mapp[a] if (self.num_prob == -1): Colour.print('Contest not configured yet', Colour.YELLOW) self.is_good = False elif (good_probs != self.num_prob): Colour.print( 'expected ' + str(self.num_prob) + ' probs got ' + str(good_probs) + ' good probs', Colour.YELLOW) self.is_good = False
def __init__(self, c_name, c_type='contest', c_title=''): # trivially cached self.c_name = str(c_name) self.c_type = c_type # fetchable variables self.announce_arr = [] self.c_title = c_title self.hash = "" self.is_good = False # loaded fully or not self.num_prob = -1 self.p_name_list = [] # non cached self.dir = Const.cache_dir + '/' + self.c_type + '/' + self.c_name self.link = "https://codeforces.com/" + self.c_type + "/" + self.c_name self.prob_mapp = {} json_file = SrbJson(self.dir + '/config', srbjson.contest_template) json_file['c_name'] = self.c_name json_file['c_type'] = self.c_type self._load_contest() # pick cached data
fname = 'input/' + fname if not _default_room_list and 'room_list' in fname: _default_room_list = abs_path(fname) elif not _default_teachers_list and 'teachers_list' in fname: _default_teachers_list = abs_path(fname) elif not _default_schedule_list and 'schedule_list' in fname: _default_schedule_list = abs_path(fname) for fname in os.listdir(abs_path('./')): if not _default_room_list and 'room_list' in fname: _default_room_list = abs_path(fname) elif not _default_teachers_list and 'teachers_list' in fname: _default_teachers_list = abs_path(fname) elif not _default_schedule_list and 'schedule_list' in fname: _default_schedule_list = abs_path(fname) _config_template = \ { 'room_list':_default_room_list, 'teachers_list':_default_teachers_list, 'schedule_list':_default_schedule_list, } config_json = SrbJson(config_file_path,_config_template) for var_name in ['room_list','teachers_list','schedule_list']: if config_json[var_name] and not os.path.isfile(config_json[var_name]): config_json[var_name] = None if not config_json[var_name]: config_json[var_name] = _config_template[var_name]
from random import randint from srblib import SrbJson work_ratio_template = { 1: 100, 2: 150, 3: 200, 4: 250, 5: 300, } work_ratio = SrbJson('~/.config/exam_scheduler/work_ratio.json', work_ratio_template) def credits_calc(rank, workratio=work_ratio): try: rank = int(rank) except: raise Exception("Rank should be integer") if rank == 0: return 9999999 return (100 * workratio["1"]) / workratio[str(rank)] def randomize(arr): n = len(arr) for i in range(0, n - 1): j = randint(i, n - 1) arr[i], arr[j] = arr[j], arr[i] for i in range(n - 1, 0, -1): j = randint(0, i) arr[i], arr[j] = arr[j], arr[i]
from srblib import on_srbpc, on_travis from srblib import SrbJson srb_predictor = SrbJson('~/.config/coolkit/config', { "coolkit": {} }).get('srb_predictor', True) def get_contest_name(folder): ''' takes parameter folder which is name of folder you are in returns contest number if possible to detect if can't determine then return None ''' if (on_srbpc or on_travis or srb_predictor): # I kept for me, you too can use this ready made function return srb_contest_name(folder) ''' to use my function just uncomment the line below this ''' # return srb_contest_name(folder) return None def get_problem_name(file_name): ''' takes parameter file_name which is name of file you are working with returns problem name if possible to detect if can't determine then return None ''' if (on_srbpc or on_travis or srb_predictor):
#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK import os from srblib import SrbJson from flask import Flask, redirect, url_for from flask_dance.contrib.google import make_google_blueprint, google app = Flask(__name__) config = SrbJson('~/.config/iblog/config.json') app.secret_key = "secretisgood" app.config["GOOGLE_OAUTH_CLIENT_ID"] = config.get('GOOGLE_OAUTH_CLIENT_ID', '') app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = config.get( 'GOOGLE_OAUTH_CLIENT_SECRET', '') google_bp = make_google_blueprint( offline=True, redirect_url='/google_login', scope=[ "https://www.googleapis.com/auth/plus.me", "openid https://www.googleapis.com/auth/userinfo.email", ]) app.register_blueprint(google_bp, url_prefix="/google_login" ) # url prefix should be same as registered there. """ if url_prefix is xyz here then Authorized redirect URLs will be xyz/google/authorized """
def fetch_global_config(): return SrbJson('~/.config/coolkit/config',srbjson.global_template)
from srblib import SrbJson from srblib import debug, on_travis cache_path = '~/.config/nith_results/cache.json' _limits_template = \ { 'base_year' : None, 'default_no_of_std' : 99, 'iiitu_no_of_std' : 70, 'dual_no_of_std' : 70, 'max_seats' : 120, 'base_url': "" } _limits = SrbJson('~/.config/nith_results/limits.json', _limits_template) base_year = _limits['base_year'] base_url = _limits['base_url'] if (not base_year): if on_travis: base_year = 19 else: base_year = int( input( 'Please enter base-year(year of 1st year student right now) ex:19 ' )) _limits['base_year'] = base_year if (base_url == ""): if on_travis: base_url = "14.139.56.15" else:
fname = 'input/' + fname if not _default_room_list and 'room_list' in fname: _default_room_list = abs_path(fname) elif not _default_teacher_list and 'teacher_list' in fname: _default_teacher_list = abs_path(fname) elif not _default_schedule_list and 'schedule_list' in fname: _default_schedule_list = abs_path(fname) for fname in os.listdir(abs_path('./')): if not _default_room_list and 'room_list' in fname: _default_room_list = abs_path(fname) elif not _default_teacher_list and 'teacher_list' in fname: _default_teacher_list = abs_path(fname) elif not _default_schedule_list and 'schedule_list' in fname: _default_schedule_list = abs_path(fname) _config_template = \ { 'room_list':_default_room_list, 'teacher_list':_default_teacher_list, 'schedule_list':_default_schedule_list, } config_json = SrbJson(config_file_path,_config_template,strict=True) for var_name in ['room_list','teacher_list','schedule_list']: if config_json[var_name] and not os.path.isfile(config_json[var_name]): config_json[var_name] = None if not config_json[var_name]: config_json[var_name] = _config_template[var_name]