예제 #1
0
 def readUserSettings(self):
     import shelve
     shelve = shelve.open(self.userOptionsPath)
     self.notebook.tabBasicPreferences.ComboBox.SetValue(shelve['crypto-alg'])
     self.notebook.tabBasicPreferences.InputUserFolder.SetValue(shelve['user-folder'])
     self.notebook.tabBasicPreferences.InputCryptPassword.SetValue(shelve['crypto-key'])
     self.checkUserFolder()
     shelve.close()
예제 #2
0
def outputgenerator(shelve,filename):
    csvfile = open('output/' + filename + '.mostcommon_words.csv', mode = 'w+')
    output_writer = csv.writer(csvfile, delimiter  = ',')
    output_writer.writerow(['password','count'])

# warning, next section can fail for large sets, as the shelve content is loaded
# to memory
    for key in sorted(shelve, key=shelve.get, reverse=True)[1:30]:
        output_writer.writerow([key,str(shelve[key])]) 
    shelve.close()
예제 #3
0
 def writeUserSetting(self):
     import shelve
     shelve = shelve.open(self.userOptionsPath, writeback=True)
     userFolder = os.path.normpath(self.notebook.tabBasicPreferences.InputUserFolder.GetValue()) + '/'
     self.parent.sb.SetStatusText(userFolder)
     self.parent.files_folder.setCurrentDir(userFolder)
     self.parent.files_folder.setUsersDir(userFolder)
     self.parent.files_folder.showFilesInDirectory(userFolder)
     shelve['crypto-alg'] = self.notebook.tabBasicPreferences.ComboBox.GetValue()
     shelve['crypto-key'] = self.notebook.tabBasicPreferences.InputCryptPassword.GetValue()
     shelve['user-folder'] = userFolder
     shelve.close()
예제 #4
0
파일: indexer.py 프로젝트: abadizb/Python1
def indexer():
    Dict = {}
    pickles = open ("C:\Users\Halim\Python34\raw_data.pickle","br")
    x = pickle.load(r)
    shelve = shelve.open("datalist")
    for x, quote in enumerate(quotes.datalist):
        words = quote.split()
        for word in words:
            if(word not in Dict.keys()):
                Dict[word]={x}
            else:
                Dict[word]= Dict[word]|{x}
    for key, value in Dict.items():
        shelve[key]=(value)
    pickles.close()
    shelve.close()
예제 #5
0
파일: indexer.py 프로젝트: ghas310/HW_4
def indexer():
    Dictionry = {}
    pickles = open ("\Users\GhasanAlyamani\raw_data.pickle","br")
    n = pickle.load(r)
    shelve = shelve.open("data_list")
    for n, quote in enumerate(quotes.data_list):
        words = quote.split()
        for word in words:
            if(word not in Dictionry.keys()):
                Dictionry[word]={n}
            else:
                Dictionry[word]= Dictionry[word]|{n}
    for key, value in Dictionry.items():
        shelve[key]=(value)
    pickles.close()
    shelve.close()
예제 #6
0
    try:
        return int(self.table[repr(game_state)])
    except KeyError:
        return -1

  def saveToCache(self,game_state,newTricks):
      try:
          oldTricks = int(self.table[repr(game_state)])
          if newTricks > oldTricks:
              self.table[repr(game_state)] = str(newTricks)
      except KeyError:
          self.table[repr(game_state)] = str(newTricks)

  def clear(self):
    if not self.persistent:
      self.table.clear()

  def close(self):
    if self.persistent:
      self.table.close()

if __name__ == '__main__':
  shelve = shelve.open('/home/scratch/tal1/double_dummy/data/transposition_table.dat2')
  config = Configuration('search_config.cfg')
  table = config.transTable
  for key,value in shelve.iteritems():
    table.saveToCache(key,value)
  config.close()
  shelve.close()
  
예제 #7
0
#Importamos las dos librerias necesarias
import gdchart
import shelve

#Abrimos el archivo que creamos anteriormente
shelve_file = shelve.access('access.s')
#El objeto shelve es un diccionario, vamos a llamar el método Items()
items_list = [(i[1], i[0]) for i in shelve_file.items()]
#Regresa una lista de tuplas en las cuales el primer elemento de ella es
# la llave del diccionario y el segundo elemento es el valor
items_list.sort()
#Podemos usar el método items() para acomodar los datos de forma que tengan
#mayor sentido cuando son impresos
bytes_sent = [i[0] for i in items_list]
#ip_addresses = [i[1] for i in items_list]
ip_addresses = ['XXX.XXX.XXX.XXX' for i in items_list]

chart = gdchart.Bar()
chart.width = 400
chart.height = 400
chart.bg_color = 'white'
chart.plot_color = 'black'
chart.xtitle = 'IP Address'
chart.ytitle = 'Bytes sent'
chart.title = 'Usage by IP Address'
chart.setData(bytes_sent)
chart.setLabels(ip_addresses)
chart.draw('bytes_ip_bar.png')

shelve.close()
예제 #8
0
        }, None)

    try:
        zeroconf.register_service(zeroconf_info)
    except Zeroconf.NonUniqueNameException:
        LOG.warn(
            "Service with name \'%s\' already broadcasting on this network!" %
            (getServiceName(), ))

    try:
        while True:
            LOG.info("Now waiting for messages on %s" %
                     (queueResult.method.queue, ))
            chan.start_consuming()
    except KeyboardInterrupt:
        chan.stop_consuming()
        pass
    finally:
        LOG.info("Shutting down server...")
        shelve.close(MSG_DB_FILE)

        LOG.info("Closing connection with RabbitMQ")
        if conn is not None:
            conn.close()

        LOG.info("Unregistering server")
        zeroconf.unregister_service(zeroconf_info)
        zeroconf.close()

        LOG.info("Shutdown complete!")
예제 #9
0
def Shelveclose(shelve):
    '''
    close shelve dictionary
    '''
    shelve.close()
예제 #10
0
def list_lol_players(slack_id=None):
    players = shelve.open('data/players')
    for player in players:
        print(players[player])
    shelve.close()
예제 #11
0
class Root(FloatLayout):
    global deploymentLocation
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)

    # text: root.text_input means that in the class of root, the variable text_input represents the text value of this thing
    # Can also have this for a function call to set values
    # but mainly you're just pointing it to a value that's all
    # I think it needs to be set to this as a handler, if you set it to text and try and change it it'll shit itself (it's like a holder)

    logger.info('Opening root')
    isDeploymentIniSet = ObjectProperty(None)
    deploymentLocation = ''
    shelve = shelve.open("FileLocations")
    if ("deploymentini" in shelve):
        isDeploymentIniSet = True
        deploymentLocation = shelve["deploymentini"]
        text_input = ObjectProperty('Selected Deployment.ini:' + deploymentLocation)
        logger.info('Deployment.ini found, using ' + deploymentLocation)
    else:
        text_input = ObjectProperty(None)
        logger.info('Deployment.ini not selected')

    #Text of a label can be a kivy property, which can be later changed and since it is a kivy property it will automatically updated everywhere. Here is an example of your .py
    shelve.close()

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        logger.info('Opening file selector')
        self._popup.open()


    def load(self, path, filename):
        ## DO SOME VALIDATION ON THIS
        try:
            if(len(filename) == 0):
                popup = Popup(title='Warning', content=Label(text='Please stop trying to break me'),
                          auto_dismiss=True, size_hint=(0.3, 0.3))
                popup.open()
            else:
                self.deploymentiniSelected(filename)
        except Exception as e:
            logger.Error("Error in load method: " + str(e))


    def deploymentiniSelected(self, fileDir):
        global deploymentLocation
        import shelve
        logger.info('Selecting and shelving deployment.ini')

        # self is how you get class level values
        self.text_input = "Selected Deployment.ini:" + fileDir[0]
        print(fileDir[0])
        deploymentLocation = fileDir[0]

        shelve = shelve.open("FileLocations")
        shelve["deploymentini"] = fileDir[0]
        # The method call dismisses the popup, since the popup is delcared as self._popup, class level
        self.dismiss_popup()
        # Make the next button visible here
        x = self.children
        x = x[0].children
        x = x[0].children
        x = x[0]
        x.disabled = False
        logger.info('Shelved, button enabled')

    def beginDeployProcess(self, tx):
        logger.info('Beginning deploy process')
        self.splitUIandBackendThreads(tx)

    def backendDeploy(self):
        global linux, deploymentLocation, finished
        logger.info('Backend thread operating')
        templist =[]
        newestbuild, droplink = GetBuildVersion.GetBuildVersion(templist, selfPickBuild)
        logger.info('Build version collected')
        if (linux == False):
            deploymentRoot = self.getPFgoldRootFromDeploymentLoc(deploymentLocation)
            logger.info("Opening corext enlistment....")
            process = subprocess.check_output("C:/Windows/System32/cmd.exe /k set inetroot="+ deploymentRoot +"&set corextbranch=pfgold_small&" + deploymentRoot + "tools/path1st/myenv.cmd & sd sync & sd edit " + deploymentRoot + "autopilotservice/Global/VirtualEnvironments/ASG_O365/Fast-PPE/deployment.ini")
            print(process)
            logger.info("Corext synced and ready")
            DeploymentReaderAndEditor.deploymentReadAndEditor(newestbuild, droplink, deploymentLocation)
            logger.info("Running apsigntoolresign ")
            process = subprocess.check_output("C:/Windows/System32/cmd.exe /k set inetroot=" + deploymentRoot + "&set corextbranch=pfgold_small&" + deploymentRoot + "tools/path1st/myenv.cmd & apsigntool resign")
            print(process)
        logger.info("FINISHED")
        finished = True
        ##### HERE you need to have it trigger the terminal opening so you'll need to parse the deployment.ini file

    def getPFgoldRootFromDeploymentLoc(self, deploymentLocation):
        logger.info('Extracting location of deployment.ini to get devenv')
        if "pfgold" in deploymentLocation.lower():
            pfgoldroot = deploymentLocation.lower().split("pfgold")[0]
            return pfgoldroot + "pfgold\\"
        else:
            logger.Error("Deployment.ini was invalid, was set to " + deploymentLocation)
            raise Exception("Deployment.ini was invalid, was set to " + deploymentLocation)



    def splitUIandBackendThreads(self,tx):
        logger.info('Forking threads')
        pool = ThreadPool(processes=1)
        self.pop_up = Factory.PopupBox()
        self.pop_up.update_pop_up_text('Running some task...')
        self.pop_up.open()

        #Clock.schedule_once(GetBuildVersion.GetBuildVersion(),2)
        # Open the pop up
        # Call some method that may take a while to run.
        # I'm using a thread to simulate this


        # The reason this works is complicated, previously this wouldn't work as the self.popup thing in KIVY needs the method to be fully
        # finished before it'll actually appear
        # badly exmplained at https://stackoverflow.com/questions/40452999/kivy-popup-displaying-at-the-end-of-a-running-process
        # previously it was freezing the main loop, we now use partials, these allow the function to take a parameter and sort of like resolve it later?
        # so it seems like it finishes everything it was doing and then comes back
        # but this is what the thread should've been doing all along
        deployThread = threading.Thread(target=tx)
        deployThread.daemon = True
        deployThread.start()
        logger.info('Thread for backend initialised')

        xThread = threading.Thread(target=self.frontendDeploy)
        xThread.daemon = True
        xThread.start()
        logger.info('Thread for frontend initialised')
        logger.info('firing partial')

        #print("here")
        #time.sleep(5)
        #finished = True
        #self.something_that_takes_5_seconds_to_run()
       #https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script





    def frontendDeploy(self):
        logger.info('Frontend thread operating')
        x = 0
        while finished == False:
            self.pop_up.update_pop_up_text(lstFunnyComments[randint(0, len(lstFunnyComments) -1)])
            x+=1# 5 seconds
            time.sleep(3)
        self.pop_up.update_pop_up_text("Finished")
        logger.info('Frontend thread terminating')
        # Once the long running task is done, close the pop up.
        self.pop_up.dismiss()


    def selfBuildPickSetting(checkbox, value):
        global selfPickBuild
        selfPickBuild = value
        print("Self pick build was changed to: " + str(selfPickBuild))
예제 #12
0
		socket.inet_aton(server_ip),
		5672, 0, 0,
		{"exchange_name": EXCHANGE_NAME, "routing_key": ROUTING_KEY, "virtual_host": VIRTUAL_HOST},
		None)
	
	try:
		zeroconf.register_service(zeroconf_info)
	except Zeroconf.NonUniqueNameException:
		LOG.warn("Service with name \'%s\' already broadcasting on this network!" % (getServiceName(),))

	try:
		while True:
			LOG.info("Now waiting for messages on %s" % (queueResult.method.queue,))
			chan.start_consuming()
	except KeyboardInterrupt:
		chan.stop_consuming()
		pass
	finally:
		LOG.info("Shutting down server...")
		shelve.close(MSG_DB_FILE)

		LOG.info("Closing connection with RabbitMQ")
		if conn is not None:
			conn.close()
		
		LOG.info("Unregistering server")
		zeroconf.unregister_service(zeroconf_info)
		zeroconf.close()
	
		LOG.info("Shutdown complete!")
예제 #13
0
 def empty(self):
     shelve = self._shelve
     shelve.close()
     os.remove(self._index_path)
     self._shelve = shelve.open(self._index_path, writeback=True)