Exemplo n.º 1
0
 def reset():
     db.reset_config(True)
     reload()
     flash('Restore completed', 'info')
     flash('RESTART THE APPLICATION IF SETTINGS FAIL TO BE APPLIED',
           'critical')
     return redirect('/config')
Exemplo n.º 2
0
 def main_dialog(self):
     greeting_text = 'ValHunter'
     print(greeting_text)
     FileModule.init_folders()
     print('Choose type of experiment:')
     experiments_names = ExperimentDescription.get_list_of_experiments_names()
     attempt_index = 0
     selected_index = -1
     for index, experiment_name in enumerate(experiments_names):
         print("    {0}) {1}".format(index+1, experiment_name))
     while attempt_index < 3:
         answer_string = input('Input number of experiment type: ')
         try:
             selected_index = int(answer_string)-1
             if selected_index < len(experiments_names):
                 break
         except:
             pass
         attempt_index += 1
         print('Invalid experiment index. Please, try again.')
     if attempt_index == 3:
         exit()
     else:
         self.__request_general_input_data()
         self.__request_specific_input_data()
         self.__run_experiment(experiments_names[selected_index])
Exemplo n.º 3
0
 def rotate(payload, list, side):
     pic = 0
     for i in range(len(list)):
         if list[i] in payload:
             pic += 1
             # flash(list[i], 'warning')
             db.fileRotate(cfg._destinationFolder, list[i], side)
     flash('Rotating {} pics to {}'.format(pic, side), 'warning')
Exemplo n.º 4
0
	def excecute(self, *args):
		try:
			FileModule.delete_file(self.elmt)
		except PermissionError:
			tkinter.messagebox.showerror(self.params2[0], self.params2[1]) 
		finally:
			pass
		self.close()
Exemplo n.º 5
0
def delErrorPng():
    path = sys.path[0]
    path = path + "/" + "errorScreenShot"
    #windows下的写法
    sys.path.append(curDir + '\\common\\FileModule')
    #mac下的写法
    sys.path.append(curDir + '/common/FileModule')
    import FileModule
    FileModule.delAllFilesOfDir(path)
Exemplo n.º 6
0
 def delete(payload, list):
     # flash(request.get_data(), 'message')
     pic = 0
     for i in range(len(list)):
         if list[i] in payload:
             pic += 1
             # flash(list[i], 'warning')
             db.filePrunning(cfg._destinationFolder, list[i])
     flash('Deleting {} pics'.format(pic), 'warning')
Exemplo n.º 7
0
 def __request_general_input_data(self):
     solver_name = input('Choose index of minisat subtype: \n'
                         '    1) minisat_core\n'
                         '    2) minisat_simp\n'
                         '    3) pmcsat\n'
                         '    4) glucored+march_release\n'
                         '    5) glucan_static\n'
                         '    6) mipisat\n'
                         '    7) minisat_ClauseSplit\n'
     )
     if (solver_name == '1') or (solver_name == 'minisat_core'):
         solver_name = 'minisat_core'
     elif (solver_name == '2') or (solver_name == 'minisat_simp'):
         solver_name = 'minisat_simp'
     elif (solver_name == '3') or (solver_name == 'pmcsat'):
         solver_name = 'pmcsat'
     elif (solver_name == '4') or (solver_name == 'glucored+march_release'):
         solver_name = 'glucored+march_release'
     elif (solver_name == '5') or (solver_name == 'glucan_static'):
         solver_name = 'glucan_static'
     elif (solver_name == '6') or (solver_name == 'mipisat'):
         solver_name = 'mipisat'
     elif (solver_name == '7') or (solver_name == 'minisat_ClauseSplit'):
         solver_name = 'minisat_ClauseSplit'
     else:
         print('Error: Invalid minisat subtype.')
         exit()
     if not FileModule.solver_exist(solver_name):
         print('Error: Solver file does not exist.')
         exit()
     # general ---------------
     self.__solver_file_path = FileModule.get_solver_file_path(solver_name)
     self.__cnf_file_path = FileModule.get_cnf_file_path()
     if len(self.__cnf_file_path) == 0:
         print('Error: Multiple cnf files in cnf folder.')
         exit()
     self.__root_experiments_path = Config.Filepaths.RESULTS_FOLDER
     start_file_name = input('Input start values file name: ')
     self.__start_parameters_values_file_path = Config.Filepaths.START_VALUES_FOLDER + '/' + start_file_name
     if not FileModule.file_exist(self.__start_parameters_values_file_path):
         print('File does not exist.')
         exit()
     self.__max_threads_number = Config.Defaults.USED_CORES_NUMBER
     parameters_templates = SolversDescriptions.get_parameters_template(solver_name, self.__max_threads_number)
     print('Choose handled parameters indexes (or just push ENTER for choose all):')
     for index, parameter in enumerate(parameters_templates):
         print('    ' + str(index) + ') ' + str(parameter))
     handled_indexes_string = input('(separated by commas): ')
     handled_indexes_string = handled_indexes_string.replace(' ', '')
     if len(handled_indexes_string) == 0:
         self.__handled_parameters_indexes = range(len(parameters_templates))
     else:
         self.__handled_parameters_indexes = list()
         for index_string in handled_indexes_string.split(','):
             self.__handled_parameters_indexes.append(int(index_string))
     self.__experiment_name = input('Input experiment name (optional): ')
Exemplo n.º 8
0
 def main_dialog(self):
     greeting_text = 'ParametersTester'
     print(greeting_text)
     FileModule.init_folders()
     solver_name = UI.__request_solver_name()
     timeout = UI.__request_solving_timeout()
     handled_parameters = UI.__request_handled_parameters(solver_name, Config.Defaults.USED_CORES_NUMBER)
     active_parameters_values = UI.__request_parameters_values(SolversDescriptions.get_active_parameters_indexes(solver_name, handled_parameters))
         #len(SolversDescriptions.get_active(solver_name, handled_parameters)))
     UI.__run_solver(solver_name, timeout, handled_parameters, active_parameters_values)
Exemplo n.º 9
0
 def __read_start_parameters(self, new_start_values_filepath=""):
     if new_start_values_filepath is not "":
         self.__start_values_filepath = new_start_values_filepath
         result = list()
         data = FileModule.read_file(self.__start_values_filepath)
         for line in str(data).split('\n'):
             line = line.replace(' ', '')
             line = line.replace('\t', '')
             if len(line) == 0:
                 continue
             words = line.split(',')
             if len(words) == 1:
                 if words[0].lower() in ['true', '1']:
                     result.append(True)
                 elif words[0].lower() in ['false', '0']:
                     result.append(False)
                 else:
                     raise RuntimeError('StartValues.__read_start_parameters: invalid start values bool line: ' + line)
             elif len(words) == 2:
                 range_val = list()
                 for val in words:
                     try:
                         range_val.append(Decimal(val))
                     except:
                         raise RuntimeError('StartValues.__read_start_parameters: invalid start values bool line: '
                                            + line)
                 result.append(range_val)
             else:
                 raise RuntimeError('StartValues.__read_start_parameters: invalid start values line: ' + line)
     else:
         result = Defaults.DEFAULT_PARAMETERS_VALUES[self.__solver_name]
     return result
Exemplo n.º 10
0
 def __init__(self,
              solver_file_path,
              cnf_file_path,
              reports_folder_path,
              threads_number,
              handled_parameters_indexes,
              # количество = количеству обрабатываемых активных параметров (лишних значений нет)
              start_parameters_values,
              max_delta,
              max_hamming_distance,
              min_hamming_distance=1):
     self.__solver_name = FileModule.get_file_name(solver_file_path)
     self.__solver_file_path = solver_file_path
     self.__cnf_file_path = cnf_file_path
     self.__reports_folder_path = reports_folder_path
     self.__handled_parameters_indexes = handled_parameters_indexes
     # start_parameters_values это массив, элементы которого могут быть:
     # bool значением для параметра типа BOOL
     # кортежем из 2-х double для параметра типа RANGE
     self.__start_parameters_values = start_parameters_values
     self.__last_parameters_values_tuple = list()
     self.__parameters_templates = SolversDescriptions.get_handled_parameters_template(self.__solver_name,
                                                                                       threads_number,
                                                                                       handled_parameters_indexes)
     parameters_classes = self.__create_parameters_classes()
     self.__max_delta = max_delta
     self.__values_factory = ParametersValuesFactory(parameters_classes,
                                                     max_delta,
                                                     max_hamming_distance,
                                                     min_hamming_distance)
Exemplo n.º 11
0
 def _process_results(self, sub_experiments_times):
     results_file_data = "Time: " + str(time.time()-self._time_of_start) + "\n"
     index = 0
     for i in range(self._number_of_experiments_produced):
         work_time = sub_experiments_times[i]
         parameters_values = self._best_results[i][0]
         time_of_solving = self._best_results[i][1]
         if index == 0:
             results_file_data += "On defaults. Best time = " \
                                  + str(time_of_solving) + ".  Parameters values: " + str(parameters_values) + "\n"
         else:
             if time_of_solving is None:
                 break
             results_file_data += "Iteration №" + str(index) + ". Summary time = " + str(work_time) + ". Best time = " \
                                  + str(time_of_solving) + ". Parameters values: " + str(parameters_values) + "\n"
         index += 1
     FileModule.create_file(self._reports_folder_path + 'RESULTS.txt', results_file_data)
Exemplo n.º 12
0
 def list_disk(self):
     """
         Lists every connected devices on the computer
     """
     L = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     name = ""
     for d in L:
         if os.path.isdir(d + ':/'):
             drives.append(d)
     for i in drives:
         if FileModule.get_device_name(i)=="":
             name = LEFT_SIDE_WORDS[8]
         else:
             name = FileModule.get_device_name(i)
         button_text = '{0} ({1}:)'.format(name,i)
         di = Button(self.disk_frame, text=' {}'.format(button_text), border=0, highlightbackground= COLORS[1], anchor='nw', command=lambda j=button_text: self.explore_disk_dispatcher(j),relief=PARAMS[1], bg='white')
         di.pack(side = TOP,fill=X)
         di.config(image=self.disk, compound= LEFT)
         drives_buttons.append(di)
Exemplo n.º 13
0
 def __run_solver(solver_name, timeout, handled_parameters, active_parameters_values):
     pm = ParametersModule(FileModule.get_solver_file_path(solver_name),
                           Config.Filepaths.RESULTS_FOLDER,
                           Config.Defaults.USED_CORES_NUMBER,
                           handled_parameters,
                           active_parameters_values)
     tl = ThreadsLauncher(pm, Config.Defaults.USED_CORES_NUMBER, timeout, 0.5,
                          functools.partial(UI.__save_solver_output_data,
                                            Config.Filepaths.RESULTS_FOLDER))
     tl.run()
     UI.__process_results(tl.get_results(), timeout)
Exemplo n.º 14
0
 def __init__(self,
              solver_file_path,
              cnf_file_path,
              root_experiments_path,
              start_parameters_values_file_path,
              max_delta,
              max_hamming_distance,
              restarts_number,
              max_threads_number,
              handled_parameters_indexes,
              experiment_name=''):
     ExperimentDescription.__init__(self,
                                    solver_file_path,
                                    cnf_file_path,
                                    root_experiments_path,
                                    start_parameters_values_file_path,
                                    handled_parameters_indexes,
                                    max_threads_number,
                                    experiment_name)
     self._max_delta = max_delta
     self._max_hamming_distance = max_hamming_distance
     self._restarts_number = restarts_number
     self._number_of_experiments_produced = 0
     self._start_parameters_values = self.get_start_parameters_values()
     experiment_name_folder = (self._experiment_name + '/') if len(self._experiment_name) != 0 else ""
     solver_name = FileModule.get_file_name(self._solver_file_path)
     cnf_name = FileModule.get_file_name(self._cnf_file_path)
     self._reports_folder_path = self._root_experiments_path \
         + "SimpleExperiment/" \
         + experiment_name_folder \
         + solver_name + '/' \
         + cnf_name + '/' \
         + ExperimentDescription.get_current_time_string() + '/'
     FileModule.create_folder(self._reports_folder_path)
     print("Calculating solver timeout...")
     self._solver_timeout = self._get_solver_timeout()
     print("Solver timeout = " + str(self._solver_timeout) + " seconds")
     # (parameters_values, time)
     self._best_results = list()
     self._best_results.append((self._get_default_parameters_values(), self._solver_timeout))
Exemplo n.º 15
0
	def excecute(self, *args):
		if self.new_name_entry.get() !='' and FileModule.checker(self.new_name_entry.get()):
			try:
				os.chdir(os.path.split(self.file)[0])
				if os.path.isdir(self.file):
					os.rename(os.path.split(self.file)[1], self.new_name_entry.get())
				elif os.path.isfile(self.file):
					try:
						if FileModule.get_file_extension(self.file) == FileModule.get_file_extension(self.new_name_entry.get()):
							os.rename(os.path.split(self.file)[1], self.new_name_entry.get())
						elif FileModule.get_file_extension(self.new_name_entry.get()) == '':
							os.rename(os.path.split(self.file)[1], self.new_name_entry.get()+'.'+FileModule.get_file_extension(self.file))
						else:
							req = tkinter.messagebox.askokcancel(self.params1[2],self.params1[3])
							if req:
								os.rename(os.path.split(self.file)[1], self.new_name_entry.get())
					except PermissionError:
						tkinter.messagebox.showerror(self.params2[0], self.params2[1])
				else:
					pass
				self.close()
			except FileExistsError:
				tkinter.messagebox.showerror(self.params2[2], self.params2[3])
Exemplo n.º 16
0
	def excecute(self, *args):
		if self.new_name_entry.get() != '' and FileModule.checker(self.new_name_entry.get()):
			if self.typ_folder.get() == 1 and self.typ_file.get() == 0:
				os.chdir(self.file)
				try:
					os.mkdir('{}'.format(self.new_name_entry.get()))
				except FileExistsError:
					tkinter.messagebox.showerror(self.params2[2],self.params2[3])
			elif self.typ_file.get() == 1 and self.typ_folder.get() ==0:
				os.chdir(self.file)
				open('{}'.format(self.new_name_entry.get()),'a').close()
			else:
				pass
			self.close()
Exemplo n.º 17
0
 def __init__(
     self,
     solver_file_path,
     reports_folder_path,
     threads_number,
     handled_parameters_indexes,
     # количество = количеству обрабатываемых активных параметров (лишних значений нет)
     start_parameters_values,
 ):
     self.__solver_name = FileModule.get_file_name(solver_file_path)
     self.__solver_file_path = solver_file_path
     self.__next_cnf_index = 0
     self.__current_cnf = ""
     self.__cnf_files_paths = FileModule.get_cnf_file_path()
     self.__reports_folder_path = reports_folder_path
     self.__handled_parameters_indexes = handled_parameters_indexes
     # start_parameters_values это массив, элементы которого могут быть:
     # bool значением для параметра типа BOOL
     # double значением для параметра типа RANGE
     self.__start_parameters_values = start_parameters_values
     self.__parameters_templates = SolversDescriptions.get_handled_parameters_template(
         self.__solver_name, threads_number, handled_parameters_indexes
     )
Exemplo n.º 18
0
 def add(self,path,ext):
     """
         Searchs every file in @path which ends with blank extention @ext and displays them in @resultDisplay_frame
     """
     
     #------------------------------------
     #   Screen splash     
     #------------------------------------
     self.show_splash()
     #------------------------------------
     
     res = FileModule.findFileByExtension(path, ext)[0]
     self.file_number['text'] = '{0} {1}'.format(len(res), MAIN_WORDS[4])
     if res == []:
         tkinter.messagebox.showwarning(MAIN_WORDS[5], MAIN_WORDS[6])
     else:
         for f in res:
             try:
                 self.resultDisplay_frame.insert(END,'{}'.format(f))
             except TclError:
                 pass
     search_path = FileModule.findFileByExtension(path, ext)[1]
     self.destroy_splash()
Exemplo n.º 19
0
    def create_secret_seed(self, scheduler):
        slot, seconds_till_the_next_slot = self.get_current_slot()

        dd = datetime.now() + timedelta(seconds=(7 - slot + 4) * 10 + seconds_till_the_next_slot)

        scheduler.add_job(self.create_secret_seed, 'date', run_date=dd,
                          kwargs={'scheduler': scheduler})
        addresses = {}
        lst_gen = self.last_genesis_block()
        if self.can_vote:
            seed = base64.b64decode(self.my_opening.encode())
            sorted_commitments = sorted(self.commitments, key=lambda k: k['commitment'])
            for comt in sorted_commitments:
                for opn in self.openings:
                    if BlockChain.__validate_commitment(opening=opn, commitment=comt):
                        address = BlockChain.get_address_by_public_key(lst_gen, opn['public_key'])
                        if address not in addresses:
                            addresses[address] = base64.b64decode(opn['opening'].encode())
                            seed = BlockChain.xor(base64.b64decode(opn['opening'].encode()), seed)
            self.seed = base64.b64encode(seed).decode('utf-8')
            epoch = self.get_current_epoch()[0]
            slot = self.get_current_slot()[0]
            self.my_seeds[epoch+1] = copy.deepcopy(self.seed)

            write_seed_to_file = {
                'epoch': epoch,
                'slot': slot,
                'seed': self.seed,
                'openings': addresses
            }
            FileModule.append_secrets_to_file(self.my_profile.address.split(':')[2].split('/')[0], write_seed_to_file)

        self.can_vote = False
        self.broadcasted_openings = {}
        self.broadcasted_commitments = {}
        self.openings.clear()
        self.commitments.clear()
Exemplo n.º 20
0
 def __request_solver_name():
     solvers_names = FileModule.get_solvers_names()
     output_string = 'Choose solver (index or name): \n'
     for index, solver_name in enumerate(solvers_names):
         output_string += '\t' + str(index+1) + ') ' + solver_name + '\n'
     user_input = input(output_string)
     if UI.__is_int(user_input):
         solver_index = int(user_input)-1
         if (solver_index >= 0) and (solver_index < len(solvers_names)):
             return solvers_names[solver_index]
         else:
             print('Error: Invalid solver index.')
             exit()
     elif solvers_names.count(user_input) == 1:
         return user_input
     else:
         print('Error: Invalid solver name.')
         exit()
Exemplo n.º 21
0
 def run(self):
     working_instances_number = 0
     list_of_working_instances = list()  # contains tuples: (solver_instance, output_pipe, cnf_name)
     while True:
         if self.__parameters_module.has_new_parameters_list() and \
                 (working_instances_number < self.__threads_number):
             parameters_list = self.__parameters_module.get_parameters_list()
             cnf_name = FileModule.get_file_name(self.__parameters_module.get_last_cnf_file_path())
             print("Run instance: " + self.__parameters_module.get_progress_string())
             self.__run_solver_instance(list_of_working_instances,
                                        parameters_list,
                                        cnf_name)
             working_instances_number += 1
         elif working_instances_number == 0:
             break
         working_instances_number = self. \
             __check_instances_on_finish(list_of_working_instances, working_instances_number)
         time.sleep(self.__sleeping_time)
Exemplo n.º 22
0
 def __init__(self,
              solver_file_path,
              cnf_file_path,
              reports_folder_path,
              threads_number,
              handled_parameters_indexes,
              start_parameters_values,
              max_delta):
     self.__solver_name = FileModule.get_file_name(solver_file_path)
     self.__solver_file_path = solver_file_path
     self.__cnf_file_path = cnf_file_path
     self.__reports_folder_path = reports_folder_path
     self.__handled_parameters_indexes = handled_parameters_indexes
     self.__start_parameters_values = start_parameters_values
     self.__max_delta = max_delta
     self.__last_parameters_values_tuple = list()
     self.__parameters_templates = SolversDescriptions.get_handled_parameters_template(self.__solver_name,
                                                                                       threads_number,
                                                                                       handled_parameters_indexes)
     parameters_classes = self.__create_parameters_classes()
     self.__values_factory = RandomParametersValuesFactory(parameters_classes)
     self.__stop = False
Exemplo n.º 23
0
    def generateTreeStructure(path):

        tree_map = {}

        for root, dir, file in os.walk(path):
            tree_files_in_path = []

            for i in dir:
                path_to_dir = root + '\\' + i
                directory_temp = dm.Directory(i, path_to_dir,
                                              os.path.getmtime(path_to_dir))
                tree_files_in_path.append(directory_temp)

            for j in file:
                path_to_file = root + '\\' + j
                file_temp = fm.File(j, path_to_file,
                                    os.path.getmtime(path_to_file))
                tree_files_in_path.append(file_temp)

            tree_map[root] = tree_files_in_path

        return tree_map
Exemplo n.º 24
0
 def focus_out(self, *args):
     """
         Focus out the research bar
     """
     self.researchBar_entry.delete(0, END)
     self.researchBar_entry.config(fg='grey')
     dirn = FileModule.get_dirname(self.addressBar_entry.get(), disk_name)
     if dirn == 'Desktop':
         dirn = LEFT_SIDE_WORDS[1]
     elif dirn == 'Pictures':
         dirn = LEFT_SIDE_WORDS[3]
     elif dirn == 'Music':
         dirn = LEFT_SIDE_WORDS[4]
     elif dirn == 'Videos':
         dirn = LEFT_SIDE_WORDS[5]
     elif dirn == 'Downloads':
         dirn = LEFT_SIDE_WORDS[6]
     else:
         pass
     researchBar_text = '{0}: {1}'.format(OTHERS_WORDS[0],dirn)
     if len(researchBar_text)>self.researchBar_entry['width']:
         researchBar_text = researchBar_text[:self.researchBar_entry['width']+1]+'...'
     self.researchBar_entry.insert(0, '{}'.format(researchBar_text))
Exemplo n.º 25
0
 def load_file_info(self, prest):
     """
         Load file in
     """
     try:
         elmt = os.path.join(self.addressBar_entry.get(), self.resultDisplay_frame.get((self.resultDisplay_frame.curselection())))
         selectItem = self.resultDisplay_frame.get((self.resultDisplay_frame.curselection()))
         ext = FileModule.get_file_extension(selectItem).lower()
         if os.path.isdir(elmt):
             self.description_icon_label.config(image=self.folder)
             self.description_type_label.config(text=FILE_NAME[32])
             self.description_size_label.config(text='')
             self.description_date_label.config(text='')
         else:
             if ext=='pdf':
                 self.description_icon_label.config(image=self.pdf_file)
                 self.description_type_label.config(text=FILE_NAME[2])
             elif ext=='mp4' or ext=='avi' or ext=='mkv' or ext=='3gp'or ext=='webm':
                 self.description_icon_label.config(image=self.video_file)
                 self.description_type_label.config(text=FILE_NAME[3]) 
             elif ext=='zip' or ext=='rar'or ext=='tar'or ext=='gz':
                 self.description_icon_label.config(image=self.archive_folder)
                 self.description_type_label.config(text=FILE_NAME[4])
             elif ext=='mp3' or ext=='wav' or ext=='wma' or ext=='ogg' or ext=='m4a':
                 self.description_icon_label.config(image=self.music_file)
                 self.description_type_label.config(text=FILE_NAME[5])
             elif ext=='jpg' or ext=='jpeg' or ext=='png' or ext=='gif':
                 self.description_icon_label.config(image=self.picture)
                 self.description_type_label.config(text=FILE_NAME[6])
             elif ext=='lnk':
                 self.description_icon_label.config(image=self.link)
                 self.description_type_label.config(text=FILE_NAME[7])
             elif ext=='py' or ext=='pyc':
                 self.description_icon_label.config(image=self.python)
                 self.description_type_label.config(text=FILE_NAME[8])
             elif ext=='php':
                 self.description_icon_label.config(image=self.php)
                 self.description_type_label.config(text=FILE_NAME[9])
             elif ext=='pptm' or ext=='ppt':
                 self.description_icon_label.config(image=self.powerpoint)
                 self.description_type_label.config(text=FILE_NAME[10])
             elif ext=='html':
                 self.description_icon_label.config(image=self.html)
                 self.description_type_label.config(text=FILE_NAME[11])
             elif ext=='java' or ext=='jar' or ext=='class':
                 self.description_icon_label.config(image=self.java)
                 self.description_type_label.config(text=FILE_NAME[12])
             elif ext=='exe':
                 self.description_icon_label.config(image=self.exe)
                 self.description_type_label.config(text=FILE_NAME[13])
             elif ext=='xlsx' or ext=='csv':
                 self.description_icon_label.config(image=self.excel)
                 self.description_type_label.config(text=FILE_NAME[14])
             elif ext=='css':
                 self.description_icon_label.config(image=self.css)
                 self.description_type_label.config(text=FILE_NAME[15])
             elif ext=='cpp':
                 self.description_icon_label.config(image=self.cpp)
                 self.description_type_label.config(text=FILE_NAME[16])
             elif ext=='c':
                 self.description_icon_label.config(image=self.c)
                 self.description_type_label.config(text=FILE_NAME[17])
             elif ext=='doc' or ext=="docx" or ext=="odt":
                 self.description_icon_label.config(image=self.word)
                 self.description_type_label.config(text=FILE_NAME[18])
             elif ext=='txt':
                 self.description_icon_label.config(image=self.text)
                 self.description_type_label.config(text=FILE_NAME[19])
             elif ext=='crt':
                 self.description_icon_label.config(image=self.crt)
                 self.description_type_label.config(text=FILE_NAME[20])
             elif ext=='iso':
                 self.description_icon_label.config(image=self.disk_image)
                 self.description_type_label.config(text=FILE_NAME[21])
             elif ext=='dll':
                 self.description_icon_label.config(image=self.dll)
                 self.description_type_label.config(text=FILE_NAME[22])
             elif ext=='h':
                 self.description_icon_label.config(image=self.header)
                 self.description_type_label.config(text=FILE_NAME[23])
             elif ext=='htm':
                 self.description_icon_label.config(image=self.htm)
                 self.description_type_label.config(text=FILE_NAME[24])
             elif ext=='log':
                 self.description_icon_label.config(image=self.log)
                 self.description_type_label.config(text=FILE_NAME[25])
             elif ext=='perl':
                 self.description_icon_label.config(image=self.perl)
                 self.description_type_label.config(text=FILE_NAME[26])
             elif ext=='rpm':
                 self.description_icon_label.config(image=self.rpm)
                 self.description_type_label.config(text=FILE_NAME[27])
             elif ext=='rtf':
                 self.description_icon_label.config(image=self.rtf)
                 self.description_type_label.config(text=FILE_NAME[28])
             elif ext=='sql':
                 self.description_icon_label.config(image=self.sql)
                 self.description_type_label.config(text=FILE_NAME[29])
             elif ext=='xml':
                 self.description_icon_label.config(image=self.xml)
                 self.description_type_label.config(text=FILE_NAME[30])
             elif ext=='deb':
                 self.description_icon_label.config(image=self.deb)
                 self.description_type_label.config(text=FILE_NAME[31])
             else:
                 self.description_icon_label.config(image=self.other_file)
                 try:
                     if ext=='':
                         self.description_type_label.config(text=FILE_NAME[1])
                     else:
                         self.description_type_label.config(text='{0} {1}'.format(FILE_NAME[0],ext.upper()))
                 except AttributeError:
                     pass
             if FileModule.get_date(elmt) == None:
                 self.description_date_label.config(text='')
             if FileModule.get_size(elmt) == None:
                 self.description_size_label.config(text='')
             else:
                 self.description_date_label.config(text='{}'.format(FileModule.get_date(elmt)))
                 self.description_size_label.config(text='{0} : {1} Ko'.format(OTHERS_WORDS[1],FileModule.get_size(elmt)))   
     except TclError:
         pass
Exemplo n.º 26
0
 def copy_job():
     db.copy_job()
     flash('Copy Job completed.', 'warning')
     title = 'New Set of Pictures'
     list = db.getListOfFiles(cfg._destinationFolder, add_path=False)
     return load_pics(list, title=title)
Exemplo n.º 27
0
 def clear():
     db.reset_config(False)
     flash('non-essential content removed. Ready for packaging', 'info')
     return redirect('/config')
Exemplo n.º 28
0
import FileModule
import json
import requests
headers = {'Content-type': 'application/json'}

cont1 = FileModule.get_account_by_port(5000)
cont2 = FileModule.get_account_by_port(5005)

data = {
    'receiver_public_key': cont2['public_key'],
    'amount': 30000,
    'sender_public_key': cont1['public_key'],
    'sender_private_key': cont1['private_key']
}

requests.post(cont1['address'] + 'transactions/new',
              data=json.dumps(data),
              headers=headers)
Exemplo n.º 29
0
 def slideshow():
     list = db.getListOfFiles(cfg._destinationFolder, add_path=False)
     return load_pics(list, page='slideshow.html', title='Slideshow')
# Step1: Open root server
subprocess.Popen('python ../Server.py 5000')
time.sleep(3)
date = datetime.datetime.now()

cont = {'address': 'http://127.0.0.1:5000/'}
_thread.start_new_thread(open_mine, (cont, ))

# Step2: open rest of servers
for port in PORTS:
    subprocess.Popen('python ../Server.py ' + port)
    time.sleep(3)
time.sleep(2)
# Get accounts
for port in range(5000, 5010):
    accounts.append(FileModule.get_account_by_port(port, True))

# distributes the stack
initial_transactions = []

amounts = [25000, 15000, 10000, 5000, 4500, 4000, 3000, 2000, 1000]
for port in range(5001, 5010):
    trans = {
        'receiver_public_key': accounts[port - 5000]['public_key'],
        'amount': amounts[port - 5001],
        'sender_public_key': accounts[0]['public_key'],
        'sender_private_key': accounts[0]['private_key']
    }

    initial_transactions.append(trans)
Exemplo n.º 31
0
 def __process_results(results, timeout):  # results contains tuples: (cnf_name, time_of_solving)
     results_file_data = 'Max time of solving: ' + str(timeout) + ' seconds\n'
     for parameters_values, time_of_solving in results:
         results_file_data += parameters_values + ': ' + str(time_of_solving) + '\n'
     print('\n'+results_file_data)
     FileModule.create_file(Config.Filepaths.RESULTS_FOLDER + '/RESULTS.txt', results_file_data)
Exemplo n.º 32
0
 def __save_solver_output_data(reports_folder_path, output_file_name, output_data):
     FileModule.create_file(reports_folder_path + output_file_name, output_data)
Exemplo n.º 33
0
    def index():
        list = db.getListOfFiles(cfg._destinationFolder, add_path=False)
        if request.method == 'GET':
            return load_pics(list, title='List of Pictures')

        else:
            payload = request.get_data().decode("utf-8")
            # only shows debug if in demo mode
            if cfg._test:
                flash(payload, 'debug')

            if request.form.get('left'):
                rotate(payload, list, 'left')
                title = 'ROTATED Pictures'

            elif request.form.get('right'):
                rotate(payload, list, 'right')
                title = 'ROTATED Pictures'

            elif request.form.get('180'):
                rotate(payload, list, '180')
                title = 'UPSIDE-DOWN Pictures'

            elif request.form.get('favorite'):
                faves = db.common(payload, list)
                flash('FAVORITED {} pics'.format(len(faves)), 'warning')
                db.append_multiple_lines('data/whitelist.txt', faves)
                title = 'FAVORITE Pictures'

            elif request.form.get('delete'):
                delete(payload, list)
                black = db.common(payload, list)
                # Check for common with whitelist
                fave_removed = db.remove_common_from_file(
                    'data/whitelist.txt', black)
                # only shows debug if in demo mode
                if cfg._test:
                    flash('Removed {} Fave pics'.format(len(fave_removed)),
                          'debug')

                flash('BLACKLISTED {} pics'.format(len(black)), 'info')
                db.append_multiple_lines('data/blacklist.txt', black)
                title = 'Remaining Pictures'

            elif request.form.get('copy_job'):
                db.copy_job()
                flash('Copy Job completed.', 'warning')
                title = 'New Set of Pictures'

            else:
                # This should never be triggered
                flash('No option selected, try again.', 'error')
                title = 'List of Pictures'

            list = db.getListOfFiles(cfg._destinationFolder, add_path=False)
            return load_pics(list, title=title)
import FileModule
import json
import asyncio
from aiohttp import ClientSession

headers = {'Content-type': 'application/json'}

account1 = FileModule.get_account_by_port(5001, True)
account2 = FileModule.get_account_by_port(5002, True)
account3 = FileModule.get_account_by_port(5003, True)

trans1 = {
    'receiver_public_key': account2['public_key'],
    'amount': 15000,
    'sender_public_key': account1['public_key'],
    'sender_private_key': account1['private_key']
}

trans2 = {
    'receiver_public_key': account3['public_key'],
    'amount': 15000,
    'sender_public_key': account1['public_key'],
    'sender_private_key': account1['private_key']
}


async def post_text(url, body):
    async with ClientSession() as session:
        async with session.post(url=url, data=body,
                                headers=headers) as response:
            await response.read()
Exemplo n.º 35
0
 def get_solver_file_name(self):
     return FileModule.get_file_name(self._solver_file_path)
Exemplo n.º 36
0
    'address': 'http://127.0.0.1:5000/'
}
_thread.start_new_thread(open_mine, (cont, ))
subprocess.Popen('python Server.py 5001')
time.sleep(2)
subprocess.Popen('python Server.py 5002')
time.sleep(2)
subprocess.Popen('python Server.py 5003')
time.sleep(2)
subprocess.Popen('python Server.py 5004')
time.sleep(3)


for port in range(5000, 5005):
    cont = {
        "cont": FileModule.get_account_by_port(port),
        "amount": 0
    }
    conturi.append(cont)

initial_transactions = []

for port in range(5001, 5005):
    trans = {
        'receiver_public_key': conturi[port-5000]['cont']['public_key'],
        'amount': random.randint(5000,7000),
        'sender_public_key': conturi[0]['cont']['public_key'],
        'sender_private_key': conturi[0]['cont']['private_key']
    }
    conturi[0]['amount'] = conturi[0]['amount'] - trans['amount']
    conturi[port-5001]['amount'] = conturi[port-5001]['amount'] + trans['amount']
Exemplo n.º 37
0
 def __create_output_file_name(self):
     return FileModule.get_file_name(self.__current_cnf)
Exemplo n.º 38
0
subprocess.Popen('python Server.py 5000')
time.sleep(3)
cont = {'address': 'http://127.0.0.1:5000/'}
_thread.start_new_thread(open_mine, (cont, ))
subprocess.Popen('python Server.py 5001')
time.sleep(2)
subprocess.Popen('python Server.py 5002')
time.sleep(2)
subprocess.Popen('python Server.py 5003')
time.sleep(2)
subprocess.Popen('python Server.py 5004')
time.sleep(3)

for port in range(5000, 5005):
    cont = {"cont": FileModule.get_account_by_port(port), "amount": 0}
    conturi.append(cont)

initial_transactions = []

for port in range(5001, 5005):
    trans = {
        'receiver_public_key': conturi[port - 5000]['cont']['public_key'],
        'amount': 15001,
        'sender_public_key': conturi[0]['cont']['public_key'],
        'sender_private_key': conturi[0]['cont']['private_key']
    }
    conturi[0]['amount'] = conturi[0]['amount'] - trans['amount']
    conturi[port -
            5001]['amount'] = conturi[port - 5001]['amount'] + trans['amount']
    initial_transactions.append(trans)
Exemplo n.º 39
0
# Photo Filename Changer
# 사진 파일이름 변환기
# 사진과 파일 이름의 메타데이터를 읽어와 사진을 찍은 시간 순으로 정렬합니다.
# 사진 json 포맷에 있는 내용대로  파일 이름을 수정하는 프로그램입니다.

import os
import FileModule as fmodule
import PhotoModule as pmodule

jsonFile = "config.json"

# get configuration directory and format from json file
pathDir, fileFormat = fmodule.getConfig(jsonFile)

# open file path and find all files int the path
# pathDir = "C:\\Users\\Owner\\Desktop\\photo\\test_file"
files = os.listdir(pathDir)

# print(type(files))

# check the files and make fileList when it is a file, not directory

fileList = []

for fileName in files:
    pathName = os.path.join(pathDir, fileName)
    if os.path.isfile(pathName):
        fileList.append(pathName)

# rename the files to "1.jpg, 2.jpg ..."