Example #1
0
 def addImageTextBoxesToDialog(self, query, txtEnd, imageList,
                               oDialogModel):
     y = 15  #add image checkboxes to the dialog
     count = 1
     x = 105
     for img in imageList:
         print(img)
         imageFilePath = fh.FileHandler().createImageFilePathForTheQuery(
             query, img)
         imageURL = "file:///" + imageFilePath
         thmbFilePath = fh.FileHandler(
         ).createThumbImageFilePathForTheQuery(query, img)
         thumbImageURL = "file:///" + thmbFilePath
         print(imageURL)
         im = Image.open(imageFilePath)
         dim = 150
         size = (dim, dim)  #create thumbnails
         im.thumbnail(size, Image.ANTIALIAS)
         im.save(thmbFilePath)
         imtb = Image.open(thmbFilePath)
         self.createCheckBox(oDialogModel, img, img, 150, 75, x, y)
         self.setCheckBoxImageURL(oDialogModel, img, thumbImageURL)
         x += 80
         count += 1
     return x
Example #2
0
 def Backup(self, params):
     #Backup/Restore encrypted files to new path
     
     #Determine if backup or restore requested
     backup = IsRequestBackup(params)
     if(backup == None):
         console.out(61)
         return None
     
     #Now need to determine file location
     backupPath = DetermineBackupPath(params)
     if(backupPath == None): #Check if user aborted backup
         return None
         
     #Backup files
     if(backup):
         returnList = File.PerformBackup(backupPath)
         if(len(returnList) == 0):
             console.out(65)            
     else:
         returnList = File.PerformRestore(backupPath)
         if(len(returnList) == 0):
             console.out(66)
     if(len(returnList) > 0 and returnList[0] != "FAIL"):
         console.outs([67,68])
         for failedCopy in returnList:
             failedCopy = failedCopy.replace("\\", "/") #Clean up file path string
             console.SlowPrint(failedCopy, 0.02, ">")
     console.out(2)
Example #3
0
def loadfiles():
    Dictionary.loadDictionary('dictionary')
    global suffixes, modals, person, imperitive

    file = FileHandler.loadFile("Resources/person.csv", "r")
    for line in file:
        line = line.strip()
        p = line.split(',')
        print(len(p))
        person.update({p[0]: [p[1], p[2], p[3], p[4], p[5], p[6], p[7]]})
    file.close()
    file = FileHandler.loadFile("Resources/modals.csv", "r")
    for line in file:
        line = line.strip()
        p = line.split(',')
        modals.update({p[0]: [p[1]]})
    file.close()
    file = FileHandler.loadFile("Resources/suffixes.csv", "r")
    for line in file:
        line = line.strip()
        p = line.split(',')
      #  print(str(p))
        suffixes.update({p[0]: [p[1]]})
    file.close()
    file = FileHandler.loadFile("Resources/imperative.csv", "r")
    for line in file:
        line = line.strip()
        p = line.split(',')
        imperitive.update({p[0]: [ p[1], p[2], p[3], p[4]]})
Example #4
0
def addSoal():
    curses.endwin()
    print("Welcome to Add Word Console.")
    print("Available Commands:  console_help, console_exit, console_cls")
    print("type your word to be added to the game! The character limit is 16 Characters")
    print("type console.help to display this message again")
    while(True):
        command = input(">").lower()
        if command ==  "console_help":
            print("Available Commands:  console_help, console_exit, console_cls")
            print("type your word to be added to the game!")
            print("type console.help to display this message again")
        elif command == "console_exit":
            main()
        elif command == "console_cls":
            os.system("cls")
        elif command == "console_guagoblok":
            cheat = True
        else:
            try:
                if len(command) > 16:
                    print("Character limit is 16 Characters!")
                elif not command.isalpha() and not command == "" and not command.isspace():
                    print("You cannot input numbers and/or symbols!")
                elif command.isspace() or command == "":
                    continue
                else:
                    FileHandler.addWord(command)
                    print("Word", command, "added Succesfully!")
            except IOError:
                print("Error in Writing File. (Unable to open file) Exception: IOError")
Example #5
0
 def upload_file(login, password):
     '''
     Uploads files 
     '''
     db_obj=DataBaseCl()
     if db_obj.checkauth(login, password):
         if request.method == 'POST':
             f = request.files['file_name']
             if f: 
                 if f.filename.split('.')[1] in ALLOWED_EXTENSIONS:
                     filename = secure_filename(f.filename)
                     path_f=os.path.join(app.config['UPLOAD_FOLDER'], filename)
                     f.save(path_f)
                     req=FileHandler(path_f)
                     res=req.parse_file()
                     return jsonify( { 'result:' : res} )
             else:
                 return 'not upload' 
         return '''
         <!doctype html>
         <form action="" method=post enctype=multipart/form-data>
               <p><input type=file name= file_name> 
              <input type=submit value=Upload>
         </form>    
             '''
     else:
         return ('you have no permissions')
Example #6
0
 def GenPass(self, params):
     wait = True
     #Generate password
     while(wait):
         generatedPassword = enc.GeneratePassword(params)
         console.out(48)
         console.SlowPrint(generatedPassword, 0.03, ">")
         console.out(49)
         inputVal = input("")
         if(inputVal.lower()=="n" or inputVal.lower()=="no"):
             wait = False
     #Give option to save password
     
     console.out(50)
     inputVal = input("")
     if(inputVal.lower()=="y" or inputVal.lower()=="yes"):
         titleSelected = False
         passTitles = File.GetPasswordTitles(self.GetFileEncryptionKey())
         while(not titleSelected):
             console.out(51) #Get user to enter a title
             inputVal = input("")
             if(inputVal.lower() == "c"):
                 return None #Quit routine
             if(passTitles == None or inputVal not in passTitles):
                 titleSelected = True            
         
         state = File.AmmendPasswordFile(inputVal, generatedPassword, self.GetFileEncryptionKey())
         if(state):
             console.PrintList([38, "Use 'EditPass' to add more information to this stored password"], 0.02)
         else:
             console.out(39)    
         
     console.out(2)
def procesaMensajesDeArchivo(mensajes):
    if mensajes is not None and len(mensajes):
        for mensaje in mensajes:
            textoMensaje = mensaje["mensaje"]
            if "archivo" in mensaje:
                textoMensaje = os.path.join("Archivos", textoMensaje)
                contenidoArchivo = mensaje["archivo"]
                FileHandler.stringAArchivo(textoMensaje, contenidoArchivo)
Example #8
0
 def populateList(self):
     file = FileHandler("Items")
     attributes = file.read()
     tokenizer = StringTokenizer('\n')
     tokenizer.setString(attributes)
     while (not tokenizer.atEnd()):
         self.items.append(Item(tokenizer.getToken()))
         self.itemCount = self.itemCount + 1
Example #9
0
 def EditTitle(self, params):
     oldTitle = params[0]
     newTitle = params[1]
     indexOfTitle = File.GetPasswordTitle(oldTitle, self.GetFileEncryptionKey())
     state = File.RenamePassTitle(newTitle, indexOfTitle, self.GetFileEncryptionKey())
     if(state):
         console.out(41)
     else:
         console.out(42)
Example #10
0
def registerMod(path_to_folder, name, mod_version, game_version):
    # Placing a file in every mod directory to register mods
    # And setting the mod visible to this program
    dirs = os.listdir(path_to_folder)

    for path in dirs:
        path2 = path_to_folder + path

        fh.writeFile(path2 + "/modmanager.txt", name + "|" + mod_version + "|" + game_version + "|" + path)
Example #11
0
def serialize_to_file(elements, path):
    """Serialize list of element into xml file

        :param path: The path to the new xml file.
        :type path: str
        :param elements: The list of elements.
        :type elements: list
        :rtype: None
    """
    FileHandler.write_to_file(serialize(elements, 0), path)
Example #12
0
 def saveImage(self):
   print("Saving image")
   if not self.yeast:
     data = self.getData()
     self.prefix = FileHandler.savePADImage(self.rawImage, self.finalImage, data, self.qr)
   if self.yeast and self.foundYeast:
     FileHandler.saveYeastImage(self.finalImage)
   elif self.yeast and self.manualFoundYeast:
     FileHandler.saveYeastWhiteImage(self.whiteImage, self.finalImage)
   self.restartCapture()
Example #13
0
def save_xyz_uv(input_line, hmatrix, camEnv, name, destination):
    lines = calcUVXYZ(input_line, hmatrix, camEnv)
    pxcoords = lines[1][1]
    xyzcoords = lines[0][1]

    xyz_name = name + "xyzcoords.txt"
    uv_name = name + "uvcoords.txt"
    # Write line coordinates to txt file
    FileHandler.writeLineCoords([pxcoords.tolist()], [xyzcoords.tolist()],
                                name, destination + uv_name,
                                destination + xyz_name)
Example #14
0
 def GetPass(self, params):
     #Get the password from titleName
     titleIndex = File.GetPasswordTitle(params[0], self.GetFileEncryptionKey())
     if(titleIndex >= 0):
         console.out(47)
         console.Wait(0.1)
         console.PrintList(File.GetPassFromFile(titleIndex, self.GetFileEncryptionKey()), 0.03, ">")
         console.out(2)
         self.toClear = True
     else:
         console.outs([43,2])  
Example #15
0
 def runUpload(self):
   print("Starting Upload...")
   status = 'Uploading... '
   data = FileHandler.getMetaData(self.instance, self.sample)
   data['uploaded'] = status
   self.updateReview(status, self.review.pushButton_2)
   FileHandler.uploadImage(self.instance, self.sample)
   data = FileHandler.getMetaData(self.instance, self.sample)
   status = data['uploaded']
   self.updateReview(status, self.review.pushButton_2)
   print("Done with upload")
Example #16
0
 def do_GET(self):#A handler for all the GET requests the server recieves
     if self.path == "/Login":#checks the path of the request
         LoginHandler.processLogin(self)#passes the /Login requests onto the Login Handler script
     elif self.path == "/SaveNote":
         FileHandler.SaveNote(self)#passes the/SaveNote File request to the save file handler script
     elif self.path == "/LoadNote":
         FileHandler.LoadNote(self)#passes the /LoadNote requests to the load handler
     elif self.path == "/ListNotes":
         FileHandler.ListNotes(self)#passes to the handler
     else:#if the path doesn't match any of the routes that I've set up it will return a 404 error meaning that path couldn't be found
         self.send_response(404)
Example #17
0
def DoMake(command):
    """calls fh.MakeTemplate()"""
    global currentFolder
    try:
        command = command[1].split(' ')
        if (len(command) > 1):
            fh.MakeTemplate(command[0], currentFolder, extension=command[1])
        else:
            fh.MakeTemplate(command[0], currentFolder)
    except Exception as e:
        print(e)
Example #18
0
def load():
    """
    read input file and self storage
    """
    N = 5
    piece_type, previous_board, board = FileHandler.readInput(N)
    q_table = FileHandler.readQTable()
    player = GreedyPlayer(q_table)
    action = player.get_input(piece_type, previous_board, board)
    FileHandler.writeQTable(player.history)
    return action
Example #19
0
 def showSamples(self, a, b):
   if a is not None:
     instance = a.text()
     sample = self.review.listWidget.currentItem().text()
     metadata = FileHandler.getMetaData(instance, sample)
     imgPath = FileHandler.getSavedImage(instance, sample)
     self.review.label.setPixmap(QPixmap(imgPath))
     self.setButton(metadata, self.review.pushButton_4, 'sample_name')
     self.setButton(metadata, self.review.pushButton_7, 'category_name')
     self.setButton(metadata, self.review.pushButton_5, 'test_name')
     self.setClickableButton(metadata, self.review.pushButton, 'sample_pred')
     self.setClickableButton(metadata, self.review.pushButton_2, 'uploaded')
Example #20
0
    def populateFromFile(self):
        self.songs = []
        self.songCount = 0

        fileObj = FileHandler(self.directory, "Songs")
        fileString = fileObj.read()
        tokenizer = StringTokenizer(NEWLINE)
        tokenizer.setString(fileString)
        while not tokenizer.atEnd():
            self.songCount = self.songCount + 1
            token = tokenizer.getToken()
            index = token.index("/,")
            name = token[index + 2:]
            path = token[:index + 1]
            self.songs.append(Song(name, path))
Example #21
0
def updateMods(csv_file, directory):
    # Updates a specific mod
    available_mods = []
    installed_mods = []

    available_csv = fh.getCSVList("mods.csv")
    installed_csv = fh.getCSVList("installed_mods.csv")

    dirs = os.listdir(directory)

    for i in available_csv[0]:
        available_mods.append(i)

    for j in installed_csv[0]:
        installed_mods.append(j)
    print(installed_mods + " | " + available_mods)
Example #22
0
 def CreateModuleVariable(self,
                          variableName,
                          variableDescription,
                          variableType,
                          variableMode,
                          value=None):
     self.__ValidateArgs()
     # Validating Variable Type
     if variableMode == "Internal":
         raise err.Conflict(
             "A Variable with the mode '{0}' is not support by Modules !".
             format(variableMode))
         return None
     # Setting Value
     if variableMode != "Static":
         value = None
     jsonContent = self.OpenModule()
     # Validating Uniquness
     if variableName in jsonContent["ModuleVariables"]:
         raise err.Conflict(
             "A Module Variable with the name '{0}' already exists !".
             format(variableName))
         return None
     else:
         jsonContent = self.OpenSchema()
         jsonContent["Modules"][
             self.moduleName]["ModuleVariables"][variableName] = (
                 js.VariableJSON(variableName, variableDescription,
                                 variableType, variableMode, value))
         fl.Write(self.schemaMetaData, js.Dump(jsonContent), True)
         return "Variable '{0}' created successfully !".format(variableName)
Example #23
0
def run(state, move_num, isPlayerMove):
    #Allow the computer to make it's move
    if not isPlayerMove:
        state = computerTurn(state, move_num)
        move_num += 1

    #Save variables to be used later
    FileHandler.saveVariable("State", state)
    FileHandler.saveVariable("Move", str(move_num))

    #Set up the window
    wn = Constants.WINDOW
    wn.onclick(place_piece)
    wn.onkey(wn.bye, "space")
    wn.listen()
    wn.mainloop()
Example #24
0
 def ShowPasswords(self, params):
     checkItem = 0        
     searchGroup = "NULL"
     if(len(params) > 0 and not str.isdigit(params[0])):
         searchGroup = params[0]    
         checkItem = 1
         
     titleList = File.GetPasswordTitles(self.GetFileEncryptionKey(), searchGroup)   
     
     if(titleList != None and len(titleList) != 0):
         pageNumber = 1
         pages = math.ceil(len(titleList) / 10)
         #Split titlelist into groups of 10, call by page number (must be int)
         if(len(params) > checkItem and str.isdigit(params[checkItem])):                
             pageNumber = int(params[checkItem])
         if(pageNumber > pages):
             console.outs([36,2])    
         else:
             #Get (up to) 10 results from the requested page
             firstIndex = (pageNumber - 1) * 10
             lastIndex = pageNumber * 10
             if(lastIndex > len(titleList)):
                 showPass = titleList[firstIndex:]
             else:
                 showPass = titleList[firstIndex:lastIndex]
             page = "Viewing page " + str(pageNumber) + " out of " + str(pages) + "."
             displayMessage = 34
             if(searchGroup != "NULL"):
                 displayMessage = "The group '" + searchGroup + "' contains the following:"
             console.PrintList([0, displayMessage, showPass, 2, page,0,2],0.02, ">", [4])            
     else:
         if(searchGroup == "NULL"):
             console.outs([2,35,0,2])
         else:
             console.PrintList([2,"No stored passwords found in the '" + searchGroup + "' group.",0,2], 0.02)
 def CreateProjectVariable(self,
                           variableName,
                           variableDescription,
                           variableType,
                           variableMode,
                           value=None):
     self.__ValidateArgs()
     # Validating Variable Type
     if variableMode != "Static" and variableMode != "Runtime":
         raise err.Conflict(
             "A Variable with the mode '{0}' is not support by Projects !".
             format(variableMode))
         return None
     # Setting Value
     if variableMode != "Static":
         value = None
     jsonContent = self.OpenProject()
     # Validating Uniquness
     if variableName in jsonContent["ProjectVariables"]:
         raise err.Conflict(
             "A Project Variable with the name '{0}' already exists !".
             format(variableName))
         return None
     else:
         jsonContent["ProjectVariables"][variableName] = (js.VariableJSON(
             variableName, variableDescription, variableType, variableMode,
             value))
         fl.Write(self.projectMetaData, js.Dump(jsonContent), True)
         return "Variable '{0}' created successfully !".format(variableName)
Example #26
0
def CreateAccount():
    console.out(16, 0.03)

    askCommand = True
    while (askCommand):
        newUser = input("")
        newPass = ""
        if (not ParseForCommand(newUser)):
            askCommand = False

    doesMatch = False
    while (not doesMatch):
        console.out(21)
        newPass = getpass.getpass("")
        if (not ParseForCommand(newPass)
            ):  #Only run rest of routine if input was not a command
            console.out(22)
            check = getpass.getpass("")

            if (newPass == check):
                doesMatch = True
            else:
                console.out(23)

    newSalt = Encryptor.GenerateSALT()
    encPass = Encryptor.OneWayEncryptor(newPass, newSalt)
    FileHandler.CreateUserAccount(newUser, encPass, newSalt)
Example #27
0
def creerGraphe():
    print("<--------Creer le graphe--------->")
    if os.stat('entrepot.txt').st_size == 0:
        print("Desole le graphe n a pas ete creer")
    else:
        G = fl.fillGraphFromFile('entrepot.txt')

        elarge = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] > 0.5]
        esmall = [(u, v) for (u, v, d) in G.edges(data=True) if d['weight'] <= 0.5]

        pos = nx.spring_layout(G)  # positions for all nodes

        # nodes
        nx.draw_networkx_nodes(G, pos, node_size=700)

        # edges
        nx.draw_networkx_edges(G, pos, edgelist=elarge,
                               width=6)
        nx.draw_networkx_edges(G, pos, edgelist=esmall,
                               width=6, alpha=0.5, edge_color='b', style='dashed')
        # labels
        nx.draw_networkx_labels(G, pos, font_size=20, font_family='sans-serif')

        plt.axis('off')
        plt.savefig("weighted_graph.png")  # save as png
        print("Fichier lu et Graphe Creer")
    print("<-------------Fin-------------->"+'\n')
Example #28
0
def getNotebook(name):
    pnoFolder = os.path.expanduser('~/PNO/')
    try:
        root = fh.Folder(os.path.join(pnoFolder, 'Notebooks/' + name))
    except Exception as e:
        raise e
    return root
Example #29
0
def loadDictionary(language):
    """

    :param language:
    :return:
    """
    global mode
    mode = language
    file = FileHandler.loadFile("Resources/" + language + ".csv", "r")
    for line in file:
        vals = line.split(',')
        # check to make sure their not blank
        if vals[0] == '':
            continue
        value = ""
        for i in range(1, len(vals)):
            if vals[i].strip() != '' and vals[i] is not None:
                value += vals[i].strip() + " ,"
        ret = {vals[0].strip(): value.strip()}
        dictionary.update(ret)

    #create the reverse
    for key, value in dictionary.items():
        vals = value.split(",")
        for v in vals:
           translation.update({v.strip(): key})
    print("**************** Dictionary File Loaded ****************")
    return dictionary
Example #30
0
def generate_queries():
    """Si occupa di istanziare le query a partire dai templates contenuti nel file specificato.
        L'istanza di ogni query avviene nella seguente maniera:
        -si considera un template;
        -si considera la lista di tipi validi per una variabile di tipo;
        -per ciascuna variabile di tipo si considerano le entità appartenenti ai sottotipi del tipo specificato;
        -per ogni entità considerata si controlla se, tra le relazioni, esistono relazioni che rispettano i vincoli
        specificati per le variabili relative alle relazioni;
        -dopo aver ottenuto i tipi validi e le relazioni valide si sostituisce al posto delle variabili del template
        e si ottiene una istanza di query;
        -l'istanza di query viene serializzata assieme al result set ed ai valori di istanza all'interno del file
        di output specificato nel template.
    """
    templates_list = FileHandler.acquire_query_templates_list()
    for template_entry in templates_list:
        type_variables_dict = map_valid_types_to_entities(
            template_entry["valid_types"])
        list_of_lists = []
        for key in type_variables_dict.keys():
            list_of_lists.append(type_variables_dict.get(key))
        for entity_tuple in itertools.product(*list_of_lists):
            dict_to_instantiate = map_dict_keys_tuple(
                type_variables_dict.keys(), entity_tuple)
            # print("voglio istanziare: " + str(dict_to_instantiate))
            instantiate_single_query(dict_to_instantiate, template_entry)
Example #31
0
 def __init__(self, filename):
     self.fileContent = []
     self.curr = None
     self.currIndex = -1
     self.tokens = []
     if not filename:
         return
     if filename[-4:] != "jack":
         raise TypeError("Type error: Should input a .jack script file!")
     fileHandler = FileHandler.FileHandler(filename)
     in_comment = False
     for s in fileHandler.fileContent:
         s = self.removeComment(s)
         if not in_comment and '/*' in s:
             s = s[:s.index('/*')]
             in_comment = True
         elif in_comment and '*/' in s:
             s = s[s.index('*/') + 2:]
             in_comment = False
         elif in_comment:
             continue
         if len(s) > 0:
             self.fileContent.append(s)
     for content in self.fileContent:
         self.parse(content)
Example #32
0
 def textDetailsAboutFormula(
         self, query):  #get the formual text details from file
     fileName = fh.FileHandler().createFilePathForTheQuery(query)
     try:
         f = open(fileName, 'r')
         resArray = f.readlines()
         res = ''.join(resArray)
         f.close()
         textList = []
         waeqr = wap.WolframAlphaQueryResult(res)  #get from titles
         for pod in waeqr.Pods():
             podObject = wap.Pod(pod)
             for subPod in podObject.Subpods():
                 subPodObject = wap.Subpod(subPod)
                 if (subPodObject.Plaintext() != [[]]):
                     title = subPodObject.Title()
                     if (title[0] != ''):
                         textList.append(title[0])
                     else:
                         textList.append(podObject.Title()[0])
         return textList
     except Exception:
         textList = ["No Text Found"]
         print("exeption thrown")
         return textList
class GameInterface:

    fh = handler.FileHandler()

    walkButtons = [["left", "right"], ["up", "down"]]
    gameInterface = [
        ["loginMenu", ["Username", "Password", "Login"]],
        ["battleMenu", ["Fight", "Pokemon", "Items", "Run"]],
        ["itemMenu", ["PokeballTab", "GreatBall"]],
        ["chatMenu", ["General", "Battle", "Trade", "Global"]],
        ["gameMenu", ["Toggle", "Return", "Logout", "Exit"]],
        [
            "emoteMenu",
            ["Toggle", "Heart", "Sleep", "Thumbsup", "Sjpiener", "Sunglasses"]
        ],
    ]
    pixels = [["avatarPixel"], ["battleMenuPixel"], ["loginPixel"],
              ["shinyPixel"], ["hpBarPixel"]]

    def __init__(self):
        print("\nP O K E T I M E  M O R E  P O W E R\n")
        print("\nImporting game interface\n" + "_" * 28)
        self.setCoordinates(self.gameInterface, "menus")
        print("\nImporting pixels\n" + "_" * 28)
        self.setCoordinates(self.pixels, "pixels")

    def setCoordinates(self, interface, folder):
        for i in interface:
            i.append(self.fh.readJson(i[0],
                                      "\\coordinates\\{}".format(folder)))
Example #34
0
 def _import_txt_triggered(self):
     path = QFileDialog.getOpenFileName(self)[0]
     self._mesh = FileHandler.load_mesh(path)
     self._width.setText(str(self._mesh.get_size().width()))
     self._height.setText(str(self._mesh.get_size().height()))
     self._canvas = Canvas(self.get_canvas__geometry(), self._mesh)
     self._canvas.show()
Example #35
0
def try_to_print_query(dict_in_query, template_entry):
    """Si occupa di inserire sul file designato le istanze valide per il template scelto.
        Args:
            dict_in_query: dizionario avente per chiavi le variabili del template (relative a tipi e relazioni) e
                per valori i corrispondenti valori da inserire all'interno della query template e della NNQT
            template_entry: entry del dizionario contenente tutte le informazioni sul template corrente
        return:
            True se l'operazione è stata completata con successo, perché dict_in_query conteneva tutte le variabili
            necessarie, con i valori validi, False altrimenti
    """
    # print(dict_in_query)
    try:
        if len(dict_in_query.keys()) >= (
                len(template_entry["valid_types"].keys()) +
                len(template_entry["relation_constraints"].keys()) +
                len(template_entry["single_entities"]) +
                len(template_entry["constants"])):
            # print("here")
            query = template_entry["template"] % dict_in_query
            NNQT = istantiate_NNQT(dict_in_query, template_entry)
            sparql = SPARQLWrapper("http://dbpedia.org/sparql")
            sparql.addExtraURITag("timeout", "30000")
            sparql.setReturnFormat(JSON)
            sparql.setQuery(query)
            result_set = sparql.query().convert()
            if len(result_set["results"]["bindings"]) == 0:
                print("empty result set")
                return False
            print(query)
            # correzione NNQT
            correct_NNQT = correct_sentence(NNQT)
            dict_to_ser = {
                "istances": dict_in_query,
                "query": query,
                "result_set": result_set,
                "NNQT_istance": NNQT,
                "correct_NNQT_istance": correct_NNQT
            }
            FileHandler.serialize_query_set(dict_to_ser,
                                            template_entry["save_name"])
            return True
        else:
            return False
    except:
        time.sleep(30)
        print("sleeping")
        try_to_print_query(dict_in_query, template_entry)
Example #36
0
 def populateSamples(self):
   samples = FileHandler.getSavedSamples()
   finalList = []
   for sample in samples:
     if sample != '.DS_Store':
       finalList.append(sample)
   finalList.sort()
   self.review.listWidget.addItems(finalList)
Example #37
0
def loadPhrases():
    ###TODO: klingon
    file = FileHandler.loadFile('Resources/CommonPhrases.csv', 'r')
    for line in file:
        details = line.split(';')
        print(details)
        values = ""
        for x in range(1, len(details)):
            values +=details[x].strip()+ ","

        entry = {details[0]: values}
        phrases.update(entry)
class Processor(object):

    def __init__(self):
        self.filer = FileHandler()
        self.validator = Validator()
        self.database = Database()
        self.editor = Editor()
        self.plotter = Plotter()

    def add_data(self, fileloc):
        self.database.empty_database()
        self.filer.set_filepath(fileloc)
        self.filer.load_file()
        self.filer.strip_tags()
        self.validator.set_raw_data(self.filer.export())
        self.validator.parse_data()
        self.database.add_people(self.validator.export_good_data())

    def process_bad(self):

        if self.validator.has_bad_data():
            self.editor.set_raw(self.validator.export_bad_data())
            self.editor.edit()
            self.database.add_people(self.editor.export_good_data())

    def set_file_path(self, new_path):
        self.database.set_directory(new_path)

    def get_file_path(self):
        return self.database.get_directory()

    def serialize(self, option):
        self.database.serialize(option)

    def deserialize(self, option):
        self.database.empty_database()
        self.database.deserialize(option)

    def pie_bmi(self):
        dist = self.database.get_bmi_distribution()
        self.plotter.pie_bmi(dist["normal"], dist["overweight"], dist["obese"], dist["underweight"])

    def pie_gender(self):
        dist = self.database.get_gender_distribution()
        self.plotter.pie_gender(dist["males"], dist["females"])

    def scatter_sales(self):
        sales_list = self.database.get_sales_ordered()
        self.plotter.scatter_sales(sales_list)

    def bar_bmi_vs_gender(self):
        self.plotter.bar_bmi_vs_gender(self.database.get_male_bmi(),self.database.get_female_bmi() )
Example #39
0
def main(argumentos):
    usuarioDestino = argumentos[1]
    nombreArchivo = argumentos[2]
    if os.path.isfile(nombreArchivo):
        mensaje = {
            "accion" : "enviar",
            "identificador" : usuarioDestino,
            "informacionMsj" : {
                "horaFecha" : str(datetime.datetime.now()),
                "mensaje" : os.path.basename(nombreArchivo),
                "archivo": FileHandler.archivoAString(nombreArchivo),
                "remitente" : argumentos[3] if len(argumentos) > 3 else ""
            }
        }

        return Client.sendData(mensaje)

    raise Exception("Archivo no existe o inválido: " + nombreArchivo)
	def divEventos( self ):
		content  = '<h2>Log de eventos nos hosts monitorados</h2>';
		content += "<div id=\"divEventos\">";
		
		# Se o arquivo de log de eventos existir, adiciona seu conteúdo à div
		if os.path.exists( EVENT_LOG_FILENAME ):
			FH = FileHandler();
			FH.open( EVENT_LOG_FILENAME, 'r' );
			for line in FH.readlines():
				content += "<p>" + line + "</p>";
			FH.close();		
		
		content += "</div>";
		return content;
Example #41
0
def loadDictionary(language):
    global mode
    mode = language
    file = FileHandler.loadFile("Resources/" + language + ".csv", "r")
    for line in file:
        vals = line.split(',')
        # check to make sure their not blank
        if vals[0] == '':
            continue
        value = ""

        for i in range(1, len(vals)):
            if vals[i].strip() != '':
                value += vals[i].strip() + ","
        dictionary.update({vals[0].strip(): value.strip()})

        translation.update({value.strip(): vals[0].strip()})

    print("**************** Dictionary Loaded ****************")
    return dictionary
    def LogMsg(self, msg):
        # Pega data e hora locais
        localTime = localtime()

        # Monta string com data e hora (YYYY-MM-DD HH:MM:SS)
        strDateTime = (
            "{0:02}".format(localTime[0])
            + "-"
            + "{0:02}".format(localTime[1])
            + "-"
            + "{0:02}".format(localTime[2])
            + " "
            + "{0:02}".format(localTime[3])
            + ":"
            + "{0:02}".format(localTime[4])
            + ":"
            + "{0:02}".format(localTime[5])
        )
        Log = FileHandler()
        Log.open(self.logFileName, "a")
        Log.write("[" + strDateTime + "]: " + msg)
        Log.close()
Example #43
0
def main(args):
    # get the absolute path of the FastSearch directory
    fastSearchDir = os.path.abspath(args[0])[:os.path.abspath(args[0]).rfind(os.sep)] + os.sep
    
    # instantiate the exit code
    code = EXIT_CLEAN
    
    # instantiate pre-run update condition
    preRunUpdateCheck = False
    
    # declare options list
    optionsList = FileHandler.initializeOptionsList(fastSearchDir, [])
    colors = Output.Colors(optionsList)
    
    # FastSearch has been updated
    if len(args) > 3 and args[1] == '-updatesuccess':
        print colors.alert() + '\nFastSearch has been successfully updated to v' + str(Updater.CURRENT_VERSION) + '!' + colors.end()
        # display the post update message retrieved from the server
        if not (args[2] in ('None', '', None)):
            print colors.alert() + args[2:] + colors.end()
    
    # run a QuickSearch and return the results as a list and quit the application
    if len(args) > 1 and args[1][1:].lower() in ('r', 'return'):
        if len(args) > 2:
            optionsList = FileHandler.defaultList
            if len(args) > 3 and args[2][1:].lower() in ('d', 'deep', 'deepsearch', 'ds'):
                optionsList[0] = True
                start = 3
            else:
                start = 2
            
            # if the user requested a deep search but provided no string
            if args[start][1:] in ('d', 'deep', 'deepsearch', 'ds'):
                return EXIT_RESULTS_BAD, None
            
            string = args[start].lower()            
            for i in range(start + 1, len(args)):
                string += ' ' + args[i].lower()
            
            search = Search.Search(string, optionsList, colors)
            search.start()
            search.join()
            return EXIT_RESULTS, search.finish()
        else:
            return EXIT_RESULTS_BAD, None
    
    print colors.blue() + '\n::Welcome to FastSearch v' + str(Updater.CURRENT_VERSION) + ' by Alex Laird::' + colors.end()
    
    # if arguments are specified, use them as the search string
    if len(args) > 1 and not args[1] == '-updatesuccess':
        if args[1].startswith('-'):
            if len(args) == 2 and not args[1][1:].lower() in ('d', 'debug'):
                if args[1][1:].lower() in ('help', 'h'):
                    Output.help(colors)
                elif args[1][1:].lower() in ('update', 'updates', 'u'):
                    runUpdater(fastSearchDir, colors)
                elif args[1][1:].lower() in ('credit', 'credits', 'c'):
                    Output.credits(colors)
                elif args[1][1:].lower() in ('option', 'options', 'o', 'pref', 'preferences', 'setting', 'settings'):
                    optionsList = Options.options(fastSearchDir, optionsList, colors)
                else:
                    print colors.alert() + 'The command-line arguments were not valid. View the help menu for assistance.\n' + colors.end()
            # run a benchmark comparing a standard os.walk method (with no comparisons) to the FastSearch localWalk method
            elif args[1][1:].lower() in ('d', 'debug'):
                try:
                    code = debug(args, colors)
                except:
                    code = EXIT_DEBUG_ERROR
                
                return code
            else:
                print colors.alert() + 'The command-line arguments were not valid. View the help menu for assistance.\n' + colors.end()
        else:
            string = args[1].lower()
            for i in range(2, len(args)):
                string += ' ' + args[i].lower()
    
            # the search will be launched immedietly with the current working directory as root
            code = runSearch(fastSearchDir, string, optionsList, False, colors)[0]
    # if no arguments were specified
    elif len(args) == 1:
        if preRunUpdateCheck:
            simpleUpdateChecker(colors)

    looping = True
    results = None
        
    # loop until the user wants out
    while looping:
        # retreive a command from the user
        string = raw_input(colors.blue() + 'Type (s)earch, (o)ptions, (u)pdate, (h)elp, (c)redits, or (q)uit: ' + colors.end()).lower()
        
        # the user entered a number
        if string.strip('[]').isdigit():
            if not results == None:
                location = int(string.strip('[]')) - 1
                ref = 0
                # decrement the number as needed to keep it consistent with the correct results subarray
                if location > len(results[0]) - 1:
                    location -= len(results[0])
                    ref = 1
                if location > len(results[1]) - 1:
                    location -= len(results[1])
                    ref = 2
                
                # ensure that the location is/was a valid search result
                if location < 0 or location > len(results[ref]) - 1:
                    print colors.alert() + 'The number entered did not correspond to a search results. Try again.\n' + colors.end()
                
                # launch the search result
                print 'Opening ' + os.path.abspath(results[ref][location]) + ' ...'
                os.system('open ' + os.path.normpath(os.path.abspath(results[ref][location])).replace(' ', '\\ '))
                print ''
            else:
                print colors.alert() + '\nThat wasn\'t an option. Try again.\n' + colors.end()
            
            continue

        # the user wants to search
        if string in ('s', 'search', 'f', 'find'):
            # retreive the string to search for from the user
            string = raw_input(colors.blue() + 'Enter a search string: ' + colors.end()).lower()
            
            code, results = runSearch(fastSearchDir, string, optionsList, False, colors)
        # the user wants to check for updates
        elif string in ('u', 'update', 'updates'):
            runUpdater(fastSearchDir, colors)
        # the user wants help
        elif string in ('h', 'help'):
            Output.help(colors)
        # the user wants to see the credits
        elif string in ('c', 'credit', 'credits'):
            Output.credits(colors)
        # the user wants to specify search options
        elif string in ('o', 'options', 'p', 'pref', 'prefs', 'preferences', 'setting', 'settings'):
            optionsList = Options.options(fastSearchDir, optionsList, colors)
        # the user wants to end the program
        elif string in ('q', 'quit', 'e', 'exit', 'c', 'close', 'end'):
            # clean exit without errors
            code = EXIT_CLEAN
            looping = False
        # the user is an idiot
        else:
            print colors.alert() + '\nThat wasn\'t an option. Try again.\n' + colors.end()
    
    if not optionsList[6] == None:
        optionsList[6].close()
    
    if code == None:
        return EXIT_UNKNOWN_ERROR
    else:
        return code
Example #44
0
 def __init__(self):
     self.filer = FileHandler()
     self.validator = Validator()
     self.database = Database()
     self.editor = Editor()
     self.plotter = Plotter()
Example #45
0
 def hazRespaldo(self):
     FileHandler.stringAArchivo("Backup/usuarios", json.dumps(self.usuarios), toBase64=False)
     FileHandler.stringAArchivo("Backup/mensajesPorUsuario", json.dumps(self.mensajesPorUsuario), toBase64=False)
     return {"status" : "ok"}
Example #46
0
def results(path, string, optionsList, results, time, colors):
    numResults = getNumResults(results)
    
    # display how many items were found in how many seconds (rounded to two decimals) a ternary operation is emulated
    # for the potential pluralization of 'Result(s)'
    print colors.green() + '--FastSearch Found \'' + string + '\' ' + str(numResults) + ' Time%s in ' % (numResults != 1 and 's' or '') \
          + optionsList[5] + ' in ' + str(round(time, 2)) + ' Seconds--' + colors.end()
    
    # a full search was performed
    if optionsList[4]:
        itemNum = 1
        
        # scan through and print the full path for each folder result (if folders are displayed)
        if optionsList[1] == 1 or optionsList[1] == 2:
            print colors.green() + '\n::Matching Folder Names::' + colors.end()
            if len(results[0]) != 0:
                for item in results[0]:
                    print colors.green() + '[' + str(itemNum) + ']: ' + item + colors.end()
                    itemNum += 1
            else:
                print colors.alert() + '-None Found-' + colors.end()

        # scan through and print full paths for each file result (if files are displayed)
        if optionsList[1] == 0 or optionsList[1] == 2:
            print colors.green() + '\n::Matching File Names::' + colors.end()
            if len(results[1]) != 0:
                for item in results[1]:
                    print colors.green() + '[' + str(itemNum) + ']: ' + item + colors.end()
                    itemNum += 1
            else:
                print colors.alert() + '-None Found-' + colors.end()

        # scan through and print full paths for each file the string was found within (if a deep search was run)
        if optionsList[0]:
            print colors.green() + '\n::Found in Files::' + colors.end()
            if len(results[2]) != 0:
                for item in results[2]:
                    print colors.green() + '[' + str(itemNum) + ']: ' + item[0] + '\n  On Line%s: ' % (len(item[1]) != 1 and 's' or '') + str(item[1]) + colors.end()
                    itemNum += 1
            else:
                print colors.alert() + '-None Found-' + colors.end()
    # a partial search was performed
    else:
        # print the only folder found
        if optionsList[1] == 1 or optionsList[1] == 2:
            print colors.green() + '\n::Matching Folder::' + colors.end()
            if len(results[0]) != 0:
                print colors.green() + '[1]: ' + results[0][0] + colors.end()
            else:
                print colors.alert() + '-None Found-' + colors.end()
        
        # print the only file found
        if optionsList[1] == 0 or optionsList[1] == 2:
            print colors.green() + '\n::Matching File::' + colors.end()
            if len(results[1]) != 0:
                    print colors.green() + '[1]: ' + results[1][0] + colors.end()
            else:
                print colors.alert() + '-None Found-' + colors.end()

        # print the only file the string was found within
        if optionsList[0]:
            print colors.green() + '\n::Found in File::' + colors.end()
            if len(results[2]) != 0:
                print colors.green() + '[1]: ' + results[2][0][0] + '\n  On Line%s: ' % (len(results[2][0][1]) != 1 and 's' or '') + str(results[2][0][1]) + colors.end()
            else:
                print colors.alert() + '-None Found-' + colors.end()
    
    # if the user desires, write this to the recent searches list
    if optionsList[8]:
        FileHandler.writeSearchHistory(path, string, optionsList, results, time)

    if os.name == 'posix':
        print colors.alert() + '\n--To open a search result, type its corresponding number from the main menu--\n' + colors.end()
Example #47
0
def options(fastSearchDir, optionsList, colors):
    Output.options(optionsList, colors)
    
    # loop until the user wants to go back
    while True:
        # capture the users choice
        string = raw_input(colors.cyan() + 'Enter an option: ' + colors.end()).lower()

        # the user wants to enable or disable a deep search
        if string in ('d', 'deep', 'deep search', 'ds'):
            optionsList[0] = not optionsList[0]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Deep Search is now %s' % (optionsList[0] and 'on' or 'off') + '...\n' + colors.end()
        # the user wants only files to be displayed in the results
        elif string in ('i', 'file', 'files', 'file only', 'files only', 'only file', 'only files'):
            optionsList[1] = 0
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will now only include files...\n' + colors.end()
        # the user wants only folders to be displayed in the results
        elif string in ('e', 'folder', 'folders', 'folder only', 'folders only', 'only folder', 'only folders'):
            optionsList[1] = 1
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will now only include folders...\n' + colors.end()
        # the user wants both files and folders to be displayed in the results
        elif string in ('o', 'both', 'both file and foler', 'both files and folder', 'both file and folders', 'both files and folders', 'file and folder', \
                        'files and folder', 'file and folders', 'files and folders', 'bff'):
            optionsList[1] = 2
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will now include both files and folders...\n' + colors.end()
        # the user wants to enable or disable the display of hidden files and folders in the results
        elif string in ('h', 'hidden', 'show hidden', 'show hidden file', 'show hidden files', 'show hidden folder', 'show hidden folders', \
                        'hidden file and folder', 'hidden files and folder', 'hidden file and folders', 'hidden files and folders', 'show hidden file and folder', \
                        'show hidden files and folder', 'show hidden file and folders', 'show hidden files and folders', 'hide file', 'hide files', \
                        'hide folder', 'hide folders', 'hide file and folder', 'hide files and folder', 'hide file and folders', 'hide files and folders'):
            optionsList[2] = not optionsList[2]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will %s show hidden files and folders' % (optionsList[2] and 'now' or 'no longer') + '...\n' + colors.end()
        # the user wants the absolute path to be shown in the search results
        elif string in ('f', 'full path', 'abs', 'absolute', 'abspath', 'abs path', 'absolute path'):
            optionsList[3] = 0
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will now show the full (absolute) path...\n' + colors.end()
        # the user wants the relative path to be shown in the search results
        elif string in ('r', 'rel', 'relative', 'relpath', 'rel path', 'relative path'):
            optionsList[3] = 1
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will now show the relative path...\n' + colors.end()
        # the user doesn't want the path shown in the search results
        elif string in ('n', 'no path'):
            optionsList[3] = 2
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Search results will no longer show a path...\n' + colors.end()
        # the user wants to enable or disable a full search
        elif string in ('u', 'full search', 'partial', 'partial search'):
            optionsList[4] = not optionsList[4]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Full Search is now %s' % (optionsList[4] and 'on' or 'off') + '...\n' + colors.end()
        # the user wants to change the root directory
        elif string in ('dir', 'directory', 'r', 'root', 'rootdir', 'root dir', 'root directory', 'curdir', 'cur dir', 'cur directory', 'current directory'):
            string = raw_input(colors.cyan() + 'Enter the path for the new root director: ' + colors.end())
            # ensure that the user has given a valid new root directory
            if os.path.exists(string):
                optionsList[5] = string
                if not optionsList[6] == None:
                    optionsList[6].close()
                optionsList[6] = None
                FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
                print colors.alert() + '...The new root directory is ' + optionsList[5] + '...\n' + colors.end()
            # if the directory isn't local, perhaps it is an ftp location
            elif isValidRemoteConn(string):
                string = string.replace('ftp://', '')
                if not string.startswith('ftp.'):
                    string = 'ftp.' + string
                localDir = None
                if not string.find('/') == -1:
                    address = string[:string.find('/')]
                    localDir = string[string.find('/'):]
                else:
                    address = string
                username = raw_input(colors.cyan() + 'Username: '******'Password: '******''):
                        try:
                            ftp.cwd(localDir)
                            optionsList[5] += localDir
                        except:
                            optionsList[5] = temp
                            print colors.error() + 'The remote server was valid, but the specified local directory, ' + localDir + ', could not be found.' \
                                  + '\nCheck your spelling, verify that the directory exists, and try again. The root directory has not changed.' + colors.end()
                            print colors.alert() + '...The root directory remains ' + optionsList[5] + '...\n' + colors.end()
                            continue
                    if not optionsList[6] == None:
                        optionsList[6].close()
                    optionsList[6] = ftp
                    print colors.alert() + '...The new root directory is ' + optionsList[5] + '...\n' + colors.end()
                else:
                    print colors.error() + 'The username or password did match any accounts on ' + string + '. The root directory has not changed.' + colors.end()
                    print colors.alert() + '...The root directory remains ' + optionsList[5] + '...\n' + colors.end()
            else:
                if isValidRemoteConn(string) == -1:
                    print colors.error() + 'The path specified was not a valid directory. The root directory has not changed.' + colors.end()
                    print colors.alert() + '...The root directory remains ' + optionsList[5] + '...\n' + colors.end()
                else:
                    print colors.error() + 'The remote server specified may have been valid, but a connection could not be made.\nCheck your internet ' \
                          + 'connection and try again. The root directory has not changed.' + colors.end()
                    print colors.alert() + '...The root directory remains ' + optionsList[5] + '...\n' + colors.end()
        # store recent search results
        elif string in ('s', 'save', 'save recent', 'save recent search', 'save recent searches', 'save search', 'save searches', 'save history', \
            'recent', 'recent searches', 'recent search', 'history'):
            optionsList[8] = not optionsList[8]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Recent search results will %s be stored in RecentSearches.txt' % (optionsList[8] and 'now' or 'no longer') + '...\n' + colors.end()
        # the user wants the screen to clear
        elif string in ('c', 'clear', 'clear screen', 'clear shell', 'clear console', 'clear terminal', 'cls', 'clr'):
            optionsList[7] = not optionsList[7]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...The screen will %s clear the screen before display search results' % (optionsList[7] and 'now' or 'no longer') + '...\n' + colors.end()
        # the user wants to change the thread count
        elif string in ('t', 'thread', 'threads', 'threads used', 'thread used', 'thread count', 'threads count', 'num thread', 'num threads', 'number thread', \
            'number threads', 'num of thread', 'num of threads', 'number of thread', 'number of threads'):
            string = raw_input(colors.cyan() + 'Enter the number of threads to split the search into: ' + colors.end())
            # ensure that the user entered an interger
            try:
                optionsList[9] = int(string)
                FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
                print colors.alert() + '...The search will no be split into ' + str(optionsList[9]) + ' threads...\n' + colors.end()
            except:
                print colors.error() + 'You did not specify a valid integer for the new thread count.' + colors.end()
                print colors.alert() + '...The thread count remains at ' + str(optionsList[9]) + '...\n' + colors.end()
        # the user wants no animations shown
        elif string in ('no anim', 'no anims', 'no animation', 'no animations', 'disable anim', 'disable anims', 'disable animation', 'disable animations', 'disable all anim', \
            'disable all anims', 'disable all animation', 'disable all animations', 'disable full anim', 'disable full anims', 'disable full animation', 'disable full animations'):
            optionsList[10] = 0
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...No search animations will be displayed...\n' + colors.end()
        # the user wants only the pinwheel animation shown
        elif string in ('p', 'pinwheel', 'show pinwheel', 'show pinwheel only', 'pinwheel anim', 'pinwheel animation', 'show pinwheel anim', 'show pinwheel animation', \
            'show pinwheel anim only', 'show pinwheel animation only', 'show only pinwheel', 'show only pinwheel anim', 'show only pinwheel animation', 'only pinwheel anim', \
            'only pinwheel animation', 'only pinwheel'):
            optionsList[10] = 1
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...Only the pinwheel search animation will be displayed...\n' + colors.end()
        # the user wants all animations shown
        elif string in ('a', 'anim', 'anims', 'animation', 'animations', 'all anim', 'all anims', 'all animation', 'all animations', 'show anim', 'show anims', 'show animation', \
            'show animations', 'show all anim', 'show all anims', 'show all animation', 'show all animations', 'full anim', 'full anims', 'full animation', 'full animations', \
            'show full anim', 'show full anims', 'show full animation', 'show full animations', 'enable anim', 'enable anims', 'enable all anim', 'enable all anims', \
            'enable all animation', 'enable all animations', 'enable full anim', 'enable full anims', 'enable full animation', 'enable full animations', 'enable search anim', \
            'enable search anims', 'enable search animation', 'enable search animations', 'enable full search anim', 'enable full search anims', 'enable full search animation', \
            'enable full search animations', 'enable all search anim', 'enable all search anims', 'enable all search animation', 'enable all search animations'):
            optionsList[10] = 2
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            print colors.alert() + '...All search animations will be displayed...\n' + colors.end()
        # the user does not want to display text
        elif string in ('x', 'color', 'coloring', 'colors', 'show colors', 'show text colors', 'show color', 'show text color', 'text color', 'text', 'text colors', \
            'text coloring', 'show coloring', 'show text coloring'):
            optionsList[11] = not optionsList[11]
            FileHandler.writeNewOptionsList(fastSearchDir, optionsList, True)
            colors.setColors(optionsList)
            print colors.alert() + '...Text coloring will %s be used' % (optionsList[11] and 'now' or 'no longer') + '...\n' + colors.end()
        elif string in ('show', 'show again', 'show menu', 'menu', 'display', 'display menu', 'option', 'options', 'option menu', 'options menu', 'show option', 'show options'):
            return options(fastSearchDir, optionsList)
        # the user wants to go back to the main menu
        elif string in ('b', 'back', 'go back', 'close', 'q', 'quit', 'exit'):
            print colors.cyan() + '\n--------------------------\n' + colors.end()
            return optionsList
        # the user is an idiot
        else:
            print colors.alert() + '\nThat wasn\'t an option. Try again.\n' + colors.end()
Example #48
0

if __name__ == "__main__":
    ## Get the command line arguments. Run in IDE for demo tweaking.
    stime = time.time()
    try:
        args = getargs()
        if args is None:
            sys.exit()
    except:
        raise

    try:
        # print(args.inputfile)
        FileHandler = FileHandler.FileHandler()
        objs = FileHandler.loadMesh(args.inputfile)

        if objs is None:
            sys.exit()
    except (KeyboardInterrupt, SystemExit):
        print("\nError, loading mesh from file failed!")
        raise

    ## Start of tweaking.
    if args.verbose:
        print("Calculating the optimal orientation:\n  {}\n".format(args.inputfile.split("\\")[-1]))
    c = 0
    for obj in objs:
        mesh = obj["Mesh"]
        if args.convert:
            R = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
	def Refresh( self, hostList ):
		guiFile = FileHandler()
		guiFile.open( GUI_FILENAME, "w" )
		guiFile.write( self.getHeader() )
		guiFile.write( self.divEstados( hostList) );
		guiFile.write( self.divEventos() );
		guiFile.write( self.getFooter() )
		guiFile.close()
Example #50
0
def install_mod(mod_name, address, mod_directory, csv_list, the_mod_version=None, alpha_build="12d",
                log1file="installed_mods.csv"):
    # Change the current dir to ensure working and setting the version of the mod
    os.chdir(dname)
    the_mod_version = fh.extractVersionNumber("mods.csv", mod_name)

    # Check if the mod is already installed

    if (fh.isNameInFile(log1file, mod_name) and
            (fh.extractVersionNumber(log1file, mod_name) ==
                 fh.extractVersionNumber("mods.csv", mod_name))):
        print("Mod is already installed and has the newest version, too!")
        return True

    # Check if the mod is outdated and needs an update

    elif (((fh.extractVersionNumber(log1file, mod_name) !=
               fh.extractVersionNumber("mods.csv", mod_name))) and
                    fh.isNameInFile(log1file, mod_name)):
        print("Mod is outdated, starting update now")
        # TODO Update routine
    elif not fh.isNameInFile(log1file, mod_name):
        print("The mod isn't installed.")

    # TODO Searching for incompatibilities has to be done

    print("Searching for dependencies...")

    # Searching for dependencies

    splitter = [i.split(';', 1)[0] for i in csv_list[4]]

    if splitter:
        if csv_list != "None":
            for i in splitter:
                install_mod(i, getModData(i, csv_list[7], 7), mod_directory, csv_list)
    else:
        print("Mod has no dependencies")

    print("Downloading: " + mod_name)

    # Downloading the zipped mod

    path_to_file = dname + "/temp_mod_d/" + mod_name
    try:
        urllib.request.urlretrieve(address, path_to_file)
    except ValueError:
        # FIXME: Error, every second time install_mod() is called
        print("URL WRONG")
        return

    # Unzip the mod
    print("Unzipping...")
    unzip(path_to_file, dname + "/unzipped/")

    # Adding the modmanager.csv files to set the mod visible for this program

    registerMod(dname+ "/unzipped/", mod_name, the_mod_version, alpha_build)

    # Logging the installation of the mod
    print("Logging...")
    fh.logData(log1file, "%s|%s|%s|%s" % (mod_name ,the_mod_version, alpha_build, strftime("%Y-%m-%d %H:%M:%S", gmtime())))

    # Move the file into the mod folder
    print("Moving file into mod folder")

    try:
        copyTree("unzipped/", mod_directory)

    except FileExistsError:
        print("Already installed")

    # Delete files after this process

    finally:
        clearDownloadFolder("unzipped/")
Example #51
0
 def restauraRespaldo(self):
     if FileHandler.existeArchivo("Backup/usuarios") and FileHandler.existeArchivo("Backup/mensajesPorUsuario"):
         self.usuarios = json.loads(FileHandler.archivoAString("Backup/usuarios", toBase64=False))
         self.mensajesPorUsuario = json.loads(FileHandler.archivoAString("Backup/mensajesPorUsuario", toBase64=False))
         return {"status" : "ok"}
     return {"status" : "error", "mensaje" : "No hay respaldo existente"}
Example #52
0
    return arguments


if __name__ == "__main__":
    # Get the command line arguments. Run in IDE for demo tweaking.
    stime = time()
    try:
        args = getargs()
        if args is None:
            sys.exit()
    except:
        raise

    try:
        FileHandler = FileHandler.FileHandler()
        objs = FileHandler.load_mesh(args.inputfile)
        if objs is None:
            sys.exit()
    except(KeyboardInterrupt, SystemExit):
        raise SystemExit("Error, loading mesh from file failed!")

    # Start of tweaking.
    if args.verbose:
        print("Calculating the optimal orientation:\n  {}"
              .format(args.inputfile.split(os.sep)[-1]))

    c = 0
    info = dict()
    for part, content in objs.items():
        mesh = content["mesh"]
        info[part] = dict()