Example #1
0
def _generateAndSaveKeys(registry=None):
    registry = registry or Registry_Base_URL
    k = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
    privatekey_pem = k.private_bytes(
        serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()
    )

    pubkey_pem = k.public_key().public_bytes(
        serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
    )

    if _isPublicRegistry(registry):
        settings.setProperty("keys", "private", privatekey_pem.decode("ascii"))
        settings.setProperty("keys", "public", pubkey_pem.decode("ascii"))
    else:
        sources = _getSources()
        keys = None
        for s in sources:
            if _sourceMatches(s, registry):
                if not "keys" in s:
                    s["keys"] = dict()
                keys = s["keys"]
                break
        if keys is None:
            keys = dict()
            sources.append({"type": "registry", "url": registry, "keys": keys})
        keys["private"] = privatekey_pem.decode("ascii")
        keys["public"] = pubkey_pem.decode("ascii")
        settings.set("sources", sources)
    return pubkey_pem, privatekey_pem
 def onResize(self, event):
     '''Record new size'''
     key = 'ui.commsdiagnostics.row.size.'
     r = 0
     while r < self.GetNumberCols():
         settings.set(key+str(r), self.GetColSize(r))
         r += 1
 def OnMove(self, event):
     """
     Event handler for moving window
     """
     x, y = self.GetPosition()
     settings.set("win.commstest.pos.x", x)
     settings.set("win.commstest.pos.y", y)
Example #4
0
def _getYottaClientUUID():
    import uuid
    current_uuid = settings.get('uuid')
    if current_uuid is None:
        current_uuid = u'%s' % uuid.uuid4()
        settings.set('uuid', current_uuid)
    return current_uuid
Example #5
0
    def _dispatch_builtin_command(self, command):
        self._reset()
        magic, category, key, value = command.split(':')
        if magic == 'builtin':
            if category == 'settings':
                try:
                    value = eval(value)
                except e:
                    logging.exception(e)
                    return False
                if key == 'romanrule':
                    self._charbuf.compile(value)
                    self._charbuf_alter.compile(value)
                elif key == 'use_title':
                    title.setenabled(value)
                settings.set(key, value)
                settings.save()
                return True
            elif category == 'task':
                if key == 'switch':
                    window_id = int(value)
                    if window_id == 0:
                        self._session.blur_process()
                    else:
                        self._draw_nothing(self._output)
                        self._inputmode.reset()
                        self._reset()
                        self._screen.taskswitch(window_id)

            return False
        return False
Example #6
0
 def test_SettingOverwriting(self):
   # test that values are updated when settings are overwritten
   s = settings.set('an_index',is_global=IS_GLOBAL,value=12345)
   t = settings.set('an_index',is_global=IS_GLOBAL,value=67890)
   self.assert_(s.key() == t.key(), "Set function should not create new objects when existig objects with the same index exist")
   self.assert_(s.value == 12345, "Initial value should remain in initial object")
   self.assert_(t.value == 67890, "Updated value should overwrite old value")
Example #7
0
def deauthorize(registry=None):
    registry = registry or Registry_Base_URL
    if _isPublicRegistry(registry):
        if settings.get('keys'):
            settings.set('keys', dict())
    else:
        sources = [s for s in _getSources() if not _sourceMatches(s, registry)]
        settings.set('sources', sources)
Example #8
0
								def add_to_ignore(self):
									gallery = self.gallery_widget.gallery
									app_constants.IGNORE_PATHS.append(gallery.path)
									settings.set(app_constants.IGNORE_PATHS, 'Application', 'ignore paths')
									if self.gallery_widget.parent_widget.gallery_layout.count() == 1:
										self.gallery_widget.parent_widget.close()
									else:
										self.gallery_widget.close()
Example #9
0
 def accept_edit(self):
     gallerydb.execute(database.db.DBBase.begin, True)
     app_constants.APPEND_TAGS_GALLERIES = self.tags_append.isChecked()
     settings.set(app_constants.APPEND_TAGS_GALLERIES, 'Application', 'append tags to gallery')
     for g in self._edit_galleries:
         self.make_gallery(g)
     self.delayed_close()
     gallerydb.execute(database.db.DBBase.end, True)
Example #10
0
 def test_settingTypes(self):
   # test the creation of settings with different types
   for k,v in supported_types.iteritems():
     s = settings.set(k,is_global=IS_GLOBAL, value=v[0])
     self.assert_(s,k+" should create a valid settings object")
   for k,v in unsupported_types.iteritems():
     s = settings.set(k,is_global=IS_GLOBAL, value=v[0])
     self.assert_(s == None, "Unsupported types should return None")
Example #11
0
 def test_SettingHierarchy(self):
   # test that user settings overwrite global settings where they are present
   g = settings.set('an_index',is_global=True,value='global value')
   u = settings.set('an_index',value='user value')
   self.assert_(g.key() != u.key(),"User settings should not overwrite global settings")
   s_one = settings.get('an_index') #should be global
   self.assert_(s_one['value'] == 'global value',"settings.get should return the global value unless user_first is set")
   s_two = settings.get('an_index',user_first=True)
   self.assert_(s_two['value'] == 'user value',"User setting should be returned in favour of the global setting when user_first is True")
Example #12
0
def delete_file(filename):
    tries = 10
    while os.path.exists(filename) and tries > 0:
        settings.set('ChannelsUpdated', 0, settingsFile)
        try:
            os.remove(filename) 
            break 
        except: 
            tries -= 1 
Example #13
0
 def _static_processing(self):
     
     self.logger.info("Static processing thread starting")
     idx = -1
     
     # resume processing with the last image the user looked at
     last_img = settings.get('processing/last_img', None)
     for i, image_name in enumerate(self.images):
         if image_name == last_img:
             self.idx = i
             break 
     
     while True:
     
         with self.condition:
             
             # wait until the user hits a key
             while idx == self.idx and not self.do_stop and not self.do_refresh:
                 self.condition.wait()
             
             if self.do_stop:
                 break
             
             idx = self.idx
             self.do_refresh = False
                 
         # if the index is valid, then process an image
         if idx < len(self.images) and idx >= 0:
             
             image_name = self.images[idx]
             
             self.logger.info("Opening %s" % image_name)
             
             img = cv2.imread(image_name)
             if img is None:
                 self.logger.error("Error opening %s: could not read file" % (image_name))
                 self.camera_widget.set_error()
                 self.idx += self.idx_increment
                 continue
             
             try:
                 target_data = self.detector.process_image(img)
             except:
                 logutil.log_exception(self.logger, 'error processing image')
                 self.camera_widget.set_error(img)
             else:
                 settings.set('processing/last_img', image_name)
                 settings.save()
                 
                 self.logger.info('Finished processing')
             
                 # note that you cannot typically interact with the UI
                 # from another thread -- but this function is special
                 self.camera_widget.set_target_data(target_data)
         
     self.logger.info("Static processing thread exiting")
Example #14
0
def delete_file(filename):
    dixie.SetSetting("epg.date", "2000-01-01")
    tries = 10
    while os.path.exists(filename) and tries > 0:
        settings.set("ChannelsUpdated", 0, settingsFile)
        try:
            os.remove(filename)
            break
        except:
            tries -= 1
Example #15
0
	def start_up(self):
		hello = ["Hello!", "Hi!", "Onii-chan!", "Senpai!", "Hisashiburi!", "Welcome!", "Okaerinasai!", "Welcome back!", "Hajimemashite!"]
		self.notification_bar.add_text("{} Please don't hesitate to report any bugs you find.".format(hello[random.randint(0, len(hello)-1)])+
								 " Go to Settings -> About -> Bug Reporting for more info!")
		level = 5
		def normalize_first_time():
			settings.set(level, 'Application', 'first time level')
			settings.save()

		def done(status=True):
			gallerydb.DatabaseEmitter.RUN = True
			if app_constants.FIRST_TIME_LEVEL != level:
				normalize_first_time()
			if app_constants.ENABLE_MONITOR and\
				app_constants.MONITOR_PATHS and all(app_constants.MONITOR_PATHS):
				self.init_watchers()
				if app_constants.LOOK_NEW_GALLERY_STARTUP:
					if self.manga_list_view.gallery_model.db_emitter.count == app_constants.GALLERY_DATA:
						self.scan_for_new_galleries()
					else:
						self.manga_list_view.gallery_model.db_emitter.DONE.connect(self.scan_for_new_galleries)
			self.download_manager = pewnet.Downloader()
			app_constants.DOWNLOAD_MANAGER = self.download_manager
			self.download_manager.start_manager(4)

		if app_constants.FIRST_TIME_LEVEL < 4:
			log_i('Invoking first time level {}'.format(4))
			settings.set([], 'Application', 'monitor paths')
			settings.set([], 'Application', 'ignore paths')
			app_constants.MONITOR_PATHS = []
			app_constants.IGNORE_PATHS = []
			settings.save()
			done()
		elif app_constants.FIRST_TIME_LEVEL < 5:
			log_i('Invoking first time level {}'.format(5))
			app_widget = misc.ApplicationPopup(self)
			app_widget.note_info.setText("<font color='red'>IMPORTANT:</font> Application restart is required when done")
			app_widget.restart_info.hide()
			self.admin_db = gallerydb.AdminDB()
			self.admin_db.moveToThread(app_constants.GENERAL_THREAD)
			self.admin_db.DONE.connect(done)
			self.admin_db.DONE.connect(lambda: app_constants.NOTIF_BAR.add_text("Application requires a restart"))
			self.admin_db.DONE.connect(self.admin_db.deleteLater)
			self.admin_db.DATA_COUNT.connect(app_widget.prog.setMaximum)
			self.admin_db.PROGRESS.connect(app_widget.prog.setValue)
			self.admin_db_method_invoker.connect(self.admin_db.rebuild_db)
			self.admin_db_method_invoker.connect(app_widget.show)
			app_widget.adjustSize()
			db_p = os.path.join(os.path.split(database.db_constants.DB_PATH)[0], 'sadpanda.db')
			self.admin_db_method_invoker.emit(db_p)
		else:
			done()
Example #16
0
def save_teams():
    r = api.method('/me/teams')
    if r.status_code == 200:
        teams = r.json()
        if len(teams) > 0:
            settings.set(teams=teams)
            for team in teams:
                save_image('http:' + team["thumbUrl"], 'team-' + team['name'])
            n.notify("AndBang Workflow Success", "Your teams were saved!", "Teams: " + ', '.join([team["name"] for team in teams]))
        else:
            n.notify("AndBang Workflow Error", "No teams were saved", "Please create one at http://andbang.com")
    else:
        n.notify("AndBang Workflow Error", resp["message"], "")
Example #17
0
    def load_settings(self):
        settings = ConfigParser.ConfigParser()

        # Fill defaults
        settings.add_section("main")
        settings.set("main", "save-before-build", "True")
        settings.set("main", "ptp-debug", "False")

        filename = self.get_settings_filename()
        if os.path.isfile(filename):
            with open(filename, "r") as f:
                settings.readfp(f)
        return settings
Example #18
0
    def POST(self):
        """
        Save settings
        :return:
        """
        inputs = web.input(jobs=[])

        cfg = settings.get()
        cfg["master"] = inputs.serveraddress
        cfg["jobs"] = inputs.jobs

        settings.set(cfg)

        return self.GET()
Example #19
0
def select_source():
    mc.ShowDialogWait()
    window = mc.GetActiveWindow()
    list = window.GetList(SOURCES_LIST_ID)
    sourceitem = list.GetItem(list.GetFocusedItem())
    username = settings.get('megaupload.username')
    password = settings.get('megaupload.password')
    cookie = settings.get('megaupload.cookie')
    print "MU: %s, %s, %s" % (username, password, cookie)
    mu = megaupload.MegaUpload(username, password, cookie)
    settings.set('megaupload.cookie', mu.get_cookie())
    link, name, wait, cookie = mu.resolve(sourceitem.GetPath())
    hide_popup()
    wd = waitdialog.WaitDialog('Megaupload', 'Waiting for link to activate')
    wd.wait(wait, waitdialog_callback, (link, name, cookie))
Example #20
0
def setAPIKey(registry, api_key):
    """ Set the api key for accessing a registry. This is only necessary for
        development/test registries.
    """
    if (registry is None) or (registry == Registry_Base_URL):
        return
    sources = _getSources()
    source = None
    for s in sources:
        if _sourceMatches(s, registry):
            source = s
    if source is None:
        source = {"type": "registry", "url": registry}
        sources.append(source)
    source["apikey"] = api_key
    settings.set("sources", sources)
Example #21
0
 def test_createBasicSetting(self):
   # test the creation of a basic settings object
   a_string = "BARfoo"
   an_index = "BARfoo_global_setting"
   s = settings.set(an_index,is_global=IS_GLOBAL,value=a_string)
   self.assert_(s.value == a_string, "Stored value: "+a_string+" retrieved: "+str(s.value))
   self.assert_(s.index == an_index, "Provided key: "+an_index+" retrieved: "+str(s.index))
Example #22
0
	def start_up(self):
		# TODO: Remove in beta
		level = 4
		def normalize_first_time():
			settings.set(level, 'Application', 'first time level')
			settings.save()

		def done(status=True):
			gallerydb.DatabaseEmitter.RUN = True
			if gui_constants.FIRST_TIME_LEVEL != level:
				normalize_first_time()
			if gui_constants.ENABLE_MONITOR and\
				gui_constants.MONITOR_PATHS and all(gui_constants.MONITOR_PATHS):
				self.init_watchers()
				if gui_constants.LOOK_NEW_GALLERY_STARTUP:
					if self.manga_list_view.gallery_model.db_emitter.count == gui_constants.GALLERY_DATA:
						self.scan_for_new_galleries()
					else:
						self.manga_list_view.gallery_model.db_emitter.DONE.connect(self.scan_for_new_galleries)
			self.download_manager = pewnet.Downloader()
			gui_constants.DOWNLOAD_MANAGER = self.download_manager
			self.download_manager.start_manager(4)

		if gui_constants.FIRST_TIME_LEVEL < 3:
			log_i('Invoking first time level {}'.format(level))
			app_widget = misc.ApplicationPopup(self)
			self.admin_db = gallerydb.AdminDB()
			self.admin_db.moveToThread(gui_constants.GENERAL_THREAD)
			self.admin_db.DONE.connect(done)
			self.admin_db.DONE.connect(self.admin_db.deleteLater)
			self.admin_db.DATA_COUNT.connect(app_widget.prog.setMaximum)
			self.admin_db.PROGRESS.connect(app_widget.prog.setValue)
			self.admin_db_method_invoker.connect(self.admin_db.rebuild_galleries)
			self.admin_db_method_invoker.connect(app_widget.show)
			app_widget.adjustSize()
			self.admin_db_method_invoker.emit()
		elif gui_constants.FIRST_TIME_LEVEL < 4:
			log_i('Invoking first time level {}'.format(level))
			settings.set([], 'Application', 'monitor paths')
			settings.set([], 'Application', 'ignore paths')
			gui_constants.MONITOR_PATHS = []
			gui_constants.IGNORE_PATHS = []
			settings.save()
			done()
		else:
			done()
Example #23
0
def save_members():
    output = []
    teams = settings.get('teams', [])
    for team in teams:
        r = api.method('/members', team['id'])
        if r.status_code == 200:
            members = r.json()
            if len(members) > 0:
                for member in members:
                    save_image('http:' + member["smallPicUrl"], 'member-' + member['id'])
                    output.append({your_key: member[your_key] for your_key in ['id', 'username', 'smallPicUrl', 'firstName', 'lastName']})
                settings.set(members=output)
                n.notify("AndBang Workflow Success", "Your teams members were saved!", "")
            else:
                n.notify("AndBang Workflow Error", "No members were saved", "Have some people join your team!")
        else:
            error = r.json()
            n.notify("AndBang Workflow Error", error["message"], "")
Example #24
0
    def OnMove(self, event):
        """Event handler for moving window"""
        if self.iconized or self.IsMaximized():
            return

        h, w = self.GetSize()
        settings.set("win.main.size.h", h)
        settings.set("win.main.size.w", w)

        x, y = self.GetPosition()
        settings.set("win.main.pos.x", x)
        settings.set("win.main.pos.y", y)
Example #25
0
def setAPIKey(registry, api_key):
    ''' Set the api key for accessing a registry. This is only necessary for
        development/test registries.
    '''
    if (registry is None) or (registry == Registry_Base_URL):
        return
    sources = _getSources()
    source = None
    for s in sources:
        if _sourceMatches(s, registry):
            source = s
    if source is None:
        source = {
           'type':'registry',
            'url':registry,
        }
        sources.append(source)
    source['apikey'] = api_key
    settings.set('sources', sources)
Example #26
0
    def OnMove(self, event):
        '''Event handler for moving window'''
        if self.iconized or self.IsMaximized():
            return

        h, w = self.GetSize()
        settings.set('win.main.size.h', h)
        settings.set('win.main.size.w', w)
            
        x, y = self.GetPosition()
        settings.set('win.main.pos.x', x)
        settings.set('win.main.pos.y', y)
Example #27
0
    def do_GET(self):
        global run_server
        parse = urlparse.urlparse(self.path)
        query = urlparse.parse_qs(parse.query)

        self.send_response(200)
        self.send_header('Content-type','text-html')
        self.end_headers()

        message = 'Token was not saved. Please try again.'

        if 'access_token' in query:
            token = query['access_token'][0]
            settings.set(token=token)
            message = 'Token has been saved. You may close this window.'
            run_server = False

        refresh_script = "<script>h = window.location.href; !!~h.indexOf('#') ? (window.location.href = h.replace('#', '?')) : document.write('" + message + "');</script>"
        self.wfile.write(refresh_script)
        return
Example #28
0
def _generateAndSaveKeys(registry=None):
    registry = registry or Registry_Base_URL
    k = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )
    privatekey_pem = k.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption()
    )

    pubkey_pem = k.public_key().public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo
    )

    if _isPublicRegistry(registry):
        settings.setProperty('keys', 'private', privatekey_pem.decode('ascii'))
        settings.setProperty('keys', 'public', pubkey_pem.decode('ascii'))
    else:
        sources = _getSources()
        keys = None
        for s in sources:
            if _sourceMatches(s, registry):
                if not 'keys' in s:
                    s['keys'] = dict()
                keys = s['keys']
                break
        if keys is None:
            keys = dict()
            sources.append({
               'type':'registry',
                'url':registry,
               'keys':keys
            })
        keys['private'] = privatekey_pem.decode('ascii')
        keys['public']  = pubkey_pem.decode('ascii')
        settings.set('sources', sources)
    return pubkey_pem, privatekey_pem
Example #29
0
    def _wasSettingsChanged(self, addon):
        settingsChanged = False
        count           = 0
        
        params = settings.getAll(settingsFile)
        
        for pair in params:
            param = pair[0]
            if param in SETTINGS_TO_CHECK:
                count += 1
                if pair[1] != addon.getSetting(param):
                    settingsChanged = True

        if count != len(SETTINGS_TO_CHECK):
            settingsChanged = True

        #update (or create) file
        if settingsChanged or len(params) == 0:
            for param in SETTINGS_TO_CHECK:
                value = addon.getSetting(param).decode('utf-8', 'ignore')
                settings.set(param, value, settingsFile)

        dixie.log('Settings changed: ' + str(settingsChanged))
        return settingsChanged
Example #30
0
    def setUp(self):
        self.tickets = mock.create_autospec(GestioTiquets)
        self.tickets.consulta_tiquet_dades.return_value = {
            "solicitant": "usuari.real",
            "emailSolicitant": "*****@*****.**"
        }
        self.identitat = mock.create_autospec(GestioIdentitat)
        self.identitat.obtenir_uid.return_value = None

        settings.init()
        settings.set("regex_reply", "(.*)")  # Una que trobi sempre algo
        settings.set("regex_privat", "X")   # Una que no trobi mai res
        settings.set("usuari_extern", "usuari.extern")
    def _updateChannelAndProgramListCaches(self, date, progress_callback,
                                           clearExistingProgramList):
        sqlite3.register_adapter(datetime.datetime, self.adapt_datetime)
        sqlite3.register_converter('timestamp', self.convert_datetime)

        if not self._isCacheExpired(date):
            return

        self.updateInProgress = True
        self.updateFailed = False
        dateStr = date.strftime('%Y-%m-%d')

        if len(self.channelDict) == 0:
            channels = self.getAllChannels()
            for channel in channels:
                theChannel = self.getChannelFromFile(channel)
                if theChannel:
                    self.channelDict[channel] = theChannel

        try:
            dixie.log('Updating caches...')
            if progress_callback:
                progress_callback(0)

            if self.settingsChanged:
                self.source.doSettingsChanged()

            self.settingsChanged = False  # only want to update once due to changed settings

            toDelete = self.getAllChannels()

            weight = 0

            imported = imported_channels = imported_programs = 0
            for item in self.source.getDataFromExternal(
                    date, progress_callback):
                imported += 1

                if isinstance(item, Channel):
                    imported_channels += 1
                    channel = item

                    clean = CleanFilename(channel.id)
                    if clean in toDelete:
                        toDelete.remove(clean)

                    weight += 1
                    channel.weight = weight
                    self.createChannel(channel)

            #channels updated
            try:
                settings.set('ChannelsUpdated',
                             self.adapt_datetime(datetime.datetime.now()),
                             settingsFile)
            except:
                pass

            self.deleteOldChannels(toDelete)

            if imported_channels == 0:
                self.updateFailed = True
            if imported_programs == 0:
                self.updateFailed = (not USE_DB_FILE)

        except SourceUpdateCanceledException:
            # force source update on next load
            try:
                settings.set('ChannelsUpdated', 0, settingsFile)
            except:
                pass

        except Exception:
            import traceback as tb
            import sys
            (etype, value, traceback) = sys.exc_info()
            tb.print_exception(etype, value, traceback)

            try:
                # invalidate cached data
                try:
                    settings.set('ChannelsUpdated', 0, settingsFile)
                except:
                    pass

            except:
                pass

            self.updateFailed = True

        update = dixie.GetSetting('updated.channels')
        if int(update) < 0:
            dixie.SetSetting('updated.channels', 0)
            dixie.SetSetting('current.channels', 0)
        else:
            dixie.SetSetting('current.channels', update)
            self.channelDict = {}
            self.updateInProgress = False

        self.initializeChannels()

        self.updateInProgress = False
Example #32
0
 def test_set(self):
     settings.set('local', 'test', '1')
     self.assertTrue(settings.contains('local'))
     self.assertEqual(settings.get('local', 'test'), '1')
Example #33
0
 def test_set_overwrite(self):
     settings.set('global', 'foo', 'xxx')
     self.assertEqual(settings.get('global', 'foo'), 'xxx')
Example #34
0
    def do_init(self, license):
        opts, files = self.tmpopts, self.tmpfiles
        del self.tmpopts
        del self.tmpfiles
        ##         del self.tmplicensedialog
        import MMurl
        import windowinterface
        if features.lightweight and len(files) > 1:
            windowinterface.showmessage(
                'Cannot open multiple files in this product.')
            files = files[:1]
        self._license = license
        ##         if not self._license.have('save'):
        ##             windowinterface.showmessage(
        ##                 'This is a demo version.\n'+
        ##                 'You will not be able to save your changes.',
        ##                 title='CMIFed license')
        self._tracing = 0
        self.tops = []
        self._mm_callbacks = {}
        self.last_location = ''
        self._untitled_counter = 1
        self.template_info = None
        try:
            import mm, posix, fcntl
        except ImportError:
            pass
        else:
            pipe_r, pipe_w = posix.pipe()
            mm.setsyncfd(pipe_w)
            self._mmfd = pipe_r
            windowinterface.select_setcallback(
                pipe_r, self._mmcallback,
                (posix.read, fcntl.fcntl, fcntl.F_SETFL, posix.O_NDELAY))
        self.commandlist = [
            EXIT(callback=(self.close_callback, ())),
            NEW_DOCUMENT(callback=(self.new_callback, ())),
            OPEN(callback=(self.open_callback, ())),
            OPENFILE(callback=(self.openfile_callback, ())),
            OPEN_RECENT(callback=self.open_recent_callback),  # Dynamic cascade
            PREFERENCES(callback=(self.preferences_callback, ())),
            CHECKVERSION(callback=(self.checkversion_callback, ())),
        ]
        import settings
        if self._license.have('preregistered'):
            settings.set('registered', 'preregistered')
        if not self._license.is_evaluation_license() and \
                        settings.get('registered') != 'preregistered':
            self.commandlist.append(
                REGISTER(callback=(self.register_callback, ())))
        import Help
        if hasattr(Help, 'hashelp') and Help.hashelp():
            self.commandlist.append(HELP(callback=(self.help_callback, ())))
        if __debug__:
            if settings.get('debug'):
                self.commandlist = self.commandlist + [
                    TRACE(callback=(self.trace_callback, ())),
                    DEBUG(callback=(self.debug_callback, ())),
                    CRASH(callback=(self.crash_callback, ())),
                ]

        if self.splash is not None:
            self.splash.unsplash()
            self.splash = None

        MainDialog.__init__(self, 'CMIFed', (not not files))

        for file in files:
            self.openURL_callback(MMurl.guessurl(file))
        self._update_recent(None)

        if ENABLE_FNORB_SUPPORT:
            import CORBA.services
            self.corba_services = CORBA.services.services(sys.argv)

        if settings.get('registered') == 'notyet' and \
                        not self._license.is_evaluation_license():
            answer = windowinterface.RegisterDialog()
            astr = ['yes', 'no', 'notyet'][answer]
            settings.set('registered', astr)
            settings.save()
            if astr == 'yes':
                self.register_callback()
Example #35
0
	serv_dir = os.path.join(os.getcwd(), "serv" )
	picon_dir = os.path.join(os.getcwd(),'logo')
	UserDir = os.path.join(os.getcwd(), "user" )

import cookielib
sid_file = os.path.join(UserDir, 'vsetv.sid')
cj = cookielib.FileCookieJar(sid_file) 
hr  = urllib2.HTTPCookieProcessor(cj) 
opener = urllib2.build_opener(hr) 
urllib2.install_opener(opener) 


try: port = int(settings.get('port'))
except: 
	port = 8185
	settings.set('port', 8185)
if port=='': 
	port = 8185
	settings.set('port', 8185)


sys.path.append(UserDir)

from UserDBcnl import *

try: 
	from EPGdb import *
	if EPG == "": EPG = {}
except:
	EPG = {}
Example #36
0
import settings


def spider_closing(spider):
    # Activates on spider closed signal
    log.msg('closing reactor', level=log.INFO)
    reactor.stop()


log.start(loglevel=log.DEBUG)  # logfile=settings.LOG_FILE,

settings = Settings()

# crawl responsibly
settings.set(
    "USER_AGENT",
    "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"
)
crawler = Crawler(settings)

# stop reactor when spider closes
crawler.signals.connect(spider_closing, signal=signals.spider_closed)

path_prefix = 'spiders.'
if len(sys.argv) > 1:
    spider_name = sys.argv[1]
    try:
        custom_spider = importlib.import_module(path_prefix + sys.argv[1])
        spider_class = getattr(custom_spider, spider_name)
        spider = spider_class()
    except Exception, e:
        print 'spider:%s 加载失败 ,error:' % spider_name, e
Example #37
0
File: core.py Project: filkint/ptv3
def get_SG():
    SG = settings.get("Sel_gr")
    if SG == '':
        SG = 'Все каналы'
        settings.set("Sel_gr", SG)
    return SG
Example #38
0
 def syncmodecb(self, arg):
     settings.set('default_sync_behavior_locked', arg == 'on')
Example #39
0
 def never_again(self):
     # Called when the user selects the "don't show again" in the initial dialog
     import settings
     settings.set('initial_dialog', 0)
     settings.save()
Example #40
0
 def systemtestcb(self, attrname, extvalue):
     attrvalue = systemtestnames.ext2intvalue(attrname, extvalue)
     if settings.get(attrname) != attrvalue:
         settings.set(attrname, attrvalue)
         self.root.ResetPlayability()
     return 1  # indicate success
Example #41
0
 def destroy(self):
     settings.set('main_window_geometry',
                  self._nametowidget(self.winfo_parent()).geometry())
     settings.save()
     super().destroy()
Example #42
0
import discord, datetime, os, time, json, settings
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from pymongo import MongoClient
set = settings.set()
try:
    client = MongoClient(host=set.ip,
                         port=set.port,
                         username=set.user,
                         password=set.pwd,
                         authSource=set.auth)
    db = client['chaemoong']['afk']
    lang = client['chaemoong']['mod.language'].find_one
except:
    print("AFK Cog에서 몽고DB를 연결할 수 없습니다!")


class Afk(commands.Cog):
    """asdf!"""
    def __init__(self, bot):
        self.bot = bot
        self.ko = 'data/language/ko.json'
        self.en = 'data/language/en.json'

    @commands.command(no_pm=True,
                      name='afk',
                      description='The afk command! | 잠수 명령어입니다!',
                      aliases=['ㅁ라', '잠수', 'wkatn'])
    async def afk(self, ctx, *, reason=None):
        """잠수 명령어 입니다!"""
        utc = datetime.datetime.utcnow()
Example #43
0
 def __skin_done(self, filename):
     if filename:
         import settings, MMurl
         url = MMurl.pathname2url(filename)
         settings.set('skin', url)
         settings.save()