コード例 #1
0
ファイル: main.py プロジェクト: yncat/falcon
    def Search(self):
        basePath = self.parent.activeTab.listObject.rootDirectory
        out_lst = []  # 入力画面が出てるときに、もうファイルリスト取得を開始してしまう
        task = workerThreads.RegisterTask(workerThreadTasks.GetRecursiveFileList, {'path': basePath, 'out_lst': out_lst, 'eol': True})

        searchHistory = history.History(globalVars.app.config.getint("search", "history_count", 0, 0, 100), False)
        grepHistory = history.History(globalVars.app.config.getint("search", "history_count", 0, 0, 100), False)
        hist = {}
        try:
            with open(constants.HISTORY_FILE_NAME, 'rb') as f:
                hist = pickle.load(f)
                searchHistory.lst = hist["search"]
                searchHistory.cursor = len(hist["search"]) - 1
                grepHistory.lst = hist["grep"]
                grepHistory.cursor = len(hist["grep"]) - 1
        except BaseException:
            pass

        d = views.search.Dialog(basePath, list(reversed(searchHistory.getList())), list(reversed(grepHistory.getList())))
        d.Initialize()
        canceled = False
        while(True):
            ret = d.Show()
            if ret == wx.ID_CANCEL:
                task.Cancel()
                canceled = True
                break
            # end キャンセルして抜ける
            val = d.GetValue()
            if val['isRegularExpression']:
                ret = misc.ValidateRegularExpression(val['keyword'])
                if ret != "OK":
                    dialog(_("エラー"), _("正規表現の文法が間違っています。\nエラー内容: %(error)s") % {'error': ret})
                    continue
                # end 正規表現違う
            # end 正規表現モードがオンかどうか
            break
        # end 入力が正しくなるまで
        if canceled:
            return
        actionstr = "search" if val['type'] == 0 else "grep"
        target = {
            'action': actionstr,
            'basePath': basePath,
            'out_lst': out_lst,
            'keyword': val['keyword'],
            'isRegularExpression': val['isRegularExpression']}
        self.parent.Navigate(target, as_new_tab=True)

        if val['type'] == 0:
            searchHistory.add(val['keyword'])
        else:
            grepHistory.add(val['keyword'])
        hist["search"] = searchHistory.getList()
        hist["grep"] = grepHistory.getList()
        try:
            with open(constants.HISTORY_FILE_NAME, 'wb') as f:
                pickle.dump(hist, f)
        except BaseException:
            pass
コード例 #2
0
ファイル: test_history.py プロジェクト: actlaboratory/history
    def test_Duplication(self):
        hist = history.History(3)
        hist.add(0)
        hist.add(1)
        hist.add(0)
        self.assertEqual(hist.getCount(), 3)
        self.assertEqual(hist.getList(), [0, 1, 0])

        hist = history.History(3, False)
        hist.add(0)
        hist.add(1)
        hist.add(0)
        self.assertEqual(hist.getCount(), 2)
        self.assertEqual(hist.getList(), [1, 0])
コード例 #3
0
def get_history():
    target_path = os.path.join(os.path.expanduser('~'), '.bluesky',
                               'metadata_history.db')
    try:
        os.makedirs(os.path.dirname(target_path), exist_ok=True)
        if os.path.isfile(target_path):
            print('Found metadata history in existing file.')
        else:
            print('Storing metadata history in a new file.')
        return history.History(target_path)
    except IOError as exc:
        print(exc)
        print('Storing History in memory; it will not persist.')
        return history.History(':memory:')
コード例 #4
0
def add_wrp_info(wrp, **kw_funcs):
    """
    Updates wrapper with values from keyfunctions.

    Example: Set the legend to the filename like this:

    >>> import os
    >>> w1 = wrappers.Wrapper(name='a_name', file_path='/path/to/my_file.root')
    >>> w1 = add_wrp_info(w1, legend=lambda w: os.path.basename(w.file_path)[:-5])
    >>> w1.legend
    'my_file'
    """
    # evaluate
    kw_args = {}
    for k, f in kw_funcs.iteritems():
        val = f(wrp)
        kw_args[k] = val
        setattr(wrp, k, val)

    # (need to track history manually)
    if isinstance(wrp, wrappers.Wrapper):
        h = history.History('add_wrp_info')
        h.add_args([wrp.history])
        h.add_kws(kw_args)
        wrp.history = h

    return wrp
コード例 #5
0
 def set_server_info(self, servers):
     '''配置服务器信息
     Args:
         servers: 服务器列表
     Returns:
         common.SUCCESS: 正常执行
         其他返回值参考set_server_ip和set_server_static
     '''
     for server in servers:
         #print type(server['adminInfo'])
         sip = server['adminInfo']['ip']
         sname = server['adminInfo']['userName']
         spasswd = server['adminInfo']['passwd']
         his = history.History(sip, sname, spasswd)
         self.svundolist.append(his)
         #print '%s %s %s' % (sip, sname, spasswd)
         ssh = ssh_tools.SshConnect(sip, sname, spasswd)
         for iface in server['svInterface']:
             ip = iface['ip'] + '/' + iface['mask']
             dev = iface['ifName']
             ret = self.set_server_ip(ssh, ip, dev, his)
             if ret != '0':  #shell返回值为字符串,0表示执行成功
                 self.undo(his)
                 return ret
         for static in server['svStaticRoute']:
             destip = '.'.join(
                 static['destIp'].split('.')[:3]) + '.0/' + static['mask']
             via = static['nextIp']
             dev = static['iface']
             #print 'ip:%s  via:%s  dev:%s' % (destip, via, dev)
             ret = self.set_server_static(ssh, destip, via, dev, his)
             if ret != '0':
                 self.undo(his)
                 return ret
     return common.SUCCESS
コード例 #6
0
 def create_transaction(self, command):
     if command == 'B':
         return borrow.Borrow()
     elif command == 'R':
         return returns.Return()
     elif command == 'H':
         return history.History()
コード例 #7
0
ファイル: test_history.py プロジェクト: actlaboratory/history
 def test_cursor(self):
     hist = history.History(4)
     self.assertEqual(hist.getNext(), None)
     self.assertEqual(hist.getPrevious(), None)
     self.assertEqual(hist.getNext(), None)
     self.assertFalse(hist.hasPrevious())
     self.assertFalse(hist.hasNext())
     hist.add(0)
     self.assertFalse(hist.hasPrevious())
     self.assertFalse(hist.hasNext())
     self.assertEqual(hist.getNext(), None)
     self.assertEqual(hist.getPrevious(), None)
     self.assertEqual(hist.getNext(), None)
     hist.add(1)
     self.assertFalse(hist.hasNext())
     self.assertTrue(hist.hasPrevious())
     self.assertFalse(hist.hasNext())
     self.assertEqual(hist.getNext(), None)
     self.assertTrue(hist.hasPrevious())
     self.assertFalse(hist.hasNext())
     self.assertEqual(hist.getPrevious(), 0)
     self.assertFalse(hist.hasPrevious())
     self.assertTrue(hist.hasNext())
     self.assertEqual(hist.getPrevious(), None)
     self.assertEqual(hist.getNext(), 1)
     self.assertEqual(hist.getNext(), None)
     self.assertTrue(hist.hasPrevious())
     self.assertFalse(hist.hasNext())
     hist.add(2)
     hist.getPrevious()
     hist.add(4)
     self.assertEqual(hist.getCount(), 3)
     self.assertEqual(hist.getList(), [0, 1, 4])
     self.assertEqual(hist.getNext(), None)
     self.assertEqual(hist.getPrevious(), 1)
コード例 #8
0
ファイル: figure.py プロジェクト: bntre/visual-lambda
    def __init__(self, expression):

        FieldItem.__init__(self)

        # Parse Expression if needed
        if type(expression) is str:
            expression = parse(expression)
            debug(2, 'init Figure', expression)

        self.expression = expression.withRoot()

        # History of Expression
        self.history = history.History()

        # Colorspace
        self.detColorSpace()

        # Size of Figure
        self.sizeRing = Ring(
            (0, 0), 1.0)  # Ring for setting size of Figure (used in morphing)
        self.refreshTransform()

        self.groups = []
        self.buildGroups()
        self.buildGeometry()

        self.history.step(self.expression.copy())

        # Eating Act
        self.eating = None
コード例 #9
0
 def test_func():
     history_ins = history.History()
     while True:
         score = random.random()
         ex = np.random.randint(low=1, high=10, size=500)
         if history_ins.set_history(ex, score) == False:
             print('Кол-во дублей: {}'.format(history_ins.count_dupl))
             break
コード例 #10
0
ファイル: rendering.py プロジェクト: nabinpoudyal3/Varial
def _track_canvas_history(rnds, kws):
    list_of_histories = []
    for rnd in rnds:
        list_of_histories.append(rnd.history)
    hstry = history.History('build_canvas')
    hstry.add_args(list_of_histories)
    hstry.add_kws(kws)
    return hstry
コード例 #11
0
 def _track_canvas_history(self):
     list_of_histories = []
     for rnd in self.renderers:
         list_of_histories.append(rnd.history)
     hstry = history.History("CanvasBuilder")
     hstry.add_args(list_of_histories)
     hstry.add_kws(self.kws)
     return hstry
コード例 #12
0
ファイル: diskio.py プロジェクト: xiaohu-cern/Varial
def _wrapperize(bare_histo, alias):
    """Returns a wrapper with a fileservice histogram."""
    if not isinstance(bare_histo, TH1):
        raise NoHistogramError('Loaded object is not of type TH1.\n'
                               'Alias: %s\nObject: %s\n' % (alias, bare_histo))
    if not bare_histo.GetSumw2().GetSize():
        bare_histo.Sumw2()
    wrp = wrappers.HistoWrapper(bare_histo, **alias.all_info())
    if isinstance(alias, wrappers.FileServiceAlias):
        bare_histo.SetTitle(alias.legend)
        wrp.history = history.History('FileService(%s, %s)' %
                                      (alias.in_file_path, alias.sample))
    else:
        info = alias.all_writeable_info()
        del info['klass']
        wrp.history = history.History('RootFile(%s)' % info)
    return wrp
コード例 #13
0
ファイル: test_history.py プロジェクト: actlaboratory/history
 def test_overflow(self):
     hist = history.History(3)
     hist.add(0)
     hist.add(1)
     hist.add(2)
     hist.add(3)
     self.assertEqual(hist.getCount(), 3)
     self.assertEqual(hist.get(1), 2)
     self.assertEqual(hist.getList(), [1, 2, 3])
コード例 #14
0
def loadHistory():
    ret = history.History(20, False)
    if os.path.isfile("m3u_history.dat"):
        f = open("m3u_history.dat", "rb")
        hList = pickle.load(f)
        if type(hList) is list:
            ret.lst = hList
            ret.cursor = len(hList) - 1
        f.close()
    return ret
コード例 #15
0
def main(filename=None):
    "if filename is not None, loads it"
    logging.info(_("Using wxPython %s"), config.wx_version)
    common.history = history.History()
    app = wxGlade()
    if filename is not None:
        win = app.GetTopWindow()
        win._open_app(filename, False)
        win.cur_dir = os.path.dirname(filename)
    app.MainLoop()
コード例 #16
0
    def set_switch_info(self, switches):
        '''配置交换机信息
        Args:
            servers: 交换机列表
        Returns:
            common.SUCCESS: 正常执行
            common.SWITCH_SET_ERR: 交换机执行set命令时出错
            common.SWITCH_COMMIT_ERR: 执行commit出错
        '''
        # TODO: 1.交换机命令执行部分代码大量冗余,应抽象出一到两个层次进行封装-[已完成-20150606]
        #       2.后续需要实现配置回滚功能(20150507)
        #
        for switch in switches:
            sip = switch['adminInfo']['ip']
            sname = switch['adminInfo']['userName']
            spasswd = switch['adminInfo']['passwd']
            his = history.History(sip, sname, spasswd)
            self.svundolist.append(his)  #暂时没有用到
            self.telobj = telnet_tools.TelnetXorplus(sip, sname, spasswd)
            for l2if in switch['l2Interface']:
                port = l2if['port']
                pvid = l2if['vlanId']
                vtype = l2if['vtype']
                vmembers = l2if['vmembers']
                if vtype == 1:
                    ret = self.set_switch_l2_trunk(port, pvid, vmembers)
                else:
                    ret = self.set_switch_l2(port, pvid)
                if ret[0] != 0:
                    print json.dumps({'err': ret[1]})
                    return common.ERROR

            for l3if in switch['l3Interface']:
                ifname = l3if['ifName']
                vid = l3if['vlanId']
                ip = l3if['ip']
                mask = l3if['mask']
                ret = self.set_switch_l3(ifname, vid, ip, mask)
                if ret[0] != 0:
                    print json.dumps({'err': ret[1]})
                    return common.ERROR

            for static in switch['swStaticRoute']:
                #'.'.join(static['destIp'].split('.')[:3]) + '.0'
                ip = static['destIp']
                mask = static['mask']
                next = static['nextIp']
                #设置静态路由
                ret = self.set_switch_SR(ip, mask, next)
                if ret[0] != 0:
                    print json.dumps({'err': ret[1]})
                    return common.ERROR
            print json.dumps({'msg': 'set info success'})
            return common.SUCCESS
コード例 #17
0
ファイル: timer.py プロジェクト: Aksem/KoffeeBreak
    def __init__(self, config, gui_connection=None):
        self.config = config
        self.gui_connection = gui_connection

        self.init_config()
        if self.GUI == "qt":
            self.init_gui_qt()
        self.init_parameters()

        self.history_file = history.History()
        self.history_file.write('Open program')

        self.start_work()
コード例 #18
0
    def __init__ (self, xmlui, bindings, props, appletMode):
        window = xmlui.get_widget("lookuplet");
        self.about = xmlui.get_widget("about");
        self.bindings = bindings;
        self.props = props;
        self.appletMode = appletMode;

        # wire up our handlers
        xmlui.signal_connect("on_query_key_press_event",
                             self.on_query_key_press_event);
        xmlui.signal_connect("on_prefs_clicked", self.on_prefs_clicked);
        xmlui.signal_connect("exit_lookuplet", self.exit_lookuplet);

        # create our query history
        self.history = history.History();

        # if we're in applet mode, extract the UI and stick it into an
        # applet widget
        if (appletMode):
            applet = gnome.applet.AppletWidget("lookuplet");
            mainbox = xmlui.get_widget("mainbox");
            # lose the border
            mainbox.set_border_width(0);
            # and hide the prefs button
            prefs = xmlui.get_widget("prefs");
            prefs.hide();
            # remove everything from the window
            window.remove(mainbox);
            # and add it to the applet
            applet.add(mainbox);
            # register our menu items
            applet.register_stock_callback(
                "properties", gnome.ui.STOCK_MENU_PROP,
                "Properties...", self.on_props_selected, None);
            applet.register_stock_callback(
                "about", gnome.ui.STOCK_MENU_ABOUT,
                "About...", self.on_about_selected, None);
            applet.show();

        else:
            window.show();

        # obtain the primary selection and stuff that into our entry box
        # clip = gtk.clipboard_get(gtk.GDK_SELECTION_PRIMARY);
        # selection = gtk.clipboard_wait_for_text(clip);
        query = xmlui.get_widget("query");
        # self.display_selection(self, query, selection);
        # query.paste_clipboard();

        # put the focus in the query box
        query.grab_focus();
コード例 #19
0
ファイル: controller.py プロジェクト: wellenvogel/avsprinkler
 def __init__(self):
     self.logger = logging.getLogger(Constants.LOGNAME)
     configString = open(os.path.join(basedir, "config.json")).read()
     self.config = json.loads(configString)
     self.hardware = hardware.Hardware()
     self.activeChannel = None
     self.stopTime = None
     self.timerThread = threading.Thread(target=self.timerRun)
     self.timerThread.daemon = True
     self.timerThread.start()
     self.history = history.History(os.path.join(basedir, "history.txt"))
     self.history.readEntries()
     for ch in self.hardware.getInputChannelNumbers():
         self.hardware.getInput(ch).registerCallback(self.__cb)
コード例 #20
0
    def setUpClass(cls):
        WXGladeBaseTest.setUpClass()
        xrc2wxg._write_timestamp = False

        # create an simply application
        cls.app = wx.App()
        cls.locale = wx.Locale(wx.LANGUAGE_DEFAULT)
        compat.wx_ArtProviderPush(main.wxGladeArtProvider())
        import history
        common.history = history.History()
        cls.frame = main.wxGladeFrame()

        # suppress wx error messages
        cls.nolog = wx.LogNull()
コード例 #21
0
ファイル: test_history.py プロジェクト: actlaboratory/history
    def test_symple_add(self):
        hist = history.History()
        self.assertTrue(hist.isEmpty())
        hist.add(0)
        self.assertFalse(hist.isEmpty())
        hist.add(1)
        self.assertEqual(hist.getCount(), 2)
        self.assertEqual(hist.get(1), 1)
        self.assertEqual(hist.getList(), [0, 1])

        hist.clear()
        self.assertEqual(hist.getCount(), 0)
        self.assertEqual(hist.get(1), None)
        self.assertEqual(hist.getList(), [])
コード例 #22
0
ファイル: script.py プロジェクト: puwkin/ScriptControl
 def __init__(self, script_name):
     self._hist = history.History('./scripts/_history.db')
     self._name = script_name
     self._trigger = {}
     self._next_run = None
     self._enabled = False
     self._thread = None
     self._running = False
     self._start_time = None
     self.trigger_type = None
     #import class from correct module
     module = importlib.import_module('scripts.' + self._name)
     self._c = getattr(module, self._name.title())
     self._script = self._c()
     self._check_trigger()
コード例 #23
0
ファイル: base.py プロジェクト: yncat/falcon
 def __init__(self, environment):
     self.task = None
     self.colums = []  # タブに表示されるカラムの一覧。外からは読み取りのみ。
     self.listObject = None  # リストの中身を保持している listObjects のうちのどれかのオブジェクト・インスタンス
     self.type = None
     self.isRenaming = False
     globalVars.app.config.add_section(self.__class__.__name__)
     self.environment = environment  # このタブ特有の環境変数
     self.stopSoundHandle = None
     self.checkedItem = set()
     self.hilightIndex = -1
     self.sortTargetColumnNo = None  # 並び替え対象としてアイコン表示中のカラム番号
     if self.environment == {}:
         self.environment["markedPlace"] = None  # マークフォルダ
         self.environment["listType"] = None  # 表示中のリストタイプ(listObject)
         self.environment["history"] = history.History()  # ディレクトリ移動の履歴
コード例 #24
0
def start():
    """
    Funkcia pripravujúca hru.
    Tu sa zisťuje počet hráčov a pripravuje sa prvý stav hry, kedy
    majú všetci hráči svoje figúrky v domčeku (sú na pozícií -1).
    """
    global game_state
    global game_history

    num_of_players = 0
    while (num_of_players < 2 or num_of_players > con.MAX_PLAYERS):
        print("Zadajte pocet hracov (min. 2, max " + str(con.MAX_PLAYERS) +
              "):")
        num_of_players = int(input())

    board = {}
    for i in range(0, num_of_players):
        board[i] = (-1, -1, -1, -1)

    game_state = state.State(num_of_players, board,
                             random.randint(0, num_of_players - 1))
    game_history = history.History()
    play()
コード例 #25
0
    def __init__(self, mainFrameObject):
        if type(mainFrameObject) is not MainFrame:
            TypeError("the input object is not MainFrame")

        self.query = query.Query()
        """
        Collect all widgets
        """
        self.main = mainFrameObject
        self.dialogbehavior = DialogBehavior(self.main)
        self.searchPanelBehavior = SearchPanelBehavior(
            self.main.panelLeft.searchPanel, self.main.panelRight.bookList,
            self.query)

        self.panelL = self.main.panelLeft
        self.panelR = self.main.panelRight
        self.booklist = self.main.panelRight.bookList
        self.statusbar = self.main.statusBar
        self.launchButton = self.main.panelLeft.launchButton
        self.infoBookTree = self.main.panelLeft.infoBookTree

        self.searchComboBox = self.main.panelLeft.searchPanel.searchComboBox
        self.searchEntry = self.main.panelLeft.searchPanel.entrySearch
        self.searchResult = self.main.panelLeft.searchPanel.resultSearch

        self.history = history.History()

        self.statusbar = self.main.statusBar
        self.statusbar.SetStatusText("{} book(s) in the"
                                     " database".format(
                                         bdd_misc_queries.numberOfBooks()))

        #init list items
        self.query.setQuery(select_items.SelectItems.like('book', 'A'))
        self.booklist.fillList(self.query)

        self.initEvent()
コード例 #26
0
 def open_history(self):
     self.history = Toplevel(self.master)
     self.run = h.History(self.history)
コード例 #27
0
ファイル: main.py プロジェクト: zxbuzzy/randomizerQt
        rule.show_rules()

    def open_cubes(self):
        cube.show()

    def open_history(self):
        his.show()
        his.show_history()


if __name__ == "__main__":
    import sys

    # create app
    app = QtWidgets.QApplication(sys.argv)
    # main window
    showMain = Main()
    showMain.show()
    # answer
    ans = answer.Answer()
    # letters
    letter = letters.Letters()
    # rules
    rule = rules.Rules()
    # cubes
    cube = cubes.Cubes()
    # history
    his = history.History()
    # run main loop
    sys.exit(app.exec_())
コード例 #28
0
ファイル: main.py プロジェクト: oluwex/hausa-learning-app
 def on_actionHistory_triggered(self):
     self.history.reverse()
     window = history.History(self.history)
     window.exec_()
コード例 #29
0
# -*- coding: utf-8 -*-
import pygal
import history

from pygal.style import Style

hsvgpath = "../view/history/"

h = history.History("../data/history.dat")

custom_style = Style(
    background='white',
    plot_background='rgba(255, 255, 255, 0.1)',
    foreground='rgba(0, 0, 0, 0.5)',
    foreground_light='rgba(0, 0, 0, 0.7)',
    foreground_dark='rgba(0, 0, 0, 0.3)',
    colors=('rgb(163, 190, 140)',
            'rgb(123, 163, 168)',
            'rgb(130, 192, 175)',
            'rgb(159, 224, 246)',
            'rgb(0, 146, 199)',
            'rgb(91, 144, 191)',
            'rgb(40, 81, 113)',
            'rgb(190, 173, 146)',
            'rgb(243, 90, 74)',
            'rgb(91, 73, 71)',
            'rgb(218, 145, 122)',
            'rgb(242, 156, 156)')
)

line = pygal.Line(
コード例 #30
0
ファイル: scan.py プロジェクト: danielperr/LANKeeper
        sniff_thread.start()
        print('host ip:', host.ip)
        send([
            IP(dst=host.ip) / TCP(dport=port, flags='S')
            for port in COMMON_PORTS
        ],
             verbose=1,
             **self.scapykwargs)
        sniff_thread.join()

        host.ports = list(set(ports))

        print('open ports:', host.ports)


class ScanError(Exception):
    pass


if __name__ == '__main__':
    sc = Scanner()
    # sc.scan('10.100.102.0/24')
    # sc.scan('10.100.102.0/24', NAME + VENDOR)
    # sc.scan('10.100.102.22', PORTS)
    hs = h.History(new=1)
    # sc.progressive_scan(hs, '10.100.102.0/24', 0, 5)
    sc.progressive_scan(
        hs, ', '.join(['172.16.%s.0/24' % x for x in [0, 3, 10, 11, 12, 13]]),
        NAME + VENDOR, 1)
    # sc.progressive_scan(hs, '172.16.0.0/16', 0, 5)