prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>config.js<|end_file_name|><|fim▁begin|>// ***************************************************************** // Ox - A modular framework for developing templated, responsive, grid-based projects. // // ***************************************************************** // Project configuration var project = 'ox' // Directory name for your project. , src = './src/' // The raw files for your project. , build = './build/' // The temporary files of your development build. , dist = './dist/' // The production package that you'll upload to your server. , assets = 'assets/' // The assets folder. , bower = './bower_components/' // Bower packages. , modules = './node_modules/' // npm packages. ; // Project settings module.exports = { browsersync: { files: [build+'/**', '!'+build+'/**.map'] // Watch all files, except map files , notify: false // In-line notifications , open: false // Stops the browser window opening automatically , port: 1337 // Port number for the live version of the site; default: 1377 , server: { baseDir: build } //, proxy: project+'.dev' // Proxy defined to work with Virtual Hosts , watchOptions: { debounceDelay: 2000 // Avoid triggering too many reloads } }, images: { build: { // Copies images from `src` to `build`; does not optimise src: src+'**/*.+(png|jpg|jpeg|gif|svg)' , dest: build } , dist: { // Optimises images in the `dist` folder src: [dist+'**/*.+(png|jpg|jpeg|gif|svg)'] , imagemin: { optimizationLevel: 7 , progressive: true , interlaced: true } , dest: dist } }, scripts: { bundles: { // Bundles are defined by a name and an array of chunks (below) to concatenate. core: ['core'] , vendor: ['vendor'] , jquery: ['jquery'] , modernizr: ['modernizr'] } , chunks: { // Chunks are arrays of paths or globs matching a set of source files core: src+assets+'js/core/*.js' , vendor: src+assets+'js/vendor/*.js' , modernizr: src+assets+'js/modernizr/*.js' , jquery: bower+'jquery/dist/jquery.js' } , dest: build+assets+'js/' , lint: { src: [src+assets+'js/**/*.js', '!'+src+assets+'js/vendor/*.js', '!'+src+assets+'js/modernizr/*.js'] } , minify: { src: build+assets+'js/**/*.js' , uglify: {} // Default options , dest: build+assets+'js/' } }, styles: { build: { src: src+assets+'scss/**/*.scss' , dest: build+assets+'/styles' } , autoprefixer: { browsers: ['> 1%', 'last 2 versions', 'ie 11', 'ios >= 6', 'android >= 4', 'safari >= 8'] , grid: true } , stylelint: {"rules": { "color-no-invalid-hex": true, "number-leading-zero": "always", "number-no-trailing-zeros": true, "length-zero-no-unit": true, "string-quotes": "double", "value-no-vendor-prefix": true, "declaration-colon-space-before": "never", "declaration-bang-space-before": "always", "declaration-bang-space-after": "never", "declaration-block-semicolon-newline-after": "always-multi-line", "selector-list-comma-space-before": "never", "selector-pseudo-element-colon-notation": "double", "max-empty-lines": 5 }} , minify: { safe: true, autoprefixer: false } , libsass: { // Requires the libsass implementation of Sass includePaths: [src+assets+'scss', bower, modules] , precision: 6 } }, theme: { beautify: { "indent_size": 4, "indent_with_tabs": true, "max_preserve_newlines": 1 } , njk: { src: src+'app/pages/**/*.+(html|njk|json)' , path: [src+'app/templates'] , dest: build<|fim▁hole|> } , html: { src: src+'**/*.html' , dest: build } , favicon: { src: src+assets+'images/favicon/*.+(ico|jpg|json)' , dest: build+assets+'images' } , font: { src: src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)' , dest: build+assets+'fonts' } }, utils: { clean: [build+'**/.DS_Store'] , wipe: [dist] , dist: { src: [build+'**/*', '!'+build+'**/*.map'] , dest: dist } }, watch: { src: { styles: src+assets+'scss/**/*.scss' , scripts: src+assets+'js/**/*.js' , images: src+'**/*.+(png|jpg|jpeg|gif|svg)' , theme: src+'**/*.+(html|njk|json)' , themeassets: [src+assets+'images/favicon/*.+(ico|jpg|json)', src+assets+'fonts/**/*.+(eot|svg|ttf|woff|woff2)'] } , watcher: 'browsersync' } }<|fim▁end|>
<|file_name|>windows.py<|end_file_name|><|fim▁begin|>import os import logging import claripy from ..errors import ( AngrSimOSError, TracerEnvironmentError, SimSegfaultException, SimUnsupportedError, SimZeroDivisionException, ) from .. import sim_options as o from ..tablespecs import StringTableSpec from ..procedures import SIM_LIBRARIES as L from .simos import SimOS _l = logging.getLogger('angr.simos.windows') class SimWindows(SimOS): """ Environemnt for the Windows Win32 subsystem. Does not support syscalls currently. """ def __init__(self, project): super(SimWindows, self).__init__(project, name='Win32') self._exception_handler = None self.fmode_ptr = None self.commode_ptr = None self.acmdln_ptr = None self.wcmdln_ptr = None def configure_project(self): super(SimWindows, self).configure_project() # here are some symbols which we MUST hook, regardless of what the user wants self._weak_hook_symbol('GetProcAddress', L['kernel32.dll'].get('GetProcAddress', self.arch)) self._weak_hook_symbol('LoadLibraryA', L['kernel32.dll'].get('LoadLibraryA', self.arch)) self._weak_hook_symbol('LoadLibraryExW', L['kernel32.dll'].get('LoadLibraryExW', self.arch)) self._exception_handler = self._find_or_make('KiUserExceptionDispatcher') self.project.hook(self._exception_handler, L['ntdll.dll'].get('KiUserExceptionDispatcher', self.arch), replace=True) self.fmode_ptr = self._find_or_make('_fmode') self.commode_ptr = self._find_or_make('_commode') self.acmdln_ptr = self._find_or_make('_acmdln') self.wcmdln_ptr = self._find_or_make('_wcmdln') def _find_or_make(self, name): sym = self.project.loader.find_symbol(name) if sym is None: return self.project.loader.extern_object.get_pseudo_addr(name) else: return sym.rebased_addr # pylint: disable=arguments-differ def state_entry(self, args=None, env=None, argc=None, **kwargs): state = super(SimWindows, self).state_entry(**kwargs) if args is None: args = []<|fim▁hole|> argc = claripy.BVV(len(args), state.arch.bits) elif type(argc) in (int, long): # pylint: disable=unidiomatic-typecheck argc = claripy.BVV(argc, state.arch.bits) # Make string table for args and env table = StringTableSpec() table.append_args(args) table.append_env(env) # calculate full command line, since this is windows and that's how everything works cmdline = claripy.BVV(0, 0) for arg in args: if cmdline.length != 0: cmdline = cmdline.concat(claripy.BVV(' ')) if type(arg) is str: if '"' in arg or '\0' in arg: raise AngrSimOSError("Can't handle windows args with quotes or nulls in them") arg = claripy.BVV(arg) elif isinstance(arg, claripy.ast.BV): for byte in arg.chop(8): state.solver.add(byte != claripy.BVV('"')) state.solver.add(byte != claripy.BVV(0, 8)) else: raise TypeError("Argument must be str or bitvector") cmdline = cmdline.concat(claripy.BVV('"'), arg, claripy.BVV('"')) cmdline = cmdline.concat(claripy.BVV(0, 8)) wcmdline = claripy.Concat(*(x.concat(0, 8) for x in cmdline.chop(8))) if not state.satisfiable(): raise AngrSimOSError("Can't handle windows args with quotes or nulls in them") # Dump the table onto the stack, calculate pointers to args, env stack_ptr = state.regs.sp stack_ptr -= 16 state.memory.store(stack_ptr, claripy.BVV(0, 8*16)) stack_ptr -= cmdline.length / 8 state.memory.store(stack_ptr, cmdline) state.mem[self.acmdln_ptr].long = stack_ptr stack_ptr -= wcmdline.length / 8 state.memory.store(stack_ptr, wcmdline) state.mem[self.wcmdln_ptr].long = stack_ptr argv = table.dump(state, stack_ptr) envp = argv + ((len(args) + 1) * state.arch.bytes) # Put argc on stack and fix the stack pointer newsp = argv - state.arch.bytes state.memory.store(newsp, argc, endness=state.arch.memory_endness) state.regs.sp = newsp # store argc argv envp in the posix plugin state.posix.argv = argv state.posix.argc = argc state.posix.environ = envp state.regs.sp = state.regs.sp - 0x80 # give us some stack space to work with # fake return address from entry point return_addr = self.return_deadend kernel32 = self.project.loader.shared_objects.get('kernel32.dll', None) if kernel32: # some programs will use the return address from start to find the kernel32 base return_addr = kernel32.get_symbol('ExitProcess').rebased_addr if state.arch.name == 'X86': state.mem[state.regs.sp].dword = return_addr # first argument appears to be PEB tib_addr = state.regs.fs.concat(state.solver.BVV(0, 16)) peb_addr = state.mem[tib_addr + 0x30].dword.resolved state.mem[state.regs.sp + 4].dword = peb_addr return state def state_blank(self, **kwargs): if self.project.loader.main_object.supports_nx: add_options = kwargs.get('add_options', set()) add_options.add(o.ENABLE_NX) kwargs['add_options'] = add_options state = super(SimWindows, self).state_blank(**kwargs) # yikes!!! fun_stuff_addr = state.libc.mmap_base if fun_stuff_addr & 0xffff != 0: fun_stuff_addr += 0x10000 - (fun_stuff_addr & 0xffff) state.memory.map_region(fun_stuff_addr, 0x2000, claripy.BVV(3, 3)) TIB_addr = fun_stuff_addr PEB_addr = fun_stuff_addr + 0x1000 if state.arch.name == 'X86': LDR_addr = fun_stuff_addr + 0x2000 state.mem[TIB_addr + 0].dword = -1 # Initial SEH frame state.mem[TIB_addr + 4].dword = state.regs.sp # stack base (high addr) state.mem[TIB_addr + 8].dword = state.regs.sp - 0x100000 # stack limit (low addr) state.mem[TIB_addr + 0x18].dword = TIB_addr # myself! state.mem[TIB_addr + 0x24].dword = 0xbad76ead # thread id if self.project.loader.tls_object is not None: state.mem[TIB_addr + 0x2c].dword = self.project.loader.tls_object.user_thread_pointer # tls array pointer state.mem[TIB_addr + 0x30].dword = PEB_addr # PEB addr, of course state.regs.fs = TIB_addr >> 16 state.mem[PEB_addr + 0xc].dword = LDR_addr # OKAY IT'S TIME TO SUFFER # http://sandsprite.com/CodeStuff/Understanding_the_Peb_Loader_Data_List.html THUNK_SIZE = 0x100 num_pe_objects = len(self.project.loader.all_pe_objects) thunk_alloc_size = THUNK_SIZE * (num_pe_objects + 1) string_alloc_size = sum(len(obj.binary)*2 + 2 for obj in self.project.loader.all_pe_objects) total_alloc_size = thunk_alloc_size + string_alloc_size if total_alloc_size & 0xfff != 0: total_alloc_size += 0x1000 - (total_alloc_size & 0xfff) state.memory.map_region(LDR_addr, total_alloc_size, claripy.BVV(3, 3)) state.libc.mmap_base = LDR_addr + total_alloc_size string_area = LDR_addr + thunk_alloc_size for i, obj in enumerate(self.project.loader.all_pe_objects): # Create a LDR_MODULE, we'll handle the links later... obj.module_id = i+1 # HACK HACK HACK HACK addr = LDR_addr + (i+1) * THUNK_SIZE state.mem[addr+0x18].dword = obj.mapped_base state.mem[addr+0x1C].dword = obj.entry # Allocate some space from the same region to store the paths path = obj.binary # we're in trouble if this is None string_size = len(path) * 2 tail_size = len(os.path.basename(path)) * 2 state.mem[addr+0x24].short = string_size state.mem[addr+0x26].short = string_size state.mem[addr+0x28].dword = string_area state.mem[addr+0x2C].short = tail_size state.mem[addr+0x2E].short = tail_size state.mem[addr+0x30].dword = string_area + string_size - tail_size for j, c in enumerate(path): # if this segfaults, increase the allocation size state.mem[string_area + j*2].short = ord(c) state.mem[string_area + string_size].short = 0 string_area += string_size + 2 # handle the links. we construct a python list in the correct order for each, and then, uh, mem_order = sorted(self.project.loader.all_pe_objects, key=lambda x: x.mapped_base) init_order = [] partially_loaded = set() def fuck_load(x): if x.provides in partially_loaded: return partially_loaded.add(x.provides) for dep in x.deps: if dep in self.project.loader.shared_objects: depo = self.project.loader.shared_objects[dep] fuck_load(depo) if depo not in init_order: init_order.append(depo) fuck_load(self.project.loader.main_object) load_order = [self.project.loader.main_object] + init_order def link(a, b): state.mem[a].dword = b state.mem[b+4].dword = a # I have genuinely never felt so dead in my life as I feel writing this code def link_list(mods, offset): if mods: addr_a = LDR_addr + 12 addr_b = LDR_addr + THUNK_SIZE * mods[0].module_id link(addr_a + offset, addr_b + offset) for mod_a, mod_b in zip(mods[:-1], mods[1:]): addr_a = LDR_addr + THUNK_SIZE * mod_a.module_id addr_b = LDR_addr + THUNK_SIZE * mod_b.module_id link(addr_a + offset, addr_b + offset) addr_a = LDR_addr + THUNK_SIZE * mods[-1].module_id addr_b = LDR_addr + 12 link(addr_a + offset, addr_b + offset) else: link(LDR_addr + 12, LDR_addr + 12) _l.debug("Load order: %s", load_order) _l.debug("In-memory order: %s", mem_order) _l.debug("Initialization order: %s", init_order) link_list(load_order, 0) link_list(mem_order, 8) link_list(init_order, 16) return state def state_tracer(self, input_content=None, magic_content=None, preconstrain_input=True, preconstrain_flag=True, constrained_addrs=None, **kwargs): raise TracerEnvironmentError("Tracer currently only supports CGC and Unix.") def handle_exception(self, successors, engine, exc_type, exc_value, exc_traceback): # don't bother handling non-vex exceptions if engine is not self.project.factory.default_engine: raise exc_type, exc_value, exc_traceback # don't bother handling symbolic-address exceptions if exc_type is SimSegfaultException: if exc_value.original_addr is not None and exc_value.original_addr.symbolic: raise exc_type, exc_value, exc_traceback _l.debug("Handling exception from block at %#x: %r", successors.addr, exc_value) # If our state was just living out the rest of an unsatisfiable guard, discard it # it's possible this is incomplete because of implicit constraints added by memory or ccalls... if not successors.initial_state.satisfiable(extra_constraints=(exc_value.guard,)): _l.debug("... NOT handling unreachable exception") successors.processed = True return # we'll need to wind up to the exception to get the correct state to resume from... # exc will be a SimError, for sure # executed_instruction_count is incremented when we see an imark BUT it starts at -1, so this is the correct val num_inst = exc_value.executed_instruction_count if num_inst >= 1: # scary... try: r = self.project.factory.default_engine.process(successors.initial_state, num_inst=num_inst) if len(r.flat_successors) != 1: if exc_value.guard.is_true(): _l.error("Got %d successors while re-executing %d instructions at %#x " "for unconditional exception windup", num_inst, successors.initial_state.addr) raise exc_type, exc_value, exc_traceback # Try to figure out which successor is ours... _, _, canon_guard = exc_value.guard.canonicalize() for possible_succ in r.flat_successors: _, _, possible_guard = possible_succ.recent_events[-1].constraint.canonicalize() if canon_guard is possible_guard: exc_state = possible_succ break else: _l.error("None of the %d successors while re-executing %d instructions at %#x " "for conditional exception windup matched guard", num_inst, successors.initial_state.addr ) raise exc_type, exc_value, exc_traceback else: exc_state = r.flat_successors[0] except: # lol no _l.error("Got some weirdo error while re-executing %d instructions at %#x " "for exception windup", num_inst, successors.initial_state.addr) raise exc_type, exc_value, exc_traceback else: # duplicate the history-cycle code here... exc_state = successors.initial_state.copy() exc_state.register_plugin('history', successors.initial_state.history.make_child()) exc_state.history.recent_bbl_addrs.append(successors.initial_state.addr) _l.debug("... wound up state to %#x", exc_state.addr) # first check that we actually have an exception handler # we check is_true since if it's symbolic this is exploitable maybe? tib_addr = exc_state.regs._fs.concat(exc_state.solver.BVV(0, 16)) if exc_state.solver.is_true(exc_state.mem[tib_addr].long.resolved == -1): _l.debug("... no handlers register") exc_value.args = ('Unhandled exception: %r' % exc_value,) raise exc_type, exc_value, exc_traceback # catch nested exceptions here with magic value if exc_state.solver.is_true(exc_state.mem[tib_addr].long.resolved == 0xBADFACE): _l.debug("... nested exception") exc_value.args = ('Unhandled exception: %r' % exc_value,) raise exc_type, exc_value, exc_traceback # serialize the thread context and set up the exception record... self._dump_regs(exc_state, exc_state.regs._esp - 0x300) exc_state.regs.esp -= 0x400 record = exc_state.regs._esp + 0x20 context = exc_state.regs._esp + 0x100 # https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx exc_state.mem[record + 0x4].uint32_t = 0 # flags = continuable exc_state.mem[record + 0x8].uint32_t = 0 # FUCK chained exceptions exc_state.mem[record + 0xc].uint32_t = exc_state.regs._eip # exceptionaddress for i in xrange(16): # zero out the arg count and args array exc_state.mem[record + 0x10 + 4*i].uint32_t = 0 # TOTAL SIZE: 0x50 # the rest of the parameters have to be set per-exception type # https://msdn.microsoft.com/en-us/library/cc704588.aspx if exc_type is SimSegfaultException: exc_state.mem[record].uint32_t = 0xc0000005 # STATUS_ACCESS_VIOLATION exc_state.mem[record + 0x10].uint32_t = 2 exc_state.mem[record + 0x14].uint32_t = 1 if exc_value.reason.startswith('write-') else 0 exc_state.mem[record + 0x18].uint32_t = exc_value.addr elif exc_type is SimZeroDivisionException: exc_state.mem[record].uint32_t = 0xC0000094 # STATUS_INTEGER_DIVIDE_BY_ZERO exc_state.mem[record + 0x10].uint32_t = 0 # set up parameters to userland dispatcher exc_state.mem[exc_state.regs._esp].uint32_t = 0xBADC0DE # god help us if we return from this func exc_state.mem[exc_state.regs._esp + 4].uint32_t = record exc_state.mem[exc_state.regs._esp + 8].uint32_t = context # let's go let's go! # we want to use a true guard here. if it's not true, then it's already been added in windup. successors.add_successor(exc_state, self._exception_handler, exc_state.solver.true, 'Ijk_Exception') successors.processed = True # these two methods load and store register state from a struct CONTEXT # https://www.nirsoft.net/kernel_struct/vista/CONTEXT.html @staticmethod def _dump_regs(state, addr): if state.arch.name != 'X86': raise SimUnsupportedError("I don't know how to work with struct CONTEXT outside of i386") # I decline to load and store the floating point/extended registers state.mem[addr + 0].uint32_t = 0x07 # contextflags = control | integer | segments # dr0 - dr7 are at 0x4-0x18 # fp state is at 0x1c: 8 ulongs plus a char[80] gives it size 0x70 state.mem[addr + 0x8c].uint32_t = state.regs.gs.concat(state.solver.BVV(0, 16)) state.mem[addr + 0x90].uint32_t = state.regs.fs.concat(state.solver.BVV(0, 16)) state.mem[addr + 0x94].uint32_t = 0 # es state.mem[addr + 0x98].uint32_t = 0 # ds state.mem[addr + 0x9c].uint32_t = state.regs.edi state.mem[addr + 0xa0].uint32_t = state.regs.esi state.mem[addr + 0xa4].uint32_t = state.regs.ebx state.mem[addr + 0xa8].uint32_t = state.regs.edx state.mem[addr + 0xac].uint32_t = state.regs.ecx state.mem[addr + 0xb0].uint32_t = state.regs.eax state.mem[addr + 0xb4].uint32_t = state.regs.ebp state.mem[addr + 0xb8].uint32_t = state.regs.eip state.mem[addr + 0xbc].uint32_t = 0 # cs state.mem[addr + 0xc0].uint32_t = state.regs.eflags state.mem[addr + 0xc4].uint32_t = state.regs.esp state.mem[addr + 0xc8].uint32_t = 0 # ss # and then 512 bytes of extended registers # TOTAL SIZE: 0x2cc @staticmethod def _load_regs(state, addr): if state.arch.name != 'X86': raise SimUnsupportedError("I don't know how to work with struct CONTEXT outside of i386") # TODO: check contextflags to see what parts to deserialize state.regs.gs = state.mem[addr + 0x8c].uint32_t.resolved[31:16] state.regs.fs = state.mem[addr + 0x90].uint32_t.resolved[31:16] state.regs.edi = state.mem[addr + 0x9c].uint32_t.resolved state.regs.esi = state.mem[addr + 0xa0].uint32_t.resolved state.regs.ebx = state.mem[addr + 0xa4].uint32_t.resolved state.regs.edx = state.mem[addr + 0xa8].uint32_t.resolved state.regs.ecx = state.mem[addr + 0xac].uint32_t.resolved state.regs.eax = state.mem[addr + 0xb0].uint32_t.resolved state.regs.ebp = state.mem[addr + 0xb4].uint32_t.resolved state.regs.eip = state.mem[addr + 0xb8].uint32_t.resolved state.regs.eflags = state.mem[addr + 0xc0].uint32_t.resolved state.regs.esp = state.mem[addr + 0xc4].uint32_t.resolved<|fim▁end|>
if env is None: env = {} # Prepare argc if argc is None:
<|file_name|>logmon_hook_test.go<|end_file_name|><|fim▁begin|>package taskrunner import ( "context" "encoding/json" "io/ioutil" "net" "os" "testing" plugin "github.com/hashicorp/go-plugin" "github.com/hashicorp/nomad/client/allocrunner/interfaces" "github.com/hashicorp/nomad/helper" "github.com/hashicorp/nomad/helper/testlog" "github.com/hashicorp/nomad/nomad/mock" pstructs "github.com/hashicorp/nomad/plugins/shared/structs" "github.com/stretchr/testify/require" ) // Statically assert the logmon hook implements the expected interfaces var _ interfaces.TaskPrestartHook = (*logmonHook)(nil) var _ interfaces.TaskStopHook = (*logmonHook)(nil) // TestTaskRunner_LogmonHook_LoadReattach unit tests loading logmon reattach // config from persisted hook state. func TestTaskRunner_LogmonHook_LoadReattach(t *testing.T) { t.Parallel() // No hook data should return nothing cfg, err := reattachConfigFromHookData(nil) require.Nil(t, cfg) require.NoError(t, err) // Hook data without the appropriate key should return nothing cfg, err = reattachConfigFromHookData(map[string]string{"foo": "bar"}) require.Nil(t, cfg) require.NoError(t, err) // Create a realistic reattach config and roundtrip it addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") require.NoError(t, err) orig := &plugin.ReattachConfig{ Protocol: plugin.ProtocolGRPC, Addr: addr, Pid: 4, } origJSON, err := json.Marshal(pstructs.ReattachConfigFromGoPlugin(orig)) require.NoError(t, err) cfg, err = reattachConfigFromHookData(map[string]string{ logmonReattachKey: string(origJSON), }) require.NoError(t, err) require.Equal(t, orig, cfg) } // TestTaskRunner_LogmonHook_StartStop asserts that a new logmon is created the // first time Prestart is called, reattached to on subsequent restarts, and // killed on Stop. func TestTaskRunner_LogmonHook_StartStop(t *testing.T) { t.Parallel() alloc := mock.BatchAlloc() task := alloc.Job.TaskGroups[0].Tasks[0] dir, err := ioutil.TempDir("", "nomadtest") require.NoError(t, err) defer func() { require.NoError(t, os.RemoveAll(dir)) }() hookConf := newLogMonHookConfig(task.Name, dir) runner := &TaskRunner{logmonHookConfig: hookConf} hook := newLogMonHook(runner, testlog.HCLogger(t)) req := interfaces.TaskPrestartRequest{<|fim▁hole|> // First prestart should set reattach key but never be Done as it needs // to rerun on agent restarts to reattach. require.NoError(t, hook.Prestart(context.Background(), &req, &resp)) defer hook.Stop(context.Background(), nil, nil) require.False(t, resp.Done) origHookData := resp.State[logmonReattachKey] require.NotEmpty(t, origHookData) // Running prestart again should effectively noop as it reattaches to // the running logmon. req.PreviousState = map[string]string{ logmonReattachKey: origHookData, } require.NoError(t, hook.Prestart(context.Background(), &req, &resp)) require.False(t, resp.Done) origHookData = resp.State[logmonReattachKey] require.Equal(t, origHookData, req.PreviousState[logmonReattachKey]) // Running stop should shutdown logmon stopReq := interfaces.TaskStopRequest{ ExistingState: helper.CopyMapStringString(resp.State), } require.NoError(t, hook.Stop(context.Background(), &stopReq, nil)) }<|fim▁end|>
Task: task, } resp := interfaces.TaskPrestartResponse{}
<|file_name|>UpdateUnitsTest.java<|end_file_name|><|fim▁begin|>/* * Copyright (C) 2016 Mkhytar Mkhoian * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License.<|fim▁hole|> * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.justplay1.shoppist.interactor.units; import com.justplay1.shoppist.executor.PostExecutionThread; import com.justplay1.shoppist.executor.ThreadExecutor; import com.justplay1.shoppist.models.UnitModel; import com.justplay1.shoppist.repository.UnitsRepository; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Collections; import java.util.List; import static com.justplay1.shoppist.ModelUtil.createFakeUnitModel; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; public class UpdateUnitsTest { private UpdateUnits useCase; @Mock private ThreadExecutor mockThreadExecutor; @Mock private PostExecutionThread mockPostExecutionThread; @Mock private UnitsRepository mockUnitsRepository; private List<UnitModel> models; @Before public void setUp() { MockitoAnnotations.initMocks(this); useCase = new UpdateUnits(mockUnitsRepository, mockThreadExecutor, mockPostExecutionThread); models = Collections.singletonList(createFakeUnitModel()); useCase.init(models); } @Test public void updateUnitsUseCase_HappyCase() { useCase.buildUseCaseObservable().subscribe(); verify(mockUnitsRepository).update(models); verifyNoMoreInteractions(mockUnitsRepository); verifyZeroInteractions(mockThreadExecutor); verifyZeroInteractions(mockPostExecutionThread); } }<|fim▁end|>
<|file_name|>ws_client_test.go<|end_file_name|><|fim▁begin|>package rpcclient import ( "context" "encoding/json" "net" "net/http" "net/http/httptest" "sync" "testing" "time" "github.com/gorilla/websocket" "github.com/stretchr/testify/require" "github.com/tendermint/tmlibs/log" types "github.com/tendermint/tendermint/rpc/lib/types" ) type myHandler struct { closeConnAfterRead bool mtx sync.RWMutex } var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func (h *myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { panic(err) } defer conn.Close() for { messageType, _, err := conn.ReadMessage() if err != nil { return } h.mtx.RLock() if h.closeConnAfterRead { conn.Close() } h.mtx.RUnlock() res := json.RawMessage(`{}`) emptyRespBytes, _ := json.Marshal(types.RPCResponse{Result: &res}) if err := conn.WriteMessage(messageType, emptyRespBytes); err != nil { return } } } func TestWSClientReconnectsAfterReadFailure(t *testing.T) { var wg sync.WaitGroup // start server h := &myHandler{} s := httptest.NewServer(h) defer s.Close() c := startClient(t, s.Listener.Addr()) defer c.Stop()<|fim▁hole|> wg.Add(1) go callWgDoneOnResult(t, c, &wg) h.mtx.Lock() h.closeConnAfterRead = true h.mtx.Unlock() // results in WS read error, no send retry because write succeeded call(t, "a", c) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) h.mtx.Lock() h.closeConnAfterRead = false h.mtx.Unlock() // should succeed call(t, "b", c) wg.Wait() } func TestWSClientReconnectsAfterWriteFailure(t *testing.T) { var wg sync.WaitGroup // start server h := &myHandler{} s := httptest.NewServer(h) c := startClient(t, s.Listener.Addr()) defer c.Stop() wg.Add(2) go callWgDoneOnResult(t, c, &wg) // hacky way to abort the connection before write c.conn.Close() // results in WS write error, the client should resend on reconnect call(t, "a", c) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) // should succeed call(t, "b", c) wg.Wait() } func TestWSClientReconnectFailure(t *testing.T) { // start server h := &myHandler{} s := httptest.NewServer(h) c := startClient(t, s.Listener.Addr()) defer c.Stop() go func() { for { select { case <-c.ResponsesCh: case <-c.Quit: return } } }() // hacky way to abort the connection before write c.conn.Close() s.Close() // results in WS write error // provide timeout to avoid blocking ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() c.Call(ctx, "a", make(map[string]interface{})) // expect to reconnect almost immediately time.Sleep(10 * time.Millisecond) done := make(chan struct{}) go func() { // client should block on this call(t, "b", c) close(done) }() // test that client blocks on the second send select { case <-done: t.Fatal("client should block on calling 'b' during reconnect") case <-time.After(5 * time.Second): t.Log("All good") } } func TestNotBlockingOnStop(t *testing.T) { timeout := 2 * time.Second s := httptest.NewServer(&myHandler{}) c := startClient(t, s.Listener.Addr()) c.Call(context.Background(), "a", make(map[string]interface{})) // Let the readRoutine get around to blocking time.Sleep(time.Second) passCh := make(chan struct{}) go func() { // Unless we have a non-blocking write to ResponsesCh from readRoutine // this blocks forever ont the waitgroup c.Stop() passCh <- struct{}{} }() select { case <-passCh: // Pass case <-time.After(timeout): t.Fatalf("WSClient did failed to stop within %v seconds - is one of the read/write routines blocking?", timeout.Seconds()) } } func startClient(t *testing.T, addr net.Addr) *WSClient { c := NewWSClient(addr.String(), "/websocket") _, err := c.Start() require.Nil(t, err) c.SetLogger(log.TestingLogger()) return c } func call(t *testing.T, method string, c *WSClient) { err := c.Call(context.Background(), method, make(map[string]interface{})) require.NoError(t, err) } func callWgDoneOnResult(t *testing.T, c *WSClient, wg *sync.WaitGroup) { for { select { case resp := <-c.ResponsesCh: if resp.Error != nil { t.Fatalf("unexpected error: %v", resp.Error) } if *resp.Result != nil { wg.Done() } case <-c.Quit: return } } }<|fim▁end|>
<|file_name|>gump_scene.rs<|end_file_name|><|fim▁begin|>use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Canvas, DrawParam, Text}; use ggez::{Context, GameResult}; use image_convert::image_to_surface; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; use std::fs::File; use std::io::Result; use std::path::Path; use uorustlibs::gump::GumpReader; pub struct GumpScene { reader: Result<GumpReader<File>>, index: u32, texture: Option<Canvas>, exiting: bool, } impl<'a> GumpScene { pub fn new(ctx: &mut Context) -> BoxedScene<'a, SceneName, ()> { let reader = GumpReader::new( &Path::new("./assets/gumpidx.mul"), &Path::new("./assets/gumpart.mul"), ); let mut scene = Box::new(GumpScene { reader: reader, index: 0, texture: None, exiting: false, }); scene.create_slice(ctx).expect("Failed to create slice"); scene } fn cycle_backward(&mut self) { match self.reader { Ok(ref mut reader) => { while self.index > 0 { self.index -= 1; match reader.read_gump(self.index) { Ok(_) => { break; } _ => {} } } } _ => {} } } fn cycle_forward(&mut self) { match self.reader { Ok(ref mut reader) => loop { self.index += 1; match reader.read_gump(self.index) { Ok(_) => { break; } _ => {} } }, _ => {} } } fn create_slice(&mut self, ctx: &mut Context) -> GameResult<()> { let dest = Canvas::with_window_size(ctx)?; graphics::set_canvas(ctx, Some(&dest)); graphics::clear(ctx, graphics::BLACK); match self.reader { Ok(ref mut reader) => match reader.read_gump(self.index) { Ok(gump) => { let image = gump.to_image(); let surface = image_to_surface(ctx, &image); graphics::draw(ctx, &surface, DrawParam::default())?; let label = Text::new(format!("{}", self.index)); graphics::draw( ctx, &label, ( Point2::new(9.0, surface.height() as f32 + 16.0), graphics::WHITE, ), )?; } _ => { let label = Text::new(format!("Invalid gump {}", self.index)); graphics::draw(ctx, &label, (Point2::new(9.0, 16.0), graphics::WHITE))?; } }, _ => { let text = Text::new("Could not create slice"); graphics::draw(ctx, &text, (Point2::new(0.0, 0.0), graphics::WHITE))?; } } graphics::set_canvas(ctx, None); self.texture = Some(dest); Ok(()) } } impl Scene<SceneName, ()> for GumpScene { fn draw(&mut self, ctx: &mut Context, _engine_data: &mut ()) -> GameResult<()> { match self.texture { Some(ref texture) => { graphics::draw(ctx, texture, DrawParam::default())?; } None => (), }; Ok(()) } fn update( &mut self, _ctx: &mut Context,<|fim▁hole|> Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } fn key_down_event( &mut self, ctx: &mut Context, keycode: KeyCode, _keymods: KeyMods, _repeat: bool, _engine_data: &mut (), ) { match keycode { KeyCode::Escape => self.exiting = true, KeyCode::Left => { self.cycle_backward(); self.create_slice(ctx).expect("Failed to create slice"); } KeyCode::Right => { self.cycle_forward(); self.create_slice(ctx).expect("Failed to create slice"); } _ => (), } } }<|fim▁end|>
_engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>> { if self.exiting {
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. <|fim▁hole|> urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), ]<|fim▁end|>
from django.conf.urls import url from dispatch.topology import views
<|file_name|>gschemas.py<|end_file_name|><|fim▁begin|>import glob import os from distutils.dep_util import newer from distutils.core import Command from distutils.spawn import find_executable from distutils.util import change_root class build_gschemas(Command): """build message catalog files Build message catalog (.mo) files from .po files using xgettext and intltool. These are placed directly in the build tree. """ description = "build gschemas used for dconf" user_options = [] build_base = None def initialize_options(self): pass def finalize_options(self): self.gschemas_directory = self.distribution.gschemas self.set_undefined_options('build', ('build_base', 'build_base')) def run(self): if find_executable("glib-compile-schemas") is None: raise SystemExit("Error: 'glib-compile-schemas' not found.") basepath = os.path.join(self.build_base, 'share', 'glib-2.0', 'schemas') self.copy_tree(self.gschemas_directory, basepath) class install_gschemas(Command): """install message catalog files Copy compiled message catalog files into their installation directory, $prefix/share/locale/$lang/LC_MESSAGES/$package.mo. """ description = "install message catalog files" user_options = [] skip_build = None build_base = None install_base = None root = None def initialize_options(self): pass def finalize_options(self): self.set_undefined_options('build', ('build_base', 'build_base')) self.set_undefined_options( 'install', ('root', 'root'), ('install_base', 'install_base'), ('skip_build', 'skip_build')) def run(self): if not self.skip_build: self.run_command('build_gschemas')<|fim▁hole|> dest = change_root(self.root, dest) self.copy_tree(src, dest) self.spawn(['glib-compile-schemas', dest]) __all__ = ["build_gschemas", "install_gschemas"]<|fim▁end|>
src = os.path.join(self.build_base, 'share', 'glib-2.0', 'schemas') dest = os.path.join(self.install_base, 'share', 'glib-2.0', 'schemas') if self.root != None:
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian<|fim▁hole|><|fim▁end|>
// Licensed under the MIT License <LICENSE.md> fn main() { println!("cargo:rustc-flags=-l scecli"); }
<|file_name|>pyDome.py<|end_file_name|><|fim▁begin|># pyDome: A geodesic dome calculator # Copyright (C) 2013 Daniel Williams # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # load useful modules # import numpy as np import getopt import sys # # load pyDome modules # from Polyhedral import * from SymmetryTriangle import * from GeodesicSphere import * from Output import * from Truncation import * from BillOfMaterials import * def display_help(): print print 'pyDome: A geodesic dome calculator. Copyright 2013 by Daniel Williams' print print 'Required Command-Line Input:' print print '\t-o, --output=\tPath to output file(s). Extensions will be added. Generates DXF and WRL files by default, but only WRL file when "-F" option is active. Example: \"-o output/test\" produces files output/test.wrl and output/test.dxf.' print print 'Options:' print print '\t-r, --radius\tRadius of generated dome. Must be floating point. Default 1.0.' print print '\t-f, --frequency\tFrequency of generated dome. Must be an integer. Default 4.' print print '\t-v, --vthreshold\tDistance required to consider two vertices equal. Default 0.0000001. Must be floating point.' print print '\t-t, --truncation\tDistance (ratio) from the bottom to truncate. Default 0.499999. I advise using only the default or 0.333333. Must be floating point.' print print '\t-b, --bom-rounding\tThe number of decimal places to round chord length output in the generated Bill of Materials. Default 5. Must be an integer.' print print '\t-p, --polyhedron\tEither \"octahedron\" or \"icosahedron\". Default icosahedron.' print print '\t-F, --face\tFlag specifying whether to generate face output in WRL file. Cancels DXF file output and cannot be used with truncation.' print def main(): # # default values # radius = np.float64(1.) frequency = 4 polyhedral = Icosahedron() vertex_equal_threshold = 0.0000001 truncation_amount = 0.499999 run_truncate = False bom_rounding_precision = 5 face_output = False output_path = None # # no input arguments # if len(sys.argv[1:]) == 0: display_help() sys.exit(-1) # # parse command line # try: opts, args = getopt.getopt(sys.argv[1:], 'r:f:v:t:b:p:Fo:', ['truncation=', 'vthreshold=', 'radius=', 'frequency=', 'help', 'bom-rounding=', 'polyhedron=', 'face', 'output=']) except getopt.error, msg: print "for help use --help"<|fim▁hole|> for o, a in opts: if o in ('-o', '--output'): output_path = a if o in ('-p', '--polyhedron'): if a == 'octahedron': polyhedral = Octahedron() if o in ('-b', '--bom-rounding'): try: bom_rounding_precision = int(a) except: print '-b or --bom-rounding argument must be an integer. Exiting.' sys.exit(-1) if o in ('-h', '--help'): display_help() sys.exit(0) if o in ('-F', '--face'): face_output = True if o in ('-r', '--radius'): try: a = float(a) radius = np.float64(a) except: print '-r or --radius argument must be a floating point number. Exiting.' sys.exit(-1) if o in ('-f', '--frequency'): try: frequency = int(a) except: print '-f or --frequency argument must be an integer. Exiting.' sys.exit(-1) if o in ('-v', '--vthreshold'): try: a = float(a) vertex_equal_threshold = np.float64(a) except: print '-v or --vthreshold argument must be a floating point number. Exiting.' sys.exit(-1) if o in ('-t', '--truncation'): try: a = float(a) truncation_amount = np.float64(a) run_truncate = True except: print '-t or --truncation argument must be a floating point number. Exiting.' sys.exit(-1) # # check for required options # if output_path == None: print 'An output path and filename is required. Use the -o argument. Exiting.' sys.exit(-1) # # check for mutually exclusive options # if face_output and run_truncate: print 'Truncation does not work with face output at this time. Use either -t or -F but not both.' exit(-1) # # generate geodesic sphere # symmetry_triangle = ClassOneMethodOneSymmetryTriangle(frequency, polyhedral) sphere = GeodesicSphere(polyhedral, symmetry_triangle, vertex_equal_threshold, radius) C_sphere = sphere.non_duplicate_chords F_sphere = sphere.non_duplicate_face_nodes V_sphere = sphere.sphere_vertices # # truncate # V = V_sphere C = C_sphere if run_truncate: V, C = truncate(V_sphere, C_sphere, truncation_amount) # # write model output # if face_output: OutputFaceVRML(V, F_sphere, output_path + '.wrl') else: OutputWireframeVRML(V, C, output_path + '.wrl') OutputDXF(V, C, output_path + '.dxf') # # bill of materials # get_bill_of_materials(V, C, bom_rounding_precision) # # run the main function # if __name__ == "__main__": main()<|fim▁end|>
sys.exit(-1)
<|file_name|>tables.py<|end_file_name|><|fim▁begin|>from horizon import tables from django.utils.translation import ugettext_lazy as _ import utils import whisper import time def get_vcpu_load_avgs(instance): cpu_files = utils.get_whisper_files_by_metric(<|fim▁hole|> utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_files: return "N/A" # TODO: what if we have more than one CPU database?? f = cpu_files[0] avgs = [] for duration in [1, 5, 15]: fetched = whisper.fetch(f, time.time() - 60*duration) times, data = fetched load_avg = utils.average(data) avgs.append(load_avg) return "%f | %f | %f" % tuple(avgs) def get_cpu_utilization_snapshot(instance, back=60): cpu_files = utils.get_whisper_files_by_metric( "cpu", utils.get_whisper_files_by_instance_id(instance.id)) if not cpu_files: return "N/A" # TODO: what if we have more than one CPU database?? fetched = whisper.fetch(cpu_files[0], time.time() - back) times, data = fetched # return the most recent data point that's not None for val in reversed(data): if val is not None: return val * 100 return "N/A" def get_mem_utilization_snapshot(instance, back=60): mem_files = utils.get_whisper_files_by_metric( "mem", utils.get_whisper_files_by_instance_id(instance.id)) if not mem_files: return "N/A" fetched = whisper.fetch(mem_files[0], time.time() - back) times, data = fetched for val in reversed(data): if val is not None: return val * 100 return "N/A" class MonitorTable(tables.DataTable): name = tables.Column("name", #link=("horizon:project:instances:detail"), link=("horizon:nova:instances_and_volumes:instances:detail"), verbose_name=_("Instance Name")) host = tables.Column("OS-EXT-SRV-ATTR:host", verbose_name=_("Host")) cpu = tables.Column(get_cpu_utilization_snapshot, verbose_name=_("CPU%")) mem = tables.Column(get_mem_utilization_snapshot, verbose_name=_("Mem%")) vcpu_load = tables.Column(get_vcpu_load_avgs, verbose_name=_("vCPU Load Avg (1, 5, 15 min)")) class Meta: name = 'instances' verbose_name = _("Instances")<|fim▁end|>
"cpu",
<|file_name|>mime_util_xdg.cc<|end_file_name|><|fim▁begin|>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/nix/mime_util_xdg.h" #include <cstdlib> #include <list> #include <map> #include <vector> #include "base/environment.h" #include "base/file_util.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/nix/xdg_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/synchronization/lock.h" #include "base/third_party/xdg_mime/xdgmime.h" #include "base/threading/thread_restrictions.h" #include "base/time/time.h" namespace base { namespace nix { namespace { class IconTheme; // None of the XDG stuff is thread-safe, so serialize all access under // this lock. LazyInstance<Lock>::Leaky g_mime_util_xdg_lock = LAZY_INSTANCE_INITIALIZER; class MimeUtilConstants { public: typedef std::map<std::string, IconTheme*> IconThemeMap; typedef std::map<FilePath, Time> IconDirMtimeMap; typedef std::vector<std::string> IconFormats; // Specified by XDG icon theme specs. static const int kUpdateIntervalInSeconds = 5; static const size_t kDefaultThemeNum = 4; static MimeUtilConstants* GetInstance() { return Singleton<MimeUtilConstants>::get(); } // Store icon directories and their mtimes. IconDirMtimeMap icon_dirs_; // Store icon formats. IconFormats icon_formats_; // Store loaded icon_theme. IconThemeMap icon_themes_; // The default theme. IconTheme* default_themes_[kDefaultThemeNum]; TimeTicks last_check_time_; // The current icon theme, usually set through GTK theme integration. std::string icon_theme_name_; private: MimeUtilConstants() { icon_formats_.push_back(".png"); icon_formats_.push_back(".svg"); icon_formats_.push_back(".xpm"); for (size_t i = 0; i < kDefaultThemeNum; ++i) default_themes_[i] = NULL; } ~MimeUtilConstants(); friend struct DefaultSingletonTraits<MimeUtilConstants>; DISALLOW_COPY_AND_ASSIGN(MimeUtilConstants); }; // IconTheme represents an icon theme as defined by the xdg icon theme spec. // Example themes on GNOME include 'Human' and 'Mist'. // Example themes on KDE include 'crystalsvg' and 'kdeclassic'. class IconTheme { public: // A theme consists of multiple sub-directories, like '32x32' and 'scalable'. class SubDirInfo {<|fim▁hole|> // See spec for details. enum Type { Fixed, Scalable, Threshold }; SubDirInfo() : size(0), type(Threshold), max_size(0), min_size(0), threshold(2) { } size_t size; // Nominal size of the icons in this directory. Type type; // Type of the icon size. size_t max_size; // Maximum size that the icons can be scaled to. size_t min_size; // Minimum size that the icons can be scaled to. size_t threshold; // Maximum difference from desired size. 2 by default. }; explicit IconTheme(const std::string& name); ~IconTheme() {} // Returns the path to an icon with the name |icon_name| and a size of |size| // pixels. If the icon does not exist, but |inherits| is true, then look for // the icon in the parent theme. FilePath GetIconPath(const std::string& icon_name, int size, bool inherits); // Load a theme with the name |theme_name| into memory. Returns null if theme // is invalid. static IconTheme* LoadTheme(const std::string& theme_name); private: // Returns the path to an icon with the name |icon_name| in |subdir|. FilePath GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir); // Whether the theme loaded properly. bool IsValid() { return index_theme_loaded_; } // Read and parse |file| which is usually named 'index.theme' per theme spec. bool LoadIndexTheme(const FilePath& file); // Checks to see if the icons in |info| matches |size| (in pixels). Returns // 0 if they match, or the size difference in pixels. size_t MatchesSize(SubDirInfo* info, size_t size); // Yet another function to read a line. std::string ReadLine(FILE* fp); // Set directories to search for icons to the comma-separated list |dirs|. bool SetDirectories(const std::string& dirs); bool index_theme_loaded_; // True if an instance is properly loaded. // store the scattered directories of this theme. std::list<FilePath> dirs_; // store the subdirs of this theme and array index of |info_array_|. std::map<std::string, int> subdirs_; scoped_ptr<SubDirInfo[]> info_array_; // List of sub-directories. std::string inherits_; // Name of the theme this one inherits from. }; IconTheme::IconTheme(const std::string& name) : index_theme_loaded_(false) { ThreadRestrictions::AssertIOAllowed(); // Iterate on all icon directories to find directories of the specified // theme and load the first encountered index.theme. MimeUtilConstants::IconDirMtimeMap::iterator iter; FilePath theme_path; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &MimeUtilConstants::GetInstance()->icon_dirs_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { theme_path = iter->first.Append(name); if (!DirectoryExists(theme_path)) continue; FilePath theme_index = theme_path.Append("index.theme"); if (!index_theme_loaded_ && PathExists(theme_index)) { if (!LoadIndexTheme(theme_index)) return; index_theme_loaded_ = true; } dirs_.push_back(theme_path); } } FilePath IconTheme::GetIconPath(const std::string& icon_name, int size, bool inherits) { std::map<std::string, int>::iterator subdir_iter; FilePath icon_path; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; if (MatchesSize(info, size) == 0) { icon_path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!icon_path.empty()) return icon_path; } } // Now looking for the mostly matched. size_t min_delta_seen = 9999; for (subdir_iter = subdirs_.begin(); subdir_iter != subdirs_.end(); ++subdir_iter) { SubDirInfo* info = &info_array_[subdir_iter->second]; size_t delta = MatchesSize(info, size); if (delta < min_delta_seen) { FilePath path = GetIconPathUnderSubdir(icon_name, subdir_iter->first); if (!path.empty()) { min_delta_seen = delta; icon_path = path; } } } if (!icon_path.empty() || !inherits || inherits_ == "") return icon_path; IconTheme* theme = LoadTheme(inherits_); // Inheriting from itself means the theme is buggy but we shouldn't crash. if (theme && theme != this) return theme->GetIconPath(icon_name, size, inherits); else return FilePath(); } IconTheme* IconTheme::LoadTheme(const std::string& theme_name) { scoped_ptr<IconTheme> theme; MimeUtilConstants::IconThemeMap* icon_themes = &MimeUtilConstants::GetInstance()->icon_themes_; if (icon_themes->find(theme_name) != icon_themes->end()) { theme.reset((*icon_themes)[theme_name]); } else { theme.reset(new IconTheme(theme_name)); if (!theme->IsValid()) theme.reset(); (*icon_themes)[theme_name] = theme.get(); } return theme.release(); } FilePath IconTheme::GetIconPathUnderSubdir(const std::string& icon_name, const std::string& subdir) { FilePath icon_path; std::list<FilePath>::iterator dir_iter; MimeUtilConstants::IconFormats* icon_formats = &MimeUtilConstants::GetInstance()->icon_formats_; for (dir_iter = dirs_.begin(); dir_iter != dirs_.end(); ++dir_iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { icon_path = dir_iter->Append(subdir); icon_path = icon_path.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon_path)) return icon_path; } } return FilePath(); } bool IconTheme::LoadIndexTheme(const FilePath& file) { FILE* fp = base::OpenFile(file, "r"); SubDirInfo* current_info = NULL; if (!fp) return false; // Read entries. while (!feof(fp) && !ferror(fp)) { std::string buf = ReadLine(fp); if (buf == "") break; std::string entry; TrimWhitespaceASCII(buf, TRIM_ALL, &entry); if (entry.length() == 0 || entry[0] == '#') { // Blank line or Comment. continue; } else if (entry[0] == '[' && info_array_.get()) { current_info = NULL; std::string subdir = entry.substr(1, entry.length() - 2); if (subdirs_.find(subdir) != subdirs_.end()) current_info = &info_array_[subdirs_[subdir]]; } std::string key, value; std::vector<std::string> r; SplitStringDontTrim(entry, '=', &r); if (r.size() < 2) continue; TrimWhitespaceASCII(r[0], TRIM_ALL, &key); for (size_t i = 1; i < r.size(); i++) value.append(r[i]); TrimWhitespaceASCII(value, TRIM_ALL, &value); if (current_info) { if (key == "Size") { current_info->size = atoi(value.c_str()); } else if (key == "Type") { if (value == "Fixed") current_info->type = SubDirInfo::Fixed; else if (value == "Scalable") current_info->type = SubDirInfo::Scalable; else if (value == "Threshold") current_info->type = SubDirInfo::Threshold; } else if (key == "MaxSize") { current_info->max_size = atoi(value.c_str()); } else if (key == "MinSize") { current_info->min_size = atoi(value.c_str()); } else if (key == "Threshold") { current_info->threshold = atoi(value.c_str()); } } else { if (key.compare("Directories") == 0 && !info_array_.get()) { if (!SetDirectories(value)) break; } else if (key.compare("Inherits") == 0) { if (value != "hicolor") inherits_ = value; } } } base::CloseFile(fp); return info_array_.get() != NULL; } size_t IconTheme::MatchesSize(SubDirInfo* info, size_t size) { if (info->type == SubDirInfo::Fixed) { if (size > info->size) return size - info->size; else return info->size - size; } else if (info->type == SubDirInfo::Scalable) { if (size < info->min_size) return info->min_size - size; if (size > info->max_size) return size - info->max_size; return 0; } else { if (size + info->threshold < info->size) return info->size - size - info->threshold; if (size > info->size + info->threshold) return size - info->size - info->threshold; return 0; } } std::string IconTheme::ReadLine(FILE* fp) { if (!fp) return std::string(); std::string result; const size_t kBufferSize = 100; char buffer[kBufferSize]; while ((fgets(buffer, kBufferSize - 1, fp)) != NULL) { result += buffer; size_t len = result.length(); if (len == 0) break; char end = result[len - 1]; if (end == '\n' || end == '\0') break; } return result; } bool IconTheme::SetDirectories(const std::string& dirs) { int num = 0; std::string::size_type pos = 0, epos; std::string dir; while ((epos = dirs.find(',', pos)) != std::string::npos) { TrimWhitespaceASCII(dirs.substr(pos, epos - pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; pos = epos + 1; } TrimWhitespaceASCII(dirs.substr(pos), TRIM_ALL, &dir); if (dir.length() == 0) { DLOG(WARNING) << "Invalid index.theme: blank subdir"; return false; } subdirs_[dir] = num++; info_array_.reset(new SubDirInfo[num]); return true; } bool CheckDirExistsAndGetMtime(const FilePath& dir, Time* last_modified) { if (!DirectoryExists(dir)) return false; File::Info file_info; if (!GetFileInfo(dir, &file_info)) return false; *last_modified = file_info.last_modified; return true; } // Make sure |dir| exists and add it to the list of icon directories. void TryAddIconDir(const FilePath& dir) { Time last_modified; if (!CheckDirExistsAndGetMtime(dir, &last_modified)) return; MimeUtilConstants::GetInstance()->icon_dirs_[dir] = last_modified; } // For a xdg directory |dir|, add the appropriate icon sub-directories. void AddXDGDataDir(const FilePath& dir) { if (!DirectoryExists(dir)) return; TryAddIconDir(dir.Append("icons")); TryAddIconDir(dir.Append("pixmaps")); } // Add all the xdg icon directories. void InitIconDir() { FilePath home = GetHomeDir(); if (!home.empty()) { FilePath legacy_data_dir(home); legacy_data_dir = legacy_data_dir.AppendASCII(".icons"); if (DirectoryExists(legacy_data_dir)) TryAddIconDir(legacy_data_dir); } const char* env = getenv("XDG_DATA_HOME"); if (env) { AddXDGDataDir(FilePath(env)); } else if (!home.empty()) { FilePath local_data_dir(home); local_data_dir = local_data_dir.AppendASCII(".local"); local_data_dir = local_data_dir.AppendASCII("share"); AddXDGDataDir(local_data_dir); } env = getenv("XDG_DATA_DIRS"); if (!env) { AddXDGDataDir(FilePath("/usr/local/share")); AddXDGDataDir(FilePath("/usr/share")); } else { std::string xdg_data_dirs = env; std::string::size_type pos = 0, epos; while ((epos = xdg_data_dirs.find(':', pos)) != std::string::npos) { AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos, epos - pos))); pos = epos + 1; } AddXDGDataDir(FilePath(xdg_data_dirs.substr(pos))); } } void EnsureUpdated() { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); if (constants->last_check_time_.is_null()) { constants->last_check_time_ = TimeTicks::Now(); InitIconDir(); return; } // Per xdg theme spec, we should check the icon directories every so often // for newly added icons. TimeDelta time_since_last_check = TimeTicks::Now() - constants->last_check_time_; if (time_since_last_check.InSeconds() > constants->kUpdateIntervalInSeconds) { constants->last_check_time_ += time_since_last_check; bool rescan_icon_dirs = false; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconDirMtimeMap::iterator iter; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { Time last_modified; if (!CheckDirExistsAndGetMtime(iter->first, &last_modified) || last_modified != iter->second) { rescan_icon_dirs = true; break; } } if (rescan_icon_dirs) { constants->icon_dirs_.clear(); constants->icon_themes_.clear(); InitIconDir(); } } } // Find a fallback icon if we cannot find it in the default theme. FilePath LookupFallbackIcon(const std::string& icon_name) { MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconDirMtimeMap::iterator iter; MimeUtilConstants::IconDirMtimeMap* icon_dirs = &constants->icon_dirs_; MimeUtilConstants::IconFormats* icon_formats = &constants->icon_formats_; for (iter = icon_dirs->begin(); iter != icon_dirs->end(); ++iter) { for (size_t i = 0; i < icon_formats->size(); ++i) { FilePath icon = iter->first.Append(icon_name + (*icon_formats)[i]); if (PathExists(icon)) return icon; } } return FilePath(); } // Initialize the list of default themes. void InitDefaultThemes() { IconTheme** default_themes = MimeUtilConstants::GetInstance()->default_themes_; scoped_ptr<Environment> env(Environment::Create()); base::nix::DesktopEnvironment desktop_env = base::nix::GetDesktopEnvironment(env.get()); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4) { // KDE std::string kde_default_theme; std::string kde_fallback_theme; // TODO(thestig): Figure out how to get the current icon theme on KDE. // Setting stored in ~/.kde/share/config/kdeglobals under Icons -> Theme. default_themes[0] = NULL; // Try some reasonable defaults for KDE. if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { // KDE 3 kde_default_theme = "default.kde"; kde_fallback_theme = "crystalsvg"; } else { // KDE 4 kde_default_theme = "default.kde4"; kde_fallback_theme = "oxygen"; } default_themes[1] = IconTheme::LoadTheme(kde_default_theme); default_themes[2] = IconTheme::LoadTheme(kde_fallback_theme); } else { // Assume it's Gnome and use GTK to figure out the theme. default_themes[1] = IconTheme::LoadTheme( MimeUtilConstants::GetInstance()->icon_theme_name_); default_themes[2] = IconTheme::LoadTheme("gnome"); } // hicolor needs to be last per icon theme spec. default_themes[3] = IconTheme::LoadTheme("hicolor"); for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i] == NULL) continue; // NULL out duplicate pointers. for (size_t j = i + 1; j < MimeUtilConstants::kDefaultThemeNum; j++) { if (default_themes[j] == default_themes[i]) default_themes[j] = NULL; } } } // Try to find an icon with the name |icon_name| that's |size| pixels. FilePath LookupIconInDefaultTheme(const std::string& icon_name, int size) { EnsureUpdated(); MimeUtilConstants* constants = MimeUtilConstants::GetInstance(); MimeUtilConstants::IconThemeMap* icon_themes = &constants->icon_themes_; if (icon_themes->empty()) InitDefaultThemes(); FilePath icon_path; IconTheme** default_themes = constants->default_themes_; for (size_t i = 0; i < MimeUtilConstants::kDefaultThemeNum; i++) { if (default_themes[i]) { icon_path = default_themes[i]->GetIconPath(icon_name, size, true); if (!icon_path.empty()) return icon_path; } } return LookupFallbackIcon(icon_name); } MimeUtilConstants::~MimeUtilConstants() { for (size_t i = 0; i < kDefaultThemeNum; i++) delete default_themes_[i]; } } // namespace std::string GetFileMimeType(const FilePath& filepath) { if (filepath.empty()) return std::string(); ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_from_file_name(filepath.value().c_str()); } std::string GetDataMimeType(const std::string& data) { ThreadRestrictions::AssertIOAllowed(); AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); return xdg_mime_get_mime_type_for_data(data.data(), data.length(), NULL); } void SetIconThemeName(const std::string& name) { // If the theme name is already loaded, do nothing. Chrome doesn't respond // to changes in the system theme, so we never need to set this more than // once. if (!MimeUtilConstants::GetInstance()->icon_theme_name_.empty()) return; MimeUtilConstants::GetInstance()->icon_theme_name_ = name; } FilePath GetMimeIcon(const std::string& mime_type, size_t size) { ThreadRestrictions::AssertIOAllowed(); std::vector<std::string> icon_names; std::string icon_name; FilePath icon_file; if (!mime_type.empty()) { AutoLock scoped_lock(g_mime_util_xdg_lock.Get()); const char *icon = xdg_mime_get_icon(mime_type.c_str()); icon_name = std::string(icon ? icon : ""); } if (icon_name.length()) icon_names.push_back(icon_name); // For text/plain, try text-plain. icon_name = mime_type; for (size_t i = icon_name.find('/', 0); i != std::string::npos; i = icon_name.find('/', i + 1)) { icon_name[i] = '-'; } icon_names.push_back(icon_name); // Also try gnome-mime-text-plain. icon_names.push_back("gnome-mime-" + icon_name); // Try "deb" for "application/x-deb" in KDE 3. size_t x_substr_pos = mime_type.find("/x-"); if (x_substr_pos != std::string::npos) { icon_name = mime_type.substr(x_substr_pos + 3); icon_names.push_back(icon_name); } // Try generic name like text-x-generic. icon_name = mime_type.substr(0, mime_type.find('/')) + "-x-generic"; icon_names.push_back(icon_name); // Last resort icon_names.push_back("unknown"); for (size_t i = 0; i < icon_names.size(); i++) { if (icon_names[i][0] == '/') { icon_file = FilePath(icon_names[i]); if (PathExists(icon_file)) return icon_file; } else { icon_file = LookupIconInDefaultTheme(icon_names[i], size); if (!icon_file.empty()) return icon_file; } } return FilePath(); } } // namespace nix } // namespace base<|fim▁end|>
public:
<|file_name|>controller.py<|end_file_name|><|fim▁begin|># Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015 Rickard Lindberg, Roger Lindberg # # This file is part of Timeline. # # Timeline is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Timeline is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Timeline. If not, see <http://www.gnu.org/licenses/>. from timelinelib.wxgui.framework import Controller class SetCategoryDialogController(Controller): def on_init(self, db, selected_event_ids): self._db = db self._selected_event_ids = selected_event_ids self.view.PopulateCategories() self._set_title() def on_ok_clicked(self, event): category = self.view.GetSelectedCategory() if not self._category_is_given(category) and self._selected_event_ids == []: self.view.DisplayErrorMessage(_("You must select a category!")) else: self._save_category_in_events(category) self.view.EndModalOk() def _set_title(self): if self._selected_event_ids == []: self.view.SetTitle(_("Set Category on events without category")) else: self.view.SetTitle(_("Set Category on selected events")) def _category_is_given(self, category): return category is not None def _save_category_in_events(self, category): if self._selected_event_ids == []: self._save_category_in_events_for_events_without_category(category) else: self._save_category_in_events_for_selected_events(category) def _save_category_in_events_for_selected_events(self, category): for event_id in self._selected_event_ids: event = self._db.find_event_with_id(event_id) event.set_category(category) def _save_category_in_events_for_events_without_category(self, category): for event in self._db.get_all_events(): if event.get_category() is None: event.set_category(category) def _events_without_category_exists(self):<|fim▁hole|> for event in self._db.get_all_events(): if event.category is None: return True return False<|fim▁end|>
<|file_name|>0007_auto_20160811_1915.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-11 11:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('article', '0006_article_owner'), ] operations = [ migrations.RenameField( model_name='article', old_name='owner', new_name='owne', ),<|fim▁hole|><|fim▁end|>
]
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>//! An in-memory event store, useful for testing //! //! # Example //! //! ```rust //! extern crate chronicle; //! extern crate chronicle_memory; //! extern crate futures; //! #[macro_use] //! extern crate lazy_static; //! extern crate uuid; //! //! //! use chronicle_memory::MemoryEventStore; //! //! //! lazy_static! { //! /// A globally accessible event store //! static ref EVENT_STORE: MemoryEventStore<&'static str> = { //! MemoryEventStore::new() //! }; //! } //! //! fn main() { //! use chronicle::EventStore; //! use futures::{Future, Stream, future}; //! use std::thread; //! use uuid::Uuid; //! //! //! // Some unique source ids //! let id_1 = Uuid::new_v4(); //! let id_2 = Uuid::new_v4(); //! //! // Some sample source id and payload pairs //! let events = vec![ //! (id_1, vec!["1", "2", "3"]), //! (id_1, vec!["4", "5"]), //! (id_2, vec!["A", "B"]), //! (id_2, vec!["C"]), //! (id_2, vec!["D", "E", "F"]), //! ]; //! //! // The event payloads partitioned by source id and sorted by value //! let events_1 = vec!["1", "2", "3", "4", "5"]; //! let events_2 = vec!["A", "B", "C", "D", "E", "F"]; //! //! //! // Append all the events - let's not worry about ordering //! let handles = events.into_iter().map(|(source_id, events)| { //! thread::spawn(move || EVENT_STORE.append_events(source_id, events)) //! }); //! //! for handle in handles.collect::<Vec<_>>() { //! handle.join().unwrap(); //! } //! //! //! // We'll expect to get the same number of events that we gave for each id //! let events_stream_1 = EVENT_STORE.events(id_1, 0); //! let events_stream_2 = EVENT_STORE.events(id_2, 0); //! //! let (mut collected_events_1, mut collected_events_2) = //! Future::join(events_stream_1.map(|e| e.payload).collect(), //! events_stream_2.map(|e| e.payload).collect()).wait().unwrap(); //! //! // We don't know the order that the events came in, so we need to //! // ensure that they are all sorted first //! collected_events_1.sort(); //! collected_events_2.sort(); //! //! // Check that we have the expected items! //! assert_eq!(collected_events_1, events_1); //! assert_eq!(collected_events_2, events_2); //! } //! ``` extern crate chashmap; extern crate chronicle; extern crate futures; extern crate uuid; use chashmap::CHashMap; use chronicle::{EventStore, PersistedEvent}; use futures::{Async, Poll, Stream}; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use uuid::Uuid; /// An in-memory event store implementation that can be concurrently accessed #[derive(Debug, Clone)] pub struct MemoryEventStore<Event> { offset: Arc<AtomicUsize>, /// The stored event payloads and their global offset number events: CHashMap<Uuid, Vec<(usize, Event)>>, } impl<Event> MemoryEventStore<Event> { /// Create an empty event store pub fn new() -> MemoryEventStore<Event> { MemoryEventStore { offset: Arc::new(AtomicUsize::new(0)), events: CHashMap::new(), } } } impl<Event> EventStore for MemoryEventStore<Event> where Event: Clone { type Offset = usize; type Event = Event; type EventsStream = EventsStream<Event>; fn append_events(&self, source_id: Uuid, events: Vec<Event>) { if events.is_empty() { return; } self.events.alter(source_id, |existing_events| { let mut existing_events = existing_events.unwrap_or(Vec::new()); let new_events = events.into_iter().map(|event| { // Keep the global offset up to date as we iterate. Opting // for the strongest, sequentially consistent memory ordering // for now. We may be able to relax this though... ¯\_(ツ)_/¯ let offset = self.offset.fetch_add(1, Ordering::SeqCst); (offset, event) }); existing_events.extend(new_events); Some(existing_events) }); } fn events(&self, source_id: Uuid, offset: Self::Offset) -> EventsStream<Event> { EventsStream { source_id: source_id, sequence_number: 0, offset: offset, event_store: self.clone(), } } } /// A stream of events for a specified source id pub struct EventsStream<Event> { source_id: Uuid, sequence_number: usize, offset: usize, event_store: MemoryEventStore<Event>, } /// An error that may be returned when polling on the `EventsStream` /// /// Note that this error has no variants, so can never happen. This will be /// replaced by `!` once `#![feature(never_type)]` has been stabilised. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EventsStreamError {} impl<Event> Stream for EventsStream<Event> where Event: Clone { type Item = PersistedEvent<usize, Event>; type Error = EventsStreamError; fn poll(&mut self) -> Poll<Option<Self::Item>, EventsStreamError> { use chronicle::SequenceNumber; if let Some(source_events) = self.event_store.events.get(&self.source_id) { while let Some(&(offset, ref payload)) = source_events.get(self.sequence_number) { let sequence_number = self.sequence_number; self.sequence_number += 1; if offset < self.offset { continue; } else { let persisted_event = PersistedEvent { source_id: self.source_id, offset: offset,<|fim▁hole|> }; return Ok(Async::Ready(Some(persisted_event))); } } } Ok(Async::Ready(None)) } } #[cfg(test)] mod tests { use chronicle::{EventStore, PersistedEvent}; use futures::Future; use uuid::Uuid; use super::*; #[test] fn append_events_if_none_exist_for_the_source_id() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B", "C"]); assert_eq!(event_store.events.get(&source_id_1).map(|es| es.clone()), Some(vec![(0, "A"), (1, "B"), (2, "C")])); } #[test] fn append_events_for_an_existing_source_id() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B", "C"]); event_store.append_events(source_id_1, vec![]); event_store.append_events(source_id_1, vec!["D", "E"]); assert_eq!(event_store.events.get(&source_id_1).map(|es| es.clone()), Some(vec![(0, "A"), (1, "B"), (2, "C"), (3, "D"), (4, "E")])); } #[test] fn append_events_maintianing_the_offsets() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); let source_id_2 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B", "C"]); event_store.append_events(source_id_2, vec!["a", "b"]); event_store.append_events(source_id_1, vec!["D", "E"]); event_store.append_events(source_id_2, vec!["c", "d"]); assert_eq!(event_store.events.get(&source_id_1).map(|es| es.clone()), Some(vec![(0, "A"), (1, "B"), (2, "C"), (5, "D"), (6, "E")])); assert_eq!(event_store.events.get(&source_id_2).map(|es| es.clone()), Some(vec![(3, "a"), (4, "b"), (7, "c"), (8, "d")])); } #[test] fn events_on_empty_store() { let event_store = MemoryEventStore::<()>::new(); let source_id_1 = Uuid::new_v4(); let events = event_store.events(source_id_1, 0).collect().wait(); assert_eq!(events, Ok(Vec::new())); } #[test] fn events_on_non_empty_store() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B", "C"]); let events = event_store.events(source_id_1, 0).collect().wait(); assert_eq!(events, Ok(vec![PersistedEvent { offset: 0, source_id: source_id_1, sequence_number: 0, payload: "A", }, PersistedEvent { offset: 1, source_id: source_id_1, sequence_number: 1, payload: "B", }, PersistedEvent { offset: 2, source_id: source_id_1, sequence_number: 2, payload: "C", }])); } #[test] fn events_with_out_of_range_offset() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B", "C"]); let events = event_store.events(source_id_1, 100).collect().wait(); assert_eq!(events, Ok(Vec::new())); } #[test] fn events_with_non_contiguous_global_id_sequence() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); let source_id_2 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A"]); event_store.append_events(source_id_2, vec!["1", "2"]); event_store.append_events(source_id_1, vec!["B", "C"]); assert_eq!(event_store.events(source_id_1, 0).collect().wait(), Ok(vec![PersistedEvent { offset: 0, source_id: source_id_1, sequence_number: 0, payload: "A", }, PersistedEvent { offset: 3, source_id: source_id_1, sequence_number: 1, payload: "B", }, PersistedEvent { offset: 4, source_id: source_id_1, sequence_number: 2, payload: "C", }])); assert_eq!(event_store.events(source_id_2, 0).collect().wait(), Ok(vec![PersistedEvent { offset: 1, source_id: source_id_2, sequence_number: 0, payload: "1", }, PersistedEvent { offset: 2, source_id: source_id_2, sequence_number: 1, payload: "2", }])); } #[test] fn events_after_offset_id() { let event_store = MemoryEventStore::new(); let source_id_1 = Uuid::new_v4(); let source_id_2 = Uuid::new_v4(); event_store.append_events(source_id_1, vec!["A", "B"]); event_store.append_events(source_id_2, vec!["1", "2", "3"]); event_store.append_events(source_id_1, vec!["C", "D"]); assert_eq!(event_store.events(source_id_1, 1).collect().wait(), Ok(vec![PersistedEvent { offset: 1, source_id: source_id_1, sequence_number: 1, payload: "B", }, PersistedEvent { offset: 5, source_id: source_id_1, sequence_number: 2, payload: "C", }, PersistedEvent { offset: 6, source_id: source_id_1, sequence_number: 3, payload: "D", }])); assert_eq!(event_store.events(source_id_1, 2).collect().wait(), Ok(vec![PersistedEvent { offset: 5, source_id: source_id_1, sequence_number: 2, payload: "C", }, PersistedEvent { offset: 6, source_id: source_id_1, sequence_number: 3, payload: "D", }])); assert_eq!(event_store.events(source_id_1, 5).collect().wait(), Ok(vec![PersistedEvent { offset: 5, source_id: source_id_1, sequence_number: 2, payload: "C", }, PersistedEvent { offset: 6, source_id: source_id_1, sequence_number: 3, payload: "D", }])); assert_eq!(event_store.events(source_id_1, 6).collect().wait(), Ok(vec![PersistedEvent { offset: 6, source_id: source_id_1, sequence_number: 3, payload: "D", }])); } }<|fim▁end|>
sequence_number: sequence_number as SequenceNumber, payload: payload.clone(),
<|file_name|>commit_stats.py<|end_file_name|><|fim▁begin|># 统计一下提交代码量 import os import subprocess import pandas as pd os.chdir('../') # %% start_dt = '2019-05-01' end_dt = '2019-06-20' commits = subprocess.check_output( "git log --after={start_dt} --before={end_dt} --format='%s%cr'". format(start_dt=start_dt, end_dt=end_dt), shell=True) commits = commits.decode('utf-8') print(commits) print('提交了' + str(len(commits.split('\n'))) + '次') # %% detail = subprocess.check_output( "git log --after={start_dt} --before={end_dt} --pretty=tformat: --numstat". format(start_dt=start_dt, end_dt=end_dt), shell=True)<|fim▁hole|>detail_str=eval(str(detail).replace('\\\\','\\')).decode('utf-8') detail_formated=[line.split('\t') for line in detail_str.split('\n') if len(line)>0] detail_pd=pd.DataFrame(detail_formated) print(detail_pd)<|fim▁end|>
<|file_name|>AbstractOverlayElement.ts<|end_file_name|><|fim▁begin|>declare var $:any; class AbstractOverlayElement { public $overlay:any; public $container:any; public containerId:string; constructor(width:number, height:number, containerId:string) { this.$overlay = $('#overlay'); this.containerId = containerId; this.$overlay.click(function(event) { if(event.target === this.$overlay[0]) this.hide(); }.bind(this)); this.$container = $('<div>', {class: 'container ' + containerId}); this.$container.css({width: width, height: height, display: 'none'}); this.$overlay.append(this.$container); }<|fim▁hole|> public show():void { this.$overlay.show(); this.$overlay.find('.' + this.containerId).show(); $('body').removeClass('noselect'); } public hide():void { $('body').addClass('noselect'); this.$overlay.find('.' + this.containerId).hide(); this.$overlay.hide(); } } export default AbstractOverlayElement;<|fim▁end|>
<|file_name|>vector-no-ann.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license<|fim▁hole|> fn main() { let _foo = Vec::new(); //~^ ERROR type annotations or generic parameter binding required }<|fim▁end|>
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
<|file_name|>test_supercell.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """Tests for constructing supercell models.""" import itertools import numpy as np from numpy.testing import assert_allclose import pytest from parameters import KPT, T_VALUES<|fim▁hole|> import tbmodels def get_equivalent_k(k, supercell_size): return itertools.product( *[ (np.linspace(0, 1, s, endpoint=False) + ki / s) for ki, s in zip(k, supercell_size) ] ) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("supercell_size", [(1, 1, 1), (2, 1, 1), (2, 3, 2)]) def test_supercell_simple(get_model, t_values, supercell_size, sparse): """ Test that the eigenvalues from a supercell model match the folded eigenvalues of the base model, for a simple model. """ model = get_model(*t_values, sparse=sparse) supercell_model = model.supercell(size=supercell_size) for k in KPT: ev_supercell = supercell_model.eigenval(k) equivalent_k = get_equivalent_k(k, supercell_size) ev_folded = np.sort( np.array([model.eigenval(kval) for kval in equivalent_k]).flatten() ) assert ev_supercell.shape == ev_folded.shape assert_allclose(ev_supercell, ev_folded, atol=1e-7) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("supercell_size", [(5, 4), (1, 1), (2, 3)]) def test_supercell_simple_2d(get_model, t_values, supercell_size): """ Test that the eigenvalues from a supercell model match the folded eigenvalues of the base model, for a simple model. """ model = get_model(*t_values, dim=2) supercell_model = model.supercell(size=supercell_size) for k in [(-0.12341, 0.92435), (0, 0), (0.65432, -0.1561)]: ev_supercell = supercell_model.eigenval(k) equivalent_k = get_equivalent_k(k, supercell_size) ev_folded = np.sort( np.array([model.eigenval(kval) for kval in equivalent_k]).flatten() ) assert ev_supercell.shape == ev_folded.shape assert_allclose(ev_supercell, ev_folded, atol=1e-7) @pytest.mark.parametrize("t_values", T_VALUES) @pytest.mark.parametrize("supercell_size", [(5, 4, 2, 2), (1, 1, 1, 1), (2, 2, 3, 2)]) def test_supercell_simple_4d(get_model, t_values, supercell_size): """ Test that the eigenvalues from a supercell model match the folded eigenvalues of the base model, for a simple model. """ model = get_model(*t_values, dim=4) supercell_model = model.supercell(size=supercell_size) for k in [ (-0.12341, 0.92435, 0.32, 0.1212), (0, 0, 0, 0), (0.65432, -0.1561, 0.2352346, -0.92345), ]: ev_supercell = supercell_model.eigenval(k) equivalent_k = get_equivalent_k(k, supercell_size) ev_folded = np.sort( np.array([model.eigenval(kval) for kval in equivalent_k]).flatten() ) assert ev_supercell.shape == ev_folded.shape assert_allclose(ev_supercell, ev_folded, atol=1e-7) @pytest.mark.parametrize("supercell_size", [(1, 1, 1), (2, 1, 1)]) def test_supercell_inas(sample, supercell_size): """ Test that the eigenvalues from a supercell model match the folded eigenvalues of the base model, for the realistic InAs model. """ model = tbmodels.io.load(sample("InAs_nosym.hdf5")) supercell_model = model.supercell(size=supercell_size) for k in [(-0.4, 0.1, 0.45), (0, 0, 0), (0.41126, -0.153112, 0.2534)]: ev_supercell = supercell_model.eigenval(k) equivalent_k = get_equivalent_k(k, supercell_size) ev_folded = np.sort( np.array([model.eigenval(kval) for kval in equivalent_k]).flatten() ) assert ev_supercell.shape == ev_folded.shape assert_allclose(ev_supercell, ev_folded, atol=1e-7) def test_supercell_model_equal(sample, models_close): """ Regression test checking that a supercell model matches a stored reference. """ model = tbmodels.io.load(sample("InAs_nosym.hdf5")) supercell_model = model.supercell(size=(1, 2, 3)) supercell_reference = tbmodels.io.load(sample("InAs_supercell_reference.hdf5")) models_close(supercell_model, supercell_reference, ignore_sparsity=True)<|fim▁end|>
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import PartyBot from 'partybot-http-client'; import React, { PropTypes, Component } from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import Heading from 'grommet/components/Heading'; import Box from 'grommet/components/Box'; import Footer from 'grommet/components/Footer'; import Button from 'grommet/components/Button'; import Form from 'grommet/components/Form'; import FormField from 'grommet/components/FormField'; import FormFields from 'grommet/components/FormFields'; import NumberInput from 'grommet/components/NumberInput'; import CloseIcon from 'grommet/components/icons/base/Close'; import Dropzone from 'react-dropzone'; import Layer from 'grommet/components/Layer'; import Header from 'grommet/components/Header'; import Section from 'grommet/components/Section'; import Paragraph from 'grommet/components/Paragraph'; import request from 'superagent'; import Select from 'react-select'; import { CLOUDINARY_UPLOAD_PRESET, CLOUDINARY_NAME, CLOUDINARY_KEY, CLOUDINARY_SECRET, CLOUDINARY_UPLOAD_URL } from '../../constants'; import Immutable from 'immutable'; import _ from 'underscore'; class ManageTablesPage extends Component { constructor(props) { super(props); this.handleMobile = this.handleMobile.bind(this); this.closeSetup = this.closeSetup.bind(this); this.onDrop = this.onDrop.bind(this); this.addVariant = this.addVariant.bind(this); this.submitSave = this.submitSave.bind(this); this.submitDelete = this.submitDelete.bind(this); this.state = { isMobile: false, tableId: props.params.table_id || null, confirm: false, name: '', variants: [], organisationId: '5800471acb97300011c68cf7', venues: [], venueId: '', events: [], eventId: '', selectedEvents: [], tableTypes: [], tableTypeId: undefined, tags: 'table', image: null, prevImage: null, isNewImage: null, prices: [] }; } componentWillMount() { if (this.state.tableId) { this.setState({variants: []}); } } componentDidMount() { if (typeof window !== 'undefined') { window.addEventListener('resize', this.handleMobile); } let options = { organisationId: this.state.organisationId }; this.getVenues(options); // IF TABLE ID EXISTS if(this.props.params.table_id) { let tOptions = { organisationId: this.state.organisationId, productId: this.props.params.table_id } this.getTable(tOptions); } } componentWillUnmount() { if (typeof window !== 'undefined') { window.removeEventListener('resize', this.handleMobile); } } handleMobile() { const isMobile = window.innerWidth <= 768; this.setState({ isMobile, }); }; getVenues = (options) => { PartyBot.venues.getAllInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({venueId: body[0]._id}); let ttOptions = { organisationId: this.state.organisationId, venue_id: this.state.venueId } // this.getEvents(ttOptions); this.getTableTypes(ttOptions); } this.setState({venues: body, events: []}); } }); } getEvents = (options) => { PartyBot.events.getEventsInOrganisation(options, (err, response, body) => { if(!err && response.statusCode == 200) { if(body.length > 0) { this.setState({eventId: body[0]._id}); } body.map((value, index) =>{ this.setState({events: this.state.events.concat({ _event: value._id, name: value.name, selected: false })}); }); } }); } getTableTypes = (options) => { PartyBot.tableTypes.getTableTypesInOrganisation(options, (errors, response, body) => { if(response.statusCode == 200) { if(body.length > 0) { this.setState({tableTypes: body}); let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: body[0]._id } PartyBot.tableTypes.getTableType(params, (aerr, aresponse, abody) => { let events = abody._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: body[0]._id, events: _.flatten(events) }); }); } } }); } getTable = (options) => { PartyBot.products.getProductsInOrganisation(options, (error, response, body) => { if(response.statusCode == 200) { this.setState({ name: body.name, image: { preview: body.image }, prevImage: { preview: body.image }, variants: body.prices.map((value, index) => { return { _event: value._event, price: value.price } }) }); } }); } onVenueChange = (event) => { let id = event.target.value; this.setState({ venueId: id, events: [], variants: []}); let options = { organisationId: this.state.organisationId, venue_id: id }; this.getTableTypes(options); // this.getEvents(options); } onEventChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: event.target.value, price: item.price}); this.setState( { variants: mutated.toArray() } ); } onPriceChange = (item, index, event) => { let variants = Immutable.List(this.state.variants); let mutated = variants.set(index, { _event: item._event, price: event.target.value}); this.setState( { variants: mutated.toArray() } ); } closeSetup(){ this.setState({ confirm: false }); this.context.router.push('/tables'); } addVariant() { // will create then get? var newArray = this.state.variants.slice(); newArray.push({ _event_id: [], description: "", image: null, imageUrl: "" }); this.setState({variants:newArray}) } removeVariant(index, event){ // delete variant ID let variants = Immutable.List(this.state.variants); let mutated = variants.remove(index); // let selectedEvents = Immutable.List(this.state.selectedEvents); // let mutatedEvents = selectedEvents.remove(index); this.setState({ variants: mutated.toJS(), }); } onEventAdd = (index, selectedEvents) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('_event_id', selectedEvents); let newClone = cloned.set(index, anIndex); let selectedEventState = Immutable.List(this.state.selectedEvents); let newSelectedEventState = selectedEventState.set(index, selectedEvents); this.setState({selectedEvents: newSelectedEventState.toJS(), variants: newClone.toJS()}); } setDescrpiption = (index, event) => { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('description', event.target.value); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS()}); } onDrop = (index, file) => { this.setState({ isBusy: true }); let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file[0]); console.log('dragged'); upload.end((err, response) => { if (err) { } else { let cloned = Immutable.List(this.state.variants); let anIndex = Immutable.fromJS(cloned.get(index)); anIndex = anIndex.set('image', file[0]); anIndex = anIndex.set('imageUrl', response.body.secure_url); let newClone = cloned.set(index, anIndex); this.setState({variants: newClone.toJS(), isBusy: false}); } }); } onTypeChange = (event) => { var id = event.target.value; let params = { organisationId: this.state.organisationId, venueId: this.state.venueId, tableTypeId: id } PartyBot.tableTypes.getTableType(params, (err, response, body) => { let events = body._events.map((value) => { return value._event_id.map((avalue) => { return { value: avalue._id, label: avalue.name } }); }); this.setState({ tableTypeId: id, variants: [], events: _.flatten(events) }); }); } setName = (event) => { this.setState({name: event.target.value}); } getTypeOptions = () => { return this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; }); } getTableVariants = () => { return this.state.variants.map((value, index) => { return ( <Box key={index} separator="all"> <FormField label="Event" htmlFor="events" /> <Select name="events" options={this.state.events.filter((x) => { let a = _.contains(_.uniq(_.flatten(this.state.selectedEvents)), x); return !a; })} value={value._event_id} onChange={this.onEventAdd.bind(this, index)} multi={true} /> <FormField label="Description" htmlFor="tableTypedescription"> <input id="tableTypedescription" type="text" onChange={this.setDescrpiption.bind(this, index)} value={value.description}/> </FormField> <FormField label="Image"> {value.image ? <Box size={{ width: 'large' }} align="center" justify="center"> <div> <img src={value.image.preview} width="200" /> </div> <Box size={{ width: 'large' }}> <Button label="Cancel" onClick={this.onRemoveImage.bind(this)} plain={true} icon={<CloseIcon />}/> </Box> </Box> : <Box align="center" justify="center" size={{ width: 'large' }}> <Dropzone multiple={false} ref={(node) => { this.dropzone = node; }} onDrop={this.onDrop.bind(this, index)} accept='image/*'> Drop image here or click to select image to upload. </Dropzone> </Box> } <Button label="Remove" onClick={this.removeVariant.bind(this, index)} primary={true} float="right"/> </FormField> </Box>) }); // return this.state.variants.map( (item, index) => { // return <div key={index}> // <FormField label="Event" htmlFor="tableName"> // <select id="tableVenue" onChange={this.onEventChange.bind(this, item, index)} value={item._event||this.state.events[0]._event}> // { // this.state.events.map( (value, index) => { // return (<option key={index} value={value._event}>{value.name}</option>) // }) // } // </select> // </FormField> // <FormField label="Price(Php)" htmlFor="tablePrice"> // <input type="number" onChange={this.onPriceChange.bind(this, item, index)} value={item.price}/> // </FormField> // <Footer pad={{"vertical": "small"}}> // <Heading align="center"> // <Button className={styles.eventButton} label="Update" primary={true} onClick={() => {}} /> // <Button className={styles.eventButton} label="Remove" onClick={this.removeVariant.bind(this, index)} /> // </Heading> // </Footer> // </div>; // }); } onDrop(file) { this.setState({ image: file[0], isNewImage: true }); } onRemoveImage = () => { this.setState({ image: null, isNewImage: false }); } handleImageUpload(file, callback) { if(this.state.isNewImage) { let options = { url: CLOUDINARY_UPLOAD_URL, formData: { file: file } }; let upload = request.post(CLOUDINARY_UPLOAD_URL) .field('upload_preset', CLOUDINARY_UPLOAD_PRESET) .field('file', file); upload.end((err, response) => { if (err) { console.error(err); } if (response.body.secure_url !== '') { callback(null, response.body.secure_url) } else { callback(err, ''); } }); } else { callback(null, null); } } submitDelete (event) { event.preventDefault(); let delParams = { organisationId: this.state.organisationId, productId: this.state.tableId }; PartyBot.products.deleteProduct(delParams, (error, response, body) => { if(!error && response.statusCode == 200) { this.setState({ confirm: true }); } else { } }); } submitSave() { event.preventDefault(); this.handleImageUpload(this.state.image, (err, imageLink) => { if(err) { console.log(err); } else { let updateParams = { name: this.state.name, organisationId: this.state.organisationId, productId: this.state.tableId, venueId: this.state.venueId, table_type: this.state.tableTypeId, image: imageLink || this.state.prevImage.preview, prices: this.state.variants }; PartyBot.products.update(updateParams, (errors, response, body) => { if(response.statusCode == 200) { this.setState({ confirm: true }); } }); } }); } submitCreate = () => { event.preventDefault(); console.log(this.state); let params = {}; // this.handleImageUpload(this.state.image, (err, imageLink) => { // if(err) { // console.log(err); // } else { // let createParams = { // name: this.state.name, // organisationId: this.state.organisationId, // venueId: this.state.venueId, // tags: this.state.tags, // table_type: this.state.tableTypeId, // image: imageLink, // prices: this.state.variants // }; // PartyBot.products.create(createParams, (errors, response, body) => { // if(response.statusCode == 200) { // this.setState({ // confirm: true // }); // } // }); // } // }); } render() { const { router, } = this.context; const { isMobile, } = this.state; const { files, variants, } = this.state; return ( <div className={styles.container}> <link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css"/> {this.state.confirm !== false ? <Layer align="center"> <Header> Table successfully created. </Header> <Section> <Button label="Close" onClick={this.closeSetup} plain={true} icon={<CloseIcon />}/> </Section> </Layer> : null } <Box> {this.state.tableId !== null ? <Heading align="center"> Edit Table </Heading> : <Heading align="center"> Add Table </Heading> } </Box> <Box size={{ width: 'large' }} direction="row" justify="center" align="center" wrap={true} margin="small"> <Form> <FormFields> <fieldset> <FormField label="Venue" htmlFor="tableVenue"> <select id="tableVenue" onChange={this.onVenueChange} value={this.state.venueId}> {this.state.venues.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label="Table Type" htmlFor="tableType"> <select id="tableType" onChange={this.onTypeChange} value={this.state.tableTypeId}> {this.state.tableTypes.map((value, index) => { return <option key={index} value={value._id}>{value.name}</option>; })} </select> </FormField> <FormField label=" Name" htmlFor="tableName"> <input id="tableName" type="text" onChange={this.setName} value={this.state.name}/> </FormField> { //Dynamic Price/Event Component this.getTableVariants() } <Button label="Add Event" primary={true} onClick={this.addVariant} /> </fieldset> </FormFields> <Footer pad={{"vertical": "medium"}}> { this.state.tableId !== null ? <Heading align="center"><|fim▁hole|> <Button label="Delete" primary={true} onClick={this.submitDelete} /> </Heading> : <Heading align="center"> <Button label="Create Table" primary={true} onClick={this.submitCreate} /> </Heading> } </Footer> </Form> </Box> </div> ); } } ManageTablesPage.contextTypes = { router: PropTypes.object.isRequired, }; export default cssModules(ManageTablesPage, styles);<|fim▁end|>
<Button label="Save Changes" primary={true} onClick={this.submitSave} />
<|file_name|>twit.py<|end_file_name|><|fim▁begin|>import sys, os import tweepy # File with colon-separaten consumer/access token and secret consumer_file='twitter.consumer' access_file='twitter.access' def __load_auth(file): if os.path.exists(file): with open(file) as f: tokens = f.readline().replace('\n','').replace('\r','').split(':') if len(tokens) == 2: return tokens[0],tokens[1] else: raise ValueError("Expecting two colon-separated tokens") else: raise IOError("File not found: %s" % file) def twit(message, secret_dir='/secret'): # # Load the twitter consumer and access tokens and secrets consumer_token, consumer_secret = __load_auth(os.path.join(secret_dir, consumer_file)) access_token, access_secret = __load_auth(os.path.join(secret_dir, access_file)) # # Perform OAuth authentication auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(access_token, access_secret) # # Create the API and post the status update try: api = tweepy.API(auth) api.update_status(message) except tweepy.error.TweepError, e: print "Failed to post status update" print "Error: %s" % str(e) print "Using:" print " consumer[%s][%s]" % (consumer_token, consumer_secret) print " access[%s][%s]" % (access_token, access_secret) if __name__ == '__main__': tokens = sys.argv[1:] #<|fim▁hole|><|fim▁end|>
twit(' '.join(tokens))
<|file_name|>0009_footer.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-07-27 17:21 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0008_sponsor_primary_sponsor'), ] operations = [ migrations.CreateModel( name='Footer', fields=[<|fim▁hole|> ('twitch_url', models.URLField(blank=True, null=True)), ], ), ]<|fim▁end|>
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('facebook_url', models.URLField(blank=True, null=True)),
<|file_name|>markdown_wiki_test.js<|end_file_name|><|fim▁begin|>'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value)<|fim▁hole|>*/ exports.markdown_wiki = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };<|fim▁end|>
<|file_name|>script.js<|end_file_name|><|fim▁begin|>const defaults = { base_css: true, // the base dark theme css inline_youtube: true, // makes youtube videos play inline the chat collapse_onebox: true, // can collapse collapse_onebox_default: false, // default option for collapse pause_youtube_on_collapse: true, // default option for pausing youtube on collapse user_color_bars: true, // show colored bars above users message blocks fish_spinner: true, // fish spinner is best spinner inline_imgur: true, // inlines webm,gifv,mp4 content from imgur visualize_hex: true, // underlines hex codes with their colour values syntax_highlight_code: true, // guess at language and highlight the code blocks emoji_translator: true, // emoji translator for INPUT area code_mode_editor: true, // uses CodeMirror for your code inputs better_image_uploads: true // use the drag & drop and paste api for image uploads }; const fileLocations = { inline_youtube: ['js/inline_youtube.js'], collapse_onebox: ['js/collapse_onebox.js'], user_color_bars: ['js/user_color_bars.js'], fish_spinner: ['js/fish_spinner.js'], inline_imgur: ['js/inline_imgur.js'], visualize_hex: ['js/visualize_hex.js'], better_image_uploads: ['js/better_image_uploads.js'], syntax_highlight_code: ['js/highlight.js', 'js/syntax_highlight_code.js'], emoji_translator: ['js/emojidata.js', 'js/emoji_translator.js'], code_mode_editor: ['CodeMirror/js/codemirror.js', 'CodeMirror/mode/cmake/cmake.js', 'CodeMirror/mode/cobol/cobol.js', 'CodeMirror/mode/coffeescript/coffeescript.js', 'CodeMirror/mode/commonlisp/commonlisp.js', 'CodeMirror/mode/css/css.js', 'CodeMirror/mode/dart/dart.js', 'CodeMirror/mode/go/go.js', 'CodeMirror/mode/groovy/groovy.js', 'CodeMirror/mode/haml/haml.js',<|fim▁hole|> 'CodeMirror/mode/haskell/haskell.js', 'CodeMirror/mode/htmlembedded/htmlembedded.js', 'CodeMirror/mode/htmlmixed/htmlmixed.js', 'CodeMirror/mode/jade/jade.js', 'CodeMirror/mode/javascript/javascript.js', 'CodeMirror/mode/lua/lua.js', 'CodeMirror/mode/markdown/markdown.js', 'CodeMirror/mode/mathematica/mathematica.js', 'CodeMirror/mode/nginx/nginx.js', 'CodeMirror/mode/pascal/pascal.js', 'CodeMirror/mode/perl/perl.js', 'CodeMirror/mode/php/php.js', 'CodeMirror/mode/puppet/puppet.js', 'CodeMirror/mode/python/python.js', 'CodeMirror/mode/ruby/ruby.js', 'CodeMirror/mode/sass/sass.js', 'CodeMirror/mode/scheme/scheme.js', 'CodeMirror/mode/shell/shell.js' , 'CodeMirror/mode/sql/sql.js', 'CodeMirror/mode/swift/swift.js', 'CodeMirror/mode/twig/twig.js', 'CodeMirror/mode/vb/vb.js', 'CodeMirror/mode/vbscript/vbscript.js', 'CodeMirror/mode/vhdl/vhdl.js', 'CodeMirror/mode/vue/vue.js', 'CodeMirror/mode/xml/xml.js', 'CodeMirror/mode/xquery/xquery.js', 'CodeMirror/mode/yaml/yaml.js', 'js/code_mode_editor.js'] }; // right now I assume order is correct because I'm a terrible person. make an order array or base it on File Locations and make that an array // inject the observer and the utils always. then initialize the options. injector([{type: 'js', location: 'js/observer.js'},{type: 'js', location: 'js/utils.js'}], _ => chrome.storage.sync.get(defaults, init)); function init(options) { // inject the options for the plugins themselves. const opts = document.createElement('script'); opts.textContent = ` const options = ${JSON.stringify(options)}; `; document.body.appendChild(opts); // now load the plugins. const loading = []; if( !options.base_css ) { document.documentElement.classList.add('nocss'); } delete options.base_css; for( const key of Object.keys(options) ) { if( !options[key] || !( key in fileLocations)) continue; for( const location of fileLocations[key] ) { const [,type] = location.split('.'); loading.push({location, type}); } } injector(loading, _ => { const drai = document.createElement('script'); drai.textContent = ` if( document.readyState === 'complete' ) { DOMObserver.drain(); } else { window.onload = _ => DOMObserver.drain(); } `; document.body.appendChild(drai); }); } function injector([first, ...rest], cb) { if( !first ) return cb(); if( first.type === 'js' ) { injectJS(first.location, _ => injector(rest, cb)); } else { injectCSS(first.location, _ => injector(rest, cb)); } } function injectCSS(file, cb) { const elm = document.createElement('link'); elm.rel = 'stylesheet'; elm.type = 'text/css'; elm.href = chrome.extension.getURL(file); elm.onload = cb; document.head.appendChild(elm); } function injectJS(file, cb) { const elm = document.createElement('script'); elm.type = 'text/javascript'; elm.src = chrome.extension.getURL(file); elm.onload = cb; document.body.appendChild(elm); }<|fim▁end|>
<|file_name|>canvas_msg.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_paint_task::{FillOrStrokeStyle, LineCapStyle, LineJoinStyle, CompositionOrBlending}; use geom::matrix2d::Matrix2D; use geom::point::Point2D; use geom::rect::Rect; use geom::size::Size2D; use std::sync::mpsc::{Sender}; #[derive(Clone)]<|fim▁hole|>pub enum CanvasMsg { Canvas2d(Canvas2dMsg), Common(CanvasCommonMsg), WebGL(CanvasWebGLMsg), } #[derive(Clone)] pub enum Canvas2dMsg { Arc(Point2D<f32>, f32, f32, f32, bool), ArcTo(Point2D<f32>, Point2D<f32>, f32), DrawImage(Vec<u8>, Size2D<f64>, Rect<f64>, Rect<f64>, bool), DrawImageSelf(Size2D<f64>, Rect<f64>, Rect<f64>, bool), BeginPath, BezierCurveTo(Point2D<f32>, Point2D<f32>, Point2D<f32>), ClearRect(Rect<f32>), Clip, ClosePath, Fill, FillRect(Rect<f32>), GetImageData(Rect<f64>, Size2D<f64>, Sender<Vec<u8>>), LineTo(Point2D<f32>), MoveTo(Point2D<f32>), PutImageData(Vec<u8>, Rect<f64>, Option<Rect<f64>>), QuadraticCurveTo(Point2D<f32>, Point2D<f32>), Rect(Rect<f32>), RestoreContext, SaveContext, StrokeRect(Rect<f32>), Stroke, SetFillStyle(FillOrStrokeStyle), SetStrokeStyle(FillOrStrokeStyle), SetLineWidth(f32), SetLineCap(LineCapStyle), SetLineJoin(LineJoinStyle), SetMiterLimit(f32), SetGlobalAlpha(f32), SetGlobalComposition(CompositionOrBlending), SetTransform(Matrix2D<f32>), } #[derive(Clone)] pub enum CanvasWebGLMsg { AttachShader(u32, u32), BindBuffer(u32, u32), BufferData(u32, Vec<f32>, u32), Clear(u32), ClearColor(f32, f32, f32, f32), CompileShader(u32), CreateBuffer(Sender<u32>), CreateProgram(Sender<u32>), CreateShader(u32, Sender<u32>), DrawArrays(u32, i32, i32), EnableVertexAttribArray(u32), GetAttribLocation(u32, String, Sender<i32>), GetShaderInfoLog(u32, Sender<String>), GetShaderParameter(u32, u32, Sender<i32>), GetUniformLocation(u32, String, Sender<u32>), LinkProgram(u32), ShaderSource(u32, Vec<String>), Uniform4fv(u32, Vec<f32>), UseProgram(u32), VertexAttribPointer2f(u32, i32, bool, i32, i64), Viewport(i32, i32, i32, i32), } #[derive(Clone)] pub enum CanvasCommonMsg { Close, Recreate(Size2D<i32>), SendPixelContents(Sender<Vec<u8>>), }<|fim▁end|>
<|file_name|>print_records.py<|end_file_name|><|fim▁begin|>"""Print all records in the pickle for the specified test""" <|fim▁hole|> def main(): """Print all records corresponding to test given as an argument""" parser = argparse.ArgumentParser(description='Submit one or more jobs.') parser.add_argument('testname', help='test directory') parser.add_argument('-c', '--configfile', type=str, default='autocms.cfg', help='AutoCMS configuration file name') args = parser.parse_args() config = load_configuration(args.configfile) records = load_records(args.testname,config) for job in records: print str(job)+'\n' return 0 if __name__ == '__main__': status = main() sys.exit(status)<|fim▁end|>
import sys import argparse from autocms.core import (load_configuration, load_records)
<|file_name|>operators.cpp<|end_file_name|><|fim▁begin|>#include "operators.h" #define ROI_SIZE (100) Operator::Operator(cvb::CvID id):id_(id) { prev_label_ = cur_label_ = BACKGROUND; action_angle_ = -1.0; } void Operator::Process(const cv::Mat &frame) { ac_.ClassifyFrame(frame, &cur_label_); if ((cur_label_ == prev_label_)) consistency_cnt_ ++; else consistency_cnt_ = 0; prev_label_ = cur_label_; if (consistency_cnt_ < WINDOW_LENGTH) cur_label_ = BACKGROUND; oe_.Evaluate(frame, (int)cur_label_, &action_angle_); } void Operators::UpdateOperators() { //remove deleted tracks for (OperatorsMap::const_iterator it = ops_.begin(); it!=ops_.end(); ++it) { cvb::CvID op_id = it->second->get_id(); if (tracks_.count(op_id) == 0) { OperatorsMap::const_iterator next_op = it; int track_id = it->first; for (std::vector<int>::iterator track_it = track_id_queue_.begin(); track_it != track_id_queue_.end(); ++track_it) if (*track_it == track_id) { track_id_queue_.erase(track_it); break; } delete it->second; std::advance(next_op, 1); if (next_op == ops_.end()) { ops_.erase(it->first); break; } ops_.erase(it->first); it = next_op; } } //add new tracks for (cvb::CvTracks::const_iterator it = tracks_.begin(); it!=tracks_.end(); ++it) { cvb::CvID track_id = it->second->id; if (ops_.count(track_id) == 0) { Operator *op = new Operator(track_id); ops_.insert(CvIDOperator(track_id, op)); track_id_queue_.push_back(track_id); } } } void Operators::StoreROI(const cv::Mat &frame, const char* output_path_char) { static int cnt = 0; fs::path output_path; int dim = ROI_SIZE; output_path = fs::path(output_path_char); //CHECK(fs::exists(output_path)); <|fim▁hole|> for (cvb::CvTracks::const_iterator it=tracks_.begin(); it!=tracks_.end(); ++it) { // Store 25 percent of potential operators if ((rand() % 100) <= 25) { cv::Mat op = cv::Mat::zeros(dim, dim, frame.type()); cvb::CvTrack *track = (*it).second; cv::Rect r1,r2; cv::Mat tmp; char filename[50]; sprintf(filename, "_object_%03d.jpg", cnt++); r1 = cv::Rect(cv::Point(std::max<int>(0, (int)track->centroid.x - dim/2), std::max<int>(0, (int)track->centroid.y - dim/2)), cv::Point(std::min<int>(frame.cols, (int)track->centroid.x + dim/2), std::min<int>(frame.rows, (int)track->centroid.y + dim/2))); tmp = frame(r1); r2 = cv::Rect((dim - tmp.cols)/2, (dim - tmp.rows)/2, tmp.cols, tmp.rows); tmp.copyTo(op(r2)); cv::imwrite(output_path.string() + std::string(filename), op); } }//for (cvb::CvTracks::const_iterator it=opTracks.begin(); it!=opTracks.end(); ++it) } void Operators::ExtractROI(const cv::Mat &frame, std::vector<OperatorROI> *roi, int max_operators=1) { for (cvb::CvTracks::const_iterator it=tracks_.begin(); it!=tracks_.end(); ++it) { cv::Mat op = cv::Mat::zeros(ROI_SIZE, ROI_SIZE, frame.type()); cvb::CvTrack *track = (*it).second; bool processed_track = false; for (int i = 0; i < max_operators; i++) if (track->id == track_id_queue_[i]) { processed_track = true; break; } if (processed_track && (track->lifetime > 5)) { cv::Rect r1,r2; cv::Mat tmp; r1 = cv::Rect(cv::Point(std::max<int>(0, (int)track->centroid.x - ROI_SIZE/2), std::max<int>(0, (int)track->centroid.y - ROI_SIZE/2)), cv::Point(std::min<int>(frame.cols, (int)track->centroid.x + ROI_SIZE/2), std::min<int>(frame.rows, (int)track->centroid.y + ROI_SIZE/2))); tmp = frame(r1); r2 = cv::Rect((ROI_SIZE - tmp.cols)/2, (ROI_SIZE - tmp.rows)/2, tmp.cols, tmp.rows); tmp.copyTo(op(r2)); roi->push_back(OperatorROI(track, op)); }//if (track->lifetime > 5) }//for (cvb::CvTracks::const_iterator it=opTracks.begin(); it!=opTracks.end(); ++it) }<|fim▁end|>
<|file_name|>twilio.py<|end_file_name|><|fim▁begin|>"""<|fim▁hole|> http://psa.matiasaguirre.net/docs/backends/twilio.html """ from re import sub from social.p3 import urlencode from social.backends.base import BaseAuth class TwilioAuth(BaseAuth): name = 'twilio' ID_KEY = 'AccountSid' def get_user_details(self, response): """Return twilio details, Twilio only provides AccountSID as parameters.""" # /complete/twilio/?AccountSid=ACc65ea16c9ebd4d4684edf814995b27e return {'username': response['AccountSid'], 'email': '', 'fullname': '', 'first_name': '', 'last_name': ''} def auth_url(self): """Return authorization redirect url.""" key, secret = self.get_key_and_secret() callback = self.strategy.absolute_uri(self.redirect_uri) callback = sub(r'^https', 'http', callback) query = urlencode({'cb': callback}) return 'https://www.twilio.com/authorize/{0}?{1}'.format(key, query) def auth_complete(self, *args, **kwargs): """Completes loging process, must return user instance""" account_sid = self.data.get('AccountSid') if not account_sid: raise ValueError('No AccountSid returned') kwargs.update({'response': self.data, 'backend': self}) return self.strategy.authenticate(*args, **kwargs)<|fim▁end|>
Amazon auth backend, docs at:
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name' : 'eInvoicing & Payments', 'version' : '1.0', 'author' : 'OpenERP SA', 'summary': 'Send Invoices and Track Payments', 'description': """ Invoicing & Payments by Accounting Voucher & Receipts ===================================================== The specific and easy-to-use Invoicing system in OpenERP allows you to keep track of your accounting, even when you are not an accountant. It provides an easy way to follow up on your suppliers and customers. You could use this simplified accounting in case you work with an (external) account to keep your books, and you still want to keep track of payments. The Invoicing system includes receipts and vouchers (an easy way to keep track of sales and purchases). It also offers you an easy method of registering payments, without having to encode complete abstracts of account. This module manages: * Voucher Entry * Voucher Receipt [Sales & Purchase] * Voucher Payment [Customer & Supplier] """, 'category': 'Accounting & Finance', 'sequence': 4, 'website' : 'http://openerp.com', 'images' : ['images/customer_payment.jpeg','images/journal_voucher.jpeg','images/sales_receipt.jpeg','images/supplier_voucher.jpeg','images/customer_invoice.jpeg','images/customer_refunds.jpeg'], 'depends' : ['account'], 'demo' : [], 'data' : [ 'security/ir.model.access.csv', 'account_voucher_sequence.xml', 'account_voucher_workflow.xml', 'account_voucher_view.xml', 'voucher_payment_receipt_view.xml', 'voucher_sales_purchase_view.xml', 'account_voucher_wizard.xml', 'account_voucher_pay_invoice.xml', 'report/account_voucher_sales_receipt_view.xml', 'security/account_voucher_security.xml', 'account_voucher_data.xml', ], 'test' : [ 'test/account_voucher_users.yml', 'test/case5_suppl_usd_usd.yml', 'test/account_voucher.yml', 'test/sales_receipt.yml', 'test/sales_payment.yml', 'test/case1_usd_usd.yml', 'test/case1_usd_usd_payment_rate.yml', 'test/case2_usd_eur_debtor_in_eur.yml', 'test/case2_usd_eur_debtor_in_usd.yml',<|fim▁hole|> 'auto_install': False, 'application': True, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
'test/case3_eur_eur.yml', 'test/case4_cad_chf.yml', 'test/case_eur_usd.yml', ],
<|file_name|>QCamera2HWI.cpp<|end_file_name|><|fim▁begin|>/* Copyright (c) 2012-2014, The Linux Foundataion. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #define LOG_TAG "QCamera2HWI" #include <cutils/properties.h> #include <hardware/camera.h> #include <stdlib.h> #include <utils/Errors.h> #include <gralloc_priv.h> #include <gui/Surface.h> #include "QCamera2HWI.h" #include "QCameraMem.h" #define MAP_TO_DRIVER_COORDINATE(val, base, scale, offset) (val * scale / base + offset) #define CAMERA_MIN_STREAMING_BUFFERS 3 #define EXTRA_ZSL_PREVIEW_STREAM_BUF 2 #define CAMERA_MIN_JPEG_ENCODING_BUFFERS 2 #define CAMERA_MIN_VIDEO_BUFFERS 9 #define CAMERA_LONGSHOT_STAGES 4 #define HDR_CONFIDENCE_THRESHOLD 0.4 namespace qcamera { cam_capability_t *gCamCapability[MM_CAMERA_MAX_NUM_SENSORS]; qcamera_saved_sizes_list savedSizes[MM_CAMERA_MAX_NUM_SENSORS]; static pthread_mutex_t g_camlock = PTHREAD_MUTEX_INITIALIZER; volatile uint32_t gCamHalLogLevel = 0; camera_device_ops_t QCamera2HardwareInterface::mCameraOps = { set_preview_window: QCamera2HardwareInterface::set_preview_window, set_callbacks: QCamera2HardwareInterface::set_CallBacks, enable_msg_type: QCamera2HardwareInterface::enable_msg_type, disable_msg_type: QCamera2HardwareInterface::disable_msg_type, msg_type_enabled: QCamera2HardwareInterface::msg_type_enabled, start_preview: QCamera2HardwareInterface::start_preview, stop_preview: QCamera2HardwareInterface::stop_preview, preview_enabled: QCamera2HardwareInterface::preview_enabled, store_meta_data_in_buffers: QCamera2HardwareInterface::store_meta_data_in_buffers, start_recording: QCamera2HardwareInterface::start_recording, stop_recording: QCamera2HardwareInterface::stop_recording, recording_enabled: QCamera2HardwareInterface::recording_enabled, release_recording_frame: QCamera2HardwareInterface::release_recording_frame, auto_focus: QCamera2HardwareInterface::auto_focus, cancel_auto_focus: QCamera2HardwareInterface::cancel_auto_focus, take_picture: QCamera2HardwareInterface::take_picture, cancel_picture: QCamera2HardwareInterface::cancel_picture, set_parameters: QCamera2HardwareInterface::set_parameters, get_parameters: QCamera2HardwareInterface::get_parameters, put_parameters: QCamera2HardwareInterface::put_parameters, send_command: QCamera2HardwareInterface::send_command, release: QCamera2HardwareInterface::release, dump: QCamera2HardwareInterface::dump, }; int32_t QCamera2HardwareInterface::getEffectValue(const char *effect) { uint32_t cnt = 0; while(NULL != QCameraParameters::EFFECT_MODES_MAP[cnt].desc) { if(!strcmp(QCameraParameters::EFFECT_MODES_MAP[cnt].desc, effect)) { return QCameraParameters::EFFECT_MODES_MAP[cnt].val; } cnt++; } return 0; } /*=========================================================================== * FUNCTION : set_preview_window * * DESCRIPTION: set preview window. * * PARAMETERS : * @device : ptr to camera device struct * @window : window ops table * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::set_preview_window(struct camera_device *device, struct preview_stream_ops *window) { int rc = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("%s: NULL camera device", __func__); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; rc = hw->processAPI(QCAMERA_SM_EVT_SET_PREVIEW_WINDOW, (void *)window); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_PREVIEW_WINDOW, &apiResult); rc = apiResult.status; } hw->unlockAPI(); return rc; } /*=========================================================================== * FUNCTION : set_CallBacks * * DESCRIPTION: set callbacks for notify and data * * PARAMETERS : * @device : ptr to camera device struct * @notify_cb : notify cb * @data_cb : data cb * @data_cb_timestamp : video data cd with timestamp * @get_memory : ops table for request gralloc memory * @user : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::set_CallBacks(struct camera_device *device, camera_notify_callback notify_cb, camera_data_callback data_cb, camera_data_timestamp_callback data_cb_timestamp, camera_request_memory get_memory, void *user) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } qcamera_sm_evt_setcb_payload_t payload; payload.notify_cb = notify_cb; payload.data_cb = data_cb; payload.data_cb_timestamp = data_cb_timestamp; payload.get_memory = get_memory; payload.user = user; hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_SET_CALLBACKS, (void *)&payload); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_CALLBACKS, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : enable_msg_type * * DESCRIPTION: enable certain msg type * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::enable_msg_type(struct camera_device *device, int32_t msg_type) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_ENABLE_MSG_TYPE, (void *)msg_type); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_ENABLE_MSG_TYPE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : disable_msg_type * * DESCRIPTION: disable certain msg type * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::disable_msg_type(struct camera_device *device, int32_t msg_type) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_DISABLE_MSG_TYPE, (void *)msg_type); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_DISABLE_MSG_TYPE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : msg_type_enabled * * DESCRIPTION: if certain msg type is enabled * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : 1 -- enabled * 0 -- not enabled *==========================================================================*/ int QCamera2HardwareInterface::msg_type_enabled(struct camera_device *device, int32_t msg_type) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_MSG_TYPE_ENABLED, (void *)msg_type); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_MSG_TYPE_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : start_preview * * DESCRIPTION: start preview * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::start_preview(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_START_PREVIEW", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; qcamera_sm_evt_enum_t evt = QCAMERA_SM_EVT_START_PREVIEW; if (hw->isNoDisplayMode()) { evt = QCAMERA_SM_EVT_START_NODISPLAY_PREVIEW; } ret = hw->processAPI(evt, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(evt, &apiResult); ret = apiResult.status; } hw->unlockAPI(); hw->m_bPreviewStarted = true; CDBG_HIGH("[KPI Perf] %s: X", __func__); #ifdef ARCSOFT_FB_SUPPORT if(hw->mArcsoftEnabled==true)hw->beautyshot.Init(); #endif return ret; } /*=========================================================================== * FUNCTION : stop_preview * * DESCRIPTION: stop preview * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::stop_preview(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_STOP_PREVIEW", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_STOP_PREVIEW, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_PREVIEW, &apiResult); } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); #ifdef ARCSOFT_FB_SUPPORT hw->beautyshot.Uninit(); #endif } /*=========================================================================== * FUNCTION : preview_enabled * * DESCRIPTION: if preview is running * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : 1 -- running * 0 -- not running *==========================================================================*/ int QCamera2HardwareInterface::preview_enabled(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_PREVIEW_ENABLED, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PREVIEW_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : store_meta_data_in_buffers * * DESCRIPTION: if need to store meta data in buffers for video frame * * PARAMETERS : * @device : ptr to camera device struct * @enable : flag if enable * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::store_meta_data_in_buffers( struct camera_device *device, int enable) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_STORE_METADATA_IN_BUFS, (void *)enable); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STORE_METADATA_IN_BUFS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : start_recording * * DESCRIPTION: start recording * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::start_recording(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_START_RECORDING", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_START_RECORDING, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_START_RECORDING, &apiResult); ret = apiResult.status; } hw->unlockAPI(); hw->m_bRecordStarted = true; CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : stop_recording * * DESCRIPTION: stop recording * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::stop_recording(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_STOP_RECORDING", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_STOP_RECORDING, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_RECORDING, &apiResult); } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); } /*=========================================================================== * FUNCTION : recording_enabled * * DESCRIPTION: if recording is running * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : 1 -- running * 0 -- not running *==========================================================================*/ int QCamera2HardwareInterface::recording_enabled(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_RECORDING_ENABLED, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RECORDING_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : release_recording_frame * * DESCRIPTION: return recording frame back * * PARAMETERS : * @device : ptr to camera device struct * @opaque : ptr to frame to be returned * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::release_recording_frame( struct camera_device *device, const void *opaque) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("%s: E", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_RELEASE_RECORIDNG_FRAME, (void *)opaque); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RELEASE_RECORIDNG_FRAME, &apiResult); } hw->unlockAPI(); CDBG_HIGH("%s: X", __func__); } /*=========================================================================== * FUNCTION : auto_focus * * DESCRIPTION: start auto focus * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::auto_focus(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s : E PROFILE_AUTO_FOCUS", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_START_AUTO_FOCUS, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_START_AUTO_FOCUS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s : X", __func__); return ret; } /*=========================================================================== * FUNCTION : cancel_auto_focus * * DESCRIPTION: cancel auto focus * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancel_auto_focus(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s : E PROFILE_CANCEL_AUTO_FOCUS", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_STOP_AUTO_FOCUS, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_AUTO_FOCUS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s : X", __func__); return ret; } /*=========================================================================== * FUNCTION : take_picture * * DESCRIPTION: take picture * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::take_picture(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_TAKE_PICTURE", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; /* Prepare snapshot in case LED needs to be flashed */ if (hw->mFlashNeeded == 1 || hw->mParameters.isChromaFlashEnabled()) { ret = hw->processAPI(QCAMERA_SM_EVT_PREPARE_SNAPSHOT, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PREPARE_SNAPSHOT, &apiResult); ret = apiResult.status; } hw->mPrepSnapRun = true; } /* Regardless what the result value for prepare_snapshot, * go ahead with capture anyway. Just like the way autofocus * is handled in capture case. */ /* capture */ ret = hw->processAPI(QCAMERA_SM_EVT_TAKE_PICTURE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_TAKE_PICTURE, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : cancel_picture * * DESCRIPTION: cancel current take picture request * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancel_picture(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_CANCEL_PICTURE", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_CANCEL_PICTURE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_CANCEL_PICTURE, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : set_parameters * * DESCRIPTION: set camera parameters * * PARAMETERS : * @device : ptr to camera device struct * @parms : string of packed parameters * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::set_parameters(struct camera_device *device, const char *parms) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); #if 0 // BEGIN<><2014.12.17><3ndPart Camera unlike local one>Jiangde char s[100], *pcStart = NULL, *pcEnd = NULL; ALOGE("%s parms begin", __func__); pcStart = (char *)parms; while((pcEnd = strchr(pcStart, ';')) != NULL) { if (pcEnd - pcStart <= 100 - 1) { strncpy(s, pcStart, pcEnd - pcStart); s[pcEnd - pcStart] = '\0'; ALOGE("%s %s", __func__, s); } else { ALOGE("%s out of boundary, print all begin", __func__); ALOGE("%s %s", __func__, pcStart); ALOGE("%s out of boundary, print all end", __func__); } pcStart = pcEnd + 1; } if(pcStart != NULL && pcStart[0] != '\0') { ALOGE("%s %s", __func__, pcStart); } ALOGE("%s parms end", __func__); #endif // END<><2014.12.17><3ndPart Camera unlike local one>Jiangde if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_SET_PARAMS, (void *)parms); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_PARAMS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); #ifdef ARCSOFT_FB_SUPPORT //ALOGE("parms===========================%s",parms); //QCameraParameters *qparam = new QCameraParameters((const String8)parms); //qparam->dump(); //hw->mParameters.dump(); int value = hw->mParameters.getInt(hw->mParameters.KEY_FACE_BEAUTY_ENABLED); if(value == 1){ if(hw->mArcsoftEnabled==false)hw->beautyshot.Init(); hw->mArcsoftEnabled = true; }else if(value == 0){ //if(hw->mArcsoftEnabled==true)hw->beautyshot.Uninit();//when prosessing uninit,cos crash hw->mArcsoftEnabled = false; } value = hw->mParameters.getInt(hw->mParameters.KEY_SKIN_SOFTEN_LEVEL); if(value != -1)hw->skinsoften = value; value = hw->mParameters.getInt(hw->mParameters.KEY_SLENDER_FACE_LEVEL); if(value != -1)hw->slenderface = value; value = hw->mParameters.getInt(hw->mParameters.KEY_EYE_ENLARGEMENT_LEVEL); if(value != -1)hw->eyeenlargement = value; ALOGE("mArcsoftEnabled=%d,skinsoften=%d,slenderface=%d,eyeenlargement=%d",hw->mArcsoftEnabled,hw->skinsoften,hw->slenderface,hw->eyeenlargement); #endif return ret; } /*=========================================================================== * FUNCTION : get_parameters * * DESCRIPTION: query camera parameters * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : packed parameters in a string *==========================================================================*/ char* QCamera2HardwareInterface::get_parameters(struct camera_device *device) { char *ret = NULL; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return NULL; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_GET_PARAMS, NULL); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_GET_PARAMS, &apiResult); ret = apiResult.params; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : put_parameters * * DESCRIPTION: return camera parameters string back to HAL * * PARAMETERS : * @device : ptr to camera device struct * @parm : ptr to parameter string to be returned * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::put_parameters(struct camera_device *device, char *parm) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_PUT_PARAMS, (void *)parm); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PUT_PARAMS, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : send_command * * DESCRIPTION: command to be executed * * PARAMETERS : * @device : ptr to camera device struct * @cmd : cmd to be executed * @arg1 : ptr to optional argument1 * @arg2 : ptr to optional argument2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::send_command(struct camera_device *device, int32_t cmd, int32_t arg1, int32_t arg2) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } qcamera_sm_evt_command_payload_t payload; memset(&payload, 0, sizeof(qcamera_sm_evt_command_payload_t)); payload.cmd = cmd; payload.arg1 = arg1; payload.arg2 = arg2; hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_SEND_COMMAND, (void *)&payload); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SEND_COMMAND, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : release * * DESCRIPTION: release camera resource * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::release(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_RELEASE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RELEASE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : dump * * DESCRIPTION: dump camera status * * PARAMETERS : * @device : ptr to camera device struct * @fd : fd for status to be dumped to * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::dump(struct camera_device *device, int fd) { int ret = NO_ERROR; //Log level property is read when "adb shell dumpsys media.camera" is //called so that the log level can be controlled without restarting //media server getLogLevel(); QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_DUMP, (void *)fd); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_DUMP, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : close_camera_device * * DESCRIPTION: close camera device * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::close_camera_device(hw_device_t *hw_dev) { int ret = NO_ERROR; CDBG_HIGH("[KPI Perf] %s: E",__func__); QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>( reinterpret_cast<camera_device_t *>(hw_dev)->priv); if (!hw) { ALOGE("%s: NULL camera device", __func__); return BAD_VALUE; } delete hw; CDBG_HIGH("[KPI Perf] %s: X",__func__); return ret; } /*=========================================================================== * FUNCTION : register_face_image * * DESCRIPTION: register a face image into imaging lib for face authenticatio/ * face recognition * * PARAMETERS : * @device : ptr to camera device struct * @img_ptr : ptr to image buffer * @config : ptr to config about input image, i.e., format, dimension, and etc. * * RETURN : >=0 unique ID of face registerd. * <0 failure. *==========================================================================*/ int QCamera2HardwareInterface::register_face_image(struct camera_device *device, void *img_ptr, cam_pp_offline_src_config_t *config) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } qcamera_sm_evt_reg_face_payload_t payload; memset(&payload, 0, sizeof(qcamera_sm_evt_reg_face_payload_t)); payload.img_ptr = img_ptr; payload.config = config; hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_REG_FACE_IMAGE, (void *)&payload); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_REG_FACE_IMAGE, &apiResult); ret = apiResult.handle; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : QCamera2HardwareInterface * * DESCRIPTION: constructor of QCamera2HardwareInterface * * PARAMETERS : * @cameraId : camera ID * * RETURN : none *==========================================================================*/ QCamera2HardwareInterface::QCamera2HardwareInterface(int cameraId) : mCameraId(cameraId), mCameraHandle(NULL), mCameraOpened(false), mPreviewWindow(NULL), mMsgEnabled(0), mStoreMetaDataInFrame(0), m_stateMachine(this), m_postprocessor(this), m_thermalAdapter(QCameraThermalAdapter::getInstance()), m_cbNotifier(this), m_bShutterSoundPlayed(false), m_bPreviewStarted(false), m_bRecordStarted(false), m_currentFocusState(CAM_AF_SCANNING), m_pPowerModule(NULL), mDumpFrmCnt(0), mDumpSkipCnt(0), mThermalLevel(QCAMERA_THERMAL_NO_ADJUSTMENT), mCancelAutoFocus(false), m_HDRSceneEnabled(false), mLongshotEnabled(false), m_max_pic_width(0), m_max_pic_height(0), mLiveSnapshotThread(0), mIntPicThread(0), mFlashNeeded(false), mCaptureRotation(0), mIs3ALocked(false), mPrepSnapRun(false), mZoomLevel(0), m_bIntEvtPending(false), mSnapshotJob(-1), mPostviewJob(-1), mMetadataJob(-1), mReprocJob(-1), mRawdataJob(-1), mPreviewFrameSkipValid(0) { getLogLevel(); mCameraDevice.common.tag = HARDWARE_DEVICE_TAG; mCameraDevice.common.version = HARDWARE_DEVICE_API_VERSION(1, 0); mCameraDevice.common.close = close_camera_device; mCameraDevice.ops = &mCameraOps; mCameraDevice.priv = this; pthread_mutex_init(&m_lock, NULL); pthread_cond_init(&m_cond, NULL); m_apiResultList = NULL; pthread_mutex_init(&m_evtLock, NULL); pthread_cond_init(&m_evtCond, NULL); memset(&m_evtResult, 0, sizeof(qcamera_api_result_t)); pthread_mutex_init(&m_parm_lock, NULL); pthread_mutex_init(&m_int_lock, NULL); pthread_cond_init(&m_int_cond, NULL); memset(m_channels, 0, sizeof(m_channels)); #ifdef HAS_MULTIMEDIA_HINTS if (hw_get_module(POWER_HARDWARE_MODULE_ID, (const hw_module_t **)&m_pPowerModule)) { ALOGE("%s: %s module not found", __func__, POWER_HARDWARE_MODULE_ID); } #endif memset(mDeffOngoingJobs, 0, sizeof(mDeffOngoingJobs)); //reset preview frame skip memset(&mPreviewFrameSkipIdxRange, 0, sizeof(cam_frame_idx_range_t)); mDefferedWorkThread.launch(defferedWorkRoutine, this); mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_START_DATA_PROC, FALSE, FALSE); #ifdef ARCSOFT_FB_SUPPORT mArcsoftEnabled = false; #endif } /*=========================================================================== * FUNCTION : ~QCamera2HardwareInterface * * DESCRIPTION: destructor of QCamera2HardwareInterface * * PARAMETERS : none * * RETURN : none *==========================================================================*/ QCamera2HardwareInterface::~QCamera2HardwareInterface() { CDBG_HIGH("%s: E", __func__); mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_STOP_DATA_PROC, TRUE, TRUE); mDefferedWorkThread.exit(); closeCamera(); pthread_mutex_destroy(&m_lock); pthread_cond_destroy(&m_cond); pthread_mutex_destroy(&m_evtLock); pthread_cond_destroy(&m_evtCond); pthread_mutex_destroy(&m_parm_lock); CDBG_HIGH("%s: X", __func__); } /*=========================================================================== * FUNCTION : openCamera * * DESCRIPTION: open camera * * PARAMETERS : * @hw_device : double ptr for camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::openCamera(struct hw_device_t **hw_device) { int rc = NO_ERROR; if (mCameraOpened) { *hw_device = NULL; return PERMISSION_DENIED; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_OPEN_CAMERA camera id %d", __func__,mCameraId); rc = openCamera(); if (rc == NO_ERROR){ *hw_device = &mCameraDevice.common; if (m_thermalAdapter.init(this) != 0) { ALOGE("Init thermal adapter failed"); } } else *hw_device = NULL; return rc; } /*=========================================================================== * FUNCTION : openCamera * * DESCRIPTION: open camera * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::openCamera() { int32_t l_curr_width = 0; int32_t l_curr_height = 0; m_max_pic_width = 0; m_max_pic_height = 0; char value[PROPERTY_VALUE_MAX]; int enable_4k2k; int i; if (mCameraHandle) { ALOGE("Failure: Camera already opened"); return ALREADY_EXISTS; } mCameraHandle = camera_open(mCameraId); if (!mCameraHandle) { ALOGE("camera_open failed."); return UNKNOWN_ERROR; } if (NULL == gCamCapability[mCameraId]) initCapabilities(mCameraId,mCameraHandle); mCameraHandle->ops->register_event_notify(mCameraHandle->camera_handle, camEvtHandle, (void *) this); /* get max pic size for jpeg work buf calculation*/ for(i = 0; i < gCamCapability[mCameraId]->picture_sizes_tbl_cnt - 1; i++) { l_curr_width = gCamCapability[mCameraId]->picture_sizes_tbl[i].width; l_curr_height = gCamCapability[mCameraId]->picture_sizes_tbl[i].height; if ((l_curr_width * l_curr_height) > (m_max_pic_width * m_max_pic_height)) { m_max_pic_width = l_curr_width; m_max_pic_height = l_curr_height; } } //reset the preview and video sizes tables in case they were changed earlier copyList(savedSizes[mCameraId].all_preview_sizes, gCamCapability[mCameraId]->preview_sizes_tbl, savedSizes[mCameraId].all_preview_sizes_cnt); gCamCapability[mCameraId]->preview_sizes_tbl_cnt = savedSizes[mCameraId].all_preview_sizes_cnt; copyList(savedSizes[mCameraId].all_video_sizes, gCamCapability[mCameraId]->video_sizes_tbl, savedSizes[mCameraId].all_video_sizes_cnt); gCamCapability[mCameraId]->video_sizes_tbl_cnt = savedSizes[mCameraId].all_video_sizes_cnt; //check if video size 4k x 2k support is enabled property_get("persist.camera.4k2k.enable", value, "0"); enable_4k2k = atoi(value) > 0 ? 1 : 0; ALOGD("%s: enable_4k2k is %d", __func__, enable_4k2k); if (!enable_4k2k) { //if the 4kx2k size exists in the supported preview size or //supported video size remove it bool found; cam_dimension_t true_size_4k_2k; cam_dimension_t size_4k_2k; true_size_4k_2k.width = 4096; true_size_4k_2k.height = 2160; size_4k_2k.width = 3840; size_4k_2k.height = 2160; found = removeSizeFromList(gCamCapability[mCameraId]->preview_sizes_tbl, gCamCapability[mCameraId]->preview_sizes_tbl_cnt, true_size_4k_2k); if (found) { gCamCapability[mCameraId]->preview_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->preview_sizes_tbl, gCamCapability[mCameraId]->preview_sizes_tbl_cnt, size_4k_2k); if (found) { gCamCapability[mCameraId]->preview_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->video_sizes_tbl, gCamCapability[mCameraId]->video_sizes_tbl_cnt, true_size_4k_2k); if (found) { gCamCapability[mCameraId]->video_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->video_sizes_tbl, gCamCapability[mCameraId]->video_sizes_tbl_cnt, size_4k_2k); if (found) { gCamCapability[mCameraId]->video_sizes_tbl_cnt--; } } int32_t rc = m_postprocessor.init(jpegEvtHandle, this); if (rc != 0) { ALOGE("Init Postprocessor failed"); mCameraHandle->ops->close_camera(mCameraHandle->camera_handle); mCameraHandle = NULL; return UNKNOWN_ERROR; } // update padding info from jpeg cam_padding_info_t padding_info; m_postprocessor.getJpegPaddingReq(padding_info); if (gCamCapability[mCameraId]->padding_info.width_padding < padding_info.width_padding) { gCamCapability[mCameraId]->padding_info.width_padding = padding_info.width_padding; } if (gCamCapability[mCameraId]->padding_info.height_padding < padding_info.height_padding) { gCamCapability[mCameraId]->padding_info.height_padding = padding_info.height_padding; } if (gCamCapability[mCameraId]->padding_info.plane_padding < padding_info.plane_padding) { gCamCapability[mCameraId]->padding_info.plane_padding = padding_info.plane_padding; } mParameters.init(gCamCapability[mCameraId], mCameraHandle, this, this); mCameraOpened = true; return NO_ERROR; } /*=========================================================================== * FUNCTION : closeCamera * * DESCRIPTION: close camera * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::closeCamera() { int rc = NO_ERROR; int i; CDBG_HIGH("%s: E", __func__); if (!mCameraOpened) { return NO_ERROR; } pthread_mutex_lock(&m_parm_lock); // set open flag to false mCameraOpened = false; // deinit Parameters mParameters.deinit(); pthread_mutex_unlock(&m_parm_lock); // exit notifier m_cbNotifier.exit(); // stop and deinit postprocessor m_postprocessor.stop(); m_postprocessor.deinit(); //free all pending api results here if(m_apiResultList != NULL) { api_result_list *apiResultList = m_apiResultList; api_result_list *apiResultListNext; while (apiResultList != NULL) { apiResultListNext = apiResultList->next; free(apiResultList); apiResultList = apiResultListNext; } } m_thermalAdapter.deinit(); // delete all channels if not already deleted for (i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { m_channels[i]->stop(); delete m_channels[i]; m_channels[i] = NULL; } } rc = mCameraHandle->ops->close_camera(mCameraHandle->camera_handle); mCameraHandle = NULL; CDBG_HIGH("%s: X", __func__); return rc; } #define DATA_PTR(MEM_OBJ,INDEX) MEM_OBJ->getPtr( INDEX ) /*=========================================================================== * FUNCTION : initCapabilities * * DESCRIPTION: initialize camera capabilities in static data struct * * PARAMETERS : * @cameraId : camera Id * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::initCapabilities(int cameraId,mm_camera_vtbl_t *cameraHandle) { int rc = NO_ERROR; QCameraHeapMemory *capabilityHeap = NULL; /* Allocate memory for capability buffer */ capabilityHeap = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); rc = capabilityHeap->allocate(1, sizeof(cam_capability_t)); if(rc != OK) { ALOGE("%s: No memory for cappability", __func__); goto allocate_failed; } /* Map memory for capability buffer */ memset(DATA_PTR(capabilityHeap,0), 0, sizeof(cam_capability_t)); rc = cameraHandle->ops->map_buf(cameraHandle->camera_handle, CAM_MAPPING_BUF_TYPE_CAPABILITY, capabilityHeap->getFd(0), sizeof(cam_capability_t)); if(rc < 0) { ALOGE("%s: failed to map capability buffer", __func__); goto map_failed; } /* Query Capability */ rc = cameraHandle->ops->query_capability(cameraHandle->camera_handle); if(rc < 0) { ALOGE("%s: failed to query capability",__func__); goto query_failed; } gCamCapability[cameraId] = (cam_capability_t *)malloc(sizeof(cam_capability_t)); if (!gCamCapability[cameraId]) { ALOGE("%s: out of memory", __func__); goto query_failed; } memcpy(gCamCapability[cameraId], DATA_PTR(capabilityHeap,0), sizeof(cam_capability_t)); //copy the preview sizes and video sizes lists because they //might be changed later copyList(gCamCapability[cameraId]->preview_sizes_tbl, savedSizes[cameraId].all_preview_sizes, gCamCapability[cameraId]->preview_sizes_tbl_cnt); savedSizes[cameraId].all_preview_sizes_cnt = gCamCapability[cameraId]->preview_sizes_tbl_cnt; copyList(gCamCapability[cameraId]->video_sizes_tbl, savedSizes[cameraId].all_video_sizes, gCamCapability[cameraId]->video_sizes_tbl_cnt); savedSizes[cameraId].all_video_sizes_cnt = gCamCapability[cameraId]->video_sizes_tbl_cnt; rc = NO_ERROR; query_failed: cameraHandle->ops->unmap_buf(cameraHandle->camera_handle, CAM_MAPPING_BUF_TYPE_CAPABILITY); map_failed: capabilityHeap->deallocate(); delete capabilityHeap; allocate_failed: return rc; } /*=========================================================================== * FUNCTION : getCapabilities * * DESCRIPTION: query camera capabilities * * PARAMETERS : * @cameraId : camera Id * @info : camera info struct to be filled in with camera capabilities * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::getCapabilities(int cameraId, struct camera_info *info) { int rc = NO_ERROR; struct camera_info *p_info; pthread_mutex_lock(&g_camlock); p_info = get_cam_info(cameraId); memcpy(info, p_info, sizeof (struct camera_info)); pthread_mutex_unlock(&g_camlock); return rc; } /*=========================================================================== * FUNCTION : prepareTorchCamera * * DESCRIPTION: initializes the camera ( if needed ) * so torch can be configured. * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::prepareTorchCamera() { int rc = NO_ERROR; if ( ( !m_stateMachine.isPreviewRunning() ) && ( m_channels[QCAMERA_CH_TYPE_PREVIEW] == NULL ) ) { rc = addChannel(QCAMERA_CH_TYPE_PREVIEW); } return rc; } /*=========================================================================== * FUNCTION : releaseTorchCamera * * DESCRIPTION: releases all previously acquired camera resources ( if any ) * needed for torch configuration. * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::releaseTorchCamera() { if ( !m_stateMachine.isPreviewRunning() && ( m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL ) ) { delete m_channels[QCAMERA_CH_TYPE_PREVIEW]; m_channels[QCAMERA_CH_TYPE_PREVIEW] = NULL; } return NO_ERROR; } /*=========================================================================== * FUNCTION : getBufNumRequired * * DESCRIPTION: return number of stream buffers needed for given stream type * * PARAMETERS : * @stream_type : type of stream * * RETURN : number of buffers needed *==========================================================================*/ uint8_t QCamera2HardwareInterface::getBufNumRequired(cam_stream_type_t stream_type) { int bufferCnt = 0; int minCaptureBuffers = mParameters.getNumOfSnapshots(); int zslQBuffers = mParameters.getZSLQueueDepth(); int minCircularBufNum = mParameters.getMaxUnmatchedFramesInQueue() + CAMERA_MIN_JPEG_ENCODING_BUFFERS; int minUndequeCount = 0; int minPPBufs = mParameters.getMinPPBufs(); int maxStreamBuf = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; if (!isNoDisplayMode()) { if(mPreviewWindow != NULL) { if (mPreviewWindow->get_min_undequeued_buffer_count(mPreviewWindow,&minUndequeCount) != 0) { ALOGE("get_min_undequeued_buffer_count failed"); } } else { //preview window might not be set at this point. So, query directly //from BufferQueue implementation of gralloc buffers. minUndequeCount = BufferQueue::MIN_UNDEQUEUED_BUFFERS; } } // Get buffer count for the particular stream type switch (stream_type) { case CAM_STREAM_TYPE_PREVIEW: { if (mParameters.isZSLMode()) { /* We need to add two extra streming buffers to add flexibility in forming matched super buf in ZSL queue. with number being 'zslQBuffers + minCircularBufNum' we see preview buffers sometimes get dropped at CPP and super buf is not forming in ZSL Q for long time. */ bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; } else { bufferCnt = CAMERA_MIN_STREAMING_BUFFERS + mParameters.getMaxUnmatchedFramesInQueue(); } bufferCnt += minUndequeCount; } break; case CAM_STREAM_TYPE_POSTVIEW: { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } bufferCnt += minUndequeCount; /* TODO: This is Temporary change to overcome the two BufDone/Buf Diverts coming consecutively without SOF in HDR/AE bracketing use case */ if (mParameters.isHDREnabled() || mParameters.isAEBracketEnabled() ) bufferCnt += 2; } break; case CAM_STREAM_TYPE_SNAPSHOT: { if (mParameters.isZSLMode() || mLongshotEnabled) { if (minCaptureBuffers == 1 && !mLongshotEnabled) { // Single ZSL snapshot case bufferCnt = zslQBuffers + CAMERA_MIN_STREAMING_BUFFERS + mParameters.getNumOfExtraBuffersForImageProc(); } else { // ZSL Burst or Longshot case bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraBuffersForImageProc(); } } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } } break; case CAM_STREAM_TYPE_RAW: if (mParameters.isZSLMode()) { bufferCnt = zslQBuffers + minCircularBufNum; } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } break; case CAM_STREAM_TYPE_VIDEO: { bufferCnt = CAMERA_MIN_VIDEO_BUFFERS; } break; case CAM_STREAM_TYPE_METADATA: { if (mParameters.isZSLMode()) { // MetaData buffers should be >= (Preview buffers-minUndequeCount) bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getMaxUnmatchedFramesInQueue() + CAMERA_MIN_STREAMING_BUFFERS + mParameters.getNumOfExtraBuffersForImageProc(); } if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } bufferCnt += minUndequeCount; } break; case CAM_STREAM_TYPE_OFFLINE_PROC: { bufferCnt = minCaptureBuffers; if (mLongshotEnabled) { bufferCnt = CAMERA_LONGSHOT_STAGES; } if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } break; case CAM_STREAM_TYPE_DEFAULT: case CAM_STREAM_TYPE_MAX: default: bufferCnt = 0; break; } ALOGD("%s: Allocating %d buffers for streamtype %d",__func__,bufferCnt,stream_type); return bufferCnt; } /*=========================================================================== * FUNCTION : allocateStreamBuf * * DESCRIPTION: alocate stream buffers * * PARAMETERS : * @stream_type : type of stream * @size : size of buffer * @stride : stride of buffer * @scanline : scanline of buffer * @bufferCnt : [IN/OUT] minimum num of buffers to be allocated. * could be modified during allocation if more buffers needed * * RETURN : ptr to a memory obj that holds stream buffers. * NULL if failed *==========================================================================*/ QCameraMemory *QCamera2HardwareInterface::allocateStreamBuf(cam_stream_type_t stream_type, int size, int stride, int scanline, uint8_t &bufferCnt) { int rc = NO_ERROR; QCameraMemory *mem = NULL; bool bCachedMem = QCAMERA_ION_USE_CACHE; bool bPoolMem = false; char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.mem.usepool", value, "1"); if (atoi(value) == 1) { bPoolMem = true; } // Allocate stream buffer memory object switch (stream_type) { case CAM_STREAM_TYPE_PREVIEW: { if (isNoDisplayMode()) { mem = new QCameraStreamMemory(mGetMemory, bCachedMem, (bPoolMem) ? &m_memoryPool : NULL, stream_type); } else { cam_dimension_t dim; QCameraGrallocMemory *grallocMemory = new QCameraGrallocMemory(mGetMemory); mParameters.getStreamDimension(stream_type, dim); if (grallocMemory) grallocMemory->setWindowInfo(mPreviewWindow, dim.width, dim.height, stride, scanline, mParameters.getPreviewHalPixelFormat()); mem = grallocMemory; } } break; case CAM_STREAM_TYPE_POSTVIEW: { if (isPreviewRestartEnabled() || isNoDisplayMode()) { mem = new QCameraStreamMemory(mGetMemory, bCachedMem); } else { cam_dimension_t dim; QCameraGrallocMemory *grallocMemory = new QCameraGrallocMemory(mGetMemory); mParameters.getStreamDimension(stream_type, dim); if (grallocMemory) { grallocMemory->setWindowInfo(mPreviewWindow, dim.width, dim.height, stride, scanline, mParameters.getPreviewHalPixelFormat()); } mem = grallocMemory; } } break; case CAM_STREAM_TYPE_SNAPSHOT: case CAM_STREAM_TYPE_RAW: case CAM_STREAM_TYPE_METADATA: case CAM_STREAM_TYPE_OFFLINE_PROC: mem = new QCameraStreamMemory(mGetMemory, bCachedMem, (bPoolMem) ? &m_memoryPool : NULL, stream_type); break; case CAM_STREAM_TYPE_VIDEO: { char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.mem.usecache", value, "1"); if (atoi(value) == 0) { bCachedMem = QCAMERA_ION_USE_NOCACHE; } ALOGD("%s: vidoe buf using cached memory = %d", __func__, bCachedMem); mem = new QCameraVideoMemory(mGetMemory, bCachedMem); } break; case CAM_STREAM_TYPE_DEFAULT: case CAM_STREAM_TYPE_MAX: default: break; } if (!mem) { return NULL; } if (bufferCnt > 0) { rc = mem->allocate(bufferCnt, size); if (rc < 0) { delete mem; return NULL; } bufferCnt = mem->getCnt(); } return mem; } /*=========================================================================== * FUNCTION : allocateMoreStreamBuf * * DESCRIPTION: alocate more stream buffers from the memory object * * PARAMETERS : * @mem_obj : memory object ptr * @size : size of buffer * @bufferCnt : [IN/OUT] additional number of buffers to be allocated. * output will be the number of total buffers * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::allocateMoreStreamBuf(QCameraMemory *mem_obj, int size, uint8_t &bufferCnt) { int rc = NO_ERROR; if (bufferCnt > 0) { rc = mem_obj->allocateMore(bufferCnt, size); bufferCnt = mem_obj->getCnt(); } return rc; } /*=========================================================================== * FUNCTION : allocateStreamInfoBuf * * DESCRIPTION: alocate stream info buffer * * PARAMETERS : * @stream_type : type of stream * * RETURN : ptr to a memory obj that holds stream info buffer. * NULL if failed *==========================================================================*/ QCameraHeapMemory *QCamera2HardwareInterface::allocateStreamInfoBuf( cam_stream_type_t stream_type) { int rc = NO_ERROR; QCameraHeapMemory *streamInfoBuf = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); if (!streamInfoBuf) { ALOGE("allocateStreamInfoBuf: Unable to allocate streamInfo object"); return NULL; } rc = streamInfoBuf->allocate(1, sizeof(cam_stream_info_t)); if (rc < 0) { ALOGE("allocateStreamInfoBuf: Failed to allocate stream info memory"); delete streamInfoBuf; return NULL; } cam_stream_info_t *streamInfo = (cam_stream_info_t *)streamInfoBuf->getPtr(0); memset(streamInfo, 0, sizeof(cam_stream_info_t)); streamInfo->stream_type = stream_type; rc = mParameters.getStreamFormat(stream_type, streamInfo->fmt); rc = mParameters.getStreamDimension(stream_type, streamInfo->dim); rc = mParameters.getStreamRotation(stream_type, streamInfo->pp_config, streamInfo->dim); streamInfo->num_bufs = getBufNumRequired(stream_type); streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; ALOGD("%s: stream_type %d, stream format %d,stream dimension %dx%d, num_bufs %d\n", __func__, stream_type, streamInfo->fmt, streamInfo->dim.width, streamInfo->dim.height, streamInfo->num_bufs); switch (stream_type) { case CAM_STREAM_TYPE_SNAPSHOT: case CAM_STREAM_TYPE_RAW: if ((mParameters.isZSLMode() && mParameters.getRecordingHintValue() != true) || mLongshotEnabled) { streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; } else { streamInfo->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfo->num_of_burst = mParameters.getNumOfSnapshots() + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc(); } break; case CAM_STREAM_TYPE_POSTVIEW: if (mLongshotEnabled) { streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; } else { streamInfo->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfo->num_of_burst = mParameters.getNumOfSnapshots() + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc(); } break; case CAM_STREAM_TYPE_VIDEO: streamInfo->useAVTimer = mParameters.isAVTimerEnabled(); case CAM_STREAM_TYPE_PREVIEW: if (mParameters.getRecordingHintValue()) { const char* dis_param = mParameters.get(QCameraParameters::KEY_QC_DIS); bool disEnabled = (dis_param != NULL) && !strcmp(dis_param,QCameraParameters::VALUE_ENABLE); if(disEnabled) { char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.is_type", value, "0"); streamInfo->is_type = static_cast<cam_is_type_t>(atoi(value)); } else { streamInfo->is_type = IS_TYPE_NONE; } } break; default: break; } if ((!isZSLMode() || (isZSLMode() && (stream_type != CAM_STREAM_TYPE_SNAPSHOT))) && !mParameters.isHDREnabled()) { //set flip mode based on Stream type; int flipMode = mParameters.getFlipMode(stream_type); if (flipMode > 0) { streamInfo->pp_config.feature_mask |= CAM_QCOM_FEATURE_FLIP; streamInfo->pp_config.flip = flipMode; } } return streamInfoBuf; } /*=========================================================================== * FUNCTION : setPreviewWindow * * DESCRIPTION: set preview window impl * * PARAMETERS : * @window : ptr to window ops table struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::setPreviewWindow( struct preview_stream_ops *window) { mPreviewWindow = window; return NO_ERROR; } /*=========================================================================== * FUNCTION : setCallBacks * * DESCRIPTION: set callbacks impl * * PARAMETERS : * @notify_cb : notify cb * @data_cb : data cb * @data_cb_timestamp : data cb with time stamp * @get_memory : request memory ops table * @user : user data ptr * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::setCallBacks(camera_notify_callback notify_cb, camera_data_callback data_cb, camera_data_timestamp_callback data_cb_timestamp, camera_request_memory get_memory, void *user) { mNotifyCb = notify_cb; mDataCb = data_cb; mDataCbTimestamp = data_cb_timestamp; mGetMemory = get_memory; mCallbackCookie = user; m_cbNotifier.setCallbacks(notify_cb, data_cb, data_cb_timestamp, user); return NO_ERROR; } /*=========================================================================== * FUNCTION : enableMsgType * * DESCRIPTION: enable msg type impl * * PARAMETERS : * @msg_type : msg type mask to be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::enableMsgType(int32_t msg_type) { mMsgEnabled |= msg_type; CDBG_HIGH("%s (0x%x) : mMsgEnabled = 0x%x", __func__, msg_type , mMsgEnabled ); return NO_ERROR; } /*=========================================================================== * FUNCTION : disableMsgType * * DESCRIPTION: disable msg type impl * * PARAMETERS : * @msg_type : msg type mask to be disabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::disableMsgType(int32_t msg_type) { mMsgEnabled &= ~msg_type; CDBG_HIGH("%s (0x%x) : mMsgEnabled = 0x%x", __func__, msg_type , mMsgEnabled ); return NO_ERROR; } /*=========================================================================== * FUNCTION : msgTypeEnabled * * DESCRIPTION: impl to determine if certain msg_type is enabled * * PARAMETERS : * @msg_type : msg type mask * * RETURN : 0 -- not enabled * none 0 -- enabled *==========================================================================*/ int QCamera2HardwareInterface::msgTypeEnabled(int32_t msg_type) { return (mMsgEnabled & msg_type); } /*=========================================================================== * FUNCTION : msgTypeEnabledWithLock * * DESCRIPTION: impl to determine if certain msg_type is enabled with lock * * PARAMETERS : * @msg_type : msg type mask * * RETURN : 0 -- not enabled * none 0 -- enabled *==========================================================================*/ int QCamera2HardwareInterface::msgTypeEnabledWithLock(int32_t msg_type) { int enabled = 0; lockAPI(); enabled = mMsgEnabled & msg_type; unlockAPI(); return enabled; } /*=========================================================================== * FUNCTION : startPreview * * DESCRIPTION: start preview impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::startPreview() { int32_t rc = NO_ERROR; CDBG_HIGH("%s: E", __func__); // start preview stream if (mParameters.isZSLMode() && mParameters.getRecordingHintValue() !=true) { rc = startChannel(QCAMERA_CH_TYPE_ZSL); } else { rc = startChannel(QCAMERA_CH_TYPE_PREVIEW); /* CAF needs cancel auto focus to resume after snapshot. Focus should be locked till take picture is done. In Non-zsl case if focus mode is CAF then calling cancel auto focus to resume CAF. */ cam_focus_mode_type focusMode = mParameters.getFocusMode(); if (focusMode == CAM_FOCUS_MODE_CONTINOUS_PICTURE) mCameraHandle->ops->cancel_auto_focus(mCameraHandle->camera_handle); } CDBG_HIGH("%s: X", __func__); //#ifdef ARCSOFT_FB_SUPPORT // beautyshot.Init(); //flf.Init(); //#endif return rc; } /*=========================================================================== * FUNCTION : stopPreview * * DESCRIPTION: stop preview impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopPreview() { CDBG_HIGH("%s: E", __func__); // stop preview stream stopChannel(QCAMERA_CH_TYPE_ZSL); stopChannel(QCAMERA_CH_TYPE_PREVIEW); //reset preview frame skip mPreviewFrameSkipValid = 0; memset(&mPreviewFrameSkipIdxRange, 0, sizeof(cam_frame_idx_range_t)); // delete all channels from preparePreview unpreparePreview(); CDBG_HIGH("%s: X", __func__); //#ifdef ARCSOFT_FB_SUPPORT // beautyshot.Uninit(); //flf.Uninit(); //#endif return NO_ERROR; } /*=========================================================================== * FUNCTION : storeMetaDataInBuffers * * DESCRIPTION: enable store meta data in buffers for video frames impl * * PARAMETERS : * @enable : flag if need enable * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::storeMetaDataInBuffers(int enable) { mStoreMetaDataInFrame = enable; return NO_ERROR; } /*=========================================================================== * FUNCTION : startRecording * * DESCRIPTION: start recording impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::startRecording() { int32_t rc = NO_ERROR; CDBG_HIGH("%s: E", __func__); if (mParameters.getRecordingHintValue() == false) { CDBG_HIGH("%s: start recording when hint is false, stop preview first", __func__); stopPreview(); // Set recording hint to TRUE mParameters.updateRecordingHintValue(TRUE); rc = preparePreview(); if (rc == NO_ERROR) { rc = startChannel(QCAMERA_CH_TYPE_PREVIEW); } } if (rc == NO_ERROR) { rc = startChannel(QCAMERA_CH_TYPE_VIDEO); } #ifdef HAS_MULTIMEDIA_HINTS if (rc == NO_ERROR) { if (m_pPowerModule) { if (m_pPowerModule->powerHint) { m_pPowerModule->powerHint(m_pPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=1"); } } } #endif CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : stopRecording * * DESCRIPTION: stop recording impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopRecording() { CDBG_HIGH("%s: E", __func__); int rc = stopChannel(QCAMERA_CH_TYPE_VIDEO); #ifdef HAS_MULTIMEDIA_HINTS if (m_pPowerModule) { if (m_pPowerModule->powerHint) { m_pPowerModule->powerHint(m_pPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=0"); } } #endif CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : releaseRecordingFrame * * DESCRIPTION: return video frame impl * * PARAMETERS : * @opaque : ptr to video frame to be returned * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::releaseRecordingFrame(const void * opaque) { int32_t rc = UNKNOWN_ERROR; QCameraVideoChannel *pChannel = (QCameraVideoChannel *)m_channels[QCAMERA_CH_TYPE_VIDEO]; CDBG_HIGH("%s: opaque data = %p", __func__,opaque); if(pChannel != NULL) { rc = pChannel->releaseFrame(opaque, mStoreMetaDataInFrame > 0); } return rc; } /*=========================================================================== * FUNCTION : autoFocus * * DESCRIPTION: start auto focus impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::autoFocus() { int rc = NO_ERROR; setCancelAutoFocus(false); cam_focus_mode_type focusMode = mParameters.getFocusMode(); CDBG_HIGH("[AF_DBG] %s: focusMode=%d, m_currentFocusState=%d, m_bAFRunning=%d", __func__, focusMode, m_currentFocusState, isAFRunning()); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: rc = mCameraHandle->ops->do_auto_focus(mCameraHandle->camera_handle); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: ALOGE("%s: No ops in focusMode (%d)", __func__, focusMode); rc = sendEvtNotify(CAMERA_MSG_FOCUS, true, 0); break; } return rc; } /*=========================================================================== * FUNCTION : cancelAutoFocus * * DESCRIPTION: cancel auto focus impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelAutoFocus() { int rc = NO_ERROR; setCancelAutoFocus(true); cam_focus_mode_type focusMode = mParameters.getFocusMode(); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: rc = mCameraHandle->ops->cancel_auto_focus(mCameraHandle->camera_handle); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: CDBG("%s: No ops in focusMode (%d)", __func__, focusMode); break; } return rc; } /*=========================================================================== * FUNCTION : processUFDumps * * DESCRIPTION: process UF jpeg dumps for refocus support * * PARAMETERS : * @evt : payload of jpeg event, including information about jpeg encoding * status, jpeg size and so on. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * * NOTE : none *==========================================================================*/ bool QCamera2HardwareInterface::processUFDumps(qcamera_jpeg_evt_payload_t *evt) { bool ret = true; if (mParameters.isUbiRefocus()) { int index = getOutputImageCount(); bool allFocusImage = (index == ((int)mParameters.UfOutputCount()-1)); char name[CAM_FN_CNT]; camera_memory_t *jpeg_mem = NULL; omx_jpeg_ouput_buf_t *jpeg_out = NULL; uint32_t dataLen; uint8_t *dataPtr; if (!m_postprocessor.getJpegMemOpt()) { dataLen = evt->out_data.buf_filled_len; dataPtr = evt->out_data.buf_vaddr; } else { jpeg_out = (omx_jpeg_ouput_buf_t*) evt->out_data.buf_vaddr; jpeg_mem = (camera_memory_t *)jpeg_out->mem_hdl; dataPtr = (uint8_t *)jpeg_mem->data; dataLen = jpeg_mem->size; } if (allFocusImage) { strncpy(name, "AllFocusImage", CAM_FN_CNT - 1); index = -1; } else { strncpy(name, "0", CAM_FN_CNT - 1); } CAM_DUMP_TO_FILE("/data/local/ubifocus", name, index, "jpg", dataPtr, dataLen); CDBG_HIGH("%s:%d] Dump the image %d %d allFocusImage %d", __func__, __LINE__, getOutputImageCount(), index, allFocusImage); setOutputImageCount(getOutputImageCount() + 1); if (!allFocusImage) { ret = false; } } return ret; } /*=========================================================================== * FUNCTION : configureAdvancedCapture * * DESCRIPTION: configure Advanced Capture. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAdvancedCapture() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; setOutputImageCount(0); mParameters.setDisplayFrame(FALSE); if (mParameters.isUbiFocusEnabled()) { rc = configureAFBracketing(); } else if (mParameters.isOptiZoomEnabled()) { rc = configureOptiZoom(); } else if (mParameters.isChromaFlashEnabled()) { rc = configureFlashBracketing(); } else if (mParameters.isHDREnabled()) { rc = configureZSLHDRBracketing(); } else if (mParameters.isAEBracketEnabled()) { rc = configureAEBracketing(); } else { ALOGE("%s: No Advanced Capture feature enabled!! ", __func__); rc = BAD_VALUE; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureAFBracketing * * DESCRIPTION: configure AF Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAFBracketing(bool enable) { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; cam_af_bracketing_t *af_bracketing_need; af_bracketing_need = &gCamCapability[mCameraId]->ubifocus_af_bracketing_need; //Enable AF Bracketing. cam_af_bracketing_t afBracket; memset(&afBracket, 0, sizeof(cam_af_bracketing_t)); afBracket.enable = enable; afBracket.burst_count = af_bracketing_need->burst_count; for(int8_t i = 0; i < MAX_AF_BRACKETING_VALUES; i++) { afBracket.focus_steps[i] = af_bracketing_need->focus_steps[i]; CDBG_HIGH("%s: focus_step[%d] = %d", __func__, i, afBracket.focus_steps[i]); } //Send cmd to backend to set AF Bracketing for Ubi Focus. rc = mParameters.commitAFBracket(afBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AF bracketing", __func__); return rc; } if (enable) { mParameters.set3ALock(QCameraParameters::VALUE_TRUE); mIs3ALocked = true; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureFlashBracketing * * DESCRIPTION: configure Flash Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureFlashBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; cam_flash_bracketing_t flashBracket; memset(&flashBracket, 0, sizeof(cam_flash_bracketing_t)); flashBracket.enable = 1; //TODO: Hardcoded value. flashBracket.burst_count = 2; //Send cmd to backend to set Flash Bracketing for chroma flash. rc = mParameters.commitFlashBracket(flashBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AF bracketing", __func__); } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureZSLHDRBracketing * * DESCRIPTION: configure HDR Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureZSLHDRBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; // 'values' should be in "idx1,idx2,idx3,..." format uint8_t hdrFrameCount = gCamCapability[mCameraId]->hdr_bracketing_setting.num_frames; CDBG_HIGH("%s : HDR values %d, %d frame count: %d", __func__, (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[0], (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[1], hdrFrameCount); // Enable AE Bracketing for HDR cam_exp_bracketing_t aeBracket; memset(&aeBracket, 0, sizeof(cam_exp_bracketing_t)); aeBracket.mode = gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.mode; String8 tmp; for ( unsigned int i = 0; i < hdrFrameCount ; i++ ) { tmp.appendFormat("%d", (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[i]); tmp.append(","); } if (mParameters.isHDR1xFrameEnabled() && mParameters.isHDR1xExtraBufferNeeded()) { tmp.appendFormat("%d", 0); tmp.append(","); } if( !tmp.isEmpty() && ( MAX_EXP_BRACKETING_LENGTH > tmp.length() ) ) { //Trim last comma memset(aeBracket.values, '\0', MAX_EXP_BRACKETING_LENGTH); memcpy(aeBracket.values, tmp.string(), tmp.length() - 1); } CDBG_HIGH("%s : HDR config values %s", __func__, aeBracket.values); rc = mParameters.setHDRAEBracket(aeBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure HDR bracketing", __func__); return rc; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureAEBracketing * * DESCRIPTION: configure AE Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAEBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; rc = mParameters.setAEBracketing(); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AE bracketing", __func__); return rc; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureOptiZoom * * DESCRIPTION: configure Opti Zoom. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureOptiZoom() { int32_t rc = NO_ERROR; //store current zoom level. mZoomLevel = (uint8_t) mParameters.getInt(CameraParameters::KEY_ZOOM); //set zoom level to 1x; mParameters.setAndCommitZoom(0); mParameters.set3ALock(QCameraParameters::VALUE_TRUE); mIs3ALocked = true; return rc; } /*=========================================================================== * FUNCTION : startAdvancedCapture * * DESCRIPTION: starts advanced capture based on capture type * * PARAMETERS : * @pChannel : channel. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::startAdvancedCapture( QCameraPicChannel *pChannel) { CDBG_HIGH("%s: Start bracketig",__func__); int32_t rc = NO_ERROR; if(mParameters.isUbiFocusEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_AF_BRACKETING); } else if (mParameters.isChromaFlashEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_FLASH_BRACKETING); } else if (mParameters.isHDREnabled() || mParameters.isAEBracketEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_AE_BRACKETING); } else if (mParameters.isOptiZoomEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_ZOOM_1X); } else { ALOGE("%s: No Advanced Capture feature enabled!",__func__); rc = BAD_VALUE; } return rc; } /*=========================================================================== * FUNCTION : takePicture * * DESCRIPTION: take picture impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takePicture() { int rc = NO_ERROR; uint8_t numSnapshots = mParameters.getNumOfSnapshots(); #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Init(); #endif if (mParameters.isUbiFocusEnabled() || mParameters.isOptiZoomEnabled() || mParameters.isHDREnabled() || mParameters.isChromaFlashEnabled() || mParameters.isAEBracketEnabled()) { rc = configureAdvancedCapture(); if (rc == NO_ERROR) { numSnapshots = mParameters.getBurstCountForAdvancedCapture(); } } CDBG_HIGH("%s: numSnapshot = %d",__func__, numSnapshots); getOrientation(); CDBG_HIGH("%s: E", __func__); if (mParameters.isZSLMode()) { QCameraPicChannel *pZSLChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pZSLChannel) { // start postprocessor rc = m_postprocessor.start(pZSLChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); return rc; } if (mParameters.isUbiFocusEnabled() || mParameters.isOptiZoomEnabled() || mParameters.isHDREnabled() || mParameters.isChromaFlashEnabled() || mParameters.isAEBracketEnabled()) { rc = startAdvancedCapture(pZSLChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start zsl advanced capture", __func__); return rc; } } if (mLongshotEnabled && mPrepSnapRun) { mCameraHandle->ops->start_zsl_snapshot( mCameraHandle->camera_handle, pZSLChannel->getMyHandle()); } rc = pZSLChannel->takePicture(numSnapshots); if (rc != NO_ERROR) { ALOGE("%s: cannot take ZSL picture", __func__); m_postprocessor.stop(); return rc; } } else { ALOGE("%s: ZSL channel is NULL", __func__); return UNKNOWN_ERROR; } } else { // start snapshot if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { if (!isLongshotEnabled()) { rc = addCaptureChannel(); // normal capture case // need to stop preview channel stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); waitDefferedWork(mSnapshotJob); waitDefferedWork(mMetadataJob); waitDefferedWork(mRawdataJob); { DefferWorkArgs args; DefferAllocBuffArgs allocArgs; memset(&args, 0, sizeof(DefferWorkArgs)); memset(&allocArgs, 0, sizeof(DefferAllocBuffArgs)); allocArgs.ch = m_channels[QCAMERA_CH_TYPE_CAPTURE]; allocArgs.type = CAM_STREAM_TYPE_POSTVIEW; args.allocArgs = allocArgs; mPostviewJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mPostviewJob == -1) rc = UNKNOWN_ERROR; } waitDefferedWork(mPostviewJob); } else { // normal capture case // need to stop preview channel stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); rc = addCaptureChannel(); } if ((rc == NO_ERROR) && (NULL != m_channels[QCAMERA_CH_TYPE_CAPTURE])) { // configure capture channel rc = m_channels[QCAMERA_CH_TYPE_CAPTURE]->config(); if (rc != NO_ERROR) { ALOGE("%s: cannot configure capture channel", __func__); delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } DefferWorkArgs args; memset(&args, 0, sizeof(DefferWorkArgs)); args.pprocArgs = m_channels[QCAMERA_CH_TYPE_CAPTURE]; mReprocJob = queueDefferedWork(CMD_DEFF_PPROC_START, args); // start catpure channel rc = m_channels[QCAMERA_CH_TYPE_CAPTURE]->start(); if (rc != NO_ERROR) { ALOGE("%s: cannot start capture channel", __func__); delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } QCameraPicChannel *pCapChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_CAPTURE]; if (NULL != pCapChannel) { if (mParameters.isUbiFocusEnabled()| mParameters.isChromaFlashEnabled()) { rc = startAdvancedCapture(pCapChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start advanced capture", __func__); return rc; } } } if ( mLongshotEnabled ) { rc = longShot(); if (NO_ERROR != rc) { delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } } } else { ALOGE("%s: cannot add capture channel", __func__); return rc; } } else { stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); rc = addRawChannel(); if (rc == NO_ERROR) { // start postprocessor rc = m_postprocessor.start(m_channels[QCAMERA_CH_TYPE_RAW]); if (rc != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); delChannel(QCAMERA_CH_TYPE_RAW); return rc; } rc = startChannel(QCAMERA_CH_TYPE_RAW); if (rc != NO_ERROR) { ALOGE("%s: cannot start raw channel", __func__); m_postprocessor.stop(); delChannel(QCAMERA_CH_TYPE_RAW); return rc; } } else { ALOGE("%s: cannot add raw channel", __func__); return rc; } } } CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : longShot * * DESCRIPTION: Queue one more ZSL frame * in the longshot pipe. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::longShot() { int32_t rc = NO_ERROR; uint8_t numSnapshots = mParameters.getNumOfSnapshots(); QCameraPicChannel *pChannel = NULL; if (mParameters.isZSLMode()) { pChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; } else { pChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_CAPTURE]; } if (NULL != pChannel) { rc = pChannel->takePicture(numSnapshots); } else { ALOGE(" %s : Capture channel not initialized!", __func__); rc = NO_INIT; goto end; } end: return rc; } /*=========================================================================== * FUNCTION : stopCaptureChannel * * DESCRIPTION: Stops capture channel * * PARAMETERS : * @destroy : Set to true to stop and delete camera channel. * Set to false to only stop capture channel. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopCaptureChannel(bool destroy) { if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { stopChannel(QCAMERA_CH_TYPE_CAPTURE); if (destroy) { // Destroy camera channel but dont release context delChannel(QCAMERA_CH_TYPE_CAPTURE, false); } } #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Uninit(); #endif return NO_ERROR; } /*=========================================================================== * FUNCTION : cancelPicture * * DESCRIPTION: cancel picture impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelPicture() { CDBG_HIGH("%s:%d] ",__func__, __LINE__); waitDefferedWork(mReprocJob); //stop post processor m_postprocessor.stop(); mParameters.setDisplayFrame(TRUE); if ( mParameters.isHDREnabled() || mParameters.isAEBracketEnabled()) { mParameters.stopAEBracket(); } if (mParameters.isZSLMode()) { QCameraPicChannel *pZSLChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pZSLChannel) { pZSLChannel->cancelPicture(); } } else { // normal capture case if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { stopChannel(QCAMERA_CH_TYPE_CAPTURE); delChannel(QCAMERA_CH_TYPE_CAPTURE); } else { stopChannel(QCAMERA_CH_TYPE_RAW); delChannel(QCAMERA_CH_TYPE_RAW); } } if(mIs3ALocked) { mParameters.set3ALock(QCameraParameters::VALUE_FALSE); mIs3ALocked = false; } if (mParameters.isUbiFocusEnabled()) { configureAFBracketing(false); } return NO_ERROR; } /*=========================================================================== * FUNCTION : captureDone * * DESCRIPTION: Function called when the capture is completed before encoding * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::captureDone() { if (mParameters.isOptiZoomEnabled() && ++mOutputCount >= mParameters.getBurstCountForAdvancedCapture()) { ALOGE("%s: Restoring previous zoom value!!",__func__); mParameters.setAndCommitZoom(mZoomLevel); mOutputCount = 0; } #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Uninit(); #endif } /*=========================================================================== * FUNCTION : Live_Snapshot_thread * * DESCRIPTION: Seperate thread for taking live snapshot during recording * * PARAMETERS : @data - pointer to QCamera2HardwareInterface class object * * RETURN : none *==========================================================================*/ void* Live_Snapshot_thread (void* data) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(data); if (!hw) { ALOGE("take_picture_thread: NULL camera device"); return (void *)BAD_VALUE; } hw->takeLiveSnapshot_internal(); return (void* )NULL; } /*=========================================================================== * FUNCTION : Int_Pic_thread * * DESCRIPTION: Seperate thread for taking snapshot triggered by camera backend * * PARAMETERS : @data - pointer to QCamera2HardwareInterface class object * * RETURN : none *==========================================================================*/ void* Int_Pic_thread (void* data) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(data); if (!hw) { ALOGE("take_picture_thread: NULL camera device"); return (void *)BAD_VALUE; } bool JpegMemOpt = false; hw->takeBackendPic_internal(&JpegMemOpt); hw->checkIntPicPending(JpegMemOpt); return (void* )NULL; } /*=========================================================================== * FUNCTION : takeLiveSnapshot * * DESCRIPTION: take live snapshot during recording * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeLiveSnapshot() { int rc = NO_ERROR; rc= pthread_create(&mLiveSnapshotThread, NULL, Live_Snapshot_thread, (void *) this); return rc; } /*=========================================================================== * FUNCTION : takePictureInternal * * DESCRIPTION: take snapshot triggered by backend * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takePictureInternal() { int rc = NO_ERROR; rc= pthread_create(&mIntPicThread, NULL, Int_Pic_thread, (void *) this); return rc; } /*=========================================================================== * FUNCTION : checkIntPicPending * * DESCRIPTION: timed wait for jpeg completion event, and send * back completion event to backend * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::checkIntPicPending(bool JpegMemOpt) { cam_int_evt_params_t params; int rc = NO_ERROR; struct timespec ts; struct timeval tp; gettimeofday(&tp, NULL); ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000 + 1000 * 1000000; if (true == m_bIntEvtPending) { //wait on the eztune condition variable pthread_mutex_lock(&m_int_lock); rc = pthread_cond_timedwait(&m_int_cond, &m_int_lock, &ts); m_bIntEvtPending = false; pthread_mutex_unlock(&m_int_lock); if (ETIMEDOUT == rc) { return; } params.dim = m_postprocessor.m_dst_dim; //send event back to server with the file path memcpy(&params.path[0], &m_BackendFileName[0], 50); params.size = mBackendFileSize; pthread_mutex_lock(&m_parm_lock); rc = mParameters.setIntEvent(params); pthread_mutex_unlock(&m_parm_lock); lockAPI(); rc = processAPI(QCAMERA_SM_EVT_SNAPSHOT_DONE, NULL); unlockAPI(); if (false == mParameters.isZSLMode()) { lockAPI(); rc = processAPI(QCAMERA_SM_EVT_START_PREVIEW, NULL); unlockAPI(); } m_postprocessor.setJpegMemOpt(JpegMemOpt); } return; } /*=========================================================================== * FUNCTION : takeBackendPic_internal * * DESCRIPTION: take snapshot triggered by backend * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeBackendPic_internal(bool *JpegMemOpt) { int rc; *JpegMemOpt = m_postprocessor.getJpegMemOpt(); m_postprocessor.setJpegMemOpt(false); lockAPI(); rc = processAPI(QCAMERA_SM_EVT_TAKE_PICTURE, NULL); if (rc == NO_ERROR) { qcamera_api_result_t apiResult; waitAPIResult(QCAMERA_SM_EVT_TAKE_PICTURE, &apiResult); } unlockAPI(); return rc; } /*=========================================================================== * FUNCTION : takeLiveSnapshot_internal * * DESCRIPTION: take live snapshot during recording * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeLiveSnapshot_internal() { int rc = NO_ERROR; getOrientation(); QCameraChannel *pChannel = NULL; // start post processor rc = m_postprocessor.start(m_channels[QCAMERA_CH_TYPE_SNAPSHOT]); if (NO_ERROR != rc) { ALOGE("%s: Post-processor start failed %d", __func__, rc); goto end; } pChannel = m_channels[QCAMERA_CH_TYPE_SNAPSHOT]; if (NULL == pChannel) { ALOGE("%s: Snapshot channel not initialized", __func__); rc = NO_INIT; goto end; } // start snapshot channel if ((rc == NO_ERROR) && (NULL != pChannel)) { // Find and try to link a metadata stream from preview channel QCameraChannel *pMetaChannel = NULL; QCameraStream *pMetaStream = NULL; if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { pMetaChannel = m_channels[QCAMERA_CH_TYPE_PREVIEW]; uint32_t streamNum = pMetaChannel->getNumOfStreams(); QCameraStream *pStream = NULL; for (uint32_t i = 0 ; i < streamNum ; i++ ) { pStream = pMetaChannel->getStreamByIndex(i); if ((NULL != pStream) && (CAM_STREAM_TYPE_METADATA == pStream->getMyType())) { pMetaStream = pStream; break; } } } if ((NULL != pMetaChannel) && (NULL != pMetaStream)) { rc = pChannel->linkStream(pMetaChannel, pMetaStream); if (NO_ERROR != rc) { ALOGE("%s : Metadata stream link failed %d", __func__, rc); } } rc = pChannel->start(); } end: if (rc != NO_ERROR) { rc = processAPI(QCAMERA_SM_EVT_CANCEL_PICTURE, NULL); rc = sendEvtNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); } return rc; } /*=========================================================================== * FUNCTION : cancelLiveSnapshot * * DESCRIPTION: cancel current live snapshot request * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelLiveSnapshot() { int rc = NO_ERROR; if (mLiveSnapshotThread != 0) { pthread_join(mLiveSnapshotThread,NULL); mLiveSnapshotThread = 0; } //stop post processor m_postprocessor.stop(); // stop snapshot channel rc = stopChannel(QCAMERA_CH_TYPE_SNAPSHOT); return rc; } /*=========================================================================== * FUNCTION : getParameters * * DESCRIPTION: get parameters impl * * PARAMETERS : none * * RETURN : a string containing parameter pairs *==========================================================================*/ char* QCamera2HardwareInterface::getParameters() { char* strParams = NULL; String8 str; int cur_width, cur_height; //Need take care Scale picture size if(mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()){ int scale_width, scale_height; mParameters.m_reprocScaleParam.getPicSizeFromAPK(scale_width,scale_height); mParameters.getPictureSize(&cur_width, &cur_height); String8 pic_size; char buffer[32]; snprintf(buffer, sizeof(buffer), "%dx%d", scale_width, scale_height); pic_size.append(buffer); mParameters.set(CameraParameters::KEY_PICTURE_SIZE, pic_size); } str = mParameters.flatten( ); strParams = (char *)malloc(sizeof(char)*(str.length()+1)); if(strParams != NULL){ memset(strParams, 0, sizeof(char)*(str.length()+1)); strncpy(strParams, str.string(), str.length()); strParams[str.length()] = 0; } if(mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()){ //need set back picture size String8 pic_size; char buffer[32]; snprintf(buffer, sizeof(buffer), "%dx%d", cur_width, cur_height); pic_size.append(buffer); mParameters.set(CameraParameters::KEY_PICTURE_SIZE, pic_size); } return strParams; } /*=========================================================================== * FUNCTION : putParameters * * DESCRIPTION: put parameters string impl * * PARAMETERS : * @parms : parameters string to be released * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::putParameters(char *parms) { free(parms); return NO_ERROR; } /*=========================================================================== * FUNCTION : sendCommand * * DESCRIPTION: send command impl * * PARAMETERS : * @command : command to be executed * @arg1 : optional argument 1 * @arg2 : optional argument 2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::sendCommand(int32_t command, int32_t &arg1, int32_t &/*arg2*/) { int rc = NO_ERROR; switch (command) { case CAMERA_CMD_LONGSHOT_ON: arg1 = 0; // Longshot can only be enabled when image capture // is not active. if ( !m_stateMachine.isCaptureRunning() ) { CDBG_HIGH("%s: Longshot Enabled", __func__); mLongshotEnabled = true; // Due to recent buffer count optimizations // ZSL might run with considerably less buffers // when not in longshot mode. Preview needs to // restart in this case. if (isZSLMode() && m_stateMachine.isPreviewRunning()) { QCameraChannel *pChannel = NULL; QCameraStream *pSnapStream = NULL; pChannel = m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pChannel) { QCameraStream *pStream = NULL; for(int i = 0; i < pChannel->getNumOfStreams(); i++) { pStream = pChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_SNAPSHOT)) { pSnapStream = pStream; break; } } } if (NULL != pSnapStream) { uint8_t required = 0; required = getBufNumRequired(CAM_STREAM_TYPE_SNAPSHOT); if (pSnapStream->getBufferCount() < required) { // We restart here, to reset the FPS and no // of buffers as per the requirement of longshot usecase. arg1 = QCAMERA_SM_EVT_RESTART_PERVIEW; } } } } rc = mParameters.setLongshotEnable(mLongshotEnabled); mPrepSnapRun = false; } else { rc = NO_INIT; } break; case CAMERA_CMD_LONGSHOT_OFF: if ( mLongshotEnabled && m_stateMachine.isCaptureRunning() ) { cancelPicture(); processEvt(QCAMERA_SM_EVT_SNAPSHOT_DONE, NULL); QCameraChannel *pZSLChannel = m_channels[QCAMERA_CH_TYPE_ZSL]; if (isZSLMode() && (NULL != pZSLChannel) && mPrepSnapRun) { mCameraHandle->ops->stop_zsl_snapshot( mCameraHandle->camera_handle, pZSLChannel->getMyHandle()); } } CDBG_HIGH("%s: Longshot Disabled", __func__); mPrepSnapRun = false; mLongshotEnabled = false; rc = mParameters.setLongshotEnable(mLongshotEnabled); break; case CAMERA_CMD_HISTOGRAM_ON: case CAMERA_CMD_HISTOGRAM_OFF: rc = setHistogram(command == CAMERA_CMD_HISTOGRAM_ON? true : false); CDBG_HIGH("%s: Histogram -> %s", __func__, mParameters.isHistogramEnabled() ? "Enabled" : "Disabled"); break; case CAMERA_CMD_START_FACE_DETECTION: case CAMERA_CMD_STOP_FACE_DETECTION: rc = setFaceDetection(command == CAMERA_CMD_START_FACE_DETECTION? true : false); CDBG_HIGH("%s: FaceDetection -> %s", __func__, mParameters.isFaceDetectionEnabled() ? "Enabled" : "Disabled"); break; case CAMERA_CMD_HISTOGRAM_SEND_DATA: default: rc = NO_ERROR; break; } return rc; } /*=========================================================================== * FUNCTION : registerFaceImage * * DESCRIPTION: register face image impl * * PARAMETERS : * @img_ptr : ptr to image buffer * @config : ptr to config struct about input image info * @faceID : [OUT] face ID to uniquely identifiy the registered face image * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::registerFaceImage(void *img_ptr, cam_pp_offline_src_config_t *config, int32_t &faceID) { int rc = NO_ERROR; faceID = -1; if (img_ptr == NULL || config == NULL) { ALOGE("%s: img_ptr or config is NULL", __func__); return BAD_VALUE; } // allocate ion memory for source image QCameraHeapMemory *imgBuf = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); if (imgBuf == NULL) { ALOGE("%s: Unable to new heap memory obj for image buf", __func__); return NO_MEMORY; } rc = imgBuf->allocate(1, config->input_buf_planes.plane_info.frame_len); if (rc < 0) { ALOGE("%s: Unable to allocate heap memory for image buf", __func__); delete imgBuf; return NO_MEMORY; } void *pBufPtr = imgBuf->getPtr(0); if (pBufPtr == NULL) { ALOGE("%s: image buf is NULL", __func__); imgBuf->deallocate(); delete imgBuf; return NO_MEMORY; } memcpy(pBufPtr, img_ptr, config->input_buf_planes.plane_info.frame_len); cam_pp_feature_config_t pp_feature; memset(&pp_feature, 0, sizeof(cam_pp_feature_config_t)); pp_feature.feature_mask = CAM_QCOM_FEATURE_REGISTER_FACE; QCameraReprocessChannel *pChannel = addOfflineReprocChannel(*config, pp_feature, NULL, NULL); if (pChannel == NULL) { ALOGE("%s: fail to add offline reprocess channel", __func__); imgBuf->deallocate(); delete imgBuf; return UNKNOWN_ERROR; } rc = pChannel->start(); if (rc != NO_ERROR) { ALOGE("%s: Cannot start reprocess channel", __func__); imgBuf->deallocate(); delete imgBuf; delete pChannel; return rc; } rc = pChannel->doReprocess(imgBuf->getFd(0), imgBuf->getSize(0), faceID); // done with register face image, free imgbuf and delete reprocess channel imgBuf->deallocate(); delete imgBuf; imgBuf = NULL; pChannel->stop(); delete pChannel; pChannel = NULL; return rc; } /*=========================================================================== * FUNCTION : release * * DESCRIPTION: release camera resource impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::release() { // stop and delete all channels for (int i = 0; i <QCAMERA_CH_TYPE_MAX ; i++) { if (m_channels[i] != NULL) { stopChannel((qcamera_ch_type_enum_t)i); delChannel((qcamera_ch_type_enum_t)i); } } return NO_ERROR; } /*=========================================================================== * FUNCTION : dump * * DESCRIPTION: camera status dump impl * * PARAMETERS : * @fd : fd for the buffer to be dumped with camera status * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::dump(int /*fd*/) { ALOGE("%s: not supported yet", __func__); return INVALID_OPERATION; } /*=========================================================================== * FUNCTION : processAPI * * DESCRIPTION: process API calls from upper layer * * PARAMETERS : * @api : API to be processed * @api_payload : ptr to API payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processAPI(qcamera_sm_evt_enum_t api, void *api_payload) { return m_stateMachine.procAPI(api, api_payload); } /*=========================================================================== * FUNCTION : processEvt * * DESCRIPTION: process Evt from backend via mm-camera-interface * * PARAMETERS : * @evt : event type to be processed * @evt_payload : ptr to event payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processEvt(qcamera_sm_evt_enum_t evt, void *evt_payload) { return m_stateMachine.procEvt(evt, evt_payload); } /*=========================================================================== * FUNCTION : processSyncEvt * * DESCRIPTION: process synchronous Evt from backend * * PARAMETERS : * @evt : event type to be processed * @evt_payload : ptr to event payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processSyncEvt(qcamera_sm_evt_enum_t evt, void *evt_payload) { int rc = NO_ERROR; pthread_mutex_lock(&m_evtLock); rc = processEvt(evt, evt_payload); if (rc == NO_ERROR) { memset(&m_evtResult, 0, sizeof(qcamera_api_result_t)); while (m_evtResult.request_api != evt) { pthread_cond_wait(&m_evtCond, &m_evtLock); } rc = m_evtResult.status; } pthread_mutex_unlock(&m_evtLock); return rc; } /*=========================================================================== * FUNCTION : evtHandle * * DESCRIPTION: Function registerd to mm-camera-interface to handle backend events * * PARAMETERS : * @camera_handle : event type to be processed * @evt : ptr to event * @user_data : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::camEvtHandle(uint32_t /*camera_handle*/, mm_camera_event_t *evt, void *user_data) { QCamera2HardwareInterface *obj = (QCamera2HardwareInterface *)user_data; if (obj && evt) { mm_camera_event_t *payload = (mm_camera_event_t *)malloc(sizeof(mm_camera_event_t)); if (NULL != payload) { *payload = *evt; //peek into the event, if this is an eztune event from server, //then we don't need to post it to the SM Qs, we shud directly //spawn a thread and get the job done (jpeg or raw snapshot) if (CAM_EVENT_TYPE_INT_TAKE_PIC == payload->server_event_type) { pthread_mutex_lock(&obj->m_int_lock); obj->m_bIntEvtPending = true; pthread_mutex_unlock(&obj->m_int_lock); obj->takePictureInternal(); free(payload); } else { obj->processEvt(QCAMERA_SM_EVT_EVT_NOTIFY, payload); } } } else { ALOGE("%s: NULL user_data", __func__); } } /*=========================================================================== * FUNCTION : jpegEvtHandle * * DESCRIPTION: Function registerd to mm-jpeg-interface to handle jpeg events * * PARAMETERS : * @status : status of jpeg job * @client_hdl: jpeg client handle * @jobId : jpeg job Id * @p_ouput : ptr to jpeg output result struct * @userdata : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::jpegEvtHandle(jpeg_job_status_t status, uint32_t /*client_hdl*/, uint32_t jobId, mm_jpeg_output_t *p_output, void *userdata) { QCamera2HardwareInterface *obj = (QCamera2HardwareInterface *)userdata; if (obj) { qcamera_jpeg_evt_payload_t *payload = (qcamera_jpeg_evt_payload_t *)malloc(sizeof(qcamera_jpeg_evt_payload_t)); if (NULL != payload) { memset(payload, 0, sizeof(qcamera_jpeg_evt_payload_t)); payload->status = status; payload->jobId = jobId; if (p_output != NULL) { payload->out_data = *p_output; } obj->processUFDumps(payload); obj->processEvt(QCAMERA_SM_EVT_JPEG_EVT_NOTIFY, payload); } } else { ALOGE("%s: NULL user_data", __func__); } } /*=========================================================================== * FUNCTION : thermalEvtHandle * * DESCRIPTION: routine to handle thermal event notification * * PARAMETERS : * @level : thermal level * @userdata : userdata passed in during registration * @data : opaque data from thermal client * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::thermalEvtHandle( qcamera_thermal_level_enum_t level, void *userdata, void *data) { if (!mCameraOpened) { CDBG("%s: Camera is not opened, no need to handle thermal evt", __func__); return NO_ERROR; } // Make sure thermal events are logged CDBG("%s: level = %d, userdata = %p, data = %p", __func__, level, userdata, data); //We don't need to lockAPI, waitAPI here. QCAMERA_SM_EVT_THERMAL_NOTIFY // becomes an aync call. This also means we can only pass payload // by value, not by address. return processAPI(QCAMERA_SM_EVT_THERMAL_NOTIFY, (void *)level); } /*=========================================================================== * FUNCTION : sendEvtNotify * * DESCRIPTION: send event notify to notify thread * * PARAMETERS : * @msg_type: msg type to be sent * @ext1 : optional extension1 * @ext2 : optional extension2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::sendEvtNotify(int32_t msg_type, int32_t ext1, int32_t ext2) { qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_NOTIFY_CALLBACK; cbArg.msg_type = msg_type; cbArg.ext1 = ext1; cbArg.ext2 = ext2; return m_cbNotifier.notifyCallback(cbArg); } /*=========================================================================== * FUNCTION : processAutoFocusEvent * * DESCRIPTION: process auto focus event * * PARAMETERS : * @focus_data: struct containing auto focus result info * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processAutoFocusEvent(cam_auto_focus_data_t &focus_data) { int32_t ret = NO_ERROR; CDBG_HIGH("%s: E",__func__); m_currentFocusState = focus_data.focus_state; cam_focus_mode_type focusMode = mParameters.getFocusMode(); CDBG_HIGH("[AF_DBG] %s: focusMode=%d, m_currentFocusState=%d, m_bAFRunning=%d", __func__, focusMode, m_currentFocusState, isAFRunning()); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: if (getCancelAutoFocus()) { // auto focus has canceled, just ignore it break; } if (focus_data.focus_state == CAM_AF_SCANNING || focus_data.focus_state == CAM_AF_INACTIVE) { // in the middle of focusing, just ignore it break; } // update focus distance mParameters.updateFocusDistances(&focus_data.focus_dist); ret = sendEvtNotify(CAMERA_MSG_FOCUS, (focus_data.focus_state == CAM_AF_FOCUSED)? true : false, 0); break; case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: if (focus_data.focus_state == CAM_AF_FOCUSED || focus_data.focus_state == CAM_AF_NOT_FOCUSED) { // update focus distance mParameters.updateFocusDistances(&focus_data.focus_dist); ret = sendEvtNotify(CAMERA_MSG_FOCUS, (focus_data.focus_state == CAM_AF_FOCUSED)? true : false, 0); } ret = sendEvtNotify(CAMERA_MSG_FOCUS_MOVE, (focus_data.focus_state == CAM_AF_SCANNING)? true : false, 0); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: CDBG_HIGH("%s: no ops for autofocus event in focusmode %d", __func__, focusMode); break; } // we save cam_auto_focus_data_t.focus_pos to parameters, // in any focus mode. CDBG_HIGH("%s, update focus position: %d", __func__, focus_data.focus_pos); mParameters.updateCurrentFocusPosition(focus_data.focus_pos); CDBG_HIGH("%s: X",__func__); return ret; } /*=========================================================================== * FUNCTION : processZoomEvent * * DESCRIPTION: process zoom event * * PARAMETERS : * @crop_info : crop info as a result of zoom operation * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processZoomEvent(cam_crop_data_t &crop_info) { int32_t ret = NO_ERROR; for (int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { ret = m_channels[i]->processZoomDone(mPreviewWindow, crop_info); } } return ret; } /*=========================================================================== * FUNCTION : processHDRData * * DESCRIPTION: process HDR scene events * * PARAMETERS : * @hdr_scene : HDR scene event data * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processHDRData(cam_asd_hdr_scene_data_t hdr_scene) { int rc = NO_ERROR; if (hdr_scene.is_hdr_scene && (hdr_scene.hdr_confidence > HDR_CONFIDENCE_THRESHOLD) && mParameters.isAutoHDREnabled()) { m_HDRSceneEnabled = true; } else { m_HDRSceneEnabled = false; } pthread_mutex_lock(&m_parm_lock); mParameters.setHDRSceneEnable(m_HDRSceneEnabled); pthread_mutex_unlock(&m_parm_lock); if ( msgTypeEnabled(CAMERA_MSG_META_DATA) ) { size_t data_len = sizeof(int); size_t buffer_len = 1 *sizeof(int) //meta type + 1 *sizeof(int) //data len + 1 *sizeof(int); //data camera_memory_t *hdrBuffer = mGetMemory(-1, buffer_len, 1, mCallbackCookie); if ( NULL == hdrBuffer ) { ALOGE("%s: Not enough memory for auto HDR data", __func__); return NO_MEMORY; } int *pHDRData = (int *)hdrBuffer->data; if (pHDRData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } pHDRData[0] = CAMERA_META_DATA_HDR; pHDRData[1] = data_len; pHDRData[2] = m_HDRSceneEnabled; qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = hdrBuffer; cbArg.user_data = hdrBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending auto HDR notification", __func__); hdrBuffer->release(hdrBuffer); } } CDBG("%s : hdr_scene_data: processHDRData: %d %f", __func__, hdr_scene.is_hdr_scene, hdr_scene.hdr_confidence); return rc; } /*=========================================================================== * FUNCTION : transAwbMetaToParams * * DESCRIPTION: translate awb params from metadata callback to QCameraParameters * * PARAMETERS : * @awb_params : awb params from metadata callback * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::transAwbMetaToParams(cam_awb_params_t &awb_params) { CDBG("%s, cct value: %d", __func__, awb_params.cct_value); return mParameters.updateCCTValue(awb_params.cct_value); } /*=========================================================================== * FUNCTION : processPrepSnapshotDone * * DESCRIPTION: process prep snapshot done event * * PARAMETERS : * @prep_snapshot_state : state of prepare snapshot done. In other words, * i.e. whether need future frames for capture. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processPrepSnapshotDoneEvent( cam_prep_snapshot_state_t prep_snapshot_state) { int32_t ret = NO_ERROR; if (m_channels[QCAMERA_CH_TYPE_ZSL] && prep_snapshot_state == NEED_FUTURE_FRAME) { CDBG_HIGH("%s: already handled in mm-camera-intf, no ops here", __func__); } return ret; } /*=========================================================================== * FUNCTION : processASDUpdate * * DESCRIPTION: process ASD update event * * PARAMETERS : * @scene: selected scene mode * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processASDUpdate(cam_auto_scene_t scene) { //set ASD parameter mParameters.set(QCameraParameters::KEY_SELECTED_AUTO_SCENE, mParameters.getASDStateString(scene)); size_t data_len = sizeof(cam_auto_scene_t); size_t buffer_len = 1 *sizeof(int) //meta type + 1 *sizeof(int) //data len + data_len; //data camera_memory_t *asdBuffer = mGetMemory(-1, buffer_len, 1, mCallbackCookie); if ( NULL == asdBuffer ) { ALOGE("%s: Not enough memory for histogram data", __func__); return NO_MEMORY; } int *pASDData = (int *)asdBuffer->data; if (pASDData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } pASDData[0] = CAMERA_META_DATA_ASD; pASDData[1] = data_len; pASDData[2] = scene; qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = asdBuffer; cbArg.user_data = asdBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); asdBuffer->release(asdBuffer); } return NO_ERROR; } /*=========================================================================== * FUNCTION : processAWBUpdate * * DESCRIPTION: process AWB update event * * PARAMETERS : * @awb_params: current awb parameters from back-end. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processAWBUpdate(cam_awb_params_t &awb_params) { return transAwbMetaToParams(awb_params); } /*=========================================================================== * FUNCTION : processJpegNotify * * DESCRIPTION: process jpeg event * * PARAMETERS : * @jpeg_evt: ptr to jpeg event payload * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processJpegNotify(qcamera_jpeg_evt_payload_t *jpeg_evt) { return m_postprocessor.processJpegEvt(jpeg_evt); } /*=========================================================================== * FUNCTION : lockAPI * * DESCRIPTION: lock to process API * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::lockAPI() { pthread_mutex_lock(&m_lock); } /*=========================================================================== * FUNCTION : waitAPIResult * * DESCRIPTION: wait for API result coming back. This is a blocking call, it will * return only cerntain API event type arrives * * PARAMETERS : * @api_evt : API event type * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::waitAPIResult(qcamera_sm_evt_enum_t api_evt, qcamera_api_result_t *apiResult) { CDBG("%s: wait for API result of evt (%d)", __func__, api_evt); int resultReceived = 0; while (!resultReceived) { pthread_cond_wait(&m_cond, &m_lock); if (m_apiResultList != NULL) { api_result_list *apiResultList = m_apiResultList; api_result_list *apiResultListPrevious = m_apiResultList; while (apiResultList != NULL) { if (apiResultList->result.request_api == api_evt) { resultReceived = 1; *apiResult = apiResultList->result; apiResultListPrevious->next = apiResultList->next; if (apiResultList == m_apiResultList) { m_apiResultList = apiResultList->next; } free(apiResultList); break; } else { apiResultListPrevious = apiResultList; apiResultList = apiResultList->next; } } } } CDBG("%s: return (%d) from API result wait for evt (%d)", __func__, apiResult->status, api_evt); } /*=========================================================================== * FUNCTION : unlockAPI * * DESCRIPTION: API processing is done, unlock * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::unlockAPI() { pthread_mutex_unlock(&m_lock); } /*=========================================================================== * FUNCTION : signalAPIResult * * DESCRIPTION: signal condition viarable that cerntain API event type arrives * * PARAMETERS : * @result : API result * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::signalAPIResult(qcamera_api_result_t *result) { pthread_mutex_lock(&m_lock); api_result_list *apiResult = (api_result_list *)malloc(sizeof(api_result_list)); if (apiResult == NULL) { ALOGE("%s: ERROR: malloc for api result failed", __func__); ALOGE("%s: ERROR: api thread will wait forever fot this lost result", __func__); goto malloc_failed; } apiResult->result = *result; apiResult->next = NULL; if (m_apiResultList == NULL) m_apiResultList = apiResult; else { api_result_list *apiResultList = m_apiResultList; while(apiResultList->next != NULL) apiResultList = apiResultList->next; apiResultList->next = apiResult; } malloc_failed: pthread_cond_broadcast(&m_cond); pthread_mutex_unlock(&m_lock); } /*=========================================================================== * FUNCTION : signalEvtResult * * DESCRIPTION: signal condition variable that certain event was processed * * PARAMETERS : * @result : Event result * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::signalEvtResult(qcamera_api_result_t *result) { pthread_mutex_lock(&m_evtLock); m_evtResult = *result; pthread_cond_signal(&m_evtCond); pthread_mutex_unlock(&m_evtLock); } int32_t QCamera2HardwareInterface::prepareRawStream(QCameraChannel *curChannel) { int32_t rc = NO_ERROR; cam_dimension_t str_dim,max_dim; QCameraChannel *pChannel; max_dim.width = 0; max_dim.height = 0; for (int j = 0; j < QCAMERA_CH_TYPE_MAX; j++) { if (m_channels[j] != NULL) { pChannel = m_channels[j]; for (int i = 0; i < pChannel->getNumOfStreams();i++) { QCameraStream *pStream = pChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_METADATA)) { continue; } pStream->getFrameDimension(str_dim); if (str_dim.width > max_dim.width) { max_dim.width = str_dim.width; } if (str_dim.height > max_dim.height) { max_dim.height = str_dim.height; } } } } } for (int i = 0; i < curChannel->getNumOfStreams();i++) { QCameraStream *pStream = curChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_METADATA)) { continue; } pStream->getFrameDimension(str_dim); if (str_dim.width > max_dim.width) { max_dim.width = str_dim.width; } if (str_dim.height > max_dim.height) { max_dim.height = str_dim.height; } } } rc = mParameters.updateRAW(max_dim); return rc; } /*=========================================================================== * FUNCTION : addStreamToChannel * * DESCRIPTION: add a stream into a channel * * PARAMETERS : * @pChannel : ptr to channel obj * @streamType : type of stream to be added * @streamCB : callback of stream * @userData : user data ptr to callback * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addStreamToChannel(QCameraChannel *pChannel, cam_stream_type_t streamType, stream_cb_routine streamCB, void *userData) { int32_t rc = NO_ERROR; if (streamType == CAM_STREAM_TYPE_RAW) { prepareRawStream(pChannel); } QCameraHeapMemory *pStreamInfo = allocateStreamInfoBuf(streamType); if (pStreamInfo == NULL) { ALOGE("%s: no mem for stream info buf", __func__); return NO_MEMORY; } uint8_t minStreamBufNum = getBufNumRequired(streamType); bool bDynAllocBuf = false; if (isZSLMode() && streamType == CAM_STREAM_TYPE_SNAPSHOT) { bDynAllocBuf = true; } if ( ( streamType == CAM_STREAM_TYPE_SNAPSHOT || streamType == CAM_STREAM_TYPE_POSTVIEW || streamType == CAM_STREAM_TYPE_METADATA || streamType == CAM_STREAM_TYPE_RAW) && !isZSLMode() && !isLongshotEnabled() && !mParameters.getRecordingHintValue()) { rc = pChannel->addStream(*this, pStreamInfo, minStreamBufNum, &gCamCapability[mCameraId]->padding_info, streamCB, userData, bDynAllocBuf, true); // Queue buffer allocation for Snapshot and Metadata streams if ( !rc ) { DefferWorkArgs args; DefferAllocBuffArgs allocArgs; memset(&args, 0, sizeof(DefferWorkArgs)); memset(&allocArgs, 0, sizeof(DefferAllocBuffArgs)); allocArgs.type = streamType; allocArgs.ch = pChannel; args.allocArgs = allocArgs; if (streamType == CAM_STREAM_TYPE_SNAPSHOT) { mSnapshotJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mSnapshotJob == -1) { rc = UNKNOWN_ERROR; } } else if (streamType == CAM_STREAM_TYPE_METADATA) { mMetadataJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mMetadataJob == -1) { rc = UNKNOWN_ERROR; } } else if (streamType == CAM_STREAM_TYPE_RAW) { mRawdataJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mRawdataJob == -1) { rc = UNKNOWN_ERROR; } } } } else { rc = pChannel->addStream(*this, pStreamInfo, minStreamBufNum, &gCamCapability[mCameraId]->padding_info, streamCB, userData, bDynAllocBuf, false); } if (rc != NO_ERROR) { ALOGE("%s: add stream type (%d) failed, ret = %d", __func__, streamType, rc); pStreamInfo->deallocate(); delete pStreamInfo; return rc; } return rc; } /*=========================================================================== * FUNCTION : addPreviewChannel * * DESCRIPTION: add a preview channel that contains a preview stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addPreviewChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { // Using the no preview torch WA it is possible // to already have a preview channel present before // start preview gets called. CDBG_HIGH(" %s : Preview Channel already added!", __func__); return NO_ERROR; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for preview channel", __func__); return NO_MEMORY; } // preview only channel, don't need bundle attr and cb rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init preview channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with preview if applicable rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (isNoDisplayMode()) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, nodisplay_preview_stream_cb_routine, this); } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); } if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_PREVIEW] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addVideoChannel * * DESCRIPTION: add a video channel that contains a video stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addVideoChannel() { int32_t rc = NO_ERROR; QCameraVideoChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_VIDEO] != NULL) { // if we had video channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_VIDEO]; m_channels[QCAMERA_CH_TYPE_VIDEO] = NULL; } pChannel = new QCameraVideoChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for video channel", __func__); return NO_MEMORY; } // preview only channel, don't need bundle attr and cb rc = pChannel->init(NULL, NULL, NULL); if (rc != 0) { ALOGE("%s: init video channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_VIDEO, video_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add video stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_VIDEO] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addSnapshotChannel * * DESCRIPTION: add a snapshot channel that contains a snapshot stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : Add this channel for live snapshot usecase. Regular capture will * use addCaptureChannel. *==========================================================================*/ int32_t QCamera2HardwareInterface::addSnapshotChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_SNAPSHOT] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_SNAPSHOT]; m_channels[QCAMERA_CH_TYPE_SNAPSHOT] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for snapshot channel", __func__); return NO_MEMORY; } mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; attr.look_back = mParameters.getZSLBackLookCount(); attr.post_frame_skip = mParameters.getZSLBurstInterval(); attr.water_mark = mParameters.getZSLQueueDepth(); attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, snapshot_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init snapshot channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_SNAPSHOT] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addRawChannel * * DESCRIPTION: add a raw channel that contains a raw image stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addRawChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_RAW] != NULL) { // if we had raw channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_RAW]; m_channels[QCAMERA_CH_TYPE_RAW] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for raw channel", __func__); return NO_MEMORY; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init raw channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with snapshot in regular RAW capture case rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } waitDefferedWork(mMetadataJob); rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, raw_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } waitDefferedWork(mRawdataJob); m_channels[QCAMERA_CH_TYPE_RAW] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addZSLChannel * * DESCRIPTION: add a ZSL channel that contains a preview stream and * a snapshot stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addZSLChannel() { int32_t rc = NO_ERROR; QCameraPicChannel *pChannel = NULL; char value[PROPERTY_VALUE_MAX]; bool raw_yuv = false; if (m_channels[QCAMERA_CH_TYPE_ZSL] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_ZSL]; m_channels[QCAMERA_CH_TYPE_ZSL] = NULL; } if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_PREVIEW]; m_channels[QCAMERA_CH_TYPE_PREVIEW] = NULL; } pChannel = new QCameraPicChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for ZSL channel", __func__); return NO_MEMORY; } // ZSL channel, init with bundle attr and cb mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_BURST; attr.look_back = mParameters.getZSLBackLookCount(); attr.post_frame_skip = mParameters.getZSLBurstInterval(); attr.water_mark = mParameters.getZSLQueueDepth(); attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, zsl_channel_cb, this); if (rc != 0) { ALOGE("%s: init ZSL channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with preview if applicable rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (isNoDisplayMode()) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, nodisplay_preview_stream_cb_routine, this); } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); } if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } property_get("persist.camera.raw_yuv", value, "0"); raw_yuv = atoi(value) > 0 ? true : false; if ( raw_yuv ) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add raw stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } m_channels[QCAMERA_CH_TYPE_ZSL] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addCaptureChannel * * DESCRIPTION: add a capture channel that contains a snapshot stream * and a postview stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : Add this channel for regular capture usecase. * For Live snapshot usecase, use addSnapshotChannel. *==========================================================================*/ int32_t QCamera2HardwareInterface::addCaptureChannel() { int32_t rc = NO_ERROR; QCameraPicChannel *pChannel = NULL; char value[PROPERTY_VALUE_MAX]; bool raw_yuv = false; if (m_channels[QCAMERA_CH_TYPE_CAPTURE] != NULL) { delete m_channels[QCAMERA_CH_TYPE_CAPTURE]; m_channels[QCAMERA_CH_TYPE_CAPTURE] = NULL; } pChannel = new QCameraPicChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for capture channel", __func__); return NO_MEMORY; } // Capture channel, only need snapshot and postview streams start together mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); if ( mLongshotEnabled ) { attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_BURST; attr.look_back = mParameters.getZSLBackLookCount(); attr.water_mark = mParameters.getZSLQueueDepth(); } else { attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; } attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, capture_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init capture channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with snapshot in regular capture case rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (!mLongshotEnabled) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_POSTVIEW, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add postview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } property_get("persist.camera.raw_yuv", value, "0"); raw_yuv = atoi(value) > 0 ? true : false; if ( raw_yuv ) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, snapshot_raw_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add raw stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } m_channels[QCAMERA_CH_TYPE_CAPTURE] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addMetaDataChannel * * DESCRIPTION: add a meta data channel that contains a metadata stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addMetaDataChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_METADATA] != NULL) { delete m_channels[QCAMERA_CH_TYPE_METADATA]; m_channels[QCAMERA_CH_TYPE_METADATA] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for metadata channel", __func__); return NO_MEMORY; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init metadata channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_METADATA] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addReprocChannel * * DESCRIPTION: add a reprocess channel that will do reprocess on frames * coming from input channel * * PARAMETERS : * @pInputChannel : ptr to input channel whose frames will be post-processed * * RETURN : Ptr to the newly created channel obj. NULL if failed. *==========================================================================*/ QCameraReprocessChannel *QCamera2HardwareInterface::addReprocChannel( QCameraChannel *pInputChannel) { int32_t rc = NO_ERROR; QCameraReprocessChannel *pChannel = NULL; const char *effect; if (pInputChannel == NULL) { ALOGE("%s: input channel obj is NULL", __func__); return NULL; } pChannel = new QCameraReprocessChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for reprocess channel", __func__); return NULL; } // Capture channel, only need snapshot and postview streams start together mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, postproc_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init reprocess channel failed, ret = %d", __func__, rc); delete pChannel; return NULL; } CDBG_HIGH("%s: Before pproc config check, ret = %x", __func__, gCamCapability[mCameraId]->min_required_pp_mask); // pp feature config cam_pp_feature_config_t pp_config; uint32_t required_mask = gCamCapability[mCameraId]->min_required_pp_mask; memset(&pp_config, 0, sizeof(cam_pp_feature_config_t)); if (mParameters.isZSLMode() || (required_mask & CAM_QCOM_FEATURE_CPP)) { if (gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_EFFECT) { pp_config.feature_mask |= CAM_QCOM_FEATURE_EFFECT; effect = mParameters.get(CameraParameters::KEY_EFFECT); if (effect != NULL) pp_config.effect = getEffectValue(effect); } if ((gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_SHARPNESS) && !mParameters.isOptiZoomEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_SHARPNESS; pp_config.sharpness = mParameters.getInt(QCameraParameters::KEY_QC_SHARPNESS); } if (gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_CROP) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CROP; } if (mParameters.isWNREnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_DENOISE2D; pp_config.denoise2d.denoise_enable = 1; pp_config.denoise2d.process_plates = mParameters.getWaveletDenoiseProcessPlate(); } if (required_mask & CAM_QCOM_FEATURE_CPP) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CPP; } } if (isCACEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CAC; } if (needRotationReprocess()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CPP; int rotation = getJpegRotation(); if (rotation == 0) { pp_config.rotation = ROTATE_0; } else if (rotation == 90) { pp_config.rotation = ROTATE_90; } else if (rotation == 180) { pp_config.rotation = ROTATE_180; } else if (rotation == 270) { pp_config.rotation = ROTATE_270; } } uint8_t minStreamBufNum = getBufNumRequired(CAM_STREAM_TYPE_OFFLINE_PROC); if (mParameters.isHDREnabled()){ pp_config.feature_mask |= CAM_QCOM_FEATURE_HDR; pp_config.hdr_param.hdr_enable = 1; pp_config.hdr_param.hdr_need_1x = mParameters.isHDR1xFrameEnabled(); pp_config.hdr_param.hdr_mode = CAM_HDR_MODE_MULTIFRAME; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_HDR; pp_config.hdr_param.hdr_enable = 0; } if(needScaleReprocess()){ pp_config.feature_mask |= CAM_QCOM_FEATURE_SCALE; mParameters.m_reprocScaleParam.getPicSizeFromAPK( pp_config.scale_param.output_width, pp_config.scale_param.output_height); } CDBG_HIGH("%s: After pproc config check, ret = %x", __func__, pp_config.feature_mask); if(mParameters.isUbiFocusEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_UBIFOCUS; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_UBIFOCUS; } if(mParameters.isChromaFlashEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CHROMA_FLASH; //TODO: check flash value for captured image, then assign. pp_config.flash_value = CAM_FLASH_ON; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_CHROMA_FLASH; } if(mParameters.isOptiZoomEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_OPTIZOOM; pp_config.zoom_level = (uint8_t) mParameters.getInt(CameraParameters::KEY_ZOOM); } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_OPTIZOOM; } //WNR and HDR happen inline. No extra buffers needed. uint32_t temp_feature_mask = pp_config.feature_mask; temp_feature_mask &= ~CAM_QCOM_FEATURE_DENOISE2D; temp_feature_mask &= ~CAM_QCOM_FEATURE_HDR; if (temp_feature_mask && mParameters.isHDREnabled()) { minStreamBufNum = 1 + mParameters.getNumOfExtraHDRInBufsIfNeeded(); } // Add non inplace image lib buffers only when ppproc is present, // becuase pproc is non inplace and input buffers for img lib // are output for pproc and this number of extra buffers is required // If pproc is not there, input buffers for imglib are from snapshot stream uint8_t imglib_extra_bufs = mParameters.getNumOfExtraBuffersForImageProc(); if (temp_feature_mask && imglib_extra_bufs) { // 1 is added because getNumOfExtraBuffersForImageProc returns extra // buffers assuming number of capture is already added minStreamBufNum += imglib_extra_bufs + 1; } CDBG_HIGH("%s: Allocating %d reproc buffers",__func__,minStreamBufNum); bool offlineReproc = isRegularCapture(); rc = pChannel->addReprocStreamsFromSource(*this, pp_config, pInputChannel, minStreamBufNum, mParameters.getNumOfSnapshots(), &gCamCapability[mCameraId]->padding_info, mParameters, mLongshotEnabled, offlineReproc); if (rc != NO_ERROR) { delete pChannel; return NULL; } return pChannel; } /*=========================================================================== * FUNCTION : addOfflineReprocChannel * * DESCRIPTION: add a offline reprocess channel contains one reproc stream, * that will do reprocess on frames coming from external images * * PARAMETERS : * @img_config : offline reporcess image info * @pp_feature : pp feature config * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ QCameraReprocessChannel *QCamera2HardwareInterface::addOfflineReprocChannel( cam_pp_offline_src_config_t &img_config, cam_pp_feature_config_t &pp_feature, stream_cb_routine stream_cb, void *userdata) { int32_t rc = NO_ERROR; QCameraReprocessChannel *pChannel = NULL; pChannel = new QCameraReprocessChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for reprocess channel", __func__); return NULL; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init reprocess channel failed, ret = %d", __func__, rc); delete pChannel; return NULL; } QCameraHeapMemory *pStreamInfo = allocateStreamInfoBuf(CAM_STREAM_TYPE_OFFLINE_PROC); if (pStreamInfo == NULL) { ALOGE("%s: no mem for stream info buf", __func__); delete pChannel; return NULL; } cam_stream_info_t *streamInfoBuf = (cam_stream_info_t *)pStreamInfo->getPtr(0); memset(streamInfoBuf, 0, sizeof(cam_stream_info_t)); streamInfoBuf->stream_type = CAM_STREAM_TYPE_OFFLINE_PROC; streamInfoBuf->fmt = img_config.input_fmt; streamInfoBuf->dim = img_config.input_dim; streamInfoBuf->buf_planes = img_config.input_buf_planes; streamInfoBuf->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfoBuf->num_of_burst = img_config.num_of_bufs; streamInfoBuf->reprocess_config.pp_type = CAM_OFFLINE_REPROCESS_TYPE; streamInfoBuf->reprocess_config.offline = img_config; streamInfoBuf->reprocess_config.pp_feature_config = pp_feature; rc = pChannel->addStream(*this, pStreamInfo, img_config.num_of_bufs, &gCamCapability[mCameraId]->padding_info, stream_cb, userdata, false); if (rc != NO_ERROR) { ALOGE("%s: add reprocess stream failed, ret = %d", __func__, rc); pStreamInfo->deallocate(); delete pStreamInfo; delete pChannel; return NULL; } return pChannel; } /*=========================================================================== * FUNCTION : addChannel * * DESCRIPTION: add a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; switch (ch_type) { case QCAMERA_CH_TYPE_ZSL: rc = addZSLChannel(); break; case QCAMERA_CH_TYPE_CAPTURE: rc = addCaptureChannel(); break; case QCAMERA_CH_TYPE_PREVIEW: rc = addPreviewChannel(); break; case QCAMERA_CH_TYPE_VIDEO: rc = addVideoChannel(); break; case QCAMERA_CH_TYPE_SNAPSHOT: rc = addSnapshotChannel(); break; case QCAMERA_CH_TYPE_RAW: rc = addRawChannel(); break; case QCAMERA_CH_TYPE_METADATA: rc = addMetaDataChannel(); break; default: break; } return rc; } /*=========================================================================== * FUNCTION : delChannel * * DESCRIPTION: delete a channel by its type * * PARAMETERS : * @ch_type : channel type * @destroy : delete context as well * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::delChannel(qcamera_ch_type_enum_t ch_type, bool destroy) { if (m_channels[ch_type] != NULL) { if (destroy) { delete m_channels[ch_type]; m_channels[ch_type] = NULL; } else { m_channels[ch_type]->deleteChannel(); } } return NO_ERROR; } /*=========================================================================== * FUNCTION : startChannel * * DESCRIPTION: start a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::startChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; if (m_channels[ch_type] != NULL) { rc = m_channels[ch_type]->config(); if (NO_ERROR == rc) { rc = m_channels[ch_type]->start(); } } return rc; } /*=========================================================================== * FUNCTION : stopChannel * * DESCRIPTION: stop a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::stopChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; if (m_channels[ch_type] != NULL) { rc = m_channels[ch_type]->stop(); } return rc; } /*=========================================================================== * FUNCTION : preparePreview * * DESCRIPTION: add channels needed for preview * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::preparePreview() { int32_t rc = NO_ERROR; if (mParameters.isZSLMode() && mParameters.getRecordingHintValue() !=true) { rc = addChannel(QCAMERA_CH_TYPE_ZSL); if (rc != NO_ERROR) { return rc; } } else { bool recordingHint = mParameters.getRecordingHintValue(); if(recordingHint) { cam_dimension_t videoSize; mParameters.getVideoSize(&videoSize.width, &videoSize.height); if (!is4k2kResolution(&videoSize)) { rc = addChannel(QCAMERA_CH_TYPE_SNAPSHOT); if (rc != NO_ERROR) { return rc; } } rc = addChannel(QCAMERA_CH_TYPE_VIDEO); if (rc != NO_ERROR) { delChannel(QCAMERA_CH_TYPE_SNAPSHOT); return rc; } } rc = addChannel(QCAMERA_CH_TYPE_PREVIEW); if (rc != NO_ERROR) { if (recordingHint) { delChannel(QCAMERA_CH_TYPE_SNAPSHOT); delChannel(QCAMERA_CH_TYPE_VIDEO); } return rc; } if (!recordingHint) { waitDefferedWork(mMetadataJob); } } return rc; } /*=========================================================================== * FUNCTION : unpreparePreview * * DESCRIPTION: delete channels for preview * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::unpreparePreview() { delChannel(QCAMERA_CH_TYPE_ZSL); delChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_VIDEO); delChannel(QCAMERA_CH_TYPE_SNAPSHOT); } /*=========================================================================== * FUNCTION : playShutter * * DESCRIPTION: send request to play shutter sound * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::playShutter(){ if (mNotifyCb == NULL || msgTypeEnabledWithLock(CAMERA_MSG_SHUTTER) == 0){ CDBG("%s: shutter msg not enabled or NULL cb", __func__); return; } CDBG_HIGH("%s: CAMERA_MSG_SHUTTER ", __func__); qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_NOTIFY_CALLBACK; cbArg.msg_type = CAMERA_MSG_SHUTTER; cbArg.ext1 = 0; cbArg.ext2 = false; m_cbNotifier.notifyCallback(cbArg); } /*=========================================================================== * FUNCTION : getChannelByHandle * * DESCRIPTION: return a channel by its handle * * PARAMETERS : * @channelHandle : channel handle * * RETURN : a channel obj if found, NULL if not found *==========================================================================*/ QCameraChannel *QCamera2HardwareInterface::getChannelByHandle(uint32_t channelHandle) { for(int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL && m_channels[i]->getMyHandle() == channelHandle) { return m_channels[i]; } } return NULL; } /*=========================================================================== * FUNCTION : processFaceDetectionReuslt * * DESCRIPTION: process face detection reuslt * * PARAMETERS : * @fd_data : ptr to face detection result struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processFaceDetectionResult(cam_face_detection_data_t *fd_data) { if (!mParameters.isFaceDetectionEnabled()) { CDBG_HIGH("%s: FaceDetection not enabled, no ops here", __func__); return NO_ERROR; } qcamera_face_detect_type_t fd_type = fd_data->fd_type; if ((NULL == mDataCb) || (fd_type == QCAMERA_FD_PREVIEW && !msgTypeEnabled(CAMERA_MSG_PREVIEW_METADATA)) || (fd_type == QCAMERA_FD_SNAPSHOT && !msgTypeEnabled(CAMERA_MSG_META_DATA)) ) { CDBG_HIGH("%s: metadata msgtype not enabled, no ops here", __func__); return NO_ERROR; } cam_dimension_t display_dim; mParameters.getStreamDimension(CAM_STREAM_TYPE_PREVIEW, display_dim); if (display_dim.width <= 0 || display_dim.height <= 0) { ALOGE("%s: Invalid preview width or height (%d x %d)", __func__, display_dim.width, display_dim.height); return UNKNOWN_ERROR; } // process face detection result // need separate face detection in preview or snapshot type size_t faceResultSize = 0; size_t data_len = 0; if(fd_type == QCAMERA_FD_PREVIEW){ //fd for preview frames faceResultSize = sizeof(camera_frame_metadata_t); faceResultSize += sizeof(camera_face_t) * MAX_ROI; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ // fd for snapshot frames //check if face is detected in this frame if(fd_data->num_faces_detected > 0){ data_len = sizeof(camera_frame_metadata_t) + sizeof(camera_face_t) * fd_data->num_faces_detected; }else{ //no face data_len = 0; } faceResultSize = 1 *sizeof(int) //meta data type + 1 *sizeof(int) // meta data len + data_len; //data } camera_memory_t *faceResultBuffer = mGetMemory(-1, faceResultSize, 1, mCallbackCookie); if ( NULL == faceResultBuffer ) { ALOGE("%s: Not enough memory for face result data", __func__); return NO_MEMORY; } unsigned char *pFaceResult = ( unsigned char * ) faceResultBuffer->data; memset(pFaceResult, 0, faceResultSize); unsigned char *faceData = NULL; if(fd_type == QCAMERA_FD_PREVIEW){ faceData = pFaceResult; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ //need fill meta type and meta data len first int *data_header = (int* )pFaceResult; data_header[0] = CAMERA_META_DATA_FD; data_header[1] = data_len; if(data_len <= 0){ //if face is not valid or do not have face, return qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = faceResultBuffer; cbArg.user_data = faceResultBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); faceResultBuffer->release(faceResultBuffer); } return rc; } faceData = pFaceResult + 2 *sizeof(int); //skip two int length } camera_frame_metadata_t *roiData = (camera_frame_metadata_t * ) faceData; camera_face_t *faces = (camera_face_t *) ( faceData + sizeof(camera_frame_metadata_t) ); roiData->number_of_faces = fd_data->num_faces_detected; roiData->faces = faces; if (roiData->number_of_faces > 0) { for (int i = 0; i < roiData->number_of_faces; i++) { faces[i].id = fd_data->faces[i].face_id; faces[i].score = fd_data->faces[i].score; // left faces[i].rect[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.left, display_dim.width, 2000, -1000); // top faces[i].rect[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.top, display_dim.height, 2000, -1000); // right faces[i].rect[2] = faces[i].rect[0] + MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.width, display_dim.width, 2000, 0); // bottom faces[i].rect[3] = faces[i].rect[1] + MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.height, display_dim.height, 2000, 0); // Center of left eye faces[i].left_eye[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].left_eye_center.x, display_dim.width, 2000, -1000); faces[i].left_eye[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].left_eye_center.y, display_dim.height, 2000, -1000); // Center of right eye faces[i].right_eye[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].right_eye_center.x, display_dim.width, 2000, -1000); faces[i].right_eye[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].right_eye_center.y, display_dim.height, 2000, -1000); // Center of mouth faces[i].mouth[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].mouth_center.x, display_dim.width, 2000, -1000); faces[i].mouth[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].mouth_center.y, display_dim.height, 2000, -1000); faces[i].smile_degree = fd_data->faces[i].smile_degree; faces[i].smile_score = fd_data->faces[i].smile_confidence; faces[i].blink_detected = fd_data->faces[i].blink_detected; faces[i].face_recognised = fd_data->faces[i].face_recognised; faces[i].gaze_angle = fd_data->faces[i].gaze_angle; // upscale by 2 to recover from demaen downscaling faces[i].updown_dir = fd_data->faces[i].updown_dir * 2; faces[i].leftright_dir = fd_data->faces[i].leftright_dir * 2; faces[i].roll_dir = fd_data->faces[i].roll_dir * 2; faces[i].leye_blink = fd_data->faces[i].left_blink; faces[i].reye_blink = fd_data->faces[i].right_blink; faces[i].left_right_gaze = fd_data->faces[i].left_right_gaze; faces[i].top_bottom_gaze = fd_data->faces[i].top_bottom_gaze; } } qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; if(fd_type == QCAMERA_FD_PREVIEW){ cbArg.msg_type = CAMERA_MSG_PREVIEW_METADATA; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ cbArg.msg_type = CAMERA_MSG_META_DATA; } cbArg.data = faceResultBuffer; cbArg.metadata = roiData; cbArg.user_data = faceResultBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); faceResultBuffer->release(faceResultBuffer); } return rc; } /*=========================================================================== * FUNCTION : releaseCameraMemory * * DESCRIPTION: releases camera memory objects * * PARAMETERS : * @data : buffer to be released * @cookie : context data * @cbStatus: callback status * * RETURN : None *==========================================================================*/ void QCamera2HardwareInterface::releaseCameraMemory(void *data, void */*cookie*/, int32_t /*cbStatus*/) { camera_memory_t *mem = ( camera_memory_t * ) data; if ( NULL != mem ) { mem->release(mem); } } /*=========================================================================== * FUNCTION : returnStreamBuffer * * DESCRIPTION: returns back a stream buffer * * PARAMETERS : * @data : buffer to be released * @cookie : context data * @cbStatus: callback status * * RETURN : None *==========================================================================*/ void QCamera2HardwareInterface::returnStreamBuffer(void *data, void *cookie, int32_t /*cbStatus*/) { QCameraStream *stream = ( QCameraStream * ) cookie; int idx = ( int ) data; if ( ( NULL != stream )) { stream->bufDone(idx); } } /*=========================================================================== * FUNCTION : processHistogramStats * * DESCRIPTION: process histogram stats * * PARAMETERS : * @hist_data : ptr to histogram stats struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processHistogramStats(cam_hist_stats_t &stats_data) { if (!mParameters.isHistogramEnabled()) { CDBG("%s: Histogram not enabled, no ops here", __func__); return NO_ERROR; } camera_memory_t *histBuffer = mGetMemory(-1, sizeof(cam_histogram_data_t), 1, mCallbackCookie); if ( NULL == histBuffer ) { ALOGE("%s: Not enough memory for histogram data", __func__); return NO_MEMORY; } cam_histogram_data_t *pHistData = (cam_histogram_data_t *)histBuffer->data; if (pHistData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } switch (stats_data.type) { case CAM_HISTOGRAM_TYPE_BAYER: *pHistData = stats_data.bayer_stats.gb_stats; break; case CAM_HISTOGRAM_TYPE_YUV: *pHistData = stats_data.yuv_stats; break; } qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_STATS_DATA; cbArg.data = histBuffer; cbArg.user_data = histBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); histBuffer->release(histBuffer); } return NO_ERROR; } /*=========================================================================== * FUNCTION : calcThermalLevel * * DESCRIPTION: Calculates the target fps range depending on * the thermal level. * * PARAMETERS : * @level : received thermal level * @minFPS : minimum configured fps range * @maxFPS : maximum configured fps range * @adjustedRange : target fps range * @skipPattern : target skip pattern * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::calcThermalLevel( qcamera_thermal_level_enum_t level, const int minFPS, const int maxFPS, cam_fps_range_t &adjustedRange, enum msm_vfe_frame_skip_pattern &skipPattern) { // Initialize video fps to preview fps int minVideoFps = minFPS, maxVideoFps = maxFPS; cam_fps_range_t videoFps; // If HFR mode, update video fps accordingly if(isHFRMode()) { mParameters.getHfrFps(videoFps); minVideoFps = videoFps.video_min_fps; maxVideoFps = videoFps.video_max_fps; } CDBG_HIGH("%s: level: %d, preview minfps %d, preview maxfpS %d" "video minfps %d, video maxfpS %d", __func__, level, minFPS, maxFPS, minVideoFps, maxVideoFps); switch(level) { case QCAMERA_THERMAL_NO_ADJUSTMENT: { adjustedRange.min_fps = minFPS / 1000.0f; adjustedRange.max_fps = maxFPS / 1000.0f; adjustedRange.video_min_fps = minVideoFps / 1000.0f; adjustedRange.video_max_fps = maxVideoFps / 1000.0f; skipPattern = NO_SKIP; } break; case QCAMERA_THERMAL_SLIGHT_ADJUSTMENT: { adjustedRange.min_fps = (minFPS / 2) / 1000.0f; adjustedRange.max_fps = (maxFPS / 2) / 1000.0f; adjustedRange.video_min_fps = (minVideoFps / 2) / 1000.0f; adjustedRange.video_max_fps = (maxVideoFps / 2 ) / 1000.0f; if ( adjustedRange.min_fps < 1 ) { adjustedRange.min_fps = 1; } if ( adjustedRange.max_fps < 1 ) { adjustedRange.max_fps = 1; } if ( adjustedRange.video_min_fps < 1 ) { adjustedRange.video_min_fps = 1; } if ( adjustedRange.video_max_fps < 1 ) { adjustedRange.video_max_fps = 1; } skipPattern = EVERY_2FRAME; } break; case QCAMERA_THERMAL_BIG_ADJUSTMENT: { adjustedRange.min_fps = (minFPS / 4) / 1000.0f; adjustedRange.max_fps = (maxFPS / 4) / 1000.0f; adjustedRange.video_min_fps = (minVideoFps / 4) / 1000.0f; adjustedRange.video_max_fps = (maxVideoFps / 4 ) / 1000.0f; if ( adjustedRange.min_fps < 1 ) { adjustedRange.min_fps = 1; } if ( adjustedRange.max_fps < 1 ) { adjustedRange.max_fps = 1; } if ( adjustedRange.video_min_fps < 1 ) { adjustedRange.video_min_fps = 1; } if ( adjustedRange.video_max_fps < 1 ) { adjustedRange.video_max_fps = 1; } skipPattern = EVERY_4FRAME; } break; case QCAMERA_THERMAL_SHUTDOWN: { // Stop Preview? // Set lowest min FPS for now adjustedRange.min_fps = minFPS/1000.0f; adjustedRange.max_fps = minFPS/1000.0f; for ( int i = 0 ; i < gCamCapability[mCameraId]->fps_ranges_tbl_cnt ; i++ ) { if ( gCamCapability[mCameraId]->fps_ranges_tbl[i].min_fps < adjustedRange.min_fps ) { adjustedRange.min_fps = gCamCapability[mCameraId]->fps_ranges_tbl[i].min_fps; adjustedRange.max_fps = adjustedRange.min_fps; } } skipPattern = MAX_SKIP; adjustedRange.video_min_fps = adjustedRange.min_fps; adjustedRange.video_max_fps = adjustedRange.max_fps; } break; default: { CDBG("%s: Invalid thermal level %d", __func__, level); return BAD_VALUE; } break; } CDBG_HIGH("%s: Thermal level %d, FPS [%3.2f,%3.2f, %3.2f,%3.2f], frameskip %d", __func__, level, adjustedRange.min_fps, adjustedRange.max_fps, adjustedRange.video_min_fps, adjustedRange.video_max_fps,skipPattern); return NO_ERROR; } /*=========================================================================== * FUNCTION : recalcFPSRange * * DESCRIPTION: adjust the configured fps range regarding * the last thermal level. * * PARAMETERS : * @minFPS : minimum configured fps range * @maxFPS : maximum configured fps range * @adjustedRange : target fps range * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::recalcFPSRange(int &minFPS, int &maxFPS, cam_fps_range_t &adjustedRange) { enum msm_vfe_frame_skip_pattern skipPattern; calcThermalLevel(mThermalLevel, minFPS, maxFPS, adjustedRange, skipPattern); return NO_ERROR; } /*=========================================================================== * FUNCTION : updateThermalLevel * * DESCRIPTION: update thermal level depending on thermal events * * PARAMETERS : * @level : thermal level * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::updateThermalLevel( qcamera_thermal_level_enum_t level) { int ret = NO_ERROR; cam_fps_range_t adjustedRange; int minFPS, maxFPS; enum msm_vfe_frame_skip_pattern skipPattern; pthread_mutex_lock(&m_parm_lock); if (!mCameraOpened) { CDBG("%s: Camera is not opened, no need to update camera parameters", __func__); pthread_mutex_unlock(&m_parm_lock); return NO_ERROR; } mParameters.getPreviewFpsRange(&minFPS, &maxFPS); qcamera_thermal_mode thermalMode = mParameters.getThermalMode(); calcThermalLevel(level, minFPS, maxFPS, adjustedRange, skipPattern); mThermalLevel = level; if (thermalMode == QCAMERA_THERMAL_ADJUST_FPS) ret = mParameters.adjustPreviewFpsRange(&adjustedRange); else if (thermalMode == QCAMERA_THERMAL_ADJUST_FRAMESKIP) ret = mParameters.setFrameSkip(skipPattern); else ALOGE("%s: Incorrect thermal mode %d", __func__, thermalMode); pthread_mutex_unlock(&m_parm_lock); return ret; } /*=========================================================================== * FUNCTION : updateParameters * * DESCRIPTION: update parameters * * PARAMETERS : * @parms : input parameters string * @needRestart : output, flag to indicate if preview restart is needed * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::updateParameters(const char *parms, bool &needRestart) { int rc = NO_ERROR; pthread_mutex_lock(&m_parm_lock); String8 str = String8(parms); QCameraParameters param(str); rc = mParameters.updateParameters(param, needRestart); // update stream based parameter settings for (int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { m_channels[i]->UpdateStreamBasedParameters(mParameters); } } pthread_mutex_unlock(&m_parm_lock); return rc; } /*===========================================================================<|fim▁hole|> * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : This function must be called after updateParameters. * Otherwise, no change will be passed to backend to take effect. *==========================================================================*/ int QCamera2HardwareInterface::commitParameterChanges() { int rc = NO_ERROR; pthread_mutex_lock(&m_parm_lock); rc = mParameters.commitParameters(); if (rc == NO_ERROR) { // update number of snapshot based on committed parameters setting rc = mParameters.setNumOfSnapshot(); } pthread_mutex_unlock(&m_parm_lock); return rc; } /*=========================================================================== * FUNCTION : needDebugFps * * DESCRIPTION: if fps log info need to be printed out * * PARAMETERS : none * * RETURN : true: need print out fps log * false: no need to print out fps log *==========================================================================*/ bool QCamera2HardwareInterface::needDebugFps() { bool needFps = false; pthread_mutex_lock(&m_parm_lock); needFps = mParameters.isFpsDebugEnabled(); pthread_mutex_unlock(&m_parm_lock); return needFps; } /*=========================================================================== * FUNCTION : isCACEnabled * * DESCRIPTION: if CAC is enabled * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::isCACEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.cac", prop, "0"); int enableCAC = atoi(prop); return enableCAC == 1; } /*=========================================================================== * FUNCTION : is4k2kResolution * * DESCRIPTION: if resolution is 4k x 2k or true 4k x 2k * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::is4k2kResolution(cam_dimension_t* resolution) { bool enabled = false; if ((resolution->width == 4096 && resolution->height == 2160) || (resolution->width == 3840 && resolution->height == 2160) ) { enabled = true; } return enabled; } /*=========================================================================== * * FUNCTION : isPreviewRestartEnabled * * DESCRIPTION: Check whether preview should be restarted automatically * during image capture. * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::isPreviewRestartEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.restart", prop, "0"); int earlyRestart = atoi(prop); return earlyRestart == 1; } /*=========================================================================== ======= * FUNCTION : isAFRunning * * DESCRIPTION: if AF is in progress while in Auto/Macro focus modes * * PARAMETERS : none * * RETURN : true: AF in progress * false: AF not in progress *==========================================================================*/ bool QCamera2HardwareInterface::isAFRunning() { bool isAFInProgress = (m_currentFocusState == CAM_AF_SCANNING && (mParameters.getFocusMode() == CAM_FOCUS_MODE_AUTO || mParameters.getFocusMode() == CAM_FOCUS_MODE_MACRO)); return isAFInProgress; } /*=========================================================================== >>>>>>> c709c9a... Camera: Block CancelAF till HAL receives AF event. * FUNCTION : needReprocess * * DESCRIPTION: if reprocess is needed * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } if (mParameters.isHDREnabled()) { CDBG_HIGH("%s: need do reprocess for HDR", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } uint32_t feature_mask = 0; uint32_t required_mask = 0; feature_mask = gCamCapability[mCameraId]->qcom_supported_feature_mask; required_mask = gCamCapability[mCameraId]->min_required_pp_mask; if (((feature_mask & CAM_QCOM_FEATURE_CPP) > 0) && (getJpegRotation() > 0) && (mParameters.getRecordingHintValue() == false)) { // current rotation is not zero, and pp has the capability to process rotation CDBG_HIGH("%s: need to do reprocess for rotation=%d", __func__, getJpegRotation()); pthread_mutex_unlock(&m_parm_lock); return true; } if (isZSLMode()) { if (((gCamCapability[mCameraId]->min_required_pp_mask > 0) || mParameters.isWNREnabled() || isCACEnabled())) { // TODO: add for ZSL HDR later CDBG_HIGH("%s: need do reprocess for ZSL WNR or min PP reprocess", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } int snapshot_flipMode = mParameters.getFlipMode(CAM_STREAM_TYPE_SNAPSHOT); if (snapshot_flipMode > 0) { CDBG_HIGH("%s: Need do flip for snapshot in ZSL mode", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } } else { if (required_mask & CAM_QCOM_FEATURE_CPP) { ALOGD("%s: Need CPP in non-ZSL mode", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } } if ((gCamCapability[mCameraId]->qcom_supported_feature_mask & CAM_QCOM_FEATURE_SCALE) > 0 && mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()) { // Reproc Scale is enaled and also need Scaling to current Snapshot CDBG_HIGH("%s: need do reprocess for scale", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } if (mParameters.isUbiFocusEnabled() | mParameters.isChromaFlashEnabled() | mParameters.isHDREnabled() | mParameters.isOptiZoomEnabled()) { CDBG_HIGH("%s: need reprocess for |UbiFocus=%d|ChramaFlash=%d|OptiZoom=%d|", __func__, mParameters.isUbiFocusEnabled(), mParameters.isChromaFlashEnabled(), mParameters.isOptiZoomEnabled()); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : needRotationReprocess * * DESCRIPTION: if rotation needs to be done by reprocess in pp * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needRotationReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } uint32_t feature_mask = 0; feature_mask = gCamCapability[mCameraId]->qcom_supported_feature_mask; if (((feature_mask & CAM_QCOM_FEATURE_CPP) > 0) && (getJpegRotation() > 0)) { // current rotation is not zero // and pp has the capability to process rotation CDBG_HIGH("%s: need to do reprocess for rotation=%d", __func__, getJpegRotation()); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : needScaleReprocess * * DESCRIPTION: if scale needs to be done by reprocess in pp * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needScaleReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } if ((gCamCapability[mCameraId]->qcom_supported_feature_mask & CAM_QCOM_FEATURE_SCALE) > 0 && mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()) { // Reproc Scale is enaled and also need Scaling to current Snapshot CDBG_HIGH("%s: need do reprocess for scale", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : getThumbnailSize * * DESCRIPTION: get user set thumbnail size * * PARAMETERS : * @dim : output of thumbnail dimension * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::getThumbnailSize(cam_dimension_t &dim) { pthread_mutex_lock(&m_parm_lock); mParameters.getThumbnailSize(&dim.width, &dim.height); pthread_mutex_unlock(&m_parm_lock); } /*=========================================================================== * FUNCTION : getJpegQuality * * DESCRIPTION: get user set jpeg quality * * PARAMETERS : none * * RETURN : jpeg quality setting *==========================================================================*/ int QCamera2HardwareInterface::getJpegQuality() { int quality = 0; pthread_mutex_lock(&m_parm_lock); quality = mParameters.getJpegQuality(); pthread_mutex_unlock(&m_parm_lock); return quality; } /*=========================================================================== * FUNCTION : getJpegRotation * * DESCRIPTION: get rotation information to be passed into jpeg encoding * * PARAMETERS : none * * RETURN : rotation information *==========================================================================*/ int QCamera2HardwareInterface::getJpegRotation() { return mCaptureRotation; } /*=========================================================================== * FUNCTION : getOrientation * * DESCRIPTION: get rotation information from camera parameters * * PARAMETERS : none * * RETURN : rotation information *==========================================================================*/ void QCamera2HardwareInterface::getOrientation() { pthread_mutex_lock(&m_parm_lock); mCaptureRotation = mParameters.getJpegRotation(); pthread_mutex_unlock(&m_parm_lock); } /*=========================================================================== * FUNCTION : getExifData * * DESCRIPTION: get exif data to be passed into jpeg encoding * * PARAMETERS : none * * RETURN : exif data from user setting and GPS *==========================================================================*/ QCameraExif *QCamera2HardwareInterface::getExifData() { QCameraExif *exif = new QCameraExif(); if (exif == NULL) { ALOGE("%s: No memory for QCameraExif", __func__); return NULL; } int32_t rc = NO_ERROR; uint32_t count = 0; pthread_mutex_lock(&m_parm_lock); //set flash value mFlash = mParameters.getFlashValue(); mRedEye = mParameters.getRedEyeValue(); mFlashPresence = mParameters.getSupportedFlashModes(); // add exif entries char dateTime[20]; memset(dateTime, 0, sizeof(dateTime)); count = 20; rc = mParameters.getExifDateTime(dateTime, count); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_EXIF_DATE_TIME_ORIGINAL, EXIF_ASCII, count, (void *)dateTime); } else { ALOGE("%s: getExifDateTime failed", __func__); } rat_t focalLength; rc = mParameters.getExifFocalLength(&focalLength); if (rc == NO_ERROR) { exif->addEntry(EXIFTAGID_FOCAL_LENGTH, EXIF_RATIONAL, 1, (void *)&(focalLength)); } else { ALOGE("%s: getExifFocalLength failed", __func__); } uint16_t isoSpeed = mParameters.getExifIsoSpeed(); exif->addEntry(EXIFTAGID_ISO_SPEED_RATING, EXIF_SHORT, 1, (void *)&(isoSpeed)); char gpsProcessingMethod[EXIF_ASCII_PREFIX_SIZE + GPS_PROCESSING_METHOD_SIZE]; count = 0; rc = mParameters.getExifGpsProcessingMethod(gpsProcessingMethod, count); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_PROCESSINGMETHOD, EXIF_ASCII, count, (void *)gpsProcessingMethod); } else { CDBG("%s: getExifGpsProcessingMethod failed", __func__); } rat_t latitude[3]; char latRef[2]; rc = mParameters.getExifLatitude(latitude, latRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_LATITUDE, EXIF_RATIONAL, 3, (void *)latitude); exif->addEntry(EXIFTAGID_GPS_LATITUDE_REF, EXIF_ASCII, 2, (void *)latRef); } else { CDBG("%s: getExifLatitude failed", __func__); } rat_t longitude[3]; char lonRef[2]; rc = mParameters.getExifLongitude(longitude, lonRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_LONGITUDE, EXIF_RATIONAL, 3, (void *)longitude); exif->addEntry(EXIFTAGID_GPS_LONGITUDE_REF, EXIF_ASCII, 2, (void *)lonRef); } else { CDBG("%s: getExifLongitude failed", __func__); } rat_t altitude; char altRef; rc = mParameters.getExifAltitude(&altitude, &altRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_ALTITUDE, EXIF_RATIONAL, 1, (void *)&(altitude)); exif->addEntry(EXIFTAGID_GPS_ALTITUDE_REF, EXIF_BYTE, 1, (void *)&altRef); } else { CDBG("%s: getExifAltitude failed", __func__); } char gpsDateStamp[20]; rat_t gpsTimeStamp[3]; rc = mParameters.getExifGpsDateTimeStamp(gpsDateStamp, 20, gpsTimeStamp); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_DATESTAMP, EXIF_ASCII, strlen(gpsDateStamp) + 1, (void *)gpsDateStamp); exif->addEntry(EXIFTAGID_GPS_TIMESTAMP, EXIF_RATIONAL, 3, (void *)gpsTimeStamp); } else { ALOGE("%s: getExifGpsDataTimeStamp failed", __func__); } pthread_mutex_unlock(&m_parm_lock); return exif; } /*=========================================================================== * FUNCTION : setHistogram * * DESCRIPTION: set if histogram should be enabled * * PARAMETERS : * @histogram_en : bool flag if histogram should be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::setHistogram(bool histogram_en) { return mParameters.setHistogram(histogram_en); } /*=========================================================================== * FUNCTION : setFaceDetection * * DESCRIPTION: set if face detection should be enabled * * PARAMETERS : * @enabled : bool flag if face detection should be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::setFaceDetection(bool enabled) { return mParameters.setFaceDetection(enabled); } /*=========================================================================== * FUNCTION : needProcessPreviewFrame * * DESCRIPTION: returns whether preview frame need to be displayed * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ bool QCamera2HardwareInterface::needProcessPreviewFrame() { return m_stateMachine.isPreviewRunning() && mParameters.isDisplayFrameNeeded(); }; /*=========================================================================== * FUNCTION : prepareHardwareForSnapshot * * DESCRIPTION: prepare hardware for snapshot, such as LED * * PARAMETERS : * @afNeeded: flag indicating if Auto Focus needs to be done during preparation * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::prepareHardwareForSnapshot(int32_t afNeeded) { CDBG_HIGH("[KPI Perf] %s: Prepare hardware such as LED",__func__); return mCameraHandle->ops->prepare_snapshot(mCameraHandle->camera_handle, afNeeded); } /*=========================================================================== * FUNCTION : needFDMetadata * * DESCRIPTION: check whether we need process Face Detection metadata in this chanel * * PARAMETERS : * @channel_type: channel type * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needFDMetadata(qcamera_ch_type_enum_t channel_type) { //Note: Currently we only process ZSL channel bool value = false; if(channel_type == QCAMERA_CH_TYPE_ZSL){ //check if FD requirement is enabled if(mParameters.isSnapshotFDNeeded() && mParameters.isFaceDetectionEnabled()){ value = true; CDBG_HIGH("%s: Face Detection metadata is required in ZSL mode.", __func__); } } return value; } bool QCamera2HardwareInterface::removeSizeFromList(cam_dimension_t* size_list, uint8_t length, cam_dimension_t size) { bool found = false; int index = 0; for (int i = 0; i < length; i++) { if ((size_list[i].width == size.width && size_list[i].height == size.height)) { found = true; index = i; break; } } if (found) { for (int i = index; i < length; i++) { size_list[i] = size_list[i+1]; } } return found; } void QCamera2HardwareInterface::copyList(cam_dimension_t* src_list, cam_dimension_t* dst_list, uint8_t len){ for (int i = 0; i < len; i++) { dst_list[i] = src_list[i]; } } /*=========================================================================== * FUNCTION : defferedWorkRoutine * * DESCRIPTION: data process routine that executes deffered tasks * * PARAMETERS : * @data : user data ptr (QCamera2HardwareInterface) * * RETURN : None *==========================================================================*/ void *QCamera2HardwareInterface::defferedWorkRoutine(void *obj) { int running = 1; int ret; uint8_t is_active = FALSE; QCamera2HardwareInterface *pme = (QCamera2HardwareInterface *)obj; QCameraCmdThread *cmdThread = &pme->mDefferedWorkThread; do { do { ret = cam_sem_wait(&cmdThread->cmd_sem); if (ret != 0 && errno != EINVAL) { ALOGE("%s: cam_sem_wait error (%s)", __func__, strerror(errno)); return NULL; } } while (ret != 0); // we got notified about new cmd avail in cmd queue camera_cmd_type_t cmd = cmdThread->getCmd(); switch (cmd) { case CAMERA_CMD_TYPE_START_DATA_PROC: CDBG_HIGH("%s: start data proc", __func__); is_active = TRUE; break; case CAMERA_CMD_TYPE_STOP_DATA_PROC: CDBG_HIGH("%s: stop data proc", __func__); is_active = FALSE; // signal cmd is completed cam_sem_post(&cmdThread->sync_sem); break; case CAMERA_CMD_TYPE_DO_NEXT_JOB: { DeffWork *dw = reinterpret_cast<DeffWork *>(pme->mCmdQueue.dequeue()); if ( NULL == dw ) { ALOGE("%s : Invalid deferred work", __func__); break; } switch( dw->cmd ) { case CMD_DEFF_ALLOCATE_BUFF: { QCameraChannel * pChannel = dw->args.allocArgs.ch; if ( NULL == pChannel ) { ALOGE("%s : Invalid deferred work channel", __func__); break; } cam_stream_type_t streamType = dw->args.allocArgs.type; uint32_t iNumOfStreams = pChannel->getNumOfStreams(); QCameraStream *pStream = NULL; for ( uint32_t i = 0; i < iNumOfStreams; ++i) { pStream = pChannel->getStreamByIndex(i); if ( NULL == pStream ) { break; } if ( pStream->isTypeOf(streamType)) { if ( pStream->allocateBuffers() ) { ALOGE("%s: Error allocating buffers !!!", __func__); } break; } } { Mutex::Autolock l(pme->mDeffLock); pme->mDeffOngoingJobs[dw->id] = false; delete dw; pme->mDeffCond.signal(); } } break; case CMD_DEFF_PPROC_START: { QCameraChannel * pChannel = dw->args.pprocArgs; assert(pChannel); if (pme->m_postprocessor.start(pChannel) != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); pme->delChannel(QCAMERA_CH_TYPE_CAPTURE); } { Mutex::Autolock l(pme->mDeffLock); pme->mDeffOngoingJobs[dw->id] = false; delete dw; pme->mDeffCond.signal(); } } break; default: ALOGE("%s[%d]: Incorrect command : %d", __func__, __LINE__, dw->cmd); } } break; case CAMERA_CMD_TYPE_EXIT: running = 0; break; default: break; } } while (running); return NULL; } /*=========================================================================== * FUNCTION : isCaptureShutterEnabled * * DESCRIPTION: Check whether shutter should be triggered immediately after * capture * * PARAMETERS : * * RETURN : true - regular capture * false - other type of capture *==========================================================================*/ bool QCamera2HardwareInterface::isCaptureShutterEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.shutter", prop, "0"); int enableShutter = atoi(prop); return enableShutter == 1; } /*=========================================================================== * FUNCTION : queueDefferedWork * * DESCRIPTION: function which queues deferred tasks * * PARAMETERS : * @cmd : deferred task * @args : deffered task arguments * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::queueDefferedWork(DefferedWorkCmd cmd, DefferWorkArgs args) { Mutex::Autolock l(mDeffLock); for (int i = 0; i < MAX_ONGOING_JOBS; ++i) { if (!mDeffOngoingJobs[i]) { mCmdQueue.enqueue(new DeffWork(cmd, i, args)); mDeffOngoingJobs[i] = true; mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE); return i; } } return -1; } /*=========================================================================== * FUNCTION : waitDefferedWork * * DESCRIPTION: waits for a deffered task to finish * * PARAMETERS : * @job_id : deferred task id * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::waitDefferedWork(int32_t &job_id) { Mutex::Autolock l(mDeffLock); if ((MAX_ONGOING_JOBS <= job_id) || (0 > job_id)) { return NO_ERROR; } while ( mDeffOngoingJobs[job_id] == true ) { mDeffCond.wait(mDeffLock); } job_id = MAX_ONGOING_JOBS; return NO_ERROR; } /*=========================================================================== * FUNCTION : isRegularCapture * * DESCRIPTION: Check configuration for regular catpure * * PARAMETERS : * * RETURN : true - regular capture * false - other type of capture *==========================================================================*/ bool QCamera2HardwareInterface::isRegularCapture() { bool ret = false; if (numOfSnapshotsExpected() == 1 && !isLongshotEnabled() && !mParameters.getRecordingHintValue() && !isZSLMode() && !mParameters.isHDREnabled()) { ret = true; } return ret; } /*=========================================================================== * FUNCTION : getLogLevel * * DESCRIPTION: Reads the log level property into a variable * * PARAMETERS : * None * * RETURN : * None *==========================================================================*/ void QCamera2HardwareInterface::getLogLevel() { char prop[PROPERTY_VALUE_MAX]; uint32_t temp; uint32_t log_level; uint32_t debug_mask; memset(prop, 0, sizeof(prop)); /* Higher 4 bits : Value of Debug log level (Default level is 1 to print all CDBG_HIGH) Lower 28 bits : Control mode for sub module logging(Only 3 sub modules in HAL) 0x1 for HAL 0x10 for mm-camera-interface 0x100 for mm-jpeg-interface */ property_get("persist.camera.hal.debug.mask", prop, "268435463"); // 0x10000007=268435463 temp = atoi(prop); log_level = ((temp >> 28) & 0xF); debug_mask = (temp & HAL_DEBUG_MASK_HAL); if (debug_mask > 0) gCamHalLogLevel = log_level; else gCamHalLogLevel = 0; // Debug logs are not required if debug_mask is zero ALOGI("%s gCamHalLogLevel=%d",__func__, gCamHalLogLevel); return; } }; // namespace qcamera<|fim▁end|>
* FUNCTION : commitParameterChanges * * DESCRIPTION: commit parameter changes to the backend to take effect
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-09-24 05:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True<|fim▁hole|> operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('username', models.CharField(max_length=30)), ('password', models.CharField(max_length=30)), ], ), ]<|fim▁end|>
dependencies = [ ]
<|file_name|>variables_9.js<|end_file_name|><|fim▁begin|>var searchData= [ ['vertical_5fline',['vertical_line',['../class_abstract_board.html#a78c4d43cc32d9dc74d73156497db6d3f',1,'AbstractBoard']]]<|fim▁hole|><|fim▁end|>
];
<|file_name|>xsupport.py<|end_file_name|><|fim▁begin|>"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import modes from Vintageous.vi.utils import regions_transformer class _vi_slash_on_parser_done(sublime_plugin.WindowCommand): def run(self, key=None): state = State(self.window.active_view()) state.motion = cmd_defs.ViSearchForwardImpl() state.last_buffer_search = (state.motion._inp or state.last_buffer_search) class _vi_question_mark_on_parser_done(sublime_plugin.WindowCommand): def run(self, key=None): state = State(self.window.active_view()) state.motion = cmd_defs.ViSearchBackwardImpl() state.last_buffer_search = (state.motion._inp or state.last_buffer_search) # TODO: Test me. class VintageStateTracker(sublime_plugin.EventListener): def on_post_save(self, view): # Ensure the carets are within valid bounds. For instance, this is a # concern when `trim_trailing_white_space_on_save` is set to true. state = State(view) view.run_command('_vi_adjust_carets', {'mode': state.mode}) def on_query_context(self, view, key, operator, operand, match_all): vintage_state = State(view) return vintage_state.context.check(key, operator, operand, match_all) def on_close(self, view): settings.destroy(view) class ViMouseTracker(sublime_plugin.EventListener): def on_text_command(self, view, command, args): if command == 'drag_select': state = State(view) if state.mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK): if (args.get('extend') or (args.get('by') == 'words') or args.get('additive')): return elif not args.get('extend'): return ('sequence', {'commands': [ ['drag_select', args], ['_enter_normal_mode', { 'mode': state.mode}] ]}) elif state.mode == modes.NORMAL: # TODO(guillermooo): Dragging the mouse does not seem to # fire a different event than simply clicking. This makes it # hard to update the xpos. if args.get('extend') or (args.get('by') == 'words'): return ('sequence', {'commands': [ ['drag_select', args], ['_enter_visual_mode', { 'mode': state.mode}] ]}) # TODO: Test me. class ViFocusRestorerEvent(sublime_plugin.EventListener): def __init__(self): self.timer = None def action(self): self.timer = None def on_activated(self, view): if self.timer: self.timer.cancel() # Switching to a different view; enter normal mode. _init_vintageous(view) else: # Switching back from another application. Ignore. pass def on_deactivated(self, view): self.timer = threading.Timer(0.25, self.action) self.timer.start() class _vi_adjust_carets(sublime_plugin.TextCommand): def run(self, edit, mode=None): def f(view, s): if mode in (modes.NORMAL, modes.INTERNAL_NORMAL): if ((view.substr(s.b) == '\n' or s.b == view.size())<|fim▁hole|> return s regions_transformer(self.view, f) class Sequence(sublime_plugin.TextCommand): """Required so that mark_undo_groups_for_gluing and friends work. """ def run(self, edit, commands): for cmd, args in commands: self.view.run_command(cmd, args) class ResetVintageous(sublime_plugin.WindowCommand): def run(self): v = self.window.active_view() v.settings().erase('vintage') _init_vintageous(v) DotFile.from_user().run() print("Package.Vintageous: State reset.") sublime.status_message("Vintageous: State reset") class ForceExitFromCommandMode(sublime_plugin.WindowCommand): """ A sort of a panic button. """ def run(self): v = self.window.active_view() v.settings().erase('vintage') # XXX: What happens exactly when the user presses Esc again now? Which # more are we in? v.settings().set('command_mode', False) v.settings().set('inverse_caret_state', False) print("Vintageous: Exiting from command mode.") sublime.status_message("Vintageous: Exiting from command mode.") class VintageousToggleCtrlKeys(sublime_plugin.WindowCommand): def run(self): prefs = sublime.load_settings('Preferences.sublime-settings') value = prefs.get('vintageous_use_ctrl_keys', False) prefs.set('vintageous_use_ctrl_keys', (not value)) sublime.save_settings('Preferences.sublime-settings') status = 'enabled' if (not value) else 'disabled' print("Package.Vintageous: Use of Ctrl- keys {0}.".format(status)) sublime.status_message("Vintageous: Use of Ctrl- keys {0}" .format(status)) class ReloadVintageousSettings(sublime_plugin.TextCommand): def run(self, edit): DotFile.from_user().run() class VintageousOpenConfigFile(sublime_plugin.WindowCommand): """Opens or creates $packages/User/.vintageousrc. """ def run(self): path = os.path.realpath(os.path.join(sublime.packages_path(), 'User/.vintageousrc')) if os.path.exists(path): self.window.open_file(path) else: with open(path, 'w'): pass self.window.open_file(path)<|fim▁end|>
and not view.line(s.b).empty()): return sublime.Region(s.b - 1)
<|file_name|>gradient.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ """ import logging import numpy as np from numpy import ma from cotede.qctests import QCCheckVar try: import pandas as pd PANDAS_AVAILABLE = True except ImportError: PANDAS_AVAILABLE = False module_logger = logging.getLogger(__name__) def gradient(x): return curvature(x) def _curvature_pandas(x): """Equivalent to curvature() but using pandas It looks like the numpy implementation is faster even for larger datasets, so the default is with numpy. Note ---- - In the future this will be useful to handle specific window widths. """ if isinstance(x, ma.MaskedArray): x[x.mask] = np.nan x = x.data if not PANDAS_AVAILABLE: return curvature(x) if hasattr(x, "to_series"): x = x.to_series() elif not isinstance(x, pd.Series): x = pd.Series(x) y = np.nan * x y = x - (x.shift(1) + x.shift(-1)) / 2.0 return np.array(y) def curvature(x): """Curvature of a timeseries This test is commonly known as gradient for historical reasons, but that is a bad name choice since it is not the actual gradient, like: d/dx + d/dy + d/dz, but as defined by GTSPP, EuroGOOS and others, which is actually the curvature of the timeseries.. Note ---- - Pandas.Series operates with indexes, so it should be done different. In that case, call for _curvature_pandas. """ if isinstance(x, ma.MaskedArray): x[x.mask] = np.nan x = x.data if PANDAS_AVAILABLE and isinstance(x, pd.Series): return _curvature_pandas(x) x = np.atleast_1d(x) y = np.nan * x y[1:-1] = x[1:-1] - (x[:-2] + x[2:]) / 2.0 return y class Gradient(QCCheckVar): def set_features(self): self.features = {"gradient": curvature(self.data[self.varname])} def test(self): self.flags = {} try: threshold = self.cfg["threshold"] except KeyError: module_logger.debug( "Deprecated cfg format. It should contain a threshold item." ) threshold = self.cfg assert ( (np.size(threshold) == 1) and (threshold is not None) and (np.isfinite(threshold))<|fim▁hole|> feature = np.absolute(self.features["gradient"]) flag[feature > threshold] = self.flag_bad flag[feature <= threshold] = self.flag_good x = np.atleast_1d(self.data[self.varname]) flag[ma.getmaskarray(x) | ~np.isfinite(x)] = 9 self.flags["gradient"] = flag<|fim▁end|>
) flag = np.zeros(np.shape(self.data[self.varname]), dtype="i1")
<|file_name|>zh-hant.js<|end_file_name|><|fim▁begin|><|fim▁hole|>MSG.title = "Webduino Blockly 課程 1-3:控制兩顆 LED 燈"; MSG.subTitle = "課程 1-3:控制兩顆 LED 燈"; MSG.demoDescription = "點選下圖左右兩顆燈泡,分別控制兩顆 LED 的開或關";<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- #--------------------------------------------------------------------# # This file is part of Py-cnotify. # # # # Copyright (C) 2007, 2008 Paul Pogonyshev. # # # # This library is free software; you can redistribute it and/or # # modify it under the terms of the GNU Lesser General Public License # # as published by the Free Software Foundation; either version 2.1 # # of the License, or (at your option) any later version. # # # # This library is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # # Lesser General Public License for more details. # # # # You should have received a copy of the GNU Lesser General Public # # License along with this library; if not, write to the Free # # Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # # Boston, MA 02110-1301 USA # #--------------------------------------------------------------------# """ cNotify package provides three main concepts: I{L{signals <signal>}}, I{L{conditions <condition>}} and I{L{variables <variable>}}. Signals are basically lists of callables that can be I{emitted} and then will call all contained callables (I{handler} of a signal) in turn. Conditions are boolean values complemented with a signal that is emitted when condition’s I{state} changes. Variables are akin to conditions but can hold arbitrary I{values}, not just booleans. Conditions, unlike variables, can also be combined using standard logic operators, like negation, conjunction and so on. All three concepts provide separation between providers (writers, setters) and listeners (readers, getters) of some entity. Conditions and variables make the entity explicit—it is a boolean state for the former and arbitrary Python object for the latter (though derived variable classes can restrict the set of allowed values.) Here is a quick example: >>> from cnotify.variable import *<|fim▁hole|> ... ... import sys ... name.changed.connect ( ... lambda string: sys.stdout.write ('Hello there, %s!\\n' % string)) ... ... name.value = 'Chuk' Note that when setting the C{name} variable, you don’t need to know who, if anyone, listens to changes to it. Interested parties take care to express their interest themselves and are informed upon a change automatically. Here is a little more elaborate example with the same functionality (it requires U{PyGTK <http://pygtk.org/>}): >>> from cnotify.variable import * ... import gtk ... ... name = Variable () ... ... def welcome_user (name_string): ... dialog = gtk.MessageDialog (None, 0, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, ... 'Hello there, %s!' % name_string) ... dialog.run () ... dialog.destroy () ... ... name.changed.connect (welcome_user) ... ... def set_name_from_entry (entry): ... name.value = entry.get_text () ... ... window = gtk.Window () ... window.set_title ('Enter name') ... ... entry = gtk.Entry () ... entry.show () ... window.add (entry) ... ... entry.connect ('activate', set_name_from_entry) ... window.connect ('destroy', lambda window: gtk.main_quit ()) ... ... window.present () ... ... gtk.main () Note that C{window} knows absolutely nothing about how changes to C{name} variable are handled. If you play with this example, you will notice one thing: pressing C{Enter} in the main window twice doesn’t pop the welcoming dialog twice. That is because both conditions and variables emit their ‘changed’ signal I{only} when their state/value actually changes, not on every assignment. Now a final, quite complicated, example introducing conditions and some other features: >>> from cnotify.all import * ... ... pilots = Variable () ... fuel = Variable () ... ... import sys ... ... pilots.changed.connect ( ... lambda pilots: sys.stdout.write ('Pilots are %s\\n' % pilots)) ... fuel.changed.connect ( ... lambda amount: sys.stdout.write ('Got %d litres of fuel\\n' % amount)) ... ... def ready_state_changed (ready): ... if ready: ... sys.stdout.write ('Ready to get off!\\n') ... else: ... sys.stdout.write ('Missing pilots or fuel\\n') ... ... ready = pilots.is_true () & fuel.predicate (lambda amount: amount > 0) ... ready.store (ready_state_changed) ... ... pilots.value = 'Jen and Jim' ... fuel.value = 500 ... ... fuel.value = 0 First line of example shows a way to save typing by importing all package contents at once. Whether to use this technique is up to you. Following lines up to C{ready = ...} should be familiar. Now let’s consider that assignment closer. First, C{L{pilots.is_true () <variable.AbstractVariable.is_true>}} code creates a condition that is true depending on C{pilots} value (true for non-empty sequences in our case.) It is just a convenience wrapper over C{L{AbstractVariable.predicate <variable.AbstractVariable.predicate>}} method. Now, the latter is also used directly in this line of code. It creates a condition that is true as long as variable’s value conforms to the passed in predicate. In particular, C{fuel.predicate (lambda amount: amount > 0)} creates a condition that is true if C{fuel}’s value is greater than zero. Predicate conditions will recompute their state each time variable’s value changes and that’s the point in using them. Finally, two just constructed conditions are combined into a third condition using ‘and’ operator (C{&}). This third condition will be true if and only if I{both} its term conditions are true. Conditions support four logic operations: negation, conjunction, disjunction and xoring (with these operators: C{~}, C{&}, C{|} and C{^}.) In addition, each condition has C{L{if_else <condition.AbstractCondition.if_else>}} method, which is much like Python’s C{if} operator. The next line introduces one more new method: C{L{store <base.AbstractValueObject.store>}}. It is really just like connecting its only argument to the ‘changed’ signal, except that it is also called once with the current state of the condition (or value of a variable.) The example should produce this output:: Missing pilots or fuel Pilots are Jen and Jim Got 500 litres of fuel Ready to get off! Got 0 litres of fuel Missing pilots or fuel Notable here is the output from C{ready_state_changed} function. It is called once at the beginning from the C{store} method with the state of C{ready} condition (then C{False}.) Both later calls correspond to changes in C{ready}’s state. When both C{pilots} and C{fuel} variables are set, corresponding predicate conditions become true and so does the C{ready} condition. However, when one of the predicate conditions becomes false (as the result of C{fuel} being set to zero), C{ready} turns false again. Note that C{ready_state_changed} is not called in between of setting C{pilots} and C{fuel} variable. C{ready} state is recomputed, but since it remains the same, ‘changed’ signal is not emitted. G{packagetree} """ __docformat__ = 'epytext en' # CONFIGURATION __version__ = '0.3.2.1' """ Version of Py-cnotify, as a string. """ version_tuple = (0, 3, 2, 1) """ Version of Py-cnotify, as a tuple of integers. It is guaranteed that version tuples of later versions will compare greater that those of earlier versions. """ # /CONFIGURATION # Local variables: # mode: python # python-indent: 4 # indent-tabs-mode: nil # fill-column: 90 # End:<|fim▁end|>
... name = Variable ()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python __version__ = '0.0.1' import pysimplesoap.client import pysimplesoap.simplexml <|fim▁hole|>from zimbrasoap.soap import soap,admin,mail<|fim▁end|>
<|file_name|>SplittingXMLFilter.java<|end_file_name|><|fim▁begin|>/* * Copyright 2011-2015 The Trustees of the University of Pennsylvania * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.upenn.library.xmlaminar.parallel; import static edu.upenn.library.xmlaminar.parallel.JoiningXMLFilter.GROUP_BY_SYSTEMID_FEATURE_NAME; import edu.upenn.library.xmlaminar.parallel.callback.OutputCallback; import edu.upenn.library.xmlaminar.parallel.callback.StdoutCallback; import edu.upenn.library.xmlaminar.parallel.callback.XMLReaderCallback; import edu.upenn.library.xmlaminar.VolatileSAXSource; import edu.upenn.library.xmlaminar.VolatileXMLFilterImpl; import java.io.IOException; import java.util.ArrayDeque; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import javax.xml.transform.sax.SAXSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.helpers.XMLFilterImpl; /** * * @author Michael Gibney */ public class SplittingXMLFilter extends QueueSourceXMLFilter implements OutputCallback { private static final Logger LOG = LoggerFactory.getLogger(SplittingXMLFilter.class); private final AtomicBoolean parsing = new AtomicBoolean(false); private volatile Future<?> consumerTask; private int level = -1; private int startEventLevel = -1; private final ArrayDeque<StructuralStartEvent> startEventStack = new ArrayDeque<StructuralStartEvent>(); public static void main(String[] args) throws Exception { LevelSplittingXMLFilter sxf = new LevelSplittingXMLFilter(); sxf.setChunkSize(1); sxf.setOutputCallback(new StdoutCallback()); sxf.setInputType(InputType.indirect); sxf.parse(new InputSource("../cli/whole-indirect.txt")); } public void ensureCleanInitialState() { if (level != -1) { throw new IllegalStateException("level != -1: "+level); } if (startEventLevel != -1) { throw new IllegalStateException("startEventLevel != -1: "+startEventLevel); } if (!startEventStack.isEmpty()) { throw new IllegalStateException("startEventStack not empty: "+startEventStack.size()); } if (parsing.get()) { throw new IllegalStateException("already parsing"); } if (consumerTask != null) { throw new IllegalStateException("consumerTask not null"); } if (producerThrowable != null || consumerThrowable != null) { throw new IllegalStateException("throwable not null: "+producerThrowable+", "+consumerThrowable); } int arrived; if ((arrived = parseBeginPhaser.getArrivedParties()) > 0) { throw new IllegalStateException("parseBeginPhaser arrived count: "+arrived); } if ((arrived = parseEndPhaser.getArrivedParties()) > 0) { throw new IllegalStateException("parseEndPhaser arrived count: "+arrived); } if ((arrived = parseChunkDonePhaser.getArrivedParties()) > 0) { throw new IllegalStateException("parseChunkDonePhaser arrived count: "+arrived); } } @Override protected void initialParse(VolatileSAXSource in) { synchronousParser.setParent(this); setupParse(in.getInputSource()); } @Override protected void repeatParse(VolatileSAXSource in) { reset(false); setupParse(in.getInputSource()); } private void setupParse(InputSource in) { setContentHandler(synchronousParser); if (!parsing.compareAndSet(false, true)) { throw new IllegalStateException("failed setting parsing = true"); } OutputLooper outputLoop = new OutputLooper(in, null, Thread.currentThread()); consumerTask = getExecutor().submit(outputLoop); } @Override protected void finished() throws SAXException { reset(false); } public void reset() { try { setFeature(RESET_PROPERTY_NAME, true); } catch (SAXException ex) { throw new AssertionError(ex); } } protected void reset(boolean cancel) { try { if (consumerTask != null) { if (cancel) { consumerTask.cancel(true); } else { consumerTask.get(); } } } catch (InterruptedException ex) { throw new RuntimeException(ex); } catch (ExecutionException ex) { throw new RuntimeException(ex); } consumerTask = null; consumerThrowable = null; producerThrowable = null; if (splitDirector != null) { splitDirector.reset(); } startEventStack.clear(); if (!parsing.compareAndSet(false, false) && !cancel) { LOG.warn("at {}.reset(), parsing had been set to true", SplittingXMLFilter.class.getName(), new IllegalStateException()); } } @Override public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { if (RESET_PROPERTY_NAME.equals(name) && value) { try { super.setFeature(name, value); } catch (SAXException ex) { /* * could run here if only want to run if deepest resettable parent. * ... but I don't think that's the case here. */ } /* * reset(false) because the downstream consumer thread issued this * reset request (initiated the interruption). */ reset(true); } else { super.setFeature(name, value); } } @Override public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { if (RESET_PROPERTY_NAME.equals(name)) { try { return super.getFeature(name) && consumerTask == null; } catch (SAXException ex) { return consumerTask == null; } } else if (GROUP_BY_SYSTEMID_FEATURE_NAME.equals(name)) { return false; }else { return super.getFeature(name); } } private final SynchronousParser synchronousParser = new SynchronousParser(); @Override public boolean allowOutputCallback() { return true; } private class SynchronousParser extends VolatileXMLFilterImpl { @Override public void parse(InputSource input) throws SAXException, IOException { parse(); } @Override public void parse(String systemId) throws SAXException, IOException { parse(); } private void parse() throws SAXException, IOException { parseBeginPhaser.arrive(); try { parseEndPhaser.awaitAdvanceInterruptibly(parseEndPhaser.arrive()); } catch (InterruptedException ex) { throw new RuntimeException(ex); } parseChunkDonePhaser.arrive(); } } private final Phaser parseBeginPhaser = new Phaser(2); private final Phaser parseEndPhaser = new Phaser(2); private final Phaser parseChunkDonePhaser = new Phaser(2); private class OutputLooper implements Runnable { private final InputSource input; private final String systemId; private final Thread producer; private OutputLooper(InputSource in, String systemId, Thread producer) { this.input = in; this.systemId = systemId; this.producer = producer; } private void parseLoop(InputSource input, String systemId) throws SAXException, IOException { if (input != null) { while (parsing.get()) { outputCallback.callback(new VolatileSAXSource(synchronousParser, input)); try { parseChunkDonePhaser.awaitAdvanceInterruptibly(parseChunkDonePhaser.arrive()); } catch (InterruptedException ex) { throw new RuntimeException(ex); } } } else { throw new NullPointerException("null InputSource"); } } @Override public void run() { try { parseLoop(input, systemId); } catch (Throwable t) { if (producerThrowable == null) { consumerThrowable = t; producer.interrupt(); } else { t = producerThrowable; producerThrowable = null; throw new RuntimeException(t); } } } } @Override public void parse(InputSource input) throws SAXException, IOException { parse(input, null); } @Override public void parse(String systemId) throws SAXException, IOException { parse(null, systemId); } private void parse(InputSource input, String systemId) { try { if (input != null) { super.parse(input); } else { super.parse(systemId); } } catch (Throwable t) { try { if (consumerThrowable == null) { producerThrowable = t; reset(true); } else {<|fim▁hole|> } finally { if (outputCallback != null) { outputCallback.finished(t); } throw new RuntimeException(t); } } outputCallback.finished(null); } @Override public XMLReaderCallback getOutputCallback() { return outputCallback; } @Override public void setOutputCallback(XMLReaderCallback xmlReaderCallback) { this.outputCallback = xmlReaderCallback; } private volatile XMLReaderCallback outputCallback; private volatile Throwable consumerThrowable; private volatile Throwable producerThrowable; @Override public void startDocument() throws SAXException { try { parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive()); } catch (InterruptedException ex) { throw new RuntimeException(ex); } startEventStack.push(new StructuralStartEvent()); super.startDocument(); level++; startEventLevel++; } @Override public void endDocument() throws SAXException { startEventLevel--; level--; super.endDocument(); startEventStack.pop(); if (!parsing.compareAndSet(true, false)) { throw new IllegalStateException("failed at endDocument setting parsing = false"); } parseEndPhaser.arrive(); } private int bypassLevel = Integer.MAX_VALUE; private int bypassStartEventLevel = Integer.MAX_VALUE; protected final void split() throws SAXException { writeSyntheticEndEvents(); parseEndPhaser.arrive(); try { parseBeginPhaser.awaitAdvanceInterruptibly(parseBeginPhaser.arrive()); } catch (InterruptedException ex) { throw new RuntimeException(ex); } writeSyntheticStartEvents(); } private void writeSyntheticEndEvents() throws SAXException { Iterator<StructuralStartEvent> iter = startEventStack.iterator(); while (iter.hasNext()) { StructuralStartEvent next = iter.next(); switch (next.type) { case DOCUMENT: super.endDocument(); break; case PREFIX_MAPPING: super.endPrefixMapping(next.one); break; case ELEMENT: super.endElement(next.one, next.two, next.three); } } } private void writeSyntheticStartEvents() throws SAXException { Iterator<StructuralStartEvent> iter = startEventStack.descendingIterator(); while (iter.hasNext()) { StructuralStartEvent next = iter.next(); switch (next.type) { case DOCUMENT: super.startDocument(); break; case PREFIX_MAPPING: super.startPrefixMapping(next.one, next.two); break; case ELEMENT: super.startElement(next.one, next.two, next.three, next.atts); } } } private SplitDirector splitDirector = new SplitDirector(); public SplitDirector getSplitDirector() { return splitDirector; } public void setSplitDirector(SplitDirector splitDirector) { this.splitDirector = splitDirector; } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (level < bypassLevel && handleDirective(splitDirector.startElement(uri, localName, qName, atts, level))) { startEventStack.push(new StructuralStartEvent(uri, localName, qName, atts)); } super.startElement(uri, localName, qName, atts); level++; startEventLevel++; } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { if (level < bypassLevel && handleDirective(splitDirector.startPrefixMapping(prefix, uri, level))) { startEventStack.push(new StructuralStartEvent(prefix, uri)); } super.startPrefixMapping(prefix, uri); startEventLevel++; } /** * Returns true if the generating event should be added to * the startEvent stack * @param directive * @return * @throws SAXException */ private boolean handleDirective(SplitDirective directive) throws SAXException { switch (directive) { case SPLIT: bypassLevel = level; bypassStartEventLevel = startEventLevel; split(); return false; case SPLIT_NO_BYPASS: split(); return true; case NO_SPLIT_BYPASS: bypassLevel = level; bypassStartEventLevel = startEventLevel; return false; case NO_SPLIT: return true; default: throw new AssertionError(); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { startEventLevel--; level--; super.endElement(uri, localName, qName); if (handleStructuralEndEvent()) { handleDirective(splitDirector.endElement(uri, localName, qName, level)); } } private boolean handleStructuralEndEvent() { if (level > bypassLevel) { return false; } else if (level < bypassLevel) { startEventStack.pop(); return true; } else { if (startEventLevel == bypassStartEventLevel) { bypassEnd(); return true; } else if (startEventLevel < bypassStartEventLevel) { startEventStack.pop(); return true; } else { return false; } } } @Override public void endPrefixMapping(String prefix) throws SAXException { startEventLevel--; super.endPrefixMapping(prefix); if (handleStructuralEndEvent()) { handleDirective(splitDirector.endPrefixMapping(prefix, level)); } } private void bypassEnd() { bypassLevel = Integer.MAX_VALUE; bypassStartEventLevel = Integer.MAX_VALUE; } @Override public void characters(char[] ch, int start, int length) throws SAXException { if (level <= bypassLevel) { handleDirective(splitDirector.characters(ch, start, length, level)); } super.characters(ch, start, length); } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { if (level <= bypassLevel) { handleDirective(splitDirector.ignorableWhitespace(ch, start, length, level)); } super.ignorableWhitespace(ch, start, length); } @Override public void skippedEntity(String name) throws SAXException { if (level <= bypassLevel) { handleDirective(splitDirector.skippedEntity(name, level)); } super.skippedEntity(name); } public static enum SplitDirective { SPLIT, NO_SPLIT, SPLIT_NO_BYPASS, NO_SPLIT_BYPASS } public static class SplitDirector { public void reset() { // default NOOP implementation } public SplitDirective startPrefixMapping(String prefix, String uri, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective endPrefixMapping(String prefix, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective startElement(String uri, String localName, String qName, Attributes atts, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective endElement(String uri, String localName, String qName, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective characters(char[] ch, int start, int length, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective ignorableWhitespace(char[] ch, int start, int length, int level) throws SAXException { return SplitDirective.NO_SPLIT; } public SplitDirective skippedEntity(String name, int level) throws SAXException { return SplitDirective.NO_SPLIT; } } }<|fim▁end|>
t = consumerThrowable; consumerThrowable = null; }
<|file_name|>TagsArrayInput.tsx<|end_file_name|><|fim▁begin|>import React, {forwardRef, useCallback, useImperativeHandle, useMemo, useRef} from 'react' import {FormField} from '@sanity/base/components' import {useId} from '@reach/auto-id' import {TagInput} from '../components/tagInput' import PatchEvent, {set, unset} from '../PatchEvent' import {Props} from './types' export const TagsArrayInput = forwardRef(function TagsArrayInput( props: Props<string[]>, ref: React.Ref<{focus: () => void}> ) { const {level, markers, onChange, onFocus, presence, readOnly, type, value = []} = props const id = useId() const tagInputValue = useMemo(() => value.map((v) => ({value: v})), [value]) const inputRef = useRef<HTMLInputElement | null>(null) const handleChange = useCallback( (nextValue: {value: string}[]) => { const patch = nextValue.length === 0 ? unset() : set(nextValue.map((v) => v.value)) onChange(PatchEvent.from(patch)) }, [onChange] ) useImperativeHandle(ref, () => ({ focus: () => inputRef.current?.focus(), })) return (<|fim▁hole|> description={type.description} __unstable_presence={presence} inputId={id} __unstable_markers={markers} > <TagInput id={id} onChange={handleChange} onFocus={onFocus} readOnly={readOnly} ref={inputRef} value={tagInputValue} /> </FormField> ) })<|fim▁end|>
<FormField level={level} title={type.title}
<|file_name|>store.ts<|end_file_name|><|fim▁begin|>/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ // React libraries import { Store, redux } from "../app-framework"; // CoCalc libraries import { cmp, cmp_array, set } from "smc-util/misc"; import { DirectoryListingEntry } from "smc-util/types"; // Course Library import { STEPS } from "./util"; import { Map, Set, List } from "immutable"; import { TypedMap, createTypedMap } from "../app-framework"; import { SITE_NAME } from "smc-util/theme"; // Upgrades import * as project_upgrades from "./project-upgrades"; import { Datastore } from "../projects/actions"; import { StudentProjectFunctionality } from "./configuration/customize-student-project-functionality"; export const PARALLEL_DEFAULT = 5; export const MAX_COPY_PARALLEL = 25; import { AssignmentCopyStep, AssignmentStatus, SiteLicenseStrategy, UpgradeGoal, } from "./types"; import { NotebookScores } from "../jupyter/nbgrader/autograde"; import { CourseActions } from "./actions"; export type TerminalCommandOutput = TypedMap<{ project_id: string; stdout?: string; stderr?: string; }>; export type TerminalCommand = TypedMap<{ input?: string; output?: List<TerminalCommandOutput>; running?: boolean; }>; export type StudentRecord = TypedMap<{ create_project: number; // Time the student project was created account_id: string; student_id: string; first_name: string; last_name: string; last_active: number; hosting: string; email_address: string; project_id: string; deleted: boolean; note: string; last_email_invite: number; }>; export type StudentsMap = Map<string, StudentRecord>; export type LastCopyInfo = { time?: number; error?: string; start?: number; }; export type AssignmentRecord = TypedMap<{ assignment_id: string; deleted: boolean; due_date: Date; path: string; peer_grade?: { enabled: boolean; due_date: number; map: { [student_id: string]: string[] }; // map from student_id to *who* will grade that student }; note: string; last_assignment?: { [student_id: string]: LastCopyInfo }; last_collect?: { [student_id: string]: LastCopyInfo }; last_peer_assignment?: { [student_id: string]: LastCopyInfo }; last_peer_collect?: { [student_id: string]: LastCopyInfo }; last_return_graded?: { [student_id: string]: LastCopyInfo }; skip_assignment: boolean; skip_collect: boolean; skip_grading: boolean; target_path: string; collect_path: string; graded_path: string; nbgrader?: boolean; // if true, probably includes at least one nbgrader ipynb file listing?: DirectoryListingEntry[]; grades?: { [student_id: string]: string }; comments?: { [student_id: string]: string }; nbgrader_scores?: { [student_id: string]: { [ipynb: string]: NotebookScores | string }; }; nbgrader_score_ids?: { [ipynb: string]: string[] }; }>; export type AssignmentsMap = Map<string, AssignmentRecord>; export type HandoutRecord = TypedMap<{ deleted: boolean; handout_id: string; target_path: string; path: string; note: string; status: { [student_id: string]: LastCopyInfo }; }>; export type HandoutsMap = Map<string, HandoutRecord>; export type SortDescription = TypedMap<{ column_name: string; is_descending: boolean; }>; export type CourseSettingsRecord = TypedMap<{ allow_collabs: boolean; student_project_functionality?: StudentProjectFunctionality; description: string; email_invite: string; institute_pay: boolean; pay: string | Date; shared_project_id: string; student_pay: boolean; title: string; upgrade_goal: Map<any, any>; site_license_id?: string; site_license_strategy?: SiteLicenseStrategy; copy_parallel?: number; nbgrader_grade_in_instructor_project?: boolean; // deprecated nbgrader_grade_project?: string; nbgrader_include_hidden_tests?: boolean; nbgrader_cell_timeout_ms?: number; nbgrader_timeout_ms?: number; nbgrader_max_output?: number; nbgrader_max_output_per_cell?: number; nbgrader_parallel?: number; }>; export const CourseSetting = createTypedMap<CourseSettingsRecord>(); export type IsGradingMap = Map<string, boolean>; export type ActivityMap = Map<number, string>; // This NBgraderRunInfo is a map from what nbgrader task is running // to when it was started (ms since epoch). The keys are as follows: // 36-character [account_id] = means that entire assignment with that id is being graded // [account_id]-[student_id] = the particular assignment for that student is being graded // We do not track grading of individual files in an assignment. // This is NOT sync'd across users, since that would increase network traffic and // is probably not critical to do, since the worst case scenario is just running nbgrader // more than once at the same time, which is probably just *inefficient*. export type NBgraderRunInfo = Map<string, number>; export interface CourseState { activity: ActivityMap; action_all_projects_state: string; active_student_sort: { column_name: string; is_descending: boolean }; active_assignment_sort: { column_name: string; is_descending: boolean }; assignments: AssignmentsMap; course_filename: string; course_project_id: string; configuring_projects?: boolean; error?: string; expanded_students: Set<string>; expanded_assignments: Set<string>; expanded_peer_configs: Set<string>; expanded_handouts: Set<string>; expanded_skip_gradings: Set<string>; active_feedback_edits: IsGradingMap; handouts: HandoutsMap; loading: boolean; // initially loading the syncdoc from disk. saving: boolean; settings: CourseSettingsRecord; show_save_button: boolean; students: StudentsMap; unsaved?: boolean; terminal_command?: TerminalCommand; nbgrader_run_info?: NBgraderRunInfo; } export class CourseStore extends Store<CourseState> { private assignment_status_cache?: { [assignment_id: string]: AssignmentStatus; }; private handout_status_cache?: { [key: string]: { handout: number; not_handout: number }; }; // Return true if there are any non-deleted assignments that use peer grading public any_assignment_uses_peer_grading(): boolean { for (const [, assignment] of this.get_assignments()) { if ( assignment.getIn(["peer_grade", "enabled"]) && !assignment.get("deleted") ) { return true; } } return false; } // Return Javascript array of the student_id's of the students // that graded the given student, or undefined if no relevant assignment. public get_peers_that_graded_student( assignment_id: string, student_id: string ): string[] { const peers: string[] = []; const assignment = this.get_assignment(assignment_id); if (assignment == null) return peers; const map = assignment.getIn(["peer_grade", "map"]); if (map == null) { return peers; } for (const [other_student_id, who_grading] of map) { if (who_grading.includes(student_id)) { peers.push(other_student_id as string); // typescript thinks it could be a number? } } return peers; } public get_shared_project_id(): string | undefined { // return project_id (a string) if shared project has been created, // or undefined or empty string otherwise. return this.getIn(["settings", "shared_project_id"]); } public get_pay(): string | Date { const settings = this.get("settings"); if (settings == null || !settings.get("student_pay")) return ""; const pay = settings.get("pay"); if (!pay) return ""; return pay; } public get_datastore(): Datastore { const settings = this.get("settings"); if (settings == null || settings.get("datastore") == null) return undefined; const ds = settings.get("datastore"); if (typeof ds === "boolean" || Array.isArray(ds)) { return ds; } else { console.warn(`course/get_datastore: encountered faulty value:`, ds); return undefined; } } public get_allow_collabs(): boolean { return !!this.getIn(["settings", "allow_collabs"]); } public get_email_invite(): string { const invite = this.getIn(["settings", "email_invite"]); if (invite) return invite; const site_name = redux.getStore("customize").get("site_name") ?? SITE_NAME; return `Hello!\n\nWe will use ${site_name} for the course *{title}*.\n\nPlease sign up!\n\n--\n\n{name}`; } public get_students(): StudentsMap { return this.get("students"); } // Return the student's name as a string, using a // bunch of heuristics to try to present the best // reasonable name, given what we know. For example, // it uses an instructor-given custom name if it was set. public get_student_name(student_id: string): string { const { student } = this.resolve({ student_id }); if (student == null) { // Student does not exist at all in store -- this shouldn't happen return "Unknown Student"; } // Try instructor assigned name: if (student.get("first_name")?.trim() || student.get("last_name")?.trim()) { return [ student.get("first_name", "")?.trim(), student.get("last_name", "")?.trim(), ].join(" "); } const account_id = student.get("account_id"); if (account_id == null) { // Student doesn't have an account yet on CoCalc (that we know about). // Email address: if (student.has("email_address")) { return student.get("email_address"); } // One of the above had to work, since we add students by email or account. // But put this in anyways: return "Unknown Student"; } // Now we have a student with a known CoCalc account. // We would have returned early above if there was an instructor assigned name, // so we just return their name from cocalc, if known. const users = this.redux.getStore("users"); if (users == null) throw Error("users must be defined"); const name = users.get_name(account_id); if (name?.trim()) return name; // This situation usually shouldn't happen, but maybe could in case the user was known but // then removed themselves as a collaborator, or something else odd. if (student.has("email_address")) { return student.get("email_address"); } // OK, now there is really no way to identify this student. I suppose this could // happen if the student was added by searching for their name, then they removed // themselves. Nothing useful we can do at this point. return "Unknown Student"; } // Returns student name as with get_student_name above, // but also include an email address in angle braces, // if one is known in a full version of the name. // This is purely meant to provide a bit of extra info // for the instructor, and not actually used to send emails. public get_student_name_extra( student_id: string ): { simple: string; full: string } { const { student } = this.resolve({ student_id }); if (student == null) { return { simple: "Unknown", full: "Unknown Student" }; } const email = student.get("email_address"); const simple = this.get_student_name(student_id); let extra: string = ""; if ( (student.has("first_name") || student.has("last_name")) && student.has("account_id") ) { const users = this.redux.getStore("users"); if (users != null) { const name = users.get_name(student.get("account_id")); if (name != null) { extra = ` (You call them "${student.has("first_name")} ${student.has( "last_name" )}", but they call themselves "${name}".)`; } } } return { simple, full: email ? `${simple} <${email}>${extra}` : simple }; } // Return a name that should sort in a sensible way in // alphabetical order. This is mainly used for CSV export, // and is not something that will ever get looked at. public get_student_sort_name(student_id: string): string { const { student } = this.resolve({ student_id }); if (student == null) { return student_id; // keeps the sort stable } if (student.has("first_name") || student.has("last_name")) { return [student.get("last_name", ""), student.get("first_name", "")].join( " " ); } const account_id = student.get("account_id"); if (account_id == null) { if (student.has("email_address")) { return student.get("email_address"); } return student_id; } const users = this.redux.getStore("users"); if (users == null) return student_id; return [ users.get_last_name(account_id), users.get_first_name(account_id), ].join(" "); } public get_student_email(student_id: string): string { return this.getIn(["students", student_id, "email_address"], ""); } public get_student_ids(opts: { deleted?: boolean } = {}): string[] { const v: string[] = []; opts.deleted = !!opts.deleted; for (const [student_id, val] of this.get("students")) { if (!!val.get("deleted") == opts.deleted) { v.push(student_id); } } return v; } // return list of all student projects public get_student_project_ids( opts: { include_deleted?: boolean; deleted_only?: boolean; } = {} ): string[] { // include_deleted = if true, also include deleted projects // deleted_only = if true, only include deleted projects const { include_deleted, deleted_only } = opts; let v: string[] = []; for (const [, val] of this.get("students")) { const project_id: string = val.get("project_id"); if (deleted_only) { if (include_deleted && val.get("deleted")) { v.push(project_id); } } else if (include_deleted) { v.push(project_id); } else if (!val.get("deleted")) { v.push(project_id); } } return v; } public get_student(student_id: string): StudentRecord | undefined { // return student with given id return this.getIn(["students", student_id]); } public get_student_project_id(student_id: string): string | undefined { return this.getIn(["students", student_id, "project_id"]); } // Return a Javascript array of immutable.js StudentRecord maps, sorted // by sort name (so first last name). public get_sorted_students(): StudentRecord[] { const v: StudentRecord[] = []; for (const [, student] of this.get("students")) { if (!student.get("deleted")) { v.push(student); } } v.sort((a, b) => cmp( this.get_student_sort_name(a.get("student_id")), this.get_student_sort_name(b.get("student_id")) ) ); return v; } public get_grade(assignment_id: string, student_id: string): string { const { assignment } = this.resolve({ assignment_id }); if (assignment == null) return ""; const r = assignment.getIn(["grades", student_id], ""); return r == null ? "" : r; } public get_nbgrader_scores( assignment_id: string, student_id: string ): { [ipynb: string]: NotebookScores | string } | undefined { const { assignment } = this.resolve({ assignment_id }); return assignment?.getIn(["nbgrader_scores", student_id])?.toJS(); } public get_nbgrader_score_ids( assignment_id: string ): { [ipynb: string]: string[] } | undefined { const { assignment } = this.resolve({ assignment_id }); const ids = assignment?.get("nbgrader_score_ids")?.toJS(); if (ids != null) return ids; // TODO: If the score id's aren't known, it would be nice to try // to parse the master ipynb file and compute them. We still // allow for the possibility that this fails and return undefined // in that case. This is painful since it involves async calls // to the backend, and the code that does this as part of grading // is deep inside other functions... } public get_comments(assignment_id: string, student_id: string): string { const { assignment } = this.resolve({ assignment_id }); if (assignment == null) return ""; const r = assignment.getIn(["comments", student_id], ""); return r == null ? "" : r; } public get_due_date(assignment_id: string): Date | undefined { const { assignment } = this.resolve({ assignment_id }); if (assignment == null) return; const due_date = assignment.get("due_date"); if (due_date != null) { return new Date(due_date); } } public get_assignments(): AssignmentsMap { return this.get("assignments"); } public get_sorted_assignments(): AssignmentRecord[] { const v: AssignmentRecord[] = []; for (const [, assignment] of this.get_assignments()) { if (!assignment.get("deleted")) { v.push(assignment); } } const f = function (a: AssignmentRecord) { return [a.get("due_date", 0), a.get("path", "")]; }; v.sort((a, b) => cmp_array(f(a), f(b))); return v; } // return assignment with given id if a string; otherwise, just return // the latest version of the assignment as stored in the store. public get_assignment(assignment_id: string): AssignmentRecord | undefined { return this.getIn(["assignments", assignment_id]); } // if deleted is true return only deleted assignments public get_assignment_ids(opts: { deleted?: boolean } = {}): string[] { const v: string[] = []; for (const [assignment_id, val] of this.get_assignments()) { if (!!val.get("deleted") == opts.deleted) { v.push(assignment_id); } } return v; } private num_nondeleted(a): number { let n: number = 0; for (const [, x] of a) { if (!x.get("deleted")) { n += 1; } } return n; } // number of non-deleted students public num_students(): number { return this.num_nondeleted(this.get_students()); } // number of student projects that are currently running public num_running_projects(project_map): number { let n = 0; for (const [, student] of this.get_students()) { if (!student.get("deleted")) { if ( project_map.getIn([student.get("project_id"), "state", "state"]) == "running" ) { n += 1; } } } return n; } // number of non-deleted assignments public num_assignments(): number { return this.num_nondeleted(this.get_assignments()); } // number of non-deleted handouts public num_handouts(): number { return this.num_nondeleted(this.get_handouts()); } // get info about relation between a student and a given assignment public student_assignment_info( student_id: string, assignment_id: string ): { last_assignment?: LastCopyInfo; last_collect?: LastCopyInfo; last_peer_assignment?: LastCopyInfo; last_peer_collect?: LastCopyInfo; last_return_graded?: LastCopyInfo; student_id: string; assignment_id: string; peer_assignment: boolean; peer_collect: boolean; } { const { assignment } = this.resolve({ assignment_id }); if (assignment == null) { return { student_id, assignment_id, peer_assignment: false, peer_collect: false, }; } const status = this.get_assignment_status(assignment_id); if (status == null) throw Error("bug"); // can't happen // Important to return undefined if no info -- assumed in code function get_info(field: string): undefined | LastCopyInfo { if (assignment == null) throw Error("bug"); // can't happen const x = assignment.getIn([field, student_id]); if (x == null) return; return (x as any).toJS(); } const peer_assignment = status.not_collect + status.not_assignment == 0 && status.collect != 0; const peer_collect = status.not_peer_assignment != null && status.not_peer_assignment == 0; return { last_assignment: get_info("last_assignment"), last_collect: get_info("last_collect"), last_peer_assignment: get_info("last_peer_assignment"), last_peer_collect: get_info("last_peer_collect"), last_return_graded: get_info("last_return_graded"), student_id, assignment_id, peer_assignment, peer_collect, }; } // Return true if the assignment was copied to/from the // student, in the given step of the workflow. // Even an attempt to copy with an error counts, // unless no_error is true, in which case it doesn't. public last_copied( step: AssignmentCopyStep, assignment_id: string, student_id: string, no_error?: boolean ): boolean { const x = this.getIn([ "assignments", assignment_id, `last_${step}`, student_id, ]); if (x == null) { return false; } const y: TypedMap<LastCopyInfo> = x; if (no_error && y.get("error")) { return false; } return y.get("time") != null; } public has_grade(assignment_id: string, student_id: string): boolean { return !!this.getIn(["assignments", assignment_id, "grades", student_id]); } public get_assignment_status( assignment_id: string ): AssignmentStatus | undefined { // // Compute and return an object that has fields (deleted students are ignored) // // assignment - number of students who have received assignment includes // all students if skip_assignment is true // not_assignment - number of students who have NOT received assignment // always 0 if skip_assignment is true // collect - number of students from whom we have collected assignment includes // all students if skip_collect is true // not_collect - number of students from whom we have NOT collected assignment but we sent it to them // always 0 if skip_assignment is true // peer_assignment - number of students who have received peer assignment // (only present if peer grading enabled; similar for peer below) // not_peer_assignment - number of students who have NOT received peer assignment // peer_collect - number of students from whom we have collected peer grading // not_peer_collect - number of students from whome we have NOT collected peer grading // return_graded - number of students to whom we've returned assignment // not_return_graded - number of students to whom we've NOT returned assignment // but we collected it from them *and* either assigned a grade or skip grading // // This function caches its result and only recomputes values when the store changes, // so it should be safe to call in render. // if (this.assignment_status_cache == null) { this.assignment_status_cache = {}; this.on("change", () => { // clear cache on any change to the store this.assignment_status_cache = {}; }); } const { assignment } = this.resolve({ assignment_id }); if (assignment == null) { return; } if (this.assignment_status_cache[assignment_id] != null) { // we have cached info return this.assignment_status_cache[assignment_id]; } const students: string[] = this.get_student_ids({ deleted: false }); // Is peer grading enabled? const peer: boolean = assignment.getIn(["peer_grade", "enabled"], false); const skip_grading: boolean = assignment.get("skip_grading", false); const obj: any = {}; for (const t of STEPS(peer)) { obj[t] = 0; obj[`not_${t}`] = 0; } const info: AssignmentStatus = obj; for (const student_id of students) { let previous: boolean = true; for (const t of STEPS(peer)) { const x = assignment.getIn([`last_${t}`, student_id]) as | undefined | TypedMap<LastCopyInfo>; if ( (x != null && !x.get("error") && !x.get("start")) || assignment.get(`skip_${t}`) ) { previous = true; info[t] += 1; } else { // add 1 only if the previous step *was* done (and in // the case of returning, they have a grade) const graded = this.has_grade(assignment_id, student_id) || skip_grading; if ((previous && t !== "return_graded") || graded) { info[`not_${t}`] += 1; } previous = false; } } } this.assignment_status_cache[assignment_id] = info; return info; } public get_handouts(): HandoutsMap { return this.get("handouts"); } public get_handout(handout_id: string): HandoutRecord | undefined { return this.getIn(["handouts", handout_id]); } public get_handout_ids(opts: { deleted?: boolean } = {}): string[] { const v: string[] = []; for (const [handout_id, val] of this.get_handouts()) { if (!!val.get("deleted") == opts.deleted) { v.push(handout_id); } } return v; } public student_handout_info( student_id: string, handout_id: string ): { status?: LastCopyInfo; handout_id: string; student_id: string } { // status -- important to be undefined if no info -- assumed in code const status = this.getIn(["handouts", handout_id, "status", student_id]); return { status: status != null ? status.toJS() : undefined, student_id, handout_id, }; } // Return the last time the handout was copied to/from the // student (in the given step of the workflow), or undefined. // Even an attempt to copy with an error counts. public handout_last_copied(handout_id: string, student_id: string): boolean { const x = this.getIn(["handouts", handout_id, "status", student_id]) as | TypedMap<LastCopyInfo> | undefined; if (x == null) { return false; } if (x.get("error")) { return false; } return x.get("time") != null; } public get_handout_status( handout_id: string ): undefined | { handout: number; not_handout: number } { // // Compute and return an object that has fields (deleted students are ignored) // // handout - number of students who have received handout // not_handout - number of students who have NOT received handout // This function caches its result and only recomputes values when the store changes, // so it should be safe to call in render. // if (this.handout_status_cache == null) { this.handout_status_cache = {}; this.on("change", () => { // clear cache on any change to the store this.handout_status_cache = {}; }); } const { handout } = this.resolve({ handout_id }); if (handout == null) { return undefined; } if (this.handout_status_cache[handout_id] != null) { return this.handout_status_cache[handout_id]; } const students: string[] = this.get_student_ids({ deleted: false }); const info = { handout: 0, not_handout: 0, }; const status = handout.get("status"); for (const student_id of students) { if (status == null) { info.not_handout += 1; } else { const x = status.get(student_id); if (x != null && !x.get("error")) { info.handout += 1; } else { info.not_handout += 1; } } } this.handout_status_cache[handout_id] = info; return info; } public get_upgrade_plan(upgrade_goal: UpgradeGoal) { const account_store: any = this.redux.getStore("account"); const project_map = this.redux.getStore("projects").get("project_map"); if (project_map == null) throw Error("not fully loaded"); const plan = project_upgrades.upgrade_plan({ account_id: account_store.get_account_id(), purchased_upgrades: account_store.get_total_upgrades(), project_map, student_project_ids: set( this.get_student_project_ids({ include_deleted: true, }) ), deleted_project_ids: set( this.get_student_project_ids({ include_deleted: true, deleted_only: true, }) ), upgrade_goal, }); return plan; }<|fim▁hole|> private resolve(opts: { assignment_id?: string; student_id?: string; handout_id?: string; }): { student?: StudentRecord; assignment?: AssignmentRecord; handout?: HandoutRecord; } { const actions = this.redux.getActions(this.name); if (actions == null) return {}; const x = (actions as CourseActions).resolve(opts); delete (x as any).store; return x; } // List of ids of (non-deleted) assignments that have been // assigned to at least one student. public get_assigned_assignment_ids(): string[] { const v: string[] = []; for (const [assignment_id, val] of this.get_assignments()) { if (val.get("deleted")) continue; const x = val.get(`last_assignment`); if (x != null && x.size > 0) { v.push(assignment_id); } } return v; } // List of ids of (non-deleted) handouts that have been copied // out to at least one student. public get_assigned_handout_ids(): string[] { const v: string[] = []; for (const [handout_id, val] of this.get_handouts()) { if (val.get("deleted")) continue; const x = val.get(`status`); if (x != null && x.size > 0) { v.push(handout_id); } } return v; } public get_copy_parallel(): number { const n = this.getIn(["settings", "copy_parallel"]) ?? PARALLEL_DEFAULT; if (n < 1) return 1; if (n > MAX_COPY_PARALLEL) return MAX_COPY_PARALLEL; return n; } public get_nbgrader_parallel(): number { const n = this.getIn(["settings", "nbgrader_parallel"]) ?? PARALLEL_DEFAULT; if (n < 1) return 1; if (n > 50) return 50; return n; } } export function get_nbgrader_score(scores: { [ipynb: string]: NotebookScores | string; }): { score: number; points: number; error?: boolean; manual_needed: boolean } { let points: number = 0; let score: number = 0; let error: boolean = false; let manual_needed: boolean = false; for (const ipynb in scores) { const x = scores[ipynb]; if (typeof x == "string") { error = true; continue; } for (const grade_id in x) { const y = x[grade_id]; if (y.score == null && y.manual) { manual_needed = true; } if (y.score) { score += y.score; } points += y.points; } } return { score, points, error, manual_needed }; }<|fim▁end|>
<|file_name|>spectral_normalization.py<|end_file_name|><|fim▁begin|>import numpy import chainer from chainer import backend from chainer import configuration import chainer.functions as F from chainer import link_hook import chainer.links as L from chainer import variable import chainerx from chainerx import _fallback_workarounds as fallback def l2normalize(xp, v, eps): """Normalize a vector by its L2 norm. Args: xp (numpy or cupy): v (numpy.ndarray or cupy.ndarray) eps (float): Epsilon value for numerical stability. Returns: :class:`numpy.ndarray` or :class:`cupy.ndarray` """ # TODO(crcrpar): Remove this when chainerx.linalg.norm becomes available. if xp is chainerx: # NOTE(crcrpar): `chainerx.power` is not available as of 2019/03/27. # See https://github.com/chainer/chainer/pull/6522 norm = chainerx.sqrt(chainerx.sum(v * v)) else: norm = xp.linalg.norm(v) return v / (norm + eps) def update_approximate_vectors( weight_matrix, u, n_power_iteration, eps): """Update the first left and right singular vectors. This function updates the first left singular vector `u` and the first right singular vector `v`. Args: weight_matrix (~chainer.Variable): 2D weight. u (numpy.ndarray, cupy.ndarray, or None): Vector that approximates the first left singular vector and has the shape of (out_size,). n_power_iteration (int): Number of iterations to approximate the first right and left singular vectors. Returns: :class:`numpy.ndarray` or `cupy.ndarray`: Approximate first left singular vector. :class:`numpy.ndarray` or `cupy.ndarray`: Approximate first right singular vector. """ weight_matrix = weight_matrix.array xp = backend.get_array_module(weight_matrix) for _ in range(n_power_iteration): v = l2normalize(xp, xp.dot(u, weight_matrix), eps) u = l2normalize(xp, xp.dot(weight_matrix, v), eps) return u, v def calculate_max_singular_value(weight_matrix, u, v): """Calculate max singular value by power iteration method. Args: weight_matrix (~chainer.Variable) u (numpy.ndarray or cupy.ndarray) v (numpy.ndarray or cupy.ndarray) Returns: ~chainer.Variable: Max singular value via power iteration method. """ sigma = F.matmul(F.matmul(u, weight_matrix), v) return sigma class SpectralNormalization(link_hook.LinkHook): """Spectral Normalization link hook implementation. This hook normalizes a weight using max singular value and this value is computed via power iteration method. Currently, this hook is supposed to be added to :class:`chainer.links.Linear`, :class:`chainer.links.EmbedID`, :class:`chainer.links.Convolution2D`, :class:`chainer.links.ConvolutionND`, :class:`chainer.links.Deconvolution2D`, and :class:`chainer.links.DeconvolutionND`. However, you can use this to other links like RNNs by specifying ``weight_name``. It is highly recommended to add this hook before optimizer setup because this hook add a scaling parameter ``gamma`` if ``use_gamma`` is True. Otherwise, the registered ``gamma`` will not be updated. .. math:: \\bar{\\mathbf{W}} &=& \\dfrac{\\mathbf{W}}{\\sigma(\\mathbf{W})} \\\\ \\text{, where} \\ \\sigma(\\mathbf{W}) &:=& \\max_{\\mathbf{h}: \\mathbf{h} \\ne 0} \\dfrac{\\|\\mathbf{W} \\mathbf{h}\\|_2}{\\|\\mathbf{h}\\|_2} = \\max_{\\|\\mathbf{h}\\|_2 \\le 1} \\|\\mathbf{W}\\mathbf{h}\\|_2 See: T. Miyato et. al., `Spectral Normalization for Generative Adversarial Networks <https://arxiv.org/abs/1802.05957>`_ Args: n_power_iteration (int): Number of power iteration. The default value is 1. eps (float): Numerical stability in norm calculation. The default value is 1e-6 for the compatibility with mixed precision training. The value used in the author's implementation is 1e-12. use_gamma (bool): If ``True``, weight scaling parameter gamma which is initialized by initial weight's max singular value is introduced. factor (float, None): Scaling parameter to divide maximum singular value. The default value is 1.0. weight_name (str): Link's weight name to apply this hook. The default value is ``'W'``. name (str or None): Name of this hook. The default value is ``'SpectralNormalization'``. Attributes: vector_name (str): Name of the approximate first left singular vector registered in the target link. the target link. axis (int): Axis of weight represents the number of output feature maps or output units (``out_channels`` and ``out_size``, respectively). .. admonition:: Example There are almost the same but 2 ways to apply spectral normalization (SN) hook to links. 1. Initialize link and SN separately. This makes it easy to handle buffer and parameter of links registered by SN hook. >>> l = L.Convolution2D(3, 5, 3) >>> hook = chainer.link_hooks.SpectralNormalization() >>> _ = l.add_hook(hook) >>> # Check the shape of the first left singular vector. >>> getattr(l, hook.vector_name).shape (5,) >>> # Delete SN hook from this link. >>> l.delete_hook(hook.name) 2. Initialize both link and SN hook at one time. This makes it easy to define your original :class:`~chainer.Chain`. >>> # SN hook handles lazy initialization! >>> layer = L.Convolution2D( ... 5, 3, stride=1, pad=1).add_hook( ... chainer.link_hooks.SpectralNormalization()) """ name = 'SpectralNormalization' def __init__(self, n_power_iteration=1, eps=1e-6, use_gamma=False, factor=None, weight_name='W', name=None): assert n_power_iteration > 0 self.n_power_iteration = n_power_iteration self.eps = eps self.use_gamma = use_gamma self.factor = factor self.weight_name = weight_name self.vector_name = weight_name + '_u' self._initialized = False self.axis = 0 if name is not None: self.name = name def __enter__(self): raise NotImplementedError( 'This hook is not supposed to be used as context manager.') <|fim▁hole|> def added(self, link): # Define axis and register ``u`` if the weight is initialized. if not hasattr(link, self.weight_name): raise ValueError( 'Weight \'{}\' does not exist!'.format(self.weight_name)) if isinstance(link, (L.Deconvolution2D, L.DeconvolutionND)): self.axis = 1 if getattr(link, self.weight_name).array is not None: self._prepare_parameters(link) def deleted(self, link): # Remove approximate vector ``u`` and parameter ``gamma` if exists. delattr(link, self.vector_name) if self.use_gamma: del link.gamma def forward_preprocess(self, cb_args): # This method normalizes target link's weight spectrally # using power iteration method link = cb_args.link input_variable = cb_args.args[0] if not self._initialized: self._prepare_parameters(link, input_variable) weight = getattr(link, self.weight_name) # For link.W or equivalents to be chainer.Parameter # consistently to users, this hook maintains a reference to # the unnormalized weight. self.original_weight = weight # note: `normalized_weight` is ~chainer.Variable normalized_weight = self.normalize_weight(link) setattr(link, self.weight_name, normalized_weight) def forward_postprocess(self, cb_args): # Here, the computational graph is already created, # we can reset link.W or equivalents to be Parameter. link = cb_args.link setattr(link, self.weight_name, self.original_weight) def _prepare_parameters(self, link, input_variable=None): """Prepare one buffer and one parameter. Args: link (:class:`~chainer.Link`): Link to normalize spectrally. input_variable (:class:`~chainer.Variable`): The first minibatch to initialize weight. """ if getattr(link, self.weight_name).array is None: if input_variable is not None: link._initialize_params(input_variable.shape[1]) initialW = getattr(link, self.weight_name) if initialW.shape[self.axis] == 0: raise ValueError( 'Expect {}.shape[{}] > 0'.format(self.weight_name, self.axis) ) u = link.xp.random.normal( size=(initialW.shape[self.axis],)).astype(dtype=initialW.dtype) setattr(link, self.vector_name, u) link.register_persistent(self.vector_name) if self.use_gamma: # Initialize the scaling parameter with the max singular value. weight_matrix = self.reshape_W(initialW.array) # TODO(crcrpar): Remove this when chainerx supports SVD. if link.xp is chainerx: xp, device, array = fallback._from_chx(weight_matrix) if xp is numpy: _, s, _ = numpy.linalg.svd(array) else: with chainer.using_device(device): _, s, _ = xp.linalg.svd(array) else: _, s, _ = link.xp.linalg.svd(weight_matrix) with link.init_scope(): link.gamma = variable.Parameter(s[0], ()) self._initialized = True def normalize_weight(self, link): """Normalize target weight before every single forward computation.""" weight_name, vector_name = self.weight_name, self.vector_name W = getattr(link, weight_name) u = getattr(link, vector_name) weight_matrix = self.reshape_W(W) if not configuration.config.in_recomputing: with chainer.using_device(link.device): u, v = update_approximate_vectors( weight_matrix, u, self.n_power_iteration, self.eps) else: v = self.v sigma = calculate_max_singular_value(weight_matrix, u, v) if self.factor is not None: sigma /= self.factor if self.use_gamma: W = link.gamma * W / sigma else: W = W / sigma if not configuration.config.in_recomputing: self.v = v with chainer.using_device(link.device): if configuration.config.train: if link.xp is chainerx: # TODO(crcrpar): Remove this when # chainerx supports `copyto`. getattr(link, vector_name)[:] = u else: backend.copyto(getattr(link, vector_name), u) return W def reshape_W(self, W): """Reshape & transpose weight into 2D if necessary.""" if self.axis != 0: axes = [self.axis] + [i for i in range(W.ndim) if i != self.axis] W = W.transpose(axes) if W.ndim == 2: return W return W.reshape(W.shape[0], -1)<|fim▁end|>
def __exit__(self): raise NotImplementedError
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>from django.conf.urls import patterns, url from rest_framework.urlpatterns import format_suffix_patterns from snippets.v3_0 import views urlpatterns = patterns('', url(r'^v3_0/snippets/$', views.SnippetList.as_view()), url(r'^v3_0/snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),<|fim▁hole|><|fim▁end|>
) urlpatterns = format_suffix_patterns(urlpatterns)
<|file_name|>jumble.py<|end_file_name|><|fim▁begin|>try: from collections import Counter except: from Counter import Counter # For Python < 2.7 import traceback import wordList import anagram import random import math import re # Allows channel members to play an acronym-based word game. # !jumble [min [max]] -- starts a new round, optionally setting the min and max length of words. # !jumble end -- stops the current game. # <guess> -- users must unjumble the given word and present their solution as a single word. # !unjumble <word> -- lists all the acronyms of the given word. # The possible words which may be used are taken from words.txt, and, if plugins.log has a log for # the channel given by VOCAB_CHANNEL, tailored to match the vocabulary of that channel. VOCAB_CHANNEL = '#calculus' # If plugins.define.define is loaded, the definitions of any mentioned words will also be given. words = set(wordList.fromFile('plugins/jumble/words.txt')) logged = nicks = None try: logged = Counter(wordList.fromLog(VOCAB_CHANNEL, 'plugins/log/database')) nicks = set(wordList.nicksFromLog(VOCAB_CHANNEL, 'plugins/log/database')) words |= set(w for w in logged if logged[w] > 99) - nicks # Include nonnicks logged > 99 times. anagrams = anagram.Finder(words) words &= set(w for w in logged if logged[w] > 1) # Exclude words logged < 2 times. except Exception as e: anagrams = anagram.Finder(words) traceback.print_exc(e) finally: del logged, nicks games = {} def chmsg(event, server): chan, nick, msg = event['channel'], event['nicka'], event['msg'] def respond(msg): server.send_msg(chan, wrap(msg, server)) if chan in games: jumble = games[chan] else: jumble = games[chan] = Jumble() return jumble.said(server, msg, nick, respond) def wrap(msg, server): max = server.MAX_SIZE - 100 end = ' (...)' if len(msg) > max: return msg[0:max-len(end)] + end else: return msg def define(server, word): if 'plugins.define.define' not in server.mod.modules: return None define = server.mod.modules['plugins.define.define'] try: return define.instance.define(word) except IOError: pass except define.dictionary.ProtocolError: pass class Jumble(object): __slots__ = 'word', 'solutions', 'min', 'max' def __init__(self): self.min = self.max = 0 self.word = None def said(self, server, msg, nick, respond): match = re.match(r'!jumble(\s+\d+)?(\s+\d+)?\s*$', msg, re.I) if match: return self.call(server, respond, *match.groups()) match = re.match(r'!jumble\s+end\s*$', msg, re.I) if match: return self.end(server, respond, *match.groups()) match = re.match(r'!jumble\s.', msg, re.I) if match: return self.help(server, respond, *match.groups()) match = re.match(r'!unjumble\s+([a-z]+)\s*$', msg, re.I) if match: return self.unjumble(server, respond, nick, *match.groups()) match = re.match(r'\s*([a-z]+)\s*$', msg, re.I) if match: return self.guess(server, respond, nick, *match.groups()) def call(self, server, respond, min, max): if min != None: self.min = int(min) if max != None: self.max = int(max) self.end(server, respond) self.start(server, respond) def start(self, server, respond): sub = set(w for w in words if self.min <= len(w) and (self.max == 0 or len(w) <= self.max)) while len(sub): word = random.sample(sub, 1)[0] solutions = anagrams(word) if math.factorial(len(word)) != len(solutions): chars = list(word) while ''.join(chars) in solutions: random.shuffle(chars) self.word, self.solutions = ''.join(chars), solutions return respond(self.word) else: sub.remove(word) # Every permutation of this word is in the dictionary. else: return respond("Failed to generate a word.") # There are no suitable words.<|fim▁hole|> word = word.upper() if word in self.solutions: defn = define(server, word) if defn: respond("%s wins with %s (%s)" % (nick, word, defn)) else: respond("%s wins with %s." % (nick, word)) self.start(server, respond) def end(self, server, respond): if not self.word: return self.word = None if len(self.solutions) == 1: defn = define(server, tuple(self.solutions)[0]) if defn: return respond('Nobody wins. Solutions: %s (%s)' % (', '.join(self.solutions), defn)) return respond('Nobody wins. Solutions: %s.' % ', '.join(self.solutions)) def unjumble(self, server, respond, nick, word): words = anagrams(word) if len(words): return respond(', '.join(words)) return respond('No results.') def help(self, server, respond): respond('Available commands:' ' \002!jumble [min [max]]\002,' ' \002!jumble end\002,' ' \002!jumble help\002,' ' \002!unjumble <word>\002.')<|fim▁end|>
def guess(self, server, respond, nick, word): if not self.word: return
<|file_name|>models.py<|end_file_name|><|fim▁begin|># Lint as: python3 # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Supported pricing models.""" import enum from typing import Any import dataclasses class InterestRateModelType(enum.Enum): """Models for pricing interest rate derivatives. <|fim▁hole|> NORMAL_RATE: Normal model for the underlying rate LOGNORMAL_SMILE_CONSISTENT_REPLICATION: Smile consistent replication (lognormal vols). NORMAL_SMILE_CONSISTENT_REPLICATION: Smile consistent replication (normal vols). HULL_WHITE_ONE_FACTOR: Hull-White single factor model of short rate. """ LOGNORMAL_RATE = 1 NORMAL_RATE = 2 LOGNORMAL_SMILE_CONSISTENT_REPLICATION = 3 NORMAL_SMILE_CONSISTENT_REPLICATION = 4 HULL_WHITE_ONE_FACTOR = 5 @dataclasses.dataclass(frozen=True) class HullWhite1FactorConfig: mean_reversion: Any volatility: Any __all__ = ["InterestRateModelType", "HullWhite1FactorConfig"]<|fim▁end|>
LOGNORMAL_RATE: Lognormal model for the underlying rate.
<|file_name|>spatialFiltering.py<|end_file_name|><|fim▁begin|># Mustafa Hussain # Digital Image Processing with Dr. Anas Salah Eddin # FL Poly, Spring 2015 # # Homework 3: Spatial Filtering # # USAGE NOTES: #<|fim▁hole|># # Please ensure that the script is running as the same directory as the images # directory! import cv2 import copy #import matplotlib.pyplot as plt import numpy import math #from skimage import exposure INPUT_DIRECTORY = 'input/' OUTPUT_DIRECTORY = 'output/' IMAGE_FILE_EXTENSION = '.JPG' MAX_INTENSITY = 255 # 8-bit images def laplacianFilter(image): """Approximates the second derivative, bringing out edges. Referencing below zero wraps around, so top and left sides will be sharpened. We are not bothering with the right and bottom edges, because referencing above the image size results in a boundary error. """ width, height = image.shape filteredImage = copy.deepcopy(image) originalImage = copy.deepcopy(image) # Avoid right, bottom edges. for i in range(width - 1): for j in range(height - 1): # Mask from homepages.inf.ed.ac.uk/rbf/HIPR2/log.htm total = 0.0 total += -1 * float(image[i][j + 1]) total += -1 * float(image[i - 1][j]) total += 4 * float(image[i][j]) total += -1 * float(image[i + 1][j]) total += -1 * float(image[i][j - 1]) filteredImage[i][j] = total / 9.0 filteredImage = (filteredImage / numpy.max(filteredImage)) * MAX_INTENSITY return filteredImage def saveImage(image, filename): """Saves the image in the output directory with the filename given. """ cv2.imwrite(OUTPUT_DIRECTORY + filename + IMAGE_FILE_EXTENSION, image) def openImage(fileName): """Opens the image in the input directory with the filename given. """ return cv2.imread(INPUT_DIRECTORY + fileName + IMAGE_FILE_EXTENSION, 0) # Input images inputForSharpening = 'testImage1' # Import image. imageForSharpening = openImage(inputForSharpening) print("Laplacian Filter...") filtered = laplacianFilter(imageForSharpening) saveImage(filtered, inputForSharpening + 'Laplace') print("Done.")<|fim▁end|>
# Written in Python 2.7
<|file_name|>resource_softlayer_lb_local_test.go<|end_file_name|><|fim▁begin|>package softlayer import ( "github.com/hashicorp/terraform/helper/resource" "testing" ) func TestAccSoftLayerLbLocalShared_Basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccCheckSoftLayerLbLocalConfigShared_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "connections", "250"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "datacenter", "tok02"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "ha_enabled", "false"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "dedicated", "false"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "ssl_enabled", "false"), ), }, }, }) } func TestAccSoftLayerLbLocalDedicated_Basic(t *testing.T) { resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, Steps: []resource.TestStep{<|fim▁hole|> resource.TestStep{ Config: testAccCheckSoftLayerLbLocalDedicatedConfig_basic, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "connections", "15000"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "datacenter", "tok02"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "ha_enabled", "false"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "dedicated", "true"), resource.TestCheckResourceAttr( "softlayer_lb_local.testacc_foobar_lb", "ssl_enabled", "true"), ), }, }, }) } const testAccCheckSoftLayerLbLocalConfigShared_basic = ` resource "softlayer_lb_local" "testacc_foobar_lb" { connections = 250 datacenter = "tok02" ha_enabled = false }` const testAccCheckSoftLayerLbLocalDedicatedConfig_basic = ` resource "softlayer_lb_local" "testacc_foobar_lb" { connections = 15000 datacenter = "tok02" ha_enabled = false dedicated = true }`<|fim▁end|>
<|file_name|>zt.megamenu.js<|end_file_name|><|fim▁begin|>var ZTMenu = function(boxTimer, xOffset, yOffset, smartBoxSuffix, smartBoxClose, isub, xduration, xtransition) { var smartBoxes = $(document.body).getElements('[id$=' + smartBoxSuffix + ']'); var closeElem = $(document.body).getElements('.' + smartBoxClose); var closeBoxes = function() { smartBoxes.setStyle('display', 'none'); }; closeElem.addEvent('click', function(){ closeBoxes() }); var closeBoxesTimer = 0; var fx = Array(); var h = Array(); var w = Array(); smartBoxes.each(function(item, i) { var currentBox = item.getProperty('id'); currentBox = currentBox.replace('' + smartBoxSuffix + '', ''); fx[i] = new Fx.Elements(item.getChildren(), {wait: false, duration: xduration, transition: xtransition, onComplete: function(){item.setStyle('overflow', '');}}); $(currentBox).addEvent('mouseleave', function(){ item.setStyle('overflow', 'hidden'); fx[i].start({ '0':{ 'opacity': [1, 0], 'height': [h[i], 0] } }); closeBoxesTimer = closeBoxes.delay(boxTimer); <|fim▁hole|> }); item.addEvent('mouseleave', function(){ closeBoxesTimer = closeBoxes.delay(boxTimer); }); $(currentBox).addEvent('mouseenter', function(){ if($defined(closeBoxesTimer)) $clear(closeBoxesTimer); }); item.addEvent('mouseenter', function(){ if($defined(closeBoxesTimer)) $clear(closeBoxesTimer); }); item.setStyle('margin', '0'); $(currentBox).addEvent('mouseenter', function() { smartBoxes.setStyle('display', 'none'); item.setStyles({ display: 'block', position: 'absolute' }); var WindowX = window.getWidth(); var boxSize = item.getSize(); var inputPOS = $(currentBox).getCoordinates(); var inputCOOR = $(currentBox).getPosition(); var inputSize = $(currentBox).getSize(); var inputBottomPOS = inputPOS.top + inputSize.y; var inputBottomPOSAdjust = inputBottomPOS - window.getScrollHeight(); var inputLeftPOS = inputPOS.left + xOffset; var inputRightPOS = inputPOS.right; var leftOffset = inputCOOR.x + xOffset; if(item.getProperty('id').split("_")[2] == 'sub0') { item.setStyle('top', inputBottomPOS); if((inputLeftPOS + boxSize.x - WindowX) < 0) { item.setStyle('left', leftOffset - 10); } else{ item.setStyle('left', (inputPOS.right - boxSize.x) - xOffset + 10); }; } else { if((inputLeftPOS + boxSize.x + inputSize.x - WindowX) < 0) { var space = inputLeftPOS - boxSize.x - inputSize.x; var left = (space > inputSize.x) ? space : inputSize.x; item.setStyle('left', left); } else { var space = WindowX - inputLeftPOS - inputSize.x/2; var right = (space > inputSize.x) ? space : inputSize.x; item.setStyle('right', right); }; } if(h[i] == null){ h[i] = boxSize.y; }; fx[i].start({ '0':{ 'opacity': [0, 1], 'height': [0, h[i]] } }); }); }); }; window.addEvent("domready", function(){ $$('ul#menusys_mega li').each(function(li, i){ li.addEvent('mouseleave', function(){li.removeClass('hover');}); li.addEvent('mouseenter', function(){li.addClass('hover');}); }); });<|fim▁end|>
<|file_name|>GridPartitionedBackupLoadSelfTest.java<|end_file_name|><|fim▁begin|>/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.processors.cache.distributed.near; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.store.CacheStoreAdapter; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.discovery.DiscoverySpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; /** * Test that persistent store is not used when loading invalidated entry from backup node. */ public class GridPartitionedBackupLoadSelfTest extends GridCommonAbstractTest { /** */ private static final TcpDiscoveryIpFinder IP_FINDER = new TcpDiscoveryVmIpFinder(true); /** */ private static final int GRID_CNT = 3; /** */ private final TestStore store = new TestStore(); /** */ private final AtomicInteger cnt = new AtomicInteger(); /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); cfg.setDiscoverySpi(discoverySpi()); cfg.setCacheConfiguration(cacheConfiguration()); return cfg; }<|fim▁hole|> /** * @return Discovery SPI. */ private DiscoverySpi discoverySpi() { TcpDiscoverySpi spi = new TcpDiscoverySpi(); spi.setIpFinder(IP_FINDER); return spi; } /** * @return Cache configuration. */ @SuppressWarnings("unchecked") private CacheConfiguration cacheConfiguration() { CacheConfiguration cfg = defaultCacheConfiguration(); cfg.setCacheMode(PARTITIONED); cfg.setBackups(1); cfg.setCacheStoreFactory(singletonFactory(store)); cfg.setReadThrough(true); cfg.setWriteThrough(true); cfg.setLoadPreviousValue(true); cfg.setWriteSynchronizationMode(FULL_SYNC); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { startGridsMultiThreaded(GRID_CNT); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); } /** * @throws Exception If failed. */ public void testBackupLoad() throws Exception { grid(0).cache(null).put(1, 1); assert store.get(1) == 1; for (int i = 0; i < GRID_CNT; i++) { IgniteCache<Integer, Integer> cache = jcache(i); if (grid(i).affinity(null).isBackup(grid(i).localNode(), 1)) { assert cache.localPeek(1, CachePeekMode.ONHEAP) == 1; jcache(i).localClear(1); assert cache.localPeek(1, CachePeekMode.ONHEAP) == null; // Store is called in putx method, so we reset counter here. cnt.set(0); assert cache.get(1) == 1; assert cnt.get() == 0; } } } /** * Test store. */ private class TestStore extends CacheStoreAdapter<Integer, Integer> { /** */ private Map<Integer, Integer> map = new ConcurrentHashMap<>(); /** {@inheritDoc} */ @Override public Integer load(Integer key) { cnt.incrementAndGet(); return null; } /** {@inheritDoc} */ @Override public void write(javax.cache.Cache.Entry<? extends Integer, ? extends Integer> e) { map.put(e.getKey(), e.getValue()); } /** {@inheritDoc} */ @Override public void delete(Object key) { // No-op } /** * @param key Key. * @return Value. */ public Integer get(Integer key) { return map.get(key); } } }<|fim▁end|>
<|file_name|>headings.py<|end_file_name|><|fim▁begin|>#!/bin/env python """ Extract and tag References from a PDF. Created on Mar 1, 2010 @author: John Harrison Usage: headings.py OPTIONS FILEPATH OPTIONS: --help, -h Print help and exit --noxml Do not tag individual headings with XML tags. Default is to include tagging. --title Only print title then exit --author Only print author then exit """ import sys, getopt from lxml import etree from utils import UsageError, ConfigError, mean, median from pdf2xml import pdf2etree def pdf2heads(opts, args): xmltag = True highlight = False titleonly = False authonly = False for o, a in opts: if (o == '--noxml'): xmltag = False elif (o == '--highlight'): highlight = True if (o == '--title'): titleonly = True elif (o == '--author'): authonly = True tree = pdf2etree(args) # find title page = 1 block = 1 title_node = None while True: try: title_node = tree.xpath("//PAGE[{0}]//BLOCK[{1}]".format(page, block))[0] except IndexError: page+=1 else: break if page > 2: # probably not going to find it now break # find author page = 1 block = 2 auth_node = None while True: try: auth_node = tree.xpath("//PAGE[{0}]//BLOCK[{1}]".format(page, block))[0] except InbdexError: block+=1 else: break if block > 4: # probably not going to find it now break font_sizes = tree.xpath('//TOKEN/@font-size') mean_font_size = mean(font_sizes) median_font_size = median(font_sizes) #print "Median Font Size (i.e. body text):", median_font_size font_colors = tree.xpath('//TOKEN/@font-color') font_color_hash = {} for fc in font_colors: try: font_color_hash[fc]+=1 except KeyError: font_color_hash[fc] = 1 sortlist = [(v,k) for k,v in font_color_hash.iteritems()] sortlist.sort(reverse=True) main_font_color = sortlist[0][1] head_txts = [] stop = False for page_node in tree.xpath('//PAGE'): for block_node in page_node.xpath('.//BLOCK'): if xmltag: if block_node == title_node: st = "<title>" et = "</title>" elif block_node == auth_node: st = "<author>" et = "</author>" else: st = "<heading>" et = "</heading>" if highlight: st = "\033[0;32m{0}\033[0m".format(st) et = "\033[0;32m{0}\033[0m".format(et) else: st = et = "" if block_node == title_node and authonly: continue headers = block_node.xpath(".//TOKEN[@font-size > {0} or @bold = 'yes' or @font-color != '{1}']".format(mean_font_size*1.05, main_font_color)) head_txt = ' '.join([etree.tostring(el, method='text', encoding="UTF-8") for el in headers]) if len(head_txt): head_txts.append("{0}{1}{2}".format(st, head_txt, et)) if block_node == title_node and titleonly: stop = True break elif block_node == auth_node and authonly: stop = True break if stop: break for txt in head_txts: sys.stdout.writelines([txt, '\n']) def main(argv=None): if argv is None: argv = sys.argv[1:] try: try: opts, args = getopt.getopt(argv, "ht", ["help", "test", "noxml", "highlight", "title", "author"]) except getopt.error as msg: raise UsageError(msg) for o, a in opts: if (o in ['-h', '--help']): # print help and exit sys.stdout.write(__doc__) sys.stdout.flush() return 0 <|fim▁hole|> print >>sys.stderr, err.msg print >>sys.stderr, "for help use --help" return 2 except ConfigError, err: sys.stderr.writelines([str(err.msg),'\n']) sys.stderr.flush() return 1 if __name__ == '__main__': sys.exit(main())<|fim▁end|>
pdf2heads(opts, args) except UsageError as err:
<|file_name|>UnaryMinusNode.java<|end_file_name|><|fim▁begin|>package compiler.ASTNodes.Operators; import compiler.ASTNodes.GeneralNodes.Node; import compiler.ASTNodes.GeneralNodes.UnaryNode; import compiler.ASTNodes.SyntaxNodes.ExprNode;<|fim▁hole|> public UnaryMinusNode(Node child) { super(child, null); } @Override public Object Accept(AbstractVisitor v) { return v.visit(this); } }<|fim▁end|>
import compiler.Visitors.AbstractVisitor; public class UnaryMinusNode extends ExprNode {
<|file_name|>views.py<|end_file_name|><|fim▁begin|># # Copyright (C) 2010 Norwegian University of Science and Technology # Copyright (C) 2011-2015 UNINETT AS # # This file is part of Network Administration Visualized (NAV). # # NAV is free software: you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by # the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. You should have received a copy of the GNU General Public License # along with NAV. If not, see <http://www.gnu.org/licenses/>. # """View controller for PortAdmin""" import ConfigParser import logging import json from operator import or_ as OR from django.http import HttpResponse, JsonResponse from django.template import RequestContext, Context from django.shortcuts import render, render_to_response, get_object_or_404 from django.contrib import messages from django.core.urlresolvers import reverse from django.db.models import Q from django.views.decorators.http import require_POST from nav.auditlog.models import LogEntry from nav.auditlog.utils import get_auditlog_entries from nav.django.utils import get_account from nav.web.utils import create_title from nav.models.manage import Netbox, Interface from nav.web.portadmin.utils import (get_and_populate_livedata, find_and_populate_allowed_vlans, get_aliastemplate, get_ifaliasformat, save_to_database, check_format_on_ifalias, find_allowed_vlans_for_user_on_netbox, find_allowed_vlans_for_user, filter_vlans, fetch_voice_vlans, should_check_access_rights, mark_detained_interfaces, read_config, is_cisco, add_dot1x_info, is_restart_interface_enabled, is_write_mem_enabled) from nav.Snmp.errors import SnmpError, TimeOutException from nav.portadmin.snmputils import SNMPFactory, SNMPHandler from .forms import SearchForm _logger = logging.getLogger("nav.web.portadmin") def get_base_context(additional_paths=None, form=None): """Returns a base context for portadmin :type additional_paths: list of tuple """ navpath = [('Home', '/'), ('PortAdmin', reverse('portadmin-index'))] if additional_paths: navpath += additional_paths form = form if form else SearchForm() return { 'navpath': navpath, 'title': create_title(navpath), 'form': form } def default_render(request): """Default render for errors etc""" return render(request, 'portadmin/base.html', get_base_context(form=get_form(request))) def get_form(request): """If we are searching for something, return a bound form with the search parameter""" if 'query' in request.GET: return SearchForm(request.GET) def index(request): """View for showing main page""" netboxes = [] interfaces = [] form = get_form(request) if form and form.is_valid(): netboxes, interfaces = search(form.cleaned_data['query']) if len(netboxes) == 1 and not interfaces: return search_by_sysname(request, netboxes[0].sysname) elif len(interfaces) == 1 and not netboxes: return search_by_interfaceid(request, interfaces[0].id) else: form = SearchForm() context = get_base_context(form=form) context['netboxes'] = netboxes context['interfaces'] = interfaces return render(request, 'portadmin/base.html', context) def search(query): """Search for something in portadmin""" netbox_filters = [ Q(sysname__icontains=query), Q(ip=query) ] netboxes = Netbox.objects.filter( reduce(OR, netbox_filters)).order_by('sysname') interfaces = Interface.objects.filter( ifalias__icontains=query).order_by('netbox__sysname', 'ifname') return netboxes, interfaces def search_by_ip(request, ip): """View for showing a search done by ip-address""" return search_by_kwargs(request, ip=ip) def search_by_sysname(request, sysname): """View for showing a search done by sysname""" return search_by_kwargs(request, sysname=sysname) def search_by_kwargs(request, **kwargs): """Search by keyword arguments""" try: netbox = Netbox.objects.get(**kwargs) except Netbox.DoesNotExist as do_not_exist_ex: _logger.error("Netbox %s not found; DoesNotExist = %s", kwargs.get('sysname') or kwargs.get('ip'), do_not_exist_ex) messages.error(request, 'Could not find IP device') return default_render(request) else: if not netbox.type: messages.error(request, 'IP device found but has no type') return default_render(request) interfaces = netbox.get_swports_sorted() auditlog_entries = get_auditlog_entries(interfaces) return render(request, 'portadmin/netbox.html', populate_infodict(request, netbox, interfaces, auditlog_entries)) def search_by_interfaceid(request, interfaceid): """View for showing a search done by interface id""" try: interface = Interface.objects.get(id=interfaceid) except Interface.DoesNotExist as do_not_exist_ex: _logger.error("Interface %s not found; DoesNotExist = %s", interfaceid, do_not_exist_ex) messages.error(request, 'Could not find interface with id %s' % str(interfaceid)) return default_render(request) else: netbox = interface.netbox if not netbox.type: messages.error(request, 'IP device found but has no type') return default_render(request) interfaces = [interface] auditlog_entries = get_auditlog_entries(interfaces) return render(request, 'portadmin/netbox.html', populate_infodict(request, netbox, interfaces, auditlog_entries)) def populate_infodict(request, netbox, interfaces, auditlog_entries=None): """Populate a dictionary used in every http response""" allowed_vlans = [] voice_vlan = None readonly = False config = read_config() auditlog_entries = {} if auditlog_entries is None else auditlog_entries try: fac = get_and_populate_livedata(netbox, interfaces) allowed_vlans = find_and_populate_allowed_vlans( request.account, netbox, interfaces, fac) voice_vlan = fetch_voice_vlan_for_netbox(request, fac, config) if voice_vlan: if is_cisco_voice_enabled(config) and is_cisco(netbox): set_voice_vlan_attribute_cisco(voice_vlan, interfaces, fac) else: set_voice_vlan_attribute(voice_vlan, interfaces) mark_detained_interfaces(interfaces) if is_dot1x_enabled: add_dot1x_info(interfaces, fac) except TimeOutException:<|fim▁hole|> messages.error(request, "Timeout when contacting %s. Values displayed " "are from database" % netbox.sysname) if not netbox.read_only: messages.error(request, "Read only community not set") except SnmpError: readonly = True messages.error(request, "SNMP error when contacting %s. Values " "displayed are from database" % netbox.sysname) if check_read_write(netbox, request): readonly = True ifaliasformat = get_ifaliasformat(config) aliastemplate = '' if ifaliasformat: tmpl = get_aliastemplate() aliastemplate = tmpl.render(Context({'ifaliasformat': ifaliasformat})) save_to_database(interfaces) info_dict = get_base_context([(netbox.sysname, )], form=get_form(request)) info_dict.update({'interfaces': interfaces, 'auditmodel': netbox.sysname, 'netbox': netbox, 'voice_vlan': voice_vlan, 'allowed_vlans': allowed_vlans, 'readonly': readonly, 'aliastemplate': aliastemplate, 'auditlog_api_parameters': json.dumps( {'subsystem': 'portadmin'}), 'auditlog_entries': auditlog_entries,}) return info_dict def is_dot1x_enabled(config): """Checks of dot1x config option is true""" section = 'general' option = 'enabledot1x' try: return (config.has_option(section, option) and config.getboolean(section, option)) except ValueError: pass return False def is_cisco_voice_enabled(config): """Checks if the Cisco config option is enabled""" section = 'general' option = 'cisco_voice_vlan' if config.has_section(section): if config.has_option(section, option): return config.getboolean(section, option) return False def fetch_voice_vlan_for_netbox(request, factory, config=None): """Fetch the voice vlan for this netbox There may be multiple voice vlans configured. Pick the one that exists on this netbox. If multiple vlans exist, we cannot know which one to use. """ if config is None: config = read_config() voice_vlans = fetch_voice_vlans(config) if not voice_vlans: return voice_vlans_on_netbox = list(set(voice_vlans) & set(factory.get_available_vlans())) if not voice_vlans_on_netbox: # Should this be reported? At the moment I do not think so. return if len(voice_vlans_on_netbox) > 1: messages.error(request, 'Multiple voice vlans configured on this ' 'netbox') return return voice_vlans_on_netbox[0] def set_voice_vlan_attribute(voice_vlan, interfaces): """Set an attribute on the interfaces to indicate voice vlan behavior""" if voice_vlan: for interface in interfaces: if not interface.trunk: continue allowed_vlans = interface.swportallowedvlan.get_allowed_vlans() interface.voice_activated = (len(allowed_vlans) == 1 and voice_vlan in allowed_vlans) def set_voice_vlan_attribute_cisco(voice_vlan, interfaces, fac): """Set voice vlan attribute for Cisco voice vlan""" voice_mapping = fac.get_cisco_voice_vlans() for interface in interfaces: voice_activated = voice_mapping.get(interface.ifindex) == voice_vlan interface.voice_activated = voice_activated def check_read_write(netbox, request): """Add a message to user explaining why he can't edit anything :returns: flag indicating readonly or not """ if not netbox.read_write: messages.error(request, "Write community not set for this device, " "changes cannot be saved") return True return False def save_interfaceinfo(request): """Set ifalias and/or vlan on netbox messages: created from the results from the messages framework interfaceid must be a part of the request ifalias, vlan and voicevlan are all optional """ if request.method == 'POST': interface = Interface.objects.get(pk=request.POST.get('interfaceid')) account = get_account(request) # Skip a lot of queries if access_control is not turned on if should_check_access_rights(account): _logger.info('Checking access rights for %s', account) if interface.vlan in [v.vlan for v in find_allowed_vlans_for_user_on_netbox( account, interface.netbox)]: set_interface_values(account, interface, request) else: # Should only happen if user tries to avoid gui restrictions messages.error(request, 'Not allowed to edit this interface') else: set_interface_values(account, interface, request) else: messages.error(request, 'Wrong request type') result = {"messages": build_ajax_messages(request)} return response_based_on_result(result) def set_interface_values(account, interface, request): """Use snmp to set the values in the request on the netbox""" fac = get_factory(interface.netbox) if fac: # Order is important here, set_voice need to be before set_vlan set_voice_vlan(fac, interface, request) set_ifalias(account, fac, interface, request) set_vlan(account, fac, interface, request) set_admin_status(fac, interface, request) save_to_database([interface]) else: messages.info(request, 'Could not connect to netbox') def build_ajax_messages(request): """Create a structure suitable for converting to json from messages""" ajax_messages = [] for message in messages.get_messages(request): ajax_messages.append({ 'level': message.level, 'message': message.message, 'extra_tags': message.tags }) return ajax_messages def set_ifalias(account, fac, interface, request): """Set ifalias on netbox if it is requested""" if 'ifalias' in request.POST: ifalias = request.POST.get('ifalias') if check_format_on_ifalias(ifalias): try: fac.set_if_alias(interface.ifindex, ifalias) interface.ifalias = ifalias LogEntry.add_log_entry( account, u'set-ifalias', u'{actor}: {object} - ifalias set to "%s"' % ifalias, subsystem=u'portadmin', object=interface, ) _logger.info('%s: %s:%s - ifalias set to "%s"', account.login, interface.netbox.get_short_sysname(), interface.ifname, ifalias) except SnmpError as error: _logger.error('Error setting ifalias: %s', error) messages.error(request, "Error setting ifalias: %s" % error) else: messages.error(request, "Wrong format on port description") def set_vlan(account, fac, interface, request): """Set vlan on netbox if it is requested""" if 'vlan' in request.POST: vlan = int(request.POST.get('vlan')) try: if is_cisco(interface.netbox): # If Cisco and trunk voice vlan (not Cisco voice vlan), # we have to set native vlan instead of access vlan config = read_config() voice_activated = request.POST.get('voice_activated', False) if not is_cisco_voice_enabled(config) and voice_activated: fac.set_native_vlan(interface, vlan) else: fac.set_vlan(interface.ifindex, vlan) else: fac.set_vlan(interface.ifindex, vlan) interface.vlan = vlan LogEntry.add_log_entry( account, u'set-vlan', u'{actor}: {object} - vlan set to "%s"' % vlan, subsystem=u'portadmin', object=interface, ) _logger.info('%s: %s:%s - vlan set to %s', account.login, interface.netbox.get_short_sysname(), interface.ifname, vlan) except (SnmpError, TypeError) as error: _logger.error('Error setting vlan: %s', error) messages.error(request, "Error setting vlan: %s" % error) def set_voice_vlan(fac, interface, request): """Set voicevlan on interface A voice vlan is a normal vlan that is defined by the user of NAV as a vlan that is used only for ip telephone traffic. To set a voice vlan we have to make sure the interface is configured to tag both the voicevlan and the "access-vlan". """ if 'voicevlan' in request.POST: config = read_config() voice_vlan = fetch_voice_vlan_for_netbox(request, fac, config) use_cisco_voice_vlan = (is_cisco_voice_enabled(config) and is_cisco(interface.netbox)) # Either the voicevlan is turned off or turned on turn_on_voice_vlan = request.POST.get('voicevlan') == 'true' account = get_account(request) try: if turn_on_voice_vlan: if use_cisco_voice_vlan: fac.set_cisco_voice_vlan(interface, voice_vlan) else: fac.set_voice_vlan(interface, voice_vlan) _logger.info('%s: %s:%s - %s', account.login, interface.netbox.get_short_sysname(), interface.ifname, 'voice vlan enabled') else: if use_cisco_voice_vlan: fac.disable_cisco_voice_vlan(interface) else: fac.set_access(interface, interface.vlan) _logger.info('%s: %s:%s - %s', account.login, interface.netbox.get_short_sysname(), interface.ifname, 'voice vlan disabled') except (SnmpError, ValueError, NotImplementedError) as error: messages.error(request, "Error setting voicevlan: %s" % error) def set_admin_status(fac, interface, request): """Set admin status for the interface :type fac: nav.portadmin.snmputils.SNMPFactory :type request: django.http.HttpRequest """ status_up = '1' status_down = '2' account = request.account if 'ifadminstatus' in request.POST: adminstatus = request.POST['ifadminstatus'] try: if adminstatus == status_up: LogEntry.add_log_entry( account, u'change status to up', u'change status to up', subsystem=u'portadmin', object=interface, ) _logger.info('%s: Setting ifadminstatus for %s to %s', account.login, interface, 'up') fac.set_if_up(interface.ifindex) elif adminstatus == status_down: LogEntry.add_log_entry( account, u'change status to down', u'change status to down', subsystem=u'portadmin', object=interface, ) _logger.info('%s: Setting ifadminstatus for %s to %s', account.login, interface, 'down') fac.set_if_down(interface.ifindex) except (SnmpError, ValueError) as error: messages.error(request, "Error setting ifadminstatus: %s" % error) def response_based_on_result(result): """Return response based on content of result result: dict containing result and message keys """ if result['messages']: return JsonResponse(result, status=500) else: return JsonResponse(result) def render_trunk_edit(request, interfaceid): """Controller for rendering trunk edit view""" interface = Interface.objects.get(pk=interfaceid) agent = get_factory(interface.netbox) if request.method == 'POST': try: handle_trunk_edit(request, agent, interface) except SnmpError as error: messages.error(request, 'Error editing trunk: %s' % error) else: messages.success(request, 'Trunk edit successful') account = request.account netbox = interface.netbox check_read_write(netbox, request) try: vlans = agent.get_netbox_vlans() # All vlans on this netbox native_vlan, trunked_vlans = agent.get_native_and_trunked_vlans( interface) except SnmpError: vlans = native_vlan = trunked_vlans = allowed_vlans = None messages.error(request, 'Error getting trunk information') else: if should_check_access_rights(account): allowed_vlans = find_allowed_vlans_for_user_on_netbox( account, interface.netbox, agent) else: allowed_vlans = vlans extra_path = [(netbox.sysname, reverse('portadmin-sysname', kwargs={'sysname': netbox.sysname})), ("Trunk %s" % interface,)] context = get_base_context(extra_path) context.update({'interface': interface, 'available_vlans': vlans, 'native_vlan': native_vlan, 'trunked_vlans': trunked_vlans, 'allowed_vlans': allowed_vlans}) return render_to_response('portadmin/trunk_edit.html', context, RequestContext(request)) def handle_trunk_edit(request, agent, interface): """Edit a trunk""" native_vlan = int(request.POST.get('native_vlan')) trunked_vlans = [int(vlan) for vlan in request.POST.getlist('trunk_vlans')] if should_check_access_rights(get_account(request)): # A user can avoid the form restrictions by sending a forged post # request Make sure only the allowed vlans are set old_native, old_trunked = agent.get_native_and_trunked_vlans(interface) allowed_vlans = [v.vlan for v in find_allowed_vlans_for_user(get_account(request))] trunked_vlans = filter_vlans(trunked_vlans, old_trunked, allowed_vlans) native_vlan = (native_vlan if native_vlan in allowed_vlans else old_native) _logger.info('Interface %s - native: %s, trunk: %s', interface, native_vlan, trunked_vlans) LogEntry.add_log_entry( request.account, u'set-vlan', u'{actor}: {object} - native vlan: "%s", trunk vlans: "%s"' % (native_vlan, trunked_vlans), subsystem=u'portadmin', object=interface, ) if trunked_vlans: agent.set_trunk(interface, native_vlan, trunked_vlans) else: agent.set_access(interface, native_vlan) @require_POST def restart_interface(request): """Restart the interface by setting admin status to down and up""" if not is_restart_interface_enabled(): _logger.debug('Not doing a restart of interface, it is configured off') return HttpResponse() interface = get_object_or_404( Interface, pk=request.POST.get('interfaceid')) fac = get_factory(interface.netbox) if fac: adminstatus = fac.get_if_admin_status(interface.ifindex) if adminstatus == SNMPHandler.IF_ADMIN_STATUS_DOWN: _logger.debug('Not restarting %s as it is down', interface) return HttpResponse() _logger.debug('Restarting interface %s', interface) try: # Restart interface so that client fetches new address fac.restart_if(interface.ifindex) except TimeOutException: # Swallow this exception as it is not important. Others should # create an error pass return HttpResponse() else: return HttpResponse(status=500) @require_POST def write_mem(request): """Do a write mem on the netbox""" if not is_write_mem_enabled(): _logger.debug('Not doing a write mem, it is configured off') return HttpResponse("Write mem is configured to not be done") interface = get_object_or_404( Interface, pk=request.POST.get('interfaceid')) fac = get_factory(interface.netbox) if fac: try: fac.write_mem() except SnmpError as error: error_message = 'Error doing write mem on {}: {}'.format( fac.netbox, error) _logger.error(error_message) return HttpResponse(error_message, status=500) except AttributeError: error_message = 'Error doing write mem on {}: {}'.format( fac.netbox, 'Write to memory not supported') _logger.error(error_message) return HttpResponse(error_message, status=500) return HttpResponse() else: return HttpResponse(status=500) def get_factory(netbox): """Get a SNMP factory instance""" config = read_config() timeout = get_config_value(config, 'general', 'timeout', fallback=3) retries = get_config_value(config, 'general', 'retries', fallback=3) try: return SNMPFactory.get_instance(netbox, timeout=timeout, retries=retries) except SnmpError as error: _logger.error('Error getting snmpfactory instance %s: %s', netbox, error) def get_config_value(config, section, key, fallback=None): """Get the value of key from a ConfigParser object, with fallback""" try: return config.get(section, key) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): return fallback<|fim▁end|>
readonly = True
<|file_name|>random.spec.js<|end_file_name|><|fim▁begin|>"use strict"; const RandomStrategy = require("../../../src/strategies/random"); const { extendExpect } = require("../utils"); extendExpect(expect); describe("Test RandomStrategy", () => { it("test with empty opts", () => { <|fim▁hole|> { a: "hello" }, { b: "world" }, ]; expect(strategy.select(list)).toBeAnyOf(list); expect(strategy.select(list)).toBeAnyOf(list); expect(strategy.select(list)).toBeAnyOf(list); }); });<|fim▁end|>
const strategy = new RandomStrategy(); const list = [
<|file_name|>115_eas_twodevices_turn.py<|end_file_name|><|fim▁begin|>"""EAS two-devices turn Revision ID: 17dc9c049f8b Revises: ad7b856bcc0 Create Date: 2014-10-21 20:38:14.311747 """ # revision identifiers, used by Alembic. revision = '17dc9c049f8b' down_revision = 'ad7b856bcc0' from datetime import datetime<|fim▁hole|> from alembic import op import sqlalchemy as sa from sqlalchemy.sql import text def upgrade(): from inbox.ignition import main_engine engine = main_engine() if not engine.has_table('easaccount'): return from inbox.models.session import session_scope Base = sa.ext.declarative.declarative_base() Base.metadata.reflect(engine) class EASAccount(Base): __table__ = Base.metadata.tables['easaccount'] primary_device = sa.orm.relationship( 'EASDevice', primaryjoin='and_(EASAccount.primary_device_id == EASDevice.id, ' 'EASDevice.deleted_at.is_(None))', uselist=False) secondary_device = sa.orm.relationship( 'EASDevice', primaryjoin='and_(EASAccount.secondary_device_id == EASDevice.id, ' 'EASDevice.deleted_at.is_(None))', uselist=False) class EASDevice(Base): __table__ = Base.metadata.tables['easdevice'] with session_scope(versioned=False) as \ db_session: accts = db_session.query(EASAccount).all() for a in accts: # Set both to filtered=False, //needed// for correct deploy. primary = EASDevice(created_at=datetime.utcnow(), updated_at=datetime.utcnow(), filtered=False, eas_device_id=a._eas_device_id, eas_device_type=a._eas_device_type, eas_policy_key=a.eas_policy_key, eas_sync_key=a.eas_account_sync_key) secondary = EASDevice(created_at=datetime.utcnow(), updated_at=datetime.utcnow(), filtered=False, eas_device_id=a._eas_device_id, eas_device_type=a._eas_device_type, eas_policy_key=a.eas_policy_key, eas_sync_key=a.eas_account_sync_key) a.primary_device = primary a.secondary_device = secondary db_session.add(a) db_session.commit() conn = op.get_bind() acct_device_map = dict( (id_, device_id) for id_, device_id in conn.execute(text( """SELECT id, secondary_device_id from easaccount"""))) print 'acct_device_map: ', acct_device_map for acct_id, device_id in acct_device_map.iteritems(): conn.execute(text(""" UPDATE easfoldersyncstatus SET device_id=:device_id WHERE account_id=:acct_id """), device_id=device_id, acct_id=acct_id) conn.execute(text(""" UPDATE easuid SET device_id=:device_id WHERE easaccount_id=:acct_id """), device_id=device_id, acct_id=acct_id) def downgrade(): raise Exception('!')<|fim▁end|>
<|file_name|>animation.py<|end_file_name|><|fim▁begin|>import os.path import pygame.image import time import ConfigParser from helpers import * from modules import Module class Animation(Module): def __init__(self, screen, folder, interval = None, autoplay = True): super(Animation, self).__init__(screen) if folder[:-1] != '/': folder = folder + '/' self.folder = folder self.screen = screen try: if self.is_single_file(): self.load_single() else: self.load_frames() if len(self.frames) == 0: raise Exception('No frames found in animation ' + self.folder) self.screen.pixel = self.frames[0] except Exception: print('Failed to load ' + folder) raise self.screen.update() if interval == None: try: self.interval = self.load_interval() except: print('No interval info found.') self.interval = 100 else: self.interval = interval self.pos = 0 if autoplay: self.start() def load_frames(self): self.frames = [] i = 0 while os.path.isfile(self.folder + str(i) + '.bmp'): try: bmp = pygame.image.load(self.folder + str(i) + '.bmp') except Exception: print('Error loading ' + str(i) + '.bmp from ' + self.folder) raise pixel_array = pygame.PixelArray(bmp) frame = [[pixel_array[x, y] for y in range(16)] for x in range(16)] self.frames.append(frame) i += 1 def is_single_file(self): return os.path.isfile(self.folder + '0.bmp') and not os.path.isfile(self.folder + '1.bmp') def load_single(self): self.frames = [] bmp = pygame.image.load(self.folder + '0.bmp') framecount = bmp.get_height() / 16 pixel_array = pygame.PixelArray(bmp) for index in range(framecount): frame = [[pixel_array[x, y + 16 * index] for y in range(16)] for x in range(16)] self.frames.append(frame)<|fim▁hole|> cfg.read(self.folder + 'config.ini') return cfg.getint('animation', 'hold') def tick(self): self.pos += 1 if self.pos >= len(self.frames): self.pos = 0 self.screen.pixel = self.frames[self.pos] self.screen.update() time.sleep(self.interval / 1000.0) def on_start(self): print('Starting ' + self.folder) def play_once(self): for frame in self.frames: self.screen.pixel = frame self.screen.update() time.sleep(self.interval / 1000.0)<|fim▁end|>
def load_interval(self): cfg = ConfigParser.ConfigParser()
<|file_name|>expr-match-generic.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // xfail-fast<|fim▁hole|> type compare<T> = extern "Rust" fn(T, T) -> bool; fn test_generic<T:Clone>(expected: T, eq: compare<T>) { let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") }; assert!((eq(expected, actual))); } fn test_bool() { fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; } test_generic::<bool>(true, compare_bool); } #[deriving(Clone)] struct Pair { a: int, b: int, } fn test_rec() { fn compare_rec(t1: Pair, t2: Pair) -> bool { t1.a == t2.a && t1.b == t2.b } test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec); } pub fn main() { test_bool(); test_rec(); }<|fim▁end|>
// -*- rust -*-
<|file_name|>PermissionsWindow.js<|end_file_name|><|fim▁begin|>/* Copyright 2010-2012 Infracom & Eurotechnia ([email protected]) This file is part of the Webcampak project. Webcampak is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Webcampak is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Webcampak. If not, see http://www.gnu.org/licenses/. */ console.log('Log: Load: Webcampak.view.permissions.PermissionsWindow'); Ext.define('Webcampak.view.permissions.PermissionsWindow' ,{ extend: 'Ext.window.Window', alias: 'widget.permissionswindow', requires: [ 'Webcampak.view.permissions.GroupsWindow', 'Webcampak.view.permissions.SourcesWindow', 'Webcampak.view.permissions.UsersWindow' ], iconCls: 'icon-user', title: i18n.gettext('Manage Permissions & interface settings'), layout: 'fit', width: 900, //height: 400, scroll: true, autoScroll: true, maximizable: true, minimizable: true, closeAction : 'hide', items: [{ xtype: 'tabpanel', items: [{ title: i18n.gettext('Users'), itemID: 'users', xtype: 'userswindow', border: 0 }, { title: i18n.gettext('Groups'), itemID: 'openGroupsTab', layout: 'fit', items: [{ xtype: 'groupwindow' }] }, { title: i18n.gettext('Companies'), itemID: 'companies', xtype: 'companylist', border: 0 }, { title: i18n.gettext('Sources'), itemID: 'sources', layout: 'fit', items: [{ xtype: 'sourcewindow' }] }] }]<|fim▁hole|><|fim▁end|>
});
<|file_name|>groupbox.go<|end_file_name|><|fim▁begin|>// Copyright 2010 The Walk Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build windows package walk import ( "syscall" ) import ( "github.com/lxn/win" ) const groupBoxWindowClass = `\o/ Walk_GroupBox_Class \o/` func init() { MustRegisterWindowClass(groupBoxWindowClass) } type GroupBox struct { WidgetBase hWndGroupBox win.HWND checkBox *CheckBox composite *Composite titleChangedPublisher EventPublisher } func NewGroupBox(parent Container) (*GroupBox, error) { gb := new(GroupBox) if err := InitWidget( gb, parent, groupBoxWindowClass, win.WS_VISIBLE, win.WS_EX_CONTROLPARENT); err != nil { return nil, err } succeeded := false defer func() { if !succeeded { gb.Dispose() } }() gb.hWndGroupBox = win.CreateWindowEx( 0, syscall.StringToUTF16Ptr("BUTTON"), nil, win.WS_CHILD|win.WS_VISIBLE|win.BS_GROUPBOX, 0, 0, 80, 24, gb.hWnd, 0, 0, nil) if gb.hWndGroupBox == 0 { return nil, lastError("CreateWindowEx(BUTTON)") } setWindowFont(gb.hWndGroupBox, gb.Font()) var err error gb.checkBox, err = NewCheckBox(gb) if err != nil { return nil, err } gb.SetCheckable(false) gb.checkBox.SetChecked(true) gb.checkBox.CheckedChanged().Attach(func() { gb.applyEnabledFromCheckBox(gb.checkBox.Checked()) }) setWindowVisible(gb.checkBox.hWnd, false) gb.composite, err = NewComposite(gb) if err != nil { return nil, err } win.SetWindowPos(gb.checkBox.hWnd, win.HWND_TOP, 0, 0, 0, 0, win.SWP_NOMOVE|win.SWP_NOSIZE) gb.MustRegisterProperty("Title", NewProperty( func() interface{} { return gb.Title() }, func(v interface{}) error { return gb.SetTitle(v.(string)) }, gb.titleChangedPublisher.Event())) gb.MustRegisterProperty("Checked", NewBoolProperty( func() bool { return gb.Checked() }, func(v bool) error { gb.SetChecked(v) return nil }, gb.CheckedChanged())) succeeded = true return gb, nil } func (gb *GroupBox) AsContainerBase() *ContainerBase { return gb.composite.AsContainerBase() } func (gb *GroupBox) LayoutFlags() LayoutFlags { if gb.composite == nil { return 0 } return gb.composite.LayoutFlags() } func (gb *GroupBox) MinSizeHint() Size { if gb.composite == nil { return Size{100, 100} } cmsh := gb.composite.MinSizeHint() if gb.Checkable() { s := gb.checkBox.SizeHint() cmsh.Width = maxi(cmsh.Width, s.Width) cmsh.Height += s.Height } return Size{cmsh.Width + 2, cmsh.Height + 14} } func (gb *GroupBox) SizeHint() Size { return gb.MinSizeHint() } func (gb *GroupBox) ClientBounds() Rectangle { cb := windowClientBounds(gb.hWndGroupBox) if gb.Layout() == nil { return cb } if gb.Checkable() { s := gb.checkBox.SizeHint() cb.Y += s.Height cb.Height -= s.Height } // FIXME: Use appropriate margins return Rectangle{cb.X + 1, cb.Y + 14, cb.Width - 2, cb.Height - 14} } func (gb *GroupBox) applyEnabled(enabled bool) { gb.WidgetBase.applyEnabled(enabled) if gb.hWndGroupBox != 0 { setWindowEnabled(gb.hWndGroupBox, enabled) } if gb.checkBox != nil { gb.checkBox.applyEnabled(enabled) } if gb.composite != nil { gb.composite.applyEnabled(enabled) } } func (gb *GroupBox) applyEnabledFromCheckBox(enabled bool) { if gb.hWndGroupBox != 0 { setWindowEnabled(gb.hWndGroupBox, enabled) } if gb.composite != nil { gb.composite.applyEnabled(enabled) } } func (gb *GroupBox) applyFont(font *Font) { gb.WidgetBase.applyFont(font) if gb.checkBox != nil { gb.checkBox.applyFont(font) } if gb.hWndGroupBox != 0 { setWindowFont(gb.hWndGroupBox, font) } if gb.composite != nil { gb.composite.applyFont(font) } } func (gb *GroupBox) SetSuspended(suspend bool) { gb.composite.SetSuspended(suspend) gb.WidgetBase.SetSuspended(suspend) gb.Invalidate() } func (gb *GroupBox) DataBinder() *DataBinder { return gb.composite.dataBinder } func (gb *GroupBox) SetDataBinder(dataBinder *DataBinder) {<|fim▁hole|>func (gb *GroupBox) Title() string { if gb.Checkable() { return gb.checkBox.Text() } return windowText(gb.hWndGroupBox) } func (gb *GroupBox) SetTitle(title string) error { if gb.Checkable() { if err := setWindowText(gb.hWndGroupBox, ""); err != nil { return err } return gb.checkBox.SetText(title) } return setWindowText(gb.hWndGroupBox, title) } func (gb *GroupBox) Checkable() bool { return gb.checkBox.visible } func (gb *GroupBox) SetCheckable(checkable bool) { title := gb.Title() gb.checkBox.SetVisible(checkable) gb.SetTitle(title) gb.updateParentLayout() } func (gb *GroupBox) Checked() bool { return gb.checkBox.Checked() } func (gb *GroupBox) SetChecked(checked bool) { gb.checkBox.SetChecked(checked) } func (gb *GroupBox) CheckedChanged() *Event { return gb.checkBox.CheckedChanged() } func (gb *GroupBox) Children() *WidgetList { if gb.composite == nil { // Without this we would get into trouble in NewComposite. return nil } return gb.composite.Children() } func (gb *GroupBox) Layout() Layout { if gb.composite == nil { // Without this we would get into trouble through the call to // SetCheckable in NewGroupBox. return nil } return gb.composite.Layout() } func (gb *GroupBox) SetLayout(value Layout) error { return gb.composite.SetLayout(value) } func (gb *GroupBox) MouseDown() *MouseEvent { return gb.composite.MouseDown() } func (gb *GroupBox) MouseMove() *MouseEvent { return gb.composite.MouseMove() } func (gb *GroupBox) MouseUp() *MouseEvent { return gb.composite.MouseUp() } func (gb *GroupBox) WndProc(hwnd win.HWND, msg uint32, wParam, lParam uintptr) uintptr { if gb.composite != nil { switch msg { case win.WM_COMMAND, win.WM_NOTIFY: gb.composite.WndProc(hwnd, msg, wParam, lParam) case win.WM_SETTEXT: gb.titleChangedPublisher.Publish() case win.WM_PAINT: win.UpdateWindow(gb.checkBox.hWnd) case win.WM_SIZE, win.WM_SIZING: wbcb := gb.WidgetBase.ClientBounds() if !win.MoveWindow( gb.hWndGroupBox, int32(wbcb.X), int32(wbcb.Y), int32(wbcb.Width), int32(wbcb.Height), true) { lastError("MoveWindow") break } if gb.Checkable() { s := gb.checkBox.SizeHint() gb.checkBox.SetBounds(Rectangle{9, 14, s.Width, s.Height}) } gbcb := gb.ClientBounds() gb.composite.SetBounds(gbcb) } } return gb.WidgetBase.WndProc(hwnd, msg, wParam, lParam) }<|fim▁end|>
gb.composite.SetDataBinder(dataBinder) }
<|file_name|>knmi_getdata.py<|end_file_name|><|fim▁begin|><|fim▁hole|> ''' Description: Author: Ronald van Haren, NLeSC ([email protected]) Created: - Last Modified: - License: Apache 2.0 Notes: - ''' from lxml.html import parse import csv import urllib2 from lxml import html import numbers import json import os import utils from numpy import vstack import argparse class get_knmi_reference_data: ''' description ''' def __init__(self, opts): #self.outputdir = opts.outputdir self.csvfile = opts.csvfile self.outputdir = opts.outputdir self.keep = opts.keep self.check_output_dir() if len(opts.stationid)==0: self.get_station_ids() else: self.stationdids = [opts.stationid] self.download_station_data() self.get_station_locations() def get_station_ids(self): ''' get all stationids from the KNMI website ''' self.url = 'http://www.knmi.nl/klimatologie/uurgegevens/' page = parse(self.url) # get list of ids rows = page.xpath(".//tbody/@id") #self.stationids = [int(stationid[3:]) for stationid in rows] self.stationids = [str(stationid) for stationid in rows] def download_station_data(self): page = parse(self.url) for stationid in self.stationids: print stationid relpaths = page.xpath(".//tbody[@id='" + stationid + "']/tr/td/span/a/@href") for path in relpaths: fullpath = os.path.join(self.url, path) request = urllib2.urlopen(fullpath) filename = os.path.basename(path) outputfile = os.path.join(self.outputdir, filename) if self.keep: if os.path.exists(outputfile): # check if filesize is not null if os.path.getsize(outputfile) > 0: # file exists and is not null, continue next iteration continue else: # file exists but is null, so remove and redownload os.remove(outputfile) elif os.path.exists(outputfile): os.remove(outputfile) #save output = open(outputfile, "w") output.write(request.read()) output.close() def get_station_locations(self): # get station names for stationids url = 'http://www.knmi.nl/klimatologie/metadata/stationslijst.html' page = parse(url) url_metadata = page.xpath(".//table/tr/td/a/@href") station_name_id = [c.text for c in page.xpath(".//table/tr/td/a")] station_id = [s.split()[0] for s in station_name_id] station_names = [" ".join(s.split()[1:]) for s in station_name_id] for idx, stationid in enumerate(station_id): station_url = os.path.join(os.path.split(url)[0], url_metadata[idx]) page = parse(station_url) rows = [c.text for c in page.xpath(".//table/tr/td")] idx_position = rows.index('Positie:') + 1 idx_startdate = rows.index('Startdatum:') + 1 lat, lon = rows[idx_position].encode('UTF-8').replace( '\xc2\xb0','').replace(' N.B. ', ',').replace( 'O.L.','').strip().split(',') lat,lon = self.latlon_conversion(lat,lon) try: dataout = vstack((dataout, [station_id[idx], station_names[idx], lat, lon, station_url])) except NameError: dataout = [station_id[idx], station_names[idx], lat, lon, station_url] header = ['station_id', 'station_name','latitude', 'longitude', 'url'] dataout = vstack((header, dataout)) # write to csv file utils.write_csvfile(self.csvfile, dataout) # get station locations pass def latlon_conversion(self, lat, lon): ''' conversion of GPS position to lat/lon decimals example string for lat and lon input: "52 11'" ''' # latitude conversion latd = lat.replace("'","").split() lat = float(latd[0]) + float(latd[1])/60 # longitude conversion lond = lon.replace("'","").split() lon = float(lond[0]) + float(lond[1])/60 return lat,lon def check_output_dir(self): ''' check if outputdir exists and create if not ''' if not os.path.exists(self.outputdir): os.makedirs(self.outputdir) if __name__ == "__main__": # define argument menu description = 'Get data KNMI reference stations' parser = argparse.ArgumentParser(description=description) # fill argument groups parser.add_argument('-o', '--outputdir', help='Data output directory', default=os.path.join(os.getcwd(),'KNMI'), required=False) parser.add_argument('-s', '--stationid', help='Station id', default='', required=False, action='store') parser.add_argument('-c', '--csvfile', help='CSV data file', required=True, action='store') parser.add_argument('-k', '--keep', help='Keep downloaded files', required=False, action='store_true') parser.add_argument('-l', '--log', help='Log level', choices=utils.LOG_LEVELS_LIST, default=utils.DEFAULT_LOG_LEVEL) # extract user entered arguments opts = parser.parse_args() # define logger logname = os.path.basename(__file__) + '.log' logger = utils.start_logging(filename=logname, level=opts.log) # process data get_knmi_reference_data(opts)<|fim▁end|>
#!/usr/bin/env python2
<|file_name|>swift.py<|end_file_name|><|fim▁begin|>''' Add in /edx/app/edxapp/edx-platform/lms/envs/aws.py: ORA2_SWIFT_URL = AUTH_TOKENS["ORA2_SWIFT_URL"] ORA2_SWIFT_KEY = AUTH_TOKENS["ORA2_SWIFT_KEY"] Add in /edx/app/edxapp/lms.auth.json "ORA2_SWIFT_URL": "https://EXAMPLE", "ORA2_SWIFT_KEY": "EXAMPLE", ORA2_SWIFT_KEY should correspond to Meta Temp-Url-Key configure in swift. Run 'swift stat -v' to get it. ''' import logging import urlparse <|fim▁hole|>import requests import swiftclient from django.conf import settings from ..exceptions import FileUploadInternalError from .base import BaseBackend logger = logging.getLogger("openassessment.fileupload.api") # prefix paths with current version, in case we need to roll it at some point SWIFT_BACKEND_VERSION = 1 class Backend(BaseBackend): """ Upload openassessment student files to swift """ def get_upload_url(self, key, content_type): bucket_name, key_name = self._retrieve_parameters(key) key, url = get_settings() try: temp_url = swiftclient.utils.generate_temp_url( path='/v%s%s/%s/%s' % (SWIFT_BACKEND_VERSION, url.path, bucket_name, key_name), key=key, method='PUT', seconds=self.UPLOAD_URL_TIMEOUT ) return '%s://%s%s' % (url.scheme, url.netloc, temp_url) except Exception as ex: logger.exception( u"An internal exception occurred while generating an upload URL." ) raise FileUploadInternalError(ex) def get_download_url(self, key): bucket_name, key_name = self._retrieve_parameters(key) key, url = get_settings() try: temp_url = swiftclient.utils.generate_temp_url( path='/v%s%s/%s/%s' % (SWIFT_BACKEND_VERSION, url.path, bucket_name, key_name), key=key, method='GET', seconds=self.DOWNLOAD_URL_TIMEOUT ) download_url = '%s://%s%s' % (url.scheme, url.netloc, temp_url) response = requests.get(download_url) return download_url if response.status_code == 200 else "" except Exception as ex: logger.exception( u"An internal exception occurred while generating a download URL." ) raise FileUploadInternalError(ex) def remove_file(self, key): bucket_name, key_name = self._retrieve_parameters(key) key, url = get_settings() try: temp_url = swiftclient.utils.generate_temp_url( path='%s/%s/%s' % (url.path, bucket_name, key_name), key=key, method='DELETE', seconds=self.DOWNLOAD_URL_TIMEOUT) remove_url = '%s://%s%s' % (url.scheme, url.netloc, temp_url) response = requests.delete(remove_url) return response.status_code == 204 except Exception as ex: logger.exception( u"An internal exception occurred while removing object on swift storage." ) raise FileUploadInternalError(ex) def get_settings(): """ Returns the swift key and a parsed url. Both are generated from django settings. """ url = getattr(settings, 'ORA2_SWIFT_URL', None) key = getattr(settings, 'ORA2_SWIFT_KEY', None) url = urlparse.urlparse(url) return key, url<|fim▁end|>
<|file_name|>util.js<|end_file_name|><|fim▁begin|>/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Generates paragraph text style for a text element. * * @param {Object} props Props. * @param {function(number):any} dataToStyleX Converts a x-unit to CSS. * @param {function(number):any} dataToStyleY Converts a y-unit to CSS. * @param {function(number):any} dataToFontSizeY Converts a font-size metric to * y-unit CSS. * @param {Object<*>} element Text element properties. * @param {function(number):any} dataToPaddingY Falls back to dataToStyleX if not provided. * @return {Object} The map of text style properties and values. */ export function generateParagraphTextStyle( props, dataToStyleX, dataToStyleY, dataToFontSizeY = dataToStyleY, element, dataToPaddingY = dataToStyleY ) { const { font, fontSize, lineHeight, padding, textAlign } = props; const { marginOffset } = calcFontMetrics(element); const verticalPadding = padding?.vertical || 0; const horizontalPadding = padding?.horizontal || 0; const hasPadding = verticalPadding || horizontalPadding; const paddingStyle = hasPadding ? `${dataToStyleY(verticalPadding)} ${dataToStyleX(horizontalPadding)}` : 0; return { dataToEditorY: dataToStyleY, whiteSpace: 'pre-wrap', overflowWrap: 'break-word', wordBreak: 'break-word', margin: `${dataToPaddingY(-marginOffset / 2)} 0`, fontFamily: generateFontFamily(font), fontSize: dataToFontSizeY(fontSize), font, lineHeight, textAlign, padding: paddingStyle, }; } export const generateFontFamily = ({ family, fallbacks } = {}) => { const genericFamilyKeywords = [<|fim▁hole|> 'cursive', 'fantasy', 'monospace', 'serif', 'sans-serif', ]; // Wrap into " since some fonts won't work without it. let fontFamilyDisplay = family ? `"${family}"` : ''; if (fallbacks && fallbacks.length) { fontFamilyDisplay += family ? `,` : ``; fontFamilyDisplay += fallbacks .map((fallback) => genericFamilyKeywords.includes(fallback) ? fallback : `"${fallback}"` ) .join(`,`); } return fontFamilyDisplay; }; export const getHighlightLineheight = function ( lineHeight, verticalPadding = 0, unit = 'px' ) { if (verticalPadding === 0) { return `${lineHeight}em`; } return `calc(${lineHeight}em ${verticalPadding > 0 ? '+' : '-'} ${ 2 * Math.abs(verticalPadding) }${unit})`; }; export function calcFontMetrics(element) { if (!element.font.metrics) { return { contentAreaPx: 0, lineBoxPx: 0, marginOffset: 0, }; } const { fontSize, lineHeight, font: { metrics: { upm, asc, des }, }, } = element; // We cant to cut some of the "virtual-area" // More info: https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align const contentAreaPx = ((asc - des) / upm) * fontSize; const lineBoxPx = lineHeight * fontSize; const marginOffset = lineBoxPx - contentAreaPx; return { marginOffset, contentAreaPx, lineBoxPx, }; }<|fim▁end|>
<|file_name|>instagram.ts<|end_file_name|><|fim▁begin|>(() => { /** * Use iframe.ly for instagram */ const instagramService = (iframelyService, $q) => { return { name: 'Instagram', patterns: ['(?:(?:http|https):\/\/)?(?:www.)?(?:instagr(?:\.am|am\.com))\/p\/.+'], // eslint-disable-line embed: (url, max_width) => { // eslint-disable-line const deferred = $q.defer(); iframelyService.embed(url, true).then(<|fim▁hole|> }, (error) => { deferred.reject(error.error_message || error.data.error_message); } ); return deferred.promise; }, }; }; angular.module('angular-embed.handlers') .service('embedInstagramHandler', ['iframelyService', '$q', instagramService]); })();<|fim▁end|>
(response) => { deferred.resolve(response);
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Root Module // // This file is part of AEx. // Copyright (C) 2017 Jeffrey Sharp<|fim▁hole|>// // AEx is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // AEx is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See // the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with AEx. If not, see <http://www.gnu.org/licenses/>. //#[macro_use] pub mod util; pub mod ast; pub mod fmt; pub mod io; //pub mod source; pub mod target; //pub mod types;<|fim▁end|>
<|file_name|>EventDetectionWeb.py<|end_file_name|><|fim▁begin|>import sys; import os sys.path.insert(0, os.path.abspath('..')) sys.path.insert(0, os.path.abspath('.')) from flask import Flask, render_template, request, redirect import subprocess from Utils import subprocess_helpers from Utils.DataSource import * app = Flask(__name__) dataSource = DataSource() def launch_preprocessors(): process = subprocess.Popen( subprocess_helpers.python_path + " Daemons/QueryProcessorDaemon.py && " + subprocess_helpers.python_path + " Daemons/ArticleProcessorDaemon.py", executable=subprocess_helpers.executable, shell=True, universal_newlines=True) @app.route("/", methods=["GET"]) def queries(): # Get lists of query from database with counts of associated articles all_queries = dataSource.queries_route() queries_formatted = [{"id": q[0], "subject": q[1], "verb": q[2], "direct_obj": q[3], "indirect_obj": q[4], "loc": q[5], "article_count": q[6]} for q in all_queries] return render_template("queries.html", queries=queries_formatted) @app.route("/query", methods=["POST"]) def new_query(): # TODO: server side validation subject = request.form["subject"] verb = request.form["verb"] direct_obj = request.form["direct-object"] indirect_obj = request.form["indirect-object"] loc = request.form["location"] email = request.form["user-email"] phone = request.form["user-phone"] # Put into database dataSource.new_query(email, phone, subject, verb, direct_obj, indirect_obj, loc) return redirect("/") @app.route("/query/<query_id>", methods=["GET"]) def query(query_id): # find query by id # if we don't find a query with that id, 404 articles, db_query = dataSource.query_route(query_id) if db_query is not None: articles_formatted = [{"title": a[0], "source": a[1], "url": a[2]} for a in articles] query_formatted = {"id": db_query[0], "subject": db_query[1], "verb": db_query[2], "direct_obj": db_query[3], "indirect_obj": db_query[4], "loc": db_query[5]} return render_template("query.html", query=query_formatted, articles=articles_formatted) return render_template("404.html"), 404 @app.route("/articles", methods=["GET"]) def articles(): articles = dataSource.articles_route() articles_formatted = [{"title": a[0], "source": a[1], "url": a[2]} for a in articles] return render_template("articles.html", articles=articles_formatted)<|fim▁hole|>def page_not_found(e): return render_template("404.html"), 404 if __name__ == "__main__": app.run(debug=True)<|fim▁end|>
@app.errorhandler(404)
<|file_name|>caffe.py<|end_file_name|><|fim▁begin|>from .util import DummyDict from .util import tprint import deepdish as dd import numpy as np # CAFFE WEIGHTS: O x I x H x W # TFLOW WEIGHTS: H x W x I x O def to_caffe(tfW, name=None, shape=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()): assert conv_fc_transitionals is None or name is not None if tfW.ndim == 4: if (name == 'conv1_1' or name == 'conv1' or name == color_layer) and tfW.shape[2] == 3: tfW = tfW[:, :, ::-1] info[name] = 'flipped' cfW = tfW.transpose(3, 2, 0, 1) return cfW else: if conv_fc_transitionals is not None and name in conv_fc_transitionals: cf_shape = conv_fc_transitionals[name] tf_shape = (cf_shape[2], cf_shape[3], cf_shape[1], cf_shape[0]) cfW = tfW.reshape(tf_shape).transpose(3, 2, 0, 1).reshape(cf_shape[0], -1) info[name] = 'fc->c transitioned with caffe shape {}'.format(cf_shape) return cfW else: return tfW.T def from_caffe(cfW, name=None, color_layer='', conv_fc_transitionals=None, info=DummyDict()): assert conv_fc_transitionals is None or name is not None if cfW.ndim == 4: tfW = cfW.transpose(2, 3, 1, 0) assert conv_fc_transitionals is None or name is not None if (name == 'conv1_1' or name == 'conv1' or name == color_layer) and tfW.shape[2] == 3: tfW = tfW[:, :, ::-1] info[name] = 'flipped' return tfW else: if conv_fc_transitionals is not None and name in conv_fc_transitionals: cf_shape = conv_fc_transitionals[name] tfW = cfW.reshape(cf_shape).transpose(2, 3, 1, 0).reshape(-1, cf_shape[0]) info[name] = 'c->fc transitioned with caffe shape {}'.format(cf_shape) return tfW else: return cfW.T def load_caffemodel(path, session, prefix='', ignore=set(), conv_fc_transitionals=None, renamed_layers=DummyDict(), color_layer='', verbose=False, pre_adjust_batch_norm=False): import tensorflow as tf def find_weights(name, which='weights'): for tw in tf.trainable_variables(): if tw.name.split(':')[0] == name + '/' + which: return tw return None """ def find_batch_norm(name, which='mean'): for tw in tf.all_variables(): if tw.name.endswith(name + '/bn_' + which + ':0'): return tw return None """ data = dd.io.load(path, '/data') assigns = [] loaded = [] info = {} for key in data: local_key = prefix + renamed_layers.get(key, key) if key not in ignore: bn_name = 'batch_' + key if '0' in data[key]: weights = find_weights(local_key, 'weights') if weights is not None: W = from_caffe(data[key]['0'], name=key, info=info, conv_fc_transitionals=conv_fc_transitionals, color_layer=color_layer) if W.ndim != weights.get_shape().as_list(): W = W.reshape(weights.get_shape().as_list()) init_str = '' if pre_adjust_batch_norm and bn_name in data: bn_data = data[bn_name] sigma = np.sqrt(1e-5 + bn_data['1'] / bn_data['2']) W /= sigma init_str += ' batch-adjusted' assigns.append(weights.assign(W)) loaded.append('{}:0 -> {}:weights{} {}'.format(key, local_key, init_str, info.get(key, ''))) if '1' in data[key]: biases = find_weights(local_key, 'biases') if biases is not None: bias = data[key]['1'] init_str = '' if pre_adjust_batch_norm and bn_name in data: bn_data = data[bn_name] sigma = np.sqrt(1e-5 + bn_data['1'] / bn_data['2']) mu = bn_data['0'] / bn_data['2'] bias = (bias - mu) / sigma init_str += ' batch-adjusted'<|fim▁hole|> # Check batch norm and load them (unless they have been folded into) #if not pre_adjust_batch_norm: session.run(assigns) if verbose: tprint('Loaded model from', path) for l in loaded: tprint('-', l) return loaded def save_caffemodel(path, session, layers, prefix='', conv_fc_transitionals=None, color_layer='', verbose=False, save_batch_norm=False, lax_naming=False): import tensorflow as tf def find_weights(name, which='weights'): for tw in tf.trainable_variables(): if lax_naming: ok = tw.name.split(':')[0].endswith(name + '/' + which) else: ok = tw.name.split(':')[0] == name + '/' + which if ok: return tw return None def find_batch_norm(name, which='mean'): for tw in tf.all_variables(): #if name + '_moments' in tw.name and tw.name.endswith(which + '/batch_norm:0'): if tw.name.endswith(name + '/bn_' + which + ':0'): return tw return None data = {} saved = [] info = {} for lay in layers: if isinstance(lay, tuple): lay, p_lay = lay else: p_lay = lay weights = find_weights(prefix + p_lay, 'weights') d = {} if weights is not None: tfW = session.run(weights) cfW = to_caffe(tfW, name=lay, conv_fc_transitionals=conv_fc_transitionals, info=info, color_layer=color_layer) d['0'] = cfW saved.append('{}:weights -> {}:0 {}'.format(prefix + p_lay, lay, info.get(lay, ''))) biases = find_weights(prefix + p_lay, 'biases') if biases is not None: b = session.run(biases) d['1'] = b saved.append('{}:biases -> {}:1'.format(prefix + p_lay, lay)) if d: data[lay] = d if save_batch_norm: mean = find_batch_norm(lay, which='mean') variance = find_batch_norm(lay, which='var') if mean is not None and variance is not None: d = {} d['0'] = np.squeeze(session.run(mean)) d['1'] = np.squeeze(session.run(variance)) d['2'] = np.array([1.0], dtype=np.float32) data['batch_' + lay] = d saved.append('batch_norm({}) saved'.format(lay)) dd.io.save(path, dict(data=data), compression=None) if verbose: tprint('Saved model to', path) for l in saved: tprint('-', l) return saved<|fim▁end|>
assigns.append(biases.assign(bias)) loaded.append('{}:1 -> {}:biases{}'.format(key, local_key, init_str))
<|file_name|>feature_maxuploadtarget.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test behavior of -maxuploadtarget. * Verify that getdata requests for old blocks (>1week) are dropped if uploadtarget has been reached. * Verify that getdata requests for recent blocks are respected even if uploadtarget has been reached. * Verify that the upload counters are reset after 24 hours. """ from collections import defaultdict import time from test_framework.messages import CInv, msg_getdata from test_framework.mininode import P2PInterface from test_framework.test_framework import GuldenTestFramework from test_framework.util import assert_equal, mine_large_block class TestP2PConn(P2PInterface): def __init__(self): super().__init__() self.block_receive_map = defaultdict(int) def on_inv(self, message): pass def on_block(self, message): message.block.calc_sha256() self.block_receive_map[message.block.sha256] += 1 class MaxUploadTest(GuldenTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [["-maxuploadtarget=800"]] # Cache for utxos, as the listunspent may take a long time later in the test self.utxo_cache = [] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): # Before we connect anything, we first set the time on the node # to be in the past, otherwise things break because the CNode # time counters can't be reset backward after initialization old_time = int(time.time() - 2*60*60*24*7) self.nodes[0].setmocktime(old_time) # Generate some old blocks self.nodes[0].generate(130) # p2p_conns[0] will only request old blocks # p2p_conns[1] will only request new blocks # p2p_conns[2] will test resetting the counters p2p_conns = [] for _ in range(3): p2p_conns.append(self.nodes[0].add_p2p_connection(TestP2PConn())) # Now mine a big block mine_large_block(self.nodes[0], self.utxo_cache) # Store the hash; we'll request this later big_old_block = self.nodes[0].getbestblockhash() old_block_size = self.nodes[0].getblock(big_old_block, True)['size'] big_old_block = int(big_old_block, 16) # Advance to two days ago self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24) # Mine one more block, so that the prior block looks old mine_large_block(self.nodes[0], self.utxo_cache) # We'll be requesting this new block too big_new_block = self.nodes[0].getbestblockhash() big_new_block = int(big_new_block, 16) # p2p_conns[0] will test what happens if we just keep requesting the # the same big old block too many times (expect: disconnect) getdata_request = msg_getdata() getdata_request.inv.append(CInv(2, big_old_block)) max_bytes_per_day = 800*1024*1024 daily_buffer = 144 * 4000000 max_bytes_available = max_bytes_per_day - daily_buffer success_count = max_bytes_available // old_block_size # 576MB will be reserved for relaying new blocks, so expect this to # succeed for ~235 tries. for i in range(success_count): p2p_conns[0].send_message(getdata_request) p2p_conns[0].sync_with_ping() assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1) assert_equal(len(self.nodes[0].getpeerinfo()), 3) # At most a couple more tries should succeed (depending on how long # the test has been running so far). for i in range(3): p2p_conns[0].send_message(getdata_request) p2p_conns[0].wait_for_disconnect() assert_equal(len(self.nodes[0].getpeerinfo()), 2) self.log.info("Peer 0 disconnected after downloading old block too many times") # Requesting the current block on p2p_conns[1] should succeed indefinitely, # even when over the max upload target. # We'll try 800 times getdata_request.inv = [CInv(2, big_new_block)] for i in range(800): p2p_conns[1].send_message(getdata_request) p2p_conns[1].sync_with_ping() assert_equal(p2p_conns[1].block_receive_map[big_new_block], i+1) self.log.info("Peer 1 able to repeatedly download new block") # But if p2p_conns[1] tries for an old block, it gets disconnected too. getdata_request.inv = [CInv(2, big_old_block)] p2p_conns[1].send_message(getdata_request) p2p_conns[1].wait_for_disconnect() assert_equal(len(self.nodes[0].getpeerinfo()), 1) self.log.info("Peer 1 disconnected after trying to download old block") self.log.info("Advancing system time on node to clear counters...") # If we advance the time by 24 hours, then the counters should reset, # and p2p_conns[2] should be able to retrieve the old block. self.nodes[0].setmocktime(int(time.time())) p2p_conns[2].sync_with_ping() p2p_conns[2].send_message(getdata_request) p2p_conns[2].sync_with_ping() assert_equal(p2p_conns[2].block_receive_map[big_old_block], 1) self.log.info("Peer 2 able to download old block") self.nodes[0].disconnect_p2ps() #stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1 self.log.info("Restarting nodes with -whitelist=127.0.0.1") self.stop_node(0) self.start_node(0, ["-whitelist=127.0.0.1", "-maxuploadtarget=1"]) # Reconnect to self.nodes[0] self.nodes[0].add_p2p_connection(TestP2PConn()) #retrieve 20 blocks which should be enough to break the 1MB limit getdata_request.inv = [CInv(2, big_new_block)] for i in range(20): self.nodes[0].p2p.send_message(getdata_request) self.nodes[0].p2p.sync_with_ping() assert_equal(self.nodes[0].p2p.block_receive_map[big_new_block], i+1) getdata_request.inv = [CInv(2, big_old_block)] self.nodes[0].p2p.send_and_ping(getdata_request)<|fim▁hole|> self.log.info("Peer still connected after trying to download old block (whitelisted)") if __name__ == '__main__': MaxUploadTest().main()<|fim▁end|>
assert_equal(len(self.nodes[0].getpeerinfo()), 1) #node is still connected because of the whitelist
<|file_name|>el.js<|end_file_name|><|fim▁begin|>OC.L10N.register( "files_sharing", { "Server to server sharing is not enabled on this server" : "Ο διαμοιρασμός μεταξύ διακομιστών δεν έχει ενεργοποιηθεί σε αυτόν το διακομιστή", "The mountpoint name contains invalid characters." : "Το όνομα σημείου προσάρτησης περιέχει μη έγκυρους χαρακτήρες.", "Not allowed to create a federated share with the same user server" : "Δεν είναι επιτρεπτή η δημιουργία ομόσπονδου διαμοιρασμού με τον ίδιο διακομιστή χρήστη", "Invalid or untrusted SSL certificate" : "Μη έγκυρο ή μη έμπιστο πιστοποιητικό SSL", "Could not authenticate to remote share, password might be wrong" : "Δεν ήταν δυνατή η πιστοποίηση στο απομακρυσμένο διαμοιρασμένο στοιχείο, μπορεί να είναι λάθος ο κωδικός πρόσβασης", "Storage not valid" : "Μη έγκυρος αποθηκευτικός χώρος", "Couldn't add remote share" : "Αδυναμία προσθήκης απομακρυσμένου κοινόχρηστου φακέλου", "Shared with you" : "Διαμοιρασμένα με εσάς", "Shared with others" : "Διαμοιρασμένα με άλλους", "Shared by link" : "Διαμοιρασμένα μέσω συνδέσμου", "Anonymous upload" : "Ανώνυμη μεταφόρτωση", "Click to select files or use drag & drop to upload" : "Κάντε κλικ για να επιλέξετε αρχεία ή χρησιμοποιήστε drag & drop για μεταφόρτωση", "Uploaded files" : "Μεταφόρτωση αρχείων", "Uploading..." : "Μεταφόρτωση...", "Nothing shared with you yet" : "Κανένα αρχείο δεν έχει διαμοιραστεί ακόμα με εσάς.", "Files and folders others share with you will show up here" : "Τα αρχεία και οι φάκελοι που άλλοι διαμοιράζονται με εσάς θα εμφανιστούν εδώ", "Nothing shared yet" : "Δεν έχει διαμοιραστεί τίποτα μέχρι στιγμής", "Files and folders you share will show up here" : "Τα αρχεία και οι φάκελοι που διαμοιράζεστε θα εμφανιστούν εδώ", "No shared links" : "Κανένας διαμοιρασμένος σύνδεσμος", "Files and folders you share by link will show up here" : "Τα αρχεία και οι φάκελοι που διαμοιράζεστε μέσω συνδέσμου θα εμφανιστούνε εδώ", "Do you want to add the remote share {name} from {owner}@{remote}?" : "Θέλετε να προσθέσουμε τον απομακρυσμένο κοινόχρηστο φάκελο {name} από {owner}@{remote}?", "Remote share" : "Απομακρυσμένος κοινόχρηστος φάκελος", "Remote share password" : "Κωδικός πρόσβασης απομακρυσμένου κοινόχρηστου φακέλου", "Cancel" : "Άκυρο", "Add remote share" : "Προσθήκη απομακρυσμένου κοινόχρηστου φακέλου", "You can upload into this folder" : "Μπορείτε να μεταφορτώσετε σε αυτόν τον φάκελο", "No ownCloud installation (7 or higher) found at {remote}" : "Δεν βρέθηκε εγκατάστση ownCloud (7 ή νεώτερη) στο {remote}", "Invalid ownCloud url" : "Άκυρη url ownCloud ", "Share" : "Διαμοιράστε", "No expiration date set" : "Δεν καθορίστηκε ημερομηνία λήξης", "Shared by" : "Διαμοιράστηκε από", "Sharing" : "Διαμοιρασμός", "Share API is disabled" : "Ο διαμοιρασμός ΑΡΙ είναι απενεργοποιημένος", "Wrong share ID, share doesn't exist" : "Εσφαλμένη διαδρομή, το αρχείο/ο φάκελος δεν υπάρχει", "Could not delete share" : "Αδυναμία διαγραφής διαμοιρασμένου", "Please specify a file or folder path" : "Παρακαλώ καθορίστε την διαδρομή του αρχείου ή του φακέλου", "Wrong path, file/folder doesn't exist" : "Εσφαλμένη διαδρομή, το αρχείο/ο φάκελος δεν υπάρχει", "Cannot remove all permissions" : "Δεν είναι δυνατή η κατάργηση όλων των δικαιωμάτων", "Please specify a valid user" : "Παρακαλώ καθορίστε έγκυρο χρήστη", "Group sharing is disabled by the administrator" : "O διαμοιρασμός μεταξύ της ιδίας ομάδας έχει απενεργοποιηθεί από το διαχειρηστή", "Please specify a valid group" : "Παρακαλώ καθορίστε μια έγκυρη ομάδα", "Public link sharing is disabled by the administrator" : "Ο δημόσιος διαμοιρασμός συνδέσμου έχει απενεργοποιηθεί από τον διαχειριστή", "Public upload disabled by the administrator" : "Η δημόσια μεταφόρτωση έχει απενεργοποιηθεί από τον διαχειριστή", "Public upload is only possible for publicly shared folders" : "Η δημόσια μεταφόρτωση είναι δυνατή μόνο για δημόσια διαμοιρασμένους φακέλους", "Invalid date, date format must be YYYY-MM-DD" : "Μη έγκυρη ημερομηνία, η μορφή ημερομηνίας πρέπει να είναι YYYY-MM-DD", "Sharing %s failed because the back end does not allow shares from type %s" : "Αποτυχία διαμοιρασμού %s γιατί το σύστημα δεν υποστηρίζει διαμοιρασμό τύπου %s", "Unknown share type" : "Άγνωστος τύπος διαμοιρασμού", "Not a directory" : "Δεν είναι κατάλογος", "Could not lock path" : "Αδυναμία κλειδώματος της διαδρομής", "Can't change permissions for public share links" : "Δεν μπορούν να γίνουν αλλαγές δικαιοδοσίας για δημόσιο διαμοιρασμό συνδέσμων", "Wrong or no update parameter given" : "Δόθηκε λανθασμένη ή χωρίς αναβάθμιση παράμετρος", "Cannot increase permissions" : "Τα δικαιώματα είναι περιορισμένα ", "A file or folder has been <strong>shared</strong>" : "Ένα αρχείο ή φάκελος <strong>διαμοιράστηκε</strong>", "A file or folder was shared from <strong>another server</strong>" : "Ένα αρχείο ή φάκελος διαμοιράστηκε από <strong>έναν άλλο διακομιστή</strong>", "A public shared file or folder was <strong>downloaded</strong>" : "Ένα δημόσια διαμοιρασμένο αρχείο ή φάκελος <strong>ελήφθη</strong>", "You received a new remote share %2$s from %1$s" : "Λάβατε ένα νέο απομακρυσμένο κοινόχρηστο %2$s από %1$s", "You received a new remote share from %s" : "Λάβατε ένα νέο απομακρυσμένο κοινόχρηστο φάκελο από %s", "%1$s accepted remote share %2$s" : "Ο %1$s αποδέχθηκε τον απομακρυσμένο φάκελο %2$s", "%1$s declined remote share %2$s" : "Ο %1$s απέρριψε το απομακρυσμένο κοινόχρηστο %2$s", "%1$s unshared %2$s from you" : "Ο %1$s αναίρεσε το διαμοιρασμό του %2$s με εσάς",<|fim▁hole|> "Public shared file %1$s was downloaded" : "Το δημόσιο διαμοιρασμένο αρχείο %1$s ελήφθη", "You shared %1$s with %2$s" : "Διαμοιραστήκατε το %1$s με %2$s", "%2$s shared %1$s with %3$s" : "Ο %2$s διαμοιράστηκε το %1$s με %3$s", "You removed the share of %2$s for %1$s" : "Έχετε αφαιρέσει το διαμοιρασμό του %2$s για %1$s", "%2$s removed the share of %3$s for %1$s" : "Ο %2$s έχει αφαιρέσει τον διαμοιασμό του %3$s για %1$s", "You shared %1$s with group %2$s" : "Διαμοιραστήκατε %1$s με την ομάδα %2$s", "%2$s shared %1$s with group %3$s" : "Ο %2$s διαμοιράστηκε το %1$s με την ομάδα %3$s", "You removed the share of group %2$s for %1$s" : "Έχετε αφαιρέσει το διαμοιρασμό της ομάδας %2$s για %1$s", "%2$s removed the share of group %3$s for %1$s" : "Ο %2$s αφαίρεσε τον διαμοιρασμό της ομάδας %3$s για %1$s", "%2$s shared %1$s via link" : "Ο %2$s διαμοιράστηκε το %1$s μέσω συνδέσμου", "You shared %1$s via link" : "Μοιραστήκατε το %1$s μέσω συνδέσμου", "You removed the public link for %1$s" : "Αφαιρέσατε δημόσιο σύνδεσμο για %1$s", "%2$s removed the public link for %1$s" : "Ο %2$s αφαίρεση τον δημόσιο σύνδεσμο για %1$s", "Your public link for %1$s expired" : "Έληξε ο δημόσιος σύνδεσμος για %1$s", "The public link of %2$s for %1$s expired" : "Έληξε ο δημόσιος σύνδεσμος του %2$s για %1$s", "%2$s shared %1$s with you" : "Ο %2$s διαμοιράστηκε το %1$s με εσάς", "%2$s removed the share for %1$s" : "Ο %2$s αφαίρεση το κοινόχρηστο για %1$s", "Downloaded via public link" : "Μεταφορτώθηκε μέσω δημόσιου συνδέσμου", "Shared with %2$s" : "Διαμοιράστηκε με %2$s", "Shared with %3$s by %2$s" : "Διαμοιράστηκε με %3$s από %2$s", "Removed share for %2$s" : "Αφαίρεση διαμοιρασμού για %2$s", "%2$s removed share for %3$s" : "Ο %2$s αφαίρεσε τον διαμοιρασμό για %3$s", "Shared with group %2$s" : "Διαμοιράστηκε με την ομάδα %2$s", "Shared with group %3$s by %2$s" : "Διαμοιράστηκε με την ομάδα %3$s από %2$s", "Removed share of group %2$s" : "Αφαίρεση κοινόχρηστου από την ομάδα %2$s", "%2$s removed share of group %3$s" : "Ο/Η %2$s κατήργησε την κοινή χρήση της ομάδας %3$s", "Shared via link by %2$s" : "Διαμοιράστηκε μέσω συνδέσμου από %2$s", "Shared via public link" : "Διαμοιράστηκε μέσω δημόσιου συνδέσμου", "Removed public link" : "Αφαιρέθηκε ο δημόσιος σύνδεσμος", "%2$s removed public link" : "Ο/Η %2$s κατήργησε τον δημόσιο σύνδεσμο", "Public link expired" : "Έληξε ο δημόσιος σύνδεσμος", "Public link of %2$s expired" : "Έληξε ο δημόσιος σύνδεσμος του %2$s", "Shared by %2$s" : "Διαμοιράστηκε από %2$s", "Shares" : "Κοινόχρηστοι φάκελοι", "This share is password-protected" : "Αυτός ο κοινόχρηστος φάκελος προστατεύεται με κωδικό", "The password is wrong. Try again." : "Εσφαλμένος κωδικός πρόσβασης. Προσπαθήστε ξανά.", "Password" : "Κωδικός πρόσβασης", "No entries found in this folder" : "Δεν βρέθηκαν καταχωρήσεις σε αυτόν το φάκελο", "Name" : "Όνομα", "Share time" : "Χρόνος διαμοιρασμού", "Expiration date" : "Ημερομηνία λήξης", "Sorry, this link doesn’t seem to work anymore." : "Συγγνώμη, αυτός ο σύνδεσμος μοιάζει να μην ισχύει πια.", "Reasons might be:" : "Οι λόγοι μπορεί να είναι:", "the item was removed" : "το αντικείμενο απομακρύνθηκε", "the link expired" : "ο σύνδεσμος έληξε", "sharing is disabled" : "ο διαμοιρασμός απενεργοποιήθηκε", "For more info, please ask the person who sent this link." : "Για περισσότερες πληροφορίες, παρακαλώ ρωτήστε το άτομο που σας έστειλε αυτόν τον σύνδεσμο.", "%s is publicly shared" : "Το %s είναι κοινόχρηστο δημοσίως", "Add to your ownCloud" : "Προσθήκη στο ownCloud σου", "Download" : "Λήψη", "Download %s" : "Λήψη %s", "Direct link" : "Άμεσος σύνδεσμος" }, "nplurals=2; plural=(n != 1);");<|fim▁end|>
"Public shared folder %1$s was downloaded" : "Ο δημόσιος διαμοιρασμένος φάκελος %1$s ελήφθη",
<|file_name|>0011_badgesbycoursemultilang.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'BadgeByCourse.title_en' db.add_column('badges_badgebycourse', 'title_en', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.title_es' db.add_column('badges_badgebycourse', 'title_es', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.title_it' db.add_column('badges_badgebycourse', 'title_it', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.title_pt' db.add_column('badges_badgebycourse', 'title_pt', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.title_fr' db.add_column('badges_badgebycourse', 'title_fr', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.title_de' db.add_column('badges_badgebycourse', 'title_de', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_en' db.add_column('badges_badgebycourse', 'description_en', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_es' db.add_column('badges_badgebycourse', 'description_es', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_it' db.add_column('badges_badgebycourse', 'description_it', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_pt' db.add_column('badges_badgebycourse', 'description_pt', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_fr' db.add_column('badges_badgebycourse', 'description_fr', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) # Adding field 'BadgeByCourse.description_de' db.add_column('badges_badgebycourse', 'description_de', self.gf('django.db.models.fields.TextField')(null=True, blank=True), keep_default=False) def backwards(self, orm): # Deleting field 'BadgeByCourse.title_en' db.delete_column('badges_badgebycourse', 'title_en') # Deleting field 'BadgeByCourse.title_es' db.delete_column('badges_badgebycourse', 'title_es') # Deleting field 'BadgeByCourse.title_it' db.delete_column('badges_badgebycourse', 'title_it') # Deleting field 'BadgeByCourse.title_pt' db.delete_column('badges_badgebycourse', 'title_pt') # Deleting field 'BadgeByCourse.title_fr' db.delete_column('badges_badgebycourse', 'title_fr') # Deleting field 'BadgeByCourse.title_de' db.delete_column('badges_badgebycourse', 'title_de') # Deleting field 'BadgeByCourse.description_en' db.delete_column('badges_badgebycourse', 'description_en') # Deleting field 'BadgeByCourse.description_es' db.delete_column('badges_badgebycourse', 'description_es') # Deleting field 'BadgeByCourse.description_it' db.delete_column('badges_badgebycourse', 'description_it') # Deleting field 'BadgeByCourse.description_pt' db.delete_column('badges_badgebycourse', 'description_pt') # Deleting field 'BadgeByCourse.description_fr' db.delete_column('badges_badgebycourse', 'description_fr') # Deleting field 'BadgeByCourse.description_de' db.delete_column('badges_badgebycourse', 'description_de') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '254'}) }, 'badges.alignment': { 'Meta': {'object_name': 'Alignment'}, 'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'url': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'badges.award': { 'Meta': {'ordering': "['-modified', '-awarded']", 'unique_together': "(('user', 'badge'),)", 'object_name': 'Award'}, 'awarded': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'badge': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'awards_set'", 'to': "orm['badges.Badge']"}), 'evidence': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'expires': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identity_hash': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'identity_hashed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'identity_salt': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'identity_type': ('django.db.models.fields.CharField', [], {'default': "'email'", 'max_length': '255', 'blank': 'True'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'user_awards'", 'to': "orm['auth.User']"}), 'uuid': ('django.db.models.fields.CharField', [], {'default': "'4d5a6e5e-c0cb-11e4-a589-08002759738a'", 'max_length': '255', 'db_index': 'True'}) }, 'badges.badge': { 'Meta': {'ordering': "['-modified', '-created']", 'object_name': 'Badge'}, 'alignments': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'alignments'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['badges.Alignment']"}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'criteria': ('django.db.models.fields.URLField', [], {'max_length': '255'}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'tags': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'related_name': "u'tags'", 'null': 'True', 'symmetrical': 'False', 'to': "orm['badges.Tag']"}), 'title': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, 'badges.badgebycourse': { 'Meta': {'object_name': 'BadgeByCourse'}, 'color': ('django.db.models.fields.TextField', [], {}), 'course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['courses.Course']"}), 'criteria': ('django.db.models.fields.TextField', [], {}), 'criteria_type': ('django.db.models.fields.IntegerField', [], {}), 'description': ('django.db.models.fields.TextField', [], {'null': 'True'}), 'description_de': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description_en': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description_es': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description_fr': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description_it': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'description_pt': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'note': ('django.db.models.fields.IntegerField', [], {}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'title_de': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title_en': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title_es': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title_fr': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title_it': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'title_pt': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'badges.identity': { 'Meta': {'object_name': 'Identity'}, 'hashed': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'identity_hash': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'salt': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}), 'type': ('django.db.models.fields.CharField', [], {'default': "'email'", 'max_length': '255'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'identity'", 'unique': 'True', 'to': "orm['auth.User']"}) }, 'badges.revocation': { 'Meta': {'object_name': 'Revocation'}, 'award': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'revocations'", 'to': "orm['badges.Award']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'reason': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'badges.tag': { 'Meta': {'object_name': 'Tag'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'courses.course': { 'Meta': {'ordering': "['order']", 'object_name': 'Course'}, 'background': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'certification_available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'certification_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'completion_badge': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'course'", 'null': 'True', 'to': "orm['badges.Badge']"}), 'created_from': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'courses_created_of'", 'null': 'True', 'on_delete': 'models.SET_NULL', 'to': "orm['courses.Course']"}), 'description': ('tinymce.models.HTMLField', [], {}), 'description_de': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'description_en': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'description_es': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'description_fr': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'description_it': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'description_pt': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'ects': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '8'}), 'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'enrollment_method': ('django.db.models.fields.CharField', [], {'default': "'free'", 'max_length': '200'}), 'estimated_effort': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_de': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_en': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_es': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_fr': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_it': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'estimated_effort_pt': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'external_certification_available': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'forum_slug': ('django.db.models.fields.CharField', [], {'max_length': '350', 'null': 'True', 'blank': 'True'}), 'group_max_size': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '50'}), 'has_groups': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'hashtag': ('django.db.models.fields.CharField', [], {'default': "'Hashtag'", 'max_length': '128'}), 'highlight': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'intended_audience': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'is_activity_clonable': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'languages': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['courses.Language']", 'symmetrical': 'False'}), 'learning_goals': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'learning_goals_de': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'learning_goals_en': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'learning_goals_es': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'learning_goals_fr': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'learning_goals_it': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'learning_goals_pt': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'max_mass_emails_month': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '200'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}), 'name_de': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_en': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_es': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_fr': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_it': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'name_pt': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'official_course': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), 'owner': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'courses_as_owner'", 'to': "orm['auth.User']"}), 'promotion_media_content_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}), 'promotion_media_content_type': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}), 'requirements': ('tinymce.models.HTMLField', [], {'blank': 'True'}), 'requirements_de': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'requirements_en': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'requirements_es': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}),<|fim▁hole|> 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '50'}), 'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'static_page': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['courses.StaticPage']", 'unique': 'True', 'null': 'True', 'blank': 'True'}), 'status': ('django.db.models.fields.CharField', [], {'default': "'d'", 'max_length': '10'}), 'students': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'courses_as_student'", 'blank': 'True', 'through': "orm['courses.CourseStudent']", 'to': "orm['auth.User']"}), 'teachers': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'courses_as_teacher'", 'symmetrical': 'False', 'through': "orm['courses.CourseTeacher']", 'to': "orm['auth.User']"}), 'threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '4', 'decimal_places': '2', 'blank': 'True'}), 'thumbnail': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'thumbnail_alt': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}) }, 'courses.coursestudent': { 'Meta': {'object_name': 'CourseStudent'}, 'course': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['courses.Course']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'old_course_status': ('django.db.models.fields.CharField', [], {'default': "'f'", 'max_length': '1'}), 'pos_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0'}), 'pos_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0'}), 'progress': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'rate': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}), 'timestamp': ('django.db.models.fields.BigIntegerField', [], {'null': 'True'}) }, 'courses.courseteacher': { 'Meta': {'ordering': "['order']", 'object_name': 'CourseTeacher'}, 'course': ('adminsortable.fields.SortableForeignKey', [], {'to': "orm['courses.Course']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}), 'teacher': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'courses.language': { 'Meta': {'object_name': 'Language'}, 'abbr': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}) }, 'courses.staticpage': { 'Meta': {'object_name': 'StaticPage'}, 'body': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_de': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_en': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_es': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_fr': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_it': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'body_pt': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_de': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_en': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_es': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_fr': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_it': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'title_pt': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) } } complete_apps = ['badges']<|fim▁end|>
'requirements_fr': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'requirements_it': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}), 'requirements_pt': ('tinymce.models.HTMLField', [], {'null': 'True', 'blank': 'True'}),
<|file_name|>server_decoration.rs<|end_file_name|><|fim▁begin|>//! Support for the KDE Server Decoration Protocol use crate::wayland_sys::server::wl_display as wl_server_display; pub use wlroots_sys::protocols::server_decoration::server::org_kde_kwin_server_decoration_manager::Mode; use wlroots_sys::{ wl_display, wlr_server_decoration_manager, wlr_server_decoration_manager_create, wlr_server_decoration_manager_destroy, wlr_server_decoration_manager_set_default_mode }; #[derive(Debug)] /// Coordinates whether the server should create /// server-side window decorations. pub struct Manager { manager: *mut wlr_server_decoration_manager<|fim▁hole|> let manager_raw = wlr_server_decoration_manager_create(display as *mut wl_display); if !manager_raw.is_null() { Some(Manager { manager: manager_raw }) } else { None } } /// Given a mode, set the server decoration mode pub fn set_default_mode(&mut self, mode: Mode) { wlr_log!(WLR_INFO, "New server decoration mode: {:?}", mode); unsafe { wlr_server_decoration_manager_set_default_mode(self.manager, mode.to_raw()) } } } impl Drop for Manager { fn drop(&mut self) { unsafe { wlr_server_decoration_manager_destroy(self.manager) } } }<|fim▁end|>
} impl Manager { pub(crate) unsafe fn new(display: *mut wl_server_display) -> Option<Self> {
<|file_name|>subscriber.py<|end_file_name|><|fim▁begin|>from collections import defaultdict<|fim▁hole|>import json import os import Pubnub as PB PUB_KEY = os.environ["PUB_KEY"] SUB_KEY = os.environ["SUB_KEY"] SEC_KEY = os.environ["SEC_KEY"] CHANNEL_NAME = os.environ["CHANNEL_NAME"] def frequency_count(text): "determine count of each letter" count = defaultdict(int) for char in text: count[char] += 1 return count def callback(message, channel): "print message, channel, and frequency count to STDOUT" print("python recevied:" + str({ "channel": channel, "message": message, "frequency count":dict(frequency_count(message)), })) def error(message): print({ "error" : message }) if __name__ == "__main__": PB.Pubnub( publish_key = PUB_KEY, subscribe_key = SUB_KEY, secret_key = SEC_KEY, cipher_key = '', ssl_on = False, ).subscribe( channels=CHANNEL_NAME, callback=callback, error=error )<|fim▁end|>
import re
<|file_name|>test_types.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pickle import pytest import pyarrow as pa import pyarrow.types as types MANY_TYPES = [ pa.null(), pa.bool_(), pa.int32(), pa.time32('s'), pa.time64('us'), pa.date32(), pa.timestamp('us'), pa.timestamp('us', tz='UTC'), pa.timestamp('us', tz='Europe/Paris'), pa.float16(), pa.float32(), pa.float64(), pa.decimal128(19, 4), pa.string(), pa.binary(), pa.binary(10), pa.list_(pa.int32()), pa.struct([pa.field('a', pa.int32()), pa.field('b', pa.int8()), pa.field('c', pa.string())]), pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], mode=pa.lib.UnionMode_DENSE), pa.union([pa.field('a', pa.binary(10)), pa.field('b', pa.string())], mode=pa.lib.UnionMode_SPARSE), # XXX Needs array pickling # pa.dictionary(pa.int32(), pa.array(['a', 'b', 'c'])), ] def test_is_boolean(): assert types.is_boolean(pa.bool_()) assert not types.is_boolean(pa.int8()) def test_is_integer(): signed_ints = [pa.int8(), pa.int16(), pa.int32(), pa.int64()] unsigned_ints = [pa.uint8(), pa.uint16(), pa.uint32(), pa.uint64()] for t in signed_ints + unsigned_ints: assert types.is_integer(t) for t in signed_ints: assert types.is_signed_integer(t) assert not types.is_unsigned_integer(t) for t in unsigned_ints: assert types.is_unsigned_integer(t) assert not types.is_signed_integer(t) assert not types.is_integer(pa.float32()) assert not types.is_signed_integer(pa.float32()) def test_is_floating(): for t in [pa.float16(), pa.float32(), pa.float64()]: assert types.is_floating(t) assert not types.is_floating(pa.int32()) def test_is_null(): assert types.is_null(pa.null()) assert not types.is_null(pa.list_(pa.int32())) def test_is_decimal(): assert types.is_decimal(pa.decimal128(19, 4)) assert not types.is_decimal(pa.int32()) def test_is_list(): assert types.is_list(pa.list_(pa.int32())) assert not types.is_list(pa.int32()) def test_is_dictionary(): assert types.is_dictionary( pa.dictionary(pa.int32(), pa.array(['a', 'b', 'c']))) assert not types.is_dictionary(pa.int32()) def test_is_nested_or_struct(): struct_ex = pa.struct([pa.field('a', pa.int32()), pa.field('b', pa.int8()), pa.field('c', pa.string())]) assert types.is_struct(struct_ex) assert not types.is_struct(pa.list_(pa.int32())) assert types.is_nested(struct_ex) assert types.is_nested(pa.list_(pa.int32())) assert not types.is_nested(pa.int32()) def test_is_union(): for mode in [pa.lib.UnionMode_SPARSE, pa.lib.UnionMode_DENSE]: assert types.is_union(pa.union([pa.field('a', pa.int32()), pa.field('b', pa.int8()), pa.field('c', pa.string())], mode=mode)) assert not types.is_union(pa.list_(pa.int32())) # TODO(wesm): is_map, once implemented def test_is_binary_string(): assert types.is_binary(pa.binary()) assert not types.is_binary(pa.string()) assert types.is_string(pa.string()) assert types.is_unicode(pa.string()) assert not types.is_string(pa.binary()) assert types.is_fixed_size_binary(pa.binary(5)) assert not types.is_fixed_size_binary(pa.binary()) def test_is_temporal_date_time_timestamp(): date_types = [pa.date32(), pa.date64()] time_types = [pa.time32('s'), pa.time64('ns')] timestamp_types = [pa.timestamp('ms')] for case in date_types + time_types + timestamp_types: assert types.is_temporal(case) for case in date_types: assert types.is_date(case) assert not types.is_time(case) assert not types.is_timestamp(case) for case in time_types: assert types.is_time(case) assert not types.is_date(case) assert not types.is_timestamp(case) for case in timestamp_types: assert types.is_timestamp(case) assert not types.is_date(case) assert not types.is_time(case) assert not types.is_temporal(pa.int32()) def test_timestamp_type(): # See ARROW-1683 assert isinstance(pa.timestamp('ns'), pa.TimestampType) def test_union_type(): def check_fields(ty, fields): assert ty.num_children == len(fields) assert [ty[i] for i in range(ty.num_children)] == fields fields = [pa.field('x', pa.list_(pa.int32())), pa.field('y', pa.binary())] for mode in ('sparse', pa.lib.UnionMode_SPARSE): ty = pa.union(fields, mode=mode) assert ty.mode == 'sparse' check_fields(ty, fields) for mode in ('dense', pa.lib.UnionMode_DENSE): ty = pa.union(fields, mode=mode) assert ty.mode == 'dense' check_fields(ty, fields) for mode in ('unknown', 2): with pytest.raises(ValueError, match='Invalid union mode'): pa.union(fields, mode=mode) def test_types_hashable(): in_dict = {} for i, type_ in enumerate(MANY_TYPES): assert hash(type_) == hash(type_) in_dict[type_] = i assert in_dict[type_] == i assert len(in_dict) == len(MANY_TYPES) def test_types_picklable(): for ty in MANY_TYPES: data = pickle.dumps(ty) assert pickle.loads(data) == ty @pytest.mark.parametrize('t,check_func', [ (pa.date32(), types.is_date32), (pa.date64(), types.is_date64), (pa.time32('s'), types.is_time32), (pa.time64('ns'), types.is_time64), (pa.int8(), types.is_int8), (pa.int16(), types.is_int16), (pa.int32(), types.is_int32), (pa.int64(), types.is_int64), (pa.uint8(), types.is_uint8), (pa.uint16(), types.is_uint16), (pa.uint32(), types.is_uint32), (pa.uint64(), types.is_uint64), (pa.float16(), types.is_float16), (pa.float32(), types.is_float32), (pa.float64(), types.is_float64) ]) def test_exact_primitive_types(t, check_func): assert check_func(t) def test_fixed_size_binary_byte_width():<|fim▁hole|> def test_decimal_byte_width(): ty = pa.decimal128(19, 4) assert ty.byte_width == 16<|fim▁end|>
ty = pa.binary(5) assert ty.byte_width == 5
<|file_name|>tfont.py<|end_file_name|><|fim▁begin|># $Id: tfont.py,v 1.2 2003/09/14 04:31:39 riq Exp $ # # Tenes Empanadas Graciela # Copyright 2000,2003 Ricardo Quesada ([email protected])<|fim▁hole|># import pygame if not pygame.font.get_init(): pygame.font.init() TFont = { 'helvetica 8' : pygame.font.SysFont('helvetica',8), 'helvetica 10' : pygame.font.SysFont('helvetica',10), 'helvetica 12' : pygame.font.SysFont('helvetica',12), 'helvetica 16' : pygame.font.SysFont('helvetica',16,0), 'helvetica 16b' : pygame.font.SysFont('helvetica',16,1), 'helvetica 20' : pygame.font.SysFont('helvetica',20,0), 'helvetica 20b' : pygame.font.SysFont('helvetica',20,1) }<|fim▁end|>
<|file_name|>test_template.py<|end_file_name|><|fim▁begin|>import pytest import gen.template from gen.template import (For, Replacement, Switch, Tokenizer, UnsetParameter, parse_str) just_text = "foo" more_complex_text = "foo {" def get_tokens(str): return Tokenizer(str).tokens def test_lex(): assert(get_tokens("foo") == [("blob", "foo"), ("eof", None)]) assert(get_tokens("{") == [('blob', '{'), ('eof', None)]) assert(get_tokens("{#") == [('blob', '{'), ('blob', '#'), ('eof', None)]) assert(get_tokens("{ foo ") == [ ('blob', '{'), ('blob', ' foo '), ('eof', None)]) assert(get_tokens("{ foo {{{{ {{{{{ ") == [('blob', '{'), ('blob', ' foo '), ( 'blob', '{{'), ('blob', ' '), ('blob', '{{'), ('blob', '{'), ('blob', ' '), ('eof', None)]) assert(get_tokens("{{ test }}") == [ ('replacement', ('test', None)), ('eof', None)]) assert(get_tokens("{{ test | foo }}") == [ ('replacement', ('test', 'foo')), ('eof', None)]) assert(get_tokens(" {{ test }}") == [ ('blob', ' '), ('replacement', ('test', None)), ('eof', None)]) assert(get_tokens("{{ test }}}}") == [ ('replacement', ('test', None)), ('blob', '}}'), ('eof', None)]) assert(get_tokens('{% switch foo %}{% case "as\\"df" %}foobar{% endswitch %}}}') == [ ('switch', 'foo'), ('case', 'as"df'), ('blob', 'foobar'), ('endswitch', None), ('blob', '}}'), ('eof', None)]) assert(get_tokens('{% switch foo %} \n \r {% case "as\\"df" %}foobar{% endswitch %}}}') == [ ('switch', 'foo'), ('blob', ' \n \r '), ('case', 'as"df'), ('blob', 'foobar'), ('endswitch', None), ('blob', '}}'), ('eof', None)]) assert(get_tokens("a{% switch foo %}{% case \"test\" %}{{ a | baz }}b{{ a | bar }}{% endswitch %}c{{ c | bar }}{{ a | foo }}") == [ # noqa ('blob', 'a'), ('switch', 'foo'), ('case', 'test'), ('replacement', ('a', 'baz')), ('blob', 'b'), ('replacement', ('a', 'bar')), ('endswitch', None), ('blob', 'c'), ('replacement', ('c', 'bar')), ('replacement', ('a', 'foo')), ('eof', None) ]) assert(get_tokens("{% for foo in bar %}{{ foo }}{% endfor %}") == [ ('for', ('foo', 'bar')), ('replacement', ('foo', None)), ('endfor', None), ('eof', None)]) with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test |}}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test| }}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test | }}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test }}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{test}}") with pytest.raises(gen.template.SyntaxError): get_tokens("{{ test}}") def test_parse(): assert(parse_str("a").ast == ["a"]) assert(parse_str("{{ a }}").ast == [Replacement(("a", None))]) assert(parse_str("a {{ a | foo }}{{ b }} c {{ d | bar }}").ast == [ "a ", Replacement(("a", 'foo')), Replacement(("b", None)), " c ", Replacement(("d", 'bar')) ]) assert(parse_str('{% switch foo %}{% case "as\\"df" %}foobar{% endswitch %}}}').ast == [Switch("foo", {'as"df': ["foobar"]}), '}}']) assert(parse_str('{{ a }}b{{ c }}{% switch foo %} \n {% case "as\\"df" %}foobar{% endswitch %}}}').ast == [ Replacement(("a", None)), "b", Replacement(("c", None)), Switch("foo", {'as"df': ["foobar"]}), "}}" ]) # TODO(cmaloney): Add parse syntax error tests assert parse_str("{% for foo in bar %}{{ foo }}{% endfor %}").ast == [For("foo", "bar", [Replacement('foo')])] def test_get_variables(): assert(parse_str("a").get_scoped_arguments() == {'variables': set(), 'sub_scopes': dict()}) assert(parse_str("{{ a }}").get_scoped_arguments() == {'variables': {"a"}, 'sub_scopes': dict()}) assert(parse_str("{{ a | foo }}").get_scoped_arguments() == {'variables': {"a"}, 'sub_scopes': dict()}) assert(parse_str("a{{ a }}b{{ c }}").get_scoped_arguments() == {'variables': {"a", "c"}, 'sub_scopes': dict()}) assert(parse_str("a{{ a }}b{{ a }}c{{ c | baz }}").get_scoped_arguments() == {'variables': {"a", "c"}, 'sub_scopes': dict()}) assert(parse_str("a{{ a }}b{{ a | bar }}c{{ c }}").get_scoped_arguments() == {'variables': {"a", "c"}, 'sub_scopes': dict()}) assert(parse_str("{{ a }}{% switch b %}{% case \"c\" %}{{ d }}{% endswitch %}{{ e }}").get_scoped_arguments() == { 'variables': {'a', 'e'}, 'sub_scopes': { 'b': {<|fim▁hole|> } } }) assert (parse_str("{% for foo in bar %}{{ foo }}{{ bar }}{{ baz }}{% endfor %}").get_scoped_arguments() == {'variables': {'bar', 'baz'}, 'sub_scopes': dict()}) # TODO(cmaloney): Disallow reusing a for new variable as a general variable. assert (parse_str("{% for foo in bar %}{{ foo }}{{ bar }}{{ baz }}{% endfor %}{{ foo }}").get_scoped_arguments() == {'variables': {'foo', 'bar', 'baz'}, 'sub_scopes': dict()}) def test_get_filters(): assert(parse_str("{{ a }}").get_filters() == set()) assert(parse_str("{{ a | foo }}").get_filters() == {"foo"}) assert(parse_str( "a{{ a | baz }}b{{ a | bar }}c{{ c | bar }}").get_filters() == {"baz", "bar"}) assert(parse_str("a{% switch foo %}{% case \"test\" %}{{ a | baz }}b{{ a | bar }}{% endswitch %}c{{ c | bar }}{{ a | foo }}").get_filters() == {"foo", "baz", "bar"}) # noqa assert parse_str("{% for foo in bar %}{{ foo | bang }}{% endfor %}").get_filters() == {'bang'} def test_render(): assert(parse_str("a").render({}) == "a") assert(parse_str("{{ a }}a{{ b }}").render({"a": "1", "b": "2"}) == "1a2") assert(parse_str("{{ a | foo }}a{{ b }}").render( {"a": "1", "b": "2"}, {'foo': lambda x: x + 'foo'} ) == "1fooa2") with pytest.raises(UnsetParameter): parse_str("{{ a }}a{{ b }}").render({"a": "1"}) with pytest.raises(UnsetParameter): parse_str("{{ a }}").render({"c": "1"}) with pytest.raises(UnsetParameter): parse_str("{{ a | foo }}").render({"a": "1"}) assert parse_str("{% for a in b %}{{ a }}{% endfor %}").render({"b": ['a', 'test']}) == "atest" assert (parse_str("{% for a in b %}{{ a }}{% endfor %}else{{ a }}").render({"b": ['b', 't', 'c'], "a": "foo"}) == "btcelsefoo") with pytest.raises(UnsetParameter): parse_str("{% for a in b %}{{ a }}{% endfor %}else{{ a }}").render({"b": ['b', 't', 'c']})<|fim▁end|>
'c': { 'variables': {'d'}, 'sub_scopes': {} }
<|file_name|>cpu.rs<|end_file_name|><|fim▁begin|>use opcode::Opcode; use keypad::Keypad; use display::Display; use util; pub struct Cpu { pub memory: [u8; 4096], pub v: [u8; 16], pub i: usize, pub pc: usize, pub gfx: [u8; 64 * 32], pub delay_timer: u8, pub sound_timer: u8, pub stack: [u16; 16], pub sp: usize, pub keypad: Keypad, pub display: Display, } fn not_implemented(op: usize, pc: usize) { println!("Not implemented:: op: {:x}, pc: {:x}", op, pc); } impl Cpu { pub fn new() -> Cpu { let mut cpu: Cpu = Cpu { v: [0; 16], gfx: [0; 64 * 32], delay_timer: 0, sound_timer: 0, stack: [0; 16], pc: 0x200, // Program counter starts at 0x200 i: 0, // Reset index register sp: 0, // Reset stack pointer memory: [0; 4096], display: Display::new(), keypad: Keypad::new(), }; // load in Util::fontset for i in 0..80 { cpu.memory[i] = util::FONTSET[i]; } return cpu; } pub fn emulate_cycle(&mut self) { // fetch opcode let opcode_bits: u16 = (self.memory[self.pc as usize] as u16) << 8 | self.memory[(self.pc + 1) as usize] as u16; let opcode: Opcode = Opcode::new(opcode_bits); util::debug_cycle(self, &opcode); self.pc += 2; self.execute(&opcode); // ?? // self.pc += 2; // update timers if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { if self.sound_timer == 0 { println!("BUZZ"); } self.sound_timer -= 1; }<|fim▁hole|> pub fn execute(&mut self, opcode: &Opcode) { match opcode.code & 0xf000 { 0x0000 => self.execute_clear_return(opcode), // 0nnn - SYS nnn 0x1000 => op_1xxx(self, opcode), 0x2000 => op_2xxx(self, opcode), 0x3000 => op_3xxx(self, opcode), 0x4000 => op_4xxx(self, opcode), 0x5000 => op_5xxx(self, opcode), 0x6000 => op_6xxx(self, opcode), 0x7000 => op_7xxx(self, opcode), 0x8000 => op_8xxx(self, opcode), 0x9000 => op_9xxx(self, opcode), 0xA000 => op_Axxx(self, opcode), 0xB000 => op_Bxxx(self, opcode), 0xC000 => op_Cxxx(self, opcode), 0xD000 => op_Dxxx(self, opcode), 0xE000 => op_Exxx(self, opcode), 0xF000 => op_Fxxx(self, opcode), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn execute_clear_return(&mut self, opcode: &Opcode) { match opcode.code { 0x00E0 => { // CLS // clear screen self.display.clear(); } 0x00EE => self.return_from_subroutine(), _ => not_implemented(opcode.code as usize, self.pc), } } pub fn return_from_subroutine(&mut self) { // 00EE - RTS // Return from subroutine. Pop the current value in the stack pointer // off of the stack, and set the program counter to the value popped. // self.registers['sp'] -= 1 // self.registers['pc'] = self.memory[self.registers['sp']] << 8 // self.registers['sp'] -= 1 // self.registers['pc'] += self.memory[self.registers['sp']] self.sp -= 1; } // 0x0: self.clear_return, # 0nnn - SYS nnn // 0x1: self.jump_to_address, # 1nnn - JUMP nnn // 0x2: self.jump_to_subroutine, # 2nnn - CALL nnn // 0x3: self.skip_if_reg_equal_val, # 3snn - SKE Vs, nn // 0x4: self.skip_if_reg_not_equal_val, # 4snn - SKNE Vs, nn // 0x5: self.skip_if_reg_equal_reg, # 5st0 - SKE Vs, Vt // 0x6: self.move_value_to_reg, # 6snn - LOAD Vs, nn // 0x7: self.add_value_to_reg, # 7snn - ADD Vs, nn // 0x8: self.execute_logical_instruction, # see subfunctions below // 0x9: self.skip_if_reg_not_equal_reg, # 9st0 - SKNE Vs, Vt // 0xA: self.load_index_reg_with_value, # Annn - LOAD I, nnn // 0xB: self.jump_to_index_plus_value, # Bnnn - JUMP [I] + nnn // 0xC: self.generate_random_number, # Ctnn - RAND Vt, nn // 0xD: self.draw_sprite, # Dstn - DRAW Vs, Vy, n // 0xE: self.keyboard_routines, # see subfunctions below // 0xF: self.misc_routines, # see subfunctions below }<|fim▁end|>
}
<|file_name|>time.go<|end_file_name|><|fim▁begin|>package null import ( "database/sql/driver" "encoding/json" "fmt" "reflect" "time" ) // Time is a nullable time.Time. It supports SQL and JSON serialization. // It will marshal to null if null. type Time struct { Time time.Time Valid bool } // Scan implements the Scanner interface. func (t *Time) Scan(value interface{}) error { var err error switch x := value.(type) { case time.Time: t.Time = x case nil: t.Valid = false return nil default: err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value) } t.Valid = err == nil return err } // Value implements the driver Valuer interface. func (t Time) Value() (driver.Value, error) { if !t.Valid { return nil, nil } return t.Time, nil } // NewTime creates a new Time. func NewTime(t time.Time, valid bool) Time { return Time{ Time: t, Valid: valid, } } // TimeFrom creates a new Time that will always be valid. func TimeFrom(t time.Time) Time { return NewTime(t, true) } // TimeFromPtr creates a new Time that will be null if t is nil. func TimeFromPtr(t *time.Time) Time { if t == nil { return NewTime(time.Time{}, false) } return NewTime(*t, true) } // ValueOrZero returns the inner value if valid, otherwise zero. func (t Time) ValueOrZero() time.Time { if !t.Valid { return time.Time{} } return t.Time<|fim▁hole|>// MarshalJSON implements json.Marshaler. // It will encode null if this time is null. func (t Time) MarshalJSON() ([]byte, error) { if !t.Valid { return []byte("null"), nil } return t.Time.MarshalJSON() } // UnmarshalJSON implements json.Unmarshaler. // It supports string, object (e.g. pq.NullTime and friends) // and null input. func (t *Time) UnmarshalJSON(data []byte) error { var err error var v interface{} if err = json.Unmarshal(data, &v); err != nil { return err } switch x := v.(type) { case string: err = t.Time.UnmarshalJSON(data) case map[string]interface{}: ti, tiOK := x["Time"].(string) valid, validOK := x["Valid"].(bool) if !tiOK || !validOK { return fmt.Errorf(`json: unmarshalling object into Go value of type null.Time requires key "Time" to be of type string and key "Valid" to be of type bool; found %T and %T, respectively`, x["Time"], x["Valid"]) } err = t.Time.UnmarshalText([]byte(ti)) t.Valid = valid return err case nil: t.Valid = false return nil default: err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.Time", reflect.TypeOf(v).Name()) } t.Valid = err == nil return err } func (t Time) MarshalText() ([]byte, error) { if !t.Valid { return []byte("null"), nil } return t.Time.MarshalText() } func (t *Time) UnmarshalText(text []byte) error { str := string(text) if str == "" || str == "null" { t.Valid = false return nil } if err := t.Time.UnmarshalText(text); err != nil { return err } t.Valid = true return nil } // SetValid changes this Time's value and sets it to be non-null. func (t *Time) SetValid(v time.Time) { t.Time = v t.Valid = true } // Ptr returns a pointer to this Time's value, or a nil pointer if this Time is null. func (t Time) Ptr() *time.Time { if !t.Valid { return nil } return &t.Time } // IsZero returns true for invalid Times, hopefully for future omitempty support. // A non-null Time with a zero value will not be considered zero. func (t Time) IsZero() bool { return !t.Valid }<|fim▁end|>
}
<|file_name|>dep_info.rs<|end_file_name|><|fim▁begin|>use cargotest::support::{basic_bin_manifest, execs, main_file, project}; use filetime::FileTime; use hamcrest::{assert_that, existing_file}; #[test] fn build_dep_info() { let p = project("foo") .file("Cargo.toml", &basic_bin_manifest("foo")) .file("src/foo.rs", &main_file(r#""i am foo""#, &[])) .build(); assert_that(p.cargo("build"), execs().with_status(0)); let depinfo_bin_path = &p.bin("foo").with_extension("d"); assert_that(depinfo_bin_path, existing_file()); } #[test] fn build_dep_info_lib() { let p = project("foo") .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [[example]] name = "ex" crate-type = ["lib"] "#, ) .file("build.rs", "fn main() {}") .file("src/lib.rs", "") .file("examples/ex.rs", "") .build(); assert_that(p.cargo("build").arg("--example=ex"), execs().with_status(0)); assert_that( &p.example_lib("ex", "lib").with_extension("d"), existing_file(), ); } #[test] fn build_dep_info_rlib() { let p = project("foo") .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1"<|fim▁hole|> name = "ex" crate-type = ["rlib"] "#, ) .file("src/lib.rs", "") .file("examples/ex.rs", "") .build(); assert_that(p.cargo("build").arg("--example=ex"), execs().with_status(0)); assert_that( &p.example_lib("ex", "rlib").with_extension("d"), existing_file(), ); } #[test] fn build_dep_info_dylib() { let p = project("foo") .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] [[example]] name = "ex" crate-type = ["dylib"] "#, ) .file("src/lib.rs", "") .file("examples/ex.rs", "") .build(); assert_that(p.cargo("build").arg("--example=ex"), execs().with_status(0)); assert_that( &p.example_lib("ex", "dylib").with_extension("d"), existing_file(), ); } #[test] fn no_rewrite_if_no_change() { let p = project("foo") .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" authors = [] "#, ) .file("src/lib.rs", "") .build(); assert_that(p.cargo("build"), execs().with_status(0)); let dep_info = p.root().join("target/debug/libfoo.d"); let metadata1 = dep_info.metadata().unwrap(); assert_that(p.cargo("build"), execs().with_status(0)); let metadata2 = dep_info.metadata().unwrap(); assert_eq!( FileTime::from_last_modification_time(&metadata1), FileTime::from_last_modification_time(&metadata2), ); }<|fim▁end|>
authors = [] [[example]]
<|file_name|>ImagePhotoSizeSelectActual.js<|end_file_name|><|fim▁begin|>module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/image/photo-size-select-actual": require('material-ui/svg-icons/image/photo-size-select-actual')<|fim▁hole|> } }, name: "ImagePhotoSizeSelectActual", ports: { input: {}, output: { component: { title: "ImagePhotoSizeSelectActual", type: "Component" } } } }<|fim▁end|>
<|file_name|>openstack.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright: (c) 2014, Hewlett-Packard Development Company, L.P. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Standard openstack documentation fragment DOCUMENTATION = r''' options: cloud: description: - Named cloud or cloud config to operate against. If I(cloud) is a string, it references a named cloud config as defined in an OpenStack clouds.yaml file. Provides default values for I(auth) and I(auth_type). This parameter is not needed if I(auth) is provided or if OpenStack OS_* environment variables are present. If I(cloud) is a dict, it contains a complete cloud configuration like would be in a section of clouds.yaml. type: raw auth: description: - Dictionary containing auth information as needed by the cloud's auth plugin strategy. For the default I(password) plugin, this would contain I(auth_url), I(username), I(password), I(project_name) and any information about domains (for example, I(os_user_domain_name) or I(os_project_domain_name)) if the cloud supports them. For other plugins, this param will need to contain whatever parameters that auth plugin requires. This parameter is not needed if a named cloud is provided or OpenStack OS_* environment variables are present. type: dict auth_type: description: - Name of the auth plugin to use. If the cloud uses something other than password authentication, the name of the plugin should be indicated here and the contents of the I(auth) parameter should be updated accordingly. type: str region_name: description: - Name of the region. type: str wait: description: - Should ansible wait until the requested resource is complete. type: bool default: yes timeout: description: - How long should ansible wait for the requested resource. type: int default: 180 api_timeout: description: - How long should the socket layer wait before timing out for API calls. If this is omitted, nothing will be passed to the requests library. type: int validate_certs: description: - Whether or not SSL API requests should be verified. - Before Ansible 2.3 this defaulted to C(yes). type: bool default: no aliases: [ verify ] ca_cert: description: - A path to a CA Cert bundle that can be used as part of verifying SSL API requests. type: str aliases: [ cacert ] client_cert: description: - A path to a client certificate to use as part of the SSL transaction. type: str aliases: [ cert ] client_key: description: - A path to a client key to use as part of the SSL transaction. type: str aliases: [ key ] interface: description: - Endpoint URL type to fetch from the service catalog.<|fim▁hole|> default: public aliases: [ endpoint_type ] version_added: "2.3" requirements: - python >= 2.7 - openstacksdk >= 0.12.0 notes: - The standard OpenStack environment variables, such as C(OS_USERNAME) may be used instead of providing explicit values. - Auth information is driven by openstacksdk, which means that values can come from a yaml config file in /etc/ansible/openstack.yaml, /etc/openstack/clouds.yaml or ~/.config/openstack/clouds.yaml, then from standard environment variables, then finally by explicit parameters in plays. More information can be found at U(https://docs.openstack.org/openstacksdk/) '''<|fim▁end|>
type: str choices: [ admin, internal, public ]
<|file_name|>test_qgssettings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Test the QgsSettings class Run with: ctest -V -R PyQgsSettings .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ import os import tempfile from qgis.core import QgsSettings, QgsTolerance, QgsMapLayerProxyModel from qgis.testing import start_app, unittest from qgis.PyQt.QtCore import QSettings, QVariant from pathlib import Path __author__ = 'Alessandro Pasotti' __date__ = '02/02/2017' __copyright__ = 'Copyright 2017, The QGIS Project' start_app() class TestQgsSettings(unittest.TestCase): cnt = 0 def setUp(self): self.cnt += 1 h, path = tempfile.mkstemp('.ini') Path(path).touch() assert QgsSettings.setGlobalSettingsPath(path) self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt) self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) self.globalsettings.sync() assert os.path.exists(self.globalsettings.fileName()) def tearDown(self): settings_file = self.settings.fileName() settings_default_file = self.settings.globalSettingsPath() del(self.settings) try: os.unlink(settings_file) except: pass try: os.unlink(settings_default_file) except: pass def addToDefaults(self, key, value): self.globalsettings.setValue(key, value) self.globalsettings.sync() def addArrayToDefaults(self, prefix, key, values): defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) # NOQA self.globalsettings.beginWriteArray(prefix) i = 0 for v in values: self.globalsettings.setArrayIndex(i) self.globalsettings.setValue(key, v) i += 1 self.globalsettings.endArray() self.globalsettings.sync() def addGroupToDefaults(self, prefix, kvp): defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) # NOQA self.globalsettings.beginGroup(prefix) for k, v in kvp.items(): self.globalsettings.setValue(k, v) self.globalsettings.endGroup() self.globalsettings.sync() def test_basic_functionality(self): self.assertEqual(self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist') self.settings.setValue('testqgissettings/name', 'qgisrocks') self.settings.sync() self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks') def test_defaults(self): self.assertIsNone(self.settings.value('testqgissettings/name')) self.addToDefaults('testqgissettings/name', 'qgisrocks') self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks') def test_allkeys(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/name', 'qgisrocks') self.addToDefaults('testqgissettings/name2', 'qgisrocks2')<|fim▁hole|> self.settings.setValue('nepoti/eman', 'osaple') self.assertEqual(3, len(self.settings.allKeys())) self.assertIn('testqgissettings/name', self.settings.allKeys()) self.assertIn('nepoti/eman', self.settings.allKeys()) self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name')) self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2')) self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name')) self.assertEqual('osaple', self.settings.value('nepoti/eman')) self.assertEqual(3, len(self.settings.allKeys())) self.assertEqual(2, len(self.globalsettings.allKeys())) def test_precedence_simple(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1') self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1') self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1') def test_precedence_group(self): """Test if user can override a group value""" self.assertEqual(self.settings.allKeys(), []) self.addGroupToDefaults('connections-xyz', { 'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png', 'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png', }) self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override edit self.settings.beginGroup('connections-xyz') self.settings.setValue('OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: the global value will be resumed!!! self.settings.beginGroup('connections-xyz') self.settings.remove('OSM') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: store a blank! self.settings.beginGroup('connections-xyz') self.settings.setValue('OSM', '') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), '') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: store a None: will resume the global setting! self.settings.beginGroup('connections-xyz') self.settings.setValue('OSM', None) self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() def test_uft8(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1') self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2') self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1') def test_groups(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1') self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2') self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3') self.addToDefaults('testqgissettings/name', 'qgisrocks') self.settings.beginGroup('testqgissettings') self.assertEqual(self.settings.group(), 'testqgissettings') self.assertEqual(['names'], self.settings.childGroups()) self.settings.setValue('surnames/name1', 'qgisrocks-1') self.assertEqual(['surnames', 'names'], self.settings.childGroups()) self.settings.setValue('names/name1', 'qgisrocks-1') self.assertEqual('qgisrocks-1', self.settings.value('names/name1')) self.settings.endGroup() self.assertEqual(self.settings.group(), '') self.settings.beginGroup('testqgissettings/names') self.assertEqual(self.settings.group(), 'testqgissettings/names') self.settings.setValue('name4', 'qgisrocks-4') keys = sorted(self.settings.childKeys()) self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4']) self.settings.endGroup() self.assertEqual(self.settings.group(), '') self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1')) self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4')) def test_global_groups(self): self.assertEqual(self.settings.allKeys(), []) self.assertEqual(self.globalsettings.allKeys(), []) self.addToDefaults('testqgissettings/foo/first', 'qgis') self.addToDefaults('testqgissettings/foo/last', 'rocks') self.settings.beginGroup('testqgissettings') self.assertEqual(self.settings.group(), 'testqgissettings') self.assertEqual(['foo'], self.settings.childGroups()) self.assertEqual(['foo'], self.settings.globalChildGroups()) self.settings.endGroup() self.assertEqual(self.settings.group(), '') self.settings.setValue('testqgissettings/bar/first', 'qgis') self.settings.setValue('testqgissettings/bar/last', 'rocks') self.settings.beginGroup('testqgissettings') self.assertEqual(sorted(['bar', 'foo']), sorted(self.settings.childGroups())) self.assertEqual(['foo'], self.settings.globalChildGroups()) self.settings.endGroup() self.globalsettings.remove('testqgissettings/foo') self.settings.beginGroup('testqgissettings') self.assertEqual(['bar'], self.settings.childGroups()) self.assertEqual([], self.settings.globalChildGroups()) self.settings.endGroup() def test_group_section(self): # Test group by using Section self.settings.beginGroup('firstgroup', section=QgsSettings.Core) self.assertEqual(self.settings.group(), 'core/firstgroup') self.assertEqual([], self.settings.childGroups()) self.settings.setValue('key', 'value') self.settings.setValue('key2/subkey1', 'subvalue1') self.settings.setValue('key2/subkey2', 'subvalue2') self.settings.setValue('key3', 'value3') self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'], self.settings.allKeys()) self.assertEqual(['key', 'key3'], self.settings.childKeys()) self.assertEqual(['key2'], self.settings.childGroups()) self.settings.endGroup() self.assertEqual(self.settings.group(), '') # Set value by writing the group manually self.settings.setValue('firstgroup/key4', 'value4', section=QgsSettings.Core) # Checking the value that have been set self.assertEqual(self.settings.value('firstgroup/key', section=QgsSettings.Core), 'value') self.assertEqual(self.settings.value('firstgroup/key2/subkey1', section=QgsSettings.Core), 'subvalue1') self.assertEqual(self.settings.value('firstgroup/key2/subkey2', section=QgsSettings.Core), 'subvalue2') self.assertEqual(self.settings.value('firstgroup/key3', section=QgsSettings.Core), 'value3') self.assertEqual(self.settings.value('firstgroup/key4', section=QgsSettings.Core), 'value4') # Clean up firstgroup self.settings.remove('firstgroup', section=QgsSettings.Core) def test_array(self): self.assertEqual(self.settings.allKeys(), []) self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size']) self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size']) self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings')) self.globalsettings.endArray() self.assertEqual(3, self.settings.beginReadArray('testqgissettings')) values = [] for i in range(3): self.settings.setArrayIndex(i) values.append(self.settings.value("key")) self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) def test_array_overrides(self): """Test if an array completely shadows the global one""" self.assertEqual(self.settings.allKeys(), []) self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) self.assertEqual(self.settings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size']) self.assertEqual(self.globalsettings.allKeys(), ['testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size']) self.assertEqual(3, self.globalsettings.beginReadArray('testqgissettings')) self.globalsettings.endArray() self.assertEqual(3, self.settings.beginReadArray('testqgissettings')) # Now override! self.settings.beginWriteArray('testqgissettings') self.settings.setArrayIndex(0) self.settings.setValue('key', 'myqgisrocksmore1') self.settings.setArrayIndex(1) self.settings.setValue('key', 'myqgisrocksmore2') self.settings.endArray() # Check it! self.assertEqual(2, self.settings.beginReadArray('testqgissettings')) values = [] for i in range(2): self.settings.setArrayIndex(i) values.append(self.settings.value("key")) self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2']) def test_section_getters_setters(self): self.assertEqual(self.settings.allKeys(), []) self.settings.setValue('key1', 'core1', section=QgsSettings.Core) self.settings.setValue('key2', 'core2', section=QgsSettings.Core) self.settings.setValue('key1', 'server1', section=QgsSettings.Server) self.settings.setValue('key2', 'server2', section=QgsSettings.Server) self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui) self.settings.setValue('key2', 'gui2', QgsSettings.Gui) self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins) self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins) self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc) self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc) self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth) self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth) self.settings.setValue('key1', 'app1', section=QgsSettings.App) self.settings.setValue('key2', 'app2', section=QgsSettings.App) self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers) self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers) # This is an overwrite of previous setting and it is intentional self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth) self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth) # Test that the values are namespaced self.assertEqual(self.settings.value('core/key1'), 'core1') self.assertEqual(self.settings.value('core/key2'), 'core2') self.assertEqual(self.settings.value('server/key1'), 'server1') self.assertEqual(self.settings.value('server/key2'), 'server2') self.assertEqual(self.settings.value('gui/key1'), 'gui1') self.assertEqual(self.settings.value('gui/key2'), 'gui2') self.assertEqual(self.settings.value('plugins/key1'), 'plugins1') self.assertEqual(self.settings.value('plugins/key2'), 'plugins2') self.assertEqual(self.settings.value('misc/key1'), 'misc1') self.assertEqual(self.settings.value('misc/key2'), 'misc2') # Test getters self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Core), 'core1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Core), 'core2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Server), 'server1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Server), 'server2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.App), 'app1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.App), 'app2') self.assertEqual(self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1') self.assertEqual(self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2') # Test default values on Section getter self.assertEqual(self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist') def test_contains(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/name', 'qgisrocks1') self.addToDefaults('testqgissettings/name2', 'qgisrocks2') self.assertTrue(self.settings.contains('testqgissettings/name')) self.assertTrue(self.settings.contains('testqgissettings/name2')) self.settings.setValue('testqgissettings/name3', 'qgisrocks3') self.assertTrue(self.settings.contains('testqgissettings/name3')) def test_remove(self): self.settings.setValue('testQgisSettings/temp', True) self.assertEqual(self.settings.value('testQgisSettings/temp'), True) self.settings.remove('testQgisSettings/temp') self.assertEqual(self.settings.value('testqQgisSettings/temp'), None) # Test remove by using Section self.settings.setValue('testQgisSettings/tempSection', True, section=QgsSettings.Core) self.assertEqual(self.settings.value('testQgisSettings/tempSection', section=QgsSettings.Core), True) self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core) self.assertEqual(self.settings.value('testqQgisSettings/temp', section=QgsSettings.Core), None) def test_enumValue(self): self.settings.setValue('enum', 'LayerUnits') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits) self.settings.setValue('enum', 'dummy_setting') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels) self.assertEqual(type(self.settings.enumValue('enum', QgsTolerance.Pixels)), QgsTolerance.UnitType) def test_setEnumValue(self): self.settings.setValue('enum', 'LayerUnits') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits) self.settings.setEnumValue('enum', QgsTolerance.Pixels) self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels) def test_flagValue(self): pointAndLine = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer) pointAndPolygon = QgsMapLayerProxyModel.Filters(QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.PolygonLayer) self.settings.setValue('flag', 'PointLayer|PolygonLayer') self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndPolygon) self.settings.setValue('flag', 'dummy_setting') self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndLine) self.assertEqual(type(self.settings.flagValue('enum', pointAndLine)), QgsMapLayerProxyModel.Filters) def test_overwriteDefaultValues(self): """Test that unchanged values are not stored""" self.globalsettings.setValue('a_value_with_default', 'a value') self.globalsettings.setValue('an_invalid_value', QVariant()) self.assertEqual(self.settings.value('a_value_with_default'), 'a value') self.assertEqual(self.settings.value('an_invalid_value'), QVariant()) # Now, set them with the same current value self.settings.setValue('a_value_with_default', 'a value') self.settings.setValue('an_invalid_value', QVariant()) # Check pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat) self.assertFalse('a_value_with_default' in pure_settings.allKeys()) self.assertFalse('an_invalid_value' in pure_settings.allKeys()) # Set a changed value self.settings.setValue('a_value_with_default', 'a new value') self.settings.setValue('an_invalid_value', 'valid value') # Check self.assertTrue('a_value_with_default' in pure_settings.allKeys()) self.assertTrue('an_invalid_value' in pure_settings.allKeys()) self.assertEqual(self.settings.value('a_value_with_default'), 'a new value') self.assertEqual(self.settings.value('an_invalid_value'), 'valid value') # Re-set to original values self.settings.setValue('a_value_with_default', 'a value') self.settings.setValue('an_invalid_value', QVariant()) self.assertEqual(self.settings.value('a_value_with_default'), 'a value') self.assertEqual(self.settings.value('an_invalid_value'), QVariant()) # Check if they are gone pure_settings = QSettings(self.settings.fileName(), QSettings.IniFormat) self.assertFalse('a_value_with_default' not in pure_settings.allKeys()) self.assertFalse('an_invalid_value' not in pure_settings.allKeys()) if __name__ == '__main__': unittest.main()<|fim▁end|>
<|file_name|>GXRA.py<|end_file_name|><|fim▁begin|>### extends 'class_empty.py' ### block ClassImports # NOTICE: Do not edit anything here, it is generated code from . import gxapi_cy from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref ### endblock ClassImports ### block Header # NOTICE: The code generator will not replace the code in this block ### endblock Header ### block ClassImplementation # NOTICE: Do not edit anything here, it is generated code class GXRA(gxapi_cy.WrapRA): """ GXRA class. The `GXRA <geosoft.gxapi.GXRA>` class is used to access ASCII files sequentially or by line number. The files are opened in read-only mode, so no write operations are defined """ def __init__(self, handle=0): super(GXRA, self).__init__(GXContext._get_tls_geo(), handle) @classmethod def null(cls): """ A null (undefined) instance of `GXRA <geosoft.gxapi.GXRA>` :returns: A null `GXRA <geosoft.gxapi.GXRA>` :rtype: GXRA """ return GXRA() def is_null(self): """ Check if this is a null (undefined) instance :returns: True if this is a null (undefined) instance, False otherwise. :rtype: bool """ return self._internal_handle() == 0 # Miscellaneous @classmethod def create(cls, file): """ Creates `GXRA <geosoft.gxapi.GXRA>` :param file: Name of the file :type file: str :returns: `GXRA <geosoft.gxapi.GXRA>` Object :rtype: GXRA .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = gxapi_cy.WrapRA._create(GXContext._get_tls_geo(), file.encode()) return GXRA(ret_val) @classmethod def create_sbf(cls, sbf, file): """ Creates `GXRA <geosoft.gxapi.GXRA>` on an `GXSBF <geosoft.gxapi.GXSBF>` :param sbf: Storage :param file: Name of the file :type sbf: GXSBF :type file: str :returns: `GXRA <geosoft.gxapi.GXRA>` Object :rtype: GXRA .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** This method allows you to open an `GXRA <geosoft.gxapi.GXRA>` in a structured file storage (an `GXSBF <geosoft.gxapi.GXSBF>`). SBFs can be created inside other data containers, such as workspaces, maps, images and databases. This lets you store application specific information together with the data to which it applies. .. seealso:: sbf.gxh """ ret_val = gxapi_cy.WrapRA._create_sbf(GXContext._get_tls_geo(), sbf, file.encode()) return GXRA(ret_val) def gets(self, strbuff): """<|fim▁hole|> :param strbuff: Buffer in which to place string :type strbuff: str_ref :returns: 0 - Ok 1 - End of file :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val, strbuff.value = self._gets(strbuff.value.encode()) return ret_val def len(self): """ Returns the total number of lines in `GXRA <geosoft.gxapi.GXRA>` :returns: # of lines in the `GXRA <geosoft.gxapi.GXRA>`. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._len() return ret_val def line(self): """ Returns current line #, 0 is the first :returns: The current read line location. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ **Note:** This will be the next line read. """ ret_val = self._line() return ret_val def seek(self, line): """ Position next read to specified line # :param line: Line #, 0 is the first. :type line: int :returns: 0 if seeked line is within the range of lines, 1 if outside range, line pointer will not be moved. :rtype: int .. versionadded:: 5.0 **License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_ """ ret_val = self._seek(line) return ret_val ### endblock ClassImplementation ### block ClassExtend # NOTICE: The code generator will not replace the code in this block ### endblock ClassExtend ### block Footer # NOTICE: The code generator will not replace the code in this block ### endblock Footer<|fim▁end|>
Get next full line from `GXRA <geosoft.gxapi.GXRA>`
<|file_name|>tree.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use crate::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint}; use crate::matching::{ElementSelectorFlags, MatchingContext}; use crate::parser::SelectorImpl; use std::fmt::Debug; use std::ptr::NonNull; /// Opaque representation of an Element, for identity comparisons. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct OpaqueElement(NonNull<()>); unsafe impl Send for OpaqueElement {} impl OpaqueElement { /// Creates a new OpaqueElement from an arbitrarily-typed pointer. pub fn new<T>(ptr: &T) -> Self { unsafe { OpaqueElement(NonNull::new_unchecked( ptr as *const T as *const () as *mut (), )) } } } pub trait Element: Sized + Clone + Debug { type Impl: SelectorImpl; /// Converts self into an opaque representation. fn opaque(&self) -> OpaqueElement; fn parent_element(&self) -> Option<Self>; /// Whether the parent node of this element is a shadow root. fn parent_node_is_shadow_root(&self) -> bool; /// The host of the containing shadow root, if any. fn containing_shadow_host(&self) -> Option<Self>; /// The parent of a given pseudo-element, after matching a pseudo-element /// selector. /// /// This is guaranteed to be called in a pseudo-element. fn pseudo_element_originating_element(&self) -> Option<Self> { debug_assert!(self.is_pseudo_element()); self.parent_element() } <|fim▁hole|> fn is_pseudo_element(&self) -> bool; /// Skips non-element nodes fn prev_sibling_element(&self) -> Option<Self>; /// Skips non-element nodes fn next_sibling_element(&self) -> Option<Self>; fn is_html_element_in_html_document(&self) -> bool; fn has_local_name(&self, local_name: &<Self::Impl as SelectorImpl>::BorrowedLocalName) -> bool; /// Empty string for no namespace fn has_namespace(&self, ns: &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl) -> bool; /// Whether this element and the `other` element have the same local name and namespace. fn is_same_type(&self, other: &Self) -> bool; fn attr_matches( &self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName, operation: &AttrSelectorOperation<&<Self::Impl as SelectorImpl>::AttrValue>, ) -> bool; fn match_non_ts_pseudo_class<F>( &self, pc: &<Self::Impl as SelectorImpl>::NonTSPseudoClass, context: &mut MatchingContext<Self::Impl>, flags_setter: &mut F, ) -> bool where F: FnMut(&Self, ElementSelectorFlags); fn match_pseudo_element( &self, pe: &<Self::Impl as SelectorImpl>::PseudoElement, context: &mut MatchingContext<Self::Impl>, ) -> bool; /// Whether this element is a `link`. fn is_link(&self) -> bool; /// Returns whether the element is an HTML <slot> element. fn is_html_slot_element(&self) -> bool; /// Returns the assigned <slot> element this element is assigned to. /// /// Necessary for the `::slotted` pseudo-class. fn assigned_slot(&self) -> Option<Self> { None } fn has_id( &self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity, ) -> bool; fn has_class( &self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity, ) -> bool; fn is_part(&self, name: &<Self::Impl as SelectorImpl>::PartName) -> bool; /// Returns whether this element matches `:empty`. /// /// That is, whether it does not contain any child element or any non-zero-length text node. /// See http://dev.w3.org/csswg/selectors-3/#empty-pseudo fn is_empty(&self) -> bool; /// Returns whether this element matches `:root`, /// i.e. whether it is the root element of a document. /// /// Note: this can be false even if `.parent_element()` is `None` /// if the parent node is a `DocumentFragment`. fn is_root(&self) -> bool; /// Returns whether this element should ignore matching nth child /// selector. fn ignores_nth_child_selectors(&self) -> bool { false } }<|fim▁end|>
/// Whether we're matching on a pseudo-element.
<|file_name|>timer.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Timers for non-Linux/non-Windows OSes //! //! This module implements timers with a worker thread, select(), and a lot of //! witchcraft that turns out to be horribly inaccurate timers. The unfortunate //! part is that I'm at a loss of what else to do one these OSes. This is also //! why Linux has a specialized timerfd implementation and windows has its own //! implementation (they're more accurate than this one). //! //! The basic idea is that there is a worker thread that's communicated to via a //! channel and a pipe, the pipe is used by the worker thread in a select() //! syscall with a timeout. The timeout is the "next timer timeout" while the //! channel is used to send data over to the worker thread. //! //! Whenever the call to select() times out, then a channel receives a message. //! Whenever the call returns that the file descriptor has information, then the //! channel from timers is drained, enqueuing all incoming requests. //! //! The actual implementation of the helper thread is a sorted array of //! timers in terms of target firing date. The target is the absolute time at //! which the timer should fire. Timers are then re-enqueued after a firing if //! the repeat boolean is set. //! //! Naturally, all this logic of adding times and keeping track of //! relative/absolute time is a little lossy and not quite exact. I've done the //! best I could to reduce the amount of calls to 'now()', but there's likely //! still inaccuracies trickling in here and there. //! //! One of the tricky parts of this implementation is that whenever a timer is //! acted upon, it must cancel whatever the previous action was (if one is //! active) in order to act like the other implementations of this timer. In //! order to do this, the timer's inner pointer is transferred to the worker //! thread. Whenever the timer is modified, it first takes ownership back from<|fim▁hole|>//! re-enqueuing later on. //! //! Note that all time units in this file are in *milliseconds*. use prelude::v1::*; use self::Req::*; use io::IoResult; use libc; use mem; use os; use ptr; use sync::atomic::{self, Ordering}; use sync::mpsc::{channel, Sender, Receiver, TryRecvError}; use sys::c; use sys::fs::FileDesc; use sys_common::helper_thread::Helper; helper_init! { static HELPER: Helper<Req> } pub trait Callback { fn call(&mut self); } pub struct Timer { id: uint, inner: Option<Box<Inner>>, } pub struct Inner { cb: Option<Box<Callback + Send>>, interval: u64, repeat: bool, target: u64, id: uint, } pub enum Req { // Add a new timer to the helper thread. NewTimer(Box<Inner>), // Remove a timer based on its id and then send it back on the channel // provided RemoveTimer(uint, Sender<Box<Inner>>), } // returns the current time (in milliseconds) pub fn now() -> u64 { unsafe { let mut now: libc::timeval = mem::zeroed(); assert_eq!(c::gettimeofday(&mut now, ptr::null_mut()), 0); return (now.tv_sec as u64) * 1000 + (now.tv_usec as u64) / 1000; } } fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) { let mut set: c::fd_set = unsafe { mem::zeroed() }; let mut fd = FileDesc::new(input, true); let mut timeout: libc::timeval = unsafe { mem::zeroed() }; // active timers are those which are able to be selected upon (and it's a // sorted list, and dead timers are those which have expired, but ownership // hasn't yet been transferred back to the timer itself. let mut active: Vec<Box<Inner>> = vec![]; let mut dead = vec![]; // inserts a timer into an array of timers (sorted by firing time) fn insert(t: Box<Inner>, active: &mut Vec<Box<Inner>>) { match active.iter().position(|tm| tm.target > t.target) { Some(pos) => { active.insert(pos, t); } None => { active.push(t); } } } // signals the first requests in the queue, possible re-enqueueing it. fn signal(active: &mut Vec<Box<Inner>>, dead: &mut Vec<(uint, Box<Inner>)>) { if active.is_empty() { return } let mut timer = active.remove(0); let mut cb = timer.cb.take().unwrap(); cb.call(); if timer.repeat { timer.cb = Some(cb); timer.target += timer.interval; insert(timer, active); } else { dead.push((timer.id, timer)); } } 'outer: loop { let timeout = if active.len() == 0 { // Empty array? no timeout (wait forever for the next request) ptr::null_mut() } else { let now = now(); // If this request has already expired, then signal it and go // through another iteration if active[0].target <= now { signal(&mut active, &mut dead); continue; } // The actual timeout listed in the requests array is an // absolute date, so here we translate the absolute time to a // relative time. let tm = active[0].target - now; timeout.tv_sec = (tm / 1000) as libc::time_t; timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t; &mut timeout as *mut libc::timeval }; c::fd_set(&mut set, input); match unsafe { c::select(input + 1, &mut set, ptr::null_mut(), ptr::null_mut(), timeout) } { // timed out 0 => signal(&mut active, &mut dead), // file descriptor write woke us up, we've got some new requests 1 => { loop { match messages.try_recv() { Err(TryRecvError::Disconnected) => { assert!(active.len() == 0); break 'outer; } Ok(NewTimer(timer)) => insert(timer, &mut active), Ok(RemoveTimer(id, ack)) => { match dead.iter().position(|&(i, _)| id == i) { Some(i) => { let (_, i) = dead.remove(i); ack.send(i).unwrap(); continue } None => {} } let i = active.iter().position(|i| i.id == id); let i = i.expect("no timer found"); let t = active.remove(i); ack.send(t).unwrap(); } Err(..) => break } } // drain the file descriptor let mut buf = [0]; assert_eq!(fd.read(&mut buf).ok().unwrap(), 1); } -1 if os::errno() == libc::EINTR as uint => {} n => panic!("helper thread failed in select() with error: {} ({})", n, os::last_os_error()) } } } impl Timer { pub fn new() -> IoResult<Timer> { // See notes above regarding using int return value // instead of () HELPER.boot(|| {}, helper); static ID: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT; let id = ID.fetch_add(1, Ordering::Relaxed); Ok(Timer { id: id, inner: Some(box Inner { cb: None, interval: 0, target: 0, repeat: false, id: id, }) }) } pub fn sleep(&mut self, ms: u64) { let mut inner = self.inner(); inner.cb = None; // cancel any previous request self.inner = Some(inner); let mut to_sleep = libc::timespec { tv_sec: (ms / 1000) as libc::time_t, tv_nsec: ((ms % 1000) * 1000000) as libc::c_long, }; while unsafe { libc::nanosleep(&to_sleep, &mut to_sleep) } != 0 { if os::errno() as int != libc::EINTR as int { panic!("failed to sleep, but not because of EINTR?"); } } } pub fn oneshot(&mut self, msecs: u64, cb: Box<Callback + Send>) { let now = now(); let mut inner = self.inner(); inner.repeat = false; inner.cb = Some(cb); inner.interval = msecs; inner.target = now + msecs; HELPER.send(NewTimer(inner)); } pub fn period(&mut self, msecs: u64, cb: Box<Callback + Send>) { let now = now(); let mut inner = self.inner(); inner.repeat = true; inner.cb = Some(cb); inner.interval = msecs; inner.target = now + msecs; HELPER.send(NewTimer(inner)); } fn inner(&mut self) -> Box<Inner> { match self.inner.take() { Some(i) => i, None => { let (tx, rx) = channel(); HELPER.send(RemoveTimer(self.id, tx)); rx.recv().unwrap() } } } } impl Drop for Timer { fn drop(&mut self) { self.inner = Some(self.inner()); } }<|fim▁end|>
//! the worker thread in order to modify the same data structure. This has the //! side effect of "cancelling" the previous requests while allowing a
<|file_name|>Car.cpp<|end_file_name|><|fim▁begin|>/* Car.cpp - Library for IWM Rocket Avoidance Robot Car. Created by Steve Mullarkey, November 18, 2013. Copyright 2013 Steve Mullarkey Licensed under the Apache License, Version 2.0 */ #include "Arduino.h" #include <Servo.h> #include "Car.h" Car::Car(int frontServoPin, int backServoPin, int motorPin, int sonarTriggerPin, int sonarEchoPin) : _sonar(sonarTriggerPin, sonarEchoPin), _motor(motorPin) { _frontServoPin = frontServoPin; _backServoPin = backServoPin; _motorPin = motorPin; _sonarTriggerPin = sonarTriggerPin; _sonarEchoPin = sonarEchoPin; // randomSeed(analogRead(0)); // pin 0 unconnected - use random noise as seed _motorSpeed = 150; _motor.setSpeed(_motorSpeed); // set speed for drive motor - 0 to 255 _motor.run(RELEASE); } // ----------------------------------------------------------------// // F O R W A R D C O M M A N D // // ----------------------------------------------------------------// void Car::forward() { _motor.setSpeed(_motorSpeed); _motor.run(FORWARD); Serial.println("Car : forward called "); delay(MOTOR_DELAY); } // ----------------------------------------------------------------// // B A C K C O M M A N D // // ----------------------------------------------------------------// void Car::back() { _motor.setSpeed(_motorSpeed); _motor.run(BACKWARD); Serial.println("Car : back called "); delay(MOTOR_DELAY); } // ----------------------------------------------------------------// // S T O P C O M M A N D // // ----------------------------------------------------------------// void Car::stop() { _motor.run(RELEASE); Serial.println("Car : stop called "); delay(MOTOR_DELAY); } // ----------------------------------------------------------------// // S T R A I G H T C O M M A N D // // ----------------------------------------------------------------// void Car::straight() { checkServoMotors(); _backServo.write(ANGLE_TURN_AHEAD + ANGLE_TURN_OFFSET); Serial.println("Car : Straight called "); delay(SERVO_DELAY); } // ----------------------------------------------------------------// // L E F T C O M M A N D // // ----------------------------------------------------------------// void Car::left() { checkServoMotors(); _backServo.write(ANGLE_TURN_LEFT + ANGLE_TURN_OFFSET); Serial.println("Car : Left called "); delay(SERVO_DELAY); } // ----------------------------------------------------------------// // R I G H T C O M M A N D // // ----------------------------------------------------------------// void Car::right() { checkServoMotors(); _backServo.write(ANGLE_TURN_RIGHT + ANGLE_TURN_OFFSET); Serial.println("Car : Right called "); delay(SERVO_DELAY); } // ----------------------------------------------------------------// // S E T M O T O R S P E E D // // ----------------------------------------------------------------// void Car::setMotorSpeed(int theMotorSpeed) { _motorSpeed = theMotorSpeed; _motor.setSpeed(_motorSpeed); Serial.print("Car : setMotorSpeed called with value of "); Serial.println(_motorSpeed); } // ----------------------------------------------------------------// // P A U S E // // ----------------------------------------------------------------// void Car::pause(float pauseTime) { int i = int(pauseTime * 1000); delay(i); Serial.print("Car : pause called with a value of "); Serial.println(pauseTime); } // ----------------------------------------------------------------// // P I N G C O M M A N D // // ----------------------------------------------------------------// int Car::ping() { checkServoMotors(); _frontServo.write(ANGLE_SCAN_OFFSET + ANGLE_SCAN_AHEAD); delay(SERVO_DELAY); unsigned int _distance = _sonar.ping_cm(); Serial.print("Car : Ping called and returned "); Serial.print(_distance); Serial.println(" cm."); return _distance; } // ----------------------------------------------------------------// // P I N G L E F T C O M M A N D // // ----------------------------------------------------------------// int Car::pingLeft() { checkServoMotors(); _frontServo.write(ANGLE_SCAN_OFFSET + ANGLE_SCAN_LEFT); delay(SERVO_DELAY); unsigned int _distance = _sonar.ping_cm(); Serial.print("Car : PingLeft called and returned "); Serial.print(_distance); Serial.println(" cm."); return _distance; } // ----------------------------------------------------------------// // P I N G R I G H T C O M M A N D // // ----------------------------------------------------------------// int Car::pingRight() { checkServoMotors(); _frontServo.write(ANGLE_SCAN_OFFSET + ANGLE_SCAN_RIGHT); delay(SERVO_DELAY); unsigned int _distance = _sonar.ping_cm(); Serial.print("Car : PingRight called and returned "); Serial.print(_distance); Serial.println(" cm."); return _distance; } // ----------------------------------------------------------------// // C H E C K S E R V O S A T T A C H E D // // ----------------------------------------------------------------// void Car::checkServoMotors() { if (_frontServo.attached()) { // Serial.print("Car : diag -> _frontServo still attached"); } else { Serial.print("Car : diag -> _frontServo not attached"); _frontServo.attach(_frontServoPin); } if (_backServo.attached()) { // Serial.println("Car : diag -> _backServo still attached"); } else { Serial.println("Car : diag -> _backServo not attached"); _backServo.attach(_backServoPin); } } // ----------------------------------------------------------------// // T E S T S E R V O M O T O R S // // ----------------------------------------------------------------// void Car::test() { delay(5000); checkServoMotors(); int pos = 0; for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree _frontServo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos >= 0; pos-=1) // goes from 180 degrees to 0 degrees { _frontServo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } _frontServo.write(90);<|fim▁hole|> { // in steps of 1 degree _backServo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for(pos = 180; pos >= 0; pos-=1) // goes from 180 degrees to 0 degrees { _backServo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } _backServo.write(90); delay(5000); }<|fim▁end|>
for(pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
<|file_name|>libembed.d.ts<|end_file_name|><|fim▁begin|>import '@phosphor/widgets/style/index.css'; import 'font-awesome/css/font-awesome.css'; import '@jupyter-widgets/controls/css/widgets.css'; import { WidgetManager } from './manager'; /** * Render the inline widgets inside a DOM element.<|fim▁hole|> * @param managerFactory A function that returns a new WidgetManager * @param element (default document.documentElement) The document element in which to process for widget state. */ export declare function renderWidgets(managerFactory: () => WidgetManager, element?: HTMLElement): Promise<void>;<|fim▁end|>
*
<|file_name|>config.js<|end_file_name|><|fim▁begin|>var _ = require('lodash'); var fs = require('fs'); var logger = require('./logger'); var jsonLoad = require('./json-load'); var config = module.exports; // defaults - can be overridden in config.json config.startServer = true; config.postgresqlUser = 'postgres'; config.postgresqlPassword = null; config.postgresqlDatabase = 'postgres'; config.postgresqlHost = 'localhost'; config.urlPrefix = '/pl'; config.homeUrl = '/'; config.redisUrl = null; // redis://localhost:6379/ for dev config.logFilename = 'server.log'; config.authType = 'none'; config.serverType = 'http'; config.serverPort = '3000'; config.cronIntervalAutoFinishExamsSec = 10 * 60; config.cronIntervalErrorAbandonedJobsSec = 10 * 60; config.cronIntervalExternalGraderLoadSec = 8; config.cronIntervalServerLoadSec = 8; config.cronIntervalServerUsageSec = 8; config.cronDailySec = 8 * 60 * 60; config.autoFinishAgeMins = 6 * 60; config.questionDefaultsDir = 'question-servers/default-calculation'; config.secretKey = 'THIS_IS_THE_SECRET_KEY'; // override in config.json config.secretSlackOpsBotEndpoint = null; // override in config.json config.gitSshCommand = null; config.secretSlackProctorToken = null; config.secretSlackProctorChannel = null; config.externalGradingUseAws = false; config.externalGradingJobsQueueName = 'grading_jobs_dev'; config.externalGradingResultsQueueName = 'grading_results_dev'; config.externalGradingJobsDeadLetterQueueName = null; config.externalGradingResultsDeadLetterQueueName = null; config.externalGradingAutoScalingGroupName = null; config.externalGradingS3Bucket = 'prairielearn.dev.grading'; config.externalGradingWebhookUrl = null; config.externalGradingDefaultTimeout = 30; // in seconds config.externalGradingLoadAverageIntervalSec = 30; config.externalGradingHistoryLoadIntervalSec = 3600; config.externalGradingCurrentCapacityFactor = 1.5; config.externalGradingHistoryCapacityFactor = 1.5; config.externalGradingSecondsPerSubmissionPerUser = 120; config.useWorkers = true; config.workersCount = null; // if null, use workersPerCpu instead config.workersPerCpu = 1; config.workerWarmUpDelayMS = 1000; config.groupName = 'local'; // used for load reporting config.instanceId = 'server'; // FIXME: needs to be determed dynamically with new config code config.reportIntervalSec = 10; // load reporting config.maxResponseTimeSec = 500; config.serverLoadAverageIntervalSec = 30; config.serverUsageIntervalSec = 10; config.PLpeekUrl = 'https://cbtf.engr.illinois.edu/sched/proctor/plpeek'; config.blockedWarnEnable = false; config.blockedWarnThresholdMS = 100; config.SEBServerUrl = null; config.SEBServerFilter = null; config.SEBDownloadUrl = null; config.hasShib = false; config.hasAzure = false; config.hasOauth = false; config.syncExamIdAccessRules = false; config.checkAccessRulesExamUuid = false; config.questionRenderCacheType = 'none'; // One of none, redis, memory config.hasLti = false; config.ltiRedirectUrl = null; config.filesRoot = null; const azure = { // Required azureIdentityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration', // azureIdentityMetadata: 'https://login.microsoftonline.com/<tenant_name>.onmicrosoft.com/.well-known/openid-configuration', // or equivalently: 'https://login.microsoftonline.com/<tenant_guid>/.well-known/openid-configuration' // // or you can use the common endpoint // 'https://login.microsoftonline.com/common/.well-known/openid-configuration' // To use the common endpoint, you have to either set `validateIssuer` to false, or provide the `issuer` value. // Required, the client ID of your app in AAD azureClientID: '<your_client_id>', <|fim▁hole|> azureResponseMode: 'form_post', // Required, the reply URL registered in AAD for your app azureRedirectUrl: 'http://localhost:3000/auth/openid/return', // Required if we use http for redirectUrl azureAllowHttpForRedirectUrl: false, // Required if `responseType` is 'code', 'id_token code' or 'code id_token'. // If app key contains '\', replace it with '\\'. azureClientSecret: '<your_client_secret>', // Required to set to false if you don't want to validate issuer azureValidateIssuer: false, // Required if you want to provide the issuer(s) you want to validate instead of using the issuer from metadata azureIssuer: null, // Required to set to true if the `verify` function has 'req' as the first parameter azurePassReqToCallback: false, // Recommended to set to true. By default we save state in express session, if this option is set to true, then // we encrypt state and save it in cookie instead. This option together with { session: false } allows your app // to be completely express session free. azureUseCookieInsteadOfSession: true, // Required if `useCookieInsteadOfSession` is set to true. You can provide multiple set of key/iv pairs for key // rollover purpose. We always use the first set of key/iv pair to encrypt cookie, but we will try every set of // key/iv pair to decrypt cookie. Key can be any string of length 32, and iv can be any string of length 12. azureCookieEncryptionKeys: [ { 'key': '12345678901234567890123456789012', 'iv': '123456789012' }, { 'key': 'abcdefghijklmnopqrstuvwxyzabcdef', 'iv': 'abcdefghijkl' }, ], // Optional. The additional scope you want besides 'openid', for example: ['email', 'profile']. azureScope: null, // Optional, 'error', 'warn' or 'info' azureLoggingLevel: 'warn', // Optional. The lifetime of nonce in session or cookie, the default value is 3600 (seconds). azureNonceLifetime: null, // Optional. The max amount of nonce saved in session or cookie, the default value is 10. azureNonceMaxAmount: 5, // Optional. The clock skew allowed in token validation, the default value is 300 seconds. azureClockSkew: null, // Optional. // If you want to get access_token for a specific resource, you can provide the resource here; otherwise, // set the value to null. // Note that in order to get access_token, the responseType must be 'code', 'code id_token' or 'id_token code'. azureResourceURL: 'https://graph.windows.net', // The url you need to go to destroy the session with AAD azureDestroySessionUrl: 'https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri=http://localhost:3000', }; _.assign(config, azure); config.loadConfig = function(file) { if (fs.existsSync(file)) { let fileConfig = jsonLoad.readJSONSyncOrDie(file, 'schemas/serverConfig.json'); _.assign(config, fileConfig); } else { logger.warn(file + ' not found, using default configuration'); } };<|fim▁end|>
// Required, must be 'code', 'code id_token', 'id_token code' or 'id_token' azureResponseType: 'code id_token', // Required
<|file_name|>bravialib.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # # bravialib - Will Cooke - Whizzy Labs - @8none1 # http://www.whizzy.org # Copyright Will Cooke 2016. Released under the GPL. # # # My attempt to talk to the Sony Bravia web API. # # This is designed to be used by a long running process # So there is a potentially slow start-up time but then it should be quick enough # at the expense of some memory usage # # The TV will give you access based on the device_id and nickname once you are authorised I think. # The TV will need to be already switched on for this to work. # # # Thanks: # https://github.com/aparraga/braviarc/ # https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGlhbC1tdWx0aXNjcmVlbi5vcmd8ZGlhbHxneDoyNzlmNzY3YWJlMmY1MjZl # # Some useful resources: # A tidied up packet capture I did from the iphone app: http://paste.ubuntu.com/23417464/plain/ # # # TODO: # Move logging out of prints and in to logging # import requests from requests.auth import HTTPBasicAuth import json from xml.dom import minidom import socket import struct import time class MockResponse(object): def __init__(self, status_code): self.status_code = status_code class Bravia(object): def __init__(self, hostname = None, ip_addr = None, mac_addr = None): self.ip_addr = ip_addr self.hostname = hostname self.mac_addr = mac_addr # You don't *have* to specify the MAC address as once we are paired via IP we can find # it from the TV but it will only be stored for this session. If the TV is off and you are running this script # from cold - you will need the MAC to wake the TV up. if self.ip_addr is None and self.hostname is not None: self.ip_addr = self._lookup_ip_from_hostname(self.hostname) self.device_id = "WebInterface:001" self.nickname = "IoT Remote Controller Interface" self.endpoint = 'http://'+self.ip_addr self.cookies = None self.x_auth_psk = None # If you're using PSK instead of cookies you need to set this. self.DIAL_cookie = {} self.packet_id = 1 self.device_friendly_name = "" self._JSON_HEADER = {'content-type':'application/json', 'connection':'close'} self._TIMEOUT = 10 self.remote_controller_code_lookup = {} self.app_lookup = {} self.input_map = {} self.dvbt_channels = {} self.paired = False def _debug_request(self, r): # Pass a Requests response in here to see what happened print "\n\n\n" print "------- What was sent out ---------" print r.request.headers print r.request.body print "---------What came back -----------" print r.status_code print r.headers print r.text print "-----------------------------------" print "\n\n\n" def _lookup_ip_from_hostname(self, hostname): ipaddr = socket.gethostbyname(hostname) if ipaddr is not '127.0.0.1': return ipaddr else: # IP lookup failed return False def _build_json_payload(self,method, params = [], version="1.0"): return {"id":self.packet_id, "method":method, "params":params, "version":version} def is_available(self): # Try to find out if the TV is actually on or not. Pinging the TV would require # this script to run as root, so not doing that. This function return True or # False depending on if the box is on or not. payload = self._build_json_payload("getPowerStatus") try: # Using a shorter timeout here so we can return more quickly r = self.do_POST(url="/sony/system", payload = payload, timeout=2) data = r.json() if data.has_key('result'): if data['result'][0]['status'] == "standby": # TV is in standby mode, and so not on. return False elif data['result'][0]['status'] == "active": # TV really is on return True else: # Assume it's not on. print "Uncaught result" return False if data.has_key('error'): if 404 in data['error']: # TV is probably booting at this point - so not available yet return False elif 403 in data['error']: # A 403 Forbidden is acceptable here, because it means the TV is responding to requests return True else: print "Uncaught error" return False return True except requests.exceptions.ConnectTimeout: print "No response, TV is probably off" return False except requests.exceptions.ConnectionError: print "TV is certainly off." return False except requests.exceptions.ReadTimeout: print "TV is on but not accepting commands yet" return False except ValueError: print "Didn't get back JSON as expected" # This might lead to false negatives - need to check return False def do_GET(self, url=None, headers=None, auth=None, cookies=None, timeout=None): if url is None: return False if url[0:4] != "http": url=self.endpoint+url if cookies is None and self.cookies is not None: cookies=self.cookies if self.x_auth_psk is not None: headers['X-Auth-PSK']=self.x_auth_psk if timeout is None: timeout = self._TIMEOUT if headers is None: r = requests.get(url, cookies=cookies, auth=auth, timeout=timeout) else: r = requests.get(url, headers=headers, cookies=cookies, auth=auth, timeout=timeout) return r def do_POST(self, url=None, payload=None, headers=None, auth=None, cookies=None, timeout=None): if url is None: return False if type(payload) is dict: payload = json.dumps(payload) if headers is None: headers = self._JSON_HEADER # If you don't want any extra headers pass in "" if cookies is None and self.cookies is not None: cookies=self.cookies if self.x_auth_psk is not None: headers['X-Auth-PSK']=self.x_auth_psk if timeout is None: timeout = self._TIMEOUT if url[0:4] != "http": url = self.endpoint+url # if you want to pass just the path you can, otherwise pass a full url and it will be used self.packet_id += 1 # From packet captures, this increments on each request, so its a good idea to use this method all the time if auth is not None: r = requests.post(url, data=payload, headers=headers, cookies=cookies, auth=self.auth, timeout=timeout) else: r = requests.post(url, data=payload, headers=headers, cookies=cookies, timeout=timeout) print r return r def connect(self): # TODO: What if the TV is off and we can't connect? # # From looking at packet captures what seems to happen is: # 1. Try and connect to the accessControl interface with the "pinRegistration" part in the payload # 2. If you get back a 200 *and* the return data looks OK then you have already authorised # 3. If #2 is a 200 you get back an auth token. I think that this token will expire, so we might need to # re-connect later on - given that this script will be running for a long time. Hopefully you won't # need to get a new PIN number ever. # 4. If #2 was a 401 then you need to authorise, and then you do that by sending the PIN on screen as # a base64 encoded BasicAuth using a blank username (e.g. "<username>:<password" -> ":1234") # If that works, you should get a cookie back. # 5. Use the cookie in all subsequent requests. Note there is an issue with this. The cookie is for # path "/sony/" *but* the Apps are run from a path "/DIAL/sony/" so I try and fix this by adding a # second cookie with that path and the same auth data. if self.x_auth_psk is None: # We have not specified a PSK therefore we have to use Cookies payload = self._build_json_payload("actRegister", [{"clientid":self.device_id,"nickname":self.nickname}, [{"value":"no","function":"WOL"}, {"value":"no","function":"pinRegistration"}]]) try: r = self.do_POST(url='/sony/accessControl', payload=payload) except requests.exceptions.ConnectTimeout: print "No response, TV is probably off" return None, False except requests.exceptions.ConnectionError: print "TV is certainly off." return None, False if r.status_code == 200: # Rather handily, the TV returns a 200 if the TV is in stand-by but not really on :) try: if "error" in r.json(): #.keys(): if "not power-on" in r.json()['error']: # TV isn't powered up r = self.wakeonlan() print "TV not on! Have sent wakeonlan, probably try again in a mo." # TODO: make this less crap return None,False except: raise # If we get here then We are already paired so get the new token self.paired = True self.cookies = r.cookies # Also add the /DIAL/ path cookie # Looks like requests doesn't handle two cookies with the same name ('auth') in one jar # so going to have a dict for the DIAL cookie and pass around as needed. :/ a = r.headers['Set-Cookie'].split(';') # copy the cookie data headers for each in a: if len(each) > 0: b = each.split('=') self.DIAL_cookie[b[0].strip()] = b[1] elif r.status_code == 401: print "We are not paired!" return r,False elif r.status_code == 404: # Most likely the TV hasn't booted yet print("TV probably hasn't booted yet") return r,False else: return None,False else: # We are using a PSK self.paired = True self.cookies = None self.DIAL_cookie = None r = None # Populate some data now automatically. print "Getting DMR info..." self.get_dmr() print "Getting sysem info..." self.get_system_info() print "Populating remote control codes..." self.populate_controller_lookup() print "Enumerating TV inputs..." self.get_input_map() print "Populating apps list..." self.populate_apps_lookup() print "Populating channel list..." self.get_channel_list() print "Matching HD channels..." self.create_HD_chan_lookups() # You might not want to do this if you don't use Freeview in the UK print "Done initialising TV data." return r,True def start_pair(self): # This should prompt the TV to display the pairing screen payload = self._build_json_payload("actRegister", [{"clientid":self.device_id,"nickname":self.nickname}, [{"value":"no","function":"WOL"}]]) r = self.do_POST(url='/sony/accessControl', payload=payload) if r.status_code == 200: print "Probably already paired" return r,True if r.status_code == 401: return r,False else: return None,False def complete_pair(self, pin): # The user should have a PIN on the screen now, pass it in here to complete the pairing process payload = self._build_json_payload("actRegister", [{"clientid":self.device_id, "nickname":self.nickname}, [{"value":"no", "function":"WOL"}]]) self.auth = HTTPBasicAuth('',pin) # Going to keep this in the object, just in case we need it again later r = self.do_POST(url='/sony/accessControl', payload=payload, auth=self.auth) if r.status_code == 200: print("have paired") self.paired = True # let's call connect again to get the cookies all set up properly a,b = self.connect() if b is True: return r,True else: return r,False else: return None,False def get_system_info(self): payload = self._build_json_payload("getSystemInformation") r = self.do_POST(url="/sony/system", payload=payload) if r.status_code == 200: self.system_info = r.json()['result'][0] if self.mac_addr == None: self.mac_addr = self.system_info['macAddr'] return self.system_info else: return False def get_input_map(self): payload = self._build_json_payload("getCurrentExternalInputsStatus") r = self.do_POST(url="/sony/avContent", payload=payload) if r.status_code == 200: for each in r.json()['result'][0]: self.input_map[each['title']] = {'label':each['label'], 'uri':each['uri']} return True else: return False def get_input_uri_from_label(self, label): for each in self.input_map: if self.input_map[each]['label'] == label: return self.input_map[each]['uri'] print "Didnt match the input name." return None def set_external_input(self, uri): payload = self._build_json_payload("setPlayContent", [{"uri":uri}]) r = self.do_POST(url="/sony/avContent", payload=payload) if r.status_code == 200: if "error" in r.json(): # Something didnt work. The JSON will tell you what. return False else: return True else: return False def get_dmr(self): r = self.do_GET('http://'+self.ip_addr+':52323/dmr.xml') self.dmr_data = minidom.parseString(r.text) # XML. FFS. :( self.device_friendly_name = self.dmr_data.getElementsByTagName('friendlyName')[0].childNodes[0].data a = self.dmr_data.getElementsByTagNameNS('urn:schemas-sony-com:av','X_IRCCCode') for each in a: name = each.getAttribute("command") value = each.firstChild.nodeValue self.remote_controller_code_lookup[name.lower()] = value # Not much more interesting stuff here really, but see: https://aydbe.com/assets/uploads/2014/11/json.txt # and https://github.com/bunk3r/braviapy # Maybe /sony/system/setLEDIndicatorStatus would be fun? #"setLEDIndicatorStatus" -> {"mode":"string","status":"bool"} # Maybe mode is a hex colour? and bool is on/off? def populate_controller_lookup(self): payload = self._build_json_payload("getRemoteControllerInfo") r = self.do_POST(url='/sony/system', payload=payload) if r.status_code == 200: for each in r.json()['result'][1]: self.remote_controller_code_lookup[each['name'].lower()] = each['value'] return True else: return False def do_remote_control(self,action): # Pass in the action name, such as: # "PowerOff" "Mute" "Pause" "Play" # You can probably guess what these would be, but if not: # print <self>.remote_controller_code_lookup action = action.lower() if action in self.remote_controller_code_lookup: #.keys(): ircc_code = self.remote_controller_code_lookup[action] else: return False header = {'SOAPACTION': '"urn:schemas-sony-com:service:IRCC:1#X_SendIRCC"'} url = "/sony/IRCC" body = '<?xml version="1.0"?>' # Look at all this crap just to send a remote control code... body += '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' body += '<s:Body>' body += '<u:X_SendIRCC xmlns:u="urn:schemas-sony-com:service:IRCC:1">' body += '<IRCCCode>' + ircc_code + '</IRCCCode>' body += '</u:X_SendIRCC>' body += '</s:Body>' body += '</s:Envelope>' try: r = self.do_POST(url=url, payload=body, headers=header) except requests.exceptions.ConnectTimeout: print("Connect timeout error") r = MockResponse(200) except requests.exceptions.ConnectionError: print("Connect error") r = MockResponse(200) if r.status_code == 200: return True else: return False def populate_apps_lookup(self): # Interesting note: If you don't do this (presumably just calling the # URL is enough) then apps won't actually launch and you will get a 404 # error back from the TV. Once you've called this it starts working. self.app_lookup={} r = self.do_GET(url="/DIAL/sony/applist", cookies=self.DIAL_cookie) if r.status_code == 200: app_xml_data = minidom.parseString(r.text.encode('utf-8')) for each in app_xml_data.getElementsByTagName('app'): appid = each.getElementsByTagName('id')[0].firstChild.data appname = each.getElementsByTagName('name')[0].firstChild.data try: iconurl = each.getElementsByTagName('icon_url')[0].firstChild.data except: iconurl = None self.app_lookup[appname] = {'id':appid, 'iconurl':iconurl} return True else: return False def load_app(self, app_name): # Pass in the name of the app, the most useful ones on my telly are: # "Amazon Instant Video" , "Netflix", "BBC iPlayer", "Demand 5" if self.app_lookup == {}: self.populate_apps_lookup() # This must happen before apps will launch try: app_id = self.app_lookup[app_name]['id'] except KeyError: return False print "Trying to load app:", app_id headers = {'Connection':'close'} r = self.do_POST(url="/DIAL/apps/"+app_id, headers=headers, cookies=self.DIAL_cookie) print r.status_code print r.headers print r if r.status_code == 201: return True else: return False def get_app_status(self): payload = self._build_json_payload("getApplicationStatusList") r = self.do_POST(url="/sony/appControl", payload=payload) return r.json() def get_channel_list(self): # This only supports dvbt for now... # First, we find out how many channels there are payload = self._build_json_payload("getContentCount", [{"target":"all", "source":"tv:dvbt"}], version="1.1") r = self.do_POST(url="/sony/avContent", payload=payload) chan_count = int(r.json()['result'][0]['count']) # It seems to only return the channels in lumps of 50, and some of those returned are blank? chunk_size = 50 loops = int(chan_count / chunk_size) + (chan_count % chunk_size > 0) # Sneaky round up trick, the mod > 0 evaluates to int 1 chunk = 0 for x in range(loops): payload = self._build_json_payload("getContentList", [{"stIdx":chunk, "source":"tv:dvbt", "cnt":chunk_size, "target":"all" }], version="1.2") r = self.do_POST(url="/sony/avContent", payload=payload) a = r.json()['result'][0] for each in a: if each['title'] == "": continue # We get back some blank entries, so just ignore them if self.dvbt_channels.has_key(each['title']): # Channel has already been added, we only want to keep the one with the lowest chan_num. # The TV seems to return channel data for channels it can't actually receive (e.g. out of # area local BBC channels). Trying to tune to these gives an error. if int(each['dispNum']) > int(self.dvbt_channels[each['title']]['chan_num']): # This is probably not a "real" channel we care about, so skip it. continue #self.dvbt_channels[each['title']] = {'chan_num':each['dispNum'], 'uri':each['uri']} else: self.dvbt_channels[each['title']] = {'chan_num':each['dispNum'], 'uri':each['uri']} chunk += chunk_size def create_HD_chan_lookups(self): # This should probably be in the script that imports this library not in # the library itself, but I wanted this feature, so I'm chucking it in # here. This probably only works for Freeview in the UK. # Use case to demonstrate why this is here: You want to use Alexa to # switch the channel. Naturally, you want the HD channel if there is # one but you don't want to have to say "BBC ONE HD" because that would # be stupid. So you just say "BBC ONE" and the script does the work to # find the HD version for you. for each in self.dvbt_channels.iteritems(): hd_version = "%s HD" % each[0] # e.g. "BBC ONE" -> "BBC ONE HD" if hd_version in self.dvbt_channels: # Extend the schema by adding a "hd_uri" key self.dvbt_channels[each[0]]['hd_uri'] = self.dvbt_channels[hd_version]['uri'] def get_channel_uri(self, title): if self.dvbt_channels == {}: self.get_channel_list() try: return self.dvbt_channels[title]['uri'] except KeyError: return False def wakeonlan(self, mac=None): # Thanks: Taken from https://github.com/aparraga/braviarc/blob/master/braviarc/braviarc.py # Not using another library for this as it's pretty small... if mac is None and self.mac_addr is not None: mac = self.mac_addr print "Waking MAC: " + mac addr_byte = mac.split(':') hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16), int(addr_byte[1], 16), int(addr_byte[2], 16), int(addr_byte[3], 16), int(addr_byte[4], 16), int(addr_byte[5], 16)) msg = b'\xff' * 6 + hw_addr * 16 socket_instance = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) socket_instance.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) socket_instance.sendto(msg, ('<broadcast>', 9)) socket_instance.close() return True def poweron(self): # Convenience function to switch the TV on and block until it's ready # to accept commands. if self.paired is False: print "You can only call this function once paired with the TV" return False elif self.paired is True: ready = False if self.is_available() is True: # If we're already on, return now. return True self.wakeonlan() for x in range(10): if self.is_available() is True: print "TV now available" return True else: print "Didn't get a response. Trying again in 10 seconds. (Attempt "+str(x+1)+" of 10)" time.sleep(10) if ready is False: print "Couldnt connect in a timely manner. Giving up" return False else: return True def get_client_ip(self): host_ip = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]<|fim▁hole|><|fim▁end|>
return host_ip
<|file_name|>error.rs<|end_file_name|><|fim▁begin|>// CITA // Copyright 2016-2017 Cryptape Technologies LLC. // This program is free software: you can redistribute it // and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any // later version. // This program is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //! jsonrpc errors use super::Value; use serde::de::{Deserialize, Deserializer}; use serde::ser::{Serialize, Serializer}; /// JSONRPC error code #[derive(Debug, PartialEq, Clone)] pub enum ErrorCode { /// Invalid JSON was received by the server. /// An error occurred on the server while parsing the JSON text. ParseError, /// The JSON sent is not a valid Request object. InvalidRequest, /// The method does not exist / is not available. MethodNotFound, /// Invalid method parameter(s). InvalidParams,<|fim▁hole|> /// Reserved for implementation-defined server-errors. ServerError(i64), } impl ErrorCode { /// Returns integer code value pub fn code(&self) -> i64 { match *self { ErrorCode::ParseError => -32700, ErrorCode::InvalidRequest => -32600, ErrorCode::MethodNotFound => -32601, ErrorCode::InvalidParams => -32602, ErrorCode::InternalError => -32603, ErrorCode::ServerError(code) => code, } } /// Returns human-readable description pub fn description(&self) -> String { let desc = match *self { ErrorCode::ParseError => "Parse error", ErrorCode::InvalidRequest => "Invalid request", ErrorCode::MethodNotFound => "Method not found", ErrorCode::InvalidParams => "Invalid params", ErrorCode::InternalError => "Internal error", ErrorCode::ServerError(_) => "Server error", }; desc.to_string() } } impl<'a> Deserialize<'a> for ErrorCode { fn deserialize<D>(deserializer: D) -> Result<ErrorCode, D::Error> where D: Deserializer<'a>, { let v: Value = try!(Deserialize::deserialize(deserializer)); match v.as_i64() { Some(-32700) => Ok(ErrorCode::ParseError), Some(-32600) => Ok(ErrorCode::InvalidRequest), Some(-32601) => Ok(ErrorCode::MethodNotFound), Some(-32602) => Ok(ErrorCode::InvalidParams), Some(-32603) => Ok(ErrorCode::InternalError), Some(code) => Ok(ErrorCode::ServerError(code)), _ => unreachable!(), } } } impl Serialize for ErrorCode { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_i64(self.code()) } } /// Error object as defined in Spec #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] pub struct Error { /// Code pub code: ErrorCode, /// Message pub message: String, /// Optional data #[serde(skip_serializing_if = "Option::is_none")] pub data: Option<Value>, } impl Error { /// Wraps given `ErrorCode` pub fn new(code: ErrorCode) -> Self { Error { message: code.description(), code: code, data: None, } } /// Creates new `ParseError` pub fn parse_error() -> Self { Self::new(ErrorCode::ParseError) } /// Creates new `InvalidRequest` pub fn invalid_request() -> Self { Self::new(ErrorCode::InvalidRequest) } /// Creates new `MethodNotFound` pub fn method_not_found() -> Self { Self::new(ErrorCode::MethodNotFound) } /// Creates new `InvalidParams` pub fn invalid_params<M>(message: M) -> Self where M: Into<String>, { Error { code: ErrorCode::InvalidParams, message: message.into(), data: None, } } /// Creates new `InternalError` pub fn internal_error() -> Self { Self::new(ErrorCode::InternalError) } /// Creates new `InvalidRequest` with invalid version description pub fn invalid_version() -> Self { Error { code: ErrorCode::InvalidRequest, message: "Unsupported JSON-RPC protocol version".to_owned(), data: None, } } pub fn server_error(err_code: i64, err_msg: &str) -> Self { Error { code: ErrorCode::ServerError(err_code), message: err_msg.to_owned(), data: None, } } } use serde_json; impl From<serde_json::Error> for Error { fn from(err: serde_json::Error) -> Error { Error { code: ErrorCode::ParseError, message: err.to_string(), data: Some(Value::Null), } } } // TODO: 对用户更友好的错误提示。错误码提示修改 https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal // 比如可以提示期待3或2个参数,收到4个参数等等 // eg: {"jsonrpc":"2.0","error":{"code":-32602,"message":"unknown field `input`, expected one of `from`, `to`, `gasPrice`, `gas`, `value`, `data`, `nonce`","data":null},"id":1} // {"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid length.","data":null},"id":1} // {"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid format","data":null},"id":1}<|fim▁end|>
/// Internal JSON-RPC error. InternalError,
<|file_name|>isdim.py<|end_file_name|><|fim▁begin|>import os from spinspy import local_data<|fim▁hole|> def isdim(dim): if os.path.isfile('{0:s}{1:s}grid'.format(local_data.path,dim)): return True else: return False<|fim▁end|>
<|file_name|>examples.routes.ts<|end_file_name|><|fim▁begin|>import { Routes, RouterModule } from '@angular/router'; import { ExamplesComponent } from './examples.component'; const routes: Routes = [ { path: '', component: ExamplesComponent, children: [ { path: 'animationexamples', loadChildren: './animations/animations.module#AnimationsModule' }, { path: 'reactiveforms', loadChildren: './reactive-forms/product.module#ReactiveFormsExampleModules' }, { path: 'components', loadChildren: './component/component-home.module#ComponentModule' }, { path: 'directives', loadChildren: './directives/directives.module#DirectivesModule' }, { path: 'uibootstrap', loadChildren: './uibootstrap/uibootstrap.module#UiBootstrapModule' }, { path: 'weather', loadChildren: './weather-search/weather.module#WeatherModule' },<|fim▁hole|> { path: 'texteditor', loadChildren: './text-editor/text-editor.module#TextEditorModule' }, { path: 'markdowneditor', loadChildren: './markdown-editor/markdown-editor.module#MarkdownEditorModule' }, { path: 'stripepayment', loadChildren: './stripe-payment/stripe-payment.module#StripePaymentModule' } ] }, ]; export const routing = RouterModule.forChild(routes);<|fim▁end|>
{ path: 'jquery', loadChildren: './jquery/jquery.module#JqueryModule' }, { path: 'googlemaps', loadChildren: './google-maps/google-maps.module#GoogleMapsModule' },
<|file_name|>km.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pagebreak', 'km', { alt: 'បំបែក​ទំព័រ', toolbar: 'បន្ថែម​ការ​បំបែក​ទំព័រ​មុន​បោះពុម្ព'<|fim▁hole|><|fim▁end|>
} );
<|file_name|>islamic.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of convertdate. # http://github.com/fitnr/convertdate # Licensed under the GPL-v3.0 license: # http://opensource.org/licenses/MIT # Copyright (c) 2016, fitnr <fitnr@fakeisthenewreal> from math import trunc from .utils import ceil, jwday, monthcalendarhelper from . import gregorian EPOCH = 1948439.5 WEEKDAYS = ("al-'ahad", "al-'ithnayn", "ath-thalatha'", "al-'arb`a'", "al-khamis", "al-jum`a", "as-sabt") HAS_29_DAYS = (2, 4, 6, 8, 10) HAS_30_DAYS = (1, 3, 5, 7, 9, 11) def leap(year): '''Is a given year a leap year in the Islamic calendar''' return (((year * 11) + 14) % 30) < 11 def to_jd(year, month, day): '''Determine Julian day count from Islamic date''' return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 1 def from_jd(jd): '''Calculate Islamic date from Julian day''' jd = trunc(jd) + 0.5 year = trunc(((30 * (jd - EPOCH)) + 10646) / 10631) month = min(12, ceil((jd - (29 + to_jd(year, 1, 1))) / 29.5) + 1) day = int(jd - to_jd(year, month, 1)) + 1 return (year, month, day) def from_gregorian(year, month, day): return from_jd(gregorian.to_jd(year, month, day)) def to_gregorian(year, month, day): return gregorian.from_jd(to_jd(year, month, day)) def month_length(year, month):<|fim▁hole|> if month in HAS_30_DAYS or (month == 12 and leap(year)): return 30 return 29 def monthcalendar(year, month): start_weekday = jwday(to_jd(year, month, 1)) monthlen = month_length(year, month) return monthcalendarhelper(start_weekday, monthlen)<|fim▁end|>
<|file_name|>test_switch.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 VMware, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. # import hashlib import mock from neutron.common import constants from neutron.common import exceptions from neutron.plugins.vmware.common import utils from neutron.plugins.vmware.nsxlib import switch as switchlib from neutron.tests.unit import test_api_v2 from neutron.tests.unit.vmware.nsxlib import base _uuid = test_api_v2._uuid class LogicalSwitchesTestCase(base.NsxlibTestCase): def test_create_and_get_lswitches_single(self): tenant_id = 'pippo'<|fim▁hole|> _uuid(), tenant_id, 'fake-switch', transport_zones_config) res_lswitch = switchlib.get_lswitches(self.fake_cluster, lswitch['uuid']) self.assertEqual(len(res_lswitch), 1) self.assertEqual(res_lswitch[0]['uuid'], lswitch['uuid']) def test_create_and_get_lswitches_single_name_exceeds_40_chars(self): tenant_id = 'pippo' transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch(self.fake_cluster, tenant_id, _uuid(), '*' * 50, transport_zones_config) res_lswitch = switchlib.get_lswitches(self.fake_cluster, lswitch['uuid']) self.assertEqual(len(res_lswitch), 1) self.assertEqual(res_lswitch[0]['uuid'], lswitch['uuid']) self.assertEqual(res_lswitch[0]['display_name'], '*' * 40) def test_create_and_get_lswitches_multiple(self): tenant_id = 'pippo' transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] network_id = _uuid() main_lswitch = switchlib.create_lswitch( self.fake_cluster, network_id, tenant_id, 'fake-switch', transport_zones_config, tags=[{'scope': 'multi_lswitch', 'tag': 'True'}]) # Create secondary lswitch second_lswitch = switchlib.create_lswitch( self.fake_cluster, network_id, tenant_id, 'fake-switch-2', transport_zones_config) res_lswitch = switchlib.get_lswitches(self.fake_cluster, network_id) self.assertEqual(len(res_lswitch), 2) switch_uuids = [ls['uuid'] for ls in res_lswitch] self.assertIn(main_lswitch['uuid'], switch_uuids) self.assertIn(second_lswitch['uuid'], switch_uuids) for ls in res_lswitch: if ls['uuid'] == main_lswitch['uuid']: main_ls = ls else: second_ls = ls main_ls_tags = self._build_tag_dict(main_ls['tags']) second_ls_tags = self._build_tag_dict(second_ls['tags']) self.assertIn('multi_lswitch', main_ls_tags) self.assertNotIn('multi_lswitch', second_ls_tags) self.assertIn('quantum_net_id', main_ls_tags) self.assertIn('quantum_net_id', second_ls_tags) self.assertEqual(main_ls_tags['quantum_net_id'], network_id) self.assertEqual(second_ls_tags['quantum_net_id'], network_id) def test_update_lswitch(self): new_name = 'new-name' new_tags = [{'scope': 'new_tag', 'tag': 'xxx'}] transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch(self.fake_cluster, _uuid(), 'pippo', 'fake-switch', transport_zones_config) switchlib.update_lswitch(self.fake_cluster, lswitch['uuid'], new_name, tags=new_tags) res_lswitch = switchlib.get_lswitches(self.fake_cluster, lswitch['uuid']) self.assertEqual(len(res_lswitch), 1) self.assertEqual(res_lswitch[0]['display_name'], new_name) switch_tags = self._build_tag_dict(res_lswitch[0]['tags']) self.assertIn('new_tag', switch_tags) self.assertEqual(switch_tags['new_tag'], 'xxx') def test_update_non_existing_lswitch_raises(self): self.assertRaises(exceptions.NetworkNotFound, switchlib.update_lswitch, self.fake_cluster, 'whatever', 'foo', 'bar') def test_delete_networks(self): transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch(self.fake_cluster, _uuid(), 'pippo', 'fake-switch', transport_zones_config) switchlib.delete_networks(self.fake_cluster, lswitch['uuid'], [lswitch['uuid']]) self.assertRaises(exceptions.NotFound, switchlib.get_lswitches, self.fake_cluster, lswitch['uuid']) def test_delete_non_existing_lswitch_raises(self): self.assertRaises(exceptions.NetworkNotFound, switchlib.delete_networks, self.fake_cluster, 'whatever', ['whatever']) class LogicalPortsTestCase(base.NsxlibTestCase): def _create_switch_and_port(self, tenant_id='pippo', neutron_port_id='whatever', name='name', device_id='device_id'): transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch(self.fake_cluster, _uuid(), tenant_id, 'fake-switch', transport_zones_config) lport = switchlib.create_lport(self.fake_cluster, lswitch['uuid'], tenant_id, neutron_port_id, name, device_id, True) return lswitch, lport def test_create_and_get_port(self): lswitch, lport = self._create_switch_and_port() lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) self.assertEqual(lport['uuid'], lport_res['uuid']) # Try again with relation lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid'], relations='LogicalPortStatus') self.assertEqual(lport['uuid'], lport_res['uuid']) def test_plug_interface(self): lswitch, lport = self._create_switch_and_port() switchlib.plug_vif_interface(self.fake_cluster, lswitch['uuid'], lport['uuid'], 'VifAttachment', 'fake') lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) self.assertEqual(lport['uuid'], lport_res['uuid']) def test_get_port_by_tag(self): lswitch, lport = self._create_switch_and_port() lport2 = switchlib.get_port_by_neutron_tag(self.fake_cluster, lswitch['uuid'], 'whatever') self.assertIsNotNone(lport2) self.assertEqual(lport['uuid'], lport2['uuid']) def test_get_port_by_tag_not_found_with_switch_id_raises_not_found(self): tenant_id = 'pippo' neutron_port_id = 'whatever' transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch( self.fake_cluster, tenant_id, _uuid(), 'fake-switch', transport_zones_config) self.assertRaises(exceptions.NotFound, switchlib.get_port_by_neutron_tag, self.fake_cluster, lswitch['uuid'], neutron_port_id) def test_get_port_by_tag_not_find_wildcard_lswitch_returns_none(self): tenant_id = 'pippo' neutron_port_id = 'whatever' transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] switchlib.create_lswitch( self.fake_cluster, tenant_id, _uuid(), 'fake-switch', transport_zones_config) lport = switchlib.get_port_by_neutron_tag( self.fake_cluster, '*', neutron_port_id) self.assertIsNone(lport) def test_get_port_status(self): lswitch, lport = self._create_switch_and_port() status = switchlib.get_port_status( self.fake_cluster, lswitch['uuid'], lport['uuid']) self.assertEqual(constants.PORT_STATUS_ACTIVE, status) def test_get_port_status_non_existent_raises(self): self.assertRaises(exceptions.PortNotFoundOnNetwork, switchlib.get_port_status, self.fake_cluster, 'boo', 'boo') def test_update_port(self): lswitch, lport = self._create_switch_and_port() switchlib.update_port( self.fake_cluster, lswitch['uuid'], lport['uuid'], 'neutron_port_id', 'pippo2', 'new_name', 'device_id', False) lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) self.assertEqual(lport['uuid'], lport_res['uuid']) self.assertEqual('new_name', lport_res['display_name']) self.assertEqual('False', lport_res['admin_status_enabled']) port_tags = self._build_tag_dict(lport_res['tags']) self.assertIn('os_tid', port_tags) self.assertIn('q_port_id', port_tags) self.assertIn('vm_id', port_tags) def test_create_port_device_id_less_than_40_chars(self): lswitch, lport = self._create_switch_and_port() lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) port_tags = self._build_tag_dict(lport_res['tags']) self.assertEqual('device_id', port_tags['vm_id']) def test_create_port_device_id_more_than_40_chars(self): dev_id = "this_is_a_very_long_device_id_with_lots_of_characters" lswitch, lport = self._create_switch_and_port(device_id=dev_id) lport_res = switchlib.get_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) port_tags = self._build_tag_dict(lport_res['tags']) self.assertNotEqual(len(dev_id), len(port_tags['vm_id'])) def test_get_ports_with_obsolete_and_new_vm_id_tag(self): def obsolete(device_id, obfuscate=False): return hashlib.sha1(device_id).hexdigest() with mock.patch.object(utils, 'device_id_to_vm_id', new=obsolete): dev_id1 = "short-dev-id-1" _, lport1 = self._create_switch_and_port(device_id=dev_id1) dev_id2 = "short-dev-id-2" _, lport2 = self._create_switch_and_port(device_id=dev_id2) lports = switchlib.get_ports(self.fake_cluster, None, [dev_id1]) port_tags = self._build_tag_dict(lports['whatever']['tags']) self.assertNotEqual(dev_id1, port_tags['vm_id']) lports = switchlib.get_ports(self.fake_cluster, None, [dev_id2]) port_tags = self._build_tag_dict(lports['whatever']['tags']) self.assertEqual(dev_id2, port_tags['vm_id']) def test_update_non_existent_port_raises(self): self.assertRaises(exceptions.PortNotFoundOnNetwork, switchlib.update_port, self.fake_cluster, 'boo', 'boo', 'boo', 'boo', 'boo', 'boo', False) def test_delete_port(self): lswitch, lport = self._create_switch_and_port() switchlib.delete_port(self.fake_cluster, lswitch['uuid'], lport['uuid']) self.assertRaises(exceptions.PortNotFoundOnNetwork, switchlib.get_port, self.fake_cluster, lswitch['uuid'], lport['uuid']) def test_delete_non_existent_port_raises(self): lswitch = self._create_switch_and_port()[0] self.assertRaises(exceptions.PortNotFoundOnNetwork, switchlib.delete_port, self.fake_cluster, lswitch['uuid'], 'bad_port_uuid') def test_query_lswitch_ports(self): lswitch, lport = self._create_switch_and_port() switch_port_uuids = [ switchlib.create_lport( self.fake_cluster, lswitch['uuid'], 'pippo', 'qportid-%s' % k, 'port-%s' % k, 'deviceid-%s' % k, True)['uuid'] for k in range(2)] switch_port_uuids.append(lport['uuid']) ports = switchlib.query_lswitch_lports( self.fake_cluster, lswitch['uuid']) self.assertEqual(len(ports), 3) for res_port in ports: self.assertIn(res_port['uuid'], switch_port_uuids)<|fim▁end|>
transport_zones_config = [{'zone_uuid': _uuid(), 'transport_type': 'stt'}] lswitch = switchlib.create_lswitch(self.fake_cluster,
<|file_name|>test_environment.py<|end_file_name|><|fim▁begin|># Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """TestEnvironment classes. These classes abstract away the various setups needed to run the WebDriver java tests in various environments. """ from __future__ import absolute_import import logging import os import sys import chrome_paths import util _THIS_DIR = os.path.abspath(os.path.dirname(__file__)) if util.IsLinux(): sys.path.insert(0, os.path.join(chrome_paths.GetSrc(), 'third_party', 'catapult', 'devil')) from devil.android import device_errors from devil.android import device_utils from devil.android import forwarder sys.path.insert(0, os.path.join(chrome_paths.GetSrc(), 'build', 'android')) import devil_chromium ANDROID_TEST_HTTP_PORT = 2311 ANDROID_TEST_HTTPS_PORT = 2411 _EXPECTATIONS = {} exec(compile(open(os.path.join(_THIS_DIR, 'test_expectations'), "rb").read(), \ os.path.join(_THIS_DIR, 'test_expectations'), 'exec'), _EXPECTATIONS) class BaseTestEnvironment(object): """Manages the environment java tests require to run.""" def __init__(self, chrome_version='HEAD'): """Initializes a desktop test environment. Args: chrome_version: Optionally a chrome version to run the tests against. """ self._chrome_version = chrome_version def GetOS(self): """Name of the OS.""" raise NotImplementedError def GlobalSetUp(self): """Sets up the global test environment state.""" pass def GlobalTearDown(self): """Tears down the global test environment state.""" pass def GetDisabledJavaTestMatchers(self): """Get the list of disabled java test matchers. Returns: List of disabled test matchers, which may contain '*' wildcards. """ return _EXPECTATIONS['GetDisabledTestMatchers'](self.GetOS()) def GetReadyToRunJavaTestMatchers(self): """Get the list of disabled for Chrome java test matchers but which already works. Returns: List of disabled for Chrome java test matchers but which already works. """ return _EXPECTATIONS['GetReadyToRunTestMatchers']() def GetPassedJavaTests(self): """Get the list of passed java tests. Returns: List of passed test names. """ with open(os.path.join(_THIS_DIR, 'java_tests.txt'), 'r') as f: return _EXPECTATIONS['ApplyJavaTestFilter']( self.GetOS(), [t.strip('\n') for t in f.readlines()]) class DesktopTestEnvironment(BaseTestEnvironment): """Manages the environment java tests require to run on Desktop.""" # override def GetOS(self): return util.GetPlatformName() class AndroidTestEnvironment(DesktopTestEnvironment): """Manages the environment java tests require to run on Android.""" def __init__(self, package, chrome_version='HEAD'): super(AndroidTestEnvironment, self).__init__(chrome_version) self._package = package self._device = None self._forwarder = None # override def GlobalSetUp(self): devil_chromium.Initialize() os.putenv('TEST_HTTP_PORT', str(ANDROID_TEST_HTTP_PORT)) os.putenv('TEST_HTTPS_PORT', str(ANDROID_TEST_HTTPS_PORT)) devices = device_utils.DeviceUtils.HealthyDevices() if not devices: raise device_errors.NoDevicesError() elif len(devices) > 1: logging.warning('Multiple devices attached. Using %s.' % devices[0]) self._device = devices[0] forwarder.Forwarder.Map( [(ANDROID_TEST_HTTP_PORT, ANDROID_TEST_HTTP_PORT), (ANDROID_TEST_HTTPS_PORT, ANDROID_TEST_HTTPS_PORT)], self._device) # override def GlobalTearDown(self): if self._device: forwarder.Forwarder.UnmapAllDevicePorts(self._device)<|fim▁hole|> return 'android:%s' % self._package<|fim▁end|>
# override def GetOS(self):
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import re import datetime import logging from urlparse import parse_qsl from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey from mamchecker.hlp import datefmt, last from mamchecker.util import PageBase from google.appengine.ext import ndb def prepare( qs # url query_string (after ?) , skey # start key, filter is filled up with it. # student key normally, but can be other, e.g. school, too. # if a parent belongs to user then all children can be queried , userkey ): '''prepares the perameters for depth_1st >>> #see depth_1st >>> skey = ctxkey(['Sc1', 'Pe1', 'Te1','Cl1','St1']) >>> #qs= "Sc0&*&*&*&*&*" >>> qs= "q~r.be" >>> prepare(qs,skey,None)[0] ['Sc1', 'Pe1', 'Te1', 'Cl1', 'St1', [('query_string', '=', 'r.be')]] >>> qs= ' ' >>> prepare(qs,skey,None)[0] ['Sc1', 'Pe1', 'Te1', 'Cl1', 'St1', []] >>> qs= "1DK&*&d>3" >>> p = prepare(qs,skey,None)[0] ''' @last def filters(x): '''convert to GAE filters from lst is ["<field><operator><value>",...] ~ -> = q = query_string age fields: H = hours, S = seconds, M = minutes, d = days ''' AGES = {'d': 'days', 'H': 'hours', 'M': 'minutes', 'S': 'seconds'} ABBR = {'q': 'query_string'} filters = [] if not isinstance(x, str): return for le in x.split(','): #le = next(iter(x.split(','))) le = le.replace('~', '=') match = re.match(r'(\w+)([=!<>]+)([\w\d\.]+)', le) if match: grps = match.groups() name, op, value = grps if name in ABBR: name = ABBR[name] age = None # le='d<~3' if name in AGES: age = AGES[name] if name in AGES.values(): age = name if age: value = datetime.datetime.now( ) - datetime.timedelta(**{age: int(value)}) name = 'answered' filters.append((name, op, value)) return filters #qs = '' O = problemCtxObjs # q=query, qq=*->[], qqf=filter->gae filter (name,op,value) q = filter(None, [k.strip() for k, v in parse_qsl(qs, True)]) qq = [[] if x == '*' else x for x in q] qqf = [filters() if filters(x) else x for x in qq] # fill up to len(O) delta = len(O) - len(qqf) if delta > 0: ext = [str(v) for k, v in skey.pairs()] extpart = min(len(ext), delta) rest = delta - extpart qqf = ext[:extpart] + [[]] * rest + qqf keys = keysOmit(qqf) obj = keys and keys[-1].get() # parent to start from if obj and obj.userkey == userkey:<|fim▁hole|> else: return qqf, [], O, False, userkey class Page(PageBase): def __init__(self, _request): super(self.__class__, self).__init__(_request) self.table = lambda: depth_1st( * prepare( self.request.query_string, self.request.student.key, self.user and self.user.key)) self.params = { 'table': self.table, 'table_entry': table_entry} def post_response(self): for urlsafe in self.request.get_all('deletee'): k = ndb.Key(urlsafe=urlsafe) k.delete() return self.get_response()<|fim▁end|>
return qqf, keys, O, True
<|file_name|>app.js<|end_file_name|><|fim▁begin|>/** * App * * Root application file. * Load main controllers here. */ define([ "jquery", "modules/connected-devices/index" ], function( $, ConnectedDevices ) { "use strict"; var retriveData = function(callback) { var connected_devices_request = $.getJSON("data/connected-devices.json", { cache: + new Date() }); $.when(connected_devices_request) .then(function(connected_devices_data) { callback(null, connected_devices_data); }, function() { callback(new Error("An error has occurred requesting init data")); }); }, app = {}, connected_devices; /* * * */ app.init = function() { var $app_el = $(".js-app"); if ($app_el.length < 1) { throw new Error("Placeholder element is not available"); } retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } connected_devices = new ConnectedDevices({ el: $app_el.get(0), data: connected_devices_data }); connected_devices.render(); }); return true; }; /* * * */ app.destroy = function() { connected_devices.destroy(); }; /* * * */ app.update = function() { retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } <|fim▁hole|> }); }; return app; });<|fim▁end|>
connected_devices.update({ data: connected_devices_data });
<|file_name|>ph2.py<|end_file_name|><|fim▁begin|>import json import argparse import numpy import sys import copy from astropy.coordinates import SkyCoord from astropy import units import operator class Program(object): def __init__(self, runid="16BP06", pi_login="gladman"): self.config = {"runid": runid, "pi_login": pi_login, "program_configuration": {"mjdates": [], "observing_blocks": [], "observing_groups": [] }} def add_target(self, target): self.config["program_configuration"]["mjdates"].append(target) def add_observing_block(self, observing_block): self.config["program_configuration"]["observing_blocks"].append(observing_block) def add_observing_group(self, observing_group): self.config["program_configuration"]["observing_groups"].append(observing_group) class Target(object): def __init__(self, filename=None): self.config = json.load(open(filename)) @property def token(self): return self.config["identifier"]["client_token"] @property def mag(self): return self.config["moving_target"]["ephemeris_points"][0]["mag"] @property def coordinate(self): return SkyCoord(self.config["moving_target"]["ephemeris_points"][0]["coordinate"]["ra"], self.config["moving_target"]["ephemeris_points"][0]["coordinate"]["dec"], unit='degree') class ObservingBlock(object): def __init__(self, client_token, target_token): self.config = {"identifier": {"client_token": client_token}, "target_identifier": {"client_token": target_token}, "constraint_identifiers": [{"server_token": "C1"}], "instrument_config_identifiers": [{"server_token": "I1"}]} @property def token(self): return self.config["identifier"]["client_token"] class ObservingGroup(object): def __init__(self, client_token): self.config = {"identifier": {"client_token": client_token}, "observing_block_identifiers": []} def add_ob(self, client_token): self.config["observing_block_identifiers"].append({"client_token": client_token}) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('ogname') parser.add_argument('mjdates', nargs='+') args = parser.parse_args() # Break the mjdates into OBs based on their max mag of source in pointing. cuts = numpy.array([23.0, 23.5, 24.0, 24.5, 25.0, 25.5, 26.0, 30.0]) IC_exptimes = [50, 100, 200, 300, 400, 500, 600, 700] program = Program() ob_tokens = [] mags = {} ob_coordinate = {} for filename in args.mjdates: target = Target(filename) program.add_target(target.config) ob_token = "OB-{}-{}".format(target.token, target.mag) ob = ObservingBlock(ob_token, target.token) idx = (target.mag > cuts).sum() + 4 ob.config["instrument_config_identifiers"] = [{"server_token": "I{}".format(idx)}] program.add_observing_block(ob.config) ob_tokens.append(ob_token) mags[ob_token] = target.mag ob_coordinate[ob_token] = target.coordinate sf = lambda x, y: cmp(x.ra, y.ra) order_tokens = sorted(ob_coordinate, cmp=sf, key=ob_coordinate.get) total_itime = 0 ogs = {} scheduled = {} og_idx = 0 while len(scheduled) < len(ob_tokens): og_idx += 1 og_token = "OG_{}_{}_{}".format(args.ogname, og_idx, 0) sys.stdout.write("{}: ".format(og_token)) og = ObservingGroup(og_token) og_coord = None og_itime = 0 for ob_token in order_tokens: if ob_token not in scheduled: if og_coord is None: og_coord = ob_coordinate[ob_token] if ob_coordinate[ob_token].separation(og_coord) > 30 * units.degree: continue og.add_ob(ob_token) scheduled[ob_token] = True sys.stdout.write("{} ".format(ob_token)) sys.stdout.flush() idx = (mags[ob_token] > cuts).sum() print ob_token, mags[ob_token], idx + 4 og_itime += IC_exptimes[idx] + 40 if og_itime > 3000.0: break break total_itime += og_itime sys.stdout.write(" {}s \n".format(og_itime)) program.add_observing_group(og.config) nrepeats = 0 for repeat in range(nrepeats): total_itime += og_itime og_token = "OG_{}_{}_{}".format(args.ogname, og_idx, repeat + 1) og = copy.deepcopy(og) og.config["identifier"]["client_token"] = og_token program.add_observing_group(og.config)<|fim▁hole|><|fim▁end|>
print "Total I-Time: {} hrs".format(total_itime/3600.) json.dump(program.config, open('program.json', 'w'), indent=4, sort_keys=True)
<|file_name|>PairDirectoryFile.java<|end_file_name|><|fim▁begin|>package com.stek101.projectzulu.common.core; /** * For usage see: {@link Pair} */ public class PairDirectoryFile<K, V> { private final K directory; private final V file; public static <K, V> PairDirectoryFile<K, V> createPair(K directory, V file) { return new PairDirectoryFile<K, V>(directory, file); } public PairDirectoryFile(K directory, V file) { this.file = file; this.directory = directory; } public K getDirectory() {<|fim▁hole|> public V getFile() { return file; } @Override public boolean equals(Object object){ if (! (object instanceof PairDirectoryFile)) { return false; } PairDirectoryFile pair = (PairDirectoryFile)object; return directory.equals(pair.directory) && file.equals(pair.file); } @Override public int hashCode(){ return 7 * directory.hashCode() + 13 * file.hashCode(); } }<|fim▁end|>
return directory; }
<|file_name|>Export2Excel.js<|end_file_name|><|fim▁begin|>function generateArray(table) { var out = []; var rows = table.querySelectorAll('tr'); var ranges = []; for (var R = 0; R < rows.length; ++R) { var outRow = []; var row = rows[R]; var columns = row.querySelectorAll('td'); for (var C = 0; C < columns.length; ++C) { var cell = columns[C]; var colspan = cell.getAttribute('colspan'); var rowspan = cell.getAttribute('rowspan'); var cellValue = cell.innerText; if(cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue; //Skip ranges ranges.forEach(function(range) { if(R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) { for(var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null); } }); //Handle Row Span if (rowspan || colspan) { rowspan = rowspan || 1; colspan = colspan || 1; ranges.push({s:{r:R, c:outRow.length},e:{r:R+rowspan-1, c:outRow.length+colspan-1}}); }; //Handle Value outRow.push(cellValue !== "" ? cellValue : null); //Handle Colspan if (colspan) for (var k = 0; k < colspan - 1; ++k) outRow.push(null); } out.push(outRow); } return [out, ranges]; }; function datenum(v, date1904) { if(date1904) v+=1462; var epoch = Date.parse(v); return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000); } function sheet_from_array_of_arrays(data, opts) { var ws = {}; var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0 }}; for(var R = 0; R != data.length; ++R) { for(var C = 0; C != data[R].length; ++C) { if(range.s.r > R) range.s.r = R; if(range.s.c > C) range.s.c = C; if(range.e.r < R) range.e.r = R; if(range.e.c < C) range.e.c = C; var cell = {v: data[R][C] }; if(cell.v == null) continue; var cell_ref = XLSX.utils.encode_cell({c:C,r:R}); if(typeof cell.v === 'number') cell.t = 'n'; else if(typeof cell.v === 'boolean') cell.t = 'b'; else if(cell.v instanceof Date) { cell.t = 'n'; cell.z = XLSX.SSF._table[14]; cell.v = datenum(cell.v); } else cell.t = 's'; ws[cell_ref] = cell; } } if(range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range); return ws; } function Workbook() { if(!(this instanceof Workbook)) return new Workbook(); this.SheetNames = []; this.Sheets = {}; } <|fim▁hole|> var buf = new ArrayBuffer(s.length); var view = new Uint8Array(buf); for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; return buf; } function export_table_to_excel(id) { var theTable = document.getElementById(id); var oo = generateArray(theTable); var ranges = oo[1]; /* original data */ var data = oo[0]; var ws_name = "SheetJS"; var wb = new Workbook(), ws = sheet_from_array_of_arrays(data); /* add ranges to worksheet */ ws['!merges'] = ranges; /* add worksheet to workbook */ wb.SheetNames.push(ws_name); wb.Sheets[ws_name] = ws; var wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:false, type: 'binary'}); saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "test.xlsx") }<|fim▁end|>
function s2ab(s) {
<|file_name|>crossBrowsers.js<|end_file_name|><|fim▁begin|>var crossBrowser = function (browser, x, y) { if (browser === 'Firefox 39') { x = x - 490; y = y + 10; } else if (browser === 'MSIE 10') { x = x - 588.7037353; y = y + 3 - 0.32638931; } else if (browser === 'IE 11') { x = x - 641; y = y + 2.5; } else if (browser === 'Opera 12') { x = x - 500; } <|fim▁hole|> y: y } };<|fim▁end|>
return { x: x,
<|file_name|>qbittorrent_bg.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="bg"> <context> <name>AboutDlg</name> <message> <location filename="../gui/about.ui" line="21"/> <source>About qBittorrent</source> <translation>Относно qBittorrent</translation> </message> <message> <location filename="../gui/about.ui" line="83"/> <source>About</source> <translation>Относно</translation> </message> <message> <location filename="../gui/about.ui" line="128"/> <source>Author</source> <translation>Автор</translation> </message> <message> <location filename="../gui/about.ui" line="216"/> <location filename="../gui/about.ui" line="293"/> <source>Name:</source> <translation>Име:</translation> </message> <message> <location filename="../gui/about.ui" line="240"/> <location filename="../gui/about.ui" line="281"/> <source>Country:</source> <translation>Страна:</translation> </message> <message> <location filename="../gui/about.ui" line="228"/> <location filename="../gui/about.ui" line="312"/> <source>E-mail:</source> <translation>E-mail:</translation> </message> <message> <location filename="../gui/about.ui" line="262"/> <source>Greece</source> <translation>Гърция</translation> </message> <message> <location filename="../gui/about.ui" line="341"/> <source>Current maintainer</source> <translation>Настоящ разработчик</translation> </message> <message> <location filename="../gui/about.ui" line="354"/> <source>Original author</source> <translation>Оригинален автор</translation> </message> <message> <location filename="../gui/about.ui" line="412"/> <source>Libraries</source> <translation>Библиотеки</translation> </message> <message> <location filename="../gui/about.ui" line="424"/> <source>This version of qBittorrent was built against the following libraries:</source> <translation>Тази версия на qBittorrent бе изградена с ползването на следните библиотеки:</translation> </message> <message> <location filename="../gui/about.ui" line="184"/> <source>France</source> <translation>Франция</translation> </message> <message> <location filename="../gui/about.ui" line="382"/> <source>Translation</source> <translation>Превод</translation> </message> <message> <location filename="../gui/about.ui" line="399"/> <source>License</source> <translation>Лиценз</translation> </message> <message> <location filename="../gui/about.ui" line="365"/> <source>Thanks to</source> <translation>Благодарим на</translation> </message> </context> <context> <name>AddNewTorrentDialog</name> <message> <location filename="../gui/addnewtorrentdialog.ui" line="29"/> <source>Save as</source> <translation>Съхрани като</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="53"/> <source>Browse...</source> <translation>Преглед...</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="62"/> <source>Set as default save path</source> <translation>Определи като път за съхраняване по подразбиране</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="72"/> <source>Never show again</source> <translation>Не показвай никога повече</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="89"/> <source>Torrent settings</source> <translation>Настройки на торента</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="95"/> <source>Start torrent</source> <translation>Стартирай торента</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="107"/> <source>Label:</source> <translation>Етикет:</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="126"/> <source>Skip hash check</source> <translation>Прескочи проверката на парчетата</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="136"/> <source>Torrent Information</source> <translation>Информация за торента</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="144"/> <source>Size:</source> <translation>Размер:</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="158"/> <source>Comment:</source> <translation>Коментар:</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="172"/> <source>Date:</source> <translation>Дата:</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="186"/> <source>Info Hash:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="277"/> <source>Normal</source> <translation>Нормален</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="282"/> <source>High</source> <translation>Висок</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="287"/> <source>Maximum</source> <translation>Максимален</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.ui" line="292"/> <source>Do not download</source> <translation>Не сваляй</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="192"/> <location filename="../gui/addnewtorrentdialog.cpp" line="643"/> <source>I/O Error</source> <translation>Грешка на Вход/Изход</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="192"/> <source>The torrent file does not exist.</source> <translation>Торент файла не съществува.</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="207"/> <source>Invalid torrent</source> <translation>Невалиден торент</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="207"/> <source>Failed to load the torrent: %1</source> <translation>Неуспешно зареждане на торент:%1</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="213"/> <location filename="../gui/addnewtorrentdialog.cpp" line="236"/> <source>Already in download list</source> <translation>Вече е в списъка за сваляне</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="213"/> <source>Torrent is already in download list. Merging trackers.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="236"/> <source>Magnet link is already in download list. Merging trackers.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="317"/> <source>Free disk space: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="644"/> <source>Unknown error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="660"/> <source>Not Available</source> <comment>This comment is unavailable</comment> <translation>Не е налично</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="661"/> <source>Not Available</source> <comment>This date is unavailable</comment> <translation>Не е налично</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="670"/> <source>Not available</source> <translation>Не е наличен</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="230"/> <source>Invalid magnet link</source> <translation>Невалидна магнитна връзка</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="230"/> <source>This magnet link was not recognized</source> <translation>Тази магнитна връзка не се разпознава</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="243"/> <source>Magnet link</source> <translation>Магнитна връзка</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="253"/> <source>Retrieving metadata...</source> <translation>Извличане на метаданни...</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="315"/> <source>Not Available</source> <comment>This size is unavailable.</comment> <translation>Не е наличен</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="346"/> <location filename="../gui/addnewtorrentdialog.cpp" line="354"/> <location filename="../gui/addnewtorrentdialog.cpp" line="356"/> <source>Choose save path</source> <translation>Избери път за съхранение</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="406"/> <source>Rename the file</source> <translation>Преименувай файла</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="407"/> <source>New name:</source> <translation>Ново име:</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="411"/> <location filename="../gui/addnewtorrentdialog.cpp" line="436"/> <source>The file could not be renamed</source> <translation>Файлът не може да се преименува</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="412"/> <source>This file name contains forbidden characters, please choose a different one.</source> <translation>Името на файла съдържа забранени символи, моля изберете различно име.</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="437"/> <location filename="../gui/addnewtorrentdialog.cpp" line="472"/> <source>This name is already in use in this folder. Please use a different name.</source> <translation>Това име вече съществува в тази папка. Моля, ползвайте различно име.</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="471"/> <source>The folder could not be renamed</source> <translation>Папката не може да се преименува</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="529"/> <source>Rename...</source> <translation>Преименувай...</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="533"/> <source>Priority</source> <translation>Предимство</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="637"/> <source>Parsing metadata...</source> <translation>Проверка на метаданните...</translation> </message> <message> <location filename="../gui/addnewtorrentdialog.cpp" line="641"/> <source>Metadata retrieval complete</source> <translation>Извличането на метаданни завърши</translation> </message> </context> <context> <name>AdvancedSettings</name> <message> <location filename="../gui/advancedsettings.h" line="191"/> <source>Disk write cache size</source> <translation>Размер на записан дисков кеш</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="172"/> <source> MiB</source> <translation>МБ</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="211"/> <source>Outgoing ports (Min) [0: Disabled]</source> <translation>Изходен порт (Мин) [0: Изключен]</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="216"/> <source>Outgoing ports (Max) [0: Disabled]</source> <translation>Изходен порт (Макс) [0: Изключен]</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="222"/> <source>Recheck torrents on completion</source> <translation>Провери торентите при завършване</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="228"/> <source>Transfer list refresh interval</source> <translation>Интервал на обновяване на списъка за трансфер</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="227"/> <source> ms</source> <comment> milliseconds</comment> <translation>мс</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="53"/> <source>Setting</source> <translation>Настройка</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="53"/> <source>Value</source> <comment>Value set for this setting</comment> <translation>Стойност</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="170"/> <source> (auto)</source> <translation>(автоматично)</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="196"/> <source> s</source> <comment> seconds</comment> <translation>с</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="197"/> <source>Disk cache expiry interval</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/advancedsettings.h" line="200"/> <source>Enable OS cache</source> <translation>Включи кеширане от ОС</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="205"/> <source> m</source> <comment> minutes</comment> <translation>м</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="231"/> <source>Resolve peer countries (GeoIP)</source> <translation>Намери държавата на двойката (GeoIP)</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="234"/> <source>Resolve peer host names</source> <translation>Намери имената на получаващата двойка</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="239"/> <source>Maximum number of half-open connections [0: Disabled]</source> <translation>Максимален брой полу-отворени връзки [0: Изключен] </translation> </message> <message> <location filename="../gui/advancedsettings.h" line="242"/> <source>Strict super seeding</source> <translation>Стриктен режим на супер-даване</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="262"/> <source>Network Interface (requires restart)</source> <translation>Интерфейс на Мрежата (изисква рестарт)</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="265"/> <source>Listen on IPv6 address (requires restart)</source> <translation>Четене на IPv6 адреса (изисква рестартиране)</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="293"/> <source>Confirm torrent recheck</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/advancedsettings.h" line="296"/> <source>Exchange trackers with other peers</source> <translation>Обмен на тракери с други двойки</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="299"/> <source>Always announce to all trackers</source> <translation>Винаги предлагай на всички тракери</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="244"/> <source>Any interface</source> <comment>i.e. Any network interface</comment> <translation>Произволен интерфейс</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="206"/> <source>Save resume data interval</source> <comment>How often the fastresume file is saved.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/advancedsettings.h" line="268"/> <source>IP Address to report to trackers (requires restart)</source> <translation>IP адрес за информиране на тракери (изисква рестарт)</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="271"/> <source>Display program on-screen notifications</source> <translation>Покажи уведомленията на програмата на екрана</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="274"/> <source>Enable embedded tracker</source> <translation>Включи вградения тракер</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="279"/> <source>Embedded tracker port</source> <translation>Вграден порт на тракер</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="282"/> <source>Check for software updates</source> <translation>Провери за обновяване на програмата</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="286"/> <source>Use system icon theme</source> <translation>Ползвай темата на системната икона</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="290"/> <source>Confirm torrent deletion</source> <translation>Потвърди изтриването на торента</translation> </message> <message> <location filename="../gui/advancedsettings.h" line="219"/> <source>Ignore transfer limits on local network</source> <translation>Игнорирай ограниченията за сваляне на локалната мрежа </translation> </message> </context> <context> <name>Application</name> <message> <location filename="../app/application.cpp" line="165"/> <source>Information</source> <translation>Информация</translation> </message> <message> <location filename="../app/application.cpp" line="166"/> <source>To control qBittorrent, access the Web UI at http://localhost:%1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/application.cpp" line="167"/> <source>The Web UI administrator user name is: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/application.cpp" line="170"/> <source>The Web UI administrator password is still the default one: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/application.cpp" line="171"/> <source>This is a security risk, please consider changing your password from program preferences.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/application.cpp" line="343"/> <source>Saving torrent progress...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomatedRssDownloader</name> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="14"/> <source>Automated RSS Downloader</source> <translation>Автоматичен RSS сваляч</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="26"/> <source>Enable the automated RSS downloader</source> <translation>Включи автоматичния RSS сваляч</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="48"/> <source>Download rules</source> <translation>Правила за сваляне</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="123"/> <source>Rule definition</source> <translation>Дефиниция на правилото</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="138"/> <source>Must contain:</source> <translation>Да съдържа:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="180"/> <source>Must not contain:</source> <translation>Да не съдържа:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="129"/> <source>Use regular expressions</source> <translation>Ползвайте стандартни изрази</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="494"/> <source>Import...</source> <translation>Внос...</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="501"/> <source>Export...</source> <translation>Износ...</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="272"/> <source>Assign label:</source> <translation>Прикачи етикет:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="254"/> <source>Episode filter:</source> <translation>Филтър на епизод:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="291"/> <source>Save to a different directory</source> <translation>Съхрани в друга директория</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="303"/> <source>Save to:</source> <translation>Съхрани в:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="338"/> <source>Ignore subsequent matches for (0 to disable)</source> <comment>... X days</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="361"/> <source> days</source> <translation>дни</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="402"/> <source>Add Paused:</source> <translation>Добави поставените на пауза:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="416"/> <source>Use global setting</source> <translation>Използвай общите настройки</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="421"/> <source>Always add paused</source> <translation>Винаги добавяй поставените на пауза</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="426"/> <source>Never add paused</source> <translation>Никога не добавяй поставените на пауза</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="447"/> <source>Apply rule to feeds:</source> <translation>Приложи правилото към канали:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.ui" line="469"/> <source>Matching RSS articles</source> <translation>Съответстващи RSS статии</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="76"/> <source>Matches articles based on episode filter.</source> <translation>Намерени статии, базирани на епизодичен филтър.</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="76"/> <source>Example: </source> <translation>Пример:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="77"/> <source> will match 2, 5, 8 through 15, 30 and onward episodes of season one</source> <comment>example X will match</comment> <translation>ще търси резултати 2, 5, 8 през 15, 30 и повече епизода на първи сезон</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="78"/> <source>Episode filter rules: </source> <translation>Правила на епизодния филтър:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="78"/> <source>Season number is a mandatory non-zero value</source> <translation>Номерът на сезона трябва да бъде със стойност, различна от нула</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="79"/> <source>Episode number is a mandatory non-zero value</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="80"/> <source>Filter must end with semicolon</source> <translation>Филтърът трябва да завършва с точка и запетая</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="81"/> <source>Three range types for episodes are supported: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="82"/> <source>Single number: &lt;b&gt;1x25;&lt;/b&gt; matches episode 25 of season one</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="83"/> <source>Normal range: &lt;b&gt;1x25-40;&lt;/b&gt; matches episodes 25 through 40 of season one</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="84"/> <source>Infinite range: &lt;b&gt;1x25-;&lt;/b&gt; matches episodes 25 and upward of season one</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="261"/> <source>Last match: </source> <translation>Последен резултат:</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="263"/> <source> days ago.</source> <translation>дни по- рано.</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="265"/> <source>Unknown</source> <translation>Неизвестен</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="358"/> <source>New rule name</source> <translation>Име на ново правила</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="358"/> <source>Please type the name of the new download rule.</source> <translation>Моля, въведете името на новото правило за сваляне.</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="362"/> <location filename="../gui/rss/automatedrssdownloader.cpp" line="480"/> <source>Rule name conflict</source> <translation>Конфликт в имената на правилата</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="362"/> <location filename="../gui/rss/automatedrssdownloader.cpp" line="480"/> <source>A rule with this name already exists, please choose another name.</source> <translation>Правило с това име вече съществува, моля изберете друго име.</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="380"/> <source>Are you sure you want to remove the download rule named %1?</source> <translation>Сигурни ли сте че искате да изтриете правилото с име %1?</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="382"/> <source>Are you sure you want to remove the selected download rules?</source> <translation>Сигурни ли сте че искате да изтриете избраните правила?</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="383"/> <source>Rule deletion confirmation</source> <translation>Потвърждение за изтриване на правилото</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="399"/> <source>Destination directory</source> <translation>Директория цел</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="407"/> <source>Invalid action</source> <translation>Невалидно действие</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="407"/> <source>The list is empty, there is nothing to export.</source> <translation>Списъка е празен, няма какво да се експортира.</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="411"/> <source>Where would you like to save the list?</source> <translation>Къде искате да се съхрани списъка?</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="411"/> <source>Rules list (*.rssrules)</source> <translation>Листа с правила (*.rssrules)</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="416"/> <source>I/O Error</source> <translation>В/И Грешка</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="416"/> <source>Failed to create the destination file</source> <translation>Неуспешно създавене на файла-получател</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="424"/> <source>Please point to the RSS download rules file</source> <translation>Моля посочете файла с правила за сваляне на RSS</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="424"/> <source>Rules list</source> <translation>Списък с правила</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="428"/> <source>Import Error</source> <translation>Грешка при внос</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="428"/> <source>Failed to import the selected rules file</source> <translation>Неуспешно внасяне на избрания файл с правила</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="439"/> <source>Add new rule...</source> <translation>Добави ново правило...</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="445"/> <source>Delete rule</source> <translation>Изтрий правилото</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="447"/> <source>Rename rule...</source> <translation>Преименувай правилото...</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="449"/> <source>Delete selected rules</source> <translation>Изтрий избраните правила</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="476"/> <source>Rule renaming</source> <translation>Преименуване на правилото</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="476"/> <source>Please type the new rule name</source> <translation>Моля напишете името на новото правило</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="578"/> <source>Regex mode: use Perl-like regular expressions</source> <translation>Режим регулярни изрази: ползвайте подобни на Perl регулярни изрази</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="582"/> <source>Wildcard mode: you can use&lt;ul&gt;&lt;li&gt;? to match any single character&lt;/li&gt;&lt;li&gt;* to match zero or more of any characters&lt;/li&gt;&lt;li&gt;Whitespaces count as AND operators&lt;/li&gt;&lt;/ul&gt;</source> <translation>Режим Жокер: можете да ползвате&lt;ul&gt;&lt;li&gt;? за заместване на всеки единичен знак&lt;/li&gt;&lt;li&gt;* за заместване от нула до много различни знаци&lt;/li&gt;&lt;li&gt;Паузите се броят като оператор AND&lt;/li&gt;&lt;/ul&gt;</translation> </message> <message> <location filename="../gui/rss/automatedrssdownloader.cpp" line="584"/> <source>Wildcard mode: you can use&lt;ul&gt;&lt;li&gt;? to match any single character&lt;/li&gt;&lt;li&gt;* to match zero or more of any characters&lt;/li&gt;&lt;li&gt;| is used as OR operator&lt;/li&gt;&lt;/ul&gt;</source> <translation>Режим Жокер: можете да ползвате&lt;ul&gt;&lt;li&gt;? за заместване на всеки отделен знак&lt;/li&gt;&lt;li&gt;* за заместване на нула или много знаци&lt;/li&gt;&lt;li&gt;| се ползва като OR оператор&lt;/li&gt;&lt;/ul&gt;</translation> </message> </context> <context> <name>CookiesDlg</name> <message> <location filename="../gui/rss/cookiesdlg.ui" line="14"/> <source>Cookies management</source> <translation>Управление на бисквитки</translation> </message> <message> <location filename="../gui/rss/cookiesdlg.ui" line="36"/> <source>Key</source> <extracomment>As in Key/Value pair</extracomment> <translation>Клавиш</translation> </message> <message> <location filename="../gui/rss/cookiesdlg.ui" line="41"/> <source>Value</source> <extracomment>As in Key/Value pair</extracomment> <translation>Стойност</translation> </message> <message> <location filename="../gui/rss/cookiesdlg.cpp" line="48"/> <source>Common keys for cookies are: &apos;%1&apos;, &apos;%2&apos;. You should get this information from your Web browser preferences.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DNSUpdater</name> <message> <location filename="../core/dnsupdater.cpp" line="192"/> <source>Your dynamic DNS was successfully updated.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="196"/> <source>Dynamic DNS error: The service is temporarily unavailable, it will be retried in 30 minutes.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="205"/> <source>Dynamic DNS error: hostname supplied does not exist under specified account.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="210"/> <source>Dynamic DNS error: Invalid username/password.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="215"/> <source>Dynamic DNS error: qBittorrent was blacklisted by the service, please report a bug at http://bugs.qbittorrent.org.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="221"/> <source>Dynamic DNS error: %1 was returned by the service, please report a bug at http://bugs.qbittorrent.org.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="227"/> <source>Dynamic DNS error: Your username was blocked due to abuse.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="248"/> <source>Dynamic DNS error: supplied domain name is invalid.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="259"/> <source>Dynamic DNS error: supplied username is too short.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/dnsupdater.cpp" line="270"/> <source>Dynamic DNS error: supplied password is too short.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DeletionConfirmationDlg</name> <message> <location filename="../gui/deletionconfirmationdlg.h" line="48"/> <source>Are you sure you want to delete &quot;%1&quot; from the transfer list?</source> <comment>Are you sure you want to delete &quot;ubuntu-linux-iso&quot; from the transfer list?</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/deletionconfirmationdlg.h" line="50"/> <source>Are you sure you want to delete these %1 torrents from the transfer list?</source> <comment>Are you sure you want to delete these 5 torrents from the transfer list?</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>DownloadThread</name> <message> <location filename="../core/downloadthread.cpp" line="165"/> <location filename="../core/downloadthread.cpp" line="169"/> <source>I/O Error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="259"/> <source>The remote host name was not found (invalid hostname)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="261"/> <source>The operation was canceled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="263"/> <source>The remote server closed the connection prematurely, before the entire reply was received and processed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="265"/> <source>The connection to the remote server timed out</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="267"/> <source>SSL/TLS handshake failed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="269"/> <source>The remote server refused the connection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="271"/> <source>The connection to the proxy server was refused</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="273"/> <source>The proxy server closed the connection prematurely</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="275"/> <source>The proxy host name was not found</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="277"/> <source>The connection to the proxy timed out or the proxy did not reply in time to the request sent</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="279"/> <source>The proxy requires authentication in order to honour the request but did not accept any credentials offered</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="281"/> <source>The access to the remote content was denied (401)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="283"/> <source>The operation requested on the remote content is not permitted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="285"/> <source>The remote content was not found at the server (404)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="287"/> <source>The remote server requires authentication to serve the content but the credentials provided were not accepted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="289"/> <source>The Network Access API cannot honor the request because the protocol is not known</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="291"/> <source>The requested operation is invalid for this protocol</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="293"/> <source>An unknown network-related error was detected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="295"/> <source>An unknown proxy-related error was detected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="297"/> <source>An unknown error related to the remote content was detected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="299"/> <source>A breakdown in protocol was detected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/downloadthread.cpp" line="301"/> <source>Unknown error</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ExecutionLog</name> <message> <location filename="../gui/executionlog.ui" line="27"/> <source>General</source> <translation>Общи</translation> </message> <message> <location filename="../gui/executionlog.ui" line="33"/> <source>Blocked IPs</source> <translation>Блокирани IP</translation> </message> <message> <location filename="../gui/executionlog.cpp" line="102"/> <source>&lt;font color=&apos;red&apos;&gt;%1&lt;/font&gt; was blocked</source> <comment>x.y.z.w was blocked</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/executionlog.cpp" line="104"/> <source>&lt;font color=&apos;red&apos;&gt;%1&lt;/font&gt; was blocked %2</source> <comment>x.y.z.w was blocked</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/executionlog.cpp" line="107"/> <source>&lt;font color=&apos;red&apos;&gt;%1&lt;/font&gt; was banned</source> <comment>x.y.z.w was banned</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>FeedListWidget</name> <message> <location filename="../gui/rss/feedlistwidget.cpp" line="41"/> <source>RSS feeds</source> <translation>RSS канали</translation> </message> <message> <location filename="../gui/rss/feedlistwidget.cpp" line="43"/> <source>Unread</source> <translation>Непрочетен</translation> </message> </context> <context> <name>HttpServer</name> <message> <location filename="../webui/extra_translations.h" line="36"/> <source>File</source> <translation>Файл</translation> </message> <message> <location filename="../webui/extra_translations.h" line="37"/> <source>Edit</source> <translation>Редактирай</translation> </message> <message> <location filename="../webui/extra_translations.h" line="38"/> <source>Help</source> <translation>Помощ</translation> </message> <message> <location filename="../webui/extra_translations.h" line="40"/> <source>Download Torrents from their URL or Magnet link</source> <translation>Сваляне на Торенти от техния URL или Magnet link</translation> </message> <message> <location filename="../webui/extra_translations.h" line="41"/> <source>Only one link per line</source> <translation>Само един линк на реда</translation> </message> <message> <location filename="../webui/extra_translations.h" line="42"/> <source>Download local torrent</source> <translation>Сваляне на местен торент</translation> </message> <message> <location filename="../webui/extra_translations.h" line="43"/> <source>Download</source> <translation>Свали</translation> </message> <message> <location filename="../webui/extra_translations.h" line="52"/> <source>Maximum number of connections limit must be greater than 0 or disabled.</source> <translation>Ограничението за максимален брой връзки трябва да е по-голямо от 0 или изключено.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="53"/> <source>Maximum number of connections per torrent limit must be greater than 0 or disabled.</source> <translation>Ограничението за максимален брой връзки на торент трябва да е по-голямо от 0 или изключено.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="54"/> <source>Maximum number of upload slots per torrent limit must be greater than 0 or disabled.</source> <translation>Ограничението за максимален брой слотове на торент трябва да е по-голямо от 0 или изключено.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="55"/> <source>Unable to save program preferences, qBittorrent is probably unreachable.</source> <translation>Не мога да съхраня предпочитанията за програмата, qBittorrent е вероятно недостъпен.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="56"/> <source>Language</source> <translation>Език</translation> </message> <message> <location filename="../webui/extra_translations.h" line="57"/> <source>The port used for incoming connections must be between 1 and 65535.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="58"/> <source>The port used for the Web UI must be between 1 and 65535.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="68"/> <source>Unable to log in, qBittorrent is probably unreachable.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="69"/> <source>Invalid Username or Password.</source> <translation>Невалидно потребителско име или парола.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="70"/> <source>Password</source> <translation>Парола</translation> </message> <message> <location filename="../webui/extra_translations.h" line="71"/> <source>Login</source> <translation>Вход</translation> </message> <message> <location filename="../webui/extra_translations.h" line="72"/> <source>Upload Failed!</source> <translation>Качването е неуспешно!</translation> </message> <message> <location filename="../webui/extra_translations.h" line="73"/> <source>Original authors</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="74"/> <source>Upload limit:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="75"/> <source>Download limit:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="76"/> <source>Apply</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="77"/> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="78"/> <source>Upload Torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="79"/> <source>All</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="80"/> <source>Downloading</source> <translation type="unfinished">Сваляне</translation> </message> <message> <location filename="../webui/extra_translations.h" line="81"/> <source>Seeding</source> <translation type="unfinished">Споделяне</translation> </message> <message> <location filename="../webui/extra_translations.h" line="82"/> <source>Completed</source> <translation type="unfinished">Приключено</translation> </message> <message> <location filename="../webui/extra_translations.h" line="83"/> <source>Resumed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="84"/> <source>Paused</source> <translation type="unfinished">Пауза</translation> </message> <message> <location filename="../webui/extra_translations.h" line="85"/> <source>Active</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="86"/> <source>Inactive</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="90"/> <source>Downloaded</source> <comment>Is the file downloaded or not?</comment> <translation>Свалени</translation> </message> <message> <location filename="../webui/extra_translations.h" line="39"/> <source>Logout</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="44"/> <source>Are you sure you want to delete the selected torrents from the transfer list?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="45"/> <source>Global upload rate limit must be greater than 0 or disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="46"/> <source>Global download rate limit must be greater than 0 or disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="47"/> <source>Alternative upload rate limit must be greater than 0 or disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="48"/> <source>Alternative download rate limit must be greater than 0 or disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="49"/> <source>Maximum active downloads must be greater than -1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="50"/> <source>Maximum active uploads must be greater than -1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="51"/> <source>Maximum active torrents must be greater than -1.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/extra_translations.h" line="59"/> <source>The Web UI username must be at least 3 characters long.</source> <translation>Потребителското име на Web UI трябва да е поне от три букви.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="60"/> <source>The Web UI password must be at least 3 characters long.</source> <translation>Паролата на Web UI трябва да е поне от три букви.</translation> </message> <message> <location filename="../webui/extra_translations.h" line="61"/> <source>Save</source> <translation>Съхрани</translation> </message> <message> <location filename="../webui/extra_translations.h" line="62"/> <source>qBittorrent client is not reachable</source> <translation>qBittorrent клиента е недостъпен</translation> </message> <message> <location filename="../webui/extra_translations.h" line="63"/> <source>HTTP Server</source> <translation>Сървър HTTP</translation> </message> <message> <location filename="../webui/extra_translations.h" line="64"/> <source>The following parameters are supported:</source> <translation>Поддържат се следните параметри:</translation> </message> <message> <location filename="../webui/extra_translations.h" line="65"/> <source>Torrent path</source> <translation>Торент път</translation> </message> <message> <location filename="../webui/extra_translations.h" line="66"/> <source>Torrent name</source> <translation>Торент име</translation> </message> <message> <location filename="../webui/extra_translations.h" line="67"/> <source>qBittorrent has been shutdown.</source> <translation>qBittorrent се изключва.</translation> </message> </context> <context> <name>LabelFiltersList</name> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="179"/> <source>All (0)</source> <comment>this is for the label filter</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="182"/> <source>Unlabeled (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="204"/> <location filename="../gui/transferlistfilterswidget.cpp" line="250"/> <source>All (%1)</source> <comment>this is for the label filter</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="207"/> <location filename="../gui/transferlistfilterswidget.cpp" line="225"/> <location filename="../gui/transferlistfilterswidget.cpp" line="253"/> <location filename="../gui/transferlistfilterswidget.cpp" line="258"/> <source>Unlabeled (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="229"/> <location filename="../gui/transferlistfilterswidget.cpp" line="266"/> <source>%1 (%2)</source> <comment>label_name (10)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="317"/> <source>Add label...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="321"/> <source>Remove label</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="322"/> <source>Remove unused labels</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="324"/> <source>Resume torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="325"/> <source>Pause torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="326"/> <source>Delete torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="353"/> <source>New Label</source> <translation type="unfinished">Нов етикет</translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="353"/> <source>Label:</source> <translation type="unfinished">Етикет:</translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="359"/> <source>Invalid label name</source> <translation type="unfinished">Невалидно име на етикет</translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="359"/> <source>Please don&apos;t use any special characters in the label name.</source> <translation type="unfinished">Моля, не ползвайте специални символи в името на етикета.</translation> </message> </context> <context> <name>LineEdit</name> <message> <location filename="../gui/lineedit/src/lineedit.cpp" line="30"/> <source>Clear the text</source> <translation>Изтрий текста</translation> </message> </context> <context> <name>LogListWidget</name> <message> <location filename="../gui/loglistwidget.cpp" line="47"/> <source>Copy</source> <translation>Копирай</translation> </message> <message> <location filename="../gui/loglistwidget.cpp" line="48"/> <source>Clear</source> <translation>Изчистване</translation> </message> </context> <context> <name>MainWindow</name> <message> <location filename="../gui/mainwindow.ui" line="37"/> <source>&amp;Edit</source> <translation>&amp;Редактирай</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="60"/> <source>&amp;Tools</source> <translation>&amp;Инструменти</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="80"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="50"/> <source>&amp;Help</source> <translation>&amp;Помощ</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="64"/> <source>On Downloads &amp;Done</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="90"/> <source>&amp;View</source> <translation>&amp;Оглед</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="161"/> <source>&amp;Options...</source> <translation>&amp;Опции...</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="174"/> <source>&amp;Resume</source> <translation>&amp;Пауза</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="206"/> <source>Torrent &amp;Creator</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="211"/> <source>Set Upload Limit...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="216"/> <source>Set Download Limit...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="226"/> <source>Set Global Download Limit...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="231"/> <source>Set Global Upload Limit...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="236"/> <source>Minimum Priority</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="244"/> <source>Top Priority</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="252"/> <source>Decrease Priority</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="260"/> <source>Increase Priority</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="271"/> <location filename="../gui/mainwindow.ui" line="274"/> <source>Alternative Speed Limits</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="282"/> <source>&amp;Top Toolbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="285"/> <source>Display Top Toolbar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="293"/> <source>S&amp;peed in Title Bar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="296"/> <source>Show Transfer Speed in Title Bar</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="304"/> <source>&amp;RSS Reader</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="312"/> <source>Search &amp;Engine</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="317"/> <source>L&amp;ock qBittorrent</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="331"/> <source>&amp;Import Existing Torrent...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="334"/> <source>Import Torrent...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="339"/> <source>Do&amp;nate!</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="347"/> <source>R&amp;esume All</source> <translation>П&amp;ауза Всички</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="360"/> <source>&amp;Log</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="371"/> <source>&amp;Exit qBittorrent</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="379"/> <source>&amp;Suspend System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="387"/> <source>&amp;Hibernate System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="395"/> <source>S&amp;hutdown System</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="403"/> <source>&amp;Disabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="418"/> <source>&amp;Statistics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="423"/> <source>Check for Updates</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="426"/> <source>Check for Program Updates</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="169"/> <source>&amp;About</source> <translation>&amp;Относно</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="156"/> <source>Exit</source> <translation>Изход</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="182"/> <source>&amp;Pause</source> <translation>&amp;Пауза</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="190"/> <source>&amp;Delete</source> <translation>&amp;Изтрий</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="352"/> <source>P&amp;ause All</source> <translation>П&amp;ауза Всички</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="145"/> <source>&amp;Add Torrent File...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="148"/> <source>Open</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="153"/> <source>E&amp;xit</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="164"/> <source>Options</source> <translation type="unfinished">Опции</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="177"/> <source>Resume</source> <translation type="unfinished">Продължи</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="185"/> <source>Pause</source> <translation type="unfinished">Пауза</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="193"/> <source>Delete</source> <translation type="unfinished">Изтрий</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="201"/> <source>Open URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="221"/> <source>&amp;Documentation</source> <translation>&amp;Документация</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="320"/> <source>Lock</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="408"/> <location filename="../gui/mainwindow.cpp" line="1365"/> <source>Show</source> <translation>Покажи</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1552"/> <source>Check for program updates</source> <translation>Проверка за обновления на програмата</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="323"/> <source>Lock qBittorrent</source> <translation>Заключи qBittorrent</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="198"/> <source>Add Torrent &amp;Link...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.ui" line="342"/> <source>If you like qBittorrent, please donate!</source> <translation>Ако ви харесва qBittorrent, моля дарете!</translation> </message> <message> <location filename="../gui/mainwindow.ui" line="363"/> <location filename="../gui/mainwindow.cpp" line="1580"/> <source>Execution Log</source> <translation>Изпълнение на Запис</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="488"/> <source>Clear the password</source> <translation>Изчистване на паролата</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="192"/> <source>Filter torrent list...</source> <translation>Филтриране на торент от списъка...</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="162"/> <source>&amp;Set Password</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="164"/> <source>&amp;Clear Password</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="209"/> <source>Transfers</source> <translation>Трансфери</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="353"/> <source>Torrent file association</source> <translation>Свързване на торент файла</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="354"/> <source>qBittorrent is not the default application to open torrent files or Magnet links. Do you want to associate qBittorrent to torrent files and Magnet links?</source> <translation>qBittorrent не е вашето приложение по подразбиране за отваряне на файлове торент или Магнитни връзки. Искате ли да свържете qBittorrent към файлове торент и Магнитни връзки?</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="385"/> <source>Icons Only</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="387"/> <source>Text Only</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="389"/> <source>Text Alongside Icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="391"/> <source>Text Under Icons</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="393"/> <source>Follow System Style</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="473"/> <location filename="../gui/mainwindow.cpp" line="500"/> <location filename="../gui/mainwindow.cpp" line="807"/> <source>UI lock password</source> <translation>Парола за потребителски интерфейс</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="473"/> <location filename="../gui/mainwindow.cpp" line="500"/> <location filename="../gui/mainwindow.cpp" line="807"/> <source>Please type the UI lock password:</source> <translation>Моля въведете парола за заключване на потребителския интерфейс:</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="477"/> <source>The password should contain at least 3 characters</source> <translation>Паролата трябва да съдържа поне 3 символа</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="482"/> <source>Password update</source> <translation>Обновяване на парола</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="482"/> <source>The UI lock password has been successfully updated</source> <translation>Паролата за заключване на потребителския интерфейс бе успешно обновена</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="488"/> <source>Are you sure you want to clear the password?</source> <translation>Наистина ли искате да изчистите паролата?</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="540"/> <source>Search</source> <translation>Търси</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="551"/> <source>Transfers (%1)</source> <translation>Трансфери (%1)</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="645"/> <source>Download completion</source> <translation>Завършва свалянето</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="645"/> <source>%1 has finished downloading.</source> <comment>e.g: xxx.avi has finished downloading.</comment> <translation>&apos;%1&apos; завърши свалянето.</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="652"/> <source>I/O Error</source> <comment>i.e: Input/Output Error</comment> <translation>В/И Грешка</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="652"/> <source>An I/O error occurred for torrent %1. Reason: %2</source> <comment>e.g: An error occurred for torrent xxx.avi. Reason: disk is full.</comment> <translation>Намерена грешка за торент %1. Причина:%2</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="718"/> <source>Recursive download confirmation</source> <translation>Допълнително потвърждение за сваляне</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="718"/> <source>The torrent %1 contains torrent files, do you want to proceed with their download?</source> <translation>Торента %1 съдържа файлове торент, искате ли да ги свалите?</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="719"/> <source>Yes</source> <translation>Да</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="720"/> <source>No</source> <translation>Не</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="721"/> <source>Never</source> <translation>Никога</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="743"/> <source>Global Upload Speed Limit</source> <translation>Общ лимит Скорост на качване</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="759"/> <source>Global Download Speed Limit</source> <translation>Общ лимит Скорост на сваляне</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="909"/> <source>&amp;No</source> <translation type="unfinished">&amp;Не</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="910"/> <source>&amp;Yes</source> <translation type="unfinished">&amp;Да</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="911"/> <source>&amp;Always Yes</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1451"/> <location filename="../gui/mainwindow.cpp" line="1665"/> <source>Python found in %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1466"/> <source>Old Python Interpreter</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1476"/> <source>Undetermined Python version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1466"/> <source>Your Python version %1 is outdated. Please upgrade to latest version for search engines to work. Minimum requirement: 2.7.0/3.3.0.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1476"/> <source>Couldn&apos;t determine your Python version (%1). Search engine disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1487"/> <location filename="../gui/mainwindow.cpp" line="1499"/> <source>Missing Python Interpreter</source> <translation>Липсващ интерпретатор на Python</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1488"/> <source>Python is required to use the search engine but it does not seem to be installed. Do you want to install it now?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1499"/> <source>Python is required to use the search engine but it does not seem to be installed.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1536"/> <source>Update Available</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1537"/> <source>A new version is available. Update to version %1?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1546"/> <source>Already Using the Latest Version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1547"/> <source>No updates available. You are already using the latest version.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1551"/> <source>&amp;Check for Updates</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1649"/> <source>Checking for Updates...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1650"/> <source>Already checking for program updates in the background</source> <translation>Проверката за обновления на програмата вече е извършена</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1720"/> <source>Download error</source> <translation type="unfinished">Грешка при сваляне</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1720"/> <source>Python setup could not be downloaded, reason: %1. Please install it manually.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="477"/> <location filename="../gui/mainwindow.cpp" line="821"/> <source>Invalid password</source> <translation>Невалидна парола</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="518"/> <location filename="../gui/mainwindow.cpp" line="530"/> <source>RSS (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="735"/> <source>URL download error</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="735"/> <source>Couldn&apos;t download file at URL: %1, reason: %2.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="821"/> <source>The password is invalid</source> <translation>Невалидна парола</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1250"/> <location filename="../gui/mainwindow.cpp" line="1257"/> <source>DL speed: %1</source> <comment>e.g: Download speed: 10 KiB/s</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1253"/> <location filename="../gui/mainwindow.cpp" line="1259"/> <source>UP speed: %1</source> <comment>e.g: Upload speed: 10 KiB/s</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1264"/> <source>[D: %1, U: %2] qBittorrent %3</source> <comment>D = Download; U = Upload; %3 is qBittorrent version</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1365"/> <source>Hide</source> <translation>Скрий</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="906"/> <source>Exiting qBittorrent</source> <translation>Напускам qBittorrent</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="907"/> <source>Some files are currently transferring. Are you sure you want to quit qBittorrent?</source> <translation>Някои файлове се прехвърлят. Сигурни ли сте че искате да напуснете qBittorrent?</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1069"/> <source>Open Torrent Files</source> <translation>Отвори Торент Файлове </translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1070"/> <source>Torrent Files</source> <translation>Торент Файлове</translation> </message> <message> <location filename="../gui/mainwindow.cpp" line="1126"/> <source>Options were saved successfully.</source> <translation>Опциите бяха съхранени успешно.</translation> </message> </context> <context> <name>PeerAdditionDlg</name> <message> <location filename="../gui/properties/peeraddition.h" line="96"/> <source>Invalid IP</source> <translation>Невалиден IP</translation> </message> <message> <location filename="../gui/properties/peeraddition.h" line="97"/> <source>The IP you provided is invalid.</source> <translation>Този IP е невалиден.</translation> </message> </context> <context> <name>PeerListDelegate</name> <message> <location filename="../gui/properties/peerlistdelegate.h" line="64"/> <source>/s</source> <comment>/second (i.e. per second)</comment> <translation>/с</translation> </message> </context> <context> <name>PeerListWidget</name> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="68"/> <source>IP</source> <translation>IP</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="69"/> <source>Port</source> <translation type="unfinished">Порт</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="70"/> <source>Flags</source> <translation>Флагове</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="71"/> <source>Connection</source> <translation>Връзка</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="72"/> <source>Client</source> <comment>i.e.: Client application</comment> <translation>Клиент</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="73"/> <source>Progress</source> <comment>i.e: % downloaded</comment> <translation>Изпълнение</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="74"/> <source>Down Speed</source> <comment>i.e: Download speed</comment> <translation>Скорост на сваляне</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="75"/> <source>Up Speed</source> <comment>i.e: Upload speed</comment> <translation>Скорост на качване</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="76"/> <source>Downloaded</source> <comment>i.e: total data downloaded</comment> <translation>Свалени</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="77"/> <source>Uploaded</source> <comment>i.e: total data uploaded</comment> <translation>Качени</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="78"/> <source>Relevance</source> <comment>i.e: How relevant this peer is to us. How many pieces it has that we don&apos;t.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="167"/> <source>Add a new peer...</source> <translation>Добави нова двойка...</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="178"/> <source>Copy selected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="181"/> <source>Limit download rate...</source> <translation type="unfinished">Ограничи процент сваляне...</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="182"/> <source>Limit upload rate...</source> <translation type="unfinished">Ограничи процент качване...</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="185"/> <source>Ban peer permanently</source> <translation>Спри двойката завинаги</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="196"/> <location filename="../gui/properties/peerlistwidget.cpp" line="198"/> <source>Peer addition</source> <translation>Добавяне на двойка</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="196"/> <source>The peer was added to this torrent.</source> <translation>Двойката бе добавена към този торент.</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="198"/> <source>The peer could not be added to this torrent.</source> <translation>Двойката не може да бъде добавена към този торент.</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="231"/> <source>Are you sure? -- qBittorrent</source> <translation>Сигурни ли сте? -- qBittorrent</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="231"/> <source>Are you sure you want to ban permanently the selected peers?</source> <translation>Сигурни ли сте че искате да спрете завинаги избраните двойки?</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="232"/> <source>&amp;Yes</source> <translation>&amp;Да</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="232"/> <source>&amp;No</source> <translation>&amp;Не</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="239"/> <source>Manually banning peer %1...</source> <translation>Ръчно спиране на двойка %1...</translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="262"/> <source>Upload rate limiting</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="294"/> <source>Download rate limiting</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="485"/> <source>interested(local) and choked(peer)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="491"/> <source>interested(local) and unchoked(peer)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="500"/> <source>interested(peer) and choked(local)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="506"/> <source>interested(peer) and unchoked(local)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="514"/> <source>optimistic unchoke</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="521"/> <source>peer snubbed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="528"/> <source>incoming connection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="535"/> <source>not interested(local) and unchoked(peer)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="542"/> <source>not interested(peer) and unchoked(local)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="549"/> <source>peer from PEX</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="556"/> <source>peer from DHT</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="563"/> <source>encrypted traffic</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="570"/> <source>encrypted handshake</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/peerlistwidget.cpp" line="588"/> <source>peer from LSD</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Preferences</name> <message> <location filename="../gui/options.ui" line="96"/> <source>Downloads</source> <translation>Сваляне</translation> </message> <message> <location filename="../gui/options.ui" line="107"/> <source>Connection</source> <translation>Връзка</translation> </message> <message> <location filename="../gui/options.ui" line="118"/> <source>Speed</source> <translation>Скорост</translation> </message> <message> <location filename="../gui/options.ui" line="140"/> <source>Web UI</source> <translation>Web UI</translation> </message> <message> <location filename="../gui/options.ui" line="151"/> <source>Advanced</source> <translation>Разширено </translation> </message> <message> <location filename="../gui/options.ui" line="227"/> <source>(Requires restart)</source> <translation>(Изисква рестартиране)</translation> </message> <message> <location filename="../gui/options.ui" line="261"/> <source>Use alternating row colors</source> <extracomment>In transfer list, one every two rows will have grey background.</extracomment> <translation>Ползвай различно оцветени редове</translation> </message> <message> <location filename="../gui/options.ui" line="303"/> <location filename="../gui/options.ui" line="329"/> <source>Start / Stop Torrent</source> <translation>Пусни / Спри Торент</translation> </message> <message> <location filename="../gui/options.ui" line="313"/> <location filename="../gui/options.ui" line="339"/> <source>No action</source> <translation>Без действие</translation> </message> <message> <location filename="../gui/options.ui" line="700"/> <source>Append .!qB extension to incomplete files</source> <translation>Добави .!qB разширение към незавършени файлове</translation> </message> <message> <location filename="../gui/options.ui" line="803"/> <source>Copy .torrent files to:</source> <translation>Копирай .торент файловете в:</translation> </message> <message> <location filename="../gui/options.ui" line="1008"/> <source>The following parameters are supported: &lt;ul&gt; &lt;li&gt;%f: Torrent path&lt;/li&gt; &lt;li&gt;%n: Torrent name&lt;/li&gt; &lt;/ul&gt;</source> <translation>Поддържат се следните параметри: &lt;ul&gt; &lt;li&gt;%f: Торент път&lt;/li&gt; &lt;li&gt;%n: Торент име&lt;/li&gt; &lt;/ul&gt;</translation> </message> <message> <location filename="../gui/options.ui" line="1122"/> <source>Connections Limits</source> <translation>Ограничения на Връзката</translation> </message> <message> <location filename="../gui/options.ui" line="1275"/> <source>Proxy Server</source> <translation>Прокси сървър</translation> </message> <message> <location filename="../gui/options.ui" line="1556"/> <source>Global Rate Limits</source> <translation>Ограничения на Общо Ниво</translation> </message> <message> <location filename="../gui/options.ui" line="1671"/> <source>Apply rate limit to uTP connections</source> <translation>Прилагане на пределна скорост за uTP-връзки</translation> </message> <message> <location filename="../gui/options.ui" line="1678"/> <source>Apply rate limit to transport overhead</source> <translation>Прилагане на пределна скорост за превишено пренасяне</translation> </message> <message> <location filename="../gui/options.ui" line="1691"/> <source>Alternative Global Rate Limits</source> <translation>Алтернативни Ограничения на Общо Ниво</translation> </message> <message> <location filename="../gui/options.ui" line="1803"/> <source>Schedule the use of alternative rate limits</source> <translation>График на използване на Алтернативни Ограничения</translation> </message> <message> <location filename="../gui/options.ui" line="2009"/> <source>Enable Local Peer Discovery to find more peers</source> <translation>Включи Откриване на локална връзка за намиране на повече връзки</translation> </message> <message> <location filename="../gui/options.ui" line="2021"/> <source>Encryption mode:</source> <translation>Режим на кодиране:</translation> </message> <message> <location filename="../gui/options.ui" line="2029"/> <source>Prefer encryption</source> <translation>Предпочитано кодиране</translation> </message> <message> <location filename="../gui/options.ui" line="2034"/> <source>Require encryption</source> <translation>Изисква кодиране</translation> </message> <message> <location filename="../gui/options.ui" line="2039"/> <source>Disable encryption</source> <translation>Изключи кодиране</translation> </message> <message> <location filename="../gui/options.ui" line="2074"/> <source> (&lt;a href=&quot;http://github.com/qbittorrent/qBittorrent/wiki/Anonymous-Mode&quot;&gt;More information&lt;/a&gt;)</source> <translation>(&lt;a href=&quot;http://github.com/qbittorrent/qBittorrent/wiki/Anonymous-Mode&quot;&gt;Повече информация&lt;/a&gt;)</translation> </message> <message> <location filename="../gui/options.ui" line="2117"/> <source>Maximum active downloads:</source> <translation>Максимум активни сваляния:</translation> </message> <message> <location filename="../gui/options.ui" line="2137"/> <source>Maximum active uploads:</source> <translation>Максимум активни качвания:</translation> </message> <message> <location filename="../gui/options.ui" line="2157"/> <source>Maximum active torrents:</source> <translation>Максимум активни торенти:</translation> </message> <message> <location filename="../gui/options.ui" line="536"/> <source>When adding a torrent</source> <translation>При добавяне на торент</translation> </message> <message> <location filename="../gui/options.ui" line="85"/> <source>Behavior</source> <translation>Режим на работа</translation> </message> <message> <location filename="../gui/options.ui" line="191"/> <source>Language</source> <translation>Език</translation> </message> <message> <location filename="../gui/options.ui" line="552"/> <source>Display torrent content and some options</source> <translation>Показване съдържание на торента и някои опции</translation> </message> <message> <location filename="../gui/options.ui" line="1058"/> <source>Port used for incoming connections:</source> <translation>Порт ползван за входящи връзки:</translation> </message> <message> <location filename="../gui/options.ui" line="1078"/> <source>Random</source> <translation>Приблизително</translation> </message> <message> <location filename="../gui/options.ui" line="1128"/> <source>Global maximum number of connections:</source> <translation>Общ максимален брой на връзки:</translation> </message> <message> <location filename="../gui/options.ui" line="1154"/> <source>Maximum number of connections per torrent:</source> <translation>Максимален брой връзки на торент:</translation> </message> <message> <location filename="../gui/options.ui" line="1177"/> <source>Maximum number of upload slots per torrent:</source> <translation>Максимален брой слотове за качване на торент:</translation> </message> <message> <location filename="../gui/options.ui" line="1574"/> <location filename="../gui/options.ui" line="1769"/> <source>Upload:</source> <translation>Качване:</translation> </message> <message> <location filename="../gui/options.ui" line="1607"/> <location filename="../gui/options.ui" line="1779"/> <source>Download:</source> <translation>Сваляне:</translation> </message> <message> <location filename="../gui/options.ui" line="1600"/> <location filename="../gui/options.ui" line="1633"/> <location filename="../gui/options.ui" line="1739"/> <location filename="../gui/options.ui" line="1762"/> <source>KiB/s</source> <translation>KiB/с</translation> </message> <message> <location filename="../gui/options.ui" line="770"/> <source>Remove folder</source> <translation>Премахни папка</translation> </message> <message> <location filename="../gui/options.ui" line="1847"/> <source>to</source> <extracomment>time1 to time2</extracomment> <translation>към</translation> </message> <message> <location filename="../gui/options.ui" line="1902"/> <source>Every day</source> <translation>Всеки ден</translation> </message> <message> <location filename="../gui/options.ui" line="1907"/> <source>Week days</source> <translation>Работни дни</translation> </message> <message> <location filename="../gui/options.ui" line="1912"/> <source>Week ends</source> <translation>Почивни дни</translation> </message> <message utf8="true"> <location filename="../gui/options.ui" line="1993"/> <source>Exchange peers with compatible Bittorrent clients (µTorrent, Vuze, ...)</source> <translation>Обмени двойки със съвместими Битторент клиенти (µTorrent, Vuze, ...)</translation> </message> <message> <location filename="../gui/options.ui" line="1317"/> <source>Host:</source> <translation>Хост:</translation> </message> <message> <location filename="../gui/options.ui" line="1296"/> <source>SOCKS4</source> <translation>SOCKS4</translation> </message> <message> <location filename="../gui/options.ui" line="1283"/> <source>Type:</source> <translation>Вид:</translation> </message> <message> <location filename="../gui/options.ui" line="20"/> <location filename="../gui/options.ui" line="1655"/> <source>Options</source> <translation>Опции</translation> </message> <message> <location filename="../gui/options.ui" line="277"/> <source>Action on double-click</source> <translation>Действие при двойно щракване</translation> </message> <message> <location filename="../gui/options.ui" line="286"/> <source>Downloading torrents:</source> <translation>Сваляне на торенти:</translation> </message> <message> <location filename="../gui/options.ui" line="308"/> <location filename="../gui/options.ui" line="334"/> <source>Open destination folder</source> <translation>Отвори папка получател</translation> </message> <message> <location filename="../gui/options.ui" line="321"/> <source>Completed torrents:</source> <translation>Завършени торенти:</translation> </message> <message> <location filename="../gui/options.ui" line="353"/> <source>Desktop</source> <translation>Десктоп</translation> </message> <message> <location filename="../gui/options.ui" line="366"/> <source>Show splash screen on start up</source> <translation>Покажи начален екран при стартиране</translation> </message> <message> <location filename="../gui/options.ui" line="376"/> <source>Start qBittorrent minimized</source> <translation>Стартирай qBittorrent минимизиран</translation> </message> <message> <location filename="../gui/options.ui" line="402"/> <source>Minimize qBittorrent to notification area</source> <translation>Минимизирай qBittorrent в зоната за уведомяване</translation> </message> <message> <location filename="../gui/options.ui" line="412"/> <source>Close qBittorrent to notification area</source> <comment>i.e: The systray tray icon will still be visible when closing the main window.</comment> <translation>Затвори qBittorrent в зоната за уведомяване</translation> </message> <message> <location filename="../gui/options.ui" line="421"/> <source>Tray icon style:</source> <translation>Стил на иконата в лентата:</translation> </message> <message> <location filename="../gui/options.ui" line="429"/> <source>Normal</source> <translation>Нормален</translation> </message> <message> <location filename="../gui/options.ui" line="434"/> <source>Monochrome (Dark theme)</source> <translation>Едноцветно (Тъмна тема)</translation> </message> <message> <location filename="../gui/options.ui" line="439"/> <source>Monochrome (Light theme)</source> <translation>Едноцветно (Светла тема)</translation> </message> <message> <location filename="../gui/options.ui" line="199"/> <source>User Interface Language:</source> <translation>Език на Потребителския Интерфейс:</translation> </message> <message> <location filename="../gui/options.ui" line="255"/> <source>Transfer List</source> <translation>Листа за обмен</translation> </message> <message> <location filename="../gui/options.ui" line="359"/> <source>Start qBittorrent on Windows start up</source> <translation>Стартирай qBittorrent със стартирането на Windows</translation> </message> <message> <location filename="../gui/options.ui" line="383"/> <source>Confirmation on exit when torrents are active</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="393"/> <source>Show qBittorrent in notification area</source> <translation>Покажи qBittorrent в зоната за уведомяване</translation> </message> <message> <location filename="../gui/options.ui" line="452"/> <source>File association</source> <translation>Свързване с файл</translation> </message> <message> <location filename="../gui/options.ui" line="458"/> <source>Use qBittorrent for .torrent files</source> <translation>Ползвай qBittorrent за торент файлове</translation> </message> <message> <location filename="../gui/options.ui" line="465"/> <source>Use qBittorrent for magnet links</source> <translation>Ползвай qBittorrent за магнитни връзки</translation> </message> <message> <location filename="../gui/options.ui" line="478"/> <source>Power Management</source> <translation>Управление на Енергията</translation> </message> <message> <location filename="../gui/options.ui" line="484"/> <source>Inhibit system sleep when torrents are active</source> <translation>Попречи на системата да заспи когато има активни торенти</translation> </message> <message> <location filename="../gui/options.ui" line="545"/> <source>Do not start the download automatically</source> <comment>The torrent will be added to download list in pause state</comment> <translation>Не стартирай свалянето автоматично</translation> </message> <message> <location filename="../gui/options.ui" line="561"/> <source>Bring torrent dialog to the front</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="583"/> <source>Hard Disk</source> <translation>Твърд диск</translation> </message> <message> <location filename="../gui/options.ui" line="589"/> <source>Save files to location:</source> <translation>Съхрани файловете в:</translation> </message> <message> <location filename="../gui/options.ui" line="637"/> <source>Append the label of the torrent to the save path</source> <translation>Добави етикета на торента в пътя за съхранение</translation> </message> <message> <location filename="../gui/options.ui" line="647"/> <source>Pre-allocate disk space for all files</source> <translation>Преразпредели дисково пространство за всички файлове </translation> </message> <message> <location filename="../gui/options.ui" line="654"/> <source>Keep incomplete torrents in:</source> <translation>Дръж незавършени торенти в:</translation> </message> <message> <location filename="../gui/options.ui" line="707"/> <source>Automatically add torrents from:</source> <translation>Автоматично добави торенти от:</translation> </message> <message> <location filename="../gui/options.ui" line="760"/> <source>Add folder...</source> <translation>Добави папка...</translation> </message> <message> <location filename="../gui/options.ui" line="852"/> <source>Copy .torrent files for finished downloads to:</source> <translation>Копирай .torrent файловете от приключилите изтегляния в:</translation> </message> <message> <location filename="../gui/options.ui" line="908"/> <source>Email notification upon download completion</source> <translation>Уведомяване с е-мейл при завършване на свалянето</translation> </message> <message> <location filename="../gui/options.ui" line="922"/> <source>Destination email:</source> <translation>Е-мейл получател:</translation> </message> <message> <location filename="../gui/options.ui" line="932"/> <source>SMTP server:</source> <translation>SMTP сървър:</translation> </message> <message> <location filename="../gui/options.ui" line="981"/> <source>This server requires a secure connection (SSL)</source> <translation>Този сървър изисква защитена връзка (SSL)</translation> </message> <message> <location filename="../gui/options.ui" line="993"/> <source>Run an external program on torrent completion</source> <translation>Пусни друга програма при завършване на торента</translation> </message> <message> <location filename="../gui/options.ui" line="1050"/> <source>Listening Port</source> <translation>Порт за прослушване</translation> </message> <message> <location filename="../gui/options.ui" line="1100"/> <source>Use UPnP / NAT-PMP port forwarding from my router</source> <translation>Ползвай UPnP / NAT-PMP порт прехвърляне от моя рутер</translation> </message> <message> <location filename="../gui/options.ui" line="1110"/> <source>Use different port on each startup</source> <translation>Използвай различен порт при всяко стартиране</translation> </message> <message> <location filename="../gui/options.ui" line="1236"/> <source>Global maximum number of upload slots:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="1371"/> <source>Otherwise, the proxy server is only used for tracker connections</source> <translation>В противен случай, прокси сървъра се използва само за връзки на тракера</translation> </message> <message> <location filename="../gui/options.ui" line="1374"/> <source>Use proxy for peer connections</source> <translation>Използвайте прокси за взаимно свързване</translation> </message> <message> <location filename="../gui/options.ui" line="1381"/> <source>Disable connections not supported by proxies</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="1450"/> <source>Info: The password is saved unencrypted</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="1463"/> <source>IP Filtering</source> <translation>IP филтриране</translation> </message> <message> <location filename="../gui/options.ui" line="1504"/> <source>Reload the filter</source> <translation>Зареди повторно филтъра</translation> </message> <message> <location filename="../gui/options.ui" line="1520"/> <source>Apply to trackers</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="1661"/> <source>Enable bandwidth management (uTP)</source> <translation>Включи управление на трафика (uTP)</translation> </message> <message> <location filename="../gui/options.ui" line="1820"/> <source>from</source> <extracomment>from (time1 to time2)</extracomment> <translation>от</translation> </message> <message> <location filename="../gui/options.ui" line="1894"/> <source>When:</source> <translation>Когато:</translation> </message> <message> <location filename="../gui/options.ui" line="1977"/> <source>Privacy</source> <translation>Лично</translation> </message> <message> <location filename="../gui/options.ui" line="1983"/> <source>Enable DHT (decentralized network) to find more peers</source> <translation>Включи мрежа DHT (децентрализирана) за намиране на повече връзки</translation> </message> <message> <location filename="../gui/options.ui" line="1996"/> <source>Enable Peer Exchange (PeX) to find more peers</source> <translation>Включи Peer Exchange (PeX) за намиране на повече връзки</translation> </message> <message> <location filename="../gui/options.ui" line="2006"/> <source>Look for peers on your local network</source> <translation>Търси връзки на твоята локална мрежа</translation> </message> <message> <location filename="../gui/options.ui" line="2064"/> <source>Enable when using a proxy or a VPN connection</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options.ui" line="2067"/> <source>Enable anonymous mode</source> <translation>Включи анонимен режим</translation> </message> <message> <location filename="../gui/options.ui" line="2216"/> <source>Do not count slow torrents in these limits</source> <translation>Не изчислявай бавни торенти в тези лимити</translation> </message> <message> <location filename="../gui/options.ui" line="2237"/> <source>Seed torrents until their ratio reaches</source> <translation>Давай торентите докато съотношението се увеличи</translation> </message> <message> <location filename="../gui/options.ui" line="2266"/> <source>then</source> <translation>тогава</translation> </message> <message> <location filename="../gui/options.ui" line="2277"/> <source>Pause them</source> <translation>Сложи ги в пауза</translation> </message> <message> <location filename="../gui/options.ui" line="2282"/> <source>Remove them</source> <translation>Премахни ги</translation> </message> <message> <location filename="../gui/options.ui" line="2380"/> <source>Use UPnP / NAT-PMP to forward the port from my router</source> <translation>Ползвай UPnP / NAT-PMP за препращане порта на моя рутер</translation> </message> <message> <location filename="../gui/options.ui" line="2390"/> <source>Use HTTPS instead of HTTP</source> <translation>Ползвай HTTPS вместо HTTP</translation> </message> <message> <location filename="../gui/options.ui" line="2433"/> <source>Import SSL Certificate</source> <translation>Вмъкни SSL Сертификат</translation> </message> <message> <location filename="../gui/options.ui" line="2486"/> <source>Import SSL Key</source> <translation>Вмъкни SSL Ключ</translation> </message> <message> <location filename="../gui/options.ui" line="2421"/> <source>Certificate:</source> <translation>Сертификат:</translation> </message> <message> <location filename="../gui/options.ui" line="2474"/> <source>Key:</source> <translation>Ключ:</translation> </message> <message> <location filename="../gui/options.ui" line="2508"/> <source>&lt;a href=http://httpd.apache.org/docs/2.2/ssl/ssl_faq.html#aboutcerts&gt;Information about certificates&lt;/a&gt;</source> <translation>&lt;a href=http://httpd.apache.org/docs/2.2/ssl/ssl_faq.html#aboutcerts&gt;Информация за сертификати&lt;/a&gt;</translation> </message> <message> <location filename="../gui/options.ui" line="2553"/> <source>Bypass authentication for localhost</source> <translation>Заобиколи удостоверяването за локален хост</translation> </message> <message> <location filename="../gui/options.ui" line="2577"/> <source>Update my dynamic domain name</source> <translation>Обнови моето динамично име на домейн</translation> </message> <message> <location filename="../gui/options.ui" line="2589"/> <source>Service:</source> <translation>Услуга:</translation> </message> <message> <location filename="../gui/options.ui" line="2612"/> <source>Register</source> <translation>Регистър</translation> </message> <message> <location filename="../gui/options.ui" line="2621"/> <source>Domain name:</source> <translation>Име на домейн:</translation> </message> <message> <location filename="../gui/options.ui" line="1291"/> <source>(None)</source> <translation>(без)</translation> </message> <message> <location filename="../gui/options.ui" line="129"/> <source>BitTorrent</source> <translation>BitTorrent</translation> </message> <message> <location filename="../gui/options.ui" line="1306"/> <source>HTTP</source> <translation>HTTP</translation> </message> <message> <location filename="../gui/options.ui" line="1343"/> <location filename="../gui/options.ui" line="2345"/> <source>Port:</source> <translation>Порт:</translation> </message> <message> <location filename="../gui/options.ui" line="942"/> <location filename="../gui/options.ui" line="1394"/> <location filename="../gui/options.ui" line="2521"/> <source>Authentication</source> <translation>Удостоверяване</translation> </message> <message> <location filename="../gui/options.ui" line="954"/> <location filename="../gui/options.ui" line="1408"/> <location filename="../gui/options.ui" line="2560"/> <location filename="../gui/options.ui" line="2635"/> <source>Username:</source> <translation>Име на потребителя:</translation> </message> <message> <location filename="../gui/options.ui" line="964"/> <location filename="../gui/options.ui" line="1428"/> <location filename="../gui/options.ui" line="2567"/> <location filename="../gui/options.ui" line="2649"/> <source>Password:</source> <translation>Парола:</translation> </message> <message> <location filename="../gui/options.ui" line="2102"/> <source>Torrent Queueing</source> <translation>Серия Торенти </translation> </message> <message> <location filename="../gui/options.ui" line="2226"/> <source>Share Ratio Limiting</source> <translation>Ограничаване Съотношението на Споделяне</translation> </message> <message> <location filename="../gui/options.ui" line="2331"/> <source>Enable Web User Interface (Remote control)</source> <translation>Включи Интерфейс на Web Потребител (Отдалечен контрол)</translation> </message> <message> <location filename="../gui/options.ui" line="1301"/> <source>SOCKS5</source> <translation>SOCKS5</translation> </message> <message> <location filename="../gui/options.ui" line="1475"/> <source>Filter path (.dat, .p2p, .p2b):</source> <translation>Филтър път (.dat, .p2p, .p2b): </translation> </message> </context> <context> <name>PreviewSelect</name> <message> <location filename="../gui/previewselect.cpp" line="51"/> <source>Name</source> <translation>Име</translation> </message> <message> <location filename="../gui/previewselect.cpp" line="52"/> <source>Size</source> <translation>Размер</translation> </message> <message> <location filename="../gui/previewselect.cpp" line="53"/> <source>Progress</source> <translation>Изпълнение</translation> </message> <message> <location filename="../gui/previewselect.cpp" line="80"/> <location filename="../gui/previewselect.cpp" line="117"/> <source>Preview impossible</source> <translation>Оглед невъзможен</translation> </message> <message> <location filename="../gui/previewselect.cpp" line="80"/> <location filename="../gui/previewselect.cpp" line="117"/> <source>Sorry, we can&apos;t preview this file</source> <translation>Съжалявам, не можем да огледаме този файл</translation> </message> </context> <context> <name>PropListDelegate</name> <message> <location filename="../gui/properties/proplistdelegate.h" line="117"/> <source>Not downloaded</source> <translation>Не свалени</translation> </message> <message> <location filename="../gui/properties/proplistdelegate.h" line="126"/> <location filename="../gui/properties/proplistdelegate.h" line="168"/> <source>Normal</source> <comment>Normal (priority)</comment> <translation>Нормален</translation> </message> <message> <location filename="../gui/properties/proplistdelegate.h" line="120"/> <location filename="../gui/properties/proplistdelegate.h" line="169"/> <source>High</source> <comment>High (priority)</comment> <translation>Висок</translation> </message> <message> <location filename="../gui/properties/proplistdelegate.h" line="114"/> <source>Mixed</source> <comment>Mixed (priorities</comment> <translation>Смесени</translation> </message> <message> <location filename="../gui/properties/proplistdelegate.h" line="123"/> <location filename="../gui/properties/proplistdelegate.h" line="170"/> <source>Maximum</source> <comment>Maximum (priority)</comment> <translation>Максимален</translation> </message> </context> <context> <name>PropTabBar</name> <message> <location filename="../gui/properties/proptabbar.cpp" line="45"/> <source>General</source> <translation>Общи</translation> </message> <message> <location filename="../gui/properties/proptabbar.cpp" line="50"/> <source>Trackers</source> <translation>Тракери</translation> </message> <message> <location filename="../gui/properties/proptabbar.cpp" line="54"/> <source>Peers</source> <translation>Двойки</translation> </message> <message> <location filename="../gui/properties/proptabbar.cpp" line="58"/> <source>HTTP Sources</source> <translation>HTTP Източници</translation> </message> <message> <location filename="../gui/properties/proptabbar.cpp" line="62"/> <source>Content</source> <translation>Съдържание</translation> </message> </context> <context> <name>PropertiesWidget</name> <message> <location filename="../gui/properties/propertieswidget.ui" line="292"/> <source>Downloaded:</source> <translation>Свалени:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="134"/> <source>Availability:</source> <translation>Наличност:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="77"/> <source>Progress:</source> <translation type="unfinished">Изпълнение:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="184"/> <source>Transfer</source> <translation>Трансфер</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="196"/> <source>Time Active:</source> <extracomment>Time (duration) the torrent is active (not paused)</extracomment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="228"/> <source>ETA:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="324"/> <source>Uploaded:</source> <translation>Качени:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="356"/> <source>Seeds:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="388"/> <source>Download Speed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="420"/> <source>Upload Speed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="452"/> <source>Peers:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="484"/> <source>Download Limit:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="516"/> <source>Upload Limit:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="548"/> <source>Wasted:</source> <translation>Изгубени:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="260"/> <source>Connections:</source> <translation>Връзки:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="679"/> <source>Information</source> <translation>Информация</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="959"/> <source>Comment:</source> <translation>Коментар:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1144"/> <source>Torrent content:</source> <translation>Съдържание на Торента:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1111"/> <source>Select All</source> <translation> Избери всички</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1118"/> <source>Select None</source> <translation>Не избирай</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1201"/> <source>Normal</source> <translation>Нормален</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1196"/> <source>High</source> <translation>Висок</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="580"/> <source>Share Ratio:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="612"/> <source>Reannounce In:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="644"/> <source>Last Seen Complete:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="691"/> <source>Total Size:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="723"/> <source>Pieces:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="755"/> <source>Created By:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="787"/> <source>Added On:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="819"/> <source>Completed On:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="851"/> <source>Created On:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="883"/> <source>Torrent Hash:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="918"/> <source>Save Path:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1191"/> <source>Maximum</source> <translation>Максимален</translation> </message> <message> <location filename="../gui/properties/propertieswidget.ui" line="1183"/> <location filename="../gui/properties/propertieswidget.ui" line="1186"/> <source>Do not download</source> <translation>Не сваляй</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="372"/> <location filename="../gui/properties/propertieswidget.cpp" line="373"/> <location filename="../gui/properties/propertieswidget.cpp" line="392"/> <location filename="../gui/properties/propertieswidget.cpp" line="394"/> <source>/s</source> <comment>/second (i.e. per second)</comment> <translation>/с</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="376"/> <source>Seeded for %1</source> <comment>e.g. Seeded for 3m10s</comment> <translation>Даващ на %1</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="379"/> <source>%1 max</source> <comment>e.g. 10 max</comment> <translation>%1 макс</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="389"/> <location filename="../gui/properties/propertieswidget.cpp" line="390"/> <source>(%1 total)</source> <comment>e.g. (10 total)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="393"/> <location filename="../gui/properties/propertieswidget.cpp" line="395"/> <source>(%1/s avg.)</source> <comment>e.g. (100KiB/s avg.)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="397"/> <source>Never</source> <translation type="unfinished">Никога</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="402"/> <source>%1 x %2 (have %3)</source> <comment>(torrent pieces) eg 152 x 4MB (have 25)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="511"/> <location filename="../gui/properties/propertieswidget.cpp" line="585"/> <source>I/O Error</source> <translation>Грешка на Вход/Изход</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="511"/> <source>This file does not exist yet.</source> <translation>Този файл още не съществува.</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="585"/> <source>This folder does not exist yet.</source> <translation>Тази папка още не съществува.</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="603"/> <source>Open</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="604"/> <source>Open Containing Folder</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="605"/> <source>Rename...</source> <translation>Преименувай...</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="610"/> <source>Priority</source> <translation>Предимство</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="656"/> <source>New Web seed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="662"/> <source>Remove Web seed</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="664"/> <source>Copy Web seed URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="665"/> <source>Edit Web seed URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="690"/> <source>Rename the file</source> <translation>Преименувай файла</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="691"/> <source>New name:</source> <translation>Ново име:</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="695"/> <location filename="../gui/properties/propertieswidget.cpp" line="726"/> <source>The file could not be renamed</source> <translation>Файла не може да се преименува</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="696"/> <source>This file name contains forbidden characters, please choose a different one.</source> <translation>Името на файла съдържа забранени символи, моля изберете различно име.</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="727"/> <location filename="../gui/properties/propertieswidget.cpp" line="765"/> <source>This name is already in use in this folder. Please use a different name.</source> <translation>Това име вече съществува в тази папка. Моля, ползвайте различно име.</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="764"/> <source>The folder could not be renamed</source> <translation>Папката не може да се преименува</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="872"/> <source>qBittorrent</source> <translation>qBittorrent</translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="84"/> <source>Filter files...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="370"/> <location filename="../gui/properties/propertieswidget.cpp" line="371"/> <source>session</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="810"/> <source>New URL seed</source> <comment>New HTTP source</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="811"/> <source>New URL seed:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="817"/> <location filename="../gui/properties/propertieswidget.cpp" line="873"/> <source>This URL seed is already in the list.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="865"/> <source>Web seed editing</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/propertieswidget.cpp" line="866"/> <source>Web seed URL:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QBtSession</name> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="134"/> <source>Peer ID: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="235"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="241"/> <source>%1 reached the maximum ratio you set.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="236"/> <source>Removing torrent %1...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="242"/> <source>Pausing torrent %1...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="409"/> <source>UPnP / NAT-PMP support [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="412"/> <source>UPnP / NAT-PMP support [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="417"/> <source>HTTP User-Agent is %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="444"/> <source>Anonymous mode [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="446"/> <source>Anonymous mode [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="529"/> <source>PeX support [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="531"/> <source>PeX support [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="534"/> <source>Restart is required to toggle PeX support</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="539"/> <source>Local Peer Discovery support [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="542"/> <source>Local Peer Discovery support [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="554"/> <source>Encryption support [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="559"/> <source>Encryption support [FORCED]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="564"/> <source>Encryption support [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="623"/> <source>Embedded Tracker [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="625"/> <source>Failed to start the embedded tracker!</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="628"/> <source>Embedded Tracker [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="770"/> <source>&apos;%1&apos; was removed from transfer list and hard disk.</source> <comment>&apos;xxx.avi&apos; was removed...</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="772"/> <source>&apos;%1&apos; was removed from transfer list.</source> <comment>&apos;xxx.avi&apos; was removed...</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="869"/> <source>Couldn&apos;t parse this Magnet URI: &apos;%1&apos;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="874"/> <source>&apos;%1&apos; is not a valid magnet URI.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="893"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1051"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1053"/> <source>&apos;%1&apos; is already in download list.</source> <comment>e.g: &apos;xxx.avi&apos; is already in download list.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="976"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1175"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1180"/> <source>&apos;%1&apos; added to download list.</source> <comment>&apos;/home/y/xxx.torrent&apos; was added to download list.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1025"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1030"/> <source>Unable to decode torrent file: &apos;%1&apos;</source> <comment>e.g: Unable to decode torrent file: &apos;/home/y/xxx.torrent&apos;</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1033"/> <source>This file is either corrupted or this isn&apos;t a torrent.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1068"/> <source>Error: The torrent %1 does not contain any file.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1173"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1178"/> <source>&apos;%1&apos; resumed. (fast resume)</source> <comment>&apos;/home/y/xxx.torrent&apos; was resumed. (fast resume)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1338"/> <source>Tracker &apos;%1&apos; was added to torrent &apos;%2&apos;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1362"/> <source>URL seed &apos;%1&apos; was added to torrent &apos;%2&apos;</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1535"/> <source>DHT support [ON]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1540"/> <source>DHT support [OFF]. Reason: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1548"/> <source>DHT support [OFF]</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1852"/> <source>qBittorrent is trying to listen on any interface port: %1</source> <comment>e.g: qBittorrent is trying to listen on any interface port: TCP/6881</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1856"/> <source>qBittorrent failed to listen on any interface port: %1. Reason: %2</source> <comment>e.g: qBittorrent failed to listen on any interface port: TCP/6881. Reason: no such interface</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1864"/> <source>The network interface defined is invalid: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1877"/> <source>qBittorrent is trying to listen on interface %1 port: %2</source> <comment>e.g: qBittorrent is trying to listen on interface 192.168.0.1 port: TCP/6881</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1881"/> <source>qBittorrent didn&apos;t find an %1 local address to listen on</source> <comment>qBittorrent didn&apos;t find an IPv4 local address to listen on</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="1989"/> <source>Recursive download of file %1 embedded in torrent %2</source> <comment>Recursive download of test.torrent embedded in torrent test2</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2028"/> <source>Torrent name: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2029"/> <source>Torrent size: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2030"/> <source>Save path: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2031"/> <source>The torrent was downloaded in %1.</source> <comment>The torrent was downloaded in 1 hour and 20 seconds</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2032"/> <source>Thank you for using qBittorrent.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2035"/> <source>[qBittorrent] %1 has finished downloading</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2172"/> <source>Unable to decode %1 torrent file.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2380"/> <source>Could not move torrent: &apos;%1&apos;. Reason: %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2385"/> <source>Attempting to move torrent: &apos;%1&apos; to path: &apos;%2&apos;.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2448"/> <source>An I/O error occurred, &apos;%1&apos; paused.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2449"/> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2603"/> <source>Reason: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2540"/> <source>UPnP/NAT-PMP: Port mapping failure, message: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2545"/> <source>UPnP/NAT-PMP: Port mapping successful, message: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2559"/> <source>due to IP filter.</source> <comment>this peer was blocked due to ip filter.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2562"/> <source>due to port filter.</source> <comment>this peer was blocked due to port filter.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2565"/> <source>due to i2p mixed mode restrictions.</source> <comment>this peer was blocked due to i2p mixed mode restrictions.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2568"/> <source>because it has a low port.</source> <comment>this peer was blocked because it has a low port.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2571"/> <source>because μTP is disabled.</source> <comment>this peer was blocked because μTP is disabled.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2574"/> <source>because TCP is disabled.</source> <comment>this peer was blocked because TCP is disabled.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2598"/> <source>File sizes mismatch for torrent %1, pausing it.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2602"/> <source>Fast resume data was rejected for torrent %1, checking again...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2609"/> <source>URL seed lookup failed for url: %1, message: %2</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2624"/> <source>qBittorrent is successfully listening on interface %1 port: %2/%3</source> <comment>e.g: qBittorrent is successfully listening on interface 192.168.0.1 port: TCP/6881</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2651"/> <source>qBittorrent failed listening on interface %1 port: %2/%3. Reason: %4</source> <comment>e.g: qBittorrent failed listening on interface 192.168.0.1 port: TCP/6881. Reason: already in use</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2684"/> <source>External IP: %1</source> <comment>e.g. External IP: 192.168.0.1</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="2814"/> <source>Downloading &apos;%1&apos;, please wait...</source> <comment>e.g: Downloading &apos;xxx.torrent&apos;, please wait...</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="3034"/> <source>Successfully parsed the provided IP filter: %1 rules were applied.</source> <comment>%1 is a number</comment> <translation type="unfinished">Успешно вмъкване на дадения IP филтър: %1 правила бяха добавени.</translation> </message> <message> <location filename="../core/qtlibtorrent/qbtsession.cpp" line="3040"/> <source>Error: Failed to parse the provided IP filter.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>QObject</name> <message> <location filename="../webui/abstractwebapplication.cpp" line="110"/> <source>Your IP address has been banned after too many failed authentication attempts.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/webapplication.cpp" line="350"/> <source>Error: &apos;%1&apos; is not a valid torrent file. </source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/webapplication.cpp" line="358"/> <source>I/O Error: Could not create temporary file.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="124"/> <source>qBittorrent %1 started</source> <comment>qBittorrent v3.2.0alpha started</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="135"/> <source>%1 is an unknown command line parameter.</source> <comment>--random-parameter is an unknown command line parameter.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="147"/> <location filename="../app/main.cpp" line="160"/> <source>%1 must be the single command line parameter.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="170"/> <source>%1 must specify the correct port (1 to 65535).</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="186"/> <source>You cannot use %1: qBittorrent is already running for this user.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="363"/> <source>Usage:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="376"/> <source>Options:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="378"/> <source>Displays program version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="380"/> <source>Displays this help message</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="382"/> <source>Changes the Web UI port (current: %1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="385"/> <source>Disable splash screen</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="387"/> <source>Run in daemon-mode (background)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="389"/> <source>Downloads the torrents passed by the user</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="399"/> <source>Help</source> <translation type="unfinished">Помощ</translation> </message> <message> <location filename="../app/main.cpp" line="408"/> <source>Run application with -h option to read about command line parameters.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="410"/> <source>Bad command line</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="416"/> <source>Bad command line: </source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="429"/> <source>Legal Notice</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="430"/> <location filename="../app/main.cpp" line="440"/> <source>qBittorrent is a file sharing program. When you run a torrent, its data will be made available to others by means of upload. Any content you share is your sole responsibility. No further notices will be issued.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="431"/> <source>Press %1 key to accept and continue...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="441"/> <source>Legal notice</source> <translation type="unfinished"></translation> </message> <message> <location filename="../app/main.cpp" line="442"/> <source>Cancel</source> <translation type="unfinished">Прекъсни</translation> </message> <message> <location filename="../app/main.cpp" line="443"/> <source>I Agree</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RSS</name> <message> <location filename="../gui/rss/rss.ui" line="17"/> <source>Search</source> <translation>Търси</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="31"/> <source>New subscription</source> <translation>Нов абонамент</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="47"/> <location filename="../gui/rss/rss.ui" line="199"/> <location filename="../gui/rss/rss.ui" line="202"/> <source>Mark items read</source> <translation>Четене на маркираните</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="66"/> <source>Update all</source> <translation>Обнови всички</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="95"/> <source>RSS Downloader...</source> <translation>RSS сваляч...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="102"/> <source>Settings...</source> <translation>Настройки...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="124"/> <source>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt; &lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt; p, li { white-space: pre-wrap; } &lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Sans&apos;; font-size:10pt; font-weight:400; font-style:normal;&quot;&gt; &lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Torrents:&lt;/span&gt; &lt;span style=&quot; font-style:italic;&quot;&gt;(double-click to download)&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;p, li { white-space: pre-wrap; }&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:&apos;Sans&apos;; font-size:10pt; font-weight:400; font-style:normal;&quot;&gt;&lt;p style=&quot; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;span style=&quot; font-weight:600;&quot;&gt;Торенти:&lt;/span&gt; &lt;span style=&quot; font-style:italic;&quot;&gt;(double-click to download)&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="162"/> <location filename="../gui/rss/rss.ui" line="165"/> <source>Delete</source> <translation>Изтрий</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="170"/> <source>Rename...</source> <translation>Преименувай...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="173"/> <source>Rename</source> <translation>Преименувай</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="178"/> <location filename="../gui/rss/rss.ui" line="181"/> <source>Update</source> <translation>Обновяване</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="186"/> <source>New subscription...</source> <translation>Нов абонамент...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="191"/> <location filename="../gui/rss/rss.ui" line="194"/> <source>Update all feeds</source> <translation>Обнови всички канали</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="207"/> <source>Download torrent</source> <translation>Торент сваляне</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="212"/> <source>Open news URL</source> <translation>Отваря URL за новини</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="217"/> <source>Copy feed URL</source> <translation>Копира URL на канал</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="222"/> <source>New folder...</source> <translation>Нова папка...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="227"/> <source>Manage cookies...</source> <translation>Управление на бисквитки...</translation> </message> <message> <location filename="../gui/rss/rss.ui" line="63"/> <source>Refresh RSS streams</source> <translation>Обнови потоците RSS</translation> </message> </context> <context> <name>RSSImp</name> <message> <location filename="../gui/rss/rss_imp.cpp" line="204"/> <source>Stream URL:</source> <translation>Поток URL:</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="204"/> <source>Please type a RSS stream URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="214"/> <source>This RSS feed is already in the list.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="241"/> <location filename="../gui/rss/rss_imp.cpp" line="248"/> <source>Are you sure? -- qBittorrent</source> <translation>Сигурни ли сте? -- qBittorrent</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="242"/> <location filename="../gui/rss/rss_imp.cpp" line="249"/> <source>&amp;Yes</source> <translation>&amp;Да</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="242"/> <location filename="../gui/rss/rss_imp.cpp" line="249"/> <source>&amp;No</source> <translation>&amp;Не</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="159"/> <source>Please choose a folder name</source> <translation>Моля изберете име на папка</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="159"/> <source>Folder name:</source> <translation>Име на папка:</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="159"/> <source>New folder</source> <translation>Нова папка</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="241"/> <source>Are you sure you want to delete these elements from the list?</source> <translation>Сигурни ли сте че искате да изтриете тези елементи от списъка?</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="248"/> <source>Are you sure you want to delete this element from the list?</source> <translation>Сигурни ли сте че искате да изтриете този елемент от списъка?</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="386"/> <source>Please choose a new name for this RSS feed</source> <translation>Моля изберете ново име за този RSS канал</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="386"/> <source>New feed name:</source> <translation>Име на нов канал:</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="390"/> <source>Name already in use</source> <translation>Името вече се ползва</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="390"/> <source>This name is already used by another item, please choose another one.</source> <translation>Това име се ползва от друг елемент, моля изберете друго.</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="568"/> <source>Date: </source> <translation> Дата:</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="570"/> <source>Author: </source> <translation> Автор:</translation> </message> <message> <location filename="../gui/rss/rss_imp.cpp" line="647"/> <source>Unread</source> <translation>Непрочетен</translation> </message> </context> <context> <name>RssFeed</name> <message> <location filename="../gui/rss/rssfeed.cpp" line="370"/> <source>Automatically downloading %1 torrent from %2 RSS feed...</source> <translation>Автоматично сваляне на %1 торент от %2 RSS канал...</translation> </message> </context> <context> <name>RssParser</name> <message> <location filename="../gui/rss/rssparser.cpp" line="458"/> <source>Failed to open downloaded RSS file.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/rss/rssparser.cpp" line="495"/> <source>Invalid RSS feed at %1.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RssSettingsDlg</name> <message> <location filename="../gui/rss/rsssettingsdlg.ui" line="14"/> <source>RSS Reader Settings</source> <translation>RSS четец настройки</translation> </message> <message> <location filename="../gui/rss/rsssettingsdlg.ui" line="47"/> <source>RSS feeds refresh interval:</source> <translation>Интервал на обновяване на RSS feeds:</translation> </message> <message> <location filename="../gui/rss/rsssettingsdlg.ui" line="70"/> <source>minutes</source> <translation>минути</translation> </message> <message> <location filename="../gui/rss/rsssettingsdlg.ui" line="77"/> <source>Maximum number of articles per feed:</source> <translation>Максимум статии на feed:</translation> </message> </context> <context> <name>ScanFoldersModel</name> <message> <location filename="../core/scannedfoldersmodel.cpp" line="97"/> <source>Watched Folder</source> <translation>Наблюдавана Папка</translation> </message> <message> <location filename="../core/scannedfoldersmodel.cpp" line="98"/> <source>Download here</source> <translation>Свали тук</translation> </message> </context> <context> <name>SearchCategories</name> <message> <location filename="../searchengine/supportedengines.h" line="53"/> <source>All categories</source> <translation>Всички категории</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="54"/> <source>Movies</source> <translation>Филми</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="55"/> <source>TV shows</source> <translation>TV шоу</translation> </message><|fim▁hole|> <translation>Музика</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="57"/> <source>Games</source> <translation>Игри</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="58"/> <source>Anime</source> <translation>Анимация</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="59"/> <source>Software</source> <translation>Софтуер</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="60"/> <source>Pictures</source> <translation>Снимки</translation> </message> <message> <location filename="../searchengine/supportedengines.h" line="61"/> <source>Books</source> <translation>Книги</translation> </message> </context> <context> <name>SearchEngine</name> <message> <location filename="../searchengine/searchengine.cpp" line="175"/> <location filename="../searchengine/searchengine.cpp" line="199"/> <location filename="../searchengine/searchengine.cpp" line="200"/> <location filename="../searchengine/searchengine.cpp" line="454"/> <source>Search</source> <translation>Търси</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="185"/> <source>Please install Python to use the Search Engine.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="212"/> <source>Empty search pattern</source> <translation>Празен образец за търсене</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="212"/> <source>Please type a search pattern first</source> <translation>Моля първо въведете образец за търсене</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="241"/> <location filename="../searchengine/searchengine.cpp" line="311"/> <source>Results</source> <translation>Резултати</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="289"/> <source>Searching...</source> <translation>Търсене...</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="292"/> <source>Stop</source> <translation>Спиране</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="185"/> <location filename="../searchengine/searchengine.cpp" line="428"/> <source>Search Engine</source> <translation>Търсачка</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="428"/> <location filename="../searchengine/searchengine.cpp" line="443"/> <source>Search has finished</source> <translation>Търсенето завърши</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="434"/> <source>An error occurred during search...</source> <translation>Намерена грешка при търсенето...</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="432"/> <location filename="../searchengine/searchengine.cpp" line="438"/> <source>Search aborted</source> <translation>Търсенето е прекъснато</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="113"/> <source>All enabled</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="114"/> <source>All engines</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="117"/> <location filename="../searchengine/searchengine.cpp" line="164"/> <source>Multiple...</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="441"/> <source>Search returned no results</source> <translation>Търсене завършено без резултат</translation> </message> <message> <location filename="../searchengine/searchengine.cpp" line="450"/> <source>Results</source> <comment>i.e: Search results</comment> <translation>Резултати</translation> </message> </context> <context> <name>SearchListDelegate</name> <message> <location filename="../searchengine/searchlistdelegate.h" line="60"/> <location filename="../searchengine/searchlistdelegate.h" line="64"/> <source>Unknown</source> <translation type="unfinished">Неизвестен</translation> </message> </context> <context> <name>SearchTab</name> <message> <location filename="../searchengine/searchtab.cpp" line="57"/> <source>Name</source> <comment>i.e: file name</comment> <translation>Име</translation> </message> <message> <location filename="../searchengine/searchtab.cpp" line="58"/> <source>Size</source> <comment>i.e: file size</comment> <translation>Размер</translation> </message> <message> <location filename="../searchengine/searchtab.cpp" line="59"/> <source>Seeders</source> <comment>i.e: Number of full sources</comment> <translation>Даващи</translation> </message> <message> <location filename="../searchengine/searchtab.cpp" line="60"/> <source>Leechers</source> <comment>i.e: Number of partial sources</comment> <translation>Вземащи</translation> </message> <message> <location filename="../searchengine/searchtab.cpp" line="61"/> <source>Search engine</source> <translation>Програма за търсене</translation> </message> </context> <context> <name>ShutdownConfirmDlg</name> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="40"/> <source>Exit confirmation</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="41"/> <source>Exit now</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="44"/> <source>Shutdown confirmation</source> <translation>Потвърждение за загасяване</translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="45"/> <source>Shutdown now</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="99"/> <source>qBittorrent will now exit unless you cancel within the next %1 seconds.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="102"/> <source>The computer will now be switched off unless you cancel within the next %1 seconds.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="105"/> <source>The computer will now go to sleep mode unless you cancel within the next %1 seconds.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/shutdownconfirm.cpp" line="108"/> <source>The computer will now go to hibernation mode unless you cancel within the next %1 seconds.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Smtp</name> <message> <location filename="../core/smtp.cpp" line="479"/> <source>Email Notification Error:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SpeedLimitDialog</name> <message> <location filename="../gui/speedlimitdlg.cpp" line="78"/> <source>KiB/s</source> <translation>KiB/с</translation> </message> </context> <context> <name>StatsDialog</name> <message> <location filename="../gui/statsdialog.ui" line="14"/> <source>Statistics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="20"/> <source>User statistics</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="26"/> <source>Total peer connections:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="33"/> <source>Global ratio:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="47"/> <source>Alltime download:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="68"/> <source>Alltime upload:</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="82"/> <source>Total waste (this session):</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="99"/> <source>Cache statistics</source> <translation>Статистика на кеша</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="105"/> <source>Read cache Hits:</source> <translation>Прочети кешираните резултати:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="126"/> <source>Total buffers size:</source> <translation>Общ размер на буфера:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="136"/> <source>Performance statistics</source> <translation>Статистика на дейността</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="170"/> <source>Queued I/O jobs:</source> <translation>Наредени на опашка В/И задачи:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="177"/> <source>Write cache overload:</source> <translation>Запиши кеша при претоварване:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="184"/> <source>Average time in queue (ms):</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statsdialog.ui" line="191"/> <source>Read cache overload:</source> <translation>Прочети кеша при претоварване:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="198"/> <source>Total queued size:</source> <translation>Общ размер на опашката:</translation> </message> <message> <location filename="../gui/statsdialog.ui" line="243"/> <source>OK</source> <translation>ОК</translation> </message> </context> <context> <name>StatusBar</name> <message> <location filename="../gui/statusbar.cpp" line="61"/> <location filename="../gui/statusbar.cpp" line="173"/> <source>Connection status:</source> <translation>Състояние на връзката:</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="61"/> <location filename="../gui/statusbar.cpp" line="173"/> <source>No direct connections. This may indicate network configuration problems.</source> <translation>Няма директни връзки. Това може да е от проблеми в мрежовата настройка.</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="75"/> <location filename="../gui/statusbar.cpp" line="180"/> <source>DHT: %1 nodes</source> <translation>DHT: %1 възли</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="143"/> <source>qBittorrent needs to be restarted</source> <translation>qBittorrent се нуждае от рестарт</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="153"/> <source>qBittorrent was just updated and needs to be restarted for the changes to be effective.</source> <translation>qBittorrent току-що бе обновен и има нужда от рестарт за да работят промените.</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="165"/> <location filename="../gui/statusbar.cpp" line="170"/> <source>Connection Status:</source> <translation>Състояние на връзката:</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="165"/> <source>Offline. This usually means that qBittorrent failed to listen on the selected port for incoming connections.</source> <translation>Извън мрежа. Това обикновено означава, че qBittorrent не е успял да прослуша избрания порт за входни връзки.</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="170"/> <source>Online</source> <translation>Свързан</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="205"/> <source>Click to switch to alternative speed limits</source> <translation>Натисни за смяна към други ограничения за скорост</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="201"/> <source>Click to switch to regular speed limits</source> <translation>Натисни за смяна към стандартни ограничения за скорост</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="215"/> <source>Manual change of rate limits mode. The scheduler is disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/statusbar.cpp" line="223"/> <source>Global Download Speed Limit</source> <translation>Общ лимит Скорост на сваляне</translation> </message> <message> <location filename="../gui/statusbar.cpp" line="249"/> <source>Global Upload Speed Limit</source> <translation>Общ лимит Скорост на качване</translation> </message> </context> <context> <name>StatusFiltersWidget</name> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="111"/> <source>All (0)</source> <comment>this is for the status filter</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="114"/> <source>Downloading (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="117"/> <source>Seeding (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="120"/> <source>Completed (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="123"/> <source>Resumed (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="126"/> <source>Paused (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="129"/> <source>Active (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="132"/> <source>Inactive (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="148"/> <source>All (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="149"/> <source>Downloading (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="150"/> <source>Seeding (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="151"/> <source>Completed (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="152"/> <source>Paused (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="153"/> <source>Resumed (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="154"/> <source>Active (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="155"/> <source>Inactive (%1)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TorrentContentModel</name> <message> <location filename="../gui/torrentcontentmodel.cpp" line="54"/> <source>Name</source> <translation>Име</translation> </message> <message> <location filename="../gui/torrentcontentmodel.cpp" line="54"/> <source>Size</source> <translation>Размер</translation> </message> <message> <location filename="../gui/torrentcontentmodel.cpp" line="55"/> <source>Progress</source> <translation>Изпълнение</translation> </message> <message> <location filename="../gui/torrentcontentmodel.cpp" line="55"/> <source>Priority</source> <translation>Предимство</translation> </message> </context> <context> <name>TorrentCreatorDlg</name> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="75"/> <source>Select a folder to add to the torrent</source> <translation>Изберете папка за добавяне към торента</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="88"/> <source>Select a file to add to the torrent</source> <translation>Изберете файл за добавяне към торента</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="108"/> <source>No input path set</source> <translation>Не е избран входящ път</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="108"/> <source>Please type an input path first</source> <translation>Моля първо напишете входящ път</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="118"/> <source>Select destination torrent file</source> <translation>Избери торент файл получател</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="118"/> <source>Torrent Files</source> <translation>Торент Файлове</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="145"/> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="159"/> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="171"/> <source>Torrent creation</source> <translation>Създаване на Торент</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="145"/> <source>Torrent creation was unsuccessful, reason: %1</source> <translation>Създаване на торент неуспешно, причина: %1</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="159"/> <source>Created torrent file is invalid. It won&apos;t be added to download list.</source> <translation>Създаденият торент файл е невалиден. Няма да бъде добавен в листа за сваляне.</translation> </message> <message> <location filename="../gui/torrentcreator/torrentcreatordlg.cpp" line="171"/> <source>Torrent was created successfully:</source> <translation>Торента бе създаден успешно:</translation> </message> </context> <context> <name>TorrentImportDlg</name> <message> <location filename="../gui/torrentimportdlg.ui" line="14"/> <source>Torrent Import</source> <translation>Внос на торент</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="53"/> <source>This assistant will help you share with qBittorrent a torrent that you have already downloaded.</source> <translation>Този помощник ще ви помогне до споделите с qBittorrent вече свален торент.</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="65"/> <source>Torrent file to import:</source> <translation>Торент файл за внос:</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="109"/> <source>...</source> <translation>...</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="90"/> <source>Content location:</source> <translation>Място на съдържанието:</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="121"/> <source>Skip the data checking stage and start seeding immediately</source> <translation>Прескочи проверката на данните и започни да даваш веднага</translation> </message> <message> <location filename="../gui/torrentimportdlg.ui" line="131"/> <source>Import</source> <translation>Внос</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="67"/> <source>Torrent file to import</source> <translation>Торент файл за внос</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="67"/> <source>Torrent files</source> <translation>Торент файлове</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="90"/> <source>%1 Files</source> <comment>%1 is a file extension (e.g. PDF)</comment> <translation>%1 файлове</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="92"/> <source>Please provide the location of %1</source> <comment>%1 is a file name</comment> <translation>Моля посочете мястото на %1</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="125"/> <source>Please point to the location of the torrent: %1</source> <translation>Моля посочете мястото на торент: %1</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="228"/> <source>Invalid torrent file</source> <translation>Невалиден торент файл</translation> </message> <message> <location filename="../gui/torrentimportdlg.cpp" line="228"/> <source>This is not a valid torrent file.</source> <translation>Това не е валиден торент файл.</translation> </message> </context> <context> <name>TorrentModel</name> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="422"/> <source>Name</source> <comment>i.e: torrent name</comment> <translation>Име</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="423"/> <source>Size</source> <comment>i.e: torrent size</comment> <translation>Размер</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="424"/> <source>Done</source> <comment>% Done</comment> <translation>Готово</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="425"/> <source>Status</source> <comment>Torrent status (e.g. downloading, seeding, paused)</comment> <translation>Състояние</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="426"/> <source>Seeds</source> <comment>i.e. full sources (often untranslated)</comment> <translation>Споделящи</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="427"/> <source>Peers</source> <comment>i.e. partial sources (often untranslated)</comment> <translation>Двойки</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="428"/> <source>Down Speed</source> <comment>i.e: Download speed</comment> <translation>Скорост Сваляне</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="429"/> <source>Up Speed</source> <comment>i.e: Upload speed</comment> <translation>Скорост на качване</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="430"/> <source>Ratio</source> <comment>Share ratio</comment> <translation>Съотношение</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="431"/> <source>ETA</source> <comment>i.e: Estimated Time of Arrival / Time left</comment> <translation>Оставащо време</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="432"/> <source>Label</source> <translation>Етикет</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="433"/> <source>Added On</source> <comment>Torrent was added to transfer list on 01/01/2010 08:00</comment> <translation>Добавен на</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="434"/> <source>Completed On</source> <comment>Torrent was completed on 01/01/2010 08:00</comment> <translation>Завършен на</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="435"/> <source>Tracker</source> <translation>Тракер</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="436"/> <source>Down Limit</source> <comment>i.e: Download limit</comment> <translation>Лимит сваляне</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="437"/> <source>Up Limit</source> <comment>i.e: Upload limit</comment> <translation>Лимит качване</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="438"/> <source>Downloaded</source> <comment>Amount of data downloaded (e.g. in MB)</comment> <translation>Свалени</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="439"/> <source>Uploaded</source> <comment>Amount of data uploaded (e.g. in MB)</comment> <translation>Качени</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="440"/> <source>Session Download</source> <comment>Amount of data downloaded since program open (e.g. in MB)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="441"/> <source>Session Upload</source> <comment>Amount of data uploaded since program open (e.g. in MB)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="442"/> <source>Remaining</source> <comment>Amount of data left to download (e.g. in MB)</comment> <translation>Оставащо</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="443"/> <source>Time Active</source> <comment>Time (duration) the torrent is active (not paused)</comment> <translation>Време активен</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="444"/> <source>Save path</source> <comment>Torrent save path</comment> <translation>Запазване на пътя</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="445"/> <source>Completed</source> <comment>Amount of data completed (e.g. in MB)</comment> <translation>Приключено</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="446"/> <source>Ratio Limit</source> <comment>Upload share ratio limit</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="447"/> <source>Last Seen Complete</source> <comment>Indicates the time when the torrent was last seen complete/whole</comment> <translation>Последно приключен</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="448"/> <source>Last Activity</source> <comment>Time passed since a chunk was downloaded/uploaded</comment> <translation>Последна активност</translation> </message> <message> <location filename="../core/qtlibtorrent/torrentmodel.cpp" line="449"/> <source>Total Size</source> <comment>i.e. Size including unwanted data</comment> <translation>Пълен размер</translation> </message> </context> <context> <name>TrackerFiltersList</name> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="424"/> <source>All (0)</source> <comment>this is for the label filter</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="427"/> <source>Trackerless (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="430"/> <source>Error (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="433"/> <source>Warning (0)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="476"/> <location filename="../gui/transferlistfilterswidget.cpp" line="533"/> <source>Trackerless (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="482"/> <location filename="../gui/transferlistfilterswidget.cpp" line="528"/> <source>%1 (%2)</source> <comment>openbittorrent.com (10)</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="558"/> <location filename="../gui/transferlistfilterswidget.cpp" line="590"/> <source>Error (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="571"/> <location filename="../gui/transferlistfilterswidget.cpp" line="605"/> <source>Warning (%1)</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="625"/> <source>Couldn&apos;t decode favicon for URL `%1`. Trying to download favicon in PNG format.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="630"/> <source>Couldn&apos;t decode favicon for URL `%1`.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="644"/> <source>Couldn&apos;t download favicon for URL `%1`. Reason: `%2`</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="651"/> <source>Resume torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="652"/> <source>Pause torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="653"/> <source>Delete torrents</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="688"/> <location filename="../gui/transferlistfilterswidget.cpp" line="703"/> <source>All (%1)</source> <comment>this is for the tracker filter</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>TrackerList</name> <message> <location filename="../gui/properties/trackerlist.cpp" line="64"/> <source>URL</source> <translation>URL</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="65"/> <source>Status</source> <translation>Състояние</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="66"/> <source>Peers</source> <translation>Двойки</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="67"/> <source>Message</source> <translation>Съобщение</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="203"/> <location filename="../gui/properties/trackerlist.cpp" line="277"/> <source>Working</source> <translation>Работи</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="204"/> <source>Disabled</source> <translation>Изключено</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="225"/> <source>This torrent is private</source> <translation>Този торент е личен</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="281"/> <source>Updating...</source> <translation>Обновяване...</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="285"/> <source>Not working</source> <translation>Не работи</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="288"/> <source>Not contacted yet</source> <translation>Още не е свързан</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="374"/> <source>Tracker URL:</source> <translation>URL адрес на тракера:</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="374"/> <source>Tracker editing</source> <translation>Редактиране на тракера</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="380"/> <location filename="../gui/properties/trackerlist.cpp" line="393"/> <source>Tracker editing failed</source> <translation>Редактирането на тракера е неуспешно</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="380"/> <source>The tracker URL entered is invalid.</source> <translation>Въведеният URL адрес на тракер е невалиден.</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="393"/> <source>The tracker URL already exists.</source> <translation>URL адреса на тракера вече съществува.</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="455"/> <source>Add a new tracker...</source> <translation>Добави нов тракер...</translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="461"/> <source>Copy tracker URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="462"/> <source>Edit selected tracker URL</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="470"/> <source>Force reannounce to selected trackers</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="473"/> <source>Force reannounce to all trackers</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/properties/trackerlist.cpp" line="460"/> <source>Remove tracker</source> <translation>Премахни тракер</translation> </message> </context> <context> <name>TrackersAdditionDlg</name> <message> <location filename="../gui/properties/trackersadditiondlg.ui" line="14"/> <source>Trackers addition dialog</source> <translation>Допълнителен диалог на тракери</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.ui" line="20"/> <source>List of trackers to add (one per line):</source> <translation>Списък тракери за добавяне (по един на ред):</translation> </message> <message utf8="true"> <location filename="../gui/properties/trackersadditiondlg.ui" line="44"/> <source>µTorrent compatible list URL:</source> <translation>URL на съвместима с µTorrent листа:</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="79"/> <source>I/O Error</source> <translation>Грешка на Вход/Изход</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="79"/> <source>Error while trying to open the downloaded file.</source> <translation>Грешка при опит за отваряне на сваления файл.</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="124"/> <source>No change</source> <translation>Без промяна</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="124"/> <source>No additional trackers were found.</source> <translation>Допълнителни тракери не бяха намерени.</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="133"/> <source>Download error</source> <translation>Грешка при сваляне</translation> </message> <message> <location filename="../gui/properties/trackersadditiondlg.h" line="133"/> <source>The trackers list could not be downloaded, reason: %1</source> <translation>Листата на тракера не може да бъде свалена, причина: %1</translation> </message> </context> <context> <name>TransferListDelegate</name> <message> <location filename="../gui/transferlistdelegate.cpp" line="95"/> <source>Downloading</source> <translation>Сваляне</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="98"/> <source>Downloading metadata</source> <comment>used when loading a magnet link</comment> <translation>Сваляне на метаданните</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="104"/> <source>Allocating</source> <comment>qBittorrent is allocating the files on disk</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="131"/> <source>Paused</source> <translation>Пауза</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="118"/> <source>Queued</source> <comment>i.e. torrent is queued</comment> <translation>Прикачен</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="111"/> <source>Seeding</source> <comment>Torrent is complete and in upload-only mode</comment> <translation>Споделяне</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="107"/> <source>Stalled</source> <comment>Torrent is waiting for download to begin</comment> <translation>Отложен</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="101"/> <source>[F] Downloading</source> <comment>used when the torrent is forced started. You probably shouldn&apos;t translate the F.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="114"/> <source>[F] Seeding</source> <comment>used when the torrent is forced started. You probably shouldn&apos;t translate the F.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="122"/> <source>Checking</source> <comment>Torrent local data is being checked</comment> <translation>Проверка</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="125"/> <source>Queued for checking</source> <comment>i.e. torrent is queued for hash checking</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="128"/> <source>Checking resume data</source> <comment>used when loading the torrents from disk after qbt is launched. It checks the correctness of the .fastresume file. Normally it is completed in a fraction of a second, unless loading many many torrents.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="134"/> <source>Completed</source> <translation type="unfinished">Приключено</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="137"/> <source>Missing Files</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="151"/> <source>/s</source> <comment>/second (.i.e per second)</comment> <translation>/с</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="159"/> <source>KiB/s</source> <comment>KiB/second (.i.e per second)</comment> <translation>KiB/с</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="167"/> <source>Seeded for %1</source> <comment>e.g. Seeded for 3m10s</comment> <translation>Даващ за %1</translation> </message> <message> <location filename="../gui/transferlistdelegate.cpp" line="230"/> <source>%1 ago</source> <comment>e.g.: 1h 20m ago</comment> <translation>%1 по- рано</translation> </message> </context> <context> <name>TransferListFiltersWidget</name> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="785"/> <source>Status</source> <translation type="unfinished">Състояние</translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="793"/> <source>Labels</source> <translation>Етикети</translation> </message> <message> <location filename="../gui/transferlistfilterswidget.cpp" line="801"/> <source>Trackers</source> <translation type="unfinished">Тракери</translation> </message> </context> <context> <name>TransferListWidget</name> <message> <location filename="../gui/transferlistwidget.cpp" line="588"/> <source>Column visibility</source> <translation>Видимост на колона</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="861"/> <source>Label</source> <translation>Етикет</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="257"/> <source>Choose save path</source> <translation>Избери път за съхранение</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="506"/> <source>Torrent Download Speed Limiting</source> <translation>Ограничаване Скорост на сваляне</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="539"/> <source>Torrent Upload Speed Limiting</source> <translation>Ограничаване Скорост на качване</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="576"/> <source>Recheck confirmation</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="576"/> <source>Are you sure you want to recheck the selected torrent(s)?</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="660"/> <source>New Label</source> <translation>Нов етикет</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="660"/> <source>Label:</source> <translation>Етикет:</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="666"/> <source>Invalid label name</source> <translation>Невалидно име на етикет</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="666"/> <source>Please don&apos;t use any special characters in the label name.</source> <translation>Моля, не ползвайте специални символи в името на етикета.</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="694"/> <source>Rename</source> <translation>Преименувай</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="694"/> <source>New name:</source> <translation>Ново име:</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="735"/> <source>Resume</source> <comment>Resume/start the torrent</comment> <translation>Продължи</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="739"/> <source>Force Resume</source> <comment>Force Resume/start the torrent</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="737"/> <source>Pause</source> <comment>Pause the torrent</comment> <translation>Пауза</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="741"/> <source>Delete</source> <comment>Delete the torrent</comment> <translation>Изтрий</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="743"/> <source>Preview file...</source> <translation>Огледай файла...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="745"/> <source>Limit share ratio...</source> <translation>Ограничение на съотношението за споделяне...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="747"/> <source>Limit upload rate...</source> <translation>Ограничи процент качване...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="749"/> <source>Limit download rate...</source> <translation>Ограничи процент сваляне...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="751"/> <source>Open destination folder</source> <translation>Отвори папка получател</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="753"/> <source>Move up</source> <comment>i.e. move up in the queue</comment> <translation>Нагоре в листата</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="755"/> <source>Move down</source> <comment>i.e. Move down in the queue</comment> <translation>Надолу в листата</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="757"/> <source>Move to top</source> <comment>i.e. Move to top of the queue</comment> <translation>На върха на листата</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="759"/> <source>Move to bottom</source> <comment>i.e. Move to bottom of the queue</comment> <translation>На дъното на листата</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="761"/> <source>Set location...</source> <translation>Определи място...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="767"/> <source>Copy name</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="905"/> <source>Priority</source> <translation>Предимство</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="763"/> <source>Force recheck</source> <translation>Включени проверки за промени</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="765"/> <source>Copy magnet link</source> <translation>Копирай връзка magnet</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="769"/> <source>Super seeding mode</source> <translation>Режим на супер-даване</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="772"/> <source>Rename...</source> <translation>Преименувай...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="774"/> <source>Download in sequential order</source> <translation>Сваляне по азбучен ред</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="777"/> <source>Download first and last piece first</source> <translation>Свали първо и последно парче първо</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="862"/> <source>New...</source> <comment>New label...</comment> <translation>Ново...</translation> </message> <message> <location filename="../gui/transferlistwidget.cpp" line="863"/> <source>Reset</source> <comment>Reset label</comment> <translation>Нулирай</translation> </message> </context> <context> <name>UpDownRatioDlg</name> <message> <location filename="../gui/updownratiodlg.ui" line="14"/> <source>Torrent Upload/Download Ratio Limiting</source> <translation>Ограничение на съотношението Сваляне/Качване на торента</translation> </message> <message> <location filename="../gui/updownratiodlg.ui" line="20"/> <source>Use global ratio limit</source> <translation>Ползвай стандартното ограничение</translation> </message> <message> <location filename="../gui/updownratiodlg.ui" line="23"/> <location filename="../gui/updownratiodlg.ui" line="33"/> <location filename="../gui/updownratiodlg.ui" line="45"/> <source>buttonGroup</source> <translation>група Бутони</translation> </message> <message> <location filename="../gui/updownratiodlg.ui" line="30"/> <source>Set no ratio limit</source> <translation>Не определяй ограничение</translation> </message> <message> <location filename="../gui/updownratiodlg.ui" line="42"/> <source>Set ratio limit to</source> <translation>Определи ограничение на</translation> </message> </context> <context> <name>WebUI</name> <message> <location filename="../webui/webui.cpp" line="77"/> <source>The Web UI is listening on port %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../webui/webui.cpp" line="79"/> <source>Web UI Error - Unable to bind Web UI to port %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>about</name> <message> <location filename="../gui/about_imp.h" line="55"/> <source>An advanced BitTorrent client programmed in &lt;nobr&gt;C++&lt;/nobr&gt;, based on Qt toolkit and libtorrent-rasterbar.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/about_imp.h" line="57"/> <source>Copyright %1 2006-2015 The qBittorrent project</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/about_imp.h" line="59"/> <source>Home Page: </source> <translation>Домашна страница:</translation> </message> <message> <location filename="../gui/about_imp.h" line="61"/> <source>Bug Tracker: </source> <translation>Докладване на грешки:</translation> </message> <message> <location filename="../gui/about_imp.h" line="63"/> <source>Forum: </source> <translation>Форум:</translation> </message> <message> <location filename="../gui/about_imp.h" line="66"/> <source>IRC: #qbittorrent on Freenode</source> <translation>IRC: #qbittorrent на Freenode</translation> </message> </context> <context> <name>addPeerDialog</name> <message> <location filename="../gui/properties/peer.ui" line="20"/> <source>Peer addition</source> <translation>Добавяне на двойка</translation> </message> <message> <location filename="../gui/properties/peer.ui" line="36"/> <source>IP</source> <translation>IP</translation> </message> <message> <location filename="../gui/properties/peer.ui" line="59"/> <source>Port</source> <translation>Порт</translation> </message> </context> <context> <name>authentication</name> <message> <location filename="../gui/login.ui" line="14"/> <location filename="../gui/login.ui" line="47"/> <source>Tracker authentication</source> <translation>Удостоверяване на тракера</translation> </message> <message> <location filename="../gui/login.ui" line="64"/> <source>Tracker:</source> <translation>Тракер:</translation> </message> <message> <location filename="../gui/login.ui" line="86"/> <source>Login</source> <translation>Вход</translation> </message> <message> <location filename="../gui/login.ui" line="94"/> <source>Username:</source> <translation>Име на потребителя:</translation> </message> <message> <location filename="../gui/login.ui" line="117"/> <source>Password:</source> <translation>Парола:</translation> </message> <message> <location filename="../gui/login.ui" line="154"/> <source>Log in</source> <translation>Влизане</translation> </message> <message> <location filename="../gui/login.ui" line="161"/> <source>Cancel</source> <translation>Прекъсни</translation> </message> </context> <context> <name>confirmDeletionDlg</name> <message> <location filename="../gui/confirmdeletiondlg.ui" line="20"/> <source>Deletion confirmation - qBittorrent</source> <translation>Потвърждение за изтриване -- qBittorrent</translation> </message> <message> <location filename="../gui/confirmdeletiondlg.ui" line="67"/> <source>Remember choice</source> <translation>Запомни избора</translation> </message> <message> <location filename="../gui/confirmdeletiondlg.ui" line="94"/> <source>Also delete the files on the hard disk</source> <translation>Също изтрий файловете от твърдия диск</translation> </message> </context> <context> <name>createTorrentDialog</name> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="308"/> <source>Cancel</source> <translation>Прекъсни</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="14"/> <source>Torrent Creation Tool</source> <translation>Инструмент за Създаване на Торент</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="38"/> <source>Torrent file creation</source> <translation>Създаване на Торент файл</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="60"/> <source>Add file</source> <translation>Добави файл</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="67"/> <source>Add folder</source> <translation>Добави папка</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="48"/> <source>File or folder to add to the torrent:</source> <translation>Файл или папка за добавяне към торента:</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="78"/> <source>Tracker URLs:</source> <translation>Тракери URL:</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="88"/> <source>Web seeds urls:</source> <translation>Web даващи URL:</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="98"/> <source>Comment:</source> <translation>Коментар:</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="127"/> <source>You can separate tracker tiers / groups with an empty line.</source> <comment>A tracker tier is a group of trackers, consisting of a main tracker and its mirrors.</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="148"/> <source>Piece size:</source> <translation>Размер на част:</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="165"/> <source>16 KiB</source> <translation type="unfinished">512 КБ {16 ?}</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="170"/> <source>32 KiB</source> <translation>32 КБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="175"/> <source>64 KiB</source> <translation>64 КБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="180"/> <source>128 KiB</source> <translation>128 КБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="185"/> <source>256 KiB</source> <translation>256 КБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="190"/> <source>512 KiB</source> <translation>512 КБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="195"/> <source>1 MiB</source> <translation>1 МБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="200"/> <source>2 MiB</source> <translation>2 МБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="205"/> <source>4 MiB</source> <translation>4 МБ</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="210"/> <source>8 MiB</source> <translation type="unfinished">4 МБ {8 ?}</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="215"/> <source>16 MiB</source> <translation type="unfinished">4 МБ {16 ?}</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="223"/> <source>Auto</source> <translation>Автоматично</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="248"/> <source>Private (won&apos;t be distributed on DHT network if enabled)</source> <translation>Лично (няма да бъде разпространено по мрежа DHT ако е включено)</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="255"/> <source>Start seeding after creation</source> <translation>Започни даване след образуване</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="265"/> <source>Ignore share ratio limits for this torrent</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="301"/> <source>Create and save...</source> <translation>Създай и съхрани...</translation> </message> <message> <location filename="../gui/torrentcreator/createtorrent.ui" line="272"/> <source>Progress:</source> <translation>Изпълнение:</translation> </message> </context> <context> <name>downloadFromURL</name> <message> <location filename="../gui/downloadfromurldlg.ui" line="28"/> <source>Add torrent links</source> <translation>Добави връзки торент</translation> </message> <message> <location filename="../gui/downloadfromurldlg.ui" line="58"/> <source>One per line (HTTP links, Magnet links and info-hashes are supported)</source> <translation>По един на ред (поддържат се HTTP връзки, магнитни линкове и инфо-хешове)</translation> </message> <message> <location filename="../gui/downloadfromurldlg.ui" line="80"/> <source>Download</source> <translation>Свали</translation> </message> <message> <location filename="../gui/downloadfromurldlg.ui" line="87"/> <source>Cancel</source> <translation>Прекъсни</translation> </message> <message> <location filename="../gui/downloadfromurldlg.ui" line="14"/> <source>Download from urls</source> <translation>Свали от url-ове</translation> </message> <message> <location filename="../gui/downloadfromurldlg.h" line="96"/> <source>No URL entered</source> <translation>Невъведен URL</translation> </message> <message> <location filename="../gui/downloadfromurldlg.h" line="96"/> <source>Please type at least one URL.</source> <translation>Моля въведете поне един URL.</translation> </message> </context> <context> <name>engineSelect</name> <message> <location filename="../searchengine/engineselect.ui" line="17"/> <source>Search plugins</source> <translation>Търси добавки</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="30"/> <source>Installed search engines:</source> <translation>Инсталирани търсачки:</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="50"/> <source>Name</source> <translation>Име</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="55"/> <source>Version</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="60"/> <source>Url</source> <translation>Url</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="65"/> <location filename="../searchengine/engineselect.ui" line="124"/> <source>Enabled</source> <translation>Включено</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="83"/> <source>You can get new search engine plugins here: &lt;a href=&quot;http://plugins.qbittorrent.org&quot;&gt;http://plugins.qbittorrent.org&lt;/a&gt;</source> <translation>Можете да вземете нови добавки за търсачката тук: &lt;a href=&quot;http:plugins.qbittorrent.org&quot;&gt;http://plugins.qbittorrent.org&lt;/a&gt;</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="98"/> <source>Install a new one</source> <translation>Инсталирай нов</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="105"/> <source>Check for updates</source> <translation>Провери за обновяване</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="112"/> <source>Close</source> <translation>Затвори</translation> </message> <message> <location filename="../searchengine/engineselect.ui" line="129"/> <source>Uninstall</source> <translation>Деинсталирай</translation> </message> </context> <context> <name>engineSelectDlg</name> <message> <location filename="../searchengine/engineselectdlg.cpp" line="195"/> <source>Uninstall warning</source> <translation>Предупреждение за деинсталиране </translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="197"/> <source>Uninstall success</source> <translation>Успешно деинсталиране</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="362"/> <source>The link doesn&apos;t seem to point to a search engine plugin.</source> <translation>Връзката изглежда не води към добавката за търсачката.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="377"/> <source>Select search plugins</source> <translation>Избери добавки за търсене</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="258"/> <location filename="../searchengine/engineselectdlg.cpp" line="283"/> <location filename="../searchengine/engineselectdlg.cpp" line="288"/> <location filename="../searchengine/engineselectdlg.cpp" line="298"/> <location filename="../searchengine/engineselectdlg.cpp" line="301"/> <source>Search plugin install</source> <translation>Инсталиране на добавка за търсене </translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="138"/> <location filename="../searchengine/engineselectdlg.cpp" line="209"/> <location filename="../searchengine/engineselectdlg.cpp" line="321"/> <source>Yes</source> <translation>Да</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="141"/> <location filename="../searchengine/engineselectdlg.cpp" line="175"/> <location filename="../searchengine/engineselectdlg.cpp" line="212"/> <location filename="../searchengine/engineselectdlg.cpp" line="324"/> <source>No</source> <translation>Не</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="258"/> <source>A more recent version of %1 search engine plugin is already installed.</source> <comment>%1 is the name of the search engine</comment> <translation>По-нова версия на %1 добавката за търсене вече е инсталирана.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="378"/> <source>qBittorrent search plugin</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="429"/> <location filename="../searchengine/engineselectdlg.cpp" line="463"/> <location filename="../searchengine/engineselectdlg.cpp" line="484"/> <location filename="../searchengine/engineselectdlg.cpp" line="491"/> <source>Search plugin update</source> <translation>Добавката за търсене е обновена</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="463"/> <location filename="../searchengine/engineselectdlg.cpp" line="484"/> <source>Sorry, update server is temporarily unavailable.</source> <translation>Съжалявам, сървъра за обновяване е временно недостъпен.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="429"/> <source>All your plugins are already up to date.</source> <translation>Всички ваши добавки са вече обновени.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="283"/> <source>%1 search engine plugin could not be updated, keeping old version.</source> <comment>%1 is the name of the search engine</comment> <translation>%1 добавка на търсачката не бе обновена, запазване на досегашната версия.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="288"/> <source>%1 search engine plugin could not be installed.</source> <comment>%1 is the name of the search engine</comment> <translation>%1 добавка на търсачката не бе инсталирана.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="197"/> <source>All selected plugins were uninstalled successfully</source> <translation>Всички избрани добавки бяха успешно деинсталирани</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="195"/> <source>Some plugins could not be uninstalled because they are included in qBittorrent. Only the ones you added yourself can be uninstalled. Those plugins were disabled.</source> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="298"/> <source>%1 search engine plugin was successfully updated.</source> <comment>%1 is the name of the search engine</comment> <translation>%1 добавка на търсачката беше успешно обновена.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="301"/> <source>%1 search engine plugin was successfully installed.</source> <comment>%1 is the name of the search engine</comment> <translation>%1 добавка на търсачката беше успешно обновена.</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="362"/> <source>Invalid link</source> <translation>Невалиден адрес</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="491"/> <source>Sorry, %1 search plugin installation failed.</source> <comment>%1 is the name of the search engine</comment> <translation type="unfinished"></translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="354"/> <location filename="../searchengine/engineselectdlg.cpp" line="363"/> <source>New search engine plugin URL</source> <translation>Нов URL за добавки на търсачката</translation> </message> <message> <location filename="../searchengine/engineselectdlg.cpp" line="355"/> <location filename="../searchengine/engineselectdlg.cpp" line="364"/> <source>URL:</source> <translation>URL:</translation> </message> </context> <context> <name>errorDialog</name> <message> <location filename="../app/stacktrace_win_dlg.ui" line="14"/> <source>Crash info</source> <translation>Информация за сривове</translation> </message> </context> <context> <name>fsutils</name> <message> <location filename="../core/fs_utils.cpp" line="475"/> <location filename="../core/fs_utils.cpp" line="478"/> <location filename="../core/fs_utils.cpp" line="510"/> <location filename="../core/fs_utils.cpp" line="522"/> <source>Downloads</source> <translation>Сваляния</translation> </message> </context> <context> <name>misc</name> <message> <location filename="../core/misc.cpp" line="86"/> <source>B</source> <comment>bytes</comment> <translation>Б</translation> </message> <message> <location filename="../core/misc.cpp" line="87"/> <source>KiB</source> <comment>kibibytes (1024 bytes)</comment> <translation>КБ</translation> </message> <message> <location filename="../core/misc.cpp" line="88"/> <source>MiB</source> <comment>mebibytes (1024 kibibytes)</comment> <translation>МБ</translation> </message> <message> <location filename="../core/misc.cpp" line="89"/> <source>GiB</source> <comment>gibibytes (1024 mibibytes)</comment> <translation>ГБ</translation> </message> <message> <location filename="../core/misc.cpp" line="90"/> <source>TiB</source> <comment>tebibytes (1024 gibibytes)</comment> <translation>ТБ</translation> </message> <message> <location filename="../core/misc.cpp" line="314"/> <source>Python not detected</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/misc.cpp" line="337"/> <source>Python version: %1</source> <translation type="unfinished"></translation> </message> <message> <location filename="../core/misc.cpp" line="363"/> <source>/s</source> <comment>per second</comment> <translation>/с</translation> </message> <message> <location filename="../core/misc.cpp" line="473"/> <source>%1h %2m</source> <comment>e.g: 3hours 5minutes</comment> <translation>%1ч%2мин</translation> </message> <message> <location filename="../core/misc.cpp" line="477"/> <source>%1d %2h</source> <comment>e.g: 2days 10hours</comment> <translation>%1д%2ч</translation> </message> <message> <location filename="../core/misc.cpp" line="351"/> <source>Unknown</source> <comment>Unknown (size)</comment> <translation>Неизвестен</translation> </message> <message> <location filename="../core/misc.cpp" line="237"/> <source>qBittorrent will shutdown the computer now because all downloads are complete.</source> <translation>qBittorrent ще угаси компютъра, защото всички сваляния са завършени.</translation> </message> <message> <location filename="../core/misc.cpp" line="466"/> <source>&lt; 1m</source> <comment>&lt; 1 minute</comment> <translation>&lt; 1мин</translation> </message> <message> <location filename="../core/misc.cpp" line="469"/> <source>%1m</source> <comment>e.g: 10minutes</comment> <translation>%1мин</translation> </message> <message> <location filename="../webui/btjson.cpp" line="378"/> <source>Working</source> <translation>Работи</translation> </message> <message> <location filename="../webui/btjson.cpp" line="382"/> <source>Updating...</source> <translation>Обновяване...</translation> </message> <message> <location filename="../webui/btjson.cpp" line="384"/> <source>Not working</source> <translation>Не работи</translation> </message> <message> <location filename="../webui/btjson.cpp" line="384"/> <source>Not contacted yet</source> <translation>Още не е свързан</translation> </message> </context> <context> <name>options_imp</name> <message> <location filename="../gui/options_imp.cpp" line="1174"/> <location filename="../gui/options_imp.cpp" line="1176"/> <source>Choose export directory</source> <translation>Изберете Директория за Експорт</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1212"/> <location filename="../gui/options_imp.cpp" line="1214"/> <location filename="../gui/options_imp.cpp" line="1225"/> <location filename="../gui/options_imp.cpp" line="1227"/> <source>Choose a save directory</source> <translation>Изберете директория за съхранение</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1128"/> <source>Add directory to scan</source> <translation>Добави директория за сканиране</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1135"/> <source>Folder is already being watched.</source> <translation>Папката вече се наблюдава.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1138"/> <source>Folder does not exist.</source> <translation>Папката не съществува.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1141"/> <source>Folder is not readable.</source> <translation>Папката не се чете.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1151"/> <source>Failure</source> <translation>Грешка</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1151"/> <source>Failed to add Scan Folder &apos;%1&apos;: %2</source> <translation>Грешка при добавяне Папка за Сканиране &apos;%1&apos;: %2</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1198"/> <location filename="../gui/options_imp.cpp" line="1200"/> <source>Filters</source> <translation>Филтри</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1198"/> <location filename="../gui/options_imp.cpp" line="1200"/> <source>Choose an IP filter file</source> <translation type="unfinished"></translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1266"/> <source>SSL Certificate</source> <translation>SSL сертификат</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1277"/> <source>SSL Key</source> <translation>SSL ключ</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1308"/> <source>Parsing error</source> <translation>Грешка при вмъкване</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1308"/> <source>Failed to parse the provided IP filter</source> <translation>Неуспешно вмъкване на дадения IP филтър</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1310"/> <source>Successfully refreshed</source> <translation>Успешно обновен</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1310"/> <source>Successfully parsed the provided IP filter: %1 rules were applied.</source> <comment>%1 is a number</comment> <translation>Успешно вмъкване на дадения IP филтър: %1 правила бяха добавени.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1397"/> <source>Invalid key</source> <translation>Невалиден ключ</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1397"/> <source>This is not a valid SSL key.</source> <translation>Това е невалиден SSL-ключ.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1412"/> <source>Invalid certificate</source> <translation>Невалиден сертификат</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1412"/> <source>This is not a valid SSL certificate.</source> <translation>Това не е валиден SSL сертификат.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1421"/> <source>The start time and the end time can&apos;t be the same.</source> <translation>Времето на стартиране и приключване не може да бъде едно и също.</translation> </message> <message> <location filename="../gui/options_imp.cpp" line="1424"/> <source>Time Error</source> <translation>Грешка във времето</translation> </message> </context> <context> <name>pluginSourceDlg</name> <message> <location filename="../searchengine/pluginsource.ui" line="13"/> <source>Plugin source</source> <translation>Източник на добавката</translation> </message> <message> <location filename="../searchengine/pluginsource.ui" line="26"/> <source>Search plugin source:</source> <translation>Търсене на източници на добавки:</translation> </message> <message> <location filename="../searchengine/pluginsource.ui" line="35"/> <source>Local file</source> <translation>Локален файл</translation> </message> <message> <location filename="../searchengine/pluginsource.ui" line="42"/> <source>Web link</source> <translation>Web линк</translation> </message> </context> <context> <name>preview</name> <message> <location filename="../gui/preview.ui" line="14"/> <source>Preview selection</source> <translation>Оглед на избраното</translation> </message> <message> <location filename="../gui/preview.ui" line="26"/> <source>The following files support previewing, please select one of them:</source> <translation>Следните файлове поддържат предварителен преглед, моля, изберете един от тях:</translation> </message> <message> <location filename="../gui/preview.ui" line="61"/> <source>Preview</source> <translation>Оглед</translation> </message> <message> <location filename="../gui/preview.ui" line="68"/> <source>Cancel</source> <translation>Прекъсни</translation> </message> </context> <context> <name>search_engine</name> <message> <location filename="../searchengine/search.ui" line="14"/> <location filename="../searchengine/search.ui" line="34"/> <source>Search</source> <translation>Търси</translation> </message> <message> <location filename="../searchengine/search.ui" line="57"/> <source>Status:</source> <translation>Състояние:</translation> </message> <message> <location filename="../searchengine/search.ui" line="81"/> <source>Stopped</source> <translation>Спрян</translation> </message> <message> <location filename="../searchengine/search.ui" line="113"/> <source>Download</source> <translation>Свали</translation> </message> <message> <location filename="../searchengine/search.ui" line="123"/> <source>Go to description page</source> <translation>Отиди в страницата с описанието</translation> </message> <message> <location filename="../searchengine/search.ui" line="143"/> <source>Search engines...</source> <translation>Търсачки...</translation> </message> </context> </TS><|fim▁end|>
<message> <location filename="../searchengine/supportedengines.h" line="56"/> <source>Music</source>
<|file_name|>server.py<|end_file_name|><|fim▁begin|>#----------------------------------------------------------- # Threaded, Gevent and Prefork Servers #----------------------------------------------------------- import datetime import errno import logging import os import os.path import platform import psutil import random import resource import select import signal import socket import subprocess import sys import threading import time import werkzeug.serving try: import fcntl except ImportError: pass try: from setproctitle import setproctitle except ImportError: setproctitle = lambda x: None import openerp import openerp.tools.config as config from openerp.release import nt_service_name from openerp.tools.misc import stripped_sys_argv, dumpstacks import wsgi_server _logger = logging.getLogger(__name__) SLEEP_INTERVAL = 60 # 1 min def memory_info(process): """ psutil < 2.0 does not have memory_info, >= 3.0 does not have get_memory_info """ pmem = (getattr(process, 'memory_info', None) or process.get_memory_info)() return (pmem.rss, pmem.vms) #---------------------------------------------------------- # Werkzeug WSGI servers patched #---------------------------------------------------------- class BaseWSGIServerNoBind(werkzeug.serving.BaseWSGIServer): """ werkzeug Base WSGI Server patched to skip socket binding. PreforkServer use this class, sets the socket and calls the process_request() manually """ def __init__(self, app): werkzeug.serving.BaseWSGIServer.__init__(self, "1", "1", app) def server_bind(self): # we dont bind beause we use the listen socket of PreforkServer#socket # instead we close the socket if self.socket: self.socket.close() def server_activate(self): # dont listen as we use PreforkServer#socket pass # _reexec() should set LISTEN_* to avoid connection refused during reload time. It # should also work with systemd socket activation. This is currently untested # and not yet used. class ThreadedWSGIServerReloadable(werkzeug.serving.ThreadedWSGIServer): """ werkzeug Threaded WSGI Server patched to allow reusing a listen socket given by the environement, this is used by autoreload to keep the listen socket open when a reload happens. """ def server_bind(self): envfd = os.environ.get('LISTEN_FDS') if envfd and os.environ.get('LISTEN_PID') == str(os.getpid()): self.reload_socket = True self.socket = socket.fromfd(int(envfd), socket.AF_INET, socket.SOCK_STREAM) # should we os.close(int(envfd)) ? it seem python duplicate the fd. else: self.reload_socket = False super(ThreadedWSGIServerReloadable, self).server_bind() def server_activate(self): if not self.reload_socket: super(ThreadedWSGIServerReloadable, self).server_activate() #---------------------------------------------------------- # AutoReload watcher #---------------------------------------------------------- class AutoReload(object): def __init__(self, server): self.server = server self.files = {} self.modules = {} import pyinotify class EventHandler(pyinotify.ProcessEvent):<|fim▁hole|> def process_IN_CREATE(self, event): _logger.debug('File created: %s', event.pathname) self.autoreload.files[event.pathname] = 1 def process_IN_MODIFY(self, event): _logger.debug('File modified: %s', event.pathname) self.autoreload.files[event.pathname] = 1 self.wm = pyinotify.WatchManager() self.handler = EventHandler(self) self.notifier = pyinotify.Notifier(self.wm, self.handler, timeout=0) mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE # IN_MOVED_FROM, IN_MOVED_TO ? for path in openerp.tools.config.options["addons_path"].split(','): _logger.info('Watching addons folder %s', path) self.wm.add_watch(path, mask, rec=True) def process_data(self, files): xml_files = [i for i in files if i.endswith('.xml')] addons_path = openerp.tools.config.options["addons_path"].split(',') for i in xml_files: for path in addons_path: if i.startswith(path): # find out wich addons path the file belongs to # and extract it's module name right = i[len(path) + 1:].split('/') if len(right) < 2: continue module = right[0] self.modules[module]=1 if self.modules: _logger.info('autoreload: xml change detected, autoreload activated') restart() def process_python(self, files): # process python changes py_files = [i for i in files if i.endswith('.py')] py_errors = [] # TODO keep python errors until they are ok if py_files: for i in py_files: try: source = open(i, 'rb').read() + '\n' compile(source, i, 'exec') except SyntaxError: py_errors.append(i) if py_errors: _logger.info('autoreload: python code change detected, errors found') for i in py_errors: _logger.info('autoreload: SyntaxError %s',i) else: _logger.info('autoreload: python code updated, autoreload activated') restart() def check_thread(self): # Check if some files have been touched in the addons path. # If true, check if the touched file belongs to an installed module # in any of the database used in the registry manager. while 1: while self.notifier.check_events(1000): self.notifier.read_events() self.notifier.process_events() l = self.files.keys() self.files.clear() self.process_data(l) self.process_python(l) def run(self): t = threading.Thread(target=self.check_thread) t.setDaemon(True) t.start() _logger.info('AutoReload watcher running') #---------------------------------------------------------- # Servers: Threaded, Gevented and Prefork #---------------------------------------------------------- class CommonServer(object): def __init__(self, app): # TODO Change the xmlrpc_* options to http_* self.app = app # config self.interface = config['xmlrpc_interface'] or '0.0.0.0' self.port = config['xmlrpc_port'] # runtime self.pid = os.getpid() def close_socket(self, sock): """ Closes a socket instance cleanly :param sock: the network socket to close :type sock: socket.socket """ try: sock.shutdown(socket.SHUT_RDWR) except socket.error, e: # On OSX, socket shutdowns both sides if any side closes it # causing an error 57 'Socket is not connected' on shutdown # of the other side (or something), see # http://bugs.python.org/issue4397 # note: stdlib fixed test, not behavior if e.errno != errno.ENOTCONN or platform.system() not in ['Darwin', 'Windows']: raise sock.close() class ThreadedServer(CommonServer): def __init__(self, app): super(ThreadedServer, self).__init__(app) self.main_thread_id = threading.currentThread().ident # Variable keeping track of the number of calls to the signal handler defined # below. This variable is monitored by ``quit_on_signals()``. self.quit_signals_received = 0 #self.socket = None self.httpd = None def signal_handler(self, sig, frame): if sig in [signal.SIGINT,signal.SIGTERM]: # shutdown on kill -INT or -TERM self.quit_signals_received += 1 if self.quit_signals_received > 1: # logging.shutdown was already called at this point. sys.stderr.write("Forced shutdown.\n") os._exit(0) elif sig == signal.SIGHUP: # restart on kill -HUP openerp.phoenix = True self.quit_signals_received += 1 def cron_thread(self, number): while True: time.sleep(SLEEP_INTERVAL + number) # Steve Reich timing style registries = openerp.modules.registry.RegistryManager.registries _logger.debug('cron%d polling for jobs', number) for db_name, registry in registries.items(): while True and registry.ready: acquired = openerp.addons.base.ir.ir_cron.ir_cron._acquire_job(db_name) if not acquired: break def cron_spawn(self): """ Start the above runner function in a daemon thread. The thread is a typical daemon thread: it will never quit and must be terminated when the main process exits - with no consequence (the processing threads it spawns are not marked daemon). """ # Force call to strptime just before starting the cron thread # to prevent time.strptime AttributeError within the thread. # See: http://bugs.python.org/issue7980 datetime.datetime.strptime('2012-01-01', '%Y-%m-%d') for i in range(openerp.tools.config['max_cron_threads']): def target(): self.cron_thread(i) t = threading.Thread(target=target, name="openerp.service.cron.cron%d" % i) t.setDaemon(True) t.start() _logger.debug("cron%d started!" % i) def http_thread(self): def app(e,s): return self.app(e,s) self.httpd = ThreadedWSGIServerReloadable(self.interface, self.port, app) self.httpd.serve_forever() def http_spawn(self): threading.Thread(target=self.http_thread).start() _logger.info('HTTP service (werkzeug) running on %s:%s', self.interface, self.port) def start(self): _logger.debug("Setting signal handlers") if os.name == 'posix': signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) signal.signal(signal.SIGCHLD, self.signal_handler) signal.signal(signal.SIGHUP, self.signal_handler) signal.signal(signal.SIGQUIT, dumpstacks) elif os.name == 'nt': import win32api win32api.SetConsoleCtrlHandler(lambda sig: signal_handler(sig, None), 1) self.cron_spawn() self.http_spawn() def stop(self): """ Shutdown the WSGI server. Wait for non deamon threads. """ _logger.info("Initiating shutdown") _logger.info("Hit CTRL-C again or send a second signal to force the shutdown.") self.httpd.shutdown() self.close_socket(self.httpd.socket) # Manually join() all threads before calling sys.exit() to allow a second signal # to trigger _force_quit() in case some non-daemon threads won't exit cleanly. # threading.Thread.join() should not mask signals (at least in python 2.5). me = threading.currentThread() _logger.debug('current thread: %r', me) for thread in threading.enumerate(): _logger.debug('process %r (%r)', thread, thread.isDaemon()) if thread != me and not thread.isDaemon() and thread.ident != self.main_thread_id: while thread.isAlive(): _logger.debug('join and sleep') # Need a busyloop here as thread.join() masks signals # and would prevent the forced shutdown. thread.join(0.05) time.sleep(0.05) _logger.debug('--') openerp.modules.registry.RegistryManager.delete_all() logging.shutdown() def run(self): """ Start the http server and the cron thread then wait for a signal. The first SIGINT or SIGTERM signal will initiate a graceful shutdown while a second one if any will force an immediate exit. """ self.start() # Wait for a first signal to be handled. (time.sleep will be interrupted # by the signal handler.) The try/except is for the win32 case. try: while self.quit_signals_received == 0: time.sleep(60) except KeyboardInterrupt: pass self.stop() def reload(self): os.kill(self.pid, signal.SIGHUP) class GeventServer(CommonServer): def __init__(self, app): super(GeventServer, self).__init__(app) self.port = config['longpolling_port'] self.httpd = None def watch_parent(self, beat=4): import gevent ppid = os.getppid() while True: if ppid != os.getppid(): pid = os.getpid() _logger.info("LongPolling (%s) Parent changed", pid) # suicide !! os.kill(pid, signal.SIGTERM) return gevent.sleep(beat) def start(self): import gevent from gevent.wsgi import WSGIServer if os.name == 'posix': signal.signal(signal.SIGQUIT, dumpstacks) gevent.spawn(self.watch_parent) self.httpd = WSGIServer((self.interface, self.port), self.app) _logger.info('Evented Service (longpolling) running on %s:%s', self.interface, self.port) self.httpd.serve_forever() def stop(self): import gevent self.httpd.stop() gevent.shutdown() def run(self): self.start() self.stop() class PreforkServer(CommonServer): """ Multiprocessing inspired by (g)unicorn. PreforkServer (aka Multicorn) currently uses accept(2) as dispatching method between workers but we plan to replace it by a more intelligent dispatcher to will parse the first HTTP request line. """ def __init__(self, app): # config self.address = (config['xmlrpc_interface'] or '0.0.0.0', config['xmlrpc_port']) self.population = config['workers'] self.timeout = config['limit_time_real'] self.limit_request = config['limit_request'] # working vars self.beat = 4 self.app = app self.pid = os.getpid() self.socket = None self.workers_http = {} self.workers_cron = {} self.workers = {} self.generation = 0 self.queue = [] self.long_polling_pid = None def pipe_new(self): pipe = os.pipe() for fd in pipe: # non_blocking flags = fcntl.fcntl(fd, fcntl.F_GETFL) | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, flags) # close_on_exec flags = fcntl.fcntl(fd, fcntl.F_GETFD) | fcntl.FD_CLOEXEC fcntl.fcntl(fd, fcntl.F_SETFD, flags) return pipe def pipe_ping(self, pipe): try: os.write(pipe[1], '.') except IOError, e: if e.errno not in [errno.EAGAIN, errno.EINTR]: raise def signal_handler(self, sig, frame): if len(self.queue) < 5 or sig == signal.SIGCHLD: self.queue.append(sig) self.pipe_ping(self.pipe) else: _logger.warn("Dropping signal: %s", sig) def worker_spawn(self, klass, workers_registry): self.generation += 1 worker = klass(self) pid = os.fork() if pid != 0: worker.pid = pid self.workers[pid] = worker workers_registry[pid] = worker return worker else: worker.run() sys.exit(0) def long_polling_spawn(self): nargs = stripped_sys_argv('--pidfile','--workers') cmd = nargs[0] cmd = os.path.join(os.path.dirname(cmd), "openerp-gevent") nargs[0] = cmd popen = subprocess.Popen(nargs) self.long_polling_pid = popen.pid def worker_pop(self, pid): if pid in self.workers: _logger.debug("Worker (%s) unregistered",pid) try: self.workers_http.pop(pid,None) self.workers_cron.pop(pid,None) u = self.workers.pop(pid) u.close() except OSError: return def worker_kill(self, pid, sig): try: os.kill(pid, sig) except OSError, e: if e.errno == errno.ESRCH: self.worker_pop(pid) def process_signals(self): while len(self.queue): sig = self.queue.pop(0) if sig in [signal.SIGINT,signal.SIGTERM]: raise KeyboardInterrupt elif sig == signal.SIGHUP: # restart on kill -HUP openerp.phoenix = True raise KeyboardInterrupt elif sig == signal.SIGQUIT: # dump stacks on kill -3 self.dumpstacks() elif sig == signal.SIGTTIN: # increase number of workers self.population += 1 elif sig == signal.SIGTTOU: # decrease number of workers self.population -= 1 def process_zombie(self): # reap dead workers while 1: try: wpid, status = os.waitpid(-1, os.WNOHANG) if not wpid: break if (status >> 8) == 3: msg = "Critial worker error (%s)" _logger.critical(msg, wpid) raise Exception(msg % wpid) self.worker_pop(wpid) except OSError, e: if e.errno == errno.ECHILD: break raise def process_timeout(self): now = time.time() for (pid, worker) in self.workers.items(): if (worker.watchdog_timeout is not None) and \ (now - worker.watchdog_time >= worker.watchdog_timeout): _logger.error("Worker (%s) timeout", pid) self.worker_kill(pid, signal.SIGKILL) def process_spawn(self): while len(self.workers_http) < self.population: self.worker_spawn(WorkerHTTP, self.workers_http) while len(self.workers_cron) < config['max_cron_threads']: self.worker_spawn(WorkerCron, self.workers_cron) if not self.long_polling_pid: self.long_polling_spawn() def sleep(self): try: # map of fd -> worker fds = dict([(w.watchdog_pipe[0],w) for k,w in self.workers.items()]) fd_in = fds.keys() + [self.pipe[0]] # check for ping or internal wakeups ready = select.select(fd_in, [], [], self.beat) # update worker watchdogs for fd in ready[0]: if fd in fds: fds[fd].watchdog_time = time.time() try: # empty pipe while os.read(fd, 1): pass except OSError, e: if e.errno not in [errno.EAGAIN]: raise except select.error, e: if e[0] not in [errno.EINTR]: raise def start(self): # Empty the cursor pool, we dont want them to be shared among forked workers. openerp.sql_db.close_all() # wakeup pipe, python doesnt throw EINTR when a syscall is interrupted # by a signal simulating a pseudo SA_RESTART. We write to a pipe in the # signal handler to overcome this behaviour self.pipe = self.pipe_new() # set signal handlers signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) signal.signal(signal.SIGHUP, self.signal_handler) signal.signal(signal.SIGCHLD, self.signal_handler) signal.signal(signal.SIGTTIN, self.signal_handler) signal.signal(signal.SIGTTOU, self.signal_handler) signal.signal(signal.SIGQUIT, dumpstacks) # listen to socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.setblocking(0) self.socket.bind(self.address) self.socket.listen(8*self.population) def stop(self, graceful=True): if self.long_polling_pid is not None: self.worker_kill(self.long_polling_pid, signal.SIGKILL) # FIXME make longpolling process handle SIGTERM correctly self.long_polling_pid = None if graceful: _logger.info("Stopping gracefully") limit = time.time() + self.timeout for pid in self.workers.keys(): self.worker_kill(pid, signal.SIGTERM) while self.workers and time.time() < limit: self.process_zombie() time.sleep(0.1) else: _logger.info("Stopping forcefully") for pid in self.workers.keys(): self.worker_kill(pid, signal.SIGTERM) self.socket.close() def run(self): self.start() _logger.debug("Multiprocess starting") while 1: try: #_logger.debug("Multiprocess beat (%s)",time.time()) self.process_signals() self.process_zombie() self.process_timeout() self.process_spawn() self.sleep() except KeyboardInterrupt: _logger.debug("Multiprocess clean stop") self.stop() break except Exception,e: _logger.exception(e) self.stop(False) sys.exit(-1) class Worker(object): """ Workers """ def __init__(self, multi): self.multi = multi self.watchdog_time = time.time() self.watchdog_pipe = multi.pipe_new() # Can be set to None if no watchdog is desired. self.watchdog_timeout = multi.timeout self.ppid = os.getpid() self.pid = None self.alive = True # should we rename into lifetime ? self.request_max = multi.limit_request self.request_count = 0 def setproctitle(self, title=""): setproctitle('openerp: %s %s %s' % (self.__class__.__name__, self.pid, title)) def close(self): os.close(self.watchdog_pipe[0]) os.close(self.watchdog_pipe[1]) def signal_handler(self, sig, frame): self.alive = False def sleep(self): try: ret = select.select([self.multi.socket], [], [], self.multi.beat) except select.error, e: if e[0] not in [errno.EINTR]: raise def process_limit(self): # If our parent changed sucide if self.ppid != os.getppid(): _logger.info("Worker (%s) Parent changed", self.pid) self.alive = False # check for lifetime if self.request_count >= self.request_max: _logger.info("Worker (%d) max request (%s) reached.", self.pid, self.request_count) self.alive = False # Reset the worker if it consumes too much memory (e.g. caused by a memory leak). rss, vms = memory_info(psutil.Process(os.getpid())) if vms > config['limit_memory_soft']: _logger.info('Worker (%d) virtual memory limit (%s) reached.', self.pid, vms) self.alive = False # Commit suicide after the request. # VMS and RLIMIT_AS are the same thing: virtual memory, a.k.a. address space soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (config['limit_memory_hard'], hard)) # SIGXCPU (exceeded CPU time) signal handler will raise an exception. r = resource.getrusage(resource.RUSAGE_SELF) cpu_time = r.ru_utime + r.ru_stime def time_expired(n, stack): _logger.info('Worker (%d) CPU time limit (%s) reached.', config['limit_time_cpu']) # We dont suicide in such case raise Exception('CPU time limit exceeded.') signal.signal(signal.SIGXCPU, time_expired) soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (cpu_time + config['limit_time_cpu'], hard)) def process_work(self): pass def start(self): self.pid = os.getpid() self.setproctitle() _logger.info("Worker %s (%s) alive", self.__class__.__name__, self.pid) # Reseed the random number generator random.seed() # Prevent fd inherientence close_on_exec flags = fcntl.fcntl(self.multi.socket, fcntl.F_GETFD) | fcntl.FD_CLOEXEC fcntl.fcntl(self.multi.socket, fcntl.F_SETFD, flags) # reset blocking status self.multi.socket.setblocking(0) signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, signal.SIG_DFL) signal.signal(signal.SIGCHLD, signal.SIG_DFL) def stop(self): pass def run(self): try: self.start() while self.alive: self.process_limit() self.multi.pipe_ping(self.watchdog_pipe) self.sleep() self.process_work() _logger.info("Worker (%s) exiting. request_count: %s.", self.pid, self.request_count) self.stop() except Exception,e: _logger.exception("Worker (%s) Exception occured, exiting..." % self.pid) # should we use 3 to abort everything ? sys.exit(1) class WorkerHTTP(Worker): """ HTTP Request workers """ def process_request(self, client, addr): client.setblocking(1) client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Prevent fd inherientence close_on_exec flags = fcntl.fcntl(client, fcntl.F_GETFD) | fcntl.FD_CLOEXEC fcntl.fcntl(client, fcntl.F_SETFD, flags) # do request using BaseWSGIServerNoBind monkey patched with socket self.server.socket = client # tolerate broken pipe when the http client closes the socket before # receiving the full reply try: self.server.process_request(client,addr) except IOError, e: if e.errno != errno.EPIPE: raise self.request_count += 1 def process_work(self): try: client, addr = self.multi.socket.accept() self.process_request(client, addr) except socket.error, e: if e[0] not in (errno.EAGAIN, errno.ECONNABORTED): raise def start(self): Worker.start(self) self.server = BaseWSGIServerNoBind(self.multi.app) class WorkerCron(Worker): """ Cron workers """ def __init__(self, multi): super(WorkerCron, self).__init__(multi) # process_work() below process a single database per call. # The variable db_index is keeping track of the next database to # process. self.db_index = 0 def sleep(self): # Really sleep once all the databases have been processed. if self.db_index == 0: interval = SLEEP_INTERVAL + self.pid % 10 # chorus effect time.sleep(interval) def _db_list(self): if config['db_name']: db_names = config['db_name'].split(',') else: db_names = openerp.service.db.exp_list(True) return db_names def process_work(self): rpc_request = logging.getLogger('openerp.netsvc.rpc.request') rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG) _logger.debug("WorkerCron (%s) polling for jobs", self.pid) db_names = self._db_list() if len(db_names): self.db_index = (self.db_index + 1) % len(db_names) db_name = db_names[self.db_index] self.setproctitle(db_name) if rpc_request_flag: start_time = time.time() start_rss, start_vms = memory_info(psutil.Process(os.getpid())) import openerp.addons.base as base base.ir.ir_cron.ir_cron._acquire_job(db_name) openerp.modules.registry.RegistryManager.delete(db_name) # dont keep cursors in multi database mode if len(db_names) > 1: openerp.sql_db.close_db(db_name) if rpc_request_flag: end_time = time.time() end_rss, end_vms = memory_info(psutil.Process(os.getpid())) logline = '%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (db_name, end_time - start_time, start_vms / 1024, end_vms / 1024, (end_vms - start_vms)/1024) _logger.debug("WorkerCron (%s) %s", self.pid, logline) self.request_count += 1 if self.request_count >= self.request_max and self.request_max < len(db_names): _logger.error("There are more dabatases to process than allowed " "by the `limit_request` configuration variable: %s more.", len(db_names) - self.request_max) else: self.db_index = 0 def start(self): os.nice(10) # mommy always told me to be nice with others... Worker.start(self) self.multi.socket.close() #---------------------------------------------------------- # start/stop public api #---------------------------------------------------------- server = None def load_server_wide_modules(): for m in openerp.conf.server_wide_modules: try: openerp.modules.module.load_openerp_module(m) except Exception: msg = '' if m == 'web': msg = """ The `web` module is provided by the addons found in the `openerp-web` project. Maybe you forgot to add those addons in your addons_path configuration.""" _logger.exception('Failed to load server-wide module `%s`.%s', m, msg) def _reexec(updated_modules=None): """reexecute openerp-server process with (nearly) the same arguments""" if openerp.tools.osutil.is_running_as_nt_service(): subprocess.call('net stop {0} && net start {0}'.format(nt_service_name), shell=True) exe = os.path.basename(sys.executable) args = stripped_sys_argv() args += ["-u", ','.join(updated_modules)] if not args or args[0] != exe: args.insert(0, exe) os.execv(sys.executable, args) def start(): """ Start the openerp http server and cron processor. """ global server load_server_wide_modules() if config['workers']: server = PreforkServer(openerp.service.wsgi_server.application) elif openerp.evented: server = GeventServer(openerp.service.wsgi_server.application) else: server = ThreadedServer(openerp.service.wsgi_server.application) if config['auto_reload']: autoreload = AutoReload(server) autoreload.run() server.run() # like the legend of the phoenix, all ends with beginnings if getattr(openerp, 'phoenix', False): modules = [] if config['auto_reload']: modules = autoreload.modules.keys() _reexec(modules) sys.exit(0) def restart(): """ Restart the server """ if os.name == 'nt': # run in a thread to let the current thread return response to the caller. threading.Thread(target=_reexec).start() else: os.kill(server.pid, signal.SIGHUP) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:<|fim▁end|>
def __init__(self, autoreload): self.autoreload = autoreload