Beispiel #1
0
    def __init__(self):
        self.principal = get_principal()

        self.config = ConfigManager(self)
        self.db = Database(self)

        self.zgram_queue = queue.Queue()
        self.error_queue = queue.Queue()

        def zgram_handler(zp, zgram):
            self.zgram_queue.put(zgram)
            # we send a SIGWINCH signal to ourselves,
            # making ncurses think that the window was resized.
            # this is the best way I know of to interrupt ncurses
            # in blocking mode.
            os.kill(os.getpid(), SIGWINCH)

        def error_handler(error):
            self.error_queue.put(error)
            os.kill(os.getpid(), SIGWINCH)

        self.zpipe = zpipe.ZPipe(['./zpipe/zpipe'], zgram_handler,
                                 error_handler)

        self.zpipe.subscribe('message', '*', self.principal)
        for class_, instance, recipient, _ in self.db.get_subscriptions():
            self.zpipe.subscribe(class_, instance, recipient)
	def setParams(self):
		ta=FreeCAD.ParamGet('User parameter:Plugins')
		ta.SetString("pluginlist","")
		pluginlist=[]
		for k in self.config.keys():
			if not self.config[k]['status'] == 'ignore':
				t=FreeCAD.ParamGet('User parameter:Plugins/'+k)
				pcm=ConfigManager(k)
				hide=pcm.get('_hide_',False)
				if hide:
					continue
				pluginlist.append(k)
				t.SetString("name",self.config[k]["name"])
				if self.config[k].has_key("author"): t.SetString("author",self.config[k]["author"])
				t.SetString("destination",self.config[k]["destdir"])
				t.SetInt('installed',1)
				itemlist=[]
				if self.config[k].has_key('menuitems'):
					for menu in self.config[k]['menuitems'].keys():
						itemlist.append(menu)
						tm=FreeCAD.ParamGet('User parameter:Plugins/'+k+'/'+menu)
						tm.SetString("exec",self.config[k]['menuitems'][menu]['exec'])
				if self.config[k].has_key('menu'):
					menu=self.config[k]['menu']
					itemlist.append(menu)
					tm=FreeCAD.ParamGet('User parameter:Plugins/'+k+'/'+menu)
					tm.SetString("exec",self.config[k]['exec'])
				ms=";".join(itemlist)
				if ms <>"":
					t.SetString("menulist",ms)
		ps=";".join(pluginlist)
		ta.SetString("pluginlist",ps)
Beispiel #3
0
def config_by_search():
    """Create a RDF Graph configuration file by searching for Orcid user."""
    orcid_profile = orcid_search(sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
	def __init__(self):
		mcf=''
		config3={}
		try:
			say("pluginmanager config file "+ fn)
			stream = open(fn, 'r').read()
			try:
				z=ConfigManager('')
				fn2=z.get('userconfigfile',"/usr/lib/freecad/Mod/plugins/myconfig.yaml")
				say("pluginmanager userconfig file "+ fn2)
				mcf = open(fn2, 'r').read()
			except:
				sayexc("userconfigfile not available",True)
			all=stream + mcf
			config3 = yaml.load(all)
		#	config3=set_defaults(config3)
		except:
			sayexc("Error in " + fn2,True)
			say("Try only:" + fn)
			config3 = yaml.load(stream)
		config3=set_defaults(config3)
		

		for plin in config3['plugins'].keys():
			for k in config3['plugins'][plin].keys():
				if config3['plugins'][plin][k] and config3['plugins'][plin][k].__class__ == dict:
					print "dict"
					print config3['plugins'][plin][k]
					if os in config3['plugins'][plin][k].keys():
						# replace
						config3['plugins'][plin][k]=config3['plugins'][plin][k][os]
			for att in ['destdir','exec','icon','backup']:
				try:
					config3['plugins'][plin][att]=pathMacro(config3['plugins'][plin][att])
				except:
					sayexc(config3['data'][plin][att])
			if plin=='defaulttest':
				pprint.pprint(config3['plugins'][plin])

		for plin in config3['data'].keys():
			for att in ['destdir','exec','icon','backup']:
				if config3['data'][plin].has_key(att):
					try:
						config3['data'][plin][att]=pathMacro(config3['data'][plin][att])
					except:
						sayexc(config3['data'][plin][att])

		self.config=config3['plugins']
		self.base=config3['base']
		self.config3=config3
		self.keys=self.config.keys
		
		#----------------------------
		if config3.has_key('keys') and config3['keys'].has_key("keyserver"):
			try:
				for ku in config3['keys']['keyserver'].keys():
					yy=transformkeytree(config3['keys']['keyserver'][ku])
					config3['keys']['keyserver'][ku]=yy
			except:
				sayexc()
Beispiel #5
0
 def configure_canvas(self, **kwargs):
     canvas_name = kwargs.pop("canvas_name", None)
     if canvas_name is not None:
         ConfigManager.set("canvas_name", canvas_name)
     options = remove_default_options(kwargs, self.canvas.configure())
     self.canvas.configure(**options)
     self.codetext.configure_canvas(canvas_name=canvas_name, **options)
Beispiel #6
0
 def set_theme(self, name):
     canvas_color = self.canvas.configure("bg")
     self.theme_manager.set_theme(name)
     self.codetext.update_theme()
     self.canvas.configure(bg=canvas_color[-1])
     self.update()
     ConfigManager.set("theme", name)
	def exe_query(self, file_name, serv_name, base_name, db_query):
		conf = ConfigManager("config/" + file_name + ".yaml")
		cnf = conf.get(serv_name)
		conn = cnf["connection"]
		database = cnf["databases"][base_name]

		if conn["type"] == "ssh":
			cmd = self.connect_command_builder(conn, 'no')
			common.conn.send(cmd)
			ans = None
			while ans == None:
				ans = common.conn.get_state()

			status, hostname, db_port = ans.split("_")
			adr = "localhost"

			if status == "ok":  #udało się utworzyć tunel
				self.psycop_query(database["name"], database["user"], conf.get_password(serv_name + '.' + base_name), adr, db_port, db_query)
			else:
				print('--------------------')
				print('Error: Unable to create ssh tunnel')
				print('--------------------')

		elif conn["type"] == "direct":
			self.psycop_query(database["name"], database["user"], conf.get_password(serv_name + '.' + base_name), conn["adress"], conn["remoteport"], db_query)
def create_command(server,perm):
	conf = ConfigManager("config/lista_test.yaml")
	connection =  conf.get(server)["connection"]
	try:
		cmd = connect_command_builder(connection,perm)
	except KeyError:
		cmd = None
	return cmd
Beispiel #9
0
 def create_sensor_connection():
     if "DATABASE3" in ConfigManager._config_dict:
         host2 = "%s:%s" % (ConfigManager.getvalue("DATABASE3", "host"),
                            ConfigManager.getvalue("DATABASE3", "port"))
         db_name2 = ConfigManager.getvalue("DATABASE3", "database")
         username2 = ConfigManager.getvalue("DATABASE3", "username")
         password2 = ConfigManager.getvalue("DATABASE3", "password")
         return DBHelperObject.create_connection(host2, db_name2, username2,
                                                 password2)
	def do_perm(self,arg):
		"Create permament ssh tunnel\n\tUsage:\tperm <list>.<server>\t(make permament tunnel to server)"
		params = arg.split(".")
		conf = ConfigManager("config/"+params[0]+".yaml")
		try:
			connection =  conf.get(params[1])["connection"]
			ret = send_command(self.connect_command_builder(connection,"yes"))
			print (ret)
		except KeePassError as e:
			print("Connecting to" , connection["adress"], "[", e, "]")
Beispiel #11
0
 def config_connection():
     host1 = "%s:%s" % (ConfigManager.getvalue(
         "DATABASE1", "host"), ConfigManager.getvalue("DATABASE1", "port"))
     DBHelperObject.CONFIG_DB_NAME = ConfigManager.getvalue(
         "DATABASE1", "database")
     username1 = ConfigManager.getvalue("DATABASE1", "username")
     password1 = ConfigManager.getvalue("DATABASE1", "password")
     return DBHelperObject.create_connection(host1,
                                             DBHelperObject.CONFIG_DB_NAME,
                                             username1, password1)
class InterfaceManager(object):
    def __init__(self, status_change_callback=print_data):
        ''' Creates a new InterfaceManager object. '''
        self._interfaces = {}
        path = wpath.etc + "interfaces.conf"
        self.config_manager = ConfigManager(path)
        self.backend_manager = BackendManager()
        self.backend_manager.load_all_available_backends()
        self.status_change_callback = status_change_callback
    def add(self, interface):
        ''' Adds interface to the dictionary of interfaces. '''
        self._interfaces[interface.interface_name] = interface
    def create(self, type, interface_name):
        ''' Creates the interface, if possible. If interface exists, returns. '''
        if not self.exists(interface_name):
            type_class = self.backend_manager.get_backend_by_type(type)
            new_interface = type_class(interface_name, self.status_change_callback)
            self.add(new_interface)
            print 'new interface: %s' % new_interface.interface_name
        else:
            print 'interface already exists: %s' % interface_name
    def get(self, interface_name):
        ''' Gets a single interface object. '''
        return self._interfaces.get(interface_name)
    def exists(self, interface_name):
        ''' Returns True if the specified interface exists, otherwise False. '''
        return bool(self._interfaces.get(interface_name))
    def load(self):
        """ Loads the saved interface configuration. """
        sections = self.config_manager.sections()
        for section in sections:
            interface_name = section
            type = self.config_manager.get_option(section, 'type')
            try:
                self.create(type, interface_name)
            except baseinterface.BaseInterface.CannotCreateInterfaceException:
                print 'error creating interface %s' % interface_name
                print 'skipping interface %s' % interface_name
            else:
                interface = self.get(interface_name)
                for k, v in self.config_manager.items(section):
                    setattr(interface, k, v)
    def save(self):
        """ Saves the current interface configuration. """
        self.config_manager.clear_all()
        for interface_name in self.get_all():
            interface = self.get(interface_name)
            interface.do_save()
            settings = interface.dump_settings_to_dictionary()
            for k, v in settings.iteritems():
                self.config_manager.set_option(interface_name, k, v)
        self.config_manager.write()
    def get_all(self):
        ''' Returns the interface dictionary. '''
        return self._interfaces
    def get_all_names(self):
        ''' Returns the names of all the interfaces. '''
        interfaces = self.get_all()
        names = [ value.interface_name for key, value in interfaces.iteritems() ]
        return names
Beispiel #13
0
def config_by_search():
    """Create a RDF Graph configuration file by searching for Orcid user."""
    orcid_profile = orcid_search(sandbox=False)
    if orcid_profile is not None:
        orcid_manager = OrcidManager(sandbox=False, orcid_id=orcid_profile)
        turtle_data = orcid_manager.get_turtle()
        config_file = ConfigManager()
        config_file.config_obj = turtle_data
        config_file.write_config()
    else:
        print("Sorry, ORCID returned no resutls for that user information.")
Beispiel #14
0
def config_by_id(orcid_id):
    """Create a RDF Graph configuration file by Orcid ID.

    :param orcid_id: string
        Orcid ID used for the configuration file ID and to create the configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    orcid_profile = OrcidManager(orcid_id=orcid_id, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Beispiel #15
0
def config_by_email(email):
    """Create a RDF Graph configuration file by Orcid email.

    :param email: string
        Orcid email address used to create a configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    email = 'email:' + email
    orcid_profile = OrcidManager(orcid_email=email, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
 def __init__(self, master, *args):
     QtGui.QWidget.__init__(self, *args)
     self.master = master
     #if hasattr(FreeCAD,"mywidget"):
     #	FreeCAD.mywidget.hide()
     FreeCAD.mywidget = self
     self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
     self.config = master.config
     self.vollabel = QtGui.QLabel('1. Select Packages ...')
     self.vollabel2 = QtGui.QLabel('2. Show Package Info ...')
     self.lab2 = QtGui.QLabel(str(datetime.now()))
     self.vollabel3 = QtGui.QLabel('3. Install/Update ...')
     self.pushButton02 = QtGui.QPushButton()
     self.pushButton02.clicked.connect(self.on_pushButton02_clicked)
     self.pushButton02.setText("Display ")
     self.pushButton03 = QtGui.QPushButton()
     self.pushButton03.clicked.connect(self.on_pushButton03_clicked)
     self.pushButton03.setText("Run")
     self.listWidget = QtGui.QListWidget()
     self.listWidget.setSelectionMode(
         QtGui.QAbstractItemView.MultiSelection)
     kl = self.config.keys()
     say(kl)
     for k in sorted(kl):
         pcm = ConfigManager(k)
         hide = pcm.get('_hide_', False)
         if not self.config[k]['status'] == "ignore" and not hide:
             item = QtGui.QListWidgetItem(k)
             self.listWidget.addItem(item)
     layout = QtGui.QGridLayout()
     self.setStyleSheet(
         "QListWidget,QPushButton {background-color: lightblue;color:brown;} "
     )
     line = 4
     layout.addWidget(self.vollabel, 0, 0)
     line = 3
     layout.addWidget(self.listWidget, line, 0, 1, 4)
     line += 1
     layout.addWidget(self.vollabel2, line, 0)
     line += 1
     layout.addWidget(self.lab2, line, 0)
     line += 1
     layout.addWidget(self.pushButton02, line, 0, 1, 4)
     line += 1
     layout.addWidget(self.vollabel3, line, 0)
     line += 1
     layout.addWidget(self.pushButton03, line, 0, 1, 4)
     line += 1
     line += 1
     self.setLayout(layout)
     self.setWindowTitle("Plugin Loader" + __vers__)
	def do_connect(self, arg):
		"""Create ssh tunnels\n\tUsage:\tconnect\t\t\t(connect using all server lists)
		connect list\t\t(connect using list)
		connect list.server\t(connect to server from list)"""
		if arg == "": # if no args connect to all
			print ("Connect to all")
			ans = input("Are you sure?[NO/yes/info]: ")
			lists = []
			for file in os.listdir("config"):
					if file.endswith(".yaml"):
						list_name = file.title()[:file.rfind(".")]
						lists.append(list_name)

			if ans == "info":
				print ("Lists with servers to connect:")
				for l in lists:
					print(l)
			elif ans == "yes":
				for l in lists:
					print("Connecting(",l,")")
					self.connectList("config/" + l + ".yaml")
			else:
				print("Aborted")

		else:
			params = arg.split(".")
			if len(params) == 1:
				print ("connect list...")
				self.connectList("config/"+params[0]+".yaml")
			elif len(params) == 2:
				print ("connect serv...")
				try:
					conf = ConfigManager("config/"+params[0]+".yaml")
					connection =  conf.get(params[1])["connection"]
					command = self.connect_command_builder(connection,"no")
					try:
						conn.send(command)
						t = None
						while t == None:
							t = conn.get_state()
						print(t)
					except AttributeError as e:
						print("Connection to ssh shepherd error!",e)
				except ConfigManagerError as e:
					print (e)
				except KeePassError as e:
					print("Connecting to" , connection["adress"], "[", e, "]")
				except Exception as e:
					print (e)
			else:
				print ("error")
Beispiel #18
0
def test_sms_sender(properties, deliver, channel, twilio_client, message, to, fixed_to):
    config = ConfigManager().configuration
    handler = MessageHandler(**config.get("sms"))
    handler.client = twilio_client
    consumer = MessageConsumer(handler, **config.get("rabbit"))

    consumer._handle_message(channel, deliver, properties, json.dumps({
        "receiver_phones": to,
        "message": message
    }).encode("utf8"))

    twilio_client.messages.create.assert_called_once_with(body=message,
                                                          from_=config.get("sms").get("sender"),
                                                          to=fixed_to)
def test_http_sender_queue(properties, deliver, channel, message, url, format):
    # Add message to queue

    message_raw = {"url": url, "message": message, "format": format}

    config = ConfigManager().configuration
    message_handler = MessageHandler()
    consumer = MessageConsumer(message_handler, **config.get("rabbit"))
    message_handler._send_http_post = MagicMock()

    consumer._handle_message(channel, deliver, properties,
                             json.dumps(message_raw).encode("utf8"))

    assert message_handler._send_http_post.called
Beispiel #20
0
    def __init__(self):
        self.root = Tk()
        winWidth = int(self.root.winfo_screenwidth() * WIN_WIDTH_RATIO)
        self.root.geometry("{}x{}".format(winWidth, WIN_HEIGHT))
        self.msg = Message(self.root, aspect=winWidth - 10)
        self.msg.grid(row=2, column=0, columnspan=2, padx=2)
        self.msgText = ''

        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/youtube_audio_download/audiodownload.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\youtube_audio_download\\audiodownload.ini'

        self.configMgr = ConfigManager(configFilePathName)
        self.emailLst = self.configMgr.getEmailLst()
	def test5_disconnect(self):
		conf = ConfigManager("config/lista_test.yaml")
		connection =  conf.get("ShouldBeOK")["connection"]
		try:
			cmd = connect_command_builder(connection,"no")
		except KeyError as e:
			self.fail("KeyError" + e)
		ans = send_command(cmd)
		status = ans.split("_")[0]
		if status != "ok":
			self.fail("Unable to create tunnel")
		dc = cmd.split("_")[0] + ":" + cmd.split("_")[4]		
		ans = send_command("clean;" + dc)
		to_find = connection["adress"] + ":" + str(connection["remoteport"])
		self.assertEqual(-1, ans.find(to_find))
Beispiel #22
0
    def gentoolbars(self, workbench='init'):
        global pathMacro
        cf = self.pluginloader.config
        say("gentoolbars ...")
        if self.pluginloader.config3["toolbars"].has_key(workbench):
            # say("toolbars for            ----------------------" + workbench)
            for ky in sorted(
                    self.pluginloader.config3["toolbars"][workbench].keys()):
                #say(ky)
                cma = ConfigManager("__toolbars__/" + workbench + "/" + ky)
                funhide = cma.get("_hide_", False)
                if funhide:
                    say("toolbar ignore item " + ky)
                    continue

                try:
                    mw = FreeCAD.Gui.getMainWindow()
                    mw.toolbar = mw.addToolBar(workbench + ': ' + ky)
                    mw.toolbar.setWindowTitle("Personal " + workbench + ': ' +
                                              ky)
                    #exitAction = QtGui.QAction('Exit 2', FreeCAD.Gui.getMainWindow())
                    #exitAction.setShortcut('.')
                    #exitAction.triggered.connect(QtGui.qApp.quit)
                    #mw.toolbar.addAction(exitAction)
                    mw.toolbar.show()
                    toolbarBox = mw.toolbar
                except Exception:
                    sayexc("exception add Tool Bar")
                for tool in sorted(self.pluginloader.config3["toolbars"]
                                   [workbench][ky].keys()):
                    say(tool)
                    yy = self.pluginloader.config3["toolbars"][workbench][ky][
                        tool]
                    myAction2 = QtGui.QAction(QtGui.QIcon(yy['icon']), tool,
                                              mw)
                    myAction2.setToolTip(tool)
                    try:
                        cmd = yy['exec']
                    except:
                        cmd = "say('" + str(yy) + "')"

                    yy = MyAction2(pathMacro(cmd))
                    myAction2.yy = yy
                    myAction2.triggered.connect(yy.run)
                    toolbarBox.addAction(myAction2)
                toolbarBox.show()
                self.toolbars.append(toolbarBox)
                say(ky + " done")
Beispiel #23
0
    def testGetProjectNameInvalidUserInput_minus_one(self):
        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/transfiles.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\trans_file_cloud\\test\\transfiles.ini'

        configManager = ConfigManager(configFilePathName)
        rq = Requester(configManager)

        # simulating user input
        stdin = sys.stdin

        # invalid user input of -1
        sys.stdin = StringIO('-1\nQ')

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString
        rq.getProjectName(
            None
        )  # will eat up what has been filled in stdin using StringIO above

        sys.stdin = stdin
        sys.stdout = stdout

        self.assertEqual(
            'Select project (Enter to loop or quit):\n\n1 transFileCloudTestProject\n2 transFileCloudProject\n3 transFileCloudFilePathNameProject\n4 cartesianAxesProject\n5 transFileCloudInvalidProject\n\nInvalid selection. Select project (Enter to loop or quit):\n\n1 transFileCloudTestProject\n2 transFileCloudProject\n3 transFileCloudFilePathNameProject\n4 cartesianAxesProject\n5 transFileCloudInvalidProject\n\n',
            outputCapturingString.getvalue())
Beispiel #24
0
    def openDB(self):
        try:
            self._config = ConfigManager()
            self.db = self._config.config[self._config.database]["database"]
            create_db = False
            if self.db == self._config.Sqlite:
                folder = self._config.config[self._config.database]["folder"]
                loc = folder + '/icepapcms.db'
                create_db = not os.path.exists(loc)
                if create_db:
                    if not os.path.exists(folder):
                        os.mkdir(folder)
                self._database = create_database("%s:%s" % (self.db, loc))
            else:
                server = self._config.config[self._config.database]["server"]
                user = self._config.config[self._config.database]["user"]
                pwd = self._config.config[self._config.database]["password"]
                self._database = create_database("%s://%s:%s@%s/icepapcms" %
                                                 (self.db, user, pwd, server))

            self._store = Store(self._database)
            if create_db:
                self.dbOK = self.createSqliteDB()
            else:
                self.dbOK = True
        except:
            print "Unexpected error:", sys.exc_info()
            self.dbOK = False
Beispiel #25
0
    def testGetUserConfirmation_downloadFiles(self):
        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/transfiles.ini'
        else:
            configFilePathName = 'D:\\Development\\Python\\trans_file_cloud\\test\\transfiles.ini'

        configManager = ConfigManager(configFilePathName)
        rq = Requester(configManager)

        # simulating user input
        stdin = sys.stdin
        sys.stdin = StringIO('y')

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString

        cloudFileLst = [
            'constants_2.py', 'filelister_2.py', 'testfilelister_2.py'
        ]
        questionStr = 'vvv {} files will be transferred from the cloud and then moved to the correct dir and sub-dir of {}.\nIf you want to upload new modified files instead, type N'.format(
            len(cloudFileLst), 'ru.iiec.pydroid3/files/trans_file_cloud')
        doDownload, lastSynchTimeChoice = rq.getUserConfirmation(
            questionStr, cloudFileLst)

        sys.stdin = stdin
        sys.stdout = stdout

        self.assertEqual(
            '\nconstants_2.py\nfilelister_2.py\ntestfilelister_2.py\n\nvvv 3 files will be transferred from the cloud and then moved to the correct dir and sub-dir of ru.iiec.pydroid3/files/trans_file_cloud.\nIf you want to upload new modified files instead, type N.\n\nContinue (Y/YK/N/Enter) ',
            outputCapturingString.getvalue())
        self.assertTrue(doDownload)
        self.assertEqual('', lastSynchTimeChoice)
 def __init__(self, status_change_callback=print_data):
     ''' Creates a new InterfaceManager object. '''
     self._interfaces = {}
     path = wpath.etc + "interfaces.conf"
     self.config_manager = ConfigManager(path)
     self.backend_manager = BackendManager()
     self.backend_manager.load_all_available_backends()
     self.status_change_callback = status_change_callback
Beispiel #27
0
    def init_connection():
        host1 = "%s:%s" % (ConfigManager.getvalue(
            "DATABASE1", "host"), ConfigManager.getvalue("DATABASE1", "port"))
        db_name1 = ConfigManager.getvalue("DATABASE1", "database")
        DBHelperObject.CONFIG_DB_NAME = db_name1
        username1 = ConfigManager.getvalue("DATABASE1", "username")
        password1 = ConfigManager.getvalue("DATABASE1", "password")
        DBHelperObject.CONFIG_CON = DBHelperObject.create_connection(
            host1, db_name1, username1, password1)

        host2 = "%s:%s" % (ConfigManager.getvalue(
            "DATABASE2", "host"), ConfigManager.getvalue("DATABASE2", "port"))
        db_name2 = ConfigManager.getvalue("DATABASE2", "database")
        username2 = ConfigManager.getvalue("DATABASE2", "username")
        password2 = ConfigManager.getvalue("DATABASE2", "password")
        DBHelperObject.ACC_CON = DBHelperObject.create_connection(
            host2, db_name2, username2, password2)
	def __init__(self, master,*args):
		QtGui.QWidget.__init__(self, *args)
		self.master=master
		FreeCAD.mywidget=self
		self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
		self.config=master.config
		self.vollabel = QtGui.QLabel('1. Select Packages ...')
		self.vollabel2 = QtGui.QLabel('2. Show Package Info ...')
		self.lab2 = QtGui.QLabel(str(datetime.now()))
		self.vollabel3 = QtGui.QLabel('3. Install/Update ...')
		self.pushButton02 = QtGui.QPushButton()
		self.pushButton02.clicked.connect(self.on_pushButton02_clicked) 
		self.pushButton02.setText("Display ")
		self.pushButton03 = QtGui.QPushButton()
		self.pushButton03.clicked.connect(self.on_pushButton03_clicked) 
		self.pushButton03.setText("Run")
		self.listWidget = QtGui.QListWidget() 
		self.listWidget.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
		kl=self.config.keys()
		say(kl)
		for k in sorted(kl):
			pcm=ConfigManager(k)
			hide=pcm.get('_hide_',False)
			if not self.config[k]['status'] == "ignore" and not hide:
				item = QtGui.QListWidgetItem(k)
				self.listWidget.addItem(item)
		layout = QtGui.QGridLayout()
		self.setStyleSheet("QListWidget,QPushButton {background-color: lightblue;color:brown;} ")
		line=4
		layout.addWidget(self.vollabel, 0, 0)
		line=3
		layout.addWidget(self.listWidget, line, 0,1,4)
		line+=1
		layout.addWidget(self.vollabel2, line, 0)
		line+=1
		layout.addWidget(self.lab2, line, 0)
		line+=1
		layout.addWidget(self.pushButton02, line, 0,1,4)
		line+=1
		layout.addWidget(self.vollabel3, line, 0)
		line+=1
		layout.addWidget(self.pushButton03, line, 0,1,4)
		line+=1
		line+=1
		self.setLayout(layout)
		self.setWindowTitle("Plugin Loader" + __vers__)
 def setParams(self):
     ta = FreeCAD.ParamGet('User parameter:Plugins')
     ta.SetString("pluginlist", "")
     pluginlist = []
     for k in self.config.keys():
         if not self.config[k]['status'] == 'ignore':
             t = FreeCAD.ParamGet('User parameter:Plugins/' + k)
             pcm = ConfigManager(k)
             hide = pcm.get('_hide_', False)
             if hide:
                 continue
             pluginlist.append(k)
             #say("--")
             #say(k)
             #say(self.config[k])
             #say(self.config[k]["name"])
             t.SetString("name", self.config[k]["name"])
             if self.config[k].has_key("author"):
                 t.SetString("author", self.config[k]["author"])
             t.SetString("destination", self.config[k]["destdir"])
             t.SetInt('installed', 1)
             itemlist = []
             if self.config[k].has_key('menuitems'):
                 for menu in self.config[k]['menuitems'].keys():
                     #say(menu)
                     itemlist.append(menu)
                     tm = FreeCAD.ParamGet('User parameter:Plugins/' + k +
                                           '/' + menu)
                     tm.SetString("exec",
                                  self.config[k]['menuitems'][menu]['exec'])
             else:
                 #say("keine menuitmes")
                 pass
             if self.config[k].has_key('menu'):
                 menu = self.config[k]['menu']
                 #say(menu)
                 itemlist.append(menu)
                 tm = FreeCAD.ParamGet('User parameter:Plugins/' + k + '/' +
                                       menu)
                 tm.SetString("exec", self.config[k]['exec'])
             ms = ";".join(itemlist)
             if ms <> "":
                 t.SetString("menulist", ms)
     ps = ";".join(pluginlist)
     ta.SetString("pluginlist", ps)
Beispiel #30
0
 def __init__(self, config=None):
     self.config = config or ConfigManager().get_specific_configuration(
         "alerts_processor")
     super().__init__(self.config["amqp_url"])
     self.exchange = self.config["exchange"]
     self.exchange_type = self.config["exchange_type"]
     self.queue = self.config["queue"]
     self.routing_key = self.config["routing_key"]
     self.alerts_enricher = AlertEnricher()
     self.alerts_inserter = AlertsInserter()
Beispiel #31
0
 def __init__(self, config=None):
     if config is None:
         self.config = ConfigManager().get_specific_configuration(
             "alerts_enricher")
     else:
         self.config = config
     self.db_connection = PostgresClient(host=self.config["host"],
                                         user=self.config["user"],
                                         password=self.config["pass"],
                                         database=self.config["database"])
Beispiel #32
0
	def gentoolbars(self,workbench='init'):
		global pathMacro
		cf=self.pluginloader.config
		say("gentoolbars ...")
		if self.pluginloader.config3["toolbars"].has_key(workbench):
			# say("toolbars for            ----------------------" + workbench)
			for ky in sorted(self.pluginloader.config3["toolbars"][workbench].keys()):
				#say(ky)
				cma=ConfigManager("__toolbars__/" + workbench +"/" + ky)
				funhide=cma.get("_hide_",False)
				if funhide:
					say("toolbar ignore item " + ky)
					continue

				try:
					mw=FreeCAD.Gui.getMainWindow()
					mw.toolbar = mw.addToolBar(workbench +': ' + ky)
					mw.toolbar.setWindowTitle("Personal " + workbench +': ' +ky)
					#exitAction = QtGui.QAction('Exit 2', FreeCAD.Gui.getMainWindow())
					#exitAction.setShortcut('.')
					#exitAction.triggered.connect(QtGui.qApp.quit)
					#mw.toolbar.addAction(exitAction)
					mw.toolbar.show()
					toolbarBox=mw.toolbar
				except Exception:
					sayexc("exception add Tool Bar")
				for tool in sorted(self.pluginloader.config3["toolbars"][workbench][ky].keys()):
					say(tool)
					yy=self.pluginloader.config3["toolbars"][workbench][ky][tool]
					myAction2=QtGui.QAction(QtGui.QIcon(yy['icon']),tool ,mw)
					myAction2.setToolTip(tool)
					try:
						cmd=yy['exec']
					except:
						cmd="say('"+str(yy)+"')"
					
					yy=MyAction2(pathMacro(cmd))
					myAction2.yy=yy
					myAction2.triggered.connect(yy.run) 
					toolbarBox.addAction(myAction2)
				toolbarBox.show()
				self.toolbars.append(toolbarBox)
				say(ky +" done")
Beispiel #33
0
def simulator_loop():
    conf_manager = ConfigManager()

    frost_config = conf_manager.get_specific_configuration("sensorthings")
    frost_url = frost_config.pop("url")
    frost_port = frost_config.pop("port")
    query_sleep = frost_config.pop("query_sleep")

    simulator_config = conf_manager.get_specific_configuration("simulator")
    mu = simulator_config.pop("mu")
    sigma = simulator_config.pop("sigma")

    frost_base_url = "http://{}:{}/FROST-Server/v1.0/".format(frost_url, frost_port)
    frost_observation_url = frost_base_url + "Observations"

    datastream_id = create_datastream(frost_base_url)

    with open("schemas/tiltmeter_observation_template.json") as f:
        template = f.read()
        template = template.replace("{datastream_id}", datastream_id)

    while True:
        axis_one = random.gauss(mu, sigma)
        axis_two = random.gauss(mu, sigma)
        dt = datetime.datetime.now()

        new_data = template.replace("{axis_one}", str(axis_one))
        new_data = new_data.replace("{axis_two}", str(axis_two))
        new_data = new_data.replace("{datetime}", dt.strftime("%Y-%m-%dT%H:%M:%SZ"))

        # TODO: find the way to prevent from having to write-read the file every iteration
        with open("schemas/tiltmeter_sensorthings.json", "w") as f:
            f.write(new_data)

        with open("schemas/tiltmeter_sensorthings.json", "rb") as f:
            response = requests.post(frost_observation_url,
                                     headers={"content-type": "application/json"},
                                     data=f)

        logging.info(response.request)

        time.sleep(query_sleep)
def test_email_sender(properties, deliver, channel, server, sender, recipients,
                      subject, message):
    def _build_server():
        return server

    config = ConfigManager().configuration
    handler = MessageHandler(**config.get("smtp"))
    handler._build_server = _build_server
    consumer = MessageConsumer(handler, **config.get("rabbit"))

    consumer._handle_message(
        channel, deliver, properties,
        json.dumps({
            "receiver_emails": recipients,
            "message_html": message,
            "title": subject
        }).encode("utf8"))

    server.sendmail.assert_called_once_with(sender, '*****@*****.**',
                                            ANY)
Beispiel #35
0
def main(application_name, arguments):
    """
    Main procedure.

    Parameters
    ----------
    application_name : str
        The name of the application (used in console messages).
    arguments : list of str
        The command line arguments passed to the interpreter (beside the name of the script).
    """

    # Parse command line arguments.
    is_config_generation_requested = False
    config_file_path = DEFAULT_CONFIG_PATH

    try:
        opts, _ = getopt.getopt(arguments, 'c:ih', ['config=', 'install'])
    except getopt.GetoptError:
        print_usage_and_exit(application_name, 2)

    for opt, arg in opts:
        if opt in ('-c', '--config'):
            config_file_path = arg
        elif opt in ('-h', '--help'):
            print_usage_and_exit(application_name)
        elif opt in ('-i', '--install'):
            is_config_generation_requested = True

    config_manager = ConfigManager(config_file_path)

    # Create configuration file and exit.
    if is_config_generation_requested:
        config = Config()
        config.create_default()
        config_manager.save(config)
    # Load configuration, then go ahead.
    else:
        config = config_manager.load()
        app = App(config)
        app.execute()
Beispiel #36
0
def init_config(config=None):
    """
    Initialize the server with the endpoints.
    Args:
        config:
    """
    if config is None:
        config = ConfigManager().configuration
    else:
        config = config
    ConfigureLogging(**config["logger"])
    app.config.update(**config)
Beispiel #37
0
def config_by_search():
    """Create a RDF Graph configuration file by searching for Orcid user."""
    orcid_profile = orcid_search(sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Beispiel #38
0
def get_config(config_file):
    # FIXME gross hack, ditch or fork this module, and numpy why?
    # class fakemodule(object):
    #     pass
    #sys.modules["PyQt5.QtWebKit"] = fakemodule
    #sys.modules["PyQt5.QtWebKitWidgets"] = fakemodule
    # os.environ['QT_API'] = '0'
    # sys.modules["numpy"] = fakemodule
    # from pyqtconfig.qt import QObject, PYSIDE, QT_API_ENV
    # print('----', QObject, PYSIDE, QT_API_ENV)
    #from pyqtconfig import ConfigManager # isort:skip

    cfg = ConfigManager()
    cfg.set_defaults({
        'run_at_startup': False,
        'watch_dir': '.',
        'api_token': '',
        'account_id': '',
        'always_running': False,
    })
    try:
        with open(config_file, 'r') as f:
            raw_config = json.loads(f.read())
            raw_config['account_id'] = str(raw_config['account_id'])
            cfg.set_defaults(raw_config)
    except FileNotFoundError:
        logging.info('Found no config file, using defaults')
    except JSONDecodeError:
        logging.error('Invalid config file, noit valid json')
    return cfg
Beispiel #39
0
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent

        self.config(bg=storedsettings.APP_MAIN_COLOR)

        self.ran = False
        self.mgr = ConfigManager()

        self.frame_buttons = tk.Frame(self, bg=storedsettings.APP_MAIN_COLOR)
        self.frame_buttons.grid(row=0, column=0)

        self.draw_menu()
Beispiel #40
0
    def checkFirmwareVersions(self, icepap_system):
        config = ConfigManager()
        if config._options.skipversioncheck == True:
            print "Firmware versions are not checked."
            return
        try:
            icepap_name = icepap_system.name
            master_version = self._ctrl_icepap.iPaps[icepap_name].getVersion(
                0, "DRIVER")
            master_version = str(master_version)
            mismatched_drivers = []
            for driver in icepap_system.getDrivers():
                #####################################################################
                driver_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersion(driver.addr, "DRIVER")
                # If the driver has been temporary removed, the error should
                if driver_version.count("ERROR") > 0:
                    driver_version = master_version
                if master_version != driver_version:
                    mismatched_drivers.append(
                        (driver.addr, str(driver_version)))

            if len(mismatched_drivers) > 0:
                msg = "Some drivers do not have the MASTER's firmware version (%s):\n" % (
                    master_version)
                for driver, version in mismatched_drivers:
                    msg = msg + "driver %d: %s\n" % (driver, version)
                saved_version = self._ctrl_icepap.iPaps[
                    icepap_name].getVersionSaved()
                msg = msg + "Board saved version: %s\n" % (saved_version)
                msg = msg + "Would you like to upgrade these drivers?\n"
                upgrade = MessageDialogs.showYesNoMessage(
                    self._form, "Firmware mismatch", msg)
                if upgrade:
                    progress_dialog = QtGui.QProgressDialog(self._form)
                    progress_dialog.setLabel(
                        QtGui.QLabel(
                            "Icepap: %s\nUpgrading drivers' firmware to %s" %
                            (icepap_name, saved_version)))
                    progress_dialog.setCancelButton(None)
                    progress_dialog.setMaximum(100)
                    upgrading = self._ctrl_icepap.upgradeDrivers(
                        icepap_name, progress_dialog)
                    if not upgrading:
                        progress_dialog.cancel()
                        msg = "Sorry, problems found while upgrading. Please try it manually :-("
                        MessageDialogs.showErrorMessage(
                            None, "Firmware upgrade error", msg)
        except:
            pass
	def connectList(self, listFile):
		try:
			conf = ConfigManager(listFile)
		except Exception as e:
			print ("No conf file", listFile)
			return 1

		server_list = []
		for server in conf.get_list():
			server_list.append(server)

		connection_list ={}
		for server in server_list:
			connection =  conf.get(server)["connection"]
			try:
				command = self.connect_command_builder(connection,"no")
				try:
					conn.send(command)
					t = None
					while t == None:
						t = conn.get_state()
						#status_adres_localport
					server_status = t.split("_")
					try:
						connection_list[server_status[1]]=server_status[2]
						print("Connecting to" , connection["adress"], "[", server_status[0], "]")
					except IndexError as e:
						print(t)
				except AttributeError as e:
					print("Connection to ssh shepherd error!",e)
			except KeePassError as e:
				print("Connecting to" , connection["adress"], "[", e, "]")
			except KeyError as e:
				print("Connecting to" , connection["adress"], "[", e, "]")
			except Exception as e:
					print (e)	
    def testMoveFilesToLocalDirs_dirNotExist(self):
        if os.name == 'posix':
            downloadDir = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/fromdir'
            downloadDirSaved = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/fromdir_saved'
            projectDir = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/projectdir'
        else:
            # Windows
            downloadDir = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\fromdir'
            downloadDirSaved = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\fromdir_saved'
            projectDir = 'D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\projectdir'

        configManager = ConfigManager(CONFIG_FILE_PATH_NAME)

        # deleting downloadDir (dir and content)
        if os.path.exists(downloadDir):
            shutil.rmtree(downloadDir)

        # restoring downloadDir from its saved version
        shutil.copytree(downloadDirSaved, downloadDir)

        projectName = 'transFileCloudTestProject'
        fm = FileMover(configManager, projectName)
        fm.projectDir = projectDir

        # capturing stdout into StringIO to avoid outputing in terminal
        # window while unit testing

        stdout = sys.stdout
        outputCapturingString = StringIO()
        sys.stdout = outputCapturingString

        cloudFileLst = ['constants_1.mp3']

        fm.moveFilesToLocalDirs(cloudFileLst)

        sys.stdout = stdout

        if os.name == 'posix':
            self.assertEqual([
                'Destination dir /storage/emulated/0/Android/data/ru.iiec.pydroid3/files/trans_file_cloud/test/testproject_1/projectdir/mp3/not_exist does not exist. Program stopped.'
            ],
                             outputCapturingString.getvalue().split('\n')[:-1])
        else:
            self.assertEqual([
                'Destination dir D:\\Development\\Python\\trans_file_cloud\\test\\testproject_1\\projectdir\\mp3\\not_exist does not exist. Program stopped.'
            ],
                             outputCapturingString.getvalue().split('\n')[:-1])
Beispiel #43
0
class PluginManager(object):
    def __init__(self,  daemon):
        self.daemon = daemon
        self.config_manager = ConfigManager('/etc/wicd/plugins.conf')
        self.loaded_plugins = []
        self.load_all_plugins()
    def set_daemon(self, daemon):
        self.daemon = daemon
    def find_available_plugins(self):
        available_plugins = []
        for item in os.listdir(os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            'plugins')):
            if item.endswith('.py') and \
               not item == 'baseplugin.py' and \
               not item == '__init__.py':
                available_plugins.append(item)
        return available_plugins
    def load_all_plugins(self):
        classes = []
        for plugin in self.find_available_plugins():
            module = self.load_plugin(plugin)
            for item in dir(module):
                if item.endswith("Plugin") \
                   and not item == 'BasePlugin' \
                   and self.config_manager.get_option(item, 'enabled', True):
                    the_class = getattr(module, item)
                    classes.append(the_class)
        import operator
        classes.sort(key=operator.attrgetter('PRIORITY'))
        for the_class in classes:
            logging.debug( 'loading plugin %s', the_class)
            self.loaded_plugins.append(the_class(self.daemon))
    def load_plugin(self, name):
        if name in self.find_available_plugins():
            if name.endswith('.py'):
                name = name[:-3]
            module = __import__('plugins.' + str(name))
            module = getattr(module, name)
            return module
        else:
            raise WicdError('Plugin %s was not found' % name)
    def action(self, action_name, values=()):
        for plugin in self.loaded_plugins:
            if hasattr(plugin, "do_%s" % action_name):
                getattr(plugin, "do_%s" % action_name)(*values)
Beispiel #44
0
def config_by_id(orcid_id):
    """Create a RDF Graph configuration file by Orcid ID.

    :param orcid_id: string
        Orcid ID used for the configuration file ID and to create the configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    orcid_profile = OrcidManager(orcid_id=orcid_id, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
Beispiel #45
0
    def __init__(self, _):

        """
        Args:
        _ : Command line arguments (not currently used)
        """

        self.configmanager = ConfigManager(".")

        self.plotter = Plotter(self.configmanager)
        self.windplotter = WindPlotter(self.configmanager)
        self.histogram = Histogram()

        self.msg_queue = None
        self.loading_timer = None
        self.data_manager = None

        self.gui = GUI(self.request_handler)
Beispiel #46
0
def config_by_email(email):
    """Create a RDF Graph configuration file by Orcid email.

    :param email: string
        Orcid email address used to create a configuration file.
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    email = 'email:' + email
    orcid_profile = OrcidManager(orcid_email=email, sandbox=False)
    turtle_data = orcid_profile.get_turtle()
    config_file = ConfigManager()
    config_file.get_config(_id=orcid_profile.orcid_id, _data=turtle_data)
    config_file.write_config()
    def __init__(self, audioDownloaderGUI, audioDir, configMgr=None):
        """
		
		:param audioDownloaderGUI: used for unit testing only !
		"""

        if os.name == 'posix':
            configFilePathName = '/storage/emulated/0/audiodownloader.ini'
        else:
            configFilePathName = 'c:\\temp\\audiodownloader.ini'

        if configMgr == None:
            self.configMgr = ConfigManager(configFilePathName)
        else:
            self.configMgr = configMgr

        self.requester = Requester(self.configMgr)
        self.audioDownloaderGUI = audioDownloaderGUI
        self.audioDownloader = YoutubeDlAudioDownloader(self, audioDir)
Beispiel #48
0
 def signDriver(self):
     # AS ESRF SAYS, WHEN SIGNING THE DRIVER CONFIG, THE COMMIT SHOULD BE DONE
     # IN THE DATABASE FIRST, AND IF NO ERRORS, THEN COMMUNICATE THE DRIVER
     # THAT THE VALUES SHOULD BE SIGNED.
     try:
         #signature = socket.gethostname() #+ "_" + str(time.time())
         user = ConfigManager().username
         host = socket.gethostname()
         signature = user+"@"+host+"_"+datetime.now().strftime('%Y/%m/%d_%H:%M:%S')
         IcepapController().signDriverConfiguration(self.icepapsystem_name, self.addr, signature)
         self.mode = unicode(Mode.OPER)
         db = StormManager()
         db.commitTransaction()
         self.current_cfg.name = unicode(time.ctime())
         self.current_cfg.setSignature(signature)        
         self.startup_cfg = self.current_cfg
         self.conflict = Conflict.NO_CONFLICT
     except Exception,e:
         print "some exception while trying to sign the driver",e
Beispiel #49
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from pytibotfactory import PyTIBotFactory
from twisted.internet import reactor
from twisted.manhole import telnet
from configmanager import ConfigManager
import sys

mandatory_settings = [("Connection", "server"), ("Connection", "port"),
                      ("Connection", "nickname"), ("Connection", "admins")]

if __name__ == "__main__":
    configfile = sys.argv[1] if len(sys.argv) > 1 else "pytibot.ini"
    # create Config Manager
    cm = ConfigManager(configfile, delimiters=("="))

    if all([cm.option_set(sec, opt) for sec, opt in mandatory_settings]):
        # connect factory to host and port
        server = cm.get("Connection", "server")
        port = cm.getint("Connection", "port")
        botfactory = PyTIBotFactory(cm)
        reactor.connectTCP(server, port, botfactory)

        # manhole for debugging
        open_telnet = False
        if cm.option_set("Connection", "open_telnet"):
            open_telnet = cm.getboolean("Connection", "open_telnet")

        if open_telnet:
            tn_f = telnet.ShellFactory()
Beispiel #50
0
def config_by_email(orcid_email):
    """Create a RDF Graph configuration file by Orcid email."""
    # Make sure sandbox variable is set correctly in cli.py before testing
    email = 'email:' + orcid_email
    config = ConfigManager(orcid_email=email, sandbox=sandbox)
    config.write_config()
	def exe_restore(self, file_name, serv_name, base_name, backup_name, type):

		try:
			conf = ConfigManager("config/" + file_name + ".yaml")
			cnf = conf.get(serv_name)
			conn = cnf["connection"]
			db = cnf["databases"][base_name]

			db_name = db["name"]
			db_user = db["user"]
			db_pass = conf.get_password(serv_name + '.' + base_name)
			conn_adr = ''
			conn_port = None

			if conn["type"] == "ssh": #Dla połączeń ssh
				cmd = self.connect_command_builder(conn, 'no')
				common.conn.send(cmd)
				ans = None
				while ans == None:
					ans = common.conn.get_state()

				status, hostname, db_port = ans.split("_")

				if status == "ok":  #udało się utworzyć tunel
					conn_adr = 'localhost'
					conn_port = db_port
				else:
					raise PostgressError('Unable to create ssh tunnel')

			elif conn["type"] == "direct":
				conn_adr = conn["adress"]
				conn_port = conn["remoteport"]

			local_version = self.get_local_version('pg_dump --version')
			remote_version = self.get_pg_version(db_name, db_user, db_pass, conn_adr, conn_port)
			if not self.is_valid_versions(local_version, remote_version):
				raise PostgressError("You have too old version of pg_dump")

			self.restore(db_name, db_user, db_pass, conn_adr, conn_port, backup_name, type)

		except ConnectionRefusedError:
			print('--------------------')
			print('ERROR: Connection Refused by host')
			print('--------------------')
		except TimeoutError:
			print('--------------------')
			print('ERROR: Connection timeout')
			print('--------------------')
		except paramiko.ssh_exception.AuthenticationException:
			print('--------------------')
			print('ERROR: Authentication problem')
			print('--------------------')
		except KeyError as e:
			print('--------------------')
			print('ERROR: Unable to find key:',e)
			print('--------------------')
		except PostgressError as e:
			print('--------------------')
			print('ERROR:',e)
			print('--------------------')
		except Exception as e:
			print('--------------------')
			print('ERROR:',e)
			print('--------------------')
Beispiel #52
0
def config_by_id(id):
    """Create a RDF Graph configuration file by Orcid ID."""
    # Make sure sandbox variable is set correctly in cli.py before testing
    config = ConfigManager(orcid_id=id, sandbox=sandbox)
    config.write_config()
Beispiel #53
0
 def __init__(self):
     self.db_path = ConfigManager.getvalue("local", "db_path")
     if not os.path.exists(self.db_path):
         raise AttributeError("The sqlite path is not exists. %s" % self.db_path)
     self.db_con = None
Beispiel #54
0
 def __init__(self,  daemon):
     self.daemon = daemon
     self.config_manager = ConfigManager('/etc/wicd/plugins.conf')
     self.loaded_plugins = []
     self.load_all_plugins()
Beispiel #55
0
	def genlabels(self):
		cf=self.pluginloader.config
		try:
			self.tabs.deleteLater()
		except:
			pass
			
		if self.pluginloader.config3.has_key("tabs"):
			tabs= QtGui.QTabWidget()
			kl=sorted(self.pluginloader.config3["tabs"].keys())
			# where to place the tabs -  still hard coded
			mode="north"
			if self.pluginloader.config3['base'].has_key('tablocation'):
				mode= self.pluginloader.config3['base']['tablocation']
			if mode =="west":
				tabs.setTabPosition(QtGui.QTabWidget.West)
				kl.reverse()
			if mode =="east":
				tabs.setTabPosition(QtGui.QTabWidget.East)
				kl.reverse()
			
			for ky in kl:
				import re
				
				cmt=ConfigManager("__tabs__/" + ky)
				hide=cmt.get("_hide_",False)
				if hide:
						say("ignore tab " + ky)
						continue
				
				tab1= QtGui.QWidget()
				pat=r"[0123456789]+ +(.*)"
				m = re.match(pat, ky)
				if m:
					kyk=m.group(1)
				else:
					kyk=ky
				tabs.addTab(tab1,kyk)
				vBoxlayout	= QtGui.QVBoxLayout()
				vBoxlayout.setAlignment(QtCore.Qt.AlignTop)
				head=QtGui.QLabel(kyk.upper())
				vBoxlayout.addWidget(head)
				head.setStyleSheet("QWidget { font: bold 18px;color:brown;}")
				if self.pluginloader.config3['tabs'][ky].has_key("info"):
					info=QtGui.QLabel(self.pluginloader.config3['tabs'][ky]["info"])
					vBoxlayout.addWidget(info)

				for fun in sorted(self.pluginloader.config3["tabs"][ky].keys()):
					cma=ConfigManager("__tabs__/" + ky +"/" + fun)
					funhide=cma.get("_hide_",False)
					if funhide:
						say("ignore item " + fun)
						continue
					ff=self.pluginloader.config3["tabs"][ky][fun]
					if fun == 'info':
						continue
					import re
					pat=r"[0123456789]+[\.]? +(.*)"
					m = re.match(pat, fun)
					if m:
						funk=m.group(1)
					else:
						funk=fun
					if ff.has_key('icon'):
						pushButton1 = QtGui.QPushButton(QtGui.QIcon(ff['icon']),funk)
					else:
						pushButton1 = QtGui.QPushButton(QtGui.QIcon(FreeCAD.ConfigGet('AppHomePath')+'/Mod/plugins/icons/sun.png'),funk)
					#say("!!" + fun + " ->" + funk + "<-")
					if ff.has_key('info'): 
						pushButton1.setToolTip(ff['info'])
					try:
						cmd=ff['exec']
					except:
						cmd="say('"+str(ff)+"')"
					#say("cmd="+cmd)
					yy=MyAction2(cmd)
					yy=MyAction2(pathMacro(cmd))
					pushButton1.yy=yy
					pushButton1.clicked.connect(yy.run) 
					hWid= QtGui.QWidget()
					hBoxlayout	= QtGui.QHBoxLayout()
					hBoxlayout.setContentsMargins(0, 0, 0, 0)
					hWid.setLayout(hBoxlayout)
					pushButt_1 = QtGui.QPushButton(funk)
					hBoxlayout.addWidget(pushButton1)
					if ff.has_key('man'):
						pushButt_2 = QtGui.QPushButton(QtGui.QIcon(FreeCAD.ConfigGet('AppHomePath')+'/Mod/plugins/icons/help.png'),'')
						pushButt_2.setToolTip('See WebSite Documentation')
						cmdh='import WebGui; WebGui.openBrowser( "' +ff['man'] + '")'
						yh=MyAction2(cmdh)
						pushButt_2.yh=yh
						pushButt_2.clicked.connect(yh.run) 
						hBoxlayout.addWidget(pushButt_2)
						pushButton1.setFixedWidth(250)
					else:
						pushButton1.setFixedWidth(290)
					hBoxlayout.setAlignment(QtCore.Qt.AlignLeft)
					vBoxlayout.addWidget(hWid)
					vBoxlayout.setSpacing(0)
				tab1.setLayout(vBoxlayout)   
		#self.lilayout.addWidget(tabs)
		self.myform.addWidget(tabs)
		
		# aktiver tab
		cm=ConfigManager("PluginManager")
		ix=cm.get("PluginTabIndex",0)
		tabs.setCurrentIndex(ix) # private testing
		# tabs.setCurrentIndex(10)  # == Favorites
		self.tabs=tabs
Beispiel #56
0
class Application:

    """
    Handles interaction between GUI events, GUI drawing, plotting, file reading etc.
    """

    def __init__(self, _):

        """
        Args:
        _ : Command line arguments (not currently used)
        """

        self.configmanager = ConfigManager(".")

        self.plotter = Plotter(self.configmanager)
        self.windplotter = WindPlotter(self.configmanager)
        self.histogram = Histogram()

        self.msg_queue = None
        self.loading_timer = None
        self.data_manager = None

        self.gui = GUI(self.request_handler)

    def request_handler(self, request, *args):
        """
        This function is passed to the GUI.
        When a button is pressed or information is required, the GUI uses this function
        to access the application.

        Args:
        request: One of the request IDs defined in app_reqs.py. Determines the action that is taken.
        args: List of additional argument that may be required on a per-request basis
        """

        if request == REQS.CHANGE_SUBPLOT1:
            self.action_subplot_change(0, args[0])
        elif request == REQS.CHANGE_SUBPLOT2:
            self.action_subplot_change(1, args[0])
        elif request == REQS.CHANGE_SUBPLOT3:
            self.action_subplot_change(2, args[0])
        elif request == REQS.AVERAGE_SUBPLOT_DATA:
            self.action_average_data()
        elif request == REQS.RESET_SUBPLOT_DATA:
            self.action_reset_average_data()
        elif request == REQS.SPECIAL_OPTION:
            self.action_special_option()
        elif request == REQS.NEW_DATA:
            self.action_new_data()
        elif request == REQS.ABOUT_DIALOG:
            show_about_dialog()
        elif request == REQS.GET_SPECIAL_ACTIONS:
            return self.data_manager.get_special_dataset_options(args[0])
        elif request == REQS.GET_PLOTTING_STYLE:
            return self.get_plotting_style_for_field(args[0])

    def action_subplot_change(self, subplot_index, display_name):

        """ Handles request to change subplot data
        Args:
        subplot_index : The index of the subpolot (0 to 2) to change
        display_name : The display name of the requested data series
        """

        get_module_logger().info("Changing subplot %d to %s", subplot_index, display_name)

        self.plotter.set_visibility(subplot_index, display_name != "None")
        self.gui.set_displayed_field(display_name, subplot_index)

        self.gui.set_dataset_choices(self.data_manager.get_numeric_display_names())

        if display_name != "None":
            self.plotter.set_dataset(
                self.data_manager.get_timestamps(display_name), self.data_manager.get_dataset(display_name),
                display_name, subplot_index)

        self.gui.draw(self.plotter)

    def action_average_data(self):

        """ Handles request to show the average of a dataset """

        # Get the dataset of interest
        display_name = self.gui.get_selected_dataset_name()

        # Get the time period over which to average
        try:
            time_period = self.gui.get_averaging_time_period()
        except ValueError:
            return # Could not convert time period to float

        if time_period == 0:
            return # Cannot average over zero time!

        # Get the units the time period is in (seconds, minutes etc.)
        time_units = self.gui.get_averaging_time_units()

        get_module_logger().info("Averaging %s over %d %s", display_name, time_period, time_units.lower())

        time_multipliers = {"Seconds":1, "Minutes":60, "Hours":60*60, "Days":24*60*60, "Weeks":7*24*60*60}

        time_period_seconds = time_period * time_multipliers[time_units]

        (data, timestamps) = self.data_manager.get_dataset_average(display_name, time_period_seconds)

        index = self.gui.get_index_of_displayed_plot(display_name)

        self.plotter.set_dataset(timestamps, data, display_name, index)

        self.gui.draw(self.plotter)

    def get_plotting_style_for_field(self, display_name):
        """
        Each field can have a style when plotted.
        This function build that style based on dataset configuration.
        If there is no config, the default plot style is a blue line.
        """

        styles = None
        if self.configmanager.has_dataset_config() and display_name is not None:
            try:
                field_name = self.data_manager.get_field_name_from_display_name(display_name)
                styles = self.configmanager.get_dataset_config('FORMATTING', field_name)

                styles = [style.strip() for style in styles.split(",")]

                if styles[0] == '':
                    styles[0] = 'line' #Add the default plot style

                if len(styles) == 1:
                    styles.append('b') #Add the default colour (blue)

            except KeyError:
                pass # This field name not in the config file

        return ["line", "b"] if styles is None else styles

    def action_reset_average_data(self):

        """ Get the dataset of interest and reset the original data """

        display_name = self.gui.get_selected_dataset_name()
        subplot_index = self.gui.get_index_of_displayed_plot(display_name)

        get_module_logger().info("Resetting dataset %s on subplot %d", display_name, subplot_index)

        self.plotter.set_dataset(
            self.data_manager.get_timestamps(display_name), self.data_manager.get_dataset(display_name),
            display_name, subplot_index)

        self.gui.draw(self.plotter)

    def action_new_data(self):

        """ Handles request to show open a new set of CSV files """

        new_directory = ask_directory("Choose directory to process")

        if new_directory != '' and DataManager.directory_has_data_files(new_directory):
            get_module_logger().info("Parsing directory %s", new_directory)

            self.configmanager.load_dataset_config(new_directory)

            self.gui.reset_and_show_progress_bar("Loading from folder '%s'" % new_directory)

            self.msg_queue = queue.Queue()
            self.data_manager = DataManager(self.msg_queue, new_directory, self.configmanager)
            self.data_manager.start()

            self.loading_timer = threading.Timer(0.1, self.check_data_manager_status)
            self.loading_timer.start()

    def check_data_manager_status(self):

        """ When the data manager is loading new data, updates the progress bar """

        dataloader_finished = False
        try:
            msg = self.msg_queue.get(0)
            if msg == EVT_DATA_LOAD_COMPLETE:
                self.gui.set_progress_text("Processing data...")
                self.gui.set_progress_percent(0)
            elif msg == EVT_DATA_PROCESSING_COMPLETE:
                # Data has finished loading.
                dataloader_finished = True
                self.gui.hide_progress_bar()
                self.plot_datasets()
            else:
                self.gui.set_progress_percent(msg)
        except queue.Empty:
            pass
        except:
            raise

        if not dataloader_finished:
            self.loading_timer = threading.Timer(0.1, self.check_data_manager_status)
            self.loading_timer.start()

    def action_special_option(self):

        """ Handles requests for special options
        e.g. histogram, windrose plot """

        action = self.gui.get_special_action()

        if action == "Windrose":

            get_module_logger().info("Plotting windrose")
            self.gui.add_new_window('Windrose', (7, 6))

            # Get the wind direction and speed data
            speed = self.data_manager.get_dataset('Wind Speed')
            direction = self.data_manager.get_dataset('Direction')

            self.windplotter.set_data(speed, direction)

            # Add window and axes to the GUI
            try:
                self.gui.draw(self.windplotter, 'Windrose')
            except Exception as exc: #pylint: disable=broad-except
                get_module_logger().info("Could not plot windrose (%s)", exc)
                show_info_dialog(
                    "Could not plot windrose - check that the windspeed and direction data are valid")

        elif action == "Histogram":
            get_module_logger().info("Plotting histogram")
            self.gui.add_new_window('Histogram', (7, 6))

            # Get the data for the histogram
            dataset_name = self.gui.get_selected_dataset_name()
            speed = self.data_manager.get_dataset(dataset_name)

            self.histogram.set_data(speed, dataset_name)

            # Add window and axes to the GUI
            self.gui.draw(self.histogram, 'Histogram')

    def plot_datasets(self):

        """ Plots the default set of data (from configuration file) """

        self.plotter.clear_data()

        # Get the default fields from config
        default_fields = self.configmanager.get_global_config('DEFAULT', 'DefaultFields')
        default_fields = [field.strip() for field in default_fields.split(",")]

        # Drawing mutiple plots, so turn off drawing until all three are processed
        self.plotter.suspend_draw(True)

        field_count = 0
        numeric_fields = self.data_manager.get_numeric_field_names()
        for field in default_fields:
            if field in numeric_fields:
                display_name = self.data_manager.get_display_name(field)
                self.action_subplot_change(field_count, display_name)
                field_count += 1

        # If field count is less than 3, fill the rest of the plots in order from datasets
        for field in numeric_fields:
            if field_count == 3:
                break # No more fields to add

            if field in default_fields:
                continue # Already added, move onto next field

            display_name = self.data_manager.get_display_name(field)
            self.action_subplot_change(field_count, display_name)
            field_count += 1

        # Now the plots can be drawn
        self.gui.set_dataset_choices(self.data_manager.get_numeric_display_names())
        self.plotter.suspend_draw(False)
        self.gui.draw(self.plotter)
#-- microelly 2015
#--
#-- GNU Lesser General Public License (LGPL)
#-------------------------------------------------


__Vers__ = '0.1b'
__Status__ = 'alpha'

import FreeCAD,PySide,os,FreeCADGui,time
from PySide import QtCore, QtGui, QtSvg
from PySide.QtGui import * 
import os,re, ast, _ast 

from configmanager import ConfigManager
cm=ConfigManager("MacroManager")
dir_name=cm.get('macrodir',FreeCAD.ConfigGet('AppHomePath')+"/Mod/plugins/FreeCAD-macros")

docstrings=['__Author__','__Version__','__Comment__','__Wiki__','__Icon__','__Help__','__Web__']



global sayexc
import sys,traceback

def sayexc(mess=''):
	exc_type, exc_value, exc_traceback = sys.exc_info()
	ttt=repr(traceback.format_exception(exc_type, exc_value,exc_traceback))
	lls=eval(ttt)
	l=len(lls)
	l2=lls[(l-3):]
Beispiel #58
0
def advanced_search(query, record_type):
    """ Function for initializing an advanced search for an orcid id.  Utilizes OrcidSearchResults() class
        from search.py

    Parameters
    ----------
    :param query: string
        Orcid ID inputted by user
    :param record_type: string
        User selected record_type that they want to display.  Must have corresponding put-code

    Returns
    -------
    :returns: no return.
        Will write to file for a 'activities' record, or print record to screen for all other records.
        Will prompt user to see if they would like to write customer records to file.

        A large amount of information can be gathered for a 'activities' record_type.  The only option
        allowed at this time is for the JSON output to be written to a JSON file.
    """
    search_obj = OrcidSearchResults(sandbox)

    # Will be 'not None' only if record type is other than 'activities'
    if record_type == 'write-rdf':
        config = ConfigManager(orcid_id=query, sandbox=sandbox)
        config.write_config()
    elif record_type == 'read-rdf':
        config = ConfigManager(orcid_id=query, sandbox=sandbox)
        rdf_graph = config.read_config()
        print rdf_graph
    elif record_type is not None:
        put_code = click.prompt('Please enter the put-code (must match record type)')
        results = search_obj.advanced_search(query, record_type, put_code)
        print('')
        print(json.dumps(results, sort_keys=True, indent=4, ensure_ascii=False))

        # Ask user if they would like to send this information to file
        while True:
            send_to_file = click.prompt('Would you like to send this output to a file [y/N]?', default='N', show_default=False)

            if send_to_file in ('y', 'Y', 'yes', 'YES', 'Yes'):
                with io.open(query + '_' + record_type + '_' + put_code + '.json', 'w', encoding='utf8') \
                        as json_file:
                    data = json.dumps(results, json_file, sort_keys=True, indent=4, ensure_ascii=False)
                    # unicode(data) auto-decodes data to unicode if str
                    json_file.write(unicode(data))
                break
            elif send_to_file in ('n', 'N', 'no', 'NO', 'No'):
                break
            else:
                print('You did not pick an appropriate answer.')
    else:
        # When 'activities' (option 1 - summary) is selected, prints to file
        results = search_obj.advanced_search(query)

        home_path = expanduser("~")
        dir_path = home_path + "/.sc/"
        filename = query + '.json'
        if os.path.exists(dir_path):
            config_path = dir_path + filename
        else:
            os.mkdir(home_path + "/.sc/")
            config_path = dir_path + filename

        with io.open(config_path, 'w', encoding='utf8') as json_file:
            data = json.dumps(results, json_file, sort_keys=True, indent=4, ensure_ascii=False)
            # unicode(data) auto-decodes data to unicode if str
            json_file.write(unicode(data))

    # Ask user if they would like to go back to the advanced search selection menu
    while True:
        new_instance = click.prompt('Back to \'Selection\' menu [y/EXIT]?', default='EXIT', show_default=False)
        print('')

        if new_instance in ('y', 'Y', 'yes', 'YES', 'Yes'):
            search_type(args = ['-a'])
            break
        elif new_instance in ('exit', 'EXIT', 'Exit'):
            exit(1)
        else:
            print('You did not pick an appropriate answer.')
Beispiel #59
0
def basic_search_config(query):
    """ Function for initializing a search for an orcid id, and then creates a RDF
        configuration file automatically.

    Parameters
    ----------
    :param query: string
        Query built from user input.

    Returns
    -------
    :returns: no return.
    """

    # Initialize and populate all variables and dictionaries
    search_obj = OrcidSearchResults(sandbox)
    search_obj.basic_search(query)
    actual_total = search_obj.actual_total_results
    total_results = search_obj.total_results
    # orcid_id = search_obj.orcid_id

    # Print results
    search_obj.print_basic_alt()

    # Print total results if actual results are above 100
    if total_results < actual_total:
        print 'Actual Total Results: {}'.format(actual_total)
        print('')

    # Get list of Orcid ID's from results
    id_list = search_obj.orcid_id

    # Write config if only one result was found
    if total_results == 1:
        orcid_id = id_list[0]
        config = ConfigManager(orcid_id=orcid_id, sandbox=sandbox)
        config.write_config()

    # If no results are found
    elif total_results == 0:
        print("No results where found. Please try again.\n")
        search_type(args = ['-c'])

    # Allow user to select Orcid profile if multiple results are found
    else:
        id_dict = dict()
        # Get list of Orcid ID's and correspond count with ID
        for i, id in enumerate(id_list):
            id_dict[i + 1] = id

        selected = None
        while not selected:
            try:
                selected = click.prompt('Select the result # of the record (Type "N" for another search, "Exit" to abort)')
                print("")
                orcid_id = id_dict[int(selected)]
                config = ConfigManager(orcid_id=orcid_id, sandbox=sandbox)
                config.write_config()
            except (KeyError):
                print('That is not a valid selection.  Please try again.\n')
                selected = None
            except (ValueError):
                if selected in ('N', 'n'):
                    search_type(args = ['-c'])
                elif selected in ('exit', 'Exit', 'EXIT'):
                    exit()
                else:
                    print('That is not a valid selection.  Please try again.\n')
                    selected = None
	def exe_dump(self, file_name, serv_name, base_name, backup_name, type):
		date = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
		dump_file_name = backup_name+'_'+file_name+'_'+serv_name+'_'+base_name+'_'+date
		dumper = """pg_dump.exe -U %s -d %s -h %s -p %s -f %s -C --column-inserts"""

		try:
			conf = ConfigManager("config/" + file_name + ".yaml")
			cnf = conf.get(serv_name)
			conn = cnf["connection"]
			db = cnf["databases"][base_name]

			db_name = db["name"]
			db_user = db["user"]
			db_pass = conf.get_password(serv_name + '.' + base_name)
			conn_adr = ''
			conn_port = None

			if conn["type"] == "ssh": #Dla połączeń ssh
				cmd = self.connect_command_builder(conn, 'no')
				common.conn.send(cmd)
				ans = None
				while ans == None:
					ans = common.conn.get_state()

				status, hostname, db_port = ans.split("_")

				if status == "ok":  #udało się utworzyć tunel
					conn_adr = 'localhost'
					conn_port = db_port
				else:
					raise PostgressError('Unable to create ssh tunnel')

			elif conn["type"] == "direct":
				conn_adr = conn["adress"]
				conn_port = conn["remoteport"]

			local_version = self.get_local_version('pg_dump --version')
			remote_version = self.get_pg_version(db_name, db_user, db_pass, conn_adr, conn_port)
			if not self.is_valid_versions(local_version, remote_version):
				raise PostgressError("You have too old version of pg_dump")

			if type == 'tar':
				dumper += ' -Ft'
				dump_file_name += '.tar'
			else:
				dump_file_name += '.sql'
			command = dumper % (db_user, db_name, conn_adr, conn_port, dump_file_name)

			os.putenv('PGPASSWORD', db_pass)
			try:
				common.set_cdir_and_store()
				proc = Popen(command, stdout=PIPE, stderr=PIPE)
			except FileNotFoundError:
				raise PostgressError(" ERROR: pg_dump not found")
			finally:
				common.restore_cdir()
			out, err = proc.communicate()

			if err != b'':
				raise PostgressError(err.decode('utf8', 'ignore'))

		except ConnectionRefusedError:
			print('--------------------')
			print('ERROR: Connection Refused by host')
			print('--------------------')
		except TimeoutError:
			print('--------------------')
			print('ERROR: Connection timeout')
			print('--------------------')
		except paramiko.ssh_exception.AuthenticationException:
			print('--------------------')
			print('ERROR: Authentication problem')
			print('--------------------')
		except KeyError as e:
			print('--------------------')
			print('ERROR: Unable to find key:',e)
			print('--------------------')
		except PostgressError as e:
			print('--------------------')
			print('ERROR:',e)
			print('--------------------')
		except Exception as e:
			print('--------------------')
			print('ERROR:',e)
			print('--------------------')