Exemplo n.º 1
0
    def _editWithEditorInThread(self, inputData, note = None):
        if note:
            self.getEvernote().loadNoteContent(note)
            editor = Editor(note.content)
        else:
            editor = Editor('')
        thread = EditorThread(editor)
        thread.start()

        result = True
        prevChecksum = editor.getTempfileChecksum()
        while True:
            if prevChecksum != editor.getTempfileChecksum() and result:
                newContent = open(editor.tempfile, 'r').read()
                inputData['content'] = Editor.textToENML(newContent)
                if not note:
                    result = self.getEvernote().createNote(**inputData)
                    # TODO: log error if result is False or None
                    if result:
                        note = result
                    else:
                        result = False
                else:
                    result = bool(self.getEvernote().updateNote(guid=note.guid, **inputData))
                    # TODO: log error if result is False

                if result:
                    prevChecksum = editor.getTempfileChecksum()

            if not thread.isAlive():
                # check if thread is alive here before sleep to avoid losing data saved during this 5 secs
                break
            time.sleep(5)
        return result
Exemplo n.º 2
0
    def _editWithEditorInThread(self, inputData, note=None, raw=None):
        editor_userprop = getEditor(self.getStorage())
        noteExt_userprop = getNoteExt(self.getStorage()).split(',')[bool(raw)]
        if note:
            self.getEvernote().loadNoteContent(note)
            editor = Editor(editor_userprop, note.content, noteExt_userprop,
                            raw)
        else:
            editor = Editor(editor_userprop, '', noteExt_userprop, raw)
        thread = EditorThread(editor)
        thread.start()

        result = True
        prevChecksum = editor.getTempfileChecksum()
        while True:
            if prevChecksum != editor.getTempfileChecksum() and result:
                newContent = open(editor.tempfile, 'r').read()
                ext = os.path.splitext(editor.tempfile)[1]
                mapping = {
                    'markdown': config.MARKDOWN_EXTENSIONS,
                    'html': config.HTML_EXTENSIONS
                }
                fmt = filter(lambda k: ext in mapping[k], mapping)
                if fmt:
                    fmt = fmt[0]

                inputData['content'] = newContent if raw \
                    else Editor.textToENML(newContent, format=fmt)
                if not note:
                    result = self.getEvernote().createNote(**inputData)
                    # TODO: log error if result is False or None
                    if result:
                        note = result
                    else:
                        result = False
                else:
                    result = bool(self.getEvernote().updateNote(guid=note.guid,
                                                                **inputData))
                    # TODO: log error if result is False

                if result:
                    prevChecksum = editor.getTempfileChecksum()

            if not thread.isAlive():
                # check if thread is alive here before sleep to avoid losing data saved during this 5 secs
                break
            thread.join(timeout=5)
        self._finalizeEditor(editor, result)
        return result
Exemplo n.º 3
0
    def __init__(self,
                 data,
                 out,
                 background_color,
                 size=(1280, 720),
                 delete=False):
        """
        Constructor
        @param data : The popcorn editor project json blob
        """
        self.delete = delete

        self.track_edits = []
        self.track_items = []
        self.track_videos = []
        self.current_video = NamedTemporaryFile(suffix='.avi',
                                                delete=self.delete)
        self.background_color = background_color
        self.size = size
        self.editor = Editor()
        self.real_duration = data['media'][0]['duration']
        self.duration = data['media'][0]['duration']
        self.out = out
        self.base_videos = []

        self.preprocess(data)
Exemplo n.º 4
0
def main():
    # Initialize all imported pygame modules
    pygame.init()
    # Set the width and height of the screen [width, height]
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    # Set the current window caption
    pygame.display.set_caption("Text Editor")
    #Loop until the user clicks the close button.
    done = False
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    # Create text editor object
    editor = Editor()
    # -------- Main Program Loop -----------
    while not done:
        # --- Main event loop
        # --- Process events (keystrokes, mouse clicks, etc)
        done = editor.process_events()
        # --- Game logic should go here
        editor.run_logic()
        # --- Draw the current frame
        editor.display_frame(screen)
        # --- Limit to 30 frames per second
        clock.tick(30)

    # Close the window and quit.
    # If you forget this line, the program will 'hang'
    # on exit if running from IDLE.
    pygame.quit()
Exemplo n.º 5
0
    def initUI(self):
        self.layout = QtGui.QHBoxLayout(self)

        self.menuLayout = QtGui.QVBoxLayout(self)
        self.detailLayout = QtGui.QVBoxLayout(self)

        self.menuLayout.setContentsMargins(8, 8, 8, 8)

        self.model = model
        self.view, self.view_selection = self.initView(model)
        self.viewcontext = self.initContext()
        self.viewsearch = LineEdit(self)
        self.viewtoolbar = self.initToolbar()

        self.editor = Editor(self)

        self.detailLayout.addWidget(self.editor)
        self.menuLayout.addWidget(self.viewtoolbar)
        self.menuLayout.addWidget(self.viewsearch)
        self.menuLayout.addWidget(self.view)

        self.layout.addLayout(self.menuLayout)
        self.layout.addLayout(self.detailLayout)
        self.layout.setStretchFactor(self.menuLayout, 2)
        self.layout.setStretchFactor(self.detailLayout, 3)

        self.setStyleSheet()
        self.setLayout(self.layout)
Exemplo n.º 6
0
    def run(self):
        if self.qpkg_dir is None:
            error('Cannot find QNAP/changelog anywhere!')
            error('Are you in the source code tree?')
            return -1

        # read ~/.qdkrc
        qdkrc = QDKrc()
        cfg_user = qdkrc.config['user']

        control = ControlFile(self.qpkg_dir)
        changelog = ChangelogFile(self.qpkg_dir)
        kv = {'package_name': control.source['source']}
        if self._args.message is not None:
            kv['messages'] = self._args.message
        if self._args.version is not None:
            kv['version'] = self._args.version
        kv['author'] = cfg_user['name'] if self.author is None else self.author
        kv['email'] = cfg_user['email'] if self.email is None else self.email
        if len(kv['author']) == 0 or len(kv['email']) == 0:
            warning('Environment variable QPKG_NAME or QPKG_EMAIL are empty')
            info('QPKG_NAME: ' + kv['author'])
            info('QPKG_EMAIL: ' + kv['email'])
            yn = raw_input('Continue? (Y/n) ')
            if yn.lower() == 'n':
                return 0
            kv['author'] = 'noname'
            kv['email'] = '*****@*****.**'
        entry = changelog.format(**kv)

        editor = Editor()
        editor.insert_content(entry)
        editor.open(changelog.filename)
        return 0
Exemplo n.º 7
0
Arquivo: edit.py Projeto: yen3/qdk2
    def run(self):
        if self.qpkg_dir is None:
            error('Cannot find QNAP/control anywhere!')
            error('Are you in the source code tree?')
            return -1

        if self._args.filename is None:
            self._args.filename = 'control'

        cfiles = self._get_support_control_files()

        if self._args.filename not in cfiles:
            error('Support control files: {}'.format(', '.join(cfiles)))
            return -1

        filename = pjoin(self.qpkg_dir, Settings.CONTROL_PATH,
                         self._args.filename)

        editor = Editor()
        if not pexists(filename):
            editor.set_template_file(
                pjoin(Settings.TEMPLATE_PATH, Settings.CONTROL_PATH,
                      '{}{}'.format(Settings.DEFAULT_PACKAGE,
                                    filename[filename.rfind('.'):])))
        editor.open(filename)
        return 0
Exemplo n.º 8
0
def main():
    if len(sys.argv) < 2:
        print("This isn't terminal 101... what the file?")
        return (1)
    filename = sys.argv[1]
    editor_in = Editor(filename)
    return (0)
Exemplo n.º 9
0
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle(self.tr("Alum Code Editor"))
        self.setMinimumSize(750,500)
        self._want_to_close = False

        #Barra de Menu TOP
        menu = self.menuBar()
        self.__crear_acciones()
        self.__crear_menu(menu)
        #Widget Cetral
        self.editor = Editor()

        self.setCentralWidget(self.editor)
        self.editor.setStyleSheet("background-color:#1e1e1e;color:white;font-size:18px;border:none;")
        self.editor.cursorPositionChanged.connect(self._actualizar_status_bar)
        #ToolBar
        self.toolbar = QToolBar()
        self.__crear_Toolbar(self.toolbar)
        self.addToolBar(Qt.LeftToolBarArea, self.toolbar)

        #satusBar
        self.status = StatusBar()
        self.setStatusBar(self.status)
        self.status.setStyleSheet("background-color:#252526;")

        #Conexiones
        self.abrir.triggered.connect(self._abrir_archivo)
        self.guardar.triggered.connect(self._guardar_archivo)
        self.nuevo.triggered.connect(self._nuevo_archivo)
Exemplo n.º 10
0
    def __init__(self):
        ShowBase.__init__(self)

        # создаём менеджер карты
        self.map_manager = MapManager()

        # создаём контроллер мышки и клавиатуры
        self.controller = Controller()

        # создаём редактор
        self.editor = Editor(self.map_manager)

        # загружаем картинку курсора
        pointer = OnscreenImage(image='target.png', pos=(0, 0, 0), scale=0.08)
        # устанавливаем прозрачность
        pointer.setTransparency(TransparencyAttrib.MAlpha)

        # имя файла для сохранения и загрузки карт
        self.file_name = "my_map.dat"

        self.accept("f1", self.basicMap)
        self.accept("f2", self.generateRandomMap)
        self.accept("f3", self.saveMap)
        self.accept("f4", self.loadMap)

        print("'f1' - создать базовую карту")
        print("'f2' - создать случайную карту")
        print("'f3' - сохранить карту")
        print("'f4' - загрузить карту")

        # генерируем случайный уровень
        self.generateRandomMap()
Exemplo n.º 11
0
 def dns_org_mud_moo_simpleedit_content(self, msg):
     editor = Editor({
         'filetype' : msg.data['type'],
         'content'  : msg.data['content'],
         'callback' : self._send_file
     })
     self.in_progress[editor._id] = msg
Exemplo n.º 12
0
 def do_ABRIR(self, archivo):
     self.archivo = Archivo(archivo)
     self.archivo.leer()
     self.archivo.conversion()
     self.archivo.agregar_objeto()
     self.editor = Editor(self.archivo)
     self.editor.representar_cancion()
Exemplo n.º 13
0
    def view_tasks(self):
        self.__cur_user.subjects = self.__data.get_courses(self.__cur_user)

        for i, sub in enumerate(self.__cur_user.subjects):
            print(i + 1, sub[0], sep=" - ")

        idx = ''
        while all([str(j) != idx for j in range(1, i + 2)]):
            idx = input("Enter course ID: ")

        task = self.__data.get_tasks(self.__cur_user.subjects[int(idx) -
                                                              1][0])[0][0]
        print(task)

        choice = ''
        while '1' != choice != '2':
            choice = input("1 - Submit new file\n" + "2 - Back to menu\n")

        if choice == '1':
            tmp = Editor([])
            tmp.write_script()
            sub = self.__cur_user.subjects[int(idx) - 1][0]
            res = tmp.run_script(
                f"{self.__cur_user.surname}_{self.__cur_user.name}_" + sub)
            self.__data.submit_path(self.__cur_user, sub, res[1])
        else:
            pass
Exemplo n.º 14
0
    def make_gif(src=None, resize=1, set=None):
        """Make gif from sequence of images. Saves to media folder.

        Parameters
        -------------
        src:String,
            The path or file location of the image sequence
        resize=1:Integer,
            Calls on Editor.resize_img to Scale down image by resize.
            Defaults to 1 which is no change.
        set=None:List,
            A list of two integer indices for a set of
            images to make the GIF.
        """
        images = []
        os.chdir('./media/img/' + str(src))
        print('{:s} files to be processed in {:s}:'.format(str(len(os.listdir('.'))), src))
        for image in os.listdir('.'):
            # Load image into Editor.
            new_image = Editor(image)
            reduced = new_image.resize_img(resize)
            # print(reduced.filename)

            images.append(imageio.imread(reduced.filename))
            reduced.close()
        new_gif_name = str(random.randint(1,10000))
        print('Saving new GIF: {}.gif'.format(new_gif_name))

        imageio.mimwrite('../../{}.gif'.format(new_gif_name), images if set is None else images[slice(set[0], set[1])], duration=1/22, fps=22)
Exemplo n.º 15
0
def add_editor():
    editor = Editor()
    fig.canvas.mpl_connect('button_press_event', editor.on_click)
    fig.canvas.mpl_connect('button_press_event', editor.on_press)
    fig.canvas.mpl_connect('button_release_event', editor.on_release)
    fig.canvas.mpl_connect('pick_event', editor.on_pick)
    fig.canvas.mpl_connect('motion_notify_event', editor.on_motion)
Exemplo n.º 16
0
    def setup_app(self):
        self.setupActions()
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        self.tree = Tree()
        self.editor = Editor()

        self.tab_widget = QtGui.QTabWidget()
        self.preview = Preview()
        self.pdf_pane = PDFPane()
        self.tab_widget.addTab(self.preview, "HTML")
        self.tab_widget.addTab(self.pdf_pane, "PDF")

        self.file_path = None
        self.output_html_path = None

        self.setCentralWidget(splitter)
        splitter.addWidget(self.tree)
        splitter.addWidget(self.editor)

        splitter.addWidget(self.tab_widget)

        self.setWindowTitle("Sphinx Docs Editor")
        self.createMenus()
        self.createToolBars()
        self.showMaximized()
Exemplo n.º 17
0
 def do_ABRIR(self, archivo):
     '''Toma como parametro un archivo y lo abre en consola'''
     self.archivo = Archivo(archivo)
     self.archivo.leer()
     self.archivo.conversion()
     self.archivo.agregar_objeto()
     self.editor = Editor(self.archivo)
     self.editor.representar_cancion()
Exemplo n.º 18
0
def main():
    root = tk.Tk()
    app = Editor(root)
    root.title("Longclaw")
    root.minsize(951,540)
    root.configure()

    root.mainloop()
Exemplo n.º 19
0
 def do_REPRODUCIR(self, archivo):
     '''Este comando reproduce el archivo dado como parametro.
     Utilizacion: *>>REPRODUCIR nombre_del_archivo.plp'''
     try:
         self.editor = Editor(archivo)
         self.editor.reproducir(-1)
     except IOError:
         print(MENSAJE_IOERROR)
Exemplo n.º 20
0
 def do_REPRODUCIR(self, archivo):
     '''Este comando reproduce el archivo dado como parametro.
     Utilizacion: *>>REPRODUCIR nombre_del_archivo.plp'''
     try:
         self.editor = Editor(archivo)
         self.editor.preparar_reproduccion(-1)
     except IOError:
         print('No se puede encontrar el archivo.')
Exemplo n.º 21
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--map-editor",
                        help="launch editor for building maps",
                        action="store_true")
    parser.add_argument("--debug",
                        help="turn on the lights",
                        action="store_true")
    parser.add_argument("--map-file",
                        help="a json file that specifies a map",
                        required=True)
    args = parser.parse_args()

    # IO engine
    pyg.init()

    editor = None
    if args.map_editor:
        editor = Editor(args)
    world = World(args)
    screen = pyg.display.set_mode(screen_size(args))

    prev_time_s = time.time()
    keys = set()
    while True:
        # take input
        events = []
        for event in pyg.event.get():
            events.append(event)
            if event.type == pyg.QUIT:
                return
            elif event.type == pyg.KEYDOWN:
                keys.add(event.key)
            elif event.type == pyg.KEYUP:
                keys.discard(event.key)

        # simulate
        if editor != None:
            should_reload = editor.handle(events, screen)
            if should_reload:
                world = World(args)
        if world.step(keys):
            return

        # draw
        screen.fill(BLACK)
        world.draw(screen)
        if editor != None:
            editor.draw(screen)
        pyg.display.flip()

        # sleep
        cur_time_s = time.time()
        elapsed_s = cur_time_s - prev_time_s
        wait_s = TIME_STEP_S - elapsed_s
        if wait_s >= 0.0:
            time.sleep(wait_s)
        prev_time_s = cur_time_s
Exemplo n.º 22
0
 def do_ABRIR(self, archivo):
     '''Este comando abre el archivo dado como parametro y lo
     prepara para edicion.
     Utilizacion: *>>ABRIR nombre_del_archivo.plp'''
     try:
         self.editor = Editor(archivo)
         self.editor.representar_cancion()
     except IOError:
         print(MENSAJE_IOERROR)
Exemplo n.º 23
0
 def __init__(self, master=None):
     super().__init__(master)
     self.master = master
     self.grid()
     self.editor = Editor(master)
     self.music = Music()
     self.player = Player()
     self.parser = Parser(self.music)
     self.create_widgets()
Exemplo n.º 24
0
    def configure(self, req):
        """ load config from server """
        _config = json.loads(req.text)
        self.endpoint = _config['endpoint']
        _editor = Editor(context=self, config=_config)

        if _config.get('use_websocket', False):
            self.broker(config=_config, editor=_editor)

        Controller(context=self, editor=_editor)
Exemplo n.º 25
0
def main(world_folder):
    """Create and run editor"""
    editor = Editor(world_folder)
    #print(editor.get_block_name(1, 120, 3))
    and_gate(editor)
    or_gate(editor, 5, 0)
    not_gate(editor, 10, 0)
    switch(editor, 15, 0)
    light(editor, 20, 0)
    xor_gate(editor, 25, 0)
Exemplo n.º 26
0
    def __init__(self, parent=None):
        super(mainWindow, self).__init__(parent)
        config.filename = "Untitled"
        self.tabNum = 0
        self.treeVis = True
        self.termVis = False
        config.docList = []
        self.edit = Editor()
        self.editDict = {"edit1": self.edit}
        self.tab = QTabWidget(self)

        self.initUI()
Exemplo n.º 27
0
def load():
    global editor

    path = filedialog.askopenfilename()

    if path:
        if editor:
            for child in editor_area.winfo_children():
                child.destroy()

        editor = Editor(path, master=editor_area, bg="black")
        editor.pack()
Exemplo n.º 28
0
 def newTab(self):
     self.tabNum += 1
     # Add a new entry to the dict and map it to an editor object
     self.editDict["edit" + str(self.tabNum)] = Editor()
     self.tab.addTab(self.getEditor(self.tabNum), "Untitled")
     config.docList.append("Untitled")
     self.guessLexer()
     try:
         self.getEditor(self.tab.currentIndex() + 1).lexer.setFont(
             config.font)
     except:
         pass
Exemplo n.º 29
0
    def post(self, request):

        start = int(float(request.POST['start']))
        end = int(float(request.POST['end']))
        editor = Editor(settings.MEDIA_ROOT + '/test1.mp4')
        video = editor.crop_video(start, end)
        filename = settings.MEDIA_ROOT + '/test1_temp.webm'
        editor.save_video(video, filename)

        return HttpResponse(json.dumps(
            {'filename': settings.MEDIA_URL + '/test1_temp.webm?i=' + n}),
                            content_type='application/json')
Exemplo n.º 30
0
def main():
    ## load mappings ##
    try:
        setup_keymap_folder()
    except Exception:
        traceback.print_exc()
        utils.rpc('GUI.ShowNotification',
                  title="Keymap Editor",
                  message="Failed to remove old keymap file",
                  image='error')
        return

    defaultkeymap = utils.read_keymap(default)
    userkeymap = []
    if os.path.exists(gen_file):
        try:
            userkeymap = utils.read_keymap(gen_file)
        except Exception:
            traceback.print_exc()
            utils.rpc('GUI.ShowNotification',
                      title="Keymap Editor",
                      message="Failed to load keymap file",
                      image='error')
            return

    ## main loop ##
    confirm_discard = False
    while True:
        idx = Dialog().select(tr(30000), [tr(30003), tr(30004), tr(30005)])
        if idx == 0:
            # edit
            editor = Editor(defaultkeymap, userkeymap)
            editor.start()
            confirm_discard = editor.dirty
        elif idx == 1:
            # reset
            confirm_discard = bool(userkeymap)
            userkeymap = []
        elif idx == 2:
            # save
            if os.path.exists(gen_file):
                shutil.copyfile(gen_file, gen_file + ".old")
            utils.write_keymap(userkeymap, gen_file)
            xbmc.executebuiltin("action(reloadkeymaps)")
            break
        elif idx == -1 and confirm_discard:
            if Dialog().yesno(tr(30000), tr(30006)) == 1:
                break
        else:
            break

    sys.modules.clear()