Exemple #1
0
    def on_btn_merge(self, sender):
        dialog = Gtk.FileChooserDialog('Subtitle', self.parent, Gtk.FileChooserAction.OPEN, ('_Cancel', Gtk.ResponseType.CANCEL, '_Open', Gtk.ResponseType.OK))
        dialog.set_default_response(Gtk.ResponseType.OK)
        dialog.set_select_multiple(True)
        filter = Gtk.FileFilter()
        filter.set_name('Subtitle File')
        filter.add_pattern('*.srt')
        dialog.add_filter(filter)
        res = dialog.run()
        filenames = []
        if res == Gtk.ResponseType.OK:
            filenames = dialog.get_filenames()
        dialog.destroy()
        if len(filenames) == 1:
            return

        subs = []
        for fn in filenames:
            subs.extend(srtFile(fn).read_from_file())
        subs.sort(key=lambda x: int(x.startTime))

        inf1 = cfile(filenames[0])
        inf2 = cfile(filenames[1])
        outf = common_part(inf1.full_path, inf2.full_path)
        if len(outf) == 0:
            outf = 'merged.srt'
        else:
            outf += '-merged.srt'
        srtFile(outf).write_to_file(subs)
        self.close()
 def last_dir(self):
     if 'videoFile' in self.project and self.project['videoFile'] != '':
         return cfile(self.project['videoFile']).abspath
     else:
         for key in self.project:
             if self.project[key] == '':
                 continue
             return cfile(self.project[key]).abspath
     return ''
	def test_03_Givedata(self):
		global data
		data = cfile(storage=self.storage)
		data.put_data(self.my_data)

		if data.data['bin_data'] != self.my_data:
			raise Exception('Data corruption ...')
	def test_02_Givefile(self):
		global file
		file = cfile(storage=self.storage)
		file.put_file(self.my_file)

		if file.data['bin_data'] != open(self.my_file,'r').read():
			raise Exception('Data corruption ...')
Exemple #5
0
def add_file():
	# Must be set as text/html cause of extjs upload file method
	# http://docs.sencha.com/extjs/4.0.7/#!/api/Ext.form.Basic-method-hasUpload
	# A json in a string will be return to avoid Bottle to automatically set header to json
	response.headers['Content-Type'] = 'text/html'

	data = request.files['file-path']

	if data.filename and data.file:
		if allowed_mimetypes.get(data.filename.split('.')[-1], False):
			content_type = allowed_mimetypes[data.filename.split('.')[-1]]
			account = get_account()
			storage = get_storage(account=account, namespace=namespace)
			cfile_record = cfile(storage=storage)
			cfile_record.put_data(data.file.read(), file_name=data.filename, content_type=content_type)
			try:
				file_id = storage.put(cfile_record)
				data = {'success': True, 'data': {'code': 200, 'message': 'File uploaded', 'filename': data.filename, 'file_id': str(file_id)}}
			except Exception as err:
				data = {'success': False, 'data': {'code': 500, 'message': err}}
		else:
			data = {'success': False, 'data': {'code': 415, 'message': 'Unsupported Media Type'}}
	else:
		data = {'success': False, 'data': {'code': 400, 'message': 'Bad request'}}

	return json.dumps(data)
Exemple #6
0
   def _generate_task_cfg_source(self, dest_dir, header_file, file_name = 'os_task_cfg.c'):
      source = C.cfile(os.path.join(dest_dir, file_name))
      code = source.code
      code.extend(_genCommentHeader('INCLUDES'))
      code.append(C.include(header_file))
      code.append(C.include('os_event_cfg.h'))
      code.append('')
      code.extend(_genCommentHeader('PRIVATE VARIABLES'))
      for static_var in sorted(self.static_vars.values(), key=lambda x: x.name):
         code.append(C.statement(static_var))
      code.append('')
      for alarm_var in self.alarm_vars:
         code.append(C.line(str(alarm_var.decl)+' ='))
         code.append(C.statement(alarm_var.body))
      code.append(C.line(str(self.os_task_var.decl)+' ='))
      code.append(C.statement(self.os_task_var.body))
      code.append('')
      code.extend(_genCommentHeader('PUBLIC VARIABLES'))
      code.append(C.line('os_cfg_t g_os_cfg ='))
      body = C.block(innerIndent = innerIndentDefault)
      body.append(C.line('&os_task_cfg[0],'))
      body.append(C.line('OS_NUM_TASKS,'))
      body.append(C.line('0,'))
      body.append(C.line('0'))
      code.append(C.statement(body))
      code.append('')
      code.extend(_genCommentHeader('PUBLIC FUNCTIONS'))
      for elem in self.cfg.partition.mode_switch_functions.values():
         for callback_name in sorted(elem.calls.keys()):
            code.extend(self._generate_mode_switch_func(callback_name, elem.calls[callback_name]))
            code.append('')

      with io.open(source.path, 'w', newline='\n') as fp:
         for line in source.lines():
            fp.write(line+'\n')
Exemple #7
0
def add_file():
	# Must be set as text/html cause of extjs upload file method
	# http://docs.sencha.com/extjs/4.0.7/#!/api/Ext.form.Basic-method-hasUpload
	# A json in a string will be return to avoid Bottle to automatically set header to json
	response.headers['Content-Type'] = 'text/html'

	data = request.files['file-path']

	if data.filename and data.file:
		if allowed_mimetypes.get(data.filename.split('.')[-1], False):
			content_type = allowed_mimetypes[data.filename.split('.')[-1]]
			account = get_account()
			storage = get_storage(account=account, namespace=namespace)
			cfile_record = cfile(storage=storage)
			cfile_record.put_data(data.file.read(), file_name=data.filename, content_type=content_type)
			try:
				file_id = storage.put(cfile_record)
				data = {'success': True, 'data': {'code': 200, 'message': 'File uploaded', 'filename': data.filename, 'file_id': str(file_id)}}
			except Exception as err:
				data = {'success': False, 'data': {'code': 500, 'message': err}}
		else:
			data = {'success': False, 'data': {'code': 415, 'message': 'Unsupported Media Type'}}
	else:
		data = {'success': False, 'data': {'code': 400, 'message': 'Bad request'}}

	return json.dumps(data)
def gen_filelist(write_file=True):
    exclude_dirs = ['.git', '__pycache__', 'scripts', 'python-3.4.4']
    exclude_files = [
        'test.py', 'filelist.txt', 'mparser_old.py', '.gitignore', 'README.md'
    ]

    if cfile('filelist.txt').exists:
        os.remove('filelist.txt')

    res = []
    for filename in get_file_list(exclude_dirs, exclude_files):
        res.append(filename + '|' + cfile(filename).md5)

    if not write_file:
        return res

    with open('filelist.txt', 'w') as f:
        for line in res:
            f.write(line + '\n')
Exemple #9
0
def put_in_grid_fs(file_path, file_name, account):
	storage = cstorage(account, namespace='files')
	report = cfile(storage=storage)
	report.put_file(file_path, file_name, content_type='application/pdf')
	report.data['creationTs'] = int(time.time())
	id = storage.put(report)
	if not report.check(storage):
		logger.error('Report not in grid fs')
		return False
	else:
		return id	
Exemple #10
0
def main_file(filename):
    f = C.cfile(filename)
    f.code.append(C.sysinclude('stdio.h'))
    f.code.append(C.blank())
    f.code.append(utils._main())
    f.code.append(utils._printf())
    f.code.append(utils._scanf_no_pointer())
    f.code.append(utils._rand())
    for i in range(10000):
        f.code.append(utils._func(f"func{i}"))
    utils._file(filename, str(f))
Exemple #11
0
def put_in_grid_fs(file_path, file_name, account,owner=None):
	storage = cstorage(account, namespace='files')
	report = cfile(storage=storage)
	report.put_file(file_path, file_name, content_type='application/pdf')
	
	if owner:
		report.chown(owner)
	
	id = storage.put(report)
	if not report.check(storage):
		logger.error('Report not in grid fs')
		return False
	else:
		return id	
Exemple #12
0
def put_in_grid_fs(file_path, file_name, account,owner=None):
	storage = cstorage(account, namespace='files')
	report = cfile(storage=storage)
	report.put_file(file_path, file_name, content_type='application/pdf')
	
	if owner:
		report.chown(owner)
	
	id = storage.put(report)
	if not report.check(storage):
		logger.error('Report not in grid fs')
		return False
	else:
		return id	
Exemple #13
0
 def on_btn_ok(self, sender):
     pnum = self.combo.get_active_text()
     if not isint(pnum):
         self.close()
         return
     files = [cfile(self.filename) for i in range(int(pnum))]
     for i, f in enumerate(files):
         f.change_base(f.base + ' - part ' + str(i + 1).zfill(2))
         f.add_subdir('split')
     if not (files[0].path_exists):
         files[0].create_path()
     subs_per_part = ceildiv(len(self.subs), int(pnum))
     for idx, f in enumerate(files):
         partfile = srtFile(f.full_path)
         partfile.write_to_file(self.subs[(idx) * subs_per_part:(idx + 1) *
                                          subs_per_part])
     self.close()
Exemple #14
0
def main():
    local_list = gen_filelist(write_file=False)
    remote_list = read_remote_file(BASE_URL + '/filelist.txt')

    local_dict = {}
    remote_dict = {}
    for line in remote_list:
        filename, md5 = line.split('|')
        filename = filename.strip()
        if platform.system() == 'Windows':
            filename = filename.replace('/', '\\')
        md5 = md5.strip()
        remote_dict[filename] = md5
    for line in local_list:
        filename, md5 = line.split('|')
        filename = filename.strip()
        md5 = md5.strip()
        local_dict[filename] = md5

    dl = []
    for key in remote_dict:
        if not (key in local_dict) or local_dict[key] != remote_dict[key]:
            tmp = key[1:] if platform.system(
            ) != 'Windows' else key[1:].replace('\\', '/')
            dl.append((BASE_URL + '/' + tmp, key))

    failed = []

    for idx, item in enumerate(dl):
        print(
            'Downloading: %s (%.2f)' % (split(item[1])[1],
                                        (idx + 1) / len(dl)), )
        f = cfile(item[1])
        if not f.path_exists:
            f.create_path()
        try:
            get_file(item[0], item[1])
        except:
            failed.append(item[1])

    if len(failed) > 0:
        print('Some files did not update:')
        for filename in failed:
            print(filename)
Exemple #15
0
    def _generate_task_cfg_source(self,
                                  dest_dir,
                                  header_file,
                                  file_name='os_task_cfg.c'):
        source = C.cfile(os.path.join(dest_dir, file_name))
        code = source.code
        code.extend(_genCommentHeader('INCLUDES'))
        code.append(C.include(header_file))
        code.append(C.include('os_event_cfg.h'))
        code.append('')
        code.extend(_genCommentHeader('PRIVATE VARIABLES'))
        for static_var in sorted(self.static_vars.values(),
                                 key=lambda x: x.name):
            code.append(C.statement(static_var))
        code.append('')
        for alarm_var in self.alarm_vars:
            code.append(C.line(str(alarm_var.decl) + ' ='))
            code.append(C.statement(alarm_var.body))
        code.append(C.line(str(self.os_task_var.decl) + ' ='))
        code.append(C.statement(self.os_task_var.body))
        code.append('')
        code.extend(_genCommentHeader('PUBLIC VARIABLES'))
        code.append(C.line('os_cfg_t g_os_cfg ='))
        body = C.block(innerIndent=innerIndentDefault)
        body.append(C.line('&os_task_cfg[0],'))
        body.append(C.line('OS_NUM_TASKS,'))
        body.append(C.line('0,'))
        body.append(C.line('0'))
        code.append(C.statement(body))
        code.append('')
        code.extend(_genCommentHeader('PUBLIC FUNCTIONS'))
        for elem in self.cfg.partition.mode_switch_functions.values():
            for callback_name in sorted(elem.calls.keys()):
                code.extend(
                    self._generate_mode_switch_func(callback_name,
                                                    elem.calls[callback_name]))
                code.append('')

        with io.open(source.path, 'w', newline='\n') as fp:
            for line in source.lines():
                fp.write(line + '\n')
Exemple #16
0
			filter = filter[0]
		else:
			logger.error(" + Invalid filter format")
			filter = {}
	
	msort = []
	if sort:
		sort = json.loads(sort)
		for item in sort:
			direction = 1
			if str(item['direction']) == "DESC":
				direction = -1

			msort.append((str(item['property']), direction))
	
	
	###########search
	try:
		records = storage.find(filter, sort=msort,limit=limit, offset=start,account=account)
		total = storage.count(filter, account=account)
	except Exception, err:
		logger.error('Error while fetching records: %s' % err)
		return HTTPError(500, "Error while fetching records: %s" % err)
	
	data = []
	
	for record in records:
		data.append(cfile(record=record).dump(json=True))
		
	return {'total': total, 'success': True, 'data': data}
Exemple #17
0
import cfile as C
test = C.cfile('test.c')
test.code.append(C.sysinclude('stdio.h'))
test.code.append(C.blank())
test.code.append(
    C.function(
        'main',
        'int',
    ).add_arg(C.variable('argc',
                         'int')).add_arg(C.variable('argv', 'char',
                                                    pointer=2)))
body = C.block(indent=3)
body.append(C.statement(C.fcall('printf').add_param(r'"Hello World!\n"')))
body.append(C.statement('return 0'))
test.code.append(body)
print(str(test))
Exemple #18
0
	def test_01_Init(self):
		global myfile
		myfile = cfile(storage=storage)
		
		if myfile.data != {}:
			raise Exception('Data corruption ...')
Exemple #19
0
	def test_01_Init(self):
		file = cfile()
		if file.data != self.data:
			raise Exception('Data corruption ...')
Exemple #20
0
		if len(filter) > 0:
			filter = filter[0]
		else:
			logger.error(" + Invalid filter format")
			filter = {}
	
	msort = []
	if sort:
		sort = json.loads(sort)
		for item in sort:
			direction = 1
			if str(item['direction']) == "DESC":
				direction = -1

			msort.append((str(item['property']), direction))
	
	
	###########search
	try:
		records, total = storage.find(filter, sort=msort,limit=limit, offset=start,account=account, with_total=True)
	except Exception, err:
		logger.error('Error while fetching records: %s' % err)
		return HTTPError(500, "Error while fetching records: %s" % err)
	
	data = []
	
	for record in records:
		data.append(cfile(record=record).dump(json=True))
		
	return {'total': total, 'success': True, 'data': data}
Exemple #21
0
import cfile as C
hello = C.cfile('hello.c')
hello.code.append(C.sysinclude('stdio.h'))
hello.code.append(C.blank())
hello.code.append(
    C.function(
        'main',
        'int',
    ).add_param(C.variable('argc', 'int')).add_param(
        C.variable('argv', 'char', pointer=2)))
body = C.block(innerIndent=3)
body.append(C.statement(C.fcall('printf').add_arg(r'"Hello World!\n"')))
body.append(C.statement('return 0'))
hello.code.append(body)
print(str(hello))
Exemple #22
0
    def test_01_Init(self):
        global myfile
        myfile = cfile(storage=storage)

        if myfile.data != {}:
            raise Exception('Data corruption ...')