示例#1
0
    def _change_window_fix_cb(self, settings, key):
        hint = self.fixed_window_hint \
            if settings.get_boolean(key) else Gdk.WindowTypeHint.NORMAL

        if hint == self.window.get_type_hint(): return

        self.window.hide()
        self.window.set_type_hint(hint)
        self.window.show()

        is_below = SETTINGS.get_boolean('window-fix') or \
            SETTINGS.get_boolean('window-keep-below')
        self.window.set_keep_below(is_below)

        if hint == Gdk.WindowTypeHint.NORMAL:
            if self.window.get_gravity() == Gdk.Gravity.CENTER:
                border = self.photoimage.window_border
                x = SETTINGS_GEOMETRY.get_int('root-x') - self.photoimage.w / 2
                y = SETTINGS_GEOMETRY.get_int('root-y') - self.photoimage.h / 2
                self.window.move(int(x - border), int(y - border))
            else:
                # a workaround for Xfwm bug (Issue #97)
                x = SETTINGS_GEOMETRY.get_int('root-x')
                y = SETTINGS_GEOMETRY.get_int('root-y')
                self.window.move(int(x), int(y))
示例#2
0
    def _change_window_fix_cb(self, settings, key):
        hint = self.fixed_window_hint \
            if settings.get_boolean(key) else Gdk.WindowTypeHint.NORMAL

        if hint == self.window.get_type_hint(): return

        self.window.hide()
        self.window.set_type_hint(hint)
        self.window.show()

        is_below = SETTINGS.get_boolean('window-fix') or \
            SETTINGS.get_boolean('window-keep-below')
        self.window.set_keep_below(is_below)

        if hint == Gdk.WindowTypeHint.NORMAL:
            if self.window.get_gravity() == Gdk.Gravity.CENTER:
                border = self.photoimage.window_border
                x = SETTINGS_GEOMETRY.get_int('root-x') - self.photoimage.w / 2
                y = SETTINGS_GEOMETRY.get_int('root-y') - self.photoimage.h / 2
                self.window.move(int(x - border), int(y - border))
            else:
                # a workaround for Xfwm bug (Issue #97)
                x = SETTINGS_GEOMETRY.get_int('root-x')
                y = SETTINGS_GEOMETRY.get_int('root-y')
                self.window.move(int(x), int(y))
示例#3
0
文件: spectrum.py 项目: ecabuk/vlf
    def run(self):
        while True:
            self.updated.emit(vlfrx.wideband_spectrum(
                SETTINGS.value('spectrum/resolution', 10, int),
                SETTINGS.value('spectrum/frames', 100, int),
                SETTINGS.value('spectrum/channels', '1,2')
            ))

            # Wait for render
            render_wait.wait(mutex)
示例#4
0
    def __init__(self, photolist):

        self.photolist = photolist
        self.fixed_window_hint = Gdk.WindowTypeHint.DOCK

        gui = Gtk.Builder()
        gui.add_objects_from_file(constants.UI_FILE, ["window"])

        SETTINGS.connect("changed::fullscreen", self._change_fullscreen_cb)
        SETTINGS.connect("changed::window-sticky", self._change_sticky_cb)
        SETTINGS.connect("changed::window-fix", self._change_window_fix_cb)
        SETTINGS.connect("changed::border-color", self._set_border_color)

        # a workaround for Xfwm bug (Issue #97)
        gravity = Gdk.Gravity.NORTH_WEST \
            if SETTINGS_GEOMETRY.get_string('gravity') == 'NORTH_WEST' \
            else Gdk.Gravity.CENTER

        self.window = gui.get_object('window')
        self.window.set_gravity(gravity)

        if SETTINGS.get_boolean('window-sticky'):
            self.window.stick()
        self._set_window_state()
        self._set_window_position()

        self._set_photoimage()
        self._set_event_box()
        self._set_popupmenu(self.photolist, self)
        self._set_accelerator()

        # FIXME: Why "query-tooltip" is not enable?
        self.window.connect("query-tooltip", self.photoimage.tooltip.query_tooltip_cb)
        gui.connect_signals(self)
示例#5
0
    def __init__(self, photolist):

        self.photolist = photolist
        self.fixed_window_hint = Gdk.WindowTypeHint.DOCK

        gui = Gtk.Builder()
        gui.add_objects_from_file(constants.UI_FILE, ["window"])

        SETTINGS.connect("changed::fullscreen", self._change_fullscreen_cb)
        SETTINGS.connect("changed::window-sticky", self._change_sticky_cb)
        SETTINGS.connect("changed::window-fix", self._change_window_fix_cb)
        SETTINGS.connect("changed::border-color", self._set_border_color)

        # a workaround for Xfwm bug (Issue #97)
        gravity = Gdk.Gravity.NORTH_WEST \
            if SETTINGS_GEOMETRY.get_string('gravity') == 'NORTH_WEST' \
            else Gdk.Gravity.CENTER

        self.window = gui.get_object('window')
        self.window.set_gravity(gravity)

        if SETTINGS.get_boolean('window-sticky'):
            self.window.stick()
        self._set_window_state()
        self._set_window_position()

        self._set_photoimage()
        self._set_event_box()
        self._set_popupmenu(self.photolist, self)
        self._set_accelerator()

        # FIXME: Why "query-tooltip" is not enable?
        self.window.connect("query-tooltip",
                            self.photoimage.tooltip.query_tooltip_cb)
        gui.connect_signals(self)
示例#6
0
    def __init__(self):
        self.queue_settings = SETTINGS.get("queue", {})
        self.cache_settings = SETTINGS.get("cache", {})

        self.key_expire_time_in_sec = self.cache_settings.get(
            "key_expire_time_in_sec", 30)
        self.cache_index = self.cache_settings.get("index", "index")
        self.cache_separator = self.cache_settings.get("separator", "::")
        self.prefix_requests = self.queue_settings.get("prefix_requests",
                                                       "search::")
        self.prefix_results = self.queue_settings.get("prefix_results",
                                                      "create::")
        self.complete_message = self.queue_settings.get(
            "complete_message", "create::")
示例#7
0
def create_auto_conf_file(conf):
    """Create DOSBox configuration file based on environment.

    Different sections are either hard-coded or generated based on
    user environment (used midi port, current screen resolution, etc.).
    """

    name = 'steam_dos_auto.conf'

    mport = midi.detect_software_synthesiser(r'timidity|fluid')
    if mport:
        print_err('steam-dos: Detected', mport.name, 'on', mport.addr)

    with open(name, 'w') as auto:
        auto.write('# Generated by steam-dos\n')
        auto.write('# This file is re-created on every run\n')
        auto.write('\n')

        sdl_fullresolution = settings.get_dosbox_fullresolution()
        auto.write(SDL_SECTION_1.format(resolution=sdl_fullresolution))

        render_scaler = settings.get_dosbox_scaler()
        render_aspect = 'false'
        if conf and conf.has_section('render'):
            render_aspect = conf['render'].get('aspect', 'false')
        auto.write(
            RENDER_SECTION_1.format(scaler=render_scaler,
                                    aspect=render_aspect))

        base, irq, dma, hdma = 220, 7, 1, 5  # DOSBox defaults
        print_err('steam-dos: Setting up DOSBox audio:')
        print_err(SBLASTER_INFO.format(base=base, irq=irq, dma=dma))
        auto.write(SBLASTER_SECTION.format(base=base, irq=irq, dma=dma,
                                           hdma=hdma))  # yapf: disable
        if mport:
            print_err(MIDI_INFO)
            auto.write(MIDI_SECTION.format(port=mport.addr))
        else:
            print_err(MIDI_INFO_NA)

        if conf and conf.has_section('dos'):
            dos_xms = conf['dos'].get('xms', 'true')
            dos_ems = conf['dos'].get('ems', 'true')
            dos_umb = conf['dos'].get('umb', 'true')
            auto.write(DOS_SECTION.format(xms=dos_xms,
                                          ems=dos_ems,
                                          umb=dos_umb))  # yapf: disable

    return name
示例#8
0
def get_pretty_logger(name):
    """create a useful logger"""
    logger = logging.Logger(name)
    filename = settings.get("LOGFILE", "/tmp/antifraud.log")
    logLevel = settings.get("LOGLEVEL", 6)
    logger.setLevel(logLevel)
    LOG_FORMAT = u'%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d]: %(message)s'
    formatter = logging.Formatter(LOG_FORMAT)
    filehandler = logging.FileHandler(filename)
    console = logging.StreamHandler(sys.stdout)
    filehandler.setFormatter(formatter)
    console.setFormatter(formatter)
    logger.addHandler(filehandler)
    logger.addHandler(console)
    return logger
示例#9
0
 def send_multicast(self,
                    message,
                    multicast_group=None,
                    multicast_port=None):
     if not multicast_group:
         multicast_group = SETTINGS.get("multicast_group")
     if not multicast_port:
         multicast_port = SETTINGS.get("multicast_port")
     try:
         message_raw = message.encode("utf-8")
     except AttributeError:
         message_raw = str(message).encode("utf-8")
     print("Sending multicast to '{}:{}': {!r}".format(
         multicast_group, multicast_port, message_raw))
     SOCK_MULTICAST.sendto(message_raw, (multicast_group, multicast_port))
示例#10
0
 def listen(self):
     print("Initializing local socket")
     addr = socket.getaddrinfo(SETTINGS.get("tcp_local_bind"),
                               SETTINGS.get("tcp_port"))[0][-1]
     self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self._sock.setblocking(True)
     self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self._sock.bind(addr)
     # ATTENTION: When on Micropython 1.10 and ESP8266 ``backlog``
     # must be >= 2!
     # See: https://github.com/micropython/micropython/issues/4511
     print("Start listening")
     # self._sock.listen(5)
     self._sock.listen(SETTINGS.get("tcp_new_unaccepted_connections"))
     self._inputs = [self._sock]
示例#11
0
    def load(self):
        weight = SETTINGS.get_int('default-weight')
        source_list = []

        if not self.has_save_file():
            return source_list

        with open(self.save_file, 'r') as f:
            entry = json.load(f)

        for dir in entry:
            data = {
                'target': '',
                'argument': '',
                'weight': weight,
                'options': {}
            }

            for key, value in entry[dir].items():
                if key in ['source', 'target', 'argument', 'weight']:
                    data[key] = value
                else:
                    data['options'][key] = value

            source_list.append(data)

        source_list.sort(cmp=lambda x, y: cmp(y['weight'], x['weight']))
        return source_list
示例#12
0
    def __init__(self, request=None, response=None):
        self.now = datetime.datetime.now()
        self.tv = {}
        self.settings = SETTINGS.copy()
        self.sb_locations = SAFEBOX_LOCATIONS.copy()
        self.initialize(request, response)
        self.has_pass = False
        self.tv["version"] = os.environ['CURRENT_VERSION_ID']
        self.local = False
        if "127.0.0.1" in self.request.uri or "localhost" in self.request.uri:
            self.local = True
        # misc
        self.tv["current_url"] = self.request.uri
        # self.tv["fb_login_url"] = facebook.generate_login_url(self.request.path, self.uri_for('www-fblogin'))

        if "?" in self.request.uri:
            self.tv["current_base_url"] = self.request.uri[0:(
                self.request.uri.find('?'))]
        else:
            self.tv["current_base_url"] = self.request.uri

        try:
            self.tv["safe_current_base_url"] = urllib.quote(
                self.tv["current_base_url"])
        except:
            logging.exception("safe url error")

        self.tv["request_method"] = self.request.method

        self.session = self.get_session()
        self.user = self.get_current_user()
示例#13
0
    def __init__(self, request=None, response=None):
        self.now = datetime.datetime.now()
        self.tv = {}
        self.settings = SETTINGS.copy()
        self.sb_locations = SAFEBOX_LOCATIONS.copy()
        self.initialize(request, response)
        self.has_pass = False
        self.tv["version"] = os.environ['CURRENT_VERSION_ID']
        self.local = False
        if "127.0.0.1" in self.request.uri or "localhost" in self.request.uri:
            self.local = True
        # misc
        self.tv["current_url"] = self.request.uri
        # self.tv["fb_login_url"] = facebook.generate_login_url(self.request.path, self.uri_for('www-fblogin'))

        if "?" in self.request.uri:
            self.tv["current_base_url"] = self.request.uri[0:(self.request.uri.find('?'))]
        else:
            self.tv["current_base_url"] = self.request.uri

        try:
            self.tv["safe_current_base_url"] = urllib.quote(self.tv["current_base_url"])
        except:
            logging.exception("safe url error")

        self.tv["request_method"] = self.request.method

        self.session = self.get_session()
        self.user = self.get_current_user()
示例#14
0
def mul():
    if SETTINGS.get('debug',''):
        print '请先关闭DEBUG'
    sockets = tornado.netutil.bind_sockets(options.port)
    tornado.process.fork_processes(options.process_num)                         
    server = tornado.httpserver.HTTPServer(application, xheaders=True)
    server.add_sockets(sockets)
    tornado.ioloop.IOLoop.instance().start()
示例#15
0
 def __init__(self):
     self.queue_settings = SETTINGS.get("queue", {})
     self.channel_to_subscribe_and_publish = self.queue_settings.get(
         "vulnerability_channel", "vulnerabilityServiceChannel")
     self.message_to_get_vulnerability = self.queue_settings.get(
         "message_to_get_vulnerability", "getVulnerability")
     self.complete_get_vulnerability = self.queue_settings.get(
         "complete_get_vulnerability", "result::")
    def start(self):
        dt_index = pandas.date_range(start=str(self.startTime),
                                     end=str(self.endTime))
        dt_list = dt_index.strftime("%Y%m%d").tolist()
        for date in dt_list:
            for time in range(0, 24):
                SETTINGS.sleep()
                try:
                    self.get_chart(date, time)
                except Exception as e:
                    # print(f"[ERR] {date}일 {time}시간의 차트를 가져오던 중 에러 발생: {e}")
                    self.log.write(
                        f"[ERR] {date}일 {time}시간의 차트를 가져오던 중 에러 발생: {e}\n")
                    SETTINGS.sleep_error()
                    pass

        self.f.close()
        self.log.close()
示例#17
0
    def start(self, widget, event):
        self.set_recent_menu()

        if SETTINGS.get_boolean('window-fix'):
            self.gui.get_object('menuitem6').set_active(True)

        photo = self.photoimage.photo
        accessible = photo.can_open() if photo else False
        self.set_open_menu_sensitive(accessible)

        is_fullscreen = SETTINGS.get_boolean('fullscreen')
        self.gui.get_object('menuitem8').set_active(is_fullscreen)

        self.gui.connect_signals(self)

        menu = self.gui.get_object('menu')
        menu.popup(None, None, None, None, event.button, event.time)
        self.is_show = True
示例#18
0
    def start(self, widget, event):
        self.set_recent_menu()

        if SETTINGS.get_boolean('window-fix'):
            self.gui.get_object('menuitem6').set_active(True)

        photo = self.photoimage.photo
        accessible = photo.can_open() if photo else False
        self.set_open_menu_sensitive(accessible)

        is_fullscreen = SETTINGS.get_boolean('fullscreen')
        self.gui.get_object('menuitem8').set_active(is_fullscreen)

        self.gui.connect_signals(self)

        menu = self.gui.get_object('menu')
        menu.popup(None, None, None, None, event.button, event.time)
        self.is_show = True
示例#19
0
 def __init__(self, request=None, response=None):
     self.now = datetime.datetime.now()
     self.tv = {}
     self.settings = SETTINGS.copy()
     self.initialize(request, response)
     self.has_pass = False
     self.tv["version"] = os.environ['CURRENT_VERSION_ID']
     self.local = False
     if "127.0.0.1" in self.request.uri or "localhost" in self.request.uri:
         self.local = True
示例#20
0
    def __init__(self,
                 handlers=None,
                 default_host='',
                 transforms=None,
                 **settings):
        super().__init__(handlers=handlers,
                         default_host=default_host,
                         transforms=transforms,
                         **settings)

        self.sentry_client = AsyncSentryClient(SETTINGS.get('sentry_dsn'))
示例#21
0
    def __init__(self, request=None, response=None):
        self.now = datetime.datetime.now()
        self.ajax_response = THIS_RESPONSE.copy()
        self.tv = {}        
        self.settings = SETTINGS.copy()        
        self.initialize(request, response)        
        self.tv["version"] = os.environ['CURRENT_VERSION_ID']
        self.local = False        

        self.session = self.get_session()
        self.user = self.get_current_user()
示例#22
0
    def _start_timer(self, change=True):
        frame = self.photoframe
        is_mouse_over = frame.check_mouse_on_frame() and change != 'force'

        if change and not is_mouse_over and not frame.has_trash_dialog():
            self.recursion_depth = 0
            updated = self._change_photo()
        else:
            updated = False

        if updated is False:
            interval = 3
            # print "skip!"
        elif frame.is_fullscreen() or frame.is_screensaver():
            interval = SETTINGS.get_int('interval-fullscreen')
        else:
            interval = SETTINGS.get_int('interval')

        self._timer = GLib.timeout_add_seconds(interval, self._start_timer)
        return False
示例#23
0
    def _start_timer(self, change=True):
        frame = self.photoframe
        is_mouse_over = frame.check_mouse_on_frame() and change != 'force'

        if change and not is_mouse_over and not frame.has_trash_dialog():
            self.recursion_depth = 0
            updated = self._change_photo()
        else:
            updated = False

        if updated is False:
            interval = 3
            # print "skip!"
        elif frame.is_fullscreen() or frame.is_screensaver():
            interval = SETTINGS.get_int('interval-fullscreen')
        else:
            interval = SETTINGS.get_int('interval')

        self._timer = GLib.timeout_add_seconds(interval, self._start_timer)
        return False
示例#24
0
    def get_selected_frequencies():
        option_lock.lock()
        out = str(SETTINGS.value('spectrum/frequencies', '')).split(',')

        def is_float(val):
            try:
                float(val)
                return True
            except ValueError:
                return False

        out = list(map(float, filter(is_float, out)))
        option_lock.unlock()
        return out
示例#25
0
def add(filename: str):
    bookmarks = Bookmarks(SETTINGS.get('bookmarks', 'bookmarks.json'))

    with open(filename, 'r') as f:
        data = f.read()

    soup = BeautifulSoup(data, features="html.parser")

    # Find all links
    links = soup.find_all('a', recursive=True)

    # Find category for each link by checking parents
    for link in links:
        bookmarks.add_bookmark(link)

    bookmarks.save()
示例#26
0
async def ctfstatus(ctx):
    if await isRegistered(ctx) == False:
        return

    if await inPublicChannel(
            ctx,
            msg=
            f"Hey, <@{ctx.author.id}>, don't view ctf status info in public channels..."
    ):
        return

    data = [(k, SETTINGS[k]) for k in SETTINGS.iterkeys() if k[0] != '_'
            ]  # filter out the private settings; see settings.py config object
    data.insert(0, ['Setting', 'Value'])
    table = GithubFlavoredMarkdownTable(data)
    await ctx.send(f'CTF Status ```{table.table}```')
示例#27
0
def job_for_cwe_updater():
    LOGINFO_IF_ENABLED(SOURCE_MODULE, '[+] Start CWE updater job')
    if check_internet_connection():
        parser = make_parser()
        cwe_handler = CWEHandler()
        parser.setContentHandler(cwe_handler)
        source = SETTINGS.get("cwe", {}).get(
            "source", "http://cwe.mitre.org/data/xml/cwec_v2.8.xml.zip")
        try:
            LOGINFO_IF_ENABLED(SOURCE_MODULE, '[+] Start downloading file')
            data, response = get_file(getfile=source)
            if 'error' not in response:
                LOGINFO_IF_ENABLED(SOURCE_MODULE, '[+] Start parsing CWE data')
                parser.parse(data)
                LOGINFO_IF_ENABLED(SOURCE_MODULE,
                                   '[+] Complete parsing CWE data')
                for cwe in cwe_handler.cwe:
                    cwe['description_summary'] = cwe[
                        'description_summary'].replace("\t\t\t\t\t", " ")
                    item = {'tag': 'cwe', 'state': 'parsed', 'data': cwe}
                    dc.append(item)
                LOGINFO_IF_ENABLED(
                    SOURCE_MODULE,
                    "[===========================================================================]"
                )
                LOGINFO_IF_ENABLED(
                    SOURCE_MODULE,
                    '[+] CWE update complete at: {}'.format(datetime.utcnow()))
                LOGINFO_IF_ENABLED(
                    SOURCE_MODULE,
                    "[===========================================================================]"
                )
                return False
            else:
                LOGERR_IF_ENABLED(
                    SOURCE_MODULE,
                    '[-] There are some errors in server response: {}'.format(
                        response))
                return False
        except Exception as ex:
            LOGERR_IF_ENABLED(
                SOURCE_MODULE,
                "Got exception during downloading CWE source: {0}".format(ex))
            return False
    else:
        LOGERR_IF_ENABLED(SOURCE_MODULE, '[-] No internet connection!')
        return False
示例#28
0
def main():
    args = argparser().parse_args()

    bookmarks = Bookmarks(SETTINGS.get('bookmarks', 'bookmarks.json'))

    if args.add:
        add(args.add[0])

    if args.dump:
        dump(args.dump[0])
    
    if args.list:
        for bm in bookmarks.get():
            print(bm)
    
    if args.clean:
        bookmarks.clean()
        bookmarks.save("cleaned.json")
示例#29
0
    def on_window_leave_notify_event(self, widget, event):
        #        if event.mode != 2:
        #            return True
        self.photoimage.on_leave_cb(widget, event)

        # save geometry
        if not SETTINGS.get_boolean('window-fix'):
            x, y = widget.get_position()
            w, h = widget.get_size()

            if self.window.get_gravity() == Gdk.Gravity.CENTER:
                x += w / 2
                y += h / 2

            SETTINGS_GEOMETRY.set_int('root-x', x)
            SETTINGS_GEOMETRY.set_int('root-y', y)

        return False
示例#30
0
    def on_window_leave_notify_event(self, widget, event):
#        if event.mode != 2:
#            return True
        self.photoimage.on_leave_cb(widget, event)

        # save geometry
        if not SETTINGS.get_boolean('window-fix'):
            x, y = widget.get_position()
            w, h = widget.get_size()

            if self.window.get_gravity() == Gdk.Gravity.CENTER:
                x += w / 2
                y += h / 2

            SETTINGS_GEOMETRY.set_int('root-x', x)
            SETTINGS_GEOMETRY.set_int('root-y', y)

        return False
示例#31
0
    def ch_buttons(self):
        option_lock.lock()

        # Uncheck all buttons
        self.button_c_h.setChecked(False)
        self.button_c_v.setChecked(False)
        self.button_c_vh.setChecked(False)

        chs = SETTINGS.value('spectrum/channels', '1,2', str).split(',')
        ch_h = '1' in chs
        ch_v = '2' in chs

        if ch_v and ch_h:
            self.button_c_vh.setChecked(True)
        elif ch_h:
            self.button_c_h.setChecked(True)
        elif ch_v:
            self.button_c_v.setChecked(True)

        option_lock.unlock()
示例#32
0
    def load(self):
        weight = SETTINGS.get_int('default-weight')
        source_list = []

        if not self.has_save_file():
            return source_list

        with open(self.save_file, 'r') as f:
            entry = json.load(f)           

        for dir in entry:
            data = { 'target' : '', 'argument' : '',
                     'weight' : weight, 'options' : {} }

            for key, value in entry[dir].items():
                if key in ['source', 'target', 'argument', 'weight']:
                    data[key] = value
                else:
                    data['options'][key] = value

            source_list.append(data)

        source_list.sort(cmp=lambda x,y: cmp(y['weight'], x['weight']))
        return source_list
示例#33
0
 def test_dosbox_cmd_command_2(self):
     settings.set_dosbox_cmd('~/bin/foo bar ~/opt/baz')
     bin_foo = os.path.expanduser('~/bin/foo')
     opt_baz = os.path.expanduser('~/opt/baz')
     self.assertEqual(settings.get_dosbox_cmd(), [bin_foo, 'bar', opt_baz])
示例#34
0
 def changed_resolution(self, val, save_val=True):
     self.label_resolution_val.setText("%d Hz" % val)
     if save_val:
         SETTINGS.setValue('spectrum/resolution', val)
示例#35
0
import json
import os
import sqlite3
import mimetypes

from flask import Flask, request, flash, make_response, g
from flask_cors import CORS

from file_domain import File
from settings import SETTINGS

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = SETTINGS.get('UPLOAD_FOLDER', '/tmp')
CORS(app)
DATABASE = SETTINGS.get('DATABASE')

mimetypes.init()


def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        db = g._database = sqlite3.connect(DATABASE)
    return db


# helper to close
@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
示例#36
0
 def on_menuitem8_toggled(self, widget, *args):
     "_full_screen_cb"
     SETTINGS.set_boolean('fullscreen', widget.get_active())
示例#37
0
try:
    from .message import STOMPMessage, STOMPMessageError
    from .settings import SETTINGS
except ImportError:
    from message import STOMPMessage, STOMPMessageError
    from settings import SETTINGS

CONN_STATUS_RESET = 0
CONN_STATUS_CONNECTED = 1
CONN_STATUS_DISCONNECTED = 128
CONN_STATUS_CLOSED = 256

MESSAGE_BUFFER_SIZE = 128
RECV_BUFFER_SIZE = SETTINGS.get("tcp_recv_buffer_size")

EOM = SETTINGS.get("eom")


class STOMPConnection(object):
    def __init__(self, socket_remote):
        self._sock_remote = socket_remote
        self._state = CONN_STATUS_RESET
        # self._message_buffer = bytearray(b"\x00") * MESSAGE_BUFFER_SIZE
        self._message_buffer = ""
        self._frames = []

        # client related status
        self._cl_accept_version = ""
        self._cl_host = ""
        self._cl_login = ""
        self._cl_passcode = ""
示例#38
0
 def run(self):
     while True:
         self.updated.emit(read_t())
         sleep(SETTINGS.value('inclinometer/t_freq', 1))
示例#39
0
 def test_dosbox_setup(self):
     self.assertFalse(settings.finalized)
     settings.setup()
     self.assertTrue(settings.finalized)
示例#40
0
 def on_menuitem6_toggled(self, widget):
     "_fix_window_cb"
     SETTINGS.set_boolean('window-fix', widget.get_active())
示例#41
0
 def _toggle_fullscreen(self, *args):
     state = not SETTINGS.get_boolean('fullscreen')
     SETTINGS.set_boolean('fullscreen', state)
示例#42
0
from collections import Counter
import hashlib

from requests.sessions import session
from settings import SETTINGS
import json

import requests

from loguru import logger
logger.add(SETTINGS.get('_logfile'))

from datetime import datetime
from pony.orm import *

# https://editor.ponyorm.com/user/shyft/byoctf/designer
# this is probably a bit of an overcomplicated db architecture.
# this is because I was learning the relationships and how they worked in pony.
# things also changed in the project and I left some things in order to not break stuff.

db = Database()


class Flag(db.Entity):
    id = PrimaryKey(int, auto=True)
    challenges = Set('Challenge')
    description = Optional(str)
    solves = Set('Solve')
    flag = Required(str)
    value = Required(float)
    unsolved = Optional(bool, default=True)
示例#43
0
 def on_button_c_vh_clicked(self):
     SETTINGS.setValue('spectrum/channels', '1,2')
     self.ch_buttons()
示例#44
0
 def changed_tx(self, *args, **kwargs):
     selected = sorted(map(self.tx_model.itemData, self.table_tx.selectionModel().selectedRows()))
     SETTINGS.setValue('spectrum/frequencies', ','.join(map(str, selected)))
示例#45
0
 def test_dosbox_cmd_command_whitespace(self):
     settings.set_dosbox_cmd('/bin/foo\\ foo bar "/opt/baz baz/baz"')
     self.assertEqual(settings.get_dosbox_cmd(),
                      ['/bin/foo foo', 'bar', '/opt/baz baz/baz'])
示例#46
0
 def test_dosbox_cmd_env_override(self):
     os.environ['SDOS_DOSBOX_CMD'] = 'test'
     self.assertEqual(settings.get_dosbox_cmd(), ['test'])
示例#47
0
import os
from settings import SETTINGS
from settings import SECRET_SETTINGS
import urllib, logging
from google.appengine.api import urlfetch

settings = SETTINGS.copy()
secret_settings = SECRET_SETTINGS.copy()

def generate_login_url(state, redirect, app_id = settings["fb_id"], scope = settings["fb_permissions"]):
    """https://www.facebook.com/dialog/oauth?
    client_id=YOUR_APP_ID
   &redirect_uri=YOUR_REDIRECT_URI
   &scope=COMMA_SEPARATED_LIST_OF_PERMISSION_NAMES
   &state=SOME_ARBITRARY_BUT_UNIQUE_STRING"""

    if not "http" in redirect:
        #add http
        redirect = "http://" + os.environ["HTTP_HOST"] + redirect

    url = "https://www.facebook.com/dialog/oauth"
    url += "?client_id=" + str(app_id)
    url += "&redirect_uri=" + str(urllib.quote(redirect,''))
    url += "&scope=" + ",".join(scope)
    url += "&state=" + str(urllib.quote(state))

    return url

def code_to_access_token(code, redirect, app_id = settings["fb_id"], app_secret = secret_settings["fb_secret"]):
    """https://graph.facebook.com/oauth/access_token?
    client_id=YOUR_APP_ID
示例#48
0
 def test_set_value(self):
     settings.set_midi_on(False)
     self.assertFalse(settings.get_midi_on())
     settings.set_midi_on(True)
     self.assertTrue(settings.get_midi_on())
示例#49
0
文件: spectrum.py 项目: ecabuk/vlf
    def plot(self, data):
        render_lock.lock()
        option_lock.lock()
        if not self.canvas_initiated:
            self.init_canvas()

        # Plot
        ch = SETTINGS.value('spectrum/channels', '1,2')
        c = 0
        for ch in ch.split(','):
            self.axes.plot(
                data[c * 2], data[c * 2 + 1],
                color='r' if ch == '1' else 'b',
                label='Horizontal' if ch == '1' else 'Vertical'
            )
            c += 1
            self.axes.hold(True)
        self.axes.hold(False)

        # Title
        self.figure.suptitle('%s R=%d F=%d AH=%.2f AV=%.2f V=%d' % (
            datetime.now().strftime('%c'),
            SETTINGS.value('spectrum/resolution', 10, int),
            SETTINGS.value('spectrum/frames', 10, int),
            self.current_aa_h,
            self.current_aa_v,
            get_mic_vol()
        ))

        # Grid
        self.axes.grid(True, which='both')

        self.axes.set_xlim([SETTINGS.value('spectrum/x_min', 15000, int), SETTINGS.value('spectrum/x_max', 30000, int)])
        y_max = SETTINGS.value('spectrum/y_max', 0.1, float)
        if y_max > 0:
            self.axes.set_ylim([0, y_max])
        # Labels
        self.axes.set_xlabel(translate('SpectrumView', 'Frequency [kHz]'))
        self.axes.set_ylabel(translate('SpectrumView', 'Amplitude'))

        option_lock.unlock()

        # Transmitter indicators
        selected = SpectrumOptionsView.get_selected_frequencies()

        if len(selected):
            frequencies = []
            for tx in TRANSMITTERS:
                freq = float(tx[0])
                if freq in selected:
                    frequencies.append([freq, tx[1]])

            # Color Map
            scalar_color_map = cmx.ScalarMappable(
                norm=colors.Normalize(vmin=1, vmax=len(frequencies)),
                cmap=plt.get_cmap('Dark2')
            )
            clr_idx = 0
            for freq in frequencies:
                clr_idx += 1
                self.axes.axvline(
                    freq[0] * 1000,
                    linewidth=2,
                    color=scalar_color_map.to_rgba(clr_idx),
                    alpha=0.9,
                    linestyle='-',
                    label="%.2f kHz [%s]" % (freq[0], freq[1])
                )

        self.axes.legend(prop={'family': 'monospace', 'size': 'small'})

        self.axes.xaxis.set_major_formatter(HZ_2_KHZ_FORMATTER)

        # Refresh canvas
        self.canvas.draw()

        render_lock.unlock()

        # Start the calculation again
        render_wait.wakeAll()
示例#50
0
 def run(self):
     while True:
         self.updated.emit(*read_xy())
         sleep(SETTINGS.value('inclinometer/xy_freq', 0.1))
示例#51
0
from __future__ import division

from gi.repository import Gtk, Gdk, GObject, GLib

import constants
from image import *
from settings import SETTINGS, SETTINGS_GEOMETRY
from menu import PopUpMenu, PopUpMenuFullScreen
from utils.gnomescreensaver import GsThemeWindow, is_screensaver_mode

SETTINGS.set_boolean('fullscreen', False)

from utils.iconimage import IconImage
# FIXME
# Gtk.window_set_default_icon(IconImage('gphotoframe').get_pixbuf())

class PhotoFrameFactory(object):

    def create(self, photolist):

        if is_screensaver_mode():
            photoframe = PhotoFrameScreenSaver()
        else:
            photoframe = PhotoFrame(photolist)

        return photoframe

class PhotoFrame(object):
    """Photo Frame Window"""

    def __init__(self, photolist):
示例#52
0
 def on_window_key_press_event(self, widget, event):
     if event.keyval == Gdk.KEY_Escape:
         SETTINGS.set_boolean('fullscreen', False)
示例#53
0
文件: main.py 项目: ecabuk/vlf
 def set_interval(self, val):
     SETTINGS.setValue('last_session/profile_interval', int(val))
     self.input_interval.setText(str(val))
示例#54
0
 def on_menuitem6_toggled(self, widget):
     "_fix_window_cb"
     SETTINGS.set_boolean('window-fix', widget.get_active())
示例#55
0
 def _set_border_color(self, *args):
     color = SETTINGS.get_string('border-color')
     if color:
         self.ebox.modify_bg(Gtk.StateType.NORMAL, Gdk.color_parse(color))
示例#56
0
文件: main.py 项目: ecabuk/vlf
    def __init__(self, *args):
        super(MainWindow, self).__init__(*args)
        self.setCentralWidget(IntroView())

        QtCore.QTimer.singleShot(SETTINGS.value('common/intro_length', 5000), self._start_main_view)
示例#57
0
 def set_val(new_val):
     option_lock.lock()
     SETTINGS.setValue(option_key, new_val)
     option_lock.unlock()
示例#58
0
 def get_val():
     option_lock.lock()
     out = SETTINGS.value(option_key, default, float)
     option_lock.unlock()
     return out
示例#59
0
 def on_menuitem8_toggled(self, widget, *args):
     "_full_screen_cb"
     SETTINGS.set_boolean('fullscreen', widget.get_active())