prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>service-registry.spec.ts<|end_file_name|><|fim▁begin|>import { ExpressServiceRegistry } from './service-registry'; import { JsRestfulRegistryConfig } from './registry'; import * as express from 'express'; import {expect} from 'chai'; import { Factory } from './test-util.spec'; class TestServiceC { } describe('service-registry', () => { var app; beforeEach(()=>{ app = express(); }); <|fim▁hole|> it('should be possible to register an object', () => { var fn = () => { ExpressServiceRegistry.registerService(app, new TestServiceC()); } expect(fn).to.not.throw(Error); }) it('should be possible to register a SecurityContextFactory', () => { var fn = () => { ExpressServiceRegistry.registerSecurityContextFactory(app, new Factory()); } expect(fn).to.not.throw(Error); }) it('should be possible to initialize the registry with a config object', () => { const config: JsRestfulRegistryConfig = {logger: null}; ExpressServiceRegistry.initJsRestfulRegistry(app, config); expect(app.locals.jsResutfulRegistry.config).to.equal(config); }); });<|fim▁end|>
<|file_name|>SortDirection.java<|end_file_name|><|fim▁begin|>package com.docuware.dev.schema._public.services.platform; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; @XmlType(name = "SortDirection") @XmlEnum public enum SortDirection { <|fim▁hole|> @XmlEnumValue("Asc") ASC("Asc"), @XmlEnumValue("Desc") DESC("Desc"); private final String value; SortDirection(String v) { value = v; } public String value() { return value; } public static SortDirection fromValue(String v) { for (SortDirection c: SortDirection.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }<|fim▁end|>
@XmlEnumValue("Default") DEFAULT("Default"),
<|file_name|>requests.js<|end_file_name|><|fim▁begin|>var request = require('request'); var url = require('url'); var authenticate = require('./oauthentication'); var Request = function(obj){ this.obj = obj; }; Request.prototype.mailboxes = function(method, specific_url, params, callback){ /* * @params: * @ param : if user wants to call specific mailbox e.g. : / * @ callback: function to pass the following parameters to: * @error * @response * @body */ makeRequest(this, method, 'https://api.slice.com/api/v1/mailboxes', specific_url, params, callback); }; Request.prototype.users = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/users', specific_url, params, callback); }; Request.prototype.orders = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/orders', specific_url, params, callback); }; Request.prototype.items = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/items', specific_url, params, callback);<|fim▁hole|>}; Request.prototype.recalls = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/recalls', specific_url, params, callback); }; Request.prototype.emails = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/emails', specific_url, params, callback); }; Request.prototype.merchants = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/merchants', specific_url, params, callback); }; Request.prototype.actions = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/actions/update', specific_url, params, callback); }; Request.prototype.setAccessToken = function(access_token){ this.access_token = access_token; } var makeRequest = function(obj, method, url, specific_url, params, callback){ this.params = params || ''; this.param_url = compileRequest(this.params); this.method = method || 'GET'; // defaults to 'GET' this.specific_url = specific_url || ''; request({ uri : url+this.specific_url+this.params, headers : { 'Authorization' : 'Bearer ' + obj.access_token }, method : this.method, timeout : 1000, followRedirect : true, maxRedirects : 4, }, function(error, response, body){ if(error){ throw error; } callback(error, response, body); }); }; var compileRequest = function(params){ var param_url = '?'; for(var key in params){ param_url += key + '=' + params[key] + '&'; } return param_url.substring(0, param_url.length-1); }; module.exports = Request; module.exports.users = Request.users; module.exports.mailboxes = Request.mailboxes; module.exports.orders = Request.orders; module.exports.items = Request.items; module.exports.shipments = Request.shipments; module.exports.recalls = Request.recalls; module.exports.emails = Request.emails; module.exports.merchants = Request.merchants; module.exports.actions = Request.actions;<|fim▁end|>
}; Request.prototype.shipments = function(method, specific_url, params, callback){ makeRequest(this, method, 'https://api.slice.com/api/v1/shipments', specific_url, params, callback);
<|file_name|>mod.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. <|fim▁hole|> typeck.rs, an introduction The type checker is responsible for: 1. Determining the type of each expression 2. Resolving methods and traits 3. Guaranteeing that most type rules are met ("most?", you say, "why most?" Well, dear reader, read on) The main entry point is `check_crate()`. Type checking operates in two major phases: collect and check. The collect phase passes over all items and determines their type, without examining their "innards". The check phase then checks function bodies and so forth. Within the check phase, we check each function body one at a time (bodies of function expressions are checked as part of the containing function). Inference is used to supply types wherever they are unknown. The actual checking of a function itself has several phases (check, regionck, writeback), as discussed in the documentation for the `check` module. The type checker is defined into various submodules which are documented independently: - astconv: converts the AST representation of types into the `ty` representation - collect: computes the types of each top-level item and enters them into the `cx.tcache` table for later use - check: walks over function bodies and type checks them, inferring types for local variables, type parameters, etc as necessary. - infer: finds the types to use for each type variable such that all subtyping and assignment constraints are met. In essence, the check module specifies the constraints, and the infer module solves them. */ use driver::session; use middle::resolve; use middle::ty; use util::common::time; use util::ppaux::Repr; use util::ppaux; use std::hashmap::HashMap; use std::result; use extra::list::List; use extra::list; use syntax::codemap::span; use syntax::print::pprust::*; use syntax::{ast, ast_map, abi}; use syntax::opt_vec; #[path = "check/mod.rs"] pub mod check; pub mod rscope; pub mod astconv; #[path = "infer/mod.rs"] pub mod infer; pub mod collect; pub mod coherence; #[deriving(Encodable, Decodable)] pub enum method_origin { // supertrait method invoked on "self" inside a default method // first field is supertrait ID; // second field is method index (relative to the *supertrait* // method list) method_super(ast::def_id, uint), // fully statically resolved method method_static(ast::def_id), // method invoked on a type parameter with a bounded trait method_param(method_param), // method invoked on a trait instance method_trait(ast::def_id, uint, ty::TraitStore), // method invoked on "self" inside a default method method_self(ast::def_id, uint) } // details for a method invoked with a receiver whose type is a type parameter // with a bounded trait. #[deriving(Encodable, Decodable)] pub struct method_param { // the trait containing the method to be invoked trait_id: ast::def_id, // index of the method to be invoked amongst the trait's methods method_num: uint, // index of the type parameter (from those that are in scope) that is // the type of the receiver param_num: uint, // index of the bound for this type parameter which specifies the trait bound_num: uint, } pub struct method_map_entry { // the type of the self parameter, which is not reflected in the fn type // (FIXME #3446) self_ty: ty::t, // the mode of `self` self_mode: ty::SelfMode, // the type of explicit self on the method explicit_self: ast::explicit_self_, // method details being invoked origin: method_origin, } // maps from an expression id that corresponds to a method call to the details // of the method to be invoked pub type method_map = @mut HashMap<ast::node_id, method_map_entry>; pub type vtable_param_res = @~[vtable_origin]; // Resolutions for bounds of all parameters, left to right, for a given path. pub type vtable_res = @~[vtable_param_res]; pub enum vtable_origin { /* Statically known vtable. def_id gives the class or impl item from whence comes the vtable, and tys are the type substs. vtable_res is the vtable itself */ vtable_static(ast::def_id, ~[ty::t], vtable_res), /* Dynamic vtable, comes from a parameter that has a bound on it: fn foo<T:quux,baz,bar>(a: T) -- a's vtable would have a vtable_param origin The first uint is the param number (identifying T in the example), and the second is the bound number (identifying baz) */ vtable_param(uint, uint), /* Dynamic vtable, comes from self. */ vtable_self(ast::def_id) } impl Repr for vtable_origin { fn repr(&self, tcx: ty::ctxt) -> ~str { match *self { vtable_static(def_id, ref tys, ref vtable_res) => { fmt!("vtable_static(%?:%s, %s, %s)", def_id, ty::item_path_str(tcx, def_id), tys.repr(tcx), vtable_res.repr(tcx)) } vtable_param(x, y) => { fmt!("vtable_param(%?, %?)", x, y) } vtable_self(def_id) => { fmt!("vtable_self(%?)", def_id) } } } } pub type vtable_map = @mut HashMap<ast::node_id, vtable_res>; pub struct CrateCtxt { // A mapping from method call sites to traits that have that method. trait_map: resolve::TraitMap, method_map: method_map, vtable_map: vtable_map, coherence_info: coherence::CoherenceInfo, tcx: ty::ctxt } // Functions that write types into the node type table pub fn write_ty_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, ty: ty::t) { debug!("write_ty_to_tcx(%d, %s)", node_id, ppaux::ty_to_str(tcx, ty)); assert!(!ty::type_needs_infer(ty)); tcx.node_types.insert(node_id as uint, ty); } pub fn write_substs_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, substs: ~[ty::t]) { if substs.len() > 0u { debug!("write_substs_to_tcx(%d, %?)", node_id, substs.map(|t| ppaux::ty_to_str(tcx, *t))); assert!(substs.iter().all(|t| !ty::type_needs_infer(*t))); tcx.node_type_substs.insert(node_id, substs); } } pub fn write_tpt_to_tcx(tcx: ty::ctxt, node_id: ast::node_id, tpt: &ty::ty_param_substs_and_ty) { write_ty_to_tcx(tcx, node_id, tpt.ty); if !tpt.substs.tps.is_empty() { write_substs_to_tcx(tcx, node_id, copy tpt.substs.tps); } } pub fn lookup_def_tcx(tcx: ty::ctxt, sp: span, id: ast::node_id) -> ast::def { match tcx.def_map.find(&id) { Some(&x) => x, _ => { tcx.sess.span_fatal(sp, "internal error looking up a definition") } } } pub fn lookup_def_ccx(ccx: &CrateCtxt, sp: span, id: ast::node_id) -> ast::def { lookup_def_tcx(ccx.tcx, sp, id) } pub fn no_params(t: ty::t) -> ty::ty_param_bounds_and_ty { ty::ty_param_bounds_and_ty { generics: ty::Generics {type_param_defs: @~[], region_param: None}, ty: t } } pub fn require_same_types( tcx: ty::ctxt, maybe_infcx: Option<@mut infer::InferCtxt>, t1_is_expected: bool, span: span, t1: ty::t, t2: ty::t, msg: &fn() -> ~str) -> bool { let l_tcx; let l_infcx; match maybe_infcx { None => { l_tcx = tcx; l_infcx = infer::new_infer_ctxt(tcx); } Some(i) => { l_tcx = i.tcx; l_infcx = i; } } match infer::mk_eqty(l_infcx, t1_is_expected, infer::Misc(span), t1, t2) { result::Ok(()) => true, result::Err(ref terr) => { l_tcx.sess.span_err(span, msg() + ": " + ty::type_err_to_str(l_tcx, terr)); ty::note_and_explain_type_err(l_tcx, terr); false } } } // a list of mapping from in-scope-region-names ("isr") to the // corresponding ty::Region pub type isr_alist = @List<(ty::bound_region, ty::Region)>; trait get_and_find_region { fn get(&self, br: ty::bound_region) -> ty::Region; fn find(&self, br: ty::bound_region) -> Option<ty::Region>; } impl get_and_find_region for isr_alist { pub fn get(&self, br: ty::bound_region) -> ty::Region { self.find(br).get() } pub fn find(&self, br: ty::bound_region) -> Option<ty::Region> { for list::each(*self) |isr| { let (isr_br, isr_r) = *isr; if isr_br == br { return Some(isr_r); } } return None; } } fn check_main_fn_ty(ccx: &CrateCtxt, main_id: ast::node_id, main_span: span) { let tcx = ccx.tcx; let main_t = ty::node_id_to_type(tcx, main_id); match ty::get(main_t).sty { ty::ty_bare_fn(ref fn_ty) => { match tcx.items.find(&main_id) { Some(&ast_map::node_item(it,_)) => { match it.node { ast::item_fn(_, _, _, ref ps, _) if ps.is_parameterized() => { tcx.sess.span_err( main_span, "main function is not allowed to have type parameters"); return; } _ => () } } _ => () } let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy { purity: ast::impure_fn, abis: abi::AbiSet::Rust(), sig: ty::FnSig { bound_lifetime_names: opt_vec::Empty, inputs: ~[], output: ty::mk_nil() } }); require_same_types(tcx, None, false, main_span, main_t, se_ty, || fmt!("main function expects type: `%s`", ppaux::ty_to_str(ccx.tcx, se_ty))); } _ => { tcx.sess.span_bug(main_span, fmt!("main has a non-function type: found `%s`", ppaux::ty_to_str(tcx, main_t))); } } } fn check_start_fn_ty(ccx: &CrateCtxt, start_id: ast::node_id, start_span: span) { let tcx = ccx.tcx; let start_t = ty::node_id_to_type(tcx, start_id); match ty::get(start_t).sty { ty::ty_bare_fn(_) => { match tcx.items.find(&start_id) { Some(&ast_map::node_item(it,_)) => { match it.node { ast::item_fn(_,_,_,ref ps,_) if ps.is_parameterized() => { tcx.sess.span_err( start_span, "start function is not allowed to have type parameters"); return; } _ => () } } _ => () } let se_ty = ty::mk_bare_fn(tcx, ty::BareFnTy { purity: ast::impure_fn, abis: abi::AbiSet::Rust(), sig: ty::FnSig { bound_lifetime_names: opt_vec::Empty, inputs: ~[ ty::mk_int(), ty::mk_imm_ptr(tcx, ty::mk_imm_ptr(tcx, ty::mk_u8())), ty::mk_imm_ptr(tcx, ty::mk_u8()) ], output: ty::mk_int() } }); require_same_types(tcx, None, false, start_span, start_t, se_ty, || fmt!("start function expects type: `%s`", ppaux::ty_to_str(ccx.tcx, se_ty))); } _ => { tcx.sess.span_bug(start_span, fmt!("start has a non-function type: found `%s`", ppaux::ty_to_str(tcx, start_t))); } } } fn check_for_entry_fn(ccx: &CrateCtxt) { let tcx = ccx.tcx; if !*tcx.sess.building_library { match *tcx.sess.entry_fn { Some((id, sp)) => match *tcx.sess.entry_type { Some(session::EntryMain) => check_main_fn_ty(ccx, id, sp), Some(session::EntryStart) => check_start_fn_ty(ccx, id, sp), None => tcx.sess.bug("entry function without a type") }, None => tcx.sess.bug("type checking without entry function") } } } pub fn check_crate(tcx: ty::ctxt, trait_map: resolve::TraitMap, crate: &ast::crate) -> (method_map, vtable_map) { let time_passes = tcx.sess.time_passes(); let ccx = @mut CrateCtxt { trait_map: trait_map, method_map: @mut HashMap::new(), vtable_map: @mut HashMap::new(), coherence_info: coherence::CoherenceInfo(), tcx: tcx }; time(time_passes, ~"type collecting", || collect::collect_item_types(ccx, crate)); // this ensures that later parts of type checking can assume that items // have valid types and not error tcx.sess.abort_if_errors(); time(time_passes, ~"coherence checking", || coherence::check_coherence(ccx, crate)); time(time_passes, ~"type checking", || check::check_item_types(ccx, crate)); check_for_entry_fn(ccx); tcx.sess.abort_if_errors(); (ccx.method_map, ccx.vtable_map) }<|fim▁end|>
/*
<|file_name|>.eslintrc.js<|end_file_name|><|fim▁begin|>module.exports = { parserOptions: {<|fim▁hole|> }, };<|fim▁end|>
sourceType: 'script',
<|file_name|>defines_15.js<|end_file_name|><|fim▁begin|>var searchData= [ ['undefined_5fband',['UNDEFINED_BAND',['../a01181.html#a9efc501b4bfd07c8e00e55bbb5f28690',1,'blkocc.h']]], ['uni_5fmax_5flegal_5futf32',['UNI_MAX_LEGAL_UTF32',['../a00614.html#a98a2f50a1ca513613316ffd384dd1bfb',1,'unichar.cpp']]], ['unichar_5flen',['UNICHAR_LEN',['../a00617.html#a902bc40c9d89802bc063afe30ce9e708',1,'unichar.h']]], ['unlikely_5fnum_5ffeat',['UNLIKELY_NUM_FEAT',['../a00659.html#a17b4f36c5132ab55beb280e0cc233228',1,'adaptmatch.cpp']]], ['unlv_5fext',['UNLV_EXT',['../a00221.html#aa14fc11aa7528cfededa3d19c18901f1',1,'blread.cpp']]], ['unusedclassidin',['UnusedClassIdIn',['../a00749.html#a3e7ae3ffbac606326937a4c701aeeaf2',1,'intproto.h']]], ['unz_5fbadzipfile',['UNZ_BADZIPFILE',['../a01565.html#a3fcc1d41cbea304ce10286ce99577625',1,'unzip.h']]],<|fim▁hole|> ['unz_5fend_5fof_5flist_5fof_5ffile',['UNZ_END_OF_LIST_OF_FILE',['../a01565.html#ac55ed190d07021ce9bc1bf34b91dcae9',1,'unzip.h']]], ['unz_5feof',['UNZ_EOF',['../a01565.html#a0438887aea4e1c58e1b3955838a907f3',1,'unzip.h']]], ['unz_5ferrno',['UNZ_ERRNO',['../a01565.html#aae99fb3e34ea9f78ca8ba4a716f86e68',1,'unzip.h']]], ['unz_5finternalerror',['UNZ_INTERNALERROR',['../a01565.html#a813da146afcb179d57e948bf6871799b',1,'unzip.h']]], ['unz_5fmaxfilenameinzip',['UNZ_MAXFILENAMEINZIP',['../a01562.html#a97ef86322b25dcc3d0fc5eb50d386b54',1,'unzip.c']]], ['unz_5fok',['UNZ_OK',['../a01565.html#ada043545f95ccd4dae93fa44d95e39a8',1,'unzip.h']]], ['unz_5fparamerror',['UNZ_PARAMERROR',['../a01565.html#aca983831f4d25e504d544eb07f48e39b',1,'unzip.h']]], ['update_5fedge_5fwindow',['update_edge_window',['../a01703.html#a3a90c5459659abe9227ab93d20042630',1,'plotedges.h']]] ];<|fim▁end|>
['unz_5fbufsize',['UNZ_BUFSIZE',['../a01562.html#ac88907609a3408a8ee6544287b6c9880',1,'unzip.c']]], ['unz_5fcrcerror',['UNZ_CRCERROR',['../a01565.html#ae9155f504a5db40587b390f9e487c303',1,'unzip.h']]],
<|file_name|>chat_commands.py<|end_file_name|><|fim▁begin|>__all__ = ['chatcommand', 'execute_chat_command', 'save_matchsettings', '_register_chat_command'] import functools import inspect from .events import eventhandler, send_event from .log import logger from .asyncio_loop import loop _registered_chat_commands = {} # dict of all registered chat commands async def execute_chat_command(server, player, cmd): #if not player.is_admin(): #r = check_rights(player) args = cmd.split(' ') if args[len(args) - 1] is '': del args[len(args) - 1] if args[0] in _registered_chat_commands: try: if len(args) == 1: server.run_task(_registered_chat_commands[args[0]](server, player)) else: server.run_task(_registered_chat_commands[args[0]](server, player, *args[1:])) except Exception as exp: server.chat_send_error('fault use of chat command: ' + args[0], player) server.chat_send_error(str(exp), player) server.chat_send('use /help to see available chat commands', player) raise else: server.chat_send_error('unknown chat command: ' + args[0], player) server.chat_send('use /help to see available chat commands', player) def _register_chat_command(chat_command, function): if chat_command not in _registered_chat_commands: _registered_chat_commands[chat_command] = function else: logger.error('chatcommand ' + "'" + chat_command + "'" + ' already registered to ' + str(function)) return False def _unregister_chat_command(chat_command): if chat_command not in _registered_chat_commands: raise 'chat command not registered' else: del _registered_chat_commands[chat_command] # @chatcommand decorator def chatcommand(cmd): def chatcommand_decorator(func): if _register_chat_command(cmd, func) is False: return module = inspect.getmodule(func) logger.debug('chatcommand ' + "'" + cmd + "' connected to " + str(func) + ' in module ' + str(module)) @functools.wraps(func)<|fim▁hole|> return chatcommand_decorator @eventhandler('ManiaPlanet.PlayerChat') async def _on_player_chat(server, callback): p = server.player_from_login(callback.login) # ignore normal chat if not callback.isCommand: if p is not None: send_event(server, 'pie.PlayerChat', p) return server.run_task(execute_chat_command(server, p, callback.text)) @chatcommand('/help') async def cmd_help(server, player): """list all chat commands""" server.chat_send('help:', player) for cmd in _registered_chat_commands: if _registered_chat_commands[cmd].__doc__ is None: docstr = 'no description set' else: docstr = _registered_chat_commands[cmd].__doc__ server.chat_send(cmd + ' - ' + docstr, player) async def save_matchsettings(server, filename = None): await server.rpc.SaveMatchSettings('MatchSettings\\' + server.config.matchsettings) @chatcommand('/savematchsettings') async def cmd_savematchsettings(server, player): await save_matchsettings(server) server.chat_send('matchsettings saved: ' + server.config.matchsettings) @chatcommand('/shutdown') async def cmd_shutdown(server, player): await server.chat_send_wait('pie shutdown') loop.stop() @chatcommand('/players') async def cmd_players(server, player): for player in server.players: server.chat_send(server.players[player].nickname)<|fim▁end|>
def func_wrapper(*args, **kwargs): return func(*args, **kwargs) return func_wrapper
<|file_name|>PointDistance.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ *************************************************************************** PointDistance.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * 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. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import math from qgis.core import * from processing.core.GeoAlgorithm import GeoAlgorithm from processing.core.parameters import ParameterNumber from processing.core.parameters import ParameterVector from processing.core.parameters import ParameterSelection from processing.core.parameters import ParameterTableField from processing.core.outputs import OutputTable from processing.tools import dataobjects, vector class PointDistance(GeoAlgorithm): INPUT_LAYER = 'INPUT_LAYER' INPUT_FIELD = 'INPUT_FIELD' TARGET_LAYER = 'TARGET_LAYER' TARGET_FIELD = 'TARGET_FIELD' MATRIX_TYPE = 'MATRIX_TYPE' NEAREST_POINTS = 'NEAREST_POINTS' DISTANCE_MATRIX = 'DISTANCE_MATRIX' MAT_TYPES = ['Linear (N*k x 3) distance matrix', 'Standard (N x T) distance matrix', 'Summary distance matrix (mean, std. dev., min, max)'] def defineCharacteristics(self): self.name = 'Distance matrix' self.group = 'Vector analysis tools' self.addParameter(ParameterVector(self.INPUT_LAYER, 'Input point layer' , [ParameterVector.VECTOR_TYPE_POINT])) self.addParameter(ParameterTableField(self.INPUT_FIELD, 'Input unique ID field', self.INPUT_LAYER, ParameterTableField.DATA_TYPE_ANY)) self.addParameter(ParameterVector(self.TARGET_LAYER, 'Target point layer', ParameterVector.VECTOR_TYPE_POINT)) self.addParameter(ParameterTableField(self.TARGET_FIELD, 'Target unique ID field', self.TARGET_LAYER, ParameterTableField.DATA_TYPE_ANY)) self.addParameter(ParameterSelection(self.MATRIX_TYPE, 'Output matrix type', self.MAT_TYPES, 0)) self.addParameter(ParameterNumber(self.NEAREST_POINTS, 'Use only the nearest (k) target points', 0, 9999, 0)) self.addOutput(OutputTable(self.DISTANCE_MATRIX, 'Distance matrix')) def processAlgorithm(self, progress): inLayer = dataobjects.getObjectFromUri( self.getParameterValue(self.INPUT_LAYER)) inField = self.getParameterValue(self.INPUT_FIELD) targetLayer = dataobjects.getObjectFromUri( self.getParameterValue(self.TARGET_LAYER)) targetField = self.getParameterValue(self.TARGET_FIELD) matType = self.getParameterValue(self.MATRIX_TYPE) nPoints = self.getParameterValue(self.NEAREST_POINTS) outputFile = self.getOutputFromName(self.DISTANCE_MATRIX) if nPoints < 1: nPoints = len(vector.features(targetLayer)) self.writer = outputFile.getTableWriter([]) if matType == 0: # Linear distance matrix self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress) elif matType == 1: # Standard distance matrix self.regularMatrix(inLayer, inField, targetLayer, targetField, nPoints, progress) elif matType == 2: # Summary distance matrix self.linearMatrix(inLayer, inField, targetLayer, targetField, matType, nPoints, progress) def linearMatrix(self, inLayer, inField, targetLayer, targetField, matType, nPoints, progress): if matType == 0: self.writer.addRecord(['InputID', 'TargetID', 'Distance']) else: self.writer.addRecord(['InputID', 'MEAN', 'STDDEV', 'MIN', 'MAX']) index = vector.spatialindex(targetLayer) inIdx = inLayer.fieldNameIndex(inField) outIdx = targetLayer.fieldNameIndex(targetField) outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() features = vector.features(inLayer)<|fim▁hole|> for inFeat in features: inGeom = inFeat.geometry() inID = unicode(inFeat.attributes()[inIdx]) featList = index.nearestNeighbor(inGeom.asPoint(), nPoints) distList = [] vari = 0.0 for i in featList: request = QgsFeatureRequest().setFilterFid(i) outFeat = targetLayer.getFeatures(request).next() outID = outFeat.attributes()[outIdx] outGeom = outFeat.geometry() dist = distArea.measureLine(inGeom.asPoint(), outGeom.asPoint()) if matType == 0: self.writer.addRecord([inID,unicode(outID),unicode(dist)]) else: distList.append(float(dist)) if matType != 0: mean = sum(distList) / len(distList) for i in distList: vari += (i - mean) * (i - mean) vari = math.sqrt(vari / len(distList)) self.writer.addRecord([inID, unicode(mean), unicode(vari), unicode(min(distList)), unicode(max(distList))]) current += 1 progress.setPercentage(int(current * total)) def regularMatrix(self, inLayer, inField, targetLayer, targetField, nPoints, progress): index = vector.spatialindex(targetLayer) inIdx = inLayer.fieldNameIndex(inField) outIdx = targetLayer.fieldNameIndex(inField) outFeat = QgsFeature() inGeom = QgsGeometry() outGeom = QgsGeometry() distArea = QgsDistanceArea() first = True current = 0 features = vector.features(inLayer) total = 100.0 / float(len(features)) for inFeat in features: inGeom = inFeat.geometry() inID = unicode(inFeat.attributes()[inIdx]) featList = index.nearestNeighbor(inGeom.asPoint(), nPoints) if first: first = False data = ['ID'] for i in range(len(featList)): data.append('DIST_{0}'.format(i+1)) self.writer.addRecord(data) data = [inID] for i in featList: request = QgsFeatureRequest().setFilterFid(i) outFeat = targetLayer.getFeatures(request).next() outGeom = outFeat.geometry() dist = distArea.measureLine(inGeom.asPoint(), outGeom.asPoint()) data.append(unicode(float(dist))) self.writer.addRecord(data) current += 1 progress.setPercentage(int(current * total))<|fim▁end|>
current = 0 total = 100.0 / float(len(features))
<|file_name|>_outlook.py<|end_file_name|><|fim▁begin|>import datetime import sqlalchemy.orm.exc from nylas.logging import get_logger log = get_logger() from inbox.auth.oauth import OAuthAuthHandler from inbox.basicauth import OAuthError from inbox.models import Namespace from inbox.config import config<|fim▁hole|>from inbox.util.url import url_concat PROVIDER = '_outlook' AUTH_HANDLER_CLS = '_OutlookAuthHandler' # Outlook OAuth app credentials OAUTH_CLIENT_ID = config.get_required('MS_LIVE_OAUTH_CLIENT_ID') OAUTH_CLIENT_SECRET = config.get_required('MS_LIVE_OAUTH_CLIENT_SECRET') OAUTH_REDIRECT_URI = config.get_required('MS_LIVE_OAUTH_REDIRECT_URI') OAUTH_AUTHENTICATE_URL = 'https://login.live.com/oauth20_authorize.srf' OAUTH_ACCESS_TOKEN_URL = 'https://login.live.com/oauth20_token.srf' OAUTH_USER_INFO_URL = 'https://apis.live.net/v5.0/me' OAUTH_BASE_URL = 'https://apis.live.net/v5.0/' OAUTH_SCOPE = ' '.join([ 'wl.basic', # Read access for basic profile info + contacts 'wl.offline_access', # ability to read / update user's info at any time 'wl.emails', # Read access to user's email addresses 'wl.imap']) # R/W access to user's email using IMAP / SMTP class _OutlookAuthHandler(OAuthAuthHandler): OAUTH_CLIENT_ID = OAUTH_CLIENT_ID OAUTH_CLIENT_SECRET = OAUTH_CLIENT_SECRET OAUTH_REDIRECT_URI = OAUTH_REDIRECT_URI OAUTH_AUTHENTICATE_URL = OAUTH_AUTHENTICATE_URL OAUTH_ACCESS_TOKEN_URL = OAUTH_ACCESS_TOKEN_URL OAUTH_USER_INFO_URL = OAUTH_USER_INFO_URL OAUTH_BASE_URL = OAUTH_BASE_URL OAUTH_SCOPE = OAUTH_SCOPE def create_account(self, db_session, email_address, response): email_address = response.get('emails')['account'] try: account = db_session.query(OutlookAccount).filter_by( email_address=email_address).one() except sqlalchemy.orm.exc.NoResultFound: namespace = Namespace() account = OutlookAccount(namespace=namespace) account.refresh_token = response['refresh_token'] account.date = datetime.datetime.utcnow() tok = response.get('access_token') expires_in = response.get('expires_in') token_manager.cache_token(account, tok, expires_in) account.scope = response.get('scope') account.email_address = email_address account.o_id_token = response.get('user_id') account.o_id = response.get('id') account.name = response.get('name') account.gender = response.get('gender') account.link = response.get('link') account.locale = response.get('locale') # Unlike Gmail, Outlook doesn't return the client_id and secret here account.client_id = OAUTH_CLIENT_ID account.client_secret = OAUTH_CLIENT_SECRET # Ensure account has sync enabled. account.enable_sync() return account def validate_token(self, access_token): return self._get_user_info(access_token) def interactive_auth(self, email_address=None): url_args = {'redirect_uri': self.OAUTH_REDIRECT_URI, 'client_id': self.OAUTH_CLIENT_ID, 'response_type': 'code', 'scope': self.OAUTH_SCOPE, 'access_type': 'offline'} url = url_concat(self.OAUTH_AUTHENTICATE_URL, url_args) print ('Please visit the following url to allow access to this ' 'application. The response will provide ' 'code=[AUTHORIZATION_CODE]&lc=XXXX in the location. Paste the' ' AUTHORIZATION_CODE here:') print '\n{}'.format(url) while True: auth_code = raw_input('Enter authorization code: ').strip() try: auth_response = self._get_authenticated_user(auth_code) return auth_response except OAuthError: print '\nInvalid authorization code, try again...\n' auth_code = None<|fim▁end|>
from inbox.models.backends.outlook import OutlookAccount from inbox.models.backends.oauth import token_manager
<|file_name|>caches.py<|end_file_name|><|fim▁begin|>""" Various caching help functions and classes. """ from django.core.cache import cache DEFAULT_CACHE_DELAY = 60 * 60 # Default cache delay is 1hour. It's quite long. USERACCOUNT_CACHE_DELAY = 60 * 3 # 3 minutes here. This is used to know if a user is online or not. class _AbstractCache(object): """ Abstract cache management class. A cache class manages data about a whole population. It is instanciated with a specific instance of this cache object. """ delay = DEFAULT_CACHE_DELAY def __init__(self, key_prefix): """<|fim▁hole|> # Save key profile AND save an empty cache value to use as an optional global timeout self.key_prefix = key_prefix def _get(self, attr, default = None): """ Return attr from the cache or default value """ return cache.get("%s#%s" % (self.key_prefix, attr), default) def _set(self, attr, value): cache.set("%s#%s" % (self.key_prefix, attr), value, self.delay) class UserAccountCache(_AbstractCache): delay = USERACCOUNT_CACHE_DELAY def __init__(self, useraccount_or_id): """ Instanciate a cache from given user (or userid) """ # Instanciate cache from twistranet.twistapp import Twistable if isinstance(useraccount_or_id, Twistable): useraccount_or_id = useraccount_or_id.id super(UserAccountCache, self).__init__("UA%d" % useraccount_or_id) # Online information def get_online(self): return self._get("online", False) def set_online(self, v): return self._set("online", v) online = property(get_online, set_online)<|fim▁end|>
We store the key prefix for easy values retrieval """
<|file_name|>local_test.go<|end_file_name|><|fim▁begin|>// Copyright 2011, 2012, 2013 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package ec2_test import ( "fmt" "net" "regexp" "sort" "strings" "github.com/juju/errors" jc "github.com/juju/testing/checkers" "github.com/juju/utils" "github.com/juju/utils/set" "gopkg.in/amz.v3/aws" amzec2 "gopkg.in/amz.v3/ec2" "gopkg.in/amz.v3/ec2/ec2test" "gopkg.in/amz.v3/s3/s3test" gc "gopkg.in/check.v1" goyaml "gopkg.in/yaml.v1" "github.com/juju/juju/constraints" "github.com/juju/juju/environs" "github.com/juju/juju/environs/bootstrap" "github.com/juju/juju/environs/config" "github.com/juju/juju/environs/configstore" "github.com/juju/juju/environs/imagemetadata" "github.com/juju/juju/environs/jujutest" "github.com/juju/juju/environs/simplestreams" envtesting "github.com/juju/juju/environs/testing" "github.com/juju/juju/environs/tools" "github.com/juju/juju/feature" "github.com/juju/juju/instance" "github.com/juju/juju/juju/arch" "github.com/juju/juju/juju/testing" "github.com/juju/juju/network" "github.com/juju/juju/provider/common" "github.com/juju/juju/provider/ec2" coretesting "github.com/juju/juju/testing" "github.com/juju/juju/utils/ssh" "github.com/juju/juju/version" ) type ProviderSuite struct { coretesting.BaseSuite } var _ = gc.Suite(&ProviderSuite{}) var localConfigAttrs = coretesting.FakeConfig().Merge(coretesting.Attrs{ "name": "sample", "type": "ec2", "region": "test", "control-bucket": "test-bucket", "access-key": "x", "secret-key": "x", "agent-version": version.Current.Number.String(), }) func registerLocalTests() { // N.B. Make sure the region we use here // has entries in the images/query txt files. aws.Regions["test"] = aws.Region{ Name: "test", } gc.Suite(&localServerSuite{}) gc.Suite(&localLiveSuite{}) gc.Suite(&localNonUSEastSuite{}) } // localLiveSuite runs tests from LiveTests using a fake // EC2 server that runs within the test process itself. type localLiveSuite struct { LiveTests srv localServer restoreEC2Patching func() } func (t *localLiveSuite) SetUpSuite(c *gc.C) { // Upload arches that ec2 supports; add to this // as ec2 coverage expands. t.UploadArches = []string{arch.AMD64, arch.I386} t.TestConfig = localConfigAttrs t.restoreEC2Patching = patchEC2ForTesting() t.srv.startServer(c) t.LiveTests.SetUpSuite(c) } func (t *localLiveSuite) TearDownSuite(c *gc.C) { t.LiveTests.TearDownSuite(c) t.srv.stopServer(c) t.restoreEC2Patching() } // localServer represents a fake EC2 server running within // the test process itself. type localServer struct { ec2srv *ec2test.Server s3srv *s3test.Server config *s3test.Config } func (srv *localServer) startServer(c *gc.C) { var err error srv.ec2srv, err = ec2test.NewServer() if err != nil { c.Fatalf("cannot start ec2 test server: %v", err) } srv.s3srv, err = s3test.NewServer(srv.config) if err != nil { c.Fatalf("cannot start s3 test server: %v", err) } aws.Regions["test"] = aws.Region{ Name: "test", EC2Endpoint: srv.ec2srv.URL(), S3Endpoint: srv.s3srv.URL(), S3LocationConstraint: true, } srv.addSpice(c) zones := make([]amzec2.AvailabilityZoneInfo, 3) zones[0].Region = "test" zones[0].Name = "test-available" zones[0].State = "available" zones[1].Region = "test" zones[1].Name = "test-impaired" zones[1].State = "impaired" zones[2].Region = "test" zones[2].Name = "test-unavailable" zones[2].State = "unavailable" srv.ec2srv.SetAvailabilityZones(zones) } // addSpice adds some "spice" to the local server // by adding state that may cause tests to fail. func (srv *localServer) addSpice(c *gc.C) { states := []amzec2.InstanceState{ ec2test.ShuttingDown, ec2test.Terminated, ec2test.Stopped, } for _, state := range states { srv.ec2srv.NewInstances(1, "m1.small", "ami-a7f539ce", state, nil) } } func (srv *localServer) stopServer(c *gc.C) { srv.ec2srv.Quit() srv.s3srv.Quit() // Clear out the region because the server address is // no longer valid. delete(aws.Regions, "test") } // localServerSuite contains tests that run against a fake EC2 server // running within the test process itself. These tests can test things that // would be unreasonably slow or expensive to test on a live Amazon server. // It starts a new local ec2test server for each test. The server is // accessed by using the "test" region, which is changed to point to the // network address of the local server. type localServerSuite struct { coretesting.BaseSuite jujutest.Tests srv localServer restoreEC2Patching func() } func (t *localServerSuite) SetUpSuite(c *gc.C) { // Upload arches that ec2 supports; add to this // as ec2 coverage expands. t.UploadArches = []string{arch.AMD64, arch.I386} t.TestConfig = localConfigAttrs t.restoreEC2Patching = patchEC2ForTesting() t.BaseSuite.SetUpSuite(c) } func (t *localServerSuite) TearDownSuite(c *gc.C) { t.BaseSuite.TearDownSuite(c) t.restoreEC2Patching() } func (t *localServerSuite) SetUpTest(c *gc.C) { t.BaseSuite.SetUpTest(c) t.SetFeatureFlags(feature.AddressAllocation) t.srv.startServer(c) t.Tests.SetUpTest(c) t.PatchValue(&version.Current, version.Binary{ Number: version.Current.Number, Series: coretesting.FakeDefaultSeries, Arch: arch.AMD64, }) } func (t *localServerSuite) TearDownTest(c *gc.C) { t.Tests.TearDownTest(c) t.srv.stopServer(c) t.BaseSuite.TearDownTest(c) } func (t *localServerSuite) prepareEnviron(c *gc.C) environs.NetworkingEnviron { env := t.Prepare(c) netenv, supported := environs.SupportsNetworking(env) c.Assert(supported, jc.IsTrue) return netenv } func (t *localServerSuite) TestBootstrapInstanceUserDataAndState(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) // check that StateServerInstances returns the id of the bootstrap machine. instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(instanceIds, gc.HasLen, 1) insts, err := env.AllInstances() c.Assert(err, jc.ErrorIsNil) c.Assert(insts, gc.HasLen, 1) c.Check(insts[0].Id(), gc.Equals, instanceIds[0]) // check that the user data is configured to start zookeeper // and the machine and provisioning agents. // check that the user data is configured to only configure // authorized SSH keys and set the log output; everything // else happens after the machine is brought up. inst := t.srv.ec2srv.Instance(string(insts[0].Id())) c.Assert(inst, gc.NotNil) addresses, err := insts[0].Addresses() c.Assert(err, jc.ErrorIsNil) c.Assert(addresses, gc.Not(gc.HasLen), 0) userData, err := utils.Gunzip(inst.UserData) c.Assert(err, jc.ErrorIsNil) c.Logf("first instance: UserData: %q", userData) var userDataMap map[interface{}]interface{} err = goyaml.Unmarshal(userData, &userDataMap) c.Assert(err, jc.ErrorIsNil) c.Assert(userDataMap, jc.DeepEquals, map[interface{}]interface{}{ "output": map[interface{}]interface{}{ "all": "| tee -a /var/log/cloud-init-output.log", }, "ssh_authorized_keys": splitAuthKeys(env.Config().AuthorizedKeys()), "runcmd": []interface{}{ "set -xe", "install -D -m 644 /dev/null '/var/lib/juju/nonce.txt'", "printf '%s\\n' 'user-admin:bootstrap' > '/var/lib/juju/nonce.txt'", }, }) // check that a new instance will be started with a machine agent inst1, hc := testing.AssertStartInstance(c, env, "1") c.Check(*hc.Arch, gc.Equals, "amd64") c.Check(*hc.Mem, gc.Equals, uint64(1740)) c.Check(*hc.CpuCores, gc.Equals, uint64(1)) c.Assert(*hc.CpuPower, gc.Equals, uint64(100)) inst = t.srv.ec2srv.Instance(string(inst1.Id())) c.Assert(inst, gc.NotNil) userData, err = utils.Gunzip(inst.UserData) c.Assert(err, jc.ErrorIsNil) c.Logf("second instance: UserData: %q", userData) userDataMap = nil err = goyaml.Unmarshal(userData, &userDataMap) c.Assert(err, jc.ErrorIsNil) CheckPackage(c, userDataMap, "curl", true) CheckPackage(c, userDataMap, "mongodb-server", false) CheckScripts(c, userDataMap, "jujud bootstrap-state", false) CheckScripts(c, userDataMap, "/var/lib/juju/agents/machine-1/agent.conf", true) // TODO check for provisioning agent err = env.Destroy() c.Assert(err, jc.ErrorIsNil) _, err = env.StateServerInstances() c.Assert(err, gc.Equals, environs.ErrNotBootstrapped) } // splitAuthKeys splits the given authorized keys // into the form expected to be found in the // user data. func splitAuthKeys(keys string) []interface{} { slines := strings.FieldsFunc(keys, func(r rune) bool { return r == '\n' }) var lines []interface{} for _, line := range slines { lines = append(lines, ssh.EnsureJujuComment(strings.TrimSpace(line))) } return lines } func (t *localServerSuite) TestInstanceStatus(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) t.srv.ec2srv.SetInitialInstanceState(ec2test.Terminated) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, jc.ErrorIsNil) c.Assert(inst.Status(), gc.Equals, "terminated") } func (t *localServerSuite) TestStartInstanceHardwareCharacteristics(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) _, hc := testing.AssertStartInstance(c, env, "1") c.Check(*hc.Arch, gc.Equals, "amd64") c.Check(*hc.Mem, gc.Equals, uint64(1740)) c.Check(*hc.CpuCores, gc.Equals, uint64(1)) c.Assert(*hc.CpuPower, gc.Equals, uint64(100)) } func (t *localServerSuite) TestStartInstanceAvailZone(c *gc.C) { inst, err := t.testStartInstanceAvailZone(c, "test-available") c.Assert(err, jc.ErrorIsNil) c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "test-available") } func (t *localServerSuite) TestStartInstanceAvailZoneImpaired(c *gc.C) { _, err := t.testStartInstanceAvailZone(c, "test-impaired") c.Assert(err, gc.ErrorMatches, `availability zone "test-impaired" is impaired`) } func (t *localServerSuite) TestStartInstanceAvailZoneUnknown(c *gc.C) { _, err := t.testStartInstanceAvailZone(c, "test-unknown") c.Assert(err, gc.ErrorMatches, `invalid availability zone "test-unknown"`) } func (t *localServerSuite) testStartInstanceAvailZone(c *gc.C, zone string) (instance.Instance, error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) params := environs.StartInstanceParams{Placement: "zone=" + zone} result, err := testing.StartInstanceWithParams(env, "1", params, nil) if err != nil { return nil, err } return result.Instance, nil } func (t *localServerSuite) TestGetAvailabilityZones(c *gc.C) { var resultZones []amzec2.AvailabilityZoneInfo var resultErr error t.PatchValue(ec2.EC2AvailabilityZones, func(e *amzec2.EC2, f *amzec2.Filter) (*amzec2.AvailabilityZonesResp, error) { resp := &amzec2.AvailabilityZonesResp{ Zones: append([]amzec2.AvailabilityZoneInfo{}, resultZones...), } return resp, resultErr }) env := t.Prepare(c).(common.ZonedEnviron) resultErr = fmt.Errorf("failed to get availability zones") zones, err := env.AvailabilityZones() c.Assert(err, gc.Equals, resultErr) c.Assert(zones, gc.IsNil) resultErr = nil resultZones = make([]amzec2.AvailabilityZoneInfo, 1) resultZones[0].Name = "whatever" zones, err = env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 1) c.Assert(zones[0].Name(), gc.Equals, "whatever") // A successful result is cached, currently for the lifetime // of the Environ. This will change if/when we have long-lived // Environs to cut down repeated IaaS requests. resultErr = fmt.Errorf("failed to get availability zones") resultZones[0].Name = "andever" zones, err = env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 1) c.Assert(zones[0].Name(), gc.Equals, "whatever") } func (t *localServerSuite) TestGetAvailabilityZonesCommon(c *gc.C) { var resultZones []amzec2.AvailabilityZoneInfo t.PatchValue(ec2.EC2AvailabilityZones, func(e *amzec2.EC2, f *amzec2.Filter) (*amzec2.AvailabilityZonesResp, error) { resp := &amzec2.AvailabilityZonesResp{ Zones: append([]amzec2.AvailabilityZoneInfo{}, resultZones...), } return resp, nil }) env := t.Prepare(c).(common.ZonedEnviron) resultZones = make([]amzec2.AvailabilityZoneInfo, 2) resultZones[0].Name = "az1" resultZones[1].Name = "az2" resultZones[0].State = "available" resultZones[1].State = "impaired" zones, err := env.AvailabilityZones() c.Assert(err, jc.ErrorIsNil) c.Assert(zones, gc.HasLen, 2) c.Assert(zones[0].Name(), gc.Equals, resultZones[0].Name) c.Assert(zones[1].Name(), gc.Equals, resultZones[1].Name) c.Assert(zones[0].Available(), jc.IsTrue) c.Assert(zones[1].Available(), jc.IsFalse) } type mockAvailabilityZoneAllocations struct { group []instance.Id // input param result []common.AvailabilityZoneInstances err error } func (t *mockAvailabilityZoneAllocations) AvailabilityZoneAllocations( e common.ZonedEnviron, group []instance.Id, ) ([]common.AvailabilityZoneInstances, error) { t.group = group return t.result, t.err } func (t *localServerSuite) TestStartInstanceDistributionParams(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{{ZoneName: "az1"}}, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) // no distribution group specified testing.AssertStartInstance(c, env, "1") c.Assert(mock.group, gc.HasLen, 0) // distribution group specified: ensure it's passed through to AvailabilityZone. expectedInstances := []instance.Id{"i-0", "i-1"} params := environs.StartInstanceParams{ DistributionGroup: func() ([]instance.Id, error) { return expectedInstances, nil }, } _, err = testing.StartInstanceWithParams(env, "1", params, nil) c.Assert(err, jc.ErrorIsNil) c.Assert(mock.group, gc.DeepEquals, expectedInstances) } func (t *localServerSuite) TestStartInstanceDistributionErrors(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ err: fmt.Errorf("AvailabilityZoneAllocations failed"), } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) _, _, _, err = testing.StartInstance(env, "1") c.Assert(errors.Cause(err), gc.Equals, mock.err) mock.err = nil dgErr := fmt.Errorf("DistributionGroup failed") params := environs.StartInstanceParams{ DistributionGroup: func() ([]instance.Id, error) { return nil, dgErr }, } _, err = testing.StartInstanceWithParams(env, "1", params, nil) c.Assert(errors.Cause(err), gc.Equals, dgErr) } func (t *localServerSuite) TestStartInstanceDistribution(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) // test-available is the only available AZ, so AvailabilityZoneAllocations // is guaranteed to return that. inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "test-available") } var azConstrainedErr = &amzec2.Error{ Code: "Unsupported", Message: "The requested Availability Zone is currently constrained etc.", } var azVolumeTypeNotAvailableInZoneErr = &amzec2.Error{ Code: "VolumeTypeNotAvailableInZone", Message: "blah blah", } var azInsufficientInstanceCapacityErr = &amzec2.Error{ Code: "InsufficientInstanceCapacity", Message: "We currently do not have sufficient m1.small capacity in the " + "Availability Zone you requested (us-east-1d). Our system will " + "be working on provisioning additional capacity. You can currently get m1.small " + "capacity by not specifying an Availability Zone in your request or choosing " + "us-east-1c, us-east-1a.", } var azNoDefaultSubnetErr = &amzec2.Error{ Code: "InvalidInput", Message: "No default subnet for availability zone: ''us-east-1e''.", } func (t *localServerSuite) TestStartInstanceAvailZoneAllConstrained(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azConstrainedErr) } func (t *localServerSuite) TestStartInstanceVolumeTypeNotAvailable(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azVolumeTypeNotAvailableInZoneErr) } func (t *localServerSuite) TestStartInstanceAvailZoneAllInsufficientInstanceCapacity(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azInsufficientInstanceCapacityErr) } func (t *localServerSuite) TestStartInstanceAvailZoneAllNoDefaultSubnet(c *gc.C) { t.testStartInstanceAvailZoneAllConstrained(c, azNoDefaultSubnetErr) } func (t *localServerSuite) testStartInstanceAvailZoneAllConstrained(c *gc.C, runInstancesError *amzec2.Error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{ {ZoneName: "az1"}, {ZoneName: "az2"}, }, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) var azArgs []string t.PatchValue(ec2.RunInstances, func(e *amzec2.EC2, ri *amzec2.RunInstances) (*amzec2.RunInstancesResp, error) { azArgs = append(azArgs, ri.AvailZone) return nil, runInstancesError }) _, _, _, err = testing.StartInstance(env, "1") c.Assert(err, gc.ErrorMatches, fmt.Sprintf( "cannot run instances: %s \\(%s\\)", regexp.QuoteMeta(runInstancesError.Message), runInstancesError.Code, )) c.Assert(azArgs, gc.DeepEquals, []string{"az1", "az2"}) } func (t *localServerSuite) TestStartInstanceAvailZoneOneConstrained(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azConstrainedErr) } func (t *localServerSuite) TestStartInstanceAvailZoneOneInsufficientInstanceCapacity(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azInsufficientInstanceCapacityErr) } func (t *localServerSuite) TestStartInstanceAvailZoneOneNoDefaultSubnetErr(c *gc.C) { t.testStartInstanceAvailZoneOneConstrained(c, azNoDefaultSubnetErr) } func (t *localServerSuite) testStartInstanceAvailZoneOneConstrained(c *gc.C, runInstancesError *amzec2.Error) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) mock := mockAvailabilityZoneAllocations{ result: []common.AvailabilityZoneInstances{ {ZoneName: "az1"}, {ZoneName: "az2"}, }, } t.PatchValue(ec2.AvailabilityZoneAllocations, mock.AvailabilityZoneAllocations) // The first call to RunInstances fails with an error indicating the AZ // is constrained. The second attempt succeeds, and so allocates to az2. var azArgs []string realRunInstances := *ec2.RunInstances t.PatchValue(ec2.RunInstances, func(e *amzec2.EC2, ri *amzec2.RunInstances) (*amzec2.RunInstancesResp, error) { azArgs = append(azArgs, ri.AvailZone) if len(azArgs) == 1 { return nil, runInstancesError } return realRunInstances(e, ri) }) inst, hwc := testing.AssertStartInstance(c, env, "1") c.Assert(azArgs, gc.DeepEquals, []string{"az1", "az2"}) c.Assert(ec2.InstanceEC2(inst).AvailZone, gc.Equals, "az2") c.Check(*hwc.AvailabilityZone, gc.Equals, "az2") } func (t *localServerSuite) TestAddresses(c *gc.C) { env := t.Prepare(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) inst, _ := testing.AssertStartInstance(c, env, "1") c.Assert(err, jc.ErrorIsNil) addrs, err := inst.Addresses() c.Assert(err, jc.ErrorIsNil) // Expected values use Address type but really contain a regexp for // the value rather than a valid ip or hostname. expected := []network.Address{{ Value: "8.0.0.*", Type: network.IPv4Address, Scope: network.ScopePublic, }, { Value: "127.0.0.*", Type: network.IPv4Address, Scope: network.ScopeCloudLocal, }} c.Assert(addrs, gc.HasLen, len(expected)) for i, addr := range addrs { c.Check(addr.Value, gc.Matches, expected[i].Value) c.Check(addr.Type, gc.Equals, expected[i].Type) c.Check(addr.Scope, gc.Equals, expected[i].Scope) } } func (t *localServerSuite) TestConstraintsValidatorUnsupported(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) cons := constraints.MustParse("arch=amd64 tags=foo") unsupported, err := validator.Validate(cons) c.Assert(err, jc.ErrorIsNil) c.Assert(unsupported, gc.DeepEquals, []string{"tags"}) } func (t *localServerSuite) TestConstraintsValidatorVocab(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) cons := constraints.MustParse("arch=ppc64el") _, err = validator.Validate(cons) c.Assert(err, gc.ErrorMatches, "invalid constraint value: arch=ppc64el\nvalid values are:.*") cons = constraints.MustParse("instance-type=foo") _, err = validator.Validate(cons) c.Assert(err, gc.ErrorMatches, "invalid constraint value: instance-type=foo\nvalid values are:.*") } func (t *localServerSuite) TestConstraintsMerge(c *gc.C) { env := t.Prepare(c) validator, err := env.ConstraintsValidator() c.Assert(err, jc.ErrorIsNil) consA := constraints.MustParse("arch=amd64 mem=1G cpu-power=10 cpu-cores=2 tags=bar") consB := constraints.MustParse("arch=i386 instance-type=m1.small") cons, err := validator.Merge(consA, consB) c.Assert(err, jc.ErrorIsNil) c.Assert(cons, gc.DeepEquals, constraints.MustParse("arch=i386 instance-type=m1.small tags=bar")) } func (t *localServerSuite) TestPrecheckInstanceValidInstanceType(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=m1.small root-disk=1G") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceInvalidInstanceType(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=m1.invalid") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, gc.ErrorMatches, `invalid AWS instance type "m1.invalid" specified`) } func (t *localServerSuite) TestPrecheckInstanceUnsupportedArch(c *gc.C) { env := t.Prepare(c) cons := constraints.MustParse("instance-type=cc1.4xlarge arch=i386") placement := "" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, cons, placement) c.Assert(err, gc.ErrorMatches, `invalid AWS instance type "cc1.4xlarge" and arch "i386" specified`) } func (t *localServerSuite) TestPrecheckInstanceAvailZone(c *gc.C) { env := t.Prepare(c) placement := "zone=test-available" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceAvailZoneUnavailable(c *gc.C) { env := t.Prepare(c) placement := "zone=test-unavailable" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestPrecheckInstanceAvailZoneUnknown(c *gc.C) { env := t.Prepare(c) placement := "zone=test-unknown" err := env.PrecheckInstance(coretesting.FakeDefaultSeries, constraints.Value{}, placement) c.Assert(err, gc.ErrorMatches, `invalid availability zone "test-unknown"`) } func (t *localServerSuite) TestValidateImageMetadata(c *gc.C) { env := t.Prepare(c) params, err := env.(simplestreams.MetadataValidator).MetadataLookupParams("test") c.Assert(err, jc.ErrorIsNil) params.Series = coretesting.FakeDefaultSeries params.Endpoint = "https://ec2.endpoint.com" params.Sources, err = environs.ImageMetadataSources(env) c.Assert(err, jc.ErrorIsNil) image_ids, _, err := imagemetadata.ValidateImageMetadata(params) c.Assert(err, jc.ErrorIsNil) sort.Strings(image_ids) c.Assert(image_ids, gc.DeepEquals, []string{"ami-00000033", "ami-00000034", "ami-00000035", "ami-00000039"}) } func (t *localServerSuite) TestGetToolsMetadataSources(c *gc.C) { t.PatchValue(&tools.DefaultBaseURL, "") env := t.Prepare(c) sources, err := tools.GetMetadataSources(env) c.Assert(err, jc.ErrorIsNil) c.Assert(sources, gc.HasLen, 0) } func (t *localServerSuite) TestSupportedArchitectures(c *gc.C) { env := t.Prepare(c) a, err := env.SupportedArchitectures() c.Assert(err, jc.ErrorIsNil) c.Assert(a, jc.SameContents, []string{"amd64", "i386"}) } func (t *localServerSuite) TestSupportsNetworking(c *gc.C) { env := t.Prepare(c) _, supported := environs.SupportsNetworking(env) c.Assert(supported, jc.IsTrue) } func (t *localServerSuite) TestAllocateAddressFailureToFindNetworkInterface(c *gc.C) { env := t.prepareEnviron(c) err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) instId := instanceIds[0] addr := network.Address{Value: "8.0.0.4"} // Invalid instance found err = env.AllocateAddress(instId+"foo", "", addr) c.Assert(err, gc.ErrorMatches, ".*InvalidInstanceID.NotFound.*") // No network interface err = env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.ErrorMatches, "unexpected AWS response: network interface not found") } func (t *localServerSuite) setUpInstanceWithDefaultVpc(c *gc.C) (environs.NetworkingEnviron, instance.Id) { // setting a default-vpc will create a network interface t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) env := t.prepareEnviron(c)<|fim▁hole|> err := bootstrap.Bootstrap(envtesting.BootstrapContext(c), env, bootstrap.BootstrapParams{}) c.Assert(err, jc.ErrorIsNil) instanceIds, err := env.StateServerInstances() c.Assert(err, jc.ErrorIsNil) return env, instanceIds[0] } func (t *localServerSuite) TestAllocateAddress(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} var actualAddr network.Address mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { actualAddr = addr return nil } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) c.Assert(actualAddr, gc.Equals, addr) } func (t *localServerSuite) TestAllocateAddressIPAddressInUseOrEmpty(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { return &amzec2.Error{Code: "InvalidParameterValue"} } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressUnavailable) err = env.AllocateAddress(instId, "", network.Address{}) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressUnavailable) } func (t *localServerSuite) TestAllocateAddressNetworkInterfaceFull(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} mockAssign := func(ec2Inst *amzec2.EC2, netId string, addr network.Address) error { return &amzec2.Error{Code: "PrivateIpAddressLimitExceeded"} } t.PatchValue(&ec2.AssignPrivateIPAddress, mockAssign) err := env.AllocateAddress(instId, "", addr) c.Assert(errors.Cause(err), gc.Equals, environs.ErrIPAddressesExhausted) } func (t *localServerSuite) TestReleaseAddress(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) addr := network.Address{Value: "8.0.0.4"} // Allocate the address first so we can release it err := env.AllocateAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) err = env.ReleaseAddress(instId, "", addr) c.Assert(err, jc.ErrorIsNil) // Releasing a second time tests that the first call actually released // it plus tests the error handling of ReleaseAddress err = env.ReleaseAddress(instId, "", addr) msg := fmt.Sprintf(`failed to release address "8\.0\.0\.4" from instance %q.*`, instId) c.Assert(err, gc.ErrorMatches, msg) } func (t *localServerSuite) TestReleaseAddressUnknownInstance(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) // We should be able to release an address with an unknown instance id // without it being allocated. addr := network.Address{Value: "8.0.0.4"} err := env.ReleaseAddress(instance.UnknownId, "", addr) c.Assert(err, jc.ErrorIsNil) } func (t *localServerSuite) TestNetworkInterfaces(c *gc.C) { env, instId := t.setUpInstanceWithDefaultVpc(c) interfaces, err := env.NetworkInterfaces(instId) c.Assert(err, jc.ErrorIsNil) expectedInterfaces := []network.InterfaceInfo{{ DeviceIndex: 0, MACAddress: "20:01:60:cb:27:37", CIDR: "10.10.0.0/20", ProviderId: "eni-0", ProviderSubnetId: "subnet-0", VLANTag: 0, InterfaceName: "unsupported0", Disabled: false, NoAutoStart: false, ConfigType: network.ConfigDHCP, Address: network.NewScopedAddress("10.10.0.5", network.ScopeCloudLocal), }} c.Assert(interfaces, jc.DeepEquals, expectedInterfaces) } func (t *localServerSuite) TestSubnets(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) subnets, err := env.Subnets("", []network.Id{"subnet-0"}) c.Assert(err, jc.ErrorIsNil) defaultSubnets := []network.SubnetInfo{{ // this is defined in the test server for the default-vpc CIDR: "10.10.0.0/20", ProviderId: "subnet-0", VLANTag: 0, AllocatableIPLow: net.ParseIP("10.10.0.4").To4(), AllocatableIPHigh: net.ParseIP("10.10.15.254").To4(), }} c.Assert(subnets, jc.DeepEquals, defaultSubnets) } func (t *localServerSuite) TestSubnetsNoNetIds(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) _, err := env.Subnets("", []network.Id{}) c.Assert(err, gc.ErrorMatches, "subnetIds must not be empty") } func (t *localServerSuite) TestSubnetsMissingSubnet(c *gc.C) { env, _ := t.setUpInstanceWithDefaultVpc(c) _, err := env.Subnets("", []network.Id{"subnet-0", "Missing"}) c.Assert(err, gc.ErrorMatches, `failed to find the following subnet ids: \[Missing\]`) } func (t *localServerSuite) TestSupportsAddressAllocationTrue(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsTrue) } func (t *localServerSuite) TestSupportsAddressAllocationWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) c.Assert(result, jc.IsFalse) } func (t *localServerSuite) TestAllocateAddressWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) err := env.AllocateAddress("i-foo", "net1", network.NewAddresses("1.2.3.4")[0]) c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) } func (t *localServerSuite) TestReleaseAddressWithNoFeatureFlag(c *gc.C) { t.SetFeatureFlags() // clear the flags. env := t.prepareEnviron(c) err := env.ReleaseAddress("i-foo", "net1", network.NewAddresses("1.2.3.4")[0]) c.Assert(err, gc.ErrorMatches, "address allocation not supported") c.Assert(err, jc.Satisfies, errors.IsNotSupported) } func (t *localServerSuite) TestSupportsAddressAllocationCaches(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"none"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) // this value won't change normally, the change here is to // ensure that subsequent calls use the cached value t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"vpc-xxxxxxx"}, }) result, err = env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) } func (t *localServerSuite) TestSupportsAddressAllocationFalse(c *gc.C) { t.srv.ec2srv.SetInitialAttributes(map[string][]string{ "default-vpc": {"none"}, }) env := t.prepareEnviron(c) result, err := env.SupportsAddressAllocation("") c.Assert(err, jc.ErrorIsNil) c.Assert(result, jc.IsFalse) } // localNonUSEastSuite is similar to localServerSuite but the S3 mock server // behaves as if it is not in the us-east region. type localNonUSEastSuite struct { coretesting.BaseSuite restoreEC2Patching func() srv localServer env environs.Environ } func (t *localNonUSEastSuite) SetUpSuite(c *gc.C) { t.BaseSuite.SetUpSuite(c) t.restoreEC2Patching = patchEC2ForTesting() } func (t *localNonUSEastSuite) TearDownSuite(c *gc.C) { t.restoreEC2Patching() t.BaseSuite.TearDownSuite(c) } func (t *localNonUSEastSuite) SetUpTest(c *gc.C) { t.BaseSuite.SetUpTest(c) t.srv.config = &s3test.Config{ Send409Conflict: true, } t.srv.startServer(c) cfg, err := config.New(config.NoDefaults, localConfigAttrs) c.Assert(err, jc.ErrorIsNil) env, err := environs.Prepare(cfg, envtesting.BootstrapContext(c), configstore.NewMem()) c.Assert(err, jc.ErrorIsNil) t.env = env } func (t *localNonUSEastSuite) TearDownTest(c *gc.C) { t.srv.stopServer(c) t.BaseSuite.TearDownTest(c) } func patchEC2ForTesting() func() { ec2.UseTestImageData(ec2.TestImagesData) ec2.UseTestInstanceTypeData(ec2.TestInstanceTypeCosts) ec2.UseTestRegionData(ec2.TestRegions) restoreTimeouts := envtesting.PatchAttemptStrategies(ec2.ShortAttempt, ec2.StorageAttempt) restoreFinishBootstrap := envtesting.DisableFinishBootstrap() return func() { restoreFinishBootstrap() restoreTimeouts() ec2.UseTestImageData(nil) ec2.UseTestInstanceTypeData(nil) ec2.UseTestRegionData(nil) } } // If match is true, CheckScripts checks that at least one script started // by the cloudinit data matches the given regexp pattern, otherwise it // checks that no script matches. It's exported so it can be used by tests // defined in ec2_test. func CheckScripts(c *gc.C, userDataMap map[interface{}]interface{}, pattern string, match bool) { scripts0 := userDataMap["runcmd"] if scripts0 == nil { c.Errorf("cloudinit has no entry for runcmd") return } scripts := scripts0.([]interface{}) re := regexp.MustCompile(pattern) found := false for _, s0 := range scripts { s := s0.(string) if re.MatchString(s) { found = true } } switch { case match && !found: c.Errorf("script %q not found in %q", pattern, scripts) case !match && found: c.Errorf("script %q found but not expected in %q", pattern, scripts) } } // CheckPackage checks that the cloudinit will or won't install the given // package, depending on the value of match. It's exported so it can be // used by tests defined outside the ec2 package. func CheckPackage(c *gc.C, userDataMap map[interface{}]interface{}, pkg string, match bool) { pkgs0 := userDataMap["packages"] if pkgs0 == nil { if match { c.Errorf("cloudinit has no entry for packages") } return } pkgs := pkgs0.([]interface{}) found := false for _, p0 := range pkgs { p := p0.(string) // p might be a space separate list of packages eg 'foo bar qed' so split them up manyPkgs := set.NewStrings(strings.Split(p, " ")...) hasPkg := manyPkgs.Contains(pkg) if p == pkg || hasPkg { found = true break } } switch { case match && !found: c.Errorf("package %q not found in %v", pkg, pkgs) case !match && found: c.Errorf("%q found but not expected in %v", pkg, pkgs) } }<|fim▁end|>
<|file_name|>mirall_cs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="cs_CZ" version="2.0"> <context> <name>FolderWizardSourcePage</name> <message> <location filename="../src/gui/folderwizardsourcepage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/folderwizardsourcepage.ui" line="33"/> <source>Pick a local folder on your computer to sync</source> <translation>Zvolte místní složku na vašem počítači k synchronizaci</translation> </message> <message> <location filename="../src/gui/folderwizardsourcepage.ui" line="44"/> <source>&amp;Choose...</source> <translation>Vy&amp;brat...</translation> </message> <message> <location filename="../src/gui/folderwizardsourcepage.ui" line="55"/> <source>&amp;Directory alias name:</source> <translation>&amp;Alias názvu adresáře:</translation> </message> </context> <context> <name>FolderWizardTargetPage</name> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="128"/> <source>Select a remote destination folder</source> <translation>Zvolte vzdálenou cílovou složku</translation> </message> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="140"/> <source>Add Folder</source> <translation>Přidat složku</translation> </message> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="160"/> <source>Refresh</source> <translation>Obnovit</translation> </message> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="174"/> <source>Folders</source> <translation>Složky</translation> </message> <message> <location filename="../src/gui/folderwizardtargetpage.ui" line="107"/> <source>TextLabel</source> <translation>TextLabel</translation> </message> </context> <context> <name>Mirall::AccountSettings</name> <message> <location filename="../src/gui/accountsettings.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="143"/> <source>Account Maintenance</source> <translation>Správa účtu</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="152"/> <source>Edit Ignored Files</source> <translation>Editovat ignorované soubory</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="159"/> <source>Modify Account</source> <translation>Upravit účet</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="20"/> <source>Account to Synchronize</source> <translation>Účet k synchronizaci</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="41"/> <source>Connected with &lt;server&gt; as &lt;user&gt;</source> <translation>Připojen k &lt;server&gt; jako &lt;user&gt;</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="62"/> <location filename="../src/gui/accountsettings.cpp" line="169"/> <source>Pause</source> <translation>Pozastavit</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="69"/> <source>Remove</source> <translation>Odebrat</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="55"/> <source>Add Folder...</source> <translation>Přidat složku...</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="76"/> <source>Choose What to Sync</source> <translation>Vybrat co synchronizovat</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="101"/> <source>Storage Usage</source> <translation>Obsazený prostor</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="123"/> <source>Retrieving usage information...</source> <translation>Zjišťuji obsazený prostor...</translation> </message> <message> <location filename="../src/gui/accountsettings.ui" line="130"/> <source>&lt;b&gt;Note:&lt;/b&gt; Some folders, including network mounted or shared folders, might have different limits.</source> <translation>&lt;b&gt;Poznámka:&lt;/b&gt; Některé složky, včetně síťových či sdílených složek, mohou mít jiné limity.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="171"/> <source>Resume</source> <translation>Obnovit</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="339"/> <source>Confirm Folder Remove</source> <translation>Potvrdit odstranění složky</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="340"/> <source>&lt;p&gt;Do you really want to stop syncing the folder &lt;i&gt;%1&lt;/i&gt;?&lt;/p&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; This will not remove the files from your client.&lt;/p&gt;</source> <translation>&lt;p&gt;Opravdu chcete zastavit synchronizaci složky &lt;i&gt;%1&lt;/i&gt;?&lt;/p&gt;&lt;p&gt;&lt;b&gt;Poznámka:&lt;/b&gt; Tato akce nesmaže soubory z místní složky.&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="376"/> <source>Confirm Folder Reset</source> <translation>Potvrdit restartování složky</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="377"/> <source>&lt;p&gt;Do you really want to reset folder &lt;i&gt;%1&lt;/i&gt; and rebuild your client database?&lt;/p&gt;&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; This function is designed for maintenance purposes only. No files will be removed, but this can cause significant data traffic and take several minutes or hours to complete, depending on the size of the folder. Only use this option if advised by your administrator.&lt;/p&gt;</source> <translation>&lt;p&gt;Skutečně chcete resetovat složku &lt;i&gt;%1&lt;/i&gt; a znovu sestavit klientskou databázi?&lt;/p&gt;&lt;p&gt;&lt;b&gt;Poznámka:&lt;/b&gt; Tato funkce je určena pouze pro účely údržby. Žádné soubory nebudou smazány, ale může to způsobit velké datové přenosy a dokončení může trvat mnoho minut či hodin v závislosti na množství dat ve složce. Použijte tuto volbu pouze na pokyn správce.&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="608"/> <source>Discovering %1</source> <translation>Hledám %1</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="654"/> <source>%1 %2 (%3 of %4)</source> <extracomment>Example text: &quot;uploading foobar.png (2MB of 2MB)&quot;</extracomment> <translation>%1 %2 (%3 ze %4)</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="658"/> <source>%1 %2</source> <extracomment>Example text: &quot;uploading foobar.png&quot;</extracomment> <translation>%1 %2</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="675"/> <source>file %1 of %2</source> <translation>soubor %1 z %2</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="763"/> <source>%1 (%3%) of %2 server space in use.</source> <translation>%1 (%3%) z %2 místa na disku použito.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="807"/> <source>No connection to %1 at &lt;a href=&quot;%2&quot;&gt;%3&lt;/a&gt;.</source> <translation>Žádné spojení s %1 na &lt;a href=&quot;%2&quot;&gt;%3&lt;/a&gt;.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="814"/> <source>No %1 connection configured.</source> <translation>Žádné spojení s %1 nenastaveno.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="487"/> <source>Sync Running</source> <translation>Synchronizace probíhá</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="110"/> <source>No account configured.</source> <translation>Žádný účet nenastaven.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="488"/> <source>The syncing operation is running.&lt;br/&gt;Do you want to terminate it?</source> <translation>Operace synchronizace právě probíhá.&lt;br/&gt;Přejete si ji ukončit?</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="648"/> <source>%1 %2 (%3 of %4) %5 left at a rate of %6/s</source> <extracomment>Example text: &quot;uploading foobar.png (1MB of 2MB) time left 2 minutes at a rate of 24Kb/s&quot;</extracomment> <translation>%1 %2 (%3 z %4) zbývající čas %5 při rychlosti %6/s</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="669"/> <source>%1 of %2, file %3 of %4 Total time left %5</source> <translation>%1 z %2, soubor %3 ze %4 Celkový zbývající čas %5</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="800"/> <source>Connected to &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt;.</source> <translation>Připojeno k &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt;.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="803"/> <source>Connected to &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt; as &lt;i&gt;%3&lt;/i&gt;.</source> <translation>Připojeno k &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt; jako &lt;i&gt;%3&lt;/i&gt;.</translation> </message> <message> <location filename="../src/gui/accountsettings.cpp" line="767"/> <source>Currently there is no storage usage information available.</source> <translation>Momentálně nejsou k dispozici žádné informace o využití úložiště</translation> </message> </context> <context> <name>Mirall::AuthenticationDialog</name> <message> <location filename="../src/libsync/authenticationdialog.cpp" line="29"/> <source>Authentication Required</source> <translation>Ověření vyžadováno</translation> </message> <message> <location filename="../src/libsync/authenticationdialog.cpp" line="31"/> <source>Enter username and password for &apos;%1&apos; at %2.</source> <translation>Zadejte uživatelské jméno a heslo pro &apos;%1&apos; na %2.</translation> </message> <message> <location filename="../src/libsync/authenticationdialog.cpp" line="35"/> <source>&amp;User:</source> <translation>&amp;Uživatel:</translation> </message> <message> <location filename="../src/libsync/authenticationdialog.cpp" line="36"/> <source>&amp;Password:</source> <translation>&amp;Heslo:</translation> </message> </context> <context> <name>Mirall::ConnectionValidator</name> <message> <location filename="../src/libsync/connectionvalidator.cpp" line="90"/> <source>No ownCloud account configured</source> <translation>Žádný účet ownCloud nenastaven</translation> </message> <message> <location filename="../src/libsync/connectionvalidator.cpp" line="105"/> <source>The configured server for this client is too old</source> <translation>Server nastavený pro tohoto klienta je příliš starý</translation> </message> <message> <location filename="../src/libsync/connectionvalidator.cpp" line="106"/> <source>Please update to the latest server and restart the client.</source> <translation>Prosím, aktualizujte na poslední verzi serveru a restartujte klienta.</translation> </message> <message> <location filename="../src/libsync/connectionvalidator.cpp" line="126"/> <source>Unable to connect to %1</source> <translation>Nelze se připojit k %1</translation> </message> <message> <location filename="../src/libsync/connectionvalidator.cpp" line="156"/> <source>The provided credentials are not correct</source> <translation>Poskytnuté přihlašovací údaje nejsou správné</translation> </message> </context> <context> <name>Mirall::Folder</name> <message> <location filename="../src/gui/folder.cpp" line="110"/> <source>Unable to create csync-context</source> <translation>Nepodařilo se vytvořit csync-context</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="164"/> <source>Local folder %1 does not exist.</source> <translation>Místní složka %1 neexistuje.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="167"/> <source>%1 should be a directory but is not.</source> <translation>%1 by měl být adresář, ale není.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="170"/> <source>%1 is not readable.</source> <translation>%1 není čitelný.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="327"/> <source>%1: %2</source> <translation>%1: %2</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="413"/> <source>%1 and %2 other files have been removed.</source> <comment>%1 names a file.</comment> <translation>%1 a %2 dalších souborů bylo odebráno.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="415"/> <source>%1 has been removed.</source> <comment>%1 names a file.</comment> <translation>%1 byl odebrán.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="420"/> <source>%1 and %2 other files have been downloaded.</source> <comment>%1 names a file.</comment> <translation>%1 a %2 dalších souborů bylo staženo.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="422"/> <source>%1 has been downloaded.</source> <comment>%1 names a file.</comment> <translation>%1 byl stažen.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="427"/> <source>%1 and %2 other files have been updated.</source> <translation>%1 a %2 dalších souborů bylo aktualizováno.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="429"/> <source>%1 has been updated.</source> <comment>%1 names a file.</comment> <translation>%1 byl aktualizován.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="434"/> <source>%1 has been renamed to %2 and %3 other files have been renamed.</source> <translation>%1 byl přejmenován na %2 a %3 dalších souborů bylo přejmenováno.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="436"/> <source>%1 has been renamed to %2.</source> <comment>%1 and %2 name files.</comment> <translation>%1 byl přejmenován na %2.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="441"/> <source>%1 has been moved to %2 and %3 other files have been moved.</source> <translation>%1 byl přesunut do %2 a %3 dalších souborů bylo přesunuto.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="443"/> <source>%1 has been moved to %2.</source> <translation>%1 byl přemístěn do %2.</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="451"/> <source>Sync Activity</source> <translation>Průběh synchronizace</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="738"/> <source>This sync would remove all the files in the sync folder '%1'. This might be because the folder was silently reconfigured, or that all the file were manually removed. Are you sure you want to perform this operation?</source> <translation>Tato synchronizace by smazala všechny soubory ve složce &apos;%1&apos;. Toto může být způsobeno změnou v nastavení synchronizace složky nebo tím, že byly všechny soubory ručně odstraněny. Opravdu chcete provést tuto akci?</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="742"/> <source>Remove All Files?</source> <translation>Odstranit všechny soubory?</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="744"/> <source>Remove all files</source> <translation>Odstranit všechny soubory</translation> </message> <message> <location filename="../src/gui/folder.cpp" line="745"/> <source>Keep files</source> <translation>Ponechat soubory</translation> </message> </context> <context> <name>Mirall::FolderMan</name> <message> <location filename="../src/gui/folderman.cpp" line="215"/> <source>Could not reset folder state</source> <translation>Nelze obnovit stav složky</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="216"/> <source>An old sync journal &apos;%1&apos; was found, but could not be removed. Please make sure that no application is currently using it.</source> <translation>Byl nalezen starý záznam synchronizace &apos;%1&apos;, ale nebylo možné jej odebrat. Ujistěte se, že není aktuálně používán jinou aplikací.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="806"/> <source>Undefined State.</source> <translation>Nedefinovaný stav.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="809"/> <source>Waits to start syncing.</source> <translation>Vyčkává na spuštění synchronizace.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="812"/> <source>Preparing for sync.</source> <translation>Příprava na synchronizaci.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="815"/> <source>Sync is running.</source> <translation>Synchronizace probíhá.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="818"/> <source>Last Sync was successful.</source> <translation>Poslední synchronizace byla úspěšná.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="823"/> <source>Last Sync was successful, but with warnings on individual files.</source> <translation>Poslední synchronizace byla úspěšná, ale s varováním u některých souborů</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="826"/> <source>Setup Error.</source> <translation>Chyba nastavení.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="829"/> <source>User Abort.</source> <translation>Zrušení uživatelem.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="832"/> <source>Sync is paused.</source> <translation>Synchronizace pozastavena.</translation> </message> <message> <location filename="../src/gui/folderman.cpp" line="838"/> <source>%1 (Sync is paused)</source> <translation>%1 (Synchronizace je pozastavena)</translation> </message> </context> <context> <name>Mirall::FolderStatusDelegate</name> <message> <location filename="../src/gui/folderstatusmodel.cpp" line="95"/> <location filename="../src/gui/folderstatusmodel.cpp" line="251"/> <source>File</source> <translation>Soubor</translation> </message> <message> <location filename="../src/gui/folderstatusmodel.cpp" line="205"/> <source>Syncing all files in your account with</source> <translation>Synchronizuji všechny soubory ve vašem účtu s</translation> </message> <message> <location filename="../src/gui/folderstatusmodel.cpp" line="208"/> <source>Remote path: %1</source> <translation>Vzdálená cesta: %1</translation> </message> </context> <context> <name>Mirall::FolderWizard</name> <message> <location filename="../src/gui/folderwizard.cpp" line="491"/> <location filename="../src/gui/folderwizard.cpp" line="493"/> <source>Add Folder</source> <translation>Přidat složku</translation> </message> </context> <context> <name>Mirall::FolderWizardLocalPath</name> <message> <location filename="../src/gui/folderwizard.cpp" line="63"/> <source>Click to select a local folder to sync.</source> <translation>Kliknutím zvolíte místní složku k synchronizaci.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="67"/> <source>Enter the path to the local folder.</source> <translation>Zadejte cestu k místní složce.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="71"/> <source>The directory alias is a descriptive name for this sync connection.</source> <translation>Alias složky je popisné jméno pro tuto synchronizaci.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="100"/> <source>No valid local folder selected!</source> <translation>Nebyla vybrána místní složka!</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="105"/> <source>You have no permission to write to the selected folder!</source> <translation>Nemáte oprávněné pro zápis do zvolené složky!</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="129"/> <source>The local path %1 is already an upload folder. Please pick another one!</source> <translation>Místní cesta %1 je již nastavena jako složka pro odesílání. Zvolte, prosím, jinou!</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="134"/> <source>An already configured folder is contained in the current entry.</source> <translation>V aktuální položce se již nachází složka s nastavenou synchronizací.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="141"/> <source>The selected folder is a symbolic link. An already configured folder is contained in the folder this link is pointing to.</source> <translation>Vybraná složka je symbolický odkaz. Cílová složka tohoto odkazu již obsahuje nastavenou složku.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="148"/> <source>An already configured folder contains the currently entered folder.</source> <translation>Právě zadaná složka je již obsažena ve složce s nastavenou synchronizací.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="154"/> <source>The selected folder is a symbolic link. An already configured folder is the parent of the current selected contains the folder this link is pointing to.</source> <translation>Zvolená složka je symbolický odkaz. Cílová složka tohoto odkazu již obsahuje složku s nastavenou synchronizací.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="167"/> <source>The alias can not be empty. Please provide a descriptive alias word.</source> <translation>Alias nemůže být prázdný. Zadejte prosím slovo, kterým složku popíšete.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="178"/> <source>The alias &lt;i&gt;%1&lt;/i&gt; is already in use. Please pick another alias.</source> <translation>Alias &lt;i&gt;%1&lt;/i&gt; je již používán. Zvolte prosím jiný.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="211"/> <source>Select the source folder</source> <translation>Zvolte zdrojovou složku</translation> </message> </context> <context> <name>Mirall::FolderWizardRemotePath</name> <message> <location filename="../src/gui/folderwizard.cpp" line="254"/> <source>Add Remote Folder</source> <translation>Přidat vzdálený adresář</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="255"/> <source>Enter the name of the new folder:</source> <translation>Zadejte název nové složky:</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="277"/> <source>Folder was successfully created on %1.</source> <translation>Složka byla úspěšně vytvořena na %1.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="285"/> <source>Failed to create the folder on %1. Please check manually.</source> <translation>Na %1 selhalo vytvoření složky. Zkontrolujte to, prosím, ručně.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="334"/> <source>Choose this to sync the entire account</source> <translation>Zvolte toto k provedení synchronizace celého účtu</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="389"/> <source>This folder is already being synced.</source> <translation>Tato složka je již synchronizována.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="391"/> <source>You are already syncing &lt;i&gt;%1&lt;/i&gt;, which is a parent folder of &lt;i&gt;%2&lt;/i&gt;.</source> <translation>Již synchronizujete složku &lt;i&gt;%1&lt;/i&gt;, která je složce &lt;i&gt;%2&lt;/i&gt; nadřazená.</translation> </message> <message> <location filename="../src/gui/folderwizard.cpp" line="395"/> <source>You are already syncing all your files. Syncing another folder is &lt;b&gt;not&lt;/b&gt; supported. If you want to sync multiple folders, please remove the currently configured root folder sync.</source> <translation>Již synchronizujete všechny vaše soubory. Synchronizování další složky &lt;b&gt;není&lt;/b&gt; podporováno. Pokud chcete synchronizovat více složek, odstraňte, prosím, synchronizaci aktuální kořenové složky.</translation> </message> </context> <context> <name>Mirall::FolderWizardSelectiveSync</name> <message> <location filename="../src/gui/folderwizard.cpp" line="433"/> <source>Choose What to Sync: You can optionally deselect subfolders you do not wish to synchronize.</source> <translation>Výběr synchronizace: Můžete dodatečně označit podadresáře, které si nepřejete synchronizovat.</translation> </message> </context> <context> <name>Mirall::FormatWarningsWizardPage</name> <message> <location filename="../src/gui/folderwizard.cpp" line="45"/> <location filename="../src/gui/folderwizard.cpp" line="47"/> <source>&lt;b&gt;Warning:&lt;/b&gt; </source> <translation>&lt;b&gt;Varování:&lt;/b&gt; </translation> </message> </context> <context> <name>Mirall::GETFileJob</name> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="473"/> <source>No E-Tag received from server, check Proxy/Gateway</source> <translation>Ze serveru nebyl obdržen E-Tag, zkontrolujte proxy/bránu</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="480"/> <source>We received a different E-Tag for resuming. Retrying next time.</source> <translation>Obdrželi jsme jiný E-Tag pro pokračování. Zkusím znovu příště.</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="507"/> <source>Server returned wrong content-range</source> <translation>Server odpověděl chybným rozsahem obsahu</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="545"/> <source>Connection Timeout</source> <translation>Spojení vypršelo</translation> </message> </context> <context> <name>Mirall::GeneralSettings</name> <message> <location filename="../src/gui/generalsettings.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="20"/> <source>General Settings</source> <translation>Hlavní nastavení</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="26"/> <source>Launch on System Startup</source> <translation>Spustit při startu systému</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="33"/> <source>Show Desktop Notifications</source> <translation>Zobrazovat události na ploše</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="40"/> <source>Use Monochrome Icons</source> <translation>Používat černobílé ikony</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="50"/> <location filename="../src/gui/generalsettings.ui" line="56"/> <source>About</source> <translation>O aplikaci</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="66"/> <source>Updates</source> <translation>Aktualizace</translation> </message> <message> <location filename="../src/gui/generalsettings.ui" line="91"/> <source>&amp;Restart &amp;&amp; Update</source> <translation>&amp;Restart &amp;&amp; aktualizace</translation> </message> </context> <context> <name>Mirall::HttpCredentials</name> <message> <location filename="../src/libsync/creds/httpcredentials.cpp" line="305"/> <source>Enter Password</source> <translation>Zadejte heslo</translation> </message> <message> <location filename="../src/libsync/creds/httpcredentials.cpp" line="306"/> <source>Please enter %1 password for user &apos;%2&apos;:</source> <translation>Zadejte prosím %1 heslo pro uživatele &apos;%2&apos;: </translation> </message> </context> <context> <name>Mirall::IgnoreListEditor</name> <message> <location filename="../src/gui/ignorelisteditor.ui" line="14"/> <source>Ignored Files Editor</source> <translation>Editor ignorovaných souborů</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.ui" line="53"/> <source>Add</source> <translation>Přidat</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.ui" line="63"/> <source>Remove</source> <translation>Odebrat</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="35"/> <source>Files or directories matching a pattern will not be synchronized. Checked items will also be deleted if they prevent a directory from being removed. This is useful for meta data.</source> <translation>Soubory či adresáře vyhovující masce nebudou synchronizovány. Zvolené položky budou smazány také v případě, že brání smazání adresáře. To je užitečné u meta dat.</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="97"/> <source>Could not open file</source> <translation>Nepodařilo se otevřít soubor</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="98"/> <source>Cannot write changes to &apos;%1&apos;.</source> <translation>Nelze zapsat změny do &apos;%1&apos;.</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="105"/> <source>Add Ignore Pattern</source> <translation>Přidat masku ignorovaných</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="106"/> <source>Add a new ignore pattern:</source> <translation>Přidat novou masku ignorovaných souborů:</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="128"/> <source>Edit Ignore Pattern</source> <translation>Upravit masku ignorovaných</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="129"/> <source>Edit ignore pattern:</source> <translation>Upravit masku ignorovaných:</translation> </message> <message> <location filename="../src/gui/ignorelisteditor.cpp" line="140"/> <source>This entry is provided by the system at &apos;%1&apos; and cannot be modified in this view.</source> <translation>Tato položka je poskytnuta systémem na &apos;%1&apos; a nemůže být v tomto pohledu změněna.</translation> </message> </context> <context> <name>Mirall::LogBrowser</name> <message> <location filename="../src/gui/logbrowser.cpp" line="59"/> <source>Log Output</source> <translation>Zaznamenat výstup</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="71"/> <source>&amp;Search: </source> <translation>&amp;Hledat: </translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="79"/> <source>&amp;Find</source> <translation>Na&amp;jít</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="97"/> <source>Clear</source> <translation>Vyčistit</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="98"/> <source>Clear the log display.</source> <translation>Vyčistit výpis logu.</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="104"/> <source>S&amp;ave</source> <translation>&amp;Uložit</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="105"/> <source>Save the log file to a file on disk for debugging.</source> <translation>Uložit soubor záznamu na disk pro ladění.</translation> </message><|fim▁hole|> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="184"/> <source>Save log file</source> <translation>Uložit log</translation> </message> <message> <location filename="../src/gui/logbrowser.cpp" line="194"/> <source>Could not write to log file </source> <translation>Nemohu zapisovat do log souboru</translation> </message> </context> <context> <name>Mirall::Logger</name> <message> <location filename="../src/libsync/logger.cpp" line="146"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location filename="../src/libsync/logger.cpp" line="147"/> <source>&lt;nobr&gt;File &apos;%1&apos;&lt;br/&gt;cannot be opened for writing.&lt;br/&gt;&lt;br/&gt;The log output can &lt;b&gt;not&lt;/b&gt; be saved!&lt;/nobr&gt;</source> <translation>&lt;nobr&gt;Soubor &apos;%1&apos;&lt;br/&gt;nelze otevřít pro zápis.&lt;br/&gt;&lt;br/&gt;Výstup záznamu &lt;b&gt;nelze&lt;/b&gt; uložit.&lt;/nobr&gt;</translation> </message> </context> <context> <name>Mirall::NSISUpdater</name> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="252"/> <source>New Version Available</source> <translation>Je dostupná nová verze</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="258"/> <source>&lt;p&gt;A new version of the %1 Client is available.&lt;/p&gt;&lt;p&gt;&lt;b&gt;%2&lt;/b&gt; is available for download. The installed version is %3.&lt;/p&gt;</source> <translation>&lt;p&gt;Je k dispozici nová verze klienta %1.&lt;/p&gt;&lt;p&gt;&lt;b&gt;%2&lt;/b&gt; je k dispozici ke stažení. Momentálně je nainstalovaná verze %3.&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="271"/> <source>Skip this version</source> <translation>Přeskoč tuto verzi</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="272"/> <source>Skip this time</source> <translation>Tentokrát přeskočit</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="273"/> <source>Get update</source> <translation>Získat aktualizaci</translation> </message> </context> <context> <name>Mirall::NetworkSettings</name> <message> <location filename="../src/gui/networksettings.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="23"/> <source>Proxy Settings</source> <translation>Nastavení proxy</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="29"/> <source>No Proxy</source> <translation>Bez proxy</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="42"/> <source>Use system proxy</source> <translation>Použít systémové proxy</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="52"/> <source>Specify proxy manually as</source> <translation>Zadat proxy server ručně jako</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="80"/> <source>Host</source> <translation>Počítač</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="100"/> <source>:</source> <translation>:</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="134"/> <source>Proxy server requires authentication</source> <translation>Proxy server vyžaduje přihlášení</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="190"/> <source>Download Bandwidth</source> <translation>Rychlost stahování</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="196"/> <location filename="../src/gui/networksettings.ui" line="278"/> <source>Limit to</source> <translation>Omezit na</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="218"/> <location filename="../src/gui/networksettings.ui" line="320"/> <source>KBytes/s</source> <translation>KBytů/s</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="227"/> <location filename="../src/gui/networksettings.ui" line="295"/> <source>No limit</source> <translation>Bez limitu</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="272"/> <source>Upload Bandwidth</source> <translation>Rychlost odesílání</translation> </message> <message> <location filename="../src/gui/networksettings.ui" line="285"/> <source>Limit automatically</source> <translation>Omezovat automaticky</translation> </message> <message> <location filename="../src/gui/networksettings.cpp" line="34"/> <source>Hostname of proxy server</source> <translation>Adresa proxy serveru</translation> </message> <message> <location filename="../src/gui/networksettings.cpp" line="35"/> <source>Username for proxy server</source> <translation>Uživatelské jméno pro proxy server</translation> </message> <message> <location filename="../src/gui/networksettings.cpp" line="36"/> <source>Password for proxy server</source> <translation>Heslo pro proxy server</translation> </message> <message> <location filename="../src/gui/networksettings.cpp" line="38"/> <source>HTTP(S) proxy</source> <translation>HTTP(S) proxy</translation> </message> <message> <location filename="../src/gui/networksettings.cpp" line="39"/> <source>SOCKS5 proxy</source> <translation>SOCKS5 proxy</translation> </message> </context> <context> <name>Mirall::OCUpdater</name> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="55"/> <source>New Update Ready</source> <translation>Nová aktualizace připravena</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="56"/> <source>A new update is about to be installed. The updater may ask for additional privileges during the process.</source> <translation>Nová aktualizace bude nainstalována. Aktualizační proces si může v průběhu vyžádat dodatečná práva.</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="77"/> <source>Downloading version %1. Please wait...</source> <translation>Stahuji verzi %1. Počkejte prosím ...</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="79"/> <source>Version %1 available. Restart application to start the update.</source> <translation>Verze %1 je dostupná. Aktualizaci zahájíte restartováním aplikace.</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="81"/> <source>Could not download update. Please click &lt;a href=&apos;%1&apos;&gt;here&lt;/a&gt; to download the update manually.</source> <translation>Nemohu stáhnout aktualizaci. Klikněte, prosím, na &lt;a href=&apos;%1&apos;&gt;tento odkaz&lt;/a&gt; pro ruční stažení aktualizace.</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="83"/> <source>Could not check for new updates.</source> <translation>Nemohu zkontrolovat aktualizace.</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="85"/> <source>New version %1 available. Please use the system&apos;s update tool to install it.</source> <translation>Je dostupná nová verze %1. Pro instalaci použijte aktualizační nástroj systému. </translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="87"/> <source>Checking update server...</source> <translation>Kontroluji aktualizační server...</translation> </message> <message> <location filename="../src/gui/updater/ocupdater.cpp" line="91"/> <source>No updates available. Your installation is at the latest version.</source> <translation>Žádne aktualizace nejsou k dispozici. Používáte aktuální verzi.</translation> </message> </context> <context> <name>Mirall::OwncloudAdvancedSetupPage</name> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="49"/> <source>Connect to %1</source> <translation>Připojit k %1</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="50"/> <source>Setup local folder options</source> <translation>Možnosti nastavení místní složky</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="59"/> <source>Connect...</source> <translation>Připojit...</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="121"/> <source>Your entire account will be synced to the local folder &apos;%1&apos;.</source> <translation>Celý váš účet bude synchronizován do místní složky &apos;%1&apos;.</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="124"/> <source>%1 folder &apos;%2&apos; is synced to local folder &apos;%3&apos;</source> <translation>%1 složka &apos;%2&apos; je synchronizována do místní složky &apos;%3&apos;</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="130"/> <source>&lt;p&gt;&lt;small&gt;&lt;strong&gt;Warning:&lt;/strong&gt; You currently have multiple folders configured. If you continue with the current settings, the folder configurations will be discarded and a single root folder sync will be created!&lt;/small&gt;&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;small&gt;&lt;strong&gt;Varování:&lt;/strong&gt; Aktuálně máte nastavenu synchronizaci více složek. Pokud budete pokračovat s tímto nastavení, nastavení složek bude zapomenuto a bude vytvořena synchronizace jedné kořenové složky!&lt;/small&gt;&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="137"/> <source>&lt;p&gt;&lt;small&gt;&lt;strong&gt;Warning:&lt;/strong&gt; The local directory is not empty. Pick a resolution!&lt;/small&gt;&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;small&gt;&lt;strong&gt;Varování:&lt;/strong&gt; Místní složka není prázdná. Zvolte další postup.&lt;/small&gt;&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="253"/> <source>Local Sync Folder</source> <translation>Místní synchronizovaná složka</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.cpp" line="266"/> <source>Update advanced setup</source> <translation>Změnit pokročilé nastavení</translation> </message> </context> <context> <name>Mirall::OwncloudHttpCredsPage</name> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.cpp" line="42"/> <source>Connect to %1</source> <translation>Připojit k %1</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.cpp" line="43"/> <source>Enter user credentials</source> <translation>Zadejte uživatelské údaje</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.cpp" line="159"/> <source>Update user credentials</source> <translation>Upravte uživatelské údaje</translation> </message> </context> <context> <name>Mirall::OwncloudSetupPage</name> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="44"/> <source>Connect to %1</source> <translation>Připojit k %1</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="45"/> <source>Setup %1 server</source> <translation>Nastavit server %1</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="105"/> <source>This url is NOT secure as it is not encrypted. It is not advisable to use it.</source> <translation>Tato adresa NENÍ bezpečná, protože není šifrovaná. Nedoporučuje se jí používat.</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="109"/> <source>This url is secure. You can use it.</source> <translation>URL je bezpečná. Můžete ji použít.</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="223"/> <source>Could not connect securely. Do you want to connect unencrypted instead (not recommended)?</source> <translation>Nemohu se připojit zabezpečeně. Přejete si místo toho připojit nezabezpečeně (nedoporučuje se)? </translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="224"/> <source>Connection failed</source> <translation>Spojení selhalo</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetuppage.cpp" line="259"/> <source>Update %1 server</source> <translation>Upravit server %1</translation> </message> </context> <context> <name>Mirall::OwncloudSetupWizard</name> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="372"/> <source>Folder rename failed</source> <translation>Přejmenování složky selhalo</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="434"/> <location filename="../src/gui/owncloudsetupwizard.cpp" line="443"/> <source>&lt;font color=&quot;green&quot;&gt;&lt;b&gt;Local sync folder %1 successfully created!&lt;/b&gt;&lt;/font&gt;</source> <translation>&lt;font color=&quot;green&quot;&gt;&lt;b&gt;Místní synchronizovaná složka %1 byla vytvořena úspěšně!&lt;/b&gt;&lt;/font&gt;</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="205"/> <source>Trying to connect to %1 at %2...</source> <translation>Pokouším se připojit k %1 na %2...</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="161"/> <source>&lt;font color=&quot;green&quot;&gt;Successfully connected to %1: %2 version %3 (%4)&lt;/font&gt;&lt;br/&gt;&lt;br/&gt;</source> <translation>&lt;font color=&quot;green&quot;&gt;Úspěšně připojeno k %1: %2 verze %3 (%4)&lt;/font&gt;&lt;br/&gt;&lt;br/&gt;</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="230"/> <source>Error: Wrong credentials.</source> <translation>Chyba: nesprávné přihlašovací údaje.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="244"/> <source>Local sync folder %1 already exists, setting it up for sync.&lt;br/&gt;&lt;br/&gt;</source> <translation>Místní synchronizovaná složka %1 již existuje, nastavuji ji pro synchronizaci.&lt;br/&gt;&lt;br/&gt;</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="246"/> <source>Creating local sync folder %1... </source> <translation>Vytvářím místní synchronizovanou složku %1... </translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="250"/> <source>ok</source> <translation>OK</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="252"/> <source>failed.</source> <translation>selhalo.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="254"/> <source>Could not create local folder %1</source> <translation>Nelze vytvořit místní složku %1</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="185"/> <location filename="../src/gui/owncloudsetupwizard.cpp" line="193"/> <source>Failed to connect to %1 at %2:&lt;br/&gt;%3</source> <translation>Selhalo spojení s %1 v %2:&lt;br/&gt;%3</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="279"/> <source>No remote folder specified!</source> <translation>Žádná vzdálená složka nenastavena!</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="285"/> <source>Error: %1</source> <translation>Chyba: %1</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="298"/> <source>creating folder on ownCloud: %1</source> <translation>vytvářím složku na ownCloudu: %1</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="314"/> <source>Remote folder %1 created successfully.</source> <translation>Vzdálená složka %1 byla úspěšně vytvořena.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="316"/> <source>The remote folder %1 already exists. Connecting it for syncing.</source> <translation>Vzdálená složka %1 již existuje. Spojuji ji pro synchronizaci.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="318"/> <location filename="../src/gui/owncloudsetupwizard.cpp" line="320"/> <source>The folder creation resulted in HTTP error code %1</source> <translation>Vytvoření složky selhalo HTTP chybou %1</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="322"/> <source>The remote folder creation failed because the provided credentials are wrong!&lt;br/&gt;Please go back and check your credentials.&lt;/p&gt;</source> <translation>Vytvoření vzdálené složky selhalo, pravděpodobně z důvodu neplatných přihlašovacích údajů.&lt;br/&gt;Vraťte se, prosím, zpět a zkontrolujte je.&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="325"/> <source>&lt;p&gt;&lt;font color=&quot;red&quot;&gt;Remote folder creation failed probably because the provided credentials are wrong.&lt;/font&gt;&lt;br/&gt;Please go back and check your credentials.&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;font color=&quot;red&quot;&gt;Vytvoření vzdálené složky selhalo, pravděpodobně z důvodu neplatných přihlašovacích údajů.&lt;/font&gt;&lt;br/&gt;Vraťte se, prosím, zpět a zkontrolujte je.&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="330"/> <location filename="../src/gui/owncloudsetupwizard.cpp" line="331"/> <source>Remote folder %1 creation failed with error &lt;tt&gt;%2&lt;/tt&gt;.</source> <translation>Vytváření vzdálené složky %1 selhalo s chybou &lt;tt&gt;%2&lt;/tt&gt;.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="347"/> <source>A sync connection from %1 to remote directory %2 was set up.</source> <translation>Bylo nastaveno synchronizované spojení z %1 do vzdáleného adresáře %2.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="352"/> <source>Successfully connected to %1!</source> <translation>Úspěšně spojeno s %1.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="359"/> <source>Connection to %1 could not be established. Please check again.</source> <translation>Spojení s %1 nelze navázat. Prosím zkuste to znovu.</translation> </message> <message> <location filename="../src/gui/owncloudsetupwizard.cpp" line="373"/> <source>Can&apos;t remove and back up the folder because the folder or a file in it is open in another program. Please close the folder or file and hit retry or cancel the setup.</source> <translation>Nelze odstranit a zazálohovat adresář, protože adresář nebo soubor v něm je otevřen v jiném programu. Prosím zavřete adresář nebo soubor a zkuste znovu nebo zrušte akci.</translation> </message> </context> <context> <name>Mirall::OwncloudWizard</name> <message> <location filename="../src/gui/wizard/owncloudwizard.cpp" line="74"/> <source>%1 Connection Wizard</source> <translation>%1 Průvodce spojením</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizard.cpp" line="83"/> <source>Skip folders configuration</source> <translation>Přeskočit konfiguraci adresářů</translation> </message> </context> <context> <name>Mirall::OwncloudWizardResultPage</name> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.cpp" line="42"/> <source>Open Local Folder</source> <translation>Otevřít místní složku</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.cpp" line="38"/> <source>Everything set up!</source> <translation>Všechno je nastaveno!</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.cpp" line="50"/> <source>Open %1 in Browser</source> <translation type="unfinished"/> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.cpp" line="77"/> <source>Your entire account is synced to the local folder &lt;i&gt;%1&lt;/i&gt;</source> <translation>Celý váš účet je synchronizován do místní složky &lt;i&gt;%1&lt;/i&gt;</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.cpp" line="80"/> <source>%1 folder &lt;i&gt;%1&lt;/i&gt; is synced to local folder &lt;i&gt;%2&lt;/i&gt;</source> <translation>Složka %1 &lt;i&gt;%1&lt;/i&gt; je synchronizována do místní složky &lt;i&gt;%2&lt;/i&gt;</translation> </message> </context> <context> <name>Mirall::PUTFileJob</name> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="91"/> <source>Connection Timeout</source> <translation>Spojení vypršelo</translation> </message> </context> <context> <name>Mirall::PropagateDownloadFileLegacy</name> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="357"/> <source>Sync was aborted by user.</source> <translation>Synchronizace zrušena uživatelem.</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="410"/> <source>No E-Tag received from server, check Proxy/Gateway</source> <translation>Ze serveru nebyl obdržen E-Tag, zkontrolujte proxy/bránu</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="416"/> <source>We received a different E-Tag for resuming. Retrying next time.</source> <translation>Obdrželi jsme jiný E-Tag pro pokračování. Zkusím znovu příště.</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="438"/> <source>Server returned wrong content-range</source> <translation>Server odpověděl chybným rozsahem obsahu</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="489"/> <source>File %1 can not be downloaded because of a local file name clash!</source> <translation>Soubor %1 nemohl být stažen z důvodu kolize názvu se souborem v místním systému.</translation> </message> </context> <context> <name>Mirall::PropagateDownloadFileQNAM</name> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="559"/> <source>File %1 can not be downloaded because of a local file name clash!</source> <translation>Soubor %1 nemohl být stažen z důvodu kolize názvu se souborem v místním systému.</translation> </message> </context> <context> <name>Mirall::PropagateItemJob</name> <message> <location filename="../src/libsync/owncloudpropagator.cpp" line="51"/> <source>; Restoration Failed: </source> <translation>; Obnovení selhalo:</translation> </message> <message> <location filename="../src/libsync/owncloudpropagator.cpp" line="61"/> <source>Operation was canceled by user interaction.</source> <translation>Operace byla ukončena na základě vstupu uživatele</translation> </message> <message> <location filename="../src/libsync/owncloudpropagator.cpp" line="178"/> <source>A file or directory was removed from a read only share, but restoring failed: %1</source> <translation>Soubor nebo adresář by odebrán ze sdílení pouze pro čtení, ale jeho obnovení selhalo: %1</translation> </message> </context> <context> <name>Mirall::PropagateLocalMkdir</name> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="113"/> <source>Attention, possible case sensitivity clash with %1</source> <translation>Pozor, možná kolize z důvodu velikosti písmen s %1</translation> </message> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="118"/> <source>could not create directory %1</source> <translation>nepodařilo se vytvořit adresář %1</translation> </message> </context> <context> <name>Mirall::PropagateLocalRemove</name> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="80"/> <source>Could not remove %1 because of a local file name clash</source> <translation>%1 nebylo možno odstranit z důvodu kolize názvu se souborem v místním systému.</translation> </message> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="87"/> <source>Could not remove directory %1</source> <translation>Nepodařilo se odstranit adresář %1</translation> </message> </context> <context> <name>Mirall::PropagateLocalRename</name> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="253"/> <source>File %1 can not be renamed to %2 because of a local file name clash</source> <translation>Soubor %1 nemohl být přejmenován na %2 z důvodu kolize názvu se souborem v místním systému.</translation> </message> </context> <context> <name>Mirall::PropagateRemoteRemove</name> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="138"/> <source>The file has been removed from a read only share. It was restored.</source> <translation>Soubor byl odebrán ze sdílení pouze pro čtení. Soubor byl obnoven.</translation> </message> </context> <context> <name>Mirall::PropagateRemoteRename</name> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="290"/> <source>This folder must not be renamed. It is renamed back to its original name.</source> <translation>Tato složka nemůže být přejmenována. Byl jí vrácen původní název.</translation> </message> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="292"/> <source>This folder must not be renamed. Please name it back to Shared.</source> <translation>Tato složka nemůže být přejmenována. Přejmenujte jí prosím zpět na Shared.</translation> </message> <message> <location filename="../src/libsync/propagatorjobs.cpp" line="307"/> <source>The file was renamed but is part of a read only share. The original file was restored.</source> <translation>Soubor byl přejmenován, ale je součástí sdílení pouze pro čtení. Původní soubor byl obnoven.</translation> </message> </context> <context> <name>Mirall::PropagateUploadFileLegacy</name> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="165"/> <location filename="../src/libsync/propagator_legacy.cpp" line="224"/> <source>Local file changed during sync, syncing once it arrived completely</source> <translation>Místní soubor byl změněn během synchronizace, bude sesynchronizován, jakmile bude kompletní</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="168"/> <source>Sync was aborted by user.</source> <translation>Synchronizace zrušena uživatelem.</translation> </message> <message> <location filename="../src/libsync/propagator_legacy.cpp" line="174"/> <source>The file was edited locally but is part of a read only share. It is restored and your edit is in the conflict file.</source> <translation>Soubor zde byl editován, ale je součástí sdílení pouze pro čtení. Původní soubor byl obnoven a editovaná verze je uložena v konfliktním souboru.</translation> </message> </context> <context> <name>Mirall::PropagateUploadFileQNAM</name> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="283"/> <source>The file was edited locally but is part of a read only share. It is restored and your edit is in the conflict file.</source> <translation>Soubor zde byl editován, ale je součástí sdílení pouze pro čtení. Původní soubor byl obnoven a editovaná verze je uložena v konfliktním souboru.</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="313"/> <source>The local file was removed during sync.</source> <translation>Místní soubor byl odstraněn během synchronizace.</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="320"/> <source>Local file changed during sync.</source> <translation>Místní soubor byl změněn během synchronizace.</translation> </message> <message> <location filename="../src/libsync/propagator_qnam.cpp" line="330"/> <source>The server did not acknowledge the last chunk. (No e-tag were present)</source> <translation>Server nepotvrdil poslední část dat. (Nebyl nalezen e-tag)</translation> </message> </context> <context> <name>Mirall::ProtocolWidget</name> <message> <location filename="../src/gui/protocolwidget.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/protocolwidget.ui" line="20"/> <source>Sync Activity</source> <translation>Aktivita synchronizace</translation> </message> <message> <location filename="../src/gui/protocolwidget.ui" line="49"/> <source>3</source> <translation>3</translation> </message> <message> <location filename="../src/gui/protocolwidget.ui" line="54"/> <source>4</source> <translation>4</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="48"/> <source>Time</source> <translation>Čas</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="49"/> <source>File</source> <translation>Soubor</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="50"/> <source>Folder</source> <translation>Složka</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="51"/> <source>Action</source> <translation>Akce</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="52"/> <source>Size</source> <translation>Velikost</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="66"/> <source>Retry Sync</source> <translation>Znovu synchronizovat</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="70"/> <source>Copy</source> <translation>Kopie</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="71"/> <source>Copy the activity list to the clipboard.</source> <translation>Kopírovat záznam aktivity do schránky.</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="116"/> <source>Copied to clipboard</source> <translation>Zkopírováno do schránky</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="116"/> <source>The sync status has been copied to the clipboard.</source> <translation>Stav synchronizace byl zkopírován do schránky.</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="238"/> <source>Currently no files are ignored because of previous errors.</source> <translation>Nyní nejsou v seznamu ignorovaných žádné soubory kvůli předchozím chybám.</translation> </message> <message> <location filename="../src/gui/protocolwidget.cpp" line="240"/> <source>%1 files are ignored because of previous errors. Try to sync these again.</source> <translation>%1 souborů je na seznamu ignorovaných kvůli předchozím chybovým stavům. Zkuste provést novou synchronizaci. </translation> </message> </context> <context> <name>Mirall::SelectiveSyncDialog</name> <message> <location filename="../src/gui/selectivesyncdialog.cpp" line="270"/> <source>Only checked folders will sync to this computer</source> <translation>Pouze označené adresáře se budou synchronizovat na tento počitač.</translation> </message> </context> <context> <name>Mirall::SettingsDialog</name> <message> <location filename="../src/gui/settingsdialog.ui" line="14"/> <source>Settings</source> <translation>Nastavení</translation> </message> <message> <location filename="../src/gui/settingsdialog.cpp" line="51"/> <source>%1</source> <translation>%1</translation> </message> <message> <location filename="../src/gui/settingsdialog.cpp" line="57"/> <source>Activity</source> <translation>Aktivita</translation> </message> <message> <location filename="../src/gui/settingsdialog.cpp" line="64"/> <source>General</source> <translation>Hlavní</translation> </message> <message> <location filename="../src/gui/settingsdialog.cpp" line="71"/> <source>Network</source> <translation>Síť</translation> </message> <message> <location filename="../src/gui/settingsdialog.cpp" line="54"/> <source>Account</source> <translation>Účet</translation> </message> </context> <context> <name>Mirall::SettingsDialogMac</name> <message> <location filename="../src/gui/settingsdialogmac.cpp" line="40"/> <source>%1</source> <translation>%1</translation> </message> <message> <location filename="../src/gui/settingsdialogmac.cpp" line="44"/> <source>Account</source> <translation>Účet</translation> </message> <message> <location filename="../src/gui/settingsdialogmac.cpp" line="48"/> <source>Activity</source> <translation>Aktivita</translation> </message> <message> <location filename="../src/gui/settingsdialogmac.cpp" line="52"/> <source>General</source> <translation>Hlavní</translation> </message> <message> <location filename="../src/gui/settingsdialogmac.cpp" line="56"/> <source>Network</source> <translation>Síť</translation> </message> </context> <context> <name>Mirall::ShibbolethCredentials</name> <message> <location filename="../src/libsync/creds/shibbolethcredentials.cpp" line="285"/> <source>Login Error</source> <translation>Chyba přihlášení</translation> </message> <message> <location filename="../src/libsync/creds/shibbolethcredentials.cpp" line="285"/> <source>You must sign in as user %1</source> <translation>Musíte se přihlásit jako uživatel %1</translation> </message> </context> <context> <name>Mirall::ShibbolethWebView</name> <message> <location filename="../src/libsync/creds/shibboleth/shibbolethwebview.cpp" line="55"/> <source>%1 - Authenticate</source> <translation>%1 - ověření</translation> </message> <message> <location filename="../src/libsync/creds/shibboleth/shibbolethwebview.cpp" line="61"/> <source>Reauthentication required</source> <translation>Je vyžadováno opětovné ověření.</translation> </message> <message> <location filename="../src/libsync/creds/shibboleth/shibbolethwebview.cpp" line="61"/> <source>Your session has expired. You need to re-login to continue to use the client.</source> <translation>Vaše sezení vypršelo. Chcete-li pokračovat v práci musíte se znovu přihlásit.</translation> </message> <message> <location filename="../src/libsync/creds/shibboleth/shibbolethwebview.cpp" line="108"/> <source>%1 - %2</source> <translation>%1 - %2</translation> </message> </context> <context> <name>Mirall::SslButton</name> <message> <location filename="../src/gui/sslbutton.cpp" line="96"/> <source>&lt;h3&gt;Certificate Details&lt;/h3&gt;</source> <translation>&lt;h3&gt;Detaily certifikátu&lt;/h3&gt;</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="99"/> <source>Common Name (CN):</source> <translation>Běžný název (CN):</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="100"/> <source>Subject Alternative Names:</source> <translation>Alternativní jména subjektu:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="102"/> <source>Organization (O):</source> <translation>Organizace (O):</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="103"/> <source>Organizational Unit (OU):</source> <translation>Organizační jednotka (OU):</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="104"/> <source>State/Province:</source> <translation>Stát/provincie:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="105"/> <source>Country:</source> <translation>Země:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="106"/> <source>Serial:</source> <translation>Sériové číslo:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="109"/> <source>&lt;h3&gt;Issuer&lt;/h3&gt;</source> <translation>&lt;h3&gt;Vydavatel&lt;/h3&gt;</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="112"/> <source>Issuer:</source> <translation>Vydavatel:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="113"/> <source>Issued on:</source> <translation>Vydáno:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="114"/> <source>Expires on:</source> <translation>Platný do:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="117"/> <source>&lt;h3&gt;Fingerprints&lt;/h3&gt;</source> <translation>&lt;h3&gt;Otisky&lt;/h3&gt;</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="121"/> <source>MD 5:</source> <translation>MD5:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="123"/> <source>SHA-256:</source> <translation>SHA-256:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="125"/> <source>SHA-1:</source> <translation>SHA-1:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="129"/> <source>&lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; This certificate was manually approved&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;b&gt;Poznámka:&lt;/b&gt; Tento certifikát byl schválen ručně&lt;/p&gt;</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="149"/> <source>%1 (self-signed)</source> <translation>%1 (podepsaný sám sebou)</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="151"/> <source>%1</source> <translation>%1</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="187"/> <source>This connection is encrypted using %1 bit %2. </source> <translation>Toto spojení je šifrováno pomocí %1 bitové šifry %2 </translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="190"/> <source>Certificate information:</source> <translation>Informace o certifikátu:</translation> </message> <message> <location filename="../src/gui/sslbutton.cpp" line="219"/> <source>This connection is NOT secure as it is not encrypted. </source> <translation>Toto spojení NENÍ bezpečné, protože není šifrované. </translation> </message> </context> <context> <name>Mirall::SslErrorDialog</name> <message> <location filename="../src/gui/sslerrordialog.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/sslerrordialog.ui" line="25"/> <source>Trust this certificate anyway</source> <translation>Přesto certifikátu důvěřovat</translation> </message> <message> <location filename="../src/gui/sslerrordialog.ui" line="44"/> <location filename="../src/gui/sslerrordialog.cpp" line="65"/> <source>SSL Connection</source> <translation>SSL připojení</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="134"/> <source>Warnings about current SSL Connection:</source> <translation>Varování v aktuálním SSL spojení:</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="170"/> <source>with Certificate %1</source> <translation>s certifikátem %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="178"/> <location filename="../src/gui/sslerrordialog.cpp" line="179"/> <location filename="../src/gui/sslerrordialog.cpp" line="180"/> <source>&amp;lt;not specified&amp;gt;</source> <translation>&amp;lt;nespecifikováno&amp;gt;</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="181"/> <location filename="../src/gui/sslerrordialog.cpp" line="201"/> <source>Organization: %1</source> <translation>Organizace: %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="182"/> <location filename="../src/gui/sslerrordialog.cpp" line="202"/> <source>Unit: %1</source> <translation>Jednotka: %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="183"/> <location filename="../src/gui/sslerrordialog.cpp" line="203"/> <source>Country: %1</source> <translation>Země: %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="190"/> <source>Fingerprint (MD5): &lt;tt&gt;%1&lt;/tt&gt;</source> <translation>Otisk (MD5): &lt;tt&gt;%1&lt;/tt&gt;</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="191"/> <source>Fingerprint (SHA1): &lt;tt&gt;%1&lt;/tt&gt;</source> <translation>Otisk (SHA1): &lt;tt&gt;%1&lt;/tt&gt;</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="193"/> <source>Effective Date: %1</source> <translation>Datum účinnosti: %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="194"/> <source>Expiration Date: %1</source> <translation>Datum vypršení: %1</translation> </message> <message> <location filename="../src/gui/sslerrordialog.cpp" line="198"/> <source>Issuer: %1</source> <translation>Vydavatel: %1</translation> </message> </context> <context> <name>Mirall::SyncEngine</name> <message> <location filename="../src/libsync/syncengine.cpp" line="85"/> <source>Success.</source> <translation>Úspěch.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="88"/> <source>CSync failed to create a lock file.</source> <translation>CSync nemůže vytvořit soubor zámku.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="91"/> <source>CSync failed to load or create the journal file. Make sure you have read and write permissions in the local sync directory.</source> <translation>CSync se nepodařilo načíst či vytvořit soubor žurnálu. Ujistěte se, že máte oprávnění pro čtení a zápis v místní synchronizované složce.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="95"/> <source>CSync failed to write the journal file.</source> <translation>CSync se nepodařilo zapsat do souboru žurnálu.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="98"/> <source>&lt;p&gt;The %1 plugin for csync could not be loaded.&lt;br/&gt;Please verify the installation!&lt;/p&gt;</source> <translation>&lt;p&gt;Plugin %1 pro csync nelze načíst.&lt;br/&gt;Zkontrolujte prosím instalaci!&lt;/p&gt;</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="101"/> <source>The system time on this client is different than the system time on the server. Please use a time synchronization service (NTP) on the server and client machines so that the times remain the same.</source> <translation>Systémový čas na klientovi je rozdílný od systémového času serveru. Použijte, prosím, službu synchronizace času (NTP) na serveru i klientovi, aby byl čas na obou strojích stejný.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="106"/> <source>CSync could not detect the filesystem type.</source> <translation>CSync nemohl detekovat typ souborového systému.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="109"/> <source>CSync got an error while processing internal trees.</source> <translation>CSync obdrželo chybu při zpracování vnitřních struktur.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="112"/> <source>CSync failed to reserve memory.</source> <translation>CSync se nezdařilo rezervovat paměť.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="115"/> <source>CSync fatal parameter error.</source> <translation>CSync: kritická chyba parametrů.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="118"/> <source>CSync processing step update failed.</source> <translation>CSync se nezdařilo zpracovat krok aktualizace.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="121"/> <source>CSync processing step reconcile failed.</source> <translation>CSync se nezdařilo zpracovat krok sladění.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="124"/> <source>CSync processing step propagate failed.</source> <translation>CSync se nezdařilo zpracovat krok propagace.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="127"/> <source>&lt;p&gt;The target directory does not exist.&lt;/p&gt;&lt;p&gt;Please check the sync setup.&lt;/p&gt;</source> <translation>&lt;p&gt;Cílový adresář neexistuje.&lt;/p&gt;&lt;p&gt;Zkontrolujte, prosím, nastavení synchronizace.&lt;/p&gt;</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="131"/> <source>A remote file can not be written. Please check the remote access.</source> <translation>Vzdálený soubor nelze zapsat. Ověřte prosím vzdálený přístup.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="135"/> <source>The local filesystem can not be written. Please check permissions.</source> <translation>Do místního souborového systému nelze zapisovat. Ověřte, prosím, přístupová práva.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="138"/> <source>CSync failed to connect through a proxy.</source> <translation>CSync se nezdařilo připojit skrze proxy.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="141"/> <source>CSync could not authenticate at the proxy.</source> <translation>CSync se nemohlo přihlásit k proxy.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="144"/> <source>CSync failed to lookup proxy or server.</source> <translation>CSync se nezdařilo najít proxy server nebo cílový server.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="147"/> <source>CSync failed to authenticate at the %1 server.</source> <translation>CSync se nezdařilo přihlásit k serveru %1.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="150"/> <source>CSync failed to connect to the network.</source> <translation>CSync se nezdařilo připojit k síti.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="153"/> <source>A network connection timeout happened.</source> <translation>Došlo k vypršení časového limitu síťového spojení.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="156"/> <source>A HTTP transmission error happened.</source> <translation>Nastala chyba HTTP přenosu.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="159"/> <source>CSync failed due to not handled permission deniend.</source> <translation>CSync selhalo z důvodu nezpracovaného odmítnutí práv.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="162"/> <source>CSync failed to access </source> <translation>CSync se nezdařil přístup</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="165"/> <source>CSync tried to create a directory that already exists.</source> <translation>CSync se pokusilo vytvořit adresář, který již existuje.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="168"/> <location filename="../src/libsync/syncengine.cpp" line="171"/> <source>CSync: No space on %1 server available.</source> <translation>CSync: Nedostatek volného místa na serveru %1.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="174"/> <source>CSync unspecified error.</source> <translation>Nespecifikovaná chyba CSync.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="177"/> <source>Aborted by the user</source> <translation>Zrušeno uživatelem</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="181"/> <source>An internal error number %1 happened.</source> <translation>Nastala vnitřní chyba číslo %1.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="240"/> <source>The item is not synced because of previous errors: %1</source> <translation>Položka nebyla synchronizována kvůli předchozí chybě: %1</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="303"/> <source>Symbolic links are not supported in syncing.</source> <translation>Symbolické odkazy nejsou při synchronizaci podporovány.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="306"/> <source>File is listed on the ignore list.</source> <translation>Soubor se nachází na seznamu ignorovaných.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="309"/> <source>File contains invalid characters that can not be synced cross platform.</source> <translation>Soubor obsahuje alespoň jeden neplatný znak, který narušuje synchronizaci v prostředí více platforem.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="485"/> <source>Unable to initialize a sync journal.</source> <translation>Nemohu inicializovat synchronizační žurnál.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="597"/> <source>Cannot open the sync journal</source> <translation>Nelze otevřít synchronizační žurnál</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="779"/> <source>Not allowed because you don&apos;t have permission to add sub-directories in that directory</source> <translation>Není povoleno, protože nemáte oprávnění vytvářet podadresáře v tomto adresáři.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="786"/> <source>Not allowed because you don&apos;t have permission to add parent directory</source> <translation>Není povoleno, protože nemáte oprávnění vytvořit rodičovský adresář.</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="793"/> <source>Not allowed because you don&apos;t have permission to add files in that directory</source> <translation>Není povoleno, protože nemáte oprávnění přidávat soubory do tohoto adresáře</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="813"/> <source>Not allowed to upload this file because it is read-only on the server, restoring</source> <translation>Není povoleno nahrát tento soubor, protože je na serveru uložen pouze pro čtení, obnovuji</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="829"/> <location filename="../src/libsync/syncengine.cpp" line="850"/> <source>Not allowed to remove, restoring</source> <translation>Odstranění není povoleno, obnovuji</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="900"/> <source>Move not allowed, item restored</source> <translation>Přesun není povolen, položka obnovena</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="909"/> <source>Move not allowed because %1 is read-only</source> <translation>Přesun není povolen, protože %1 je pouze pro čtení</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="910"/> <source>the destination</source> <translation>cílové umístění</translation> </message> <message> <location filename="../src/libsync/syncengine.cpp" line="910"/> <source>the source</source> <translation>zdroj</translation> </message> </context> <context> <name>Mirall::Systray</name> <message> <location filename="../src/gui/systray.cpp" line="49"/> <source>%1: %2</source> <translation>%1: %2</translation> </message> </context> <context> <name>Mirall::Theme</name> <message> <location filename="../src/libsync/theme.cpp" line="233"/> <source>&lt;p&gt;Version %1 For more information please visit &lt;a href=&apos;%2&apos;&gt;%3&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Copyright ownCloud, Inc.&lt;/p&gt;&lt;p&gt;Distributed by %4 and licensed under the GNU General Public License (GPL) Version 2.0.&lt;br/&gt;%5 and the %5 logo are registered trademarks of %4 in the United States, other countries, or both.&lt;/p&gt;</source> <translation>&lt;p&gt;Verze %1. Pro více informací navštivte &lt;a href=&apos;%2&apos;&gt;%3&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;Copyright ownCloud, Inc.&lt;/p&gt;&lt;p&gt;Distribuováno %4 a licencováno pod GNU General Public License (GPL) Version 2.0.&lt;br/&gt;%5 a logo %5 jsou registrované obchodní známky %4 ve&lt;br&gt;Spojených státech, ostatních zemích nebo obojí.&lt;/p&gt;</translation> </message> </context> <context> <name>Mirall::ownCloudGui</name> <message> <location filename="../src/gui/owncloudgui.cpp" line="225"/> <source>Please sign in</source> <translation>Přihlašte se prosím</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="230"/> <source>Disconnected from server</source> <translation>Odpojen od serveru</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="262"/> <source>Folder %1: %2</source> <translation>Složka %1: %2</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="268"/> <source>No sync folders configured.</source> <translation>Nejsou nastaveny žádné synchronizované složky.</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="277"/> <source>There are no sync folders configured.</source> <translation>Nejsou nastaveny žádné složky pro synchronizaci.</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="303"/> <source>None.</source> <translation>Nic.</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="307"/> <source>Recent Changes</source> <translation>Poslední změny</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="324"/> <source>Open %1 folder</source> <translation>Otevřít složku %1</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="334"/> <source>Managed Folders:</source> <translation>Spravované složky:</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="337"/> <source>Open folder &apos;%1&apos;</source> <translation>Otevřít složku &apos;%1&apos;</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="409"/> <source>Open %1 in browser</source> <translation>Otevřít %1 v prohlížeči</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="411"/> <source>Calculating quota...</source> <translation>Počítám kvóty...</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="413"/> <source>Unknown status</source> <translation>Neznámý stav</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="415"/> <source>Settings...</source> <translation>Nastavení...</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="416"/> <source>Details...</source> <translation>Podrobnosti...</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="421"/> <source>Help</source> <translation>Nápověda</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="423"/> <source>Quit %1</source> <translation>Ukončit %1</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="426"/> <source>Sign in...</source> <translation>Přihlásit...</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="428"/> <source>Sign out</source> <translation>Odhlásit</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="436"/> <source>Quota n/a</source> <translation>Kvóta nedostupná</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="443"/> <source>%1% of %2 in use</source> <translation>%1% z %2 v používání</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="455"/> <source>No items synced recently</source> <translation>Žádné položky nebyly nedávno synchronizovány</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="467"/> <source>Discovering %1</source> <translation>Hledám %1</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="471"/> <source>Syncing %1 of %2 (%3 left)</source> <translation>Synchronizuji %1 ze %2 (zbývá %3)</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="476"/> <source>Syncing %1 (%2 left)</source> <translation>Synchronizuji %1 (zbývá %2)</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="496"/> <source>%1 (%2, %3)</source> <translation>%1 (%2, %3)</translation> </message> <message> <location filename="../src/gui/owncloudgui.cpp" line="524"/> <source>Up to date</source> <translation>Aktuální</translation> </message> </context> <context> <name>Mirall::ownCloudTheme</name> <message utf8="true"> <location filename="../src/libsync/owncloudtheme.cpp" line="48"/> <source>&lt;p&gt;Version %2. For more information visit &lt;a href=&quot;%3&quot;&gt;%4&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;small&gt;By Klaas Freitag, Daniel Molkentin, Jan-Christoph Borchardt, Olivier Goffart, Markus Götz and others.&lt;br/&gt;Based on Mirall by Duncan Mac-Vicar P.&lt;/small&gt;&lt;/p&gt;&lt;p&gt;Copyright ownCloud, Inc.&lt;/p&gt;&lt;p&gt;Licensed under the GNU Public License (GPL) Version 2.0&lt;br/&gt;ownCloud and the ownCloud Logo are registered trademarks of ownCloud, Inc. in the United States, other countries, or both&lt;/p&gt;</source> <translation>&lt;p&gt;Verze %2. Pro více informací navštivte &lt;a href=&quot;%3&quot;&gt;%4&lt;/a&gt;&lt;/p&gt;&lt;p&gt;&lt;small&gt;Klaas Freitag, Daniel Molkentin, Jan-Christoph Borchardt, Olivier Goffart, Markus Götz a další.&lt;br/&gt;Na základě kódu Mirall, Duncan Mac-Vicar P.&lt;/small&gt;&lt;/p&gt;&lt;p&gt;Copyright ownCloud, Inc.&lt;/p&gt;&lt;p&gt;Licencováno pod GNU General Public License (GPL) Version 2.0&lt;br/&gt;ownCloud a ownCloud logo jsou registrované obchodní známky ownCloud, Inc. ve Spojených státech, ostatních zemích nebo obojí&lt;/p&gt;</translation> </message> </context> <context> <name>OwncloudAdvancedSetupPage</name> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="20"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="32"/> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="78"/> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="162"/> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="265"/> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="288"/> <source>TextLabel</source> <translation>Textový štítek</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="88"/> <source>Server</source> <translation type="unfinished"/> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="103"/> <source>Sync everything from server</source> <translation type="unfinished"/> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="122"/> <source>Choose what to sync</source> <translation type="unfinished"/> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="178"/> <source>&amp;Local Folder</source> <translation>Místní s&amp;ložka</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="221"/> <source>&amp;Start a clean sync (Erases the local folder!)</source> <translation type="unfinished"/> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="256"/> <source>pbSelectLocalFolder</source> <translation>pbSelectLocalFolder</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="208"/> <source>&amp;Keep local data</source> <translation>&amp;Ponechat místní data</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="218"/> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;If this box is checked, existing content in the local directory will be erased to start a clean sync from the server.&lt;/p&gt;&lt;p&gt;Do not check this if the local content should be uploaded to the servers directory.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Pokud je zaškrtnuta tato volba, aktuální obsah v místní složce bude smazán a bude zahájena nová synchronizace ze serveru.&lt;/p&gt;&lt;p&gt;Nevolte tuto možnost pokud má být místní obsah nahrán do složky na serveru.&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</translation> </message> <message> <location filename="../src/gui/wizard/owncloudadvancedsetuppage.ui" line="272"/> <source>Status message</source> <translation>Stavová zpráva</translation> </message> </context> <context> <name>OwncloudHttpCredsPage</name> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="38"/> <source>&amp;Username</source> <translation>&amp;Uživatelské jméno</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="48"/> <source>&amp;Password</source> <translation>&amp;Heslo</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="58"/> <source>Error Label</source> <translation>Chybový popis</translation> </message> <message> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="109"/> <location filename="../src/gui/wizard/owncloudhttpcredspage.ui" line="122"/> <source>TextLabel</source> <translation>Textový štítek</translation> </message> </context> <context> <name>OwncloudSetupPage</name> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="14"/> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="20"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="20"/> <source>Server &amp;address:</source> <translation>&amp;Adresa serveru:</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="36"/> <location filename="../src/gui/owncloudsetuppage.ui" line="129"/> <location filename="../src/gui/owncloudsetuppage.ui" line="156"/> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="32"/> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="184"/> <source>TextLabel</source> <translation>Textový popisek</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="47"/> <source>Use &amp;secure connection</source> <translation>Použít za&amp;bezpečené spojení</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="60"/> <source>CheckBox</source> <translation>Zaškrtávací pole</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="75"/> <source>&amp;Username:</source> <translation>&amp;Uživatelské jméno:</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="85"/> <source>Enter the ownCloud username.</source> <translation>Zadejte uživatelské jméno ownCloud.</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="92"/> <source>&amp;Password:</source> <translation>&amp;Heslo:</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="102"/> <source>Enter the ownCloud password.</source> <translation>Zadejte heslo ownCloud.</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="117"/> <source>Do not allow the local storage of the password.</source> <translation>Nepovolit místní uložení hesla.</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="120"/> <source>&amp;Do not store password on local machine</source> <translation>Neuklá&amp;dat heslo na místním počítači</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="140"/> <source>https://</source> <translation>https://</translation> </message> <message> <location filename="../src/gui/owncloudsetuppage.ui" line="147"/> <source>Enter the url of the ownCloud you want to connect to (without http or https).</source> <translation>Zadejte URL ownCloud, ke které si přejete se připojit (bez http, či https).</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="83"/> <source>Server &amp;Address</source> <translation>&amp;Adresa serveru</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="99"/> <source>https://...</source> <translation>https://...</translation> </message> <message> <location filename="../src/gui/wizard/owncloudsetupnocredspage.ui" line="157"/> <source>Error Label</source> <translation>Popis chyby</translation> </message> </context> <context> <name>OwncloudWizardResultPage</name> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.ui" line="14"/> <source>Form</source> <translation>Formulář</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.ui" line="20"/> <source>TextLabel</source> <translation>Textový popisek</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.ui" line="163"/> <source>Your entire account is synced to the local folder </source> <translation>Celý váš účet je synchronizován do místní složky</translation> </message> <message> <location filename="../src/gui/wizard/owncloudwizardresultpage.ui" line="98"/> <location filename="../src/gui/wizard/owncloudwizardresultpage.ui" line="120"/> <source>PushButton</source> <translation>Tlačítko</translation> </message> </context> <context> <name>Utility</name> <message> <location filename="../src/libsync/utility.cpp" line="113"/> <source>%L1 TB</source> <translation>%L1 TB</translation> </message> <message> <location filename="../src/libsync/utility.cpp" line="116"/> <source>%L1 GB</source> <translation>%L1 GB</translation> </message> <message> <location filename="../src/libsync/utility.cpp" line="119"/> <source>%L1 MB</source> <translation>%L1 MB</translation> </message> <message> <location filename="../src/libsync/utility.cpp" line="122"/> <source>%L1 kB</source> <translation>%L1 kB</translation> </message> <message> <location filename="../src/libsync/utility.cpp" line="125"/> <source>%L1 B</source> <translation>%L1 B</translation> </message> </context> <context> <name>main.cpp</name> <message> <location filename="../src/gui/main.cpp" line="38"/> <source>System Tray not available</source> <translation>Systémová lišta není k dispozici</translation> </message> <message> <location filename="../src/gui/main.cpp" line="39"/> <source>%1 requires on a working system tray. If you are running XFCE, please follow &lt;a href=&quot;http://docs.xfce.org/xfce/xfce4-panel/systray&quot;&gt;these instructions&lt;/a&gt;. Otherwise, please install a system tray application such as &apos;trayer&apos; and try again.</source> <translation>%1 vyžaduje fungující systémovou lištu. Pokud používáte XFCE, řiďte se &lt;a href=&quot;http://docs.xfce.org/xfce/xfce4-panel/systray&quot;&gt;těmito instrukcemi&lt;/a&gt;. V ostatních případech prosím nainstalujte do svého systému aplikaci pro systémovou lištu, např. &apos;trayer&apos;, a zkuste to znovu.</translation> </message> </context> <context> <name>ownCloudTheme::about()</name> <message> <location filename="../src/libsync/theme.cpp" line="221"/> <source>&lt;p&gt;&lt;small&gt;Built from Git revision &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt; on %3, %4 using Qt %5.&lt;/small&gt;&lt;/p&gt;</source> <translation>&lt;p&gt;&lt;small&gt;Sestaveno z Git revize &lt;a href=&quot;%1&quot;&gt;%2&lt;/a&gt; na %3, %4 pomocí Qt %5.&lt;/small&gt;&lt;/p&gt;</translation> </message> </context> <context> <name>progress</name> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="32"/> <source>Downloaded</source> <translation>Staženo</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="34"/> <source>Uploaded</source> <translation>Odesláno</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="37"/> <source>Deleted</source> <translation>Smazáno</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="40"/> <source>Moved to %1</source> <translation>Přesunuto do %1</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="42"/> <source>Ignored</source> <translation>Ignorováno</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="44"/> <source>Filesystem access error</source> <translation>Chyba přístupu k souborovému systému</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="46"/> <source>Error</source> <translation>Chyba</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="49"/> <location filename="../src/libsync/progressdispatcher.cpp" line="52"/> <source>Unknown</source> <translation>Neznámý</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="62"/> <source>downloading</source> <translation>stahování</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="64"/> <source>uploading</source> <translation>odesílání</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="66"/> <source>deleting</source> <translation>mazání</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="69"/> <source>moving</source> <translation>přesouvání</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="71"/> <source>ignoring</source> <translation>ignoruji</translation> </message> <message> <location filename="../src/libsync/progressdispatcher.cpp" line="73"/> <location filename="../src/libsync/progressdispatcher.cpp" line="75"/> <source>error</source> <translation>chyba</translation> </message> </context> <context> <name>theme</name> <message> <location filename="../src/libsync/theme.cpp" line="51"/> <source>Status undefined</source> <translation>Nedefinovaný stav</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="54"/> <source>Waiting to start sync</source> <translation>Čekám na zahájení synchronizace</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="57"/> <source>Sync is running</source> <translation>Synchronizace běží</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="60"/> <source>Sync Success</source> <translation>Synchronizace úspěšná</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="63"/> <source>Sync Success, some files were ignored.</source> <translation>Synchronizace úspěšná, některé soubory byly ignorovány.</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="66"/> <source>Sync Error</source> <translation>Chyba synchronizace</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="69"/> <source>Setup Error</source> <translation>Chyba nastavení</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="72"/> <source>Preparing to sync</source> <translation>Připravuji na synchronizaci</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="75"/> <source>Aborting...</source> <translation>Ruším...</translation> </message> <message> <location filename="../src/libsync/theme.cpp" line="78"/> <source>Sync is paused</source> <translation>Synchronizace pozastavena</translation> </message> </context> </TS><|fim▁end|>
<message> <location filename="../src/gui/logbrowser.cpp" line="194"/> <source>Error</source> <translation>Chyba</translation>
<|file_name|>test_filtering.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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. from tests import unittest from twisted.internet import defer from mock import Mock from tests.utils import ( MockHttpResource, DeferredMockCallable, setup_test_homeserver ) from synapse.api.filtering import Filter from synapse.events import FrozenEvent user_localpart = "test_user" def MockEvent(**kwargs): if "event_id" not in kwargs: kwargs["event_id"] = "fake_event_id" if "type" not in kwargs: kwargs["type"] = "fake_type" return FrozenEvent(kwargs) class FilteringTestCase(unittest.TestCase): @defer.inlineCallbacks def setUp(self): self.mock_federation_resource = MockHttpResource() self.mock_http_client = Mock(spec=[]) self.mock_http_client.put_json = DeferredMockCallable() hs = yield setup_test_homeserver( handlers=None, http_client=self.mock_http_client, keyring=Mock(), ) self.filtering = hs.get_filtering() self.datastore = hs.get_datastore() def test_definition_types_works_with_literals(self): definition = { "types": ["m.room.message", "org.matrix.foo.bar"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!foo:bar" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_types_works_with_wildcards(self): definition = { "types": ["m.*", "org.matrix.foo.bar"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!foo:bar" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_types_works_with_unknowns(self): definition = { "types": ["m.room.message", "org.matrix.foo.bar"] } event = MockEvent( sender="@foo:bar", type="now.for.something.completely.different", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_types_works_with_literals(self): definition = { "not_types": ["m.room.message", "org.matrix.foo.bar"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_types_works_with_wildcards(self): definition = { "not_types": ["m.room.message", "org.matrix.*"] } event = MockEvent( sender="@foo:bar", type="org.matrix.custom.event", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_types_works_with_unknowns(self): definition = { "not_types": ["m.*", "org.*"] } event = MockEvent( sender="@foo:bar", type="com.nom.nom.nom", room_id="!foo:bar" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_not_types_takes_priority_over_types(self): definition = { "not_types": ["m.*", "org.*"], "types": ["m.room.message", "m.room.topic"] } event = MockEvent( sender="@foo:bar", type="m.room.topic", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_senders_works_with_literals(self): definition = { "senders": ["@flibble:wibble"] } event = MockEvent( sender="@flibble:wibble", type="com.nom.nom.nom", room_id="!foo:bar" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_senders_works_with_unknowns(self): definition = { "senders": ["@flibble:wibble"] } event = MockEvent( sender="@challenger:appears", type="com.nom.nom.nom", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_senders_works_with_literals(self): definition = { "not_senders": ["@flibble:wibble"] } event = MockEvent( sender="@flibble:wibble", type="com.nom.nom.nom", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_senders_works_with_unknowns(self): definition = { "not_senders": ["@flibble:wibble"] } event = MockEvent( sender="@challenger:appears", type="com.nom.nom.nom", room_id="!foo:bar" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_not_senders_takes_priority_over_senders(self): definition = { "not_senders": ["@misspiggy:muppets"], "senders": ["@kermit:muppets", "@misspiggy:muppets"] } event = MockEvent( sender="@misspiggy:muppets", type="m.room.topic", room_id="!foo:bar" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_rooms_works_with_literals(self): definition = { "rooms": ["!secretbase:unknown"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!secretbase:unknown" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_rooms_works_with_unknowns(self): definition = { "rooms": ["!secretbase:unknown"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!anothersecretbase:unknown" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_rooms_works_with_literals(self): definition = { "not_rooms": ["!anothersecretbase:unknown"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!anothersecretbase:unknown" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_not_rooms_works_with_unknowns(self): definition = { "not_rooms": ["!secretbase:unknown"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!anothersecretbase:unknown" ) self.assertTrue( Filter(definition).check(event) ) def test_definition_not_rooms_takes_priority_over_rooms(self): definition = { "not_rooms": ["!secretbase:unknown"], "rooms": ["!secretbase:unknown"] } event = MockEvent( sender="@foo:bar", type="m.room.message", room_id="!secretbase:unknown" ) self.assertFalse( Filter(definition).check(event) ) def test_definition_combined_event(self): definition = { "not_senders": ["@misspiggy:muppets"], "senders": ["@kermit:muppets"], "rooms": ["!stage:unknown"], "not_rooms": ["!piggyshouse:muppets"], "types": ["m.room.message", "muppets.kermit.*"], "not_types": ["muppets.misspiggy.*"] } event = MockEvent( sender="@kermit:muppets", # yup type="m.room.message", # yup room_id="!stage:unknown" # yup ) self.assertTrue( Filter(definition).check(event) ) def test_definition_combined_event_bad_sender(self): definition = { "not_senders": ["@misspiggy:muppets"], "senders": ["@kermit:muppets"], "rooms": ["!stage:unknown"], "not_rooms": ["!piggyshouse:muppets"], "types": ["m.room.message", "muppets.kermit.*"], "not_types": ["muppets.misspiggy.*"] } event = MockEvent( sender="@misspiggy:muppets", # nope type="m.room.message", # yup room_id="!stage:unknown" # yup ) self.assertFalse( Filter(definition).check(event) ) def test_definition_combined_event_bad_room(self): definition = { "not_senders": ["@misspiggy:muppets"], "senders": ["@kermit:muppets"], "rooms": ["!stage:unknown"], "not_rooms": ["!piggyshouse:muppets"], "types": ["m.room.message", "muppets.kermit.*"], "not_types": ["muppets.misspiggy.*"] } event = MockEvent( sender="@kermit:muppets", # yup type="m.room.message", # yup room_id="!piggyshouse:muppets" # nope ) self.assertFalse( Filter(definition).check(event) ) def test_definition_combined_event_bad_type(self): definition = { "not_senders": ["@misspiggy:muppets"], "senders": ["@kermit:muppets"], "rooms": ["!stage:unknown"], "not_rooms": ["!piggyshouse:muppets"], "types": ["m.room.message", "muppets.kermit.*"], "not_types": ["muppets.misspiggy.*"] } event = MockEvent( sender="@kermit:muppets", # yup type="muppets.misspiggy.kisses", # nope room_id="!stage:unknown" # yup ) self.assertFalse( Filter(definition).check(event) ) @defer.inlineCallbacks def test_filter_presence_match(self): user_filter_json = { "presence": { "types": ["m.*"] } } filter_id = yield self.datastore.add_user_filter( user_localpart=user_localpart, user_filter=user_filter_json, ) event = MockEvent( sender="@foo:bar", type="m.profile", ) events = [event] user_filter = yield self.filtering.get_user_filter( user_localpart=user_localpart, filter_id=filter_id, ) results = user_filter.filter_presence(events=events) self.assertEquals(events, results) @defer.inlineCallbacks def test_filter_presence_no_match(self): user_filter_json = { "presence": { "types": ["m.*"] } } filter_id = yield self.datastore.add_user_filter( user_localpart=user_localpart + "2", user_filter=user_filter_json, ) event = MockEvent( event_id="$asdasd:localhost", sender="@foo:bar", type="custom.avatar.3d.crazy", ) events = [event] user_filter = yield self.filtering.get_user_filter( user_localpart=user_localpart + "2", filter_id=filter_id, ) results = user_filter.filter_presence(events=events) self.assertEquals([], results) @defer.inlineCallbacks def test_filter_room_state_match(self): user_filter_json = { "room": { "state": { "types": ["m.*"] } } } filter_id = yield self.datastore.add_user_filter( user_localpart=user_localpart, user_filter=user_filter_json, ) event = MockEvent( sender="@foo:bar", type="m.room.topic", room_id="!foo:bar" ) events = [event] user_filter = yield self.filtering.get_user_filter( user_localpart=user_localpart, filter_id=filter_id, ) results = user_filter.filter_room_state(events=events) self.assertEquals(events, results) @defer.inlineCallbacks def test_filter_room_state_no_match(self): user_filter_json = { "room": { "state": { "types": ["m.*"] } } } filter_id = yield self.datastore.add_user_filter( user_localpart=user_localpart, user_filter=user_filter_json, ) event = MockEvent( sender="@foo:bar", type="org.matrix.custom.event", room_id="!foo:bar" ) events = [event] user_filter = yield self.filtering.get_user_filter( user_localpart=user_localpart, filter_id=filter_id, ) results = user_filter.filter_room_state(events) self.assertEquals([], results) def test_filter_rooms(self): definition = { "rooms": ["!allowed:example.com", "!excluded:example.com"], "not_rooms": ["!excluded:example.com"], } room_ids = [ "!allowed:example.com", # Allowed because in rooms and not in not_rooms. "!excluded:example.com", # Disallowed because in not_rooms. "!not_included:example.com", # Disallowed because not in rooms. ] filtered_room_ids = list(Filter(definition).filter_rooms(room_ids)) self.assertEquals(filtered_room_ids, ["!allowed:example.com"]) @defer.inlineCallbacks def test_add_filter(self): user_filter_json = {<|fim▁hole|> } } } filter_id = yield self.filtering.add_user_filter( user_localpart=user_localpart, user_filter=user_filter_json, ) self.assertEquals(filter_id, 0) self.assertEquals(user_filter_json, ( yield self.datastore.get_user_filter( user_localpart=user_localpart, filter_id=0, ) )) @defer.inlineCallbacks def test_get_filter(self): user_filter_json = { "room": { "state": { "types": ["m.*"] } } } filter_id = yield self.datastore.add_user_filter( user_localpart=user_localpart, user_filter=user_filter_json, ) filter = yield self.filtering.get_user_filter( user_localpart=user_localpart, filter_id=filter_id, ) self.assertEquals(filter.get_filter_json(), user_filter_json) self.assertRegexpMatches(repr(filter), r"<FilterCollection \{.*\}>")<|fim▁end|>
"room": { "state": { "types": ["m.*"]
<|file_name|>ControlGame.ts<|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/. */ export interface ControlPoint { faction: string;<|fim▁hole|> x: number; y: number; }; class ControlGame { arthurianScore: number; controlPoints: ControlPoint[]; gameState: number; timeLeft: number; tuathaDeDanannScore: number; vikingScore: number; constructor(controlGame = <ControlGame>{}) { // Game State this.gameState = controlGame.gameState || 0; // Game Score this.arthurianScore = controlGame.arthurianScore || 0; this.tuathaDeDanannScore = controlGame.tuathaDeDanannScore || 0; this.vikingScore = controlGame.vikingScore || 0; // Time remaining this.timeLeft = controlGame.timeLeft || 0; // Control Points (if included) this.controlPoints = controlGame.controlPoints || <ControlPoint[]>[]; } static create() { let a = new ControlGame(); return a; } } export default ControlGame;<|fim▁end|>
id: string; size: string;
<|file_name|>sol-popmenu.js<|end_file_name|><|fim▁begin|>import {module, inject, createRootFactory} from '../mocks'; describe('solPopmenu directive', function () { let $compile; let $rootScope; let createRoot; let rootEl; beforeEach(module('karma.templates')); beforeEach(module('ui-kit')); beforeEach(inject((_$compile_, _$rootScope_) => { $compile = _$compile_; $rootScope = _$rootScope_; createRoot = createRootFactory($compile); let html = '<div><sol-popmenu icon="list">tranclusion</sol-popmenu></div>'; rootEl = createRoot(html, $rootScope); })); it('should replace the element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content'); expect(rootEl).not.toContainElement('sol-popmenu'); }); it('should transclude content inside a ".popmenu-popup .popmenu-content" element', () => { let menu = rootEl.find('.popmenu-popup .popmenu-content');<|fim▁hole|> expect(menu).toHaveText('tranclusion'); }); it('should add "fa fa-<icon>" class on toggler according to icon attribute', () => { let toggler = rootEl.find('.popmenu-toggler'); expect(toggler).toHaveClass('fa fa-list'); }); it('should toggle the "closed" class on .popmenu once the .popmenu-toggler clicked', () => { let menu = rootEl.find('.popmenu'); let toggler = rootEl.find('.popmenu-toggler'); expect(menu).not.toHaveClass('closed'); toggler.click(); toggler.click(); $rootScope.$digest(); expect(menu).toHaveClass('closed'); }); it('contains a .popmenu-toggler element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu-toggler'); }); it('contains a .popmenu element', () => { let html = '<div><sol-popmenu></sol-popmenu></div>'; let rootEl = createRoot(html, $rootScope); expect(rootEl).toContainElement('.popmenu'); }); });<|fim▁end|>
<|file_name|>CTFGameMods.java<|end_file_name|><|fim▁begin|><|fim▁hole|> import org.bukkit.plugin.java.JavaPlugin; public class CTFGameMods extends JavaPlugin { }<|fim▁end|>
package br.com.gamemods.tutorial.ctf;
<|file_name|>middleware.py<|end_file_name|><|fim▁begin|>from threading import local from django.contrib.sites.models import Site import os<|fim▁hole|> def get_current_request(): return getattr(_locals, 'request', None) def get_current_site(): request = get_current_request() host = request.get_host() try: return Site.objects.get(domain__iexact=host) except: return Site.objects.all()[0] class GlobalRequestMiddleware(object): def process_request(self, request): _locals.request = request<|fim▁end|>
_locals = local()
<|file_name|>SMB_Core.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # ============================================================================ # # SMB_Core.py # # Copyright: # Copyright (C) 2014 by Christopher R. Hertel # # $Id: SMB_Core.py; 2019-04-14 16:25:33 -0500; Christopher R. Hertel$ # # ---------------------------------------------------------------------------- # # # Description: # Carnaval Toolkit: Core components. # # ---------------------------------------------------------------------------- # # # License: # # 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 3.0 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, see <http://www.gnu.org/licenses/>. # # See Also: # The 0.README file included with the distribution. # # ---------------------------------------------------------------------------- # # This code was developed in participation with the # Protocol Freedom Information Foundation. # <www.protocolfreedom.org> # ---------------------------------------------------------------------------- # # # References: # [MS-CIFS] Microsoft Corporation, "Common Internet File System (CIFS) # Protocol Specification" # http://msdn.microsoft.com/en-us/library/ee442092.aspx # # [MS-SMB] Microsoft Corporation, "Server Message Block (SMB) Protocol # Specification" # http://msdn.microsoft.com/en-us/library/cc246231.aspx # # [MS-SMB2] Microsoft Corporation, "Server Message Block (SMB) Protocol # Versions 2 and 3" # http://msdn.microsoft.com/en-us/library/cc246482.aspx # # ============================================================================ # # """Carnaval Toolkit: Core components Classes, functions, and other objects used throughout this SMB protocol implementation. Fundamental stuff. """ # Imports -------------------------------------------------------------------- # # # time.time() - Get the current system time. # ErrorCodeExceptions - Provides the CodedError() class, upon which the # SMBerror class is built. # from time import time from common.ErrorCodeExceptions import CodedError # Classes -------------------------------------------------------------------- # # class SMBerror( CodedError ): """SMB2/3 exceptions. An exception class with an associated set of error codes, defined by numbers (starting at 1000). The error codes are specific to this exception class. Class Attributes: error_dict - A dictionary that maps error codes to descriptive names. This dictionary defines the set of valid SMBerror error codes. Error Codes: 1000 - Warning message (operation succeded with caveats). 1001 - SMB Syntax Error encountered. 1002 - SMB Semantic Error encountered. 1003 - SMB Protocol mismatch ([<FF>|<FE>|<FD>]+"SMB" not found). See Also: common.ErrorCodeExceptions.CodedError Doctest: >>> print SMBerror.errStr( 1002 ) SMB Semantic Error >>> a, b = SMBerror.errRange() >>> a < b True >>> SMBerror() Traceback (most recent call last): ... ValueError: Undefined error code: None. >>> print SMBerror( 1003, "Die Flipperwaldt gersput" ) 1003: SMB Protocol Mismatch; Die Flipperwaldt gersput. """ # This assignment is all that's needed to create the class: error_dict = { 1000 : "Warning", 1001 : "SMB Syntax Error", 1002 : "SMB Semantic Error", 1003 : "SMB Protocol Mismatch" } class SMB_FileTime( object ): """FILETIME format time value handling. FILETIME values are given in bozoseconds since the Windows Epoch. The Windows Epoch is UTC midnight on 1-Jan-1601, and a bozosecond is equal to 100 nanoseconds (or 1/10th of a microsecond, or 10^-7 seconds). There is no "official" prefix for 10^-7, so use of the term "bozosecond" is on your own recognizance. FILETIME values are 64-bit unsigned integers, supporting a date range from the Windows Epoch to 28-May-60056. """ # References: # Implementing CIFS: The Common Internet File System # Section 2.6.3.1 under "SystemTimeLow and SystemTimeHigh" # http://ubiqx.org/cifs/SMB.html#SMB.6.3.1 # [MS-DTYP;2.3.3] # Microsoft Corporation, "Windows Data Types", section 2.3.3 # https://msdn.microsoft.com/en-us/library/cc230324.aspx # Wikipedia: 1601 # https://en.wikipedia.org/wiki/1601 # Wikipedia: NTFS # https://en.wikipedia.org/wiki/NTFS # # Class Values: # _EPOCH_DELTA_SECS - The number of seconds between the Windows Epoch # and the Unix/POSIX/Linux/BSD/etc. Epoch. _EPOCH_DELTA_SECS = 11644473600 @classmethod def utcNow( cls ): """Return the current UTC time as a FILETIME value. Output: An unsigned long integer representing the current time in FILETIME format. Notes: Yeah...the few nanoseconds it will take to run this code means that by the time the result is actually returned it is already a bit stale. """ return( long( round( time(), 7 ) * 10000000 ) + cls._EPOCH_DELTA_SECS ) # Functions ------------------------------------------------------------------ # # def SMB_Pad8( msglen=0 ): """Return the number of padding octets needed for 8-octet alignment. Input: msglen - The length of the bytestream that may need to be padded. It is assumed that this bytestream starts on an 8-octet boundary (otherwise, the results are somewhat meaningless). Output: The number of octets required in order to pad to a multiple of 8 octets. This, of course, will be in the range 0..7. Doctest: >>> for i in [-9, -2, 0, 3, 8, 9]: ... print "%2d ==> %d" % (i, SMB_Pad8( i )) -9 ==> 1 -2 ==> 2 0 ==> 0 3 ==> 5 8 ==> 0 9 ==> 7 """<|fim▁hole|># ============================================================================ # # Sean sat despondently on the edge of the Wankel rotary engine, as the # two manicurists crafted a transistor radio using parts from a discarded # Velociraptor. # ============================================================================ #<|fim▁end|>
return( (8 - (msglen % 8)) & 0x7 ) # 9% code, 91% documentation.
<|file_name|>ContinuousOperations.java<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> * Copyright 2004,2005 The Apache Software Foundation. * * 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 org.wso2.carbon.registry.ws.client.test.security; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.ResourceImpl; import org.wso2.carbon.registry.core.utils.RegistryUtils; public class ContinuousOperations extends SecurityTestSetup { public ContinuousOperations(String text) { super(text); } public void testContinousDelete() throws Exception { int iterations = 100; for (int i = 0; i < iterations; i++) { Resource res1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R2 content"); res1.setContent(r1content); String path = "/con-delete/test/" + i + 1; registry.put(path, res1); Resource resource1 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource1.getContent()), RegistryUtils.decodeBytes((byte[]) res1.getContent())); registry.delete(path); boolean value = false; if (registry.resourceExists(path)) { value = true; } assertFalse("Resoruce not found at the path", value); res1.discard(); resource1.discard(); Thread.sleep(100); } } public void testContinuousUpdate() throws Exception { int iterations = 100; for (int i = 0; i < iterations; i++) { Resource res1 = registry.newResource(); byte[] r1content = RegistryUtils.encodeString("R2 content"); res1.setContent(r1content); String path = "/con-delete/test-update/" + i + 1; registry.put(path, res1); Resource resource1 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource1.getContent()), RegistryUtils.decodeBytes((byte[]) res1.getContent())); Resource resource = new ResourceImpl(); byte[] r1content1 = RegistryUtils.encodeString("R2 content updated"); resource.setContent(r1content1); resource.setProperty("abc", "abc"); registry.put(path, resource); Resource resource2 = registry.get(path); assertEquals("File content is not matching", RegistryUtils.decodeBytes((byte[]) resource.getContent()), RegistryUtils.decodeBytes((byte[]) resource2.getContent())); resource.discard(); res1.discard(); resource1.discard(); resource2.discard(); Thread.sleep(100); } } }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" mbed SDK Copyright (c) 2011-2017 ARM Limited 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. Title: GNU ARM Eclipse (http://gnuarmeclipse.github.io) exporter. Description: Creates a managed build project that can be imported by the GNU ARM Eclipse plug-ins. Author: Liviu Ionescu <[email protected]> """ import os import copy import tempfile import shutil import copy from subprocess import call, Popen, PIPE from os.path import splitext, basename, relpath, dirname, exists, join, dirname from random import randint from json import load from tools.export.exporters import Exporter from tools.options import list_profiles from tools.targets import TARGET_MAP from tools.utils import NotSupportedException from tools.build_api import prepare_toolchain # ============================================================================= class UID: """ Helper class, used to generate unique ids required by .cproject symbols. """ @property def id(self): return "%0.9u" % randint(0, 999999999) # Global UID generator instance. # Passed to the template engine, and referred as {{u.id}}. # Each invocation generates a new number. u = UID() # ============================================================================= class GNUARMEclipse(Exporter): NAME = 'GNU ARM Eclipse' TOOLCHAIN = 'GCC_ARM' # Indirectly support all GCC_ARM targets. TARGETS = [target for target, obj in TARGET_MAP.iteritems() if 'GCC_ARM' in obj.supported_toolchains] # override @property def flags(self): """Returns a dictionary of toolchain flags. Keys of the dictionary are: cxx_flags - c++ flags c_flags - c flags ld_flags - linker flags asm_flags - assembler flags common_flags - common options The difference from the parent function is that it does not add macro definitions, since they are passed separately. """ config_header = self.toolchain.get_config_header() flags = {key + "_flags": copy.deepcopy(value) for key, value in self.toolchain.flags.iteritems()} if config_header: config_header = relpath(config_header, self.resources.file_basepath[config_header]) flags['c_flags'] += self.toolchain.get_config_option(config_header) flags['cxx_flags'] += self.toolchain.get_config_option( config_header) return flags def toolchain_flags(self, toolchain): """Returns a dictionary of toolchain flags. Keys of the dictionary are: cxx_flags - c++ flags c_flags - c flags ld_flags - linker flags asm_flags - assembler flags common_flags - common options The difference from the above is that it takes a parameter. """ # Note: use the config options from the currently selected toolchain. config_header = self.toolchain.get_config_header() flags = {key + "_flags": copy.deepcopy(value) for key, value in toolchain.flags.iteritems()} if config_header: config_header = relpath(config_header, self.resources.file_basepath[config_header]) header_options = self.toolchain.get_config_option(config_header) flags['c_flags'] += header_options flags['cxx_flags'] += header_options return flags # override def generate(self): """ Generate the .project and .cproject files. """ if not self.resources.linker_script: raise NotSupportedException("No linker script found.") print print 'Create a GNU ARM Eclipse C++ managed project' print 'Project name: {0}'.format(self.project_name) print 'Target: {0}'.format(self.toolchain.target.name) print 'Toolchain: {0}'.format(self.TOOLCHAIN) self.resources.win_to_unix() # TODO: use some logger to display additional info if verbose libraries = [] # print 'libraries' # print self.resources.libraries for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) self.system_libraries = [ 'stdc++', 'supc++', 'm', 'c', 'gcc', 'nosys' ] # Read in all profiles, we'll extract compiler options. profiles = self.get_all_profiles() profile_ids = [s.lower() for s in profiles] profile_ids.sort() # TODO: get the list from existing .cproject build_folders = [s.capitalize() for s in profile_ids] build_folders.append('BUILD') # print build_folders objects = [self.filter_dot(s) for s in self.resources.objects] for bf in build_folders: objects = [o for o in objects if not o.startswith(bf + '/')] # print 'objects' # print objects self.compute_exclusions() self.include_path = [ self.filter_dot(s) for s in self.resources.inc_dirs] print 'Include folders: {0}'.format(len(self.include_path)) self.as_defines = self.toolchain.get_symbols(True) self.c_defines = self.toolchain.get_symbols() self.cpp_defines = self.c_defines print 'Symbols: {0}'.format(len(self.c_defines)) self.ld_script = self.filter_dot( self.resources.linker_script) print 'Linker script: {0}'.format(self.ld_script) self.options = {} for id in profile_ids: # There are 4 categories of options, a category common too # all tools and a specific category for each of the tools. opts = {} opts['common'] = {} opts['as'] = {} opts['c'] = {} opts['cpp'] = {} opts['ld'] = {} opts['id'] = id opts['name'] = opts['id'].capitalize() print print 'Build configuration: {0}'.format(opts['name']) profile = profiles[id] profile_toolchain = profile[self.TOOLCHAIN] # A small hack, do not bother with src_path again, # pass an empty string to avoid crashing. src_paths = [''] target_name = self.toolchain.target.name toolchain = prepare_toolchain( src_paths, target_name, self.TOOLCHAIN, build_profile=profile_toolchain) # Hack to fill in build_dir toolchain.build_dir = self.toolchain.build_dir flags = self.toolchain_flags(toolchain) print 'Common flags:', ' '.join(flags['common_flags']) print 'C++ flags:', ' '.join(flags['cxx_flags']) print 'C flags:', ' '.join(flags['c_flags']) print 'ASM flags:', ' '.join(flags['asm_flags']) print 'Linker flags:', ' '.join(flags['ld_flags']) # Most GNU ARM Eclipse options have a parent, # either debug or release. if '-O0' in flags['common_flags'] or '-Og' in flags['common_flags']: opts['parent_id'] = 'debug' else: opts['parent_id'] = 'release' self.process_options(opts, flags) opts['as']['defines'] = self.as_defines opts['c']['defines'] = self.c_defines opts['cpp']['defines'] = self.cpp_defines opts['common']['include_paths'] = self.include_path opts['common']['excluded_folders'] = '|'.join( self.excluded_folders) opts['ld']['library_paths'] = [ self.filter_dot(s) for s in self.resources.lib_dirs] opts['ld']['object_files'] = objects opts['ld']['user_libraries'] = libraries opts['ld']['system_libraries'] = self.system_libraries opts['ld']['script'] = self.ld_script # Unique IDs used in multiple places. # Those used only once are implemented with {{u.id}}. uid = {} uid['config'] = u.id uid['tool_c_compiler'] = u.id uid['tool_c_compiler_input'] = u.id uid['tool_cpp_compiler'] = u.id uid['tool_cpp_compiler_input'] = u.id opts['uid'] = uid self.options[id] = opts jinja_ctx = { 'name': self.project_name, # Compiler & linker command line options 'options': self.options, # Must be an object with an `id` property, which # will be called repeatedly, to generate multiple UIDs. 'u': u, } # TODO: it would be good to have jinja stop if one of the # expected context values is not defined. self.gen_file('gnuarmeclipse/.project.tmpl', jinja_ctx, '.project', trim_blocks=True, lstrip_blocks=True) self.gen_file('gnuarmeclipse/.cproject.tmpl', jinja_ctx, '.cproject', trim_blocks=True, lstrip_blocks=True) self.gen_file('gnuarmeclipse/makefile.targets.tmpl', jinja_ctx, 'makefile.targets', trim_blocks=True, lstrip_blocks=True) if not exists('.mbedignore'): print print 'Create .mbedignore' with open('.mbedignore', 'w') as f: for bf in build_folders: print bf + '/' f.write(bf + '/\n') print print 'Done. Import the \'{0}\' project in Eclipse.'.format(self.project_name) # override @staticmethod def build(project_name, log_name="build_log.txt", cleanup=True): """ Headless build an Eclipse project. The following steps are performed: - a temporary workspace is created, - the project is imported, - a clean build of all configurations is performed and - the temporary workspace is removed. The build results are in the Debug & Release folders. All executables (eclipse & toolchain) must be in the PATH. The general method to start a headless Eclipse build is: $ eclipse \ --launcher.suppressErrors \ -nosplash \ -application org.eclipse.cdt.managedbuilder.core.headlessbuild \ -data /path/to/workspace \ -import /path/to/project \ -cleanBuild "project[/configuration] | all" """ # TODO: possibly use the log file. # Create a temporary folder for the workspace. tmp_folder = tempfile.mkdtemp() cmd = [ 'eclipse', '--launcher.suppressErrors', '-nosplash', '-application org.eclipse.cdt.managedbuilder.core.headlessbuild', '-data', tmp_folder, '-import', os.getcwd(), '-cleanBuild', project_name ] p = Popen(' '.join(cmd), shell=True, stdout=PIPE, stderr=PIPE) out, err = p.communicate() ret_code = p.returncode stdout_string = "=" * 10 + "STDOUT" + "=" * 10 + "\n" err_string = "=" * 10 + "STDERR" + "=" * 10 + "\n" err_string += err ret_string = "SUCCESS\n" if ret_code != 0: ret_string += "FAILURE\n" print "%s\n%s\n%s\n%s" % (stdout_string, out, err_string, ret_string) if log_name: # Write the output to the log file with open(log_name, 'w+') as f: f.write(stdout_string) f.write(out) f.write(err_string) f.write(ret_string) # Cleanup the exported and built files if cleanup: if exists(log_name): os.remove(log_name) os.remove('.project') os.remove('.cproject') if exists('Debug'): shutil.rmtree('Debug') if exists('Release'): shutil.rmtree('Release') if exists('makefile.targets'): os.remove('makefile.targets') # Always remove the temporary folder. if exists(tmp_folder): shutil.rmtree(tmp_folder) if ret_code == 0: # Return Success return 0 # Seems like something went wrong. return -1 # ------------------------------------------------------------------------- @staticmethod def get_all_profiles(): tools_path = dirname(dirname(dirname(__file__))) file_names = [join(tools_path, "profiles", fn) for fn in os.listdir( join(tools_path, "profiles")) if fn.endswith(".json")] # print file_names profile_names = [basename(fn).replace(".json", "") for fn in file_names] # print profile_names profiles = {} for fn in file_names: content = load(open(fn)) profile_name = basename(fn).replace(".json", "") profiles[profile_name] = content return profiles # ------------------------------------------------------------------------- # Process source files/folders exclusions. def compute_exclusions(self): """ With the project root as the only source folder known to CDT, based on the list of source files, compute the folders to not be included in the build. The steps are: - get the list of source folders, as dirname(source_file) - compute the top folders (subfolders of the project folder) - iterate all subfolders and add them to a tree, with all nodes markes as 'not used' - iterate the source folders and mark them as 'used' in the tree, including all intermediate nodes - recurse the tree and collect all unused folders; descend the hierarchy only for used nodes """ source_folders = [self.filter_dot(s) for s in set(dirname( src) for src in self.resources.c_sources + self.resources.cpp_sources + self.resources.s_sources)] if '.' in source_folders: source_folders.remove('.') # print 'source folders' # print source_folders # Source folders were converted before and are guaranteed to # use the POSIX separator. top_folders = [f for f in set(s.split('/')[0] for s in source_folders)] # print 'top folders' # print top_folders self.source_tree = {} for top_folder in top_folders: for root, dirs, files in os.walk(top_folder, topdown=True): # print root, dirs, files # Paths returned by os.walk() must be split with os.dep # to accomodate Windows weirdness. parts = root.split(os.sep) <|fim▁hole|> if part.startswith('.'): skip = True break if skip: continue # Further process only leaf paths, (that do not have # sub-folders). if len(dirs) == 0: # The path is reconstructed using POSIX separators. self.add_source_folder_to_tree('/'.join(parts)) for folder in source_folders: self.add_source_folder_to_tree(folder, True) # print # print self.source_tree # self.dump_paths(self.source_tree) # self.dump_tree(self.source_tree) # print 'excludings' self.excluded_folders = ['BUILD'] self.recurse_excludings(self.source_tree) print 'Source folders: {0}, with {1} exclusions'.format(len(source_folders), len(self.excluded_folders)) def add_source_folder_to_tree(self, path, is_used=False): """ Decompose a path in an array of folder names and create the tree. On the second pass the nodes should be already there; mark them as used. """ # print path, is_used # All paths arriving here are guaranteed to use the POSIX # separators, os.walk() paths were also explicitly converted. parts = path.split('/') # print parts node = self.source_tree prev = None for part in parts: if part not in node.keys(): new_node = {} new_node['name'] = part new_node['children'] = {} if prev != None: new_node['parent'] = prev node[part] = new_node node[part]['is_used'] = is_used prev = node[part] node = node[part]['children'] def recurse_excludings(self, nodes): """ Recurse the tree and collect all unused folders; descend the hierarchy only for used nodes. """ for k in nodes.keys(): node = nodes[k] if node['is_used'] == False: parts = [] cnode = node while True: parts.insert(0, cnode['name']) if 'parent' not in cnode: break cnode = cnode['parent'] # Compose a POSIX path. path = '/'.join(parts) # print path self.excluded_folders.append(path) else: self.recurse_excludings(node['children']) # ------------------------------------------------------------------------- @staticmethod def filter_dot(str): """ Remove the './' prefix, if present. This function assumes that resources.win_to_unix() replaced all windows backslashes with slashes. """ if str == None: return None if str[:2] == './': return str[2:] return str # ------------------------------------------------------------------------- def dump_tree(self, nodes, depth=0): for k in nodes.keys(): node = nodes[k] parent_name = node['parent'][ 'name'] if 'parent' in node.keys() else '' print ' ' * depth, node['name'], node['is_used'], parent_name if len(node['children'].keys()) != 0: self.dump_tree(node['children'], depth + 1) def dump_paths(self, nodes, depth=0): for k in nodes.keys(): node = nodes[k] parts = [] while True: parts.insert(0, node['name']) if 'parent' not in node: break node = node['parent'] path = '/'.join(parts) print path, nodes[k]['is_used'] self.dump_paths(nodes[k]['children'], depth + 1) # ------------------------------------------------------------------------- def process_options(self, opts, flags_in): """ CDT managed projects store lots of build options in separate variables, with separate IDs in the .cproject file. When the CDT build is started, all these options are brought together to compose the compiler and linker command lines. Here the process is reversed, from the compiler and linker command lines, the options are identified and various flags are set to control the template generation process. Once identified, the options are removed from the command lines. The options that were not identified are options that do not have CDT equivalents and will be passed in the 'Other options' categories. Although this process does not have a very complicated logic, given the large number of explicit configuration options used by the GNU ARM Eclipse managed build plug-in, it is tedious... """ # Make a copy of the flags, to be one by one removed after processing. flags = copy.deepcopy(flags_in) if False: print print 'common_flags', flags['common_flags'] print 'asm_flags', flags['asm_flags'] print 'c_flags', flags['c_flags'] print 'cxx_flags', flags['cxx_flags'] print 'ld_flags', flags['ld_flags'] # Initialise the 'last resort' options where all unrecognised # options will be collected. opts['as']['other'] = '' opts['c']['other'] = '' opts['cpp']['other'] = '' opts['ld']['other'] = '' MCPUS = { 'Cortex-M0': {'mcpu': 'cortex-m0', 'fpu_unit': None}, 'Cortex-M0+': {'mcpu': 'cortex-m0plus', 'fpu_unit': None}, 'Cortex-M1': {'mcpu': 'cortex-m1', 'fpu_unit': None}, 'Cortex-M3': {'mcpu': 'cortex-m3', 'fpu_unit': None}, 'Cortex-M4': {'mcpu': 'cortex-m4', 'fpu_unit': None}, 'Cortex-M4F': {'mcpu': 'cortex-m4', 'fpu_unit': 'fpv4spd16'}, 'Cortex-M7': {'mcpu': 'cortex-m7', 'fpu_unit': None}, 'Cortex-M7F': {'mcpu': 'cortex-m7', 'fpu_unit': 'fpv4spd16'}, 'Cortex-M7FD': {'mcpu': 'cortex-m7', 'fpu_unit': 'fpv5d16'}, 'Cortex-A9': {'mcpu': 'cortex-a9', 'fpu_unit': 'vfpv3'} } # Remove options that are supplied by CDT self.remove_option(flags['common_flags'], '-c') self.remove_option(flags['common_flags'], '-MMD') # As 'plan B', get the CPU from the target definition. core = self.toolchain.target.core opts['common']['arm.target.family'] = None # cortex-m0, cortex-m0-small-multiply, cortex-m0plus, # cortex-m0plus-small-multiply, cortex-m1, cortex-m1-small-multiply, # cortex-m3, cortex-m4, cortex-m7. str = self.find_options(flags['common_flags'], '-mcpu=') if str != None: opts['common']['arm.target.family'] = str[len('-mcpu='):] self.remove_option(flags['common_flags'], str) self.remove_option(flags['ld_flags'], str) else: if core not in MCPUS: raise NotSupportedException( 'Target core {0} not supported.'.format(core)) opts['common']['arm.target.family'] = MCPUS[core]['mcpu'] opts['common']['arm.target.arch'] = 'none' str = self.find_options(flags['common_flags'], '-march=') arch = str[len('-march='):] archs = {'armv6-m': 'armv6-m', 'armv7-m': 'armv7-m', 'armv7-a': 'armv7-a'} if arch in archs: opts['common']['arm.target.arch'] = archs[arch] self.remove_option(flags['common_flags'], str) opts['common']['arm.target.instructionset'] = 'thumb' if '-mthumb' in flags['common_flags']: self.remove_option(flags['common_flags'], '-mthumb') self.remove_option(flags['ld_flags'], '-mthumb') elif '-marm' in flags['common_flags']: opts['common']['arm.target.instructionset'] = 'arm' self.remove_option(flags['common_flags'], '-marm') self.remove_option(flags['ld_flags'], '-marm') opts['common']['arm.target.thumbinterwork'] = False if '-mthumb-interwork' in flags['common_flags']: opts['common']['arm.target.thumbinterwork'] = True self.remove_option(flags['common_flags'], '-mthumb-interwork') opts['common']['arm.target.endianness'] = None if '-mlittle-endian' in flags['common_flags']: opts['common']['arm.target.endianness'] = 'little' self.remove_option(flags['common_flags'], '-mlittle-endian') elif '-mbig-endian' in flags['common_flags']: opts['common']['arm.target.endianness'] = 'big' self.remove_option(flags['common_flags'], '-mbig-endian') opts['common']['arm.target.fpu.unit'] = None # default, fpv4spd16, fpv5d16, fpv5spd16 str = self.find_options(flags['common_flags'], '-mfpu=') if str != None: fpu = str[len('-mfpu='):] fpus = { 'fpv4-sp-d16': 'fpv4spd16', 'fpv5-d16': 'fpv5d16', 'fpv5-sp-d16': 'fpv5spd16' } if fpu in fpus: opts['common']['arm.target.fpu.unit'] = fpus[fpu] self.remove_option(flags['common_flags'], str) self.remove_option(flags['ld_flags'], str) if opts['common']['arm.target.fpu.unit'] == None: if core not in MCPUS: raise NotSupportedException( 'Target core {0} not supported.'.format(core)) if MCPUS[core]['fpu_unit']: opts['common'][ 'arm.target.fpu.unit'] = MCPUS[core]['fpu_unit'] # soft, softfp, hard. str = self.find_options(flags['common_flags'], '-mfloat-abi=') if str != None: opts['common']['arm.target.fpu.abi'] = str[ len('-mfloat-abi='):] self.remove_option(flags['common_flags'], str) self.remove_option(flags['ld_flags'], str) opts['common']['arm.target.unalignedaccess'] = None if '-munaligned-access' in flags['common_flags']: opts['common']['arm.target.unalignedaccess'] = 'enabled' self.remove_option(flags['common_flags'], '-munaligned-access') elif '-mno-unaligned-access' in flags['common_flags']: opts['common']['arm.target.unalignedaccess'] = 'disabled' self.remove_option(flags['common_flags'], '-mno-unaligned-access') # Default optimisation level for Release. opts['common']['optimization.level'] = '-Os' # If the project defines an optimisation level, it is used # only for the Release configuration, the Debug one used '-Og'. str = self.find_options(flags['common_flags'], '-O') if str != None: levels = { '-O0': 'none', '-O1': 'optimize', '-O2': 'more', '-O3': 'most', '-Os': 'size', '-Og': 'debug' } if str in levels: opts['common']['optimization.level'] = levels[str] self.remove_option(flags['common_flags'], str) include_files = [] for all_flags in [flags['common_flags'], flags['c_flags'], flags['cxx_flags']]: while '-include' in all_flags: ix = all_flags.index('-include') str = all_flags[ix + 1] if str not in include_files: include_files.append(str) self.remove_option(all_flags, '-include') self.remove_option(all_flags, str) opts['common']['include_files'] = include_files if '-ansi' in flags['c_flags']: opts['c']['compiler.std'] = '-ansi' self.remove_option(flags['c_flags'], str) else: str = self.find_options(flags['c_flags'], '-std') std = str[len('-std='):] c_std = { 'c90': 'c90', 'c89': 'c90', 'gnu90': 'gnu90', 'gnu89': 'gnu90', 'c99': 'c99', 'c9x': 'c99', 'gnu99': 'gnu99', 'gnu9x': 'gnu98', 'c11': 'c11', 'c1x': 'c11', 'gnu11': 'gnu11', 'gnu1x': 'gnu11' } if std in c_std: opts['c']['compiler.std'] = c_std[std] self.remove_option(flags['c_flags'], str) if '-ansi' in flags['cxx_flags']: opts['cpp']['compiler.std'] = '-ansi' self.remove_option(flags['cxx_flags'], str) else: str = self.find_options(flags['cxx_flags'], '-std') std = str[len('-std='):] cpp_std = { 'c++98': 'cpp98', 'c++03': 'cpp98', 'gnu++98': 'gnucpp98', 'gnu++03': 'gnucpp98', 'c++0x': 'cpp0x', 'gnu++0x': 'gnucpp0x', 'c++11': 'cpp11', 'gnu++11': 'gnucpp11', 'c++1y': 'cpp1y', 'gnu++1y': 'gnucpp1y', 'c++14': 'cpp14', 'gnu++14': 'gnucpp14', 'c++1z': 'cpp1z', 'gnu++1z': 'gnucpp1z', } if std in cpp_std: opts['cpp']['compiler.std'] = cpp_std[std] self.remove_option(flags['cxx_flags'], str) # Common optimisation options. optimization_options = { '-fmessage-length=0': 'optimization.messagelength', '-fsigned-char': 'optimization.signedchar', '-ffunction-sections': 'optimization.functionsections', '-fdata-sections': 'optimization.datasections', '-fno-common': 'optimization.nocommon', '-fno-inline-functions': 'optimization.noinlinefunctions', '-ffreestanding': 'optimization.freestanding', '-fno-builtin': 'optimization.nobuiltin', '-fsingle-precision-constant': 'optimization.spconstant', '-fPIC': 'optimization.PIC', '-fno-move-loop-invariants': 'optimization.nomoveloopinvariants', } for option in optimization_options: opts['common'][optimization_options[option]] = False if option in flags['common_flags']: opts['common'][optimization_options[option]] = True self.remove_option(flags['common_flags'], option) # Common warning options. warning_options = { '-fsyntax-only': 'warnings.syntaxonly', '-pedantic': 'warnings.pedantic', '-pedantic-errors': 'warnings.pedanticerrors', '-w': 'warnings.nowarn', '-Wunused': 'warnings.unused', '-Wuninitialized': 'warnings.uninitialized', '-Wall': 'warnings.allwarn', '-Wextra': 'warnings.extrawarn', '-Wmissing-declarations': 'warnings.missingdeclaration', '-Wconversion': 'warnings.conversion', '-Wpointer-arith': 'warnings.pointerarith', '-Wpadded': 'warnings.padded', '-Wshadow': 'warnings.shadow', '-Wlogical-op': 'warnings.logicalop', '-Waggregate-return': 'warnings.agreggatereturn', '-Wfloat-equal': 'warnings.floatequal', '-Werror': 'warnings.toerrors', } for option in warning_options: opts['common'][warning_options[option]] = False if option in flags['common_flags']: opts['common'][warning_options[option]] = True self.remove_option(flags['common_flags'], option) # Common debug options. debug_levels = { '-g': 'default', '-g1': 'minimal', '-g3': 'max', } opts['common']['debugging.level'] = 'none' for option in debug_levels: if option in flags['common_flags']: opts['common'][ 'debugging.level'] = debug_levels[option] self.remove_option(flags['common_flags'], option) debug_formats = { '-ggdb': 'gdb', '-gstabs': 'stabs', '-gstabs+': 'stabsplus', '-gdwarf-2': 'dwarf2', '-gdwarf-3': 'dwarf3', '-gdwarf-4': 'dwarf4', '-gdwarf-5': 'dwarf5', } opts['common']['debugging.format'] = '' for option in debug_levels: if option in flags['common_flags']: opts['common'][ 'debugging.format'] = debug_formats[option] self.remove_option(flags['common_flags'], option) opts['common']['debugging.prof'] = False if '-p' in flags['common_flags']: opts['common']['debugging.prof'] = True self.remove_option(flags['common_flags'], '-p') opts['common']['debugging.gprof'] = False if '-pg' in flags['common_flags']: opts['common']['debugging.gprof'] = True self.remove_option(flags['common_flags'], '-gp') # Assembler options. opts['as']['usepreprocessor'] = False while '-x' in flags['asm_flags']: ix = flags['asm_flags'].index('-x') str = flags['asm_flags'][ix + 1] if str == 'assembler-with-cpp': opts['as']['usepreprocessor'] = True else: # Collect all other assembler options. opts['as']['other'] += ' -x ' + str self.remove_option(flags['asm_flags'], '-x') self.remove_option(flags['asm_flags'], 'assembler-with-cpp') opts['as']['nostdinc'] = False if '-nostdinc' in flags['asm_flags']: opts['as']['nostdinc'] = True self.remove_option(flags['asm_flags'], '-nostdinc') opts['as']['verbose'] = False if '-v' in flags['asm_flags']: opts['as']['verbose'] = True self.remove_option(flags['asm_flags'], '-v') # C options. opts['c']['nostdinc'] = False if '-nostdinc' in flags['c_flags']: opts['c']['nostdinc'] = True self.remove_option(flags['c_flags'], '-nostdinc') opts['c']['verbose'] = False if '-v' in flags['c_flags']: opts['c']['verbose'] = True self.remove_option(flags['c_flags'], '-v') warning_options = { '-Wmissing-prototypes': 'warnings.missingprototypes', '-Wstrict-prototypes': 'warnings.strictprototypes', '-Wbad-function-cast': 'warnings.badfunctioncast', } for option in warning_options: opts['c'][warning_options[option]] = False if option in flags['common_flags']: opts['c'][warning_options[option]] = True self.remove_option(flags['common_flags'], option) # C++ options. opts['cpp']['nostdinc'] = False if '-nostdinc' in flags['cxx_flags']: opts['cpp']['nostdinc'] = True self.remove_option(flags['cxx_flags'], '-nostdinc') opts['cpp']['nostdincpp'] = False if '-nostdinc++' in flags['cxx_flags']: opts['cpp']['nostdincpp'] = True self.remove_option(flags['cxx_flags'], '-nostdinc++') optimization_options = { '-fno-exceptions': 'optimization.noexceptions', '-fno-rtti': 'optimization.nortti', '-fno-use-cxa-atexit': 'optimization.nousecxaatexit', '-fno-threadsafe-statics': 'optimization.nothreadsafestatics', } for option in optimization_options: opts['cpp'][optimization_options[option]] = False if option in flags['cxx_flags']: opts['cpp'][optimization_options[option]] = True self.remove_option(flags['cxx_flags'], option) if option in flags['common_flags']: opts['cpp'][optimization_options[option]] = True self.remove_option(flags['common_flags'], option) warning_options = { '-Wabi': 'warnabi', '-Wctor-dtor-privacy': 'warnings.ctordtorprivacy', '-Wnoexcept': 'warnings.noexcept', '-Wnon-virtual-dtor': 'warnings.nonvirtualdtor', '-Wstrict-null-sentinel': 'warnings.strictnullsentinel', '-Wsign-promo': 'warnings.signpromo', '-Weffc++': 'warneffc', } for option in warning_options: opts['cpp'][warning_options[option]] = False if option in flags['cxx_flags']: opts['cpp'][warning_options[option]] = True self.remove_option(flags['cxx_flags'], option) if option in flags['common_flags']: opts['cpp'][warning_options[option]] = True self.remove_option(flags['common_flags'], option) opts['cpp']['verbose'] = False if '-v' in flags['cxx_flags']: opts['cpp']['verbose'] = True self.remove_option(flags['cxx_flags'], '-v') # Linker options. linker_options = { '-nostartfiles': 'nostart', '-nodefaultlibs': 'nodeflibs', '-nostdlib': 'nostdlibs', } for option in linker_options: opts['ld'][linker_options[option]] = False if option in flags['ld_flags']: opts['ld'][linker_options[option]] = True self.remove_option(flags['ld_flags'], option) opts['ld']['gcsections'] = False if '-Wl,--gc-sections' in flags['ld_flags']: opts['ld']['gcsections'] = True self.remove_option(flags['ld_flags'], '-Wl,--gc-sections') opts['ld']['flags'] = [] to_remove = [] for opt in flags['ld_flags']: if opt.startswith('-Wl,--wrap,'): opts['ld']['flags'].append( '--wrap=' + opt[len('-Wl,--wrap,'):]) to_remove.append(opt) for opt in to_remove: self.remove_option(flags['ld_flags'], opt) # Other tool remaining options are separated by category. opts['as']['otherwarnings'] = self.find_options( flags['asm_flags'], '-W') opts['c']['otherwarnings'] = self.find_options( flags['c_flags'], '-W') opts['c']['otheroptimizations'] = self.find_options(flags[ 'c_flags'], '-f') opts['cpp']['otherwarnings'] = self.find_options( flags['cxx_flags'], '-W') opts['cpp']['otheroptimizations'] = self.find_options( flags['cxx_flags'], '-f') # Other common remaining options are separated by category. opts['common']['optimization.other'] = self.find_options( flags['common_flags'], '-f') opts['common']['warnings.other'] = self.find_options( flags['common_flags'], '-W') # Remaining common flags are added to each tool. opts['as']['other'] += ' ' + \ ' '.join(flags['common_flags']) + ' ' + \ ' '.join(flags['asm_flags']) opts['c']['other'] += ' ' + \ ' '.join(flags['common_flags']) + ' ' + ' '.join(flags['c_flags']) opts['cpp']['other'] += ' ' + \ ' '.join(flags['common_flags']) + ' ' + \ ' '.join(flags['cxx_flags']) opts['ld']['other'] += ' ' + \ ' '.join(flags['common_flags']) + ' ' + ' '.join(flags['ld_flags']) if len(self.system_libraries) > 0: opts['ld']['other'] += ' -Wl,--start-group ' opts['ld'][ 'other'] += ' '.join('-l' + s for s in self.system_libraries) opts['ld']['other'] += ' -Wl,--end-group ' # Strip all 'other' flags, since they might have leading spaces. opts['as']['other'] = opts['as']['other'].strip() opts['c']['other'] = opts['c']['other'].strip() opts['cpp']['other'] = opts['cpp']['other'].strip() opts['ld']['other'] = opts['ld']['other'].strip() if False: print print opts print print 'common_flags', flags['common_flags'] print 'asm_flags', flags['asm_flags'] print 'c_flags', flags['c_flags'] print 'cxx_flags', flags['cxx_flags'] print 'ld_flags', flags['ld_flags'] @staticmethod def find_options(lst, option): tmp = [str for str in lst if str.startswith(option)] if len(tmp) > 0: return tmp[0] else: return None @staticmethod def find_options(lst, prefix): other = '' opts = [str for str in lst if str.startswith(prefix)] if len(opts) > 0: for opt in opts: other += ' ' + opt GNUARMEclipse.remove_option(lst, opt) return other.strip() @staticmethod def remove_option(lst, option): if option in lst: lst.remove(option) # =============================================================================<|fim▁end|>
# Ignore paths that include parts starting with dot. skip = False for part in parts:
<|file_name|>tests.py<|end_file_name|><|fim▁begin|>""" Tests for file field behavior, and specifically #639, in which Model.save() gets called *again* for each FileField. This test will fail if calling a ModelForm's save() method causes Model.save() to be called more than once. """ from __future__ import absolute_import import os import shutil from django.core.files.uploadedfile import SimpleUploadedFile from django.utils import unittest <|fim▁hole|> class Bug639Test(unittest.TestCase): def testBug639(self): """ Simulate a file upload and check how many times Model.save() gets called. """ # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.jpg") img = open(filename, "rb").read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('test.jpg', img, 'image/jpeg')} form = PhotoForm(data=data, files=files) p = form.save() # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) def tearDown(self): """ Make sure to delete the "uploaded" file to avoid clogging /tmp. """ p = Photo.objects.get() p.image.delete(save=False) shutil.rmtree(temp_storage_dir)<|fim▁end|>
from .models import Photo, PhotoForm, temp_storage_dir
<|file_name|>af.js<|end_file_name|><|fim▁begin|>/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.<|fim▁hole|>CKEDITOR.plugins.setLang( 'blockquote', 'af', { toolbar: 'Sitaatblok' } );<|fim▁end|>
For licensing, see LICENSE.md or http://ckeditor.com/license */
<|file_name|>clientos.py<|end_file_name|><|fim▁begin|>""" Based on http://vaig.be/2009/03/getting-client-os-in-django.html """ import re def client_os(user_agent): ''' Context processor for Django that provides operating system information base on HTTP user agent. A user agent looks like (line break added): "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.6) \ Gecko/2009020409 Iceweasel/3.0.6 (Debian-3.0.6-1)" ''' # Mozilla/5.0 regex = '(?P<application_name>\w+)/(?P<application_version>[\d\.]+)' regex += ' \(' # X11 regex += '(?P<compatibility_flag>\w+)' regex += '; ' # U if "U;" in user_agent or "MSIE" in user_agent: # some UA strings leave out the U; regex += '(?P<version_token>[\w .]+)' regex += '; ' # Linux i686 regex += '(?P<platform_token>[\w ._]+)' # anything else regex += '; .*' result = re.match(regex, user_agent) if result: result_dict = result.groupdict() full_platform = result_dict['platform_token'] platform_values = full_platform.split(' ') if platform_values[0] in ('Windows', 'Linux', 'Mac'): platform = platform_values[0] elif platform_values[1] in ('Mac',): # Mac is given as "PPC Mac" or "Intel Mac" platform = platform_values[1] else: platform = None else: # Total hack to avoid dealing with regex nightmares if 'mac' in user_agent.lower(): full_platform = "Intel Mac 10.6" platform = 'Mac' elif 'windows' in user_agent.lower(): full_platform = "Windows" platform = 'Windows' else:<|fim▁hole|> full_platform = None platform = None return { 'full_platform': full_platform, 'platform': platform, }<|fim▁end|>
<|file_name|>mongolian-vowel-separator.js<|end_file_name|><|fim▁begin|>// Copyright (C) 2016 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-white-space description: > Mongolian Vowel Separator is not recognized as white space. info: | 11.2 White Space WhiteSpace :: <TAB> <VT> <FF> <SP> <NBSP><|fim▁hole|> Other category “Zs” code points General Category of U+180E is “Cf” (Format). negative: phase: parse type: SyntaxError features: [u180e] ---*/ throw "Test262: This statement should not be evaluated."; // U+180E between "var" and "foo"; UTF8(0x180E) = 0xE1 0xA0 0x8E var᠎foo;<|fim▁end|>
<ZWNBSP> <USP> <USP> ::
<|file_name|>light.cpp<|end_file_name|><|fim▁begin|>#include "stdafx.h" #include "light.h" using namespace graphic; cLight::cLight() { } cLight::~cLight() { } void cLight::Init(TYPE type, const Vector4 &ambient, // Vector4(1, 1, 1, 1), const Vector4 &diffuse, // Vector4(0.2, 0.2, 0.2, 1) const Vector4 &specular, // Vector4(1,1,1,1)<|fim▁hole|>{ ZeroMemory(&m_light, sizeof(m_light)); m_light.Type = (D3DLIGHTTYPE)type; m_light.Ambient = *(D3DCOLORVALUE*)&ambient; m_light.Diffuse = *(D3DCOLORVALUE*)&diffuse; m_light.Specular = *(D3DCOLORVALUE*)&specular; m_light.Direction = *(D3DXVECTOR3*)&direction; } void cLight::SetDirection( const Vector3 &direction ) { m_light.Direction = *(D3DXVECTOR3*)&direction; } void cLight::SetPosition( const Vector3 &pos ) { m_light.Position = *(D3DXVECTOR3*)&pos; } // ±×¸²ÀÚ¸¦ Ãâ·ÂÇϱâ À§ÇÑ Á¤º¸¸¦ ¸®ÅÏÇÑ´Ù. // modelPos : ±×¸²ÀÚ¸¦ Ãâ·ÂÇÒ ¸ðµ¨ÀÇ À§Ä¡ (¿ùµå»óÀÇ) // lightPos : ±¤¿øÀÇ À§Ä¡°¡ ÀúÀåµÇ¾î ¸®ÅÏ. // view : ±¤¿ø¿¡¼­ ¸ðµ¨À» ¹Ù¶óº¸´Â ºä Çà·Ä // proj : ±¤¿ø¿¡¼­ ¸ðµ¨À» ¹Ù¶óº¸´Â Åõ¿µ Çà·Ä // tt : Åõ¿µ ÁÂÇ¥¿¡¼­ ÅØ½ºÃÄ ÁÂÇ¥·Î º¯È¯ÇÏ´Â Çà·Ä. void cLight::GetShadowMatrix( const Vector3 &modelPos, OUT Vector3 &lightPos, OUT Matrix44 &view, OUT Matrix44 &proj, OUT Matrix44 &tt ) { if (D3DLIGHT_DIRECTIONAL == m_light.Type) { // ¹æÇ⼺ Á¶¸íÀ̸é Direction º¤Å͸¦ ÅëÇØ À§Ä¡¸¦ °è»êÇÏ°Ô ÇÑ´Ù. Vector3 pos = *(Vector3*)&m_light.Position; Vector3 dir = *(Vector3*)&m_light.Direction; lightPos = -dir * pos.Length(); } else { lightPos = *(Vector3*)&m_light.Position; } view.SetView2( lightPos, modelPos, Vector3(0,1,0)); proj.SetProjection( D3DX_PI/8.f, 1, 0.1f, 10000); D3DXMATRIX mTT= D3DXMATRIX(0.5f, 0.0f, 0.0f, 0.0f , 0.0f,-0.5f, 0.0f, 0.0f , 0.0f, 0.0f, 1.0f, 0.0f , 0.5f, 0.5f, 0.0f, 1.0f); tt = *(Matrix44*)&mTT; } void cLight::Bind(cRenderer &renderer, int lightIndex) const { renderer.GetDevice()->SetLight(lightIndex, &m_light); // ±¤¿ø ¼³Á¤. } // ¼ÎÀÌ´õ º¯¼ö¿¡ ¶óÀÌÆÃ¿¡ °ü·ÃµÈ º¯¼ö¸¦ ÃʱâÈ­ ÇÑ´Ù. void cLight::Bind(cShader &shader) const { static cShader *oldPtr = NULL; static D3DXHANDLE hDir = NULL; static D3DXHANDLE hPos = NULL; static D3DXHANDLE hAmbient = NULL; static D3DXHANDLE hDiffuse = NULL; static D3DXHANDLE hSpecular = NULL; static D3DXHANDLE hTheta = NULL; static D3DXHANDLE hPhi = NULL; if (oldPtr != &shader) { hDir = shader.GetValueHandle("light.dir"); hPos = shader.GetValueHandle("light.pos"); hAmbient = shader.GetValueHandle("light.ambient"); hDiffuse = shader.GetValueHandle("light.diffuse"); hSpecular = shader.GetValueHandle("light.specular"); hTheta = shader.GetValueHandle("light.spotInnerCone"); hPhi = shader.GetValueHandle("light.spotOuterCone"); oldPtr = &shader; } shader.SetVector( hDir, *(Vector3*)&m_light.Direction); shader.SetVector( hPos, *(Vector3*)&m_light.Position); shader.SetVector( hAmbient, *(Vector4*)&m_light.Ambient); shader.SetVector( hDiffuse, *(Vector4*)&m_light.Diffuse); shader.SetVector( hSpecular, *(Vector4*)&m_light.Specular); shader.SetFloat( hTheta, m_light.Theta); shader.SetFloat( hPhi, m_light.Phi); //shader.SetFloat( "light.radius", m_light.r); }<|fim▁end|>
const Vector3 &direction) // Vector3(0,-1,0)
<|file_name|>scaler.py<|end_file_name|><|fim▁begin|>import time import config from ophyd import scaler from ophyd.utils import enum ScalerMode = enum(ONE_SHOT=0, AUTO_COUNT=1) loggers = ('ophyd.signal', 'ophyd.scaler', ) config.setup_loggers(loggers) logger = config.logger sca = scaler.EpicsScaler(config.scalers[0]) sca.preset_time.put(5.2, wait=True) logger.info('Counting in One-Shot mode for %f s...', sca.preset_time.get()) sca.trigger() logger.info('Sleeping...') time.sleep(3) logger.info('Done sleeping. Stopping counter...') sca.count.put(0) logger.info('Set mode to AutoCount') sca.count_mode.put(ScalerMode.AUTO_COUNT, wait=True) sca.trigger() logger.info('Begin auto-counting (aka "background counting")...') time.sleep(2) logger.info('Set mode to OneShot') sca.count_mode.put(ScalerMode.ONE_SHOT, wait=True) time.sleep(1) logger.info('Stopping (aborting) auto-counting.') sca.count.put(0) logger.info('read() all channels in one-shot mode...') vals = sca.read() logger.info(vals) <|fim▁hole|><|fim▁end|>
logger.info('sca.channels.get() shows: %s', sca.channels.get())
<|file_name|>gengo.py<|end_file_name|><|fim▁begin|>from datetime import datetime import rfGengou from . import PluginBase __all__ = ['Gengo']<|fim▁hole|> class Gengo(PluginBase): def execute(self, args): if len(args) == 0: target = datetime.now() elif len(args) == 1: target = datetime.strptime(args[0], '%Y/%m/%d') else: raise ValueError('wrong number of arguments are given') return '{:s}{:d}年{:d}月{:d}日'.format(*rfGengou.s2g(target)) def help(self): return """[yyyy/mm/dd] Convert from string to Japanese Gengo. If string is not given, use current time. ex) > gengo 平成28年12月2日 > gengo 2000/01/01 平成12年1月1日 """<|fim▁end|>
<|file_name|>and_then.rs<|end_file_name|><|fim▁begin|>#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::clone::Clone; // #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub enum Option<T> { // /// No value // #[stable(feature = "rust1", since = "1.0.0")] // None, // /// Some value `T` // #[stable(feature = "rust1", since = "1.0.0")] // Some(T) // } // impl<T> Option<T> { // ///////////////////////////////////////////////////////////////////////// // // Querying the contained values // ///////////////////////////////////////////////////////////////////////// // // /// Returns `true` if the option is a `Some` value // /// // /// # Examples // /// // /// ``` // /// let x: Option<u32> = Some(2); // /// assert_eq!(x.is_some(), true); // /// // /// let x: Option<u32> = None; // /// assert_eq!(x.is_some(), false); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn is_some(&self) -> bool { // match *self { // Some(_) => true, // None => false // } // } // // /// Returns `true` if the option is a `None` value // /// // /// # Examples // /// // /// ``` // /// let x: Option<u32> = Some(2); // /// assert_eq!(x.is_none(), false); // /// // /// let x: Option<u32> = None; // /// assert_eq!(x.is_none(), true); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn is_none(&self) -> bool { // !self.is_some() // } // // ///////////////////////////////////////////////////////////////////////// // // Adapter for working with references // ///////////////////////////////////////////////////////////////////////// // // /// Converts from `Option<T>` to `Option<&T>` // /// // /// # Examples // /// // /// Convert an `Option<String>` into an `Option<usize>`, preserving the original. // /// The `map` method takes the `self` argument by value, consuming the original, // /// so this technique uses `as_ref` to first take an `Option` to a reference // /// to the value inside the original. // /// // /// ``` // /// let num_as_str: Option<String> = Some("10".to_string()); // /// // First, cast `Option<String>` to `Option<&String>` with `as_ref`, // /// // then consume *that* with `map`, leaving `num_as_str` on the stack. // /// let num_as_int: Option<usize> = num_as_str.as_ref().map(|n| n.len()); // /// println!("still can print num_as_str: {:?}", num_as_str); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn as_ref<'r>(&'r self) -> Option<&'r T> { // match *self { // Some(ref x) => Some(x), // None => None // } // } // // /// Converts from `Option<T>` to `Option<&mut T>` // /// // /// # Examples // /// // /// ``` // /// let mut x = Some(2); // /// match x.as_mut() { // /// Some(v) => *v = 42, // /// None => {}, // /// } // /// assert_eq!(x, Some(42)); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> { // match *self { // Some(ref mut x) => Some(x), // None => None // } // } // // /// Converts from `Option<T>` to `&mut [T]` (without copying) // /// // /// # Examples // /// // /// ``` // /// # #![feature(core)] // /// let mut x = Some("Diamonds"); // /// { // /// let v = x.as_mut_slice(); // /// assert!(v == ["Diamonds"]); // /// v[0] = "Dirt";<|fim▁hole|> // /// assert_eq!(x, Some("Dirt")); // /// ``` // #[inline] // #[unstable(feature = "core", // reason = "waiting for mut conventions")] // pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] { // match *self { // Some(ref mut x) => { // let result: &mut [T] = slice::mut_ref_slice(x); // result // } // None => { // let result: &mut [T] = &mut []; // result // } // } // } // // ///////////////////////////////////////////////////////////////////////// // // Getting to contained values // ///////////////////////////////////////////////////////////////////////// // // /// Unwraps an option, yielding the content of a `Some` // /// // /// # Panics // /// // /// Panics if the value is a `None` with a custom panic message provided by // /// `msg`. // /// // /// # Examples // /// // /// ``` // /// let x = Some("value"); // /// assert_eq!(x.expect("the world is ending"), "value"); // /// ``` // /// // /// ```{.should_panic} // /// let x: Option<&str> = None; // /// x.expect("the world is ending"); // panics with `the world is ending` // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn expect(self, msg: &str) -> T { // match self { // Some(val) => val, // None => panic!("{}", msg), // } // } // // /// Moves the value `v` out of the `Option<T>` if it is `Some(v)`. // /// // /// # Panics // /// // /// Panics if the self value equals `None`. // /// // /// # Safety note // /// // /// In general, because this function may panic, its use is discouraged. // /// Instead, prefer to use pattern matching and handle the `None` // /// case explicitly. // /// // /// # Examples // /// // /// ``` // /// let x = Some("air"); // /// assert_eq!(x.unwrap(), "air"); // /// ``` // /// // /// ```{.should_panic} // /// let x: Option<&str> = None; // /// assert_eq!(x.unwrap(), "air"); // fails // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn unwrap(self) -> T { // match self { // Some(val) => val, // None => panic!("called `Option::unwrap()` on a `None` value"), // } // } // // /// Returns the contained value or a default. // /// // /// # Examples // /// // /// ``` // /// assert_eq!(Some("car").unwrap_or("bike"), "car"); // /// assert_eq!(None.unwrap_or("bike"), "bike"); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn unwrap_or(self, def: T) -> T { // match self { // Some(x) => x, // None => def // } // } // // /// Returns the contained value or computes it from a closure. // /// // /// # Examples // /// // /// ``` // /// let k = 10; // /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); // /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T { // match self { // Some(x) => x, // None => f() // } // } // // ///////////////////////////////////////////////////////////////////////// // // Transforming contained values // ///////////////////////////////////////////////////////////////////////// // // /// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value // /// // /// # Examples // /// // /// Convert an `Option<String>` into an `Option<usize>`, consuming the original: // /// // /// ``` // /// let maybe_some_string = Some(String::from("Hello, World!")); // /// // `Option::map` takes self *by value*, consuming `maybe_some_string` // /// let maybe_some_len = maybe_some_string.map(|s| s.len()); // /// // /// assert_eq!(maybe_some_len, Some(13)); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> { // match self { // Some(x) => Some(f(x)), // None => None // } // } // // /// Applies a function to the contained value (if any), // /// or returns a `default` (if not). // /// // /// # Examples // /// // /// ``` // /// let x = Some("foo"); // /// assert_eq!(x.map_or(42, |v| v.len()), 3); // /// // /// let x: Option<&str> = None; // /// assert_eq!(x.map_or(42, |v| v.len()), 42); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U { // match self { // Some(t) => f(t), // None => default, // } // } // // /// Applies a function to the contained value (if any), // /// or computes a `default` (if not). // /// // /// # Examples // /// // /// ``` // /// let k = 21; // /// // /// let x = Some("foo"); // /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); // /// // /// let x: Option<&str> = None; // /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { // match self { // Some(t) => f(t), // None => default() // } // } // // /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to // /// `Ok(v)` and `None` to `Err(err)`. // /// // /// # Examples // /// // /// ``` // /// # #![feature(core)] // /// let x = Some("foo"); // /// assert_eq!(x.ok_or(0), Ok("foo")); // /// // /// let x: Option<&str> = None; // /// assert_eq!(x.ok_or(0), Err(0)); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn ok_or<E>(self, err: E) -> Result<T, E> { // match self { // Some(v) => Ok(v), // None => Err(err), // } // } // // /// Transforms the `Option<T>` into a `Result<T, E>`, mapping `Some(v)` to // /// `Ok(v)` and `None` to `Err(err())`. // /// // /// # Examples // /// // /// ``` // /// # #![feature(core)] // /// let x = Some("foo"); // /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); // /// // /// let x: Option<&str> = None; // /// assert_eq!(x.ok_or_else(|| 0), Err(0)); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn ok_or_else<E, F: FnOnce() -> E>(self, err: F) -> Result<T, E> { // match self { // Some(v) => Ok(v), // None => Err(err()), // } // } // // ///////////////////////////////////////////////////////////////////////// // // Iterator constructors // ///////////////////////////////////////////////////////////////////////// // // /// Returns an iterator over the possibly contained value. // /// // /// # Examples // /// // /// ``` // /// let x = Some(4); // /// assert_eq!(x.iter().next(), Some(&4)); // /// // /// let x: Option<u32> = None; // /// assert_eq!(x.iter().next(), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn iter(&self) -> Iter<T> { // Iter { inner: Item { opt: self.as_ref() } } // } // // /// Returns a mutable iterator over the possibly contained value. // /// // /// # Examples // /// // /// ``` // /// # #![feature(core)] // /// let mut x = Some(4); // /// match x.iter_mut().next() { // /// Some(&mut ref mut v) => *v = 42, // /// None => {}, // /// } // /// assert_eq!(x, Some(42)); // /// // /// let mut x: Option<u32> = None; // /// assert_eq!(x.iter_mut().next(), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn iter_mut(&mut self) -> IterMut<T> { // IterMut { inner: Item { opt: self.as_mut() } } // } // // ///////////////////////////////////////////////////////////////////////// // // Boolean operations on the values, eager and lazy // ///////////////////////////////////////////////////////////////////////// // // /// Returns `None` if the option is `None`, otherwise returns `optb`. // /// // /// # Examples // /// // /// ``` // /// let x = Some(2); // /// let y: Option<&str> = None; // /// assert_eq!(x.and(y), None); // /// // /// let x: Option<u32> = None; // /// let y = Some("foo"); // /// assert_eq!(x.and(y), None); // /// // /// let x = Some(2); // /// let y = Some("foo"); // /// assert_eq!(x.and(y), Some("foo")); // /// // /// let x: Option<u32> = None; // /// let y: Option<&str> = None; // /// assert_eq!(x.and(y), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn and<U>(self, optb: Option<U>) -> Option<U> { // match self { // Some(_) => optb, // None => None, // } // } // // /// Returns `None` if the option is `None`, otherwise calls `f` with the // /// wrapped value and returns the result. // /// // /// Some languages call this operation flatmap. // /// // /// # Examples // /// // /// ``` // /// fn sq(x: u32) -> Option<u32> { Some(x * x) } // /// fn nope(_: u32) -> Option<u32> { None } // /// // /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); // /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); // /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); // /// assert_eq!(None.and_then(sq).and_then(sq), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> { // match self { // Some(x) => f(x), // None => None, // } // } // // /// Returns the option if it contains a value, otherwise returns `optb`. // /// // /// # Examples // /// // /// ``` // /// let x = Some(2); // /// let y = None; // /// assert_eq!(x.or(y), Some(2)); // /// // /// let x = None; // /// let y = Some(100); // /// assert_eq!(x.or(y), Some(100)); // /// // /// let x = Some(2); // /// let y = Some(100); // /// assert_eq!(x.or(y), Some(2)); // /// // /// let x: Option<u32> = None; // /// let y = None; // /// assert_eq!(x.or(y), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn or(self, optb: Option<T>) -> Option<T> { // match self { // Some(_) => self, // None => optb // } // } // // /// Returns the option if it contains a value, otherwise calls `f` and // /// returns the result. // /// // /// # Examples // /// // /// ``` // /// fn nobody() -> Option<&'static str> { None } // /// fn vikings() -> Option<&'static str> { Some("vikings") } // /// // /// assert_eq!(Some("barbarians").or_else(vikings), Some("barbarians")); // /// assert_eq!(None.or_else(vikings), Some("vikings")); // /// assert_eq!(None.or_else(nobody), None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> { // match self { // Some(_) => self, // None => f() // } // } // // ///////////////////////////////////////////////////////////////////////// // // Misc // ///////////////////////////////////////////////////////////////////////// // // /// Takes the value out of the option, leaving a `None` in its place. /// // /// # Examples // /// // /// ``` // /// let mut x = Some(2); // /// x.take(); // /// assert_eq!(x, None); // /// // /// let mut x: Option<u32> = None; // /// x.take(); // /// assert_eq!(x, None); // /// ``` // #[inline] // #[stable(feature = "rust1", since = "1.0.0")] // pub fn take(&mut self) -> Option<T> { // mem::replace(self, None) // } // // /// Converts from `Option<T>` to `&[T]` (without copying) // #[inline] // #[unstable(feature = "as_slice", since = "unsure of the utility here")] // pub fn as_slice<'a>(&'a self) -> &'a [T] { // match *self { // Some(ref x) => slice::ref_slice(x), // None => { // let result: &[_] = &[]; // result // } // } // } // } type T = u32; type U = T; struct F; type Args = (T,); impl FnOnce<Args> for F { type Output = Option<U>; extern "rust-call" fn call_once(self, (arg,): Args) -> Self::Output { Some::<U>(arg * arg) } } impl Clone for F { fn clone(&self) -> Self { F } } fn err(_: T) -> Option<U> { None::<U> } #[test] fn and_then_test1() { let x: Option<T> = Some::<T>(2); let f: F = F; let y: Option<U> = x.and_then::<U, F>(f.clone()); assert_eq!(y, Some::<U>(4)); let z: Option<U> = y.and_then::<U, F>(f); assert_eq!(z, Some::<U>(16)); } #[test] fn and_then_test2() { let x: Option<T> = Some::<T>(2); let f: F = F; let y: Option<U> = x.and_then::<U, F>(f); assert_eq!(y, Some::<U>(4)); let z: Option<U> = y.and_then::<U, _>(err); assert_eq!(z, None::<U>); } #[test] fn and_then_test3() { let x: Option<T> = Some::<T>(2); let f: F = F; let y: Option<U> = x.and_then::<U, _>(err); let z: Option<U> = y.and_then::<U, F>(f); assert_eq!(z, None::<U>); } #[test] fn and_then_test4() { let x: Option<T> = Some::<T>(2); let y: Option<U> = x.and_then::<U, _>(err); let z: Option<U> = y.and_then::<U, _>(err); assert_eq!(z, None::<U>); } #[test] fn and_then_test5() { let x: Option<T> = None::<T>; let f: F = F; let y: Option<U> = x.and_then::<U, F>(f.clone()); let z: Option<U> = y.and_then::<U, F>(f); assert_eq!(z, None::<U>); } #[test] fn and_then_test6() { let x: Option<T> = None::<T>; let f: F = F; let y: Option<U> = x.and_then::<U, F>(f); let z: Option<U> = y.and_then::<U, _>(err); assert_eq!(z, None::<U>); } #[test] fn and_then_test7() { let x: Option<T> = None::<T>; let f: F = F; let y: Option<U> = x.and_then::<U, _>(err); let z: Option<U> = y.and_then::<U, F>(f); assert_eq!(z, None::<U>); } #[test] fn and_then_test8() { let x: Option<T> = None::<T>; let y: Option<U> = x.and_then::<U, _>(err); let z: Option<U> = y.and_then::<U, _>(err); assert_eq!(z, None::<U>); } }<|fim▁end|>
// /// assert!(v == ["Dirt"]); // /// }
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from setuptools import setup NAME = "apicaller" DESCRIPTION = "APICaller makes the creating API client library easier." AUTHOR = "Jan Češpivo" AUTHOR_EMAIL = "[email protected]" URL = "https://github.com/cespivo/apicaller" VERSION = '0.1.2a' setup( name=NAME, version=VERSION, description=DESCRIPTION, author=AUTHOR, author_email=AUTHOR_EMAIL, license="Apache 2.0", url=URL, py_modules=['apicaller'], classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment',<|fim▁hole|> 'Topic :: Internet :: WWW/HTTP', ], install_requires=[ "requests>=2.4.3", ], )<|fim▁end|>
'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python',
<|file_name|>VelocityOverTime.py<|end_file_name|><|fim▁begin|># -*- coding: Latin-1 -*- """ @file VelocityOverTime.py @author Sascha Krieg @author Daniel Krajzewicz @author Michael Behrisch @date 2008-05-29 Shows the velocityCurve of the chosen taxi for all available sources, thereby the time duration per Edge is apparent. SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/ Copyright (C) 2008-2013 DLR (http://www.dlr.de/) and contributors All rights reserved """ from pylab import * import profile import util.Path as path import util.Reader as reader from cPickle import load from analysis.Taxi import * from matplotlib.collections import LineCollection from matplotlib.colors import colorConverter #global vars WEE=True #=withoutEmptyEdges decide which analysis file should be used edgeDict={} taxis=[] def main(): print "start program" global taxis, edgeDict #decide if you want to save charts for every taxi or show a single one all=False; taxiId="316_3" #load data edgeDict=load(open(path.edgeLengthDict,'r')) taxis=reader.readAnalysisInfo(WEE) #reader.readEdgesLength() if all: plotAllTaxis() else: plotIt(taxiId) show() print "end" def plotAllTaxis(): """plot all taxis to an folder."""<|fim▁hole|> #kind of progress bar :-) allT=len(taxis) lastProz=0 for i in range(5,105,5): s="%02d" %i print s, print "%" for i in range(allT): actProz=(100*i/allT) if actProz!=lastProz and actProz%5==0: print "**", lastProz=actProz if plotIt(taxis[i].id)!=-1: savefig(path.vOverTimeDir+"taxi_"+str(taxis[i].id)+".png", format="png") close() #close the figure def fetchData(taxiId): """fetch the data for the given taxi""" route=[[],[],[],[]] #route of the taxi (edge, length, edgeSimFCD(to find doubles)) values=[[],[],[],[]] #x,y1,x2,y2 (position, vFCD,vSIMFCD) actLen=0 x=0 def getTime(s,v): if v==0: return 0 return s/(v/3.6) for step in taxis[taxis.index(taxiId)].getSteps(): if step.source==SOURCE_FCD or step.source==SOURCE_SIMFCD: routeLen=edgeDict[step.edge] #save the simFCD infos in apart Lists if step.source==SOURCE_SIMFCD and len(values[2])<=0: x=2 actLen=0 if len(route[0+x])>0 and step.edge==route[0+x][-1]: #print step.edge values[1+x][-1]=(values[1+x][-1]+step.speed)/2.0 values[1+x][-2]=values[1+x][-1] else: #start point of route values[0+x].append(actLen) values[1+x].append(step.speed) actLen+=getTime(routeLen,step.speed) print "l ",actLen," rL ",routeLen," s ",step.speed route[0+x].append(step.edge) #label route[1+x].append(actLen) #location #end point of route values[0+x].append(actLen) values[1+x].append(step.speed) return route,values def plotIt(taxiId): """draws the chart""" width=12 #1200px height=9 #900px #fetch data route,values=fetchData(taxiId) #check if a route exists for this vehicle if len(route[1])<1 or len(route[3])<1: return -1 #make nice labels maxRoute=max((route[1][-1]),route[3][-1]) minDist=(maxRoute/(width-4.5)) def makethemNice(source=SOURCE_FCD): """create labels of the x-Axis for the FCD and simFCD chart""" if source==SOURCE_FCD: label=0; loc=1 elif source==SOURCE_SIMFCD: label=2; loc=3 else: assert False lastShown=route[loc][0] for i in range(len(route[label])): if i==0 or i==len(route[label])-1: route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] elif route[loc][i]-lastShown>minDist: #if distance between last Label location and actual location big enough route[label][i]=str(int(round(route[loc][i])))+"\n"+route[label][i] lastShown=route[loc][i] else: route[label][i]="" if route[loc][-1]-lastShown<minDist: #check if the last shown element troubles the last route[label][route[loc].index(lastShown)]="" makethemNice(SOURCE_FCD) makethemNice(SOURCE_SIMFCD) #plot the results fig=figure(figsize=(width,height), dpi=96) subplot(211) title(U"Geschwindigkeit \u00FCber Zeit pro Kante") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[1],route[0]) plot(values[0],values[1], label='FCD') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) subplot(212) xlabel("\n\nt (s) unterteilt in Routenabschnitte (Kanten)\n\n") ylabel("v (km/h)") grid(True) #set the x scale xticks(route[3],route[2]) plot(values[2],values[3], label='simulierte FCD', color='g') legend() #set that the axis axis([axis()[0],maxRoute,0,max(max(values[1]),max(values[3]))+10]) return 1 #start the program #profile.run('main()') main()<|fim▁end|>
<|file_name|>version.go<|end_file_name|><|fim▁begin|>// Copyright 2016 <chaishushan{AT}gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package ptyy<|fim▁hole|><|fim▁end|>
// 数据版本号 const DataVersion = "20160519"
<|file_name|>xtrabytes_es_DO.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="es_DO" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;hackcoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin Developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The hackcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation> Este es un software experimental. Distribuido bajo la licencia MIT/X11, vea el archivo adjunto COPYING o http://www.opensource.org/licenses/mit-license.php. Este producto incluye software desarrollado por OpenSSL Project para su uso en el OpenSSL Toolkit (http://www.openssl.org/) y software criptográfico escrito por Eric Young ([email protected]) y el software UPnP escrito por Thomas Bernard.</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Haga doble clic para editar una dirección o etiqueta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crear una nueva dirección</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiar la dirección seleccionada al portapapeles del sistema</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your hackcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar dirección</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Borrar de la lista la dirección seleccionada</translation> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Eliminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;etiqueta</translation> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Archivos de columnas separadas por coma (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de contraseña</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Introducir contraseña</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nueva contraseña</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita la nueva contraseña</translation> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduzca la nueva contraseña de la cartera.&lt;br/&gt;Por favor elija una con &lt;b&gt;10 o más caracteres aleatorios&lt;/b&gt;, u &lt;b&gt;ocho o más palabras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifrar la cartera</translation> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Esta operación requiere su contraseña para desbloquear la cartera</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear cartera</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Esta operación requiere su contraseña para descifrar la cartera.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Descifrar la certare</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambiar contraseña</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introduzca la contraseña anterior de la cartera y la nueva. </translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar cifrado de la cartera</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>¿Seguro que desea cifrar su monedero?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation>Monedero cifrado</translation> </message> <message> <location line="-58"/> <source>hackcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Ha fallado el cifrado del monedero</translation> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation>Las contraseñas no coinciden.</translation> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation>Ha fallado el desbloqueo del monedero</translation> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La contraseña introducida para descifrar el monedero es incorrecta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Ha fallado el descifrado del monedero</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Se ha cambiado correctamente la contraseña del monedero.</translation> </message> </context> <context> <name>XtraBYtesGUI</name> <message> <location filename="../xtrabytesgui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation>Firmar &amp;mensaje...</translation> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation>Sincronizando con la red…</translation> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation>&amp;Vista general</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar vista general del monedero</translation> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Transacciones</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Examinar el historial de transacciones</translation> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation>&amp;Salir</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Salir de la aplicación</translation> </message> <message> <location line="+6"/> <source>Show information about hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Acerca de &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar información acerca de Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opciones...</translation> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifrar monedero…</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>Copia de &amp;respaldo del monedero...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambiar la contraseña…</translation> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation>Copia de seguridad del monedero en otra ubicación</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation>Ventana de &amp;depuración</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir la consola de depuración y diagnóstico</translation> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensaje...</translation> </message> <message> <location line="-202"/> <source>hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Monedero</translation> </message> <message> <location line="+180"/> <source>&amp;About hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar/ocultar</translation> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Archivo</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation>&amp;Configuración</translation> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>A&amp;yuda</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation>Barra de pestañas</translation> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+0"/> <location line="+60"/> <source>hackcoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to hackcoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About hackcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about hackcoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Actualizado</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation>Actualizando...</translation> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation>Transacción enviada</translation> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation>Transacción entrante</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Fecha: %1 Cantidad: %2 Tipo: %3 Dirección: %4 </translation> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid hackcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;desbloqueado&lt;/b&gt;</translation> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>El monedero está &lt;b&gt;cifrado&lt;/b&gt; y actualmente &lt;b&gt;bloqueado&lt;/b&gt;</translation> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../xtrabytes.cpp" line="+109"/> <source>A fatal error occurred. hackcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation>Alerta de red</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+48"/> <source>Amount:</source> <translation>Cuantía:</translation> </message> <message> <location line="+32"/> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <location line="+48"/> <source>Fee:</source> <translation>Tasa:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Envío pequeño:</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation>no</translation> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation>Después de tasas:</translation> </message> <message> <location line="+35"/> <source>Change:</source> <translation>Cambio:</translation> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation>(des)selecciona todos</translation> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation>Modo arbol</translation> </message> <message> <location line="+16"/> <source>List mode</source> <translation>Modo lista</translation> </message> <message> <location line="+45"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation>Confirmaciones</translation> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <location line="+5"/> <source>Priority</source> <translation>Prioridad</translation> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation>Copiar dirección</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation>Copiar cantidad</translation> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation>Copiar identificador de transacción</translation> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation>Copiar cantidad</translation> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation>Copiar donación</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copiar después de aplicar donación</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copiar prioridad</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copiar envío pequeño</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copiar cambio</translation> </message> <message> <location line="+317"/> <source>highest</source> <translation>lo más alto</translation> </message> <message> <location line="+1"/> <source>high</source> <translation>alto</translation> </message> <message> <location line="+1"/> <source>medium-high</source> <translation>medio-alto</translation> </message> <message> <location line="+1"/> <source>medium</source> <translation>medio</translation> </message> <message> <location line="+4"/> <source>low-medium</source> <translation>bajo-medio</translation> </message> <message> <location line="+1"/> <source>low</source> <translation>bajo</translation> </message> <message> <location line="+1"/> <source>lowest</source> <translation>lo más bajo</translation> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation>si</translation> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation>Enviar desde %1 (%2)</translation> </message> <message> <location line="+1"/> <source>(change)</source> <translation>(cambio)</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Dirección</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etiqueta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Dirección</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation>Nueva dirección de recepción</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nueva dirección de envío</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar dirección de recepción</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar dirección de envío</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>La dirección introducida &quot;%1&quot; ya está presente en la libreta de direcciones.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid hackcoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>No se pudo desbloquear el monedero.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Ha fallado la generación de la nueva clave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>hackcoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opciones</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Comisión de &amp;transacciones</translation> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start hackcoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start hackcoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Red</translation> </message> <message> <location line="+6"/> <source>Automatically open the hackcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear el puerto usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the hackcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Dirección &amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Puerto:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Puerto del servidor proxy (ej. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versión SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versión del proxy SOCKS (ej. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Ventana</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar a la bandeja en vez de a la barra de tareas</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimizar en lugar de salir de la aplicación al cerrar la ventana. Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar al cerrar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Interfaz</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>I&amp;dioma de la interfaz de usuario</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting hackcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>Mostrar las cantidades en la &amp;unidad:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show hackcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostrar las direcciones en la lista de transacciones</translation> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation>Mostrar o no características de control de moneda</translation> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Aceptar</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>predeterminado</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting hackcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>La dirección proxy indicada es inválida.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Desde</translation> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the hackcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>No confirmado(s):</translation> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Monedero</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation>Su balance actual gastable</translation> </message> <message> <location line="+71"/> <source>Immature:</source> <translation>No disponible:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Saldo recién minado que aún no está disponible.</translation> </message> <message> <location line="+20"/> <source>Total:</source> <translation>Total:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation>Su balance actual total</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Movimientos recientes&lt;/b&gt;</translation> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>desincronizado</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nombre del cliente</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versión del cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Información</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Utilizando la versión OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Hora de inicio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Red</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de conexiones</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadena de bloques</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de bloques</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Bloques totales estimados</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Hora del último bloque</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the hackcoin-Qt help message to get a list with possible hackcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Fecha de compilación</translation> </message> <message> <location line="-104"/> <source>hackcoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>hackcoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Archivo de registro de depuración</translation> </message> <message> <location line="+7"/> <source>Open the hackcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Borrar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the hackcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use las flechas arriba y abajo para navegar por el historial y &lt;b&gt;Control+L&lt;/b&gt; para limpiar la pantalla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Escriba &lt;b&gt;help&lt;/b&gt; para ver un resumen de los comandos disponibles.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar monedas</translation> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation>Características de control de la moneda</translation> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation>Entradas...</translation> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation>Seleccionado automaticamente</translation> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation>Fondos insuficientes!</translation> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation>Cantidad:</translation> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation>Bytes:</translation> </message> <message> <location line="+51"/> <source>Amount:</source> <translation>Cuantía:</translation> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 hack</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation>Prioridad:</translation> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation>Tasa:</translation> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation>Envío pequeño:</translation> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation>Después de tasas:</translation> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation>Enviar a múltiples destinatarios de una vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Añadir &amp;destinatario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Limpiar &amp;todo</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+16"/> <source>123.456 hack</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmar el envío</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation>Copiar cantidad</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar cuantía</translation> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation>Copiar donación</translation> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation>Copiar después de aplicar donación</translation> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation>Copiar bytes</translation> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation>Copiar prioridad</translation> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation>Copiar envío pequeño</translation> </message> <message> <location line="+1"/> <source>Copy change</source> <translation>Copiar Cambio</translation> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirmar el envío de monedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation>La dirección de recepción no es válida, compruébela de nuevo.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>La cantidad por pagar tiene que ser mayor de 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>La cantidad sobrepasa su saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation><|fim▁hole|> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(sin etiqueta)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Ca&amp;ntidad:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar a:</translation> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation>Etiquete esta dirección para añadirla a la libreta</translation> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation>&amp;Etiqueta:</translation> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firmas - Firmar / verificar un mensaje</translation> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation>&amp;Firmar mensaje</translation> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Pegar dirección desde portapapeles</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Introduzca el mensaje que desea firmar aquí</translation> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar la firma actual al portapapeles del sistema</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation>Limpiar todos los campos de la firma de mensaje</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpiar &amp;todo</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar mensaje</translation> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified hackcoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation>Limpiar todos los campos de la verificación de mensaje</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a hackcoin address (e.g. hackcoinfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Haga clic en &quot;Firmar mensaje&quot; para generar la firma</translation> </message> <message> <location line="+3"/> <source>Enter hackcoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>La dirección introducida es inválida.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Verifique la dirección e inténtelo de nuevo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>La dirección introducida no corresponde a una clave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Se ha cancelado el desbloqueo del monedero. </translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>No se dispone de la clave privada para la dirección introducida.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Ha fallado la firma del mensaje.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensaje firmado.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>No se puede decodificar la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Compruebe la firma e inténtelo de nuevo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma no coincide con el resumen del mensaje.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>La verificación del mensaje ha fallado.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensaje verificado.</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/fuera de línea</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/no confirmado</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmaciones</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Fuente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>dirección propia</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etiqueta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>no aceptada</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Comisión de transacción</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Cantidad neta</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensaje</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentario</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Identificador de transacción</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Información de depuración</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transacción</translation> </message> <message> <location line="+5"/> <source>Inputs</source> <translation>entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation>, todavía no se ha sido difundido satisfactoriamente</translation> </message> <message> <location line="+35"/> <source>unknown</source> <translation>desconocido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalles de transacción</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta ventana muestra información detallada sobre la transacción</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation>Abierto hasta %1</translation> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmado (%1 confirmaciones)</translation> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generado pero no aceptado</translation> </message> <message> <location line="+42"/> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recibidos de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pago propio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nd)</translation> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Fecha y hora en que se recibió la transacción.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transacción.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Dirección de destino de la transacción.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Cantidad retirada o añadida al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation>Todo</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoy</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mes</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mes pasado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este año</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Rango...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recibido con</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviado a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A usted mismo</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Otra</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Introduzca una dirección o etiqueta que buscar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Cantidad mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar dirección</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar etiqueta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar cuantía</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar identificador de transacción</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar etiqueta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalles de la transacción</translation> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Archivos de columnas separadas por coma (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmado</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Fecha</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etiqueta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Dirección</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Cantidad</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Rango:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>para</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>xtrabytes-core</name> <message> <location filename="../xtrabytesstrings.cpp" line="+33"/> <source>hackcoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation>Uso:</translation> </message> <message> <location line="+1"/> <source>Send command to -server or hackcoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation>Muestra comandos </translation> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation>Recibir ayuda para un comando </translation> </message> <message> <location line="+2"/> <source>Options:</source> <translation>Opciones: </translation> </message> <message> <location line="+2"/> <source>Specify configuration file (default: hackcoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: hackcoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation>Especificar archivo de monedero (dentro del directorio de datos)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar directorio para los datos</translation> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantener como máximo &lt;n&gt; conexiones a pares (predeterminado: 125)</translation> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation>Especifique su propia dirección pública</translation> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 86400)</translation> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceptar comandos consola y JSON-RPC </translation> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation>Ejecutar en segundo plano como daemon y aceptar comandos </translation> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation>Usar la red de pruebas </translation> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</translation> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</translation> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong hackcoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</translation> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation>Opciones de creación de bloques:</translation> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation>Conectar sólo a los nodos (o nodo) especificados</translation> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Búfer de recepción máximo por conexión, &lt;n&gt;*1000 bytes (predeterminado: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Búfer de recepción máximo por conexión, , &lt;n&gt;*1000 bytes (predeterminado: 1000)</translation> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Conectarse solo a nodos de la red &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the XtraBYtes Wiki for SSL setup instructions)</source> <translation>Opciones SSL: (ver la XtraBYtes Wiki para instrucciones de configuración SSL)</translation> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation>Nombre de usuario para las conexiones JSON-RPC </translation> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupto. Ha fallado la recuperación.</translation> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation>Contraseña para las conexiones JSON-RPC </translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=hackcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;hackcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir conexiones JSON-RPC desde la dirección IP especificada </translation> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comando al nodo situado en &lt;ip&gt; (predeterminado: 127.0.0.1) </translation> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation>Actualizar el monedero al último formato</translation> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Ajustar el número de claves en reserva &lt;n&gt; (predeterminado: 100) </translation> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para las conexiones JSON-RPC </translation> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificado del servidor (predeterminado: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Clave privada del servidor (predeterminado: server.pem) </translation> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation>Este mensaje de ayuda </translation> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. hackcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation>Cargando direcciones...</translation> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Error al cargar wallet.dat: el monedero está dañado</translation> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of hackcoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart hackcoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation>Error al cargar wallet.dat</translation> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Dirección -proxy inválida: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>La red especificada en -onlynet &apos;%s&apos; es desconocida</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Solicitada versión de proxy -socks desconocida: %i</translation> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>No se puede resolver la dirección de -bind: &apos;%s&apos;</translation> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>No se puede resolver la dirección de -externalip: &apos;%s&apos;</translation> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Cantidad inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation>Cuantía no válida</translation> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation>Fondos insuficientes</translation> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation>Cargando el índice de bloques...</translation> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. hackcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation>Cargando monedero...</translation> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation>No se puede rebajar el monedero</translation> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation>No se puede escribir la dirección predeterminada</translation> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation>Reexplorando...</translation> </message> <message> <location line="+5"/> <source>Done loading</source> <translation>Generado pero no aceptado</translation> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation>Para utilizar la opción %s</translation> </message> <message> <location line="+14"/> <source>Error</source> <translation>Error</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Tiene que establecer rpcpassword=&lt;contraseña&gt; en el fichero de configuración: ⏎ %s ⏎ Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation> </message> </context> </TS><|fim▁end|>
</message> <message>
<|file_name|>copymapping.go<|end_file_name|><|fim▁begin|>package batch type CopyMapping struct {<|fim▁hole|><|fim▁end|>
MemberEmail string `json:"member_email"` SrcPath string `json:"src_path"` DstPath string `json:"dst_path"` }
<|file_name|>0004_add_sqlivrbackend_sqlkookoobackend.py<|end_file_name|><|fim▁begin|>from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('sms', '0003_add_backend_models'), ] <|fim▁hole|> operations = [ migrations.CreateModel( name='SQLIVRBackend', fields=[ ], options={ 'proxy': True, }, bases=('sms.sqlmobilebackend',), ), migrations.CreateModel( name='SQLKooKooBackend', fields=[ ], options={ 'proxy': True, }, bases=('sms.sqlivrbackend',), ), ]<|fim▁end|>
<|file_name|>twoNode_cfoLogging.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from datetime import * from numpy import log10, linspace import time import sys mods = [[2,2,2100,78-1]] pktLens = [1412]; #range(1412, 91, -240) #[1440:-120:120]-28 time_on = 5*60 time_off = 0 numItrs = 1 fileName_offset = 50 #cfo = 2**20 cfo = 2**17 txGain = 55 minChanMag_D = 20 class ScriptMaster: def startup(self): stderr_log = open("exp_err.log", "a") stderr_log.write("\r\n####################################################################\r\n") stderr_log.write("%s started at %s\r\n" % (sys.argv[0], datetime.now())) stderr_log.write("####################################################################\r\n\r\n") stderr_log.flush() sys.stderr = stderr_log er_log = MyDataLogger('results/twoNode_realCFO_v%d_logging.txt' % (fileName_offset)) er_log.log("%s" % (datetime.now()) ) er_log.log("CFO: %d, Time on: %d, time off: %d, numIttrs: %d, fn_offset: %d\r\n" % (cfo, time_on, time_off, numItrs, fileName_offset)) er_log.log("Continuous test of actual CFO on emulator kits\r\n") registerWithServer() nodes = dict() #WARP Nodes createNode(nodes, Node(0, NODE_PCAP)) createNode(nodes, Node(2, NODE_PCAP)) #BER processor "node" createNode(nodes, Node(98, NODE_PCAP)) #PHY logger connectToServer(nodes) controlStruct = ControlStruct() nodes[0].addStruct('controlStruct', controlStruct) nodes[2].addStruct('controlStruct', controlStruct) phyCtrl0 = PHYctrlStruct() phyCtrl1 = PHYctrlStruct() nodes[0].addStruct('phyCtrlStruct', phyCtrl0) nodes[2].addStruct('phyCtrlStruct', phyCtrl1) cmdStructStart = CommandStruct(COMMANDID_STARTTRIAL, 0) nodes[0].addStruct('cmdStructStart', cmdStructStart) cmdStructStop = CommandStruct(COMMANDID_STOPTRIAL, 0) nodes[0].addStruct('cmdStructStop', cmdStructStop) cmdStructResetPER = CommandStruct(COMMANDID_RESET_PER, 0) nodes[0].addStruct('cmdStructResetPER', cmdStructResetPER) nodes[2].addStruct('cmdStructResetPER', cmdStructResetPER) perStruct0 = ObservePERStruct() perStruct1 = ObservePERStruct() nodes[0].addStruct('perStruct', perStruct0) nodes[2].addStruct('perStruct', perStruct1) logParams = LogParams() nodes[98].addStruct('logParams', logParams) sendRegistrations(nodes) controlStruct.packetGeneratorPeriod = mods[0][2] controlStruct.packetGeneratorLength = pktLens[0] controlStruct.channel = 9 controlStruct.txPower = txGain controlStruct.modOrderHeader = mods[0][0] controlStruct.modOrderPayload = mods[0][1] #PHYCtrol params: #param0: txStartOut delay #param1: artificial txCFO #param2: minPilotChanMag #param3: # [0-0x01]: PHYCTRL_BER_EN: enable BER reporting # [1-0x02]: PHYCTRL_CFO_EN: enable CFO reporting # [2-0x04]: PHYCTRL_PHYDUMP_EN: enable Rx PHY dumping # [3-0x08]: PHYTRCL_EXTPKTDET_EN: use only ext pkt det # [4-0x10]: PHYCTRL_COOP_EN: 0=nonCoop, 1=coopMode # [5-0x20]: PHYCTRL_CFO_CORR_EN: 0=bypass CFO correction, 1=enable CFO correction # [6-0x40]: PHYCTRL_SWAP_ANT: 0=AntA, 1=AntA_Swapped #param4: # [ 7:0]: src re-Tx delay # [ 7:0]: relay AF Tx delay (only used when in COOP_TESTING) # [15:8]: relay DF Tx delay (only used when in COOP_TESTING) #param5: (0 ignores) # [17: 0]: AGC IIR coef FB #param6: (0 ignores) # [31:16]: H_BA minEstMag (UFix16_15) # [15: 0]: H_AA minEstMag (UFix16_15) #param7: (0 ignores) # [27:16]: AF blank stop # [11: 0]: AF blank start #param8: (0 ignores) # [17: 0]: AGC IIR coef Gain #param9: (Tx pkt types) # [31: 0]: OR'd combination of PHYCTRL_TX_* phyCtrl0.param0 = 32+12 phyCtrl0.param1 = cfo #(2**19 ~ 1.2e-4) phyCtrl0.param2 = 0xFFF # phyCtrl0.param3 = (PHYCTRL_COOP_EN | PHYCTRL_BER_EN) phyCtrl0.param3 = (0) #PHYCTRL_COOP_EN) # phyCtrl0.param4 = (251-2) #v21 timing; #######reTxDly/FFToffset: 251/12, 249/10 phyCtrl0.param4 = 255 #v22 timing phyCtrl0.param5 = 0 phyCtrl0.param6 = 0 phyCtrl0.param7 = 0 phyCtrl0.param8 = 0 # phyCtrl0.param9 = (PHYCTRL_TX_NC | PHYCTRL_TX_DF | PHYCTRL_TX_AF | PHYCTRL_TX_AFGH | PHYCTRL_TX_DFGH | PHYCTRL_TX_NCMHOP) phyCtrl0.param9 = (PHYCTRL_TX_NC) phyCtrl1.param0 = 0 phyCtrl1.param1 = 0 phyCtrl1.param2 = minChanMag_D # phyCtrl1.param3 = (PHYCTRL_CFO_CORR_EN | PHYCTRL_PHYDUMP_EN) phyCtrl1.param3 = (PHYCTRL_PHYDUMP_EN) phyCtrl1.param4 = 0 phyCtrl1.param5 = 0x20000 phyCtrl1.param6 = 1000 | (1000<<16) phyCtrl1.param7 = 0 phyCtrl1.param8 = 0x20000 phyCtrl1.param9 = 0 nodes[0].sendToNode('phyCtrlStruct') nodes[2].sendToNode('phyCtrlStruct') nodes[0].sendToNode('controlStruct') nodes[2].sendToNode('controlStruct') nodes[0].sendToNode('cmdStructResetPER') nodes[2].sendToNode('cmdStructResetPER') trialInd = -1 #Increment before first trial, which should be trialNum=0 pktLen = pktLens[0]; #Experiment Loops for ittr in range(1,numItrs+1): print("Starting iteration %d of %d at %s" % (ittr, numItrs, datetime.now().strftime("%H:%M:%S"))) trialInd += 1 #Stop any traffic that might be running nodes[0].sendToNode('cmdStructStop') logParams.fileSuffix = fileName_offset+trialInd logParams.param0 = ittr logParams.param1 = 0 logParams.param2 = 0 logParams.param3 = 0 nodes[98].sendToNode('logParams') #Reset the PER counters at all nodes nodes[0].sendToNode('cmdStructResetPER') nodes[2].sendToNode('cmdStructResetPER') #Start the trial nodes[0].sendToNode('cmdStructStart') #Run until minTime elapses time.sleep(time_on) nodes[0].sendToNode('cmdStructStop') time.sleep(time_off) if not reactor.running: return print("############################################") print("############# Experiment Done! #############") print("############################################") reactor.callFromThread(reactor.stop) sm = ScriptMaster() stdio.StandardIO(CmdReader()) #if interactive shell is needed factory = WARPnetClient(sm.startup); reactor.connectTCP('localhost', 10101, factory) reactor.run()<|fim▁end|>
from warpnet_framework.warpnet_client import * from warpnet_framework.warpnet_common_params import * from warpnet_experiment_structs import * from twisted.internet import reactor
<|file_name|>CommonRequest$29$1.java<|end_file_name|><|fim▁begin|>package com.ximalaya.ting.android.opensdk.datatrasfer; import com.google.gson.reflect.TypeToken; import com.ximalaya.ting.android.opensdk.model.album.HotAggregation; import java.util.List; class CommonRequest$29$1 extends TypeToken<List<HotAggregation>><|fim▁hole|> /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ximalaya.ting.android.opensdk.datatrasfer.CommonRequest.29.1 * JD-Core Version: 0.6.0 */<|fim▁end|>
{ }
<|file_name|>mock_transport.ts<|end_file_name|><|fim▁begin|>// tslint:disable:no-console import chalk from "chalk"; import { EventEmitter } from "events"; import { assert } from "node-opcua-assert"; import { display_trace_from_this_projet_only, hexDump, make_debugLog } from "node-opcua-debug"; import { analyseExtensionObject } from "node-opcua-packet-analyzer"; import { GetEndpointsResponse } from "node-opcua-service-endpoints"; import { CloseSecureChannelResponse, OpenSecureChannelResponse } from "node-opcua-service-secure-channel"; import { ActivateSessionResponse, CreateSessionResponse } from "node-opcua-service-session"; import { AcknowledgeMessage } from "node-opcua-transport"; import { DirectTransport } from "node-opcua-transport/dist/test_helpers"; import * as _ from "underscore"; const debugLog = make_debugLog(__filename); export const fakeAcknowledgeMessage = new AcknowledgeMessage({ maxChunkCount: 600000, maxMessageSize: 100000, protocolVersion: 0, receiveBufferSize: 8192, sendBufferSize: 8192, }); export const fakeCloseSecureChannelResponse = new CloseSecureChannelResponse({}); export const fakeOpenSecureChannelResponse = new OpenSecureChannelResponse({ serverProtocolVersion: 0, securityToken: { channelId: 23, createdAt: new Date(), // now revisedLifetime: 30000, tokenId: 1, }, serverNonce: Buffer.from("qwerty") }); export const fakeGetEndpointsResponse = new GetEndpointsResponse({ endpoints: [ { endpointUrl: "fake://localhost:2033/SomeAddress" } ] }); export const fakeCreateSessionResponse = new CreateSessionResponse({}); export const fakeActivateSessionResponse = new ActivateSessionResponse({}); export class MockServerTransport extends EventEmitter { private _replies: any; private _mockTransport: DirectTransport; private _counter: number; constructor(expectedReplies: any) { super(); this._replies = expectedReplies; this._counter = 0; this._mockTransport = new DirectTransport();<|fim▁hole|> this._mockTransport.server.on("data", (data: Buffer) => { let reply = this._replies[this._counter]; this._counter++; if (reply) { if (_.isFunction(reply)) { reply = reply.call(this); // console.log(" interpreting reply as a function" + reply); if (!reply) { return; } } debugLog("\nFAKE SERVER RECEIVED"); debugLog(hexDump(data)); let replies = []; if (reply instanceof Buffer) { replies.push(reply); } else { replies = reply; } assert(replies.length >= 1, " expecting at least one reply " + JSON.stringify(reply)); replies.forEach((reply1: any) => { debugLog("\nFAKE SERVER SEND"); debugLog(chalk.red(hexDump(reply1))); this._mockTransport.server.write(reply1); }); } else { const msg = " MockServerTransport has no more packets to send to client to" + " emulate server responses.... "; console.log(chalk.red.bold(msg)); console.log(chalk.blue.bold(hexDump(data))); display_trace_from_this_projet_only(); analyseExtensionObject(data, 0, 0, {}); this.emit("done"); } }); } }<|fim▁end|>
this._mockTransport.initialize(() => { console.log("initialized"); });
<|file_name|>dbh.py<|end_file_name|><|fim▁begin|>#!/usr/local/bin/python3.4 # dbh.ph debounce hardware """ Pyboard: Switch pins: Y1 or X19 usage: >>> init() >>> loop() """ from pyb import ExtInt,Pin # declare the pin id pinId = 'X19' # interrupt 0 'Y1' # interrupt 6 # itnerrupt mechanics and debounce globals flag= False interCount=0 eObj = None # define ISR def callback(line): global flag flag += 1 def init(): global eObj eObj=ExtInt(pinId, ExtInt.IRQ_FALLING, Pin.PULL_UP, callback) def doFlag (): global flag,interCount print('Flag:',flag,'\tInterCount: ',interCount) flag=0 interCount +=1 def loop(): try: while True: if flag>0: doFlag()<|fim▁hole|><|fim▁end|>
except KeyboardInterrupt: print('Test ended!\nBye ...')
<|file_name|>0009_auto_20170608_0525.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime class Migration(migrations.Migration): dependencies = [ ('ccx', '0008_auto_20170523_0630'),<|fim▁hole|> ] operations = [ migrations.AlterField( model_name='customcourseforedx', name='delivery_mode', field=models.CharField(default=b'IN_PERSON', max_length=255, choices=[(b'IN_PERSON', b'In Person'), (b'ONLINE_ONLY', b'Online')]), ), migrations.AlterField( model_name='customcourseforedx', name='time', field=models.DateTimeField(default=datetime.datetime(2017, 6, 8, 5, 24, 53, 908103)), ), ]<|fim▁end|>
<|file_name|>__init__.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. # """ .. _toaccess: .. program:: toaccess ``toaccess`` ============ This module provides a set of functions meant to provide ease-of-use functionality for interacting with the Traffic Ops API. It provides scripts named :file:`to{method}` where `method` is the name of an HTTP method (in lowercase). Collectively they are referred to as :program:`toaccess` Implemented methods thus far are: - delete - head - get - options - patch - post - put Arguments and Flags ------------------- .. option:: PATH This is the request path. By default, whatever is passed is considered to be relative to :file:`/api/{api-version}/` where ``api-version`` is :option:`--api-version`. This behavior can be disabled by using :option:`--raw-path`. .. option:: DATA An optional positional argument that is a data payload to pass to the Traffic Ops server in the request body. If this is the absolute or relative path to a file, the contents of the file will instead be read and used as the request payload. .. option:: -h, --help Print usage information and exit .. option:: -a API_VERSION, --api-version API_VERSION Specifies the version of the Traffic Ops API that will be used for the request. Has no effect if :option:`--raw-path` is used. (Default: 2.0) .. option:: -f, --full Output the full HTTP exchange including request method line, request headers, request body (if any), response status line, and response headers (as well as the response body, if any). This is equivalent to using :option:`--request-headers`, :option:`--request-payload`, and :option:`--response-headers` at the same time, and those options will have no effect if given. (Default: false) .. option:: -k, --insecure Do not verify SSL certificates - typically useful for making requests to development or testing servers as they frequently have self-signed certificates. (Default: false) .. option:: -p, --pretty Pretty-print any payloads that are output as formatted JSON. Has no effect on plaintext payloads. Uses tab characters for indentation. (Default: false) .. option:: -r, --raw-path Request exactly :option:`PATH`; do not preface the request path with :file:`/api/{api_version}`. This effectively means that :option:`--api-version` will have no effect. (Default: false) .. option:: -v, --version Print version information and exit. .. option:: --request-headers Output the request method line and any and all request headers. (Default: false) .. option:: --request-payload Output the request body if any was sent. Will attempt to pretty-print the body as JSON if :option:`--pretty` is used. (Default: false) .. option:: --response-headers Output the response status line and any and all response headers. (Default: false) .. option:: --to-url URL The :abbr:`FQDN (Fully Qualified Domain Name)` and optionally the port and scheme of the Traffic Ops server. This will override :envvar:`TO_URL`. The format is the same as for :envvar:`TO_URL`. (Default: uses the value of :envvar:`TO_URL`) .. option:: --to-password PASSWORD The password to use when authenticating to Traffic Ops. Overrides :envvar:`TO_PASSWORD`. (Default: uses the value of :envvar:`TO_PASSWORD`) .. option:: --to-user USERNAME The username to use when connecting to Traffic Ops. Overrides :envvar:`TO_USER`. (Default: uses the value of :envvar:`TO_USER`) Environment Variables --------------------- If defined, :program:`toaccess` scripts will use the :envvar:`TO_URL`, :envvar:`TO_USER`, and :envvar`TO_PASSWORD` environment variables to define their connection to and authentication with the Traffic Ops server. Typically, setting these is easier than using the long options :option:`--to-url`, :option:`--to-user`, and :option:`--to-password` on every invocation. Exit Codes ---------- The exit code of a :program:`toaccess` script can sometimes be used by the caller to determine what the result of calling the script was without needing to parse the output. The exit codes used are: 0 The command executed successfully, and the result is on STDOUT. 1 Typically this exit code means that an error was encountered when parsing positional command line arguments. However, this is also the exit code used by most Python interpreters to signal an unhandled exception. 2 Signifies a runtime error that caused the request to fail - this is **not** generally indicative of an HTTP client or server error, but rather an underlying issue connecting to or authenticating with Traffic Ops. This is distinct from an exit code of ``32`` in that the *format* of the arguments was correct, but there was some problem with the *value*. For example, passing ``https://test:`` to :option:`--to-url` will cause an exit code of ``2``, not ``32``. 4 An HTTP client error occurred. The HTTP stack will be printed to stdout as indicated by other options - meaning by default it will only print the response payload if one was given, but will respect options like e.g. :option:`--request-payload` as well as :option:`-p`/:option:`--pretty`. 5 An HTTP server error occurred. The HTTP stack will be printed to stdout as indicated by other options - meaning by default it will only print the response payload if one was given, but will respect options like e.g. :option:`--request-payload` as well as :option:`-p`/:option:`--pretty`. 32 This is the error code emitted by Python's :mod:`argparse` module when the passed arguments could not be parsed successfully. .. note:: The way exit codes ``4`` and ``5`` are implemented is by returning the status code of the HTTP request divided by 100 whenever it is at least 400. This means that if the Traffic Ops server ever started returning e.g. 700 status codes, the exit code of the script would be 7. Module Reference ================ """ import json import logging import os import sys from urllib.parse import urlparse from trafficops.restapi import LoginError, OperationError, InvalidJSONError from trafficops.tosession import TOSession from trafficops.__version__ import __version__ from requests.exceptions import RequestException l = logging.getLogger() l.disabled = True logging.basicConfig(level=logging.CRITICAL+1) def output(r, pretty, request_header, response_header, request_payload, indent = '\t'): """ Prints the passed response object in a format consistent with the other parameters. :param r: The :mod:`requests` response object being printed :param pretty: If :const:`True`, attempt to pretty-print payloads as JSON :param request_header: If :const:`True`, print request line and request headers :param response_header: If :const:`True`, print response line and response headers :param request_payload: If :const:`True`, print the request payload :param indent: An optional number of spaces for pretty-printing indentation (default is the tab character) """ if request_header: print(r.request.method, r.request.path_url, "HTTP/1.1") for h,v in r.request.headers.items(): print("%s:" % h, v) print() if request_payload and r.request.body: try: result = r.request.body if not pretty else json.dumps(json.loads(r.request.body)) except ValueError: result = r.request.body print(result, end="\n\n") if response_header: print("HTTP/1.1", r.status_code, end="") print(" "+r.reason if r.reason else "") for h,v in r.headers.items(): print("%s:" % h, v) print() try: result = r.text if not pretty else json.dumps(r.json(), indent=indent) except ValueError: result = r.text print(result) def parse_arguments(program): """ A common-use function that parses the command line arguments. :param program: The name of the program being run - used for usage informational output :returns: The Traffic Ops HTTP session object, the requested path, any data to be sent, an output format specification, whether or not the path is raw, and whether or not output should be prettified """ from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(prog=program, formatter_class=ArgumentDefaultsHelpFormatter, description="A helper program for interfacing with the Traffic Ops API", epilog=("Typically, one will want to connect and authenticate by defining " "the 'TO_URL', 'TO_USER' and 'TO_PASSWORD' environment variables " "rather than (respectively) the '--to-url', '--to-user' and " "'--to-password' command-line flags. Those flags are only " "required when said environment variables are not defined.\n" "%(prog)s will exit with a success provided a response was " "received and the status code of said response was less than 400. " "The exit code will be 1 if command line arguments cannot be " "parsed or authentication with the Traffic Ops server fails. " "In the event of some unknown error occurring when waiting for a " "response, the exit code will be 2. If the server responds with " "a status code indicating a client or server error, that status " "code will be used as the exit code.")) parser.add_argument("--to-url", type=str, help=("The fully qualified domain name of the Traffic Ops server. Overrides " "'$TO_URL'. The format for both the environment variable and the flag " "is '[scheme]hostname[:port]'. That is, ports should be specified here, " "and they need not start with 'http://' or 'https://'. HTTPS is the " "assumed protocol unless the scheme _is_ provided and is 'http://'.")) parser.add_argument("--to-user", type=str, help="The username to use when connecting to Traffic Ops. Overrides '$TO_USER") parser.add_argument("--to-password", type=str, help="The password to use when authenticating to Traffic Ops. Overrides '$TO_PASSWORD'") parser.add_argument("-k", "--insecure", action="store_true", help="Do not verify SSL certificates") parser.add_argument("-f", "--full", action="store_true", help=("Also output HTTP request/response lines and headers, and request payload. " "This is equivalent to using '--request-headers', '--response-headers' " "and '--request-payload' at the same time.")) parser.add_argument("--request-headers", action="store_true", help="Output request method line and headers") parser.add_argument("--response-headers", action="store_true", help="Output response status line and headers") parser.add_argument("--request-payload", action="store_true", help="Output request payload (will try to pretty-print if '--pretty' is given)") parser.add_argument("-r", "--raw-path", action="store_true", help="Request exactly PATH; it won't be prefaced with '/api/{{api-version}}/") parser.add_argument("-a", "--api-version", type=float, default=2.0, help="Specify the API version to request against") parser.add_argument("-p", "--pretty", action="store_true", help=("Pretty-print payloads as JSON. " "Note that this will make Content-Type headers \"wrong\", in general")) parser.add_argument("-v", "--version", action="version", help="Print version information and exit", version="%(prog)s v"+__version__) parser.add_argument("PATH", help="The path to the resource being requested - omit '/api/2.x'") parser.add_argument("DATA", help=("An optional data string to pass with the request. If this is a " "filename, the contents of the file will be sent instead."), nargs='?') args = parser.parse_args() try: to_host = args.to_url if args.to_url else os.environ["TO_URL"] except KeyError as e: raise KeyError("Traffic Ops hostname not set! Set the TO_URL environment variable or use "\ "'--to-url'.") from e original_to_host = to_host to_host = urlparse(to_host, scheme="https") useSSL = to_host.scheme.lower() == "https" to_port = to_host.port if to_port is None: if useSSL: to_port = 443 else: to_port = 80 to_host = to_host.hostname if not to_host: raise KeyError(f"Invalid URL/host for Traffic Ops: '{original_to_host}'") s = TOSession(to_host, host_port=to_port, ssl=useSSL, api_version=f"{args.api_version:.1f}", verify_cert=not args.insecure) data = args.DATA if data and os.path.isfile(data): with open(data) as f: data = f.read() if isinstance(data, str): data = data.encode() try: to_user = args.to_user if args.to_user else os.environ["TO_USER"] except KeyError as e: raise KeyError("Traffic Ops user not set! Set the TO_USER environment variable or use "\<|fim▁hole|> try: to_passwd = args.to_password if args.to_password else os.environ["TO_PASSWORD"] except KeyError as e: raise KeyError("Traffic Ops password not set! Set the TO_PASSWORD environment variable or "\ "use '--to-password'") from e # TOSession objects return LoginError when certs are invalid, OperationError when # login actually fails try: s.login(to_user, to_passwd) except LoginError as e: raise PermissionError( "certificate verification failed, the system may have a self-signed certificate - try using -k/--insecure" ) from e except (OperationError, InvalidJSONError) as e: raise PermissionError(e) from e except RequestException as e: raise ConnectionError("Traffic Ops host not found: Name or service not known") from e return (s, args.PATH, data, ( args.request_headers or args.full, args.response_headers or args.full, args.request_payload or args.full ), args.raw_path, args.pretty) def request(method): """ All of the scripts wind up calling this function to handle their common functionality. :param method: The name of the request method to use (case-insensitive) :returns: The program's exit code """ try: s, path, data, full, raw, pretty = parse_arguments("to%s" % method) except (PermissionError, KeyError, ConnectionError) as e: print(e, file=sys.stderr) return 1 if raw: path = '/'.join((s.to_url.rstrip('/'), path.lstrip('/'))) else: path = '/'.join((s.base_url.rstrip('/'), path.lstrip('/'))) try: if data is not None: r = s._session.request(method, path, data=data) else: r = s._session.request(method, path) except (RequestException, ValueError) as e: print("Error occurred: ", e, file=sys.stderr) return 2 output(r, pretty, *full) return 0 if r.status_code < 400 else r.status_code // 100 def get(): """ Entry point for :program:`toget` :returns: The program's exit code """ return request("get") def put(): """ Entry point for :program:`toput` :returns: The program's exit code """ return request("put") def post(): """ Entry point for :program:`topost` :returns: The program's exit code """ return request("post") def delete(): """ Entry point for :program:`todelete` :returns: The program's exit code """ return request("delete") def options(): """ Entry point for :program:`tooptions` :returns: The program's exit code """ return request("options") def head(): """ Entry point for :program:`tohead` :returns: The program's exit code """ return request("head") def patch(): """ Entry point for :program:`topatch` :returns: The program's exit code """ return request("patch")<|fim▁end|>
"'--to-user'.") from e
<|file_name|>extensionEditingBrowserMain.ts<|end_file_name|><|fim▁begin|>/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as vscode from 'vscode'; import { PackageDocument } from './packageDocumentHelper'; export function activate(context: vscode.ExtensionContext) { //package.json suggestions context.subscriptions.push(registerPackageDocumentCompletions()); } function registerPackageDocumentCompletions(): vscode.Disposable { return vscode.languages.registerCompletionItemProvider({ language: 'json', pattern: '**/package.json' }, {<|fim▁hole|> provideCompletionItems(document, position, token) { return new PackageDocument(document).provideCompletionItems(position, token); } }); }<|fim▁end|>
<|file_name|>generate_bnmf.py<|end_file_name|><|fim▁begin|>""" Generate a toy dataset for the matrix factorisation case, and store it. We use dimensions 100 by 50 for the dataset, and 10 latent factors. As the prior for U and V we take value 1 for all entries (so exp 1). As a result, each value in R has a value of around 20, and a variance of 100-120. For contrast, the Sanger dataset of 705 by 140 shifted to nonnegative has mean 31.522999753779082 and variance 243.2427345740027. We add Gaussian noise of precision tau = 1 (prior for gamma: alpha=1,beta=1). (Simply using the expectation of our Gamma distribution over tau) """ import sys, os project_location = os.path.dirname(__file__)+"/../../../" sys.path.append(project_location) from BNMTF.code.models.distributions.exponential import exponential_draw from BNMTF.code.models.distributions.normal import normal_draw from BNMTF.code.cross_validation.mask import generate_M import numpy, itertools, matplotlib.pyplot as plt def generate_dataset(I,J,K,lambdaU,lambdaV,tau): # Generate U, V U = numpy.zeros((I,K)) for i,k in itertools.product(xrange(0,I),xrange(0,K)): U[i,k] = exponential_draw(lambdaU[i,k]) V = numpy.zeros((J,K)) for j,k in itertools.product(xrange(0,J),xrange(0,K)): V[j,k] = exponential_draw(lambdaV[j,k]) # Generate R true_R = numpy.dot(U,V.T) R = add_noise(true_R,tau) return (U,V,tau,true_R,R) def add_noise(true_R,tau): if numpy.isinf(tau): return numpy.copy(true_R) (I,J) = true_R.shape R = numpy.zeros((I,J)) for i,j in itertools.product(xrange(0,I),xrange(0,J)): R[i,j] = normal_draw(true_R[i,j],tau) return R def try_generate_M(I,J,fraction_unknown,attempts): for attempt in range(1,attempts+1): try: M = generate_M(I,J,fraction_unknown) sums_columns = M.sum(axis=0) sums_rows = M.sum(axis=1) for i,c in enumerate(sums_rows): assert c != 0, "Fully unobserved row in M, row %s. Fraction %s." % (i,fraction_unknown) for j,c in enumerate(sums_columns): assert c != 0, "Fully unobserved column in M, column %s. Fraction %s." % (j,fraction_unknown) print "Took %s attempts to generate M." % attempt return M except AssertionError: pass raise Exception("Tried to generate M %s times, with I=%s, J=%s, fraction=%s, but failed." % (attempts,I,J,fraction_unknown)) ########## if __name__ == "__main__": output_folder = project_location+"BNMTF/data_toy/bnmf/" I,J,K = 100, 80, 10 #20, 10, 5 # fraction_unknown = 0.1 alpha, beta = 1., 1. lambdaU = numpy.ones((I,K)) lambdaV = numpy.ones((I,K)) tau = alpha / beta (U,V,tau,true_R,R) = generate_dataset(I,J,K,lambdaU,lambdaV,tau) # Try to generate M M = try_generate_M(I,J,fraction_unknown,attempts=1000)<|fim▁hole|> numpy.savetxt(open(output_folder+"U.txt",'w'),U) numpy.savetxt(open(output_folder+"V.txt",'w'),V) numpy.savetxt(open(output_folder+"R_true.txt",'w'),true_R) numpy.savetxt(open(output_folder+"R.txt",'w'),R) numpy.savetxt(open(output_folder+"M.txt",'w'),M) print "Mean R: %s. Variance R: %s. Min R: %s. Max R: %s." % (numpy.mean(R),numpy.var(R),R.min(),R.max()) fig = plt.figure() plt.hist(R.flatten(),bins=range(0,int(R.max())+1)) plt.show()<|fim▁end|>
# Store all matrices in text files
<|file_name|>write_log.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 import datetime import sys import os homedir = os.environ['HOME'] log_path = homedir + "/Pigrow/logs/trigger_log.txt" script = "write_log.py" message = "" for argu in sys.argv[1:]: argu_l = str(argu).lower() if argu_l == 'help' or argu_l == '-h' or argu_l == '--help': print(" Script for writing to a log file") print(" ") print(" log=" + homedir + "/Pigrow/logs/trigger_log.txt") print(" ") print(' script="text with spaces"') print(' to include spaces ensure the text is in "speech marks"') print("") print(' message="text with spaces"') print(' to include spaces ensure the text is in "speech marks"') sys.exit() elif argu_l == '-flags': print("log=" + log_path) print("script=write_log.py") print('message="text to record here"') sys.exit() elif "=" in argu: thearg = argu_l.split('=')[0] thevalue = argu.split('=')[1] if thearg == 'log' or thearg == 'log_path': log_path = thevalue elif thearg == 'script': script = thevalue elif thearg == 'message': message = thevalue line = script + "@" + str(datetime.datetime.now()) + "@" + message + '\n'<|fim▁hole|> with open(log_path, "a") as f: f.write(line) print("Log writen:" + line) print("to " + log_path)<|fim▁end|>
<|file_name|>attr.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 devtools_traits::AttrInfo; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; use dom::bindings::inheritance::Castable; use dom::bindings::js::{LayoutJS, MutNullableJS, Root, RootedReference}; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::customelementregistry::CallbackReaction; use dom::element::{AttributeMutation, Element}; use dom::mutationobserver::{Mutation, MutationObserver}; use dom::node::Node; use dom::virtualmethods::vtable_for; use dom::window::Window; use dom_struct::dom_struct; use html5ever::{Prefix, LocalName, Namespace}; use script_thread::ScriptThread; use servo_atoms::Atom; use std::borrow::ToOwned; use std::cell::Ref; use std::mem; use style::attr::{AttrIdentifier, AttrValue}; // https://dom.spec.whatwg.org/#interface-attr #[dom_struct] pub struct Attr { reflector_: Reflector, identifier: AttrIdentifier, value: DOMRefCell<AttrValue>, /// the element that owns this attribute. owner: MutNullableJS<Element>, } impl Attr { fn new_inherited(local_name: LocalName, value: AttrValue, name: LocalName, namespace: Namespace, prefix: Option<Prefix>, owner: Option<&Element>) -> Attr { Attr { reflector_: Reflector::new(), identifier: AttrIdentifier { local_name: local_name, name: name, namespace: namespace, prefix: prefix, }, value: DOMRefCell::new(value), owner: MutNullableJS::new(owner), } } pub fn new(window: &Window, local_name: LocalName, value: AttrValue, name: LocalName, namespace: Namespace, prefix: Option<Prefix>, owner: Option<&Element>) -> Root<Attr> { reflect_dom_object(box Attr::new_inherited(local_name, value, name, namespace, prefix, owner), window, AttrBinding::Wrap) } #[inline] pub fn name(&self) -> &LocalName { &self.identifier.name } #[inline] pub fn namespace(&self) -> &Namespace { &self.identifier.namespace } #[inline] pub fn prefix(&self) -> Option<&Prefix> { self.identifier.prefix.as_ref() } } impl AttrMethods for Attr { // https://dom.spec.whatwg.org/#dom-attr-localname fn LocalName(&self) -> DOMString { // FIXME(ajeffrey): convert directly from LocalName to DOMString DOMString::from(&**self.local_name()) } // https://dom.spec.whatwg.org/#dom-attr-value fn Value(&self) -> DOMString { // FIXME(ajeffrey): convert directly from AttrValue to DOMString DOMString::from(&**self.value()) } // https://dom.spec.whatwg.org/#dom-attr-value fn SetValue(&self, value: DOMString) { if let Some(owner) = self.owner() { let value = owner.parse_attribute(&self.identifier.namespace, self.local_name(), value); self.set_value(value, &owner); } else { *self.value.borrow_mut() = AttrValue::String(value.into()); } } // https://dom.spec.whatwg.org/#dom-attr-textcontent fn TextContent(&self) -> DOMString { self.Value() } // https://dom.spec.whatwg.org/#dom-attr-textcontent fn SetTextContent(&self, value: DOMString) { self.SetValue(value) } // https://dom.spec.whatwg.org/#dom-attr-nodevalue fn NodeValue(&self) -> DOMString { self.Value() } // https://dom.spec.whatwg.org/#dom-attr-nodevalue fn SetNodeValue(&self, value: DOMString) { self.SetValue(value) } // https://dom.spec.whatwg.org/#dom-attr-name fn Name(&self) -> DOMString { // FIXME(ajeffrey): convert directly from LocalName to DOMString DOMString::from(&*self.identifier.name) } // https://dom.spec.whatwg.org/#dom-attr-nodename fn NodeName(&self) -> DOMString { self.Name() } // https://dom.spec.whatwg.org/#dom-attr-namespaceuri fn GetNamespaceURI(&self) -> Option<DOMString> { match self.identifier.namespace { ns!() => None, ref url => Some(DOMString::from(&**url)), } } // https://dom.spec.whatwg.org/#dom-attr-prefix fn GetPrefix(&self) -> Option<DOMString> { // FIXME(ajeffrey): convert directly from LocalName to DOMString self.prefix().map(|p| DOMString::from(&**p)) } // https://dom.spec.whatwg.org/#dom-attr-ownerelement fn GetOwnerElement(&self) -> Option<Root<Element>> { self.owner() } // https://dom.spec.whatwg.org/#dom-attr-specified fn Specified(&self) -> bool { true // Always returns true } } impl Attr { pub fn set_value(&self, mut value: AttrValue, owner: &Element) { let name = self.local_name().clone(); let namespace = self.namespace().clone(); let old_value = DOMString::from(&**self.value()); let new_value = DOMString::from(&*value); let mutation = Mutation::Attribute { name: name.clone(), namespace: namespace.clone(), old_value: old_value.clone(), }; MutationObserver::queue_a_mutation_record(owner.upcast::<Node>(), mutation); if owner.get_custom_element_definition().is_some() { let reaction = CallbackReaction::AttributeChanged(name, Some(old_value), Some(new_value), namespace); ScriptThread::enqueue_callback_reaction(owner, reaction); } assert!(Some(owner) == self.owner().r()); owner.will_mutate_attr(self); self.swap_value(&mut value); if self.identifier.namespace == ns!() { vtable_for(owner.upcast()) .attribute_mutated(self, AttributeMutation::Set(Some(&value))); } } /// Used to swap the attribute's value without triggering mutation events pub fn swap_value(&self, value: &mut AttrValue) { mem::swap(&mut *self.value.borrow_mut(), value); } pub fn identifier(&self) -> &AttrIdentifier { &self.identifier } pub fn value(&self) -> Ref<AttrValue> { self.value.borrow() } pub fn local_name(&self) -> &LocalName { &self.identifier.local_name } <|fim▁hole|> pub fn set_owner(&self, owner: Option<&Element>) { let ns = &self.identifier.namespace; match (self.owner(), owner) { (Some(old), None) => { // Already gone from the list of attributes of old owner. assert!(old.get_attribute(&ns, &self.identifier.local_name).r() != Some(self)) } (Some(old), Some(new)) => assert!(&*old == new), _ => {}, } self.owner.set(owner); } pub fn owner(&self) -> Option<Root<Element>> { self.owner.get() } pub fn summarize(&self) -> AttrInfo { AttrInfo { namespace: (*self.identifier.namespace).to_owned(), name: String::from(self.Name()), value: String::from(self.Value()), } } } #[allow(unsafe_code)] pub trait AttrHelpersForLayout { unsafe fn value_forever(&self) -> &'static AttrValue; unsafe fn value_ref_forever(&self) -> &'static str; unsafe fn value_atom_forever(&self) -> Option<Atom>; unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>; unsafe fn local_name_atom_forever(&self) -> LocalName; unsafe fn value_for_layout(&self) -> &AttrValue; } #[allow(unsafe_code)] impl AttrHelpersForLayout for LayoutJS<Attr> { #[inline] unsafe fn value_forever(&self) -> &'static AttrValue { // This transmute is used to cheat the lifetime restriction. mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout()) } #[inline] unsafe fn value_ref_forever(&self) -> &'static str { &**self.value_forever() } #[inline] unsafe fn value_atom_forever(&self) -> Option<Atom> { let value = (*self.unsafe_get()).value.borrow_for_layout(); match *value { AttrValue::Atom(ref val) => Some(val.clone()), _ => None, } } #[inline] unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> { // This transmute is used to cheat the lifetime restriction. match *self.value_forever() { AttrValue::TokenList(_, ref tokens) => Some(tokens), _ => None, } } #[inline] unsafe fn local_name_atom_forever(&self) -> LocalName { (*self.unsafe_get()).identifier.local_name.clone() } #[inline] unsafe fn value_for_layout(&self) -> &AttrValue { (*self.unsafe_get()).value.borrow_for_layout() } }<|fim▁end|>
/// Sets the owner element. Should be called after the attribute is added /// or removed from its older parent.
<|file_name|>main.cpp<|end_file_name|><|fim▁begin|>/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** BSD License Usage ** Alternatively, you may use this file under the terms of the BSD license ** as follows: ** ** "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 Qt Company Ltd 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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE 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." ** ** $QT_END_LICENSE$<|fim▁hole|> #include "pathstroke.h" #include <QApplication> int main(int argc, char **argv) { Q_INIT_RESOURCE(pathstroke); QApplication app(argc, argv); bool smallScreen = QApplication::arguments().contains("-small-screen"); PathStrokeWidget pathStrokeWidget(smallScreen); QStyle *arthurStyle = new ArthurStyle(); pathStrokeWidget.setStyle(arthurStyle); QList<QWidget *> widgets = pathStrokeWidget.findChildren<QWidget *>(); foreach (QWidget *w, widgets) { w->setStyle(arthurStyle); w->setAttribute(Qt::WA_AcceptTouchEvents); } if (smallScreen) pathStrokeWidget.showFullScreen(); else pathStrokeWidget.show(); #ifdef QT_KEYPAD_NAVIGATION QApplication::setNavigationMode(Qt::NavigationModeCursorAuto); #endif return app.exec(); }<|fim▁end|>
** ****************************************************************************/
<|file_name|>tests.rs<|end_file_name|><|fim▁begin|>// Copyright 2016-2018 Matthew D. Michelotti // // 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. use super::{Collider, HbEvent, HbId, HbProfile, HbVel}; use geom::{v2, Shape}; use std::f64; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] struct TestHbProfile { id: HbId, } impl From<HbId> for TestHbProfile { fn from(id: HbId) -> TestHbProfile { TestHbProfile { id } } } impl HbProfile for TestHbProfile { fn id(&self) -> HbId { self.id } fn can_interact(&self, _other: &TestHbProfile) -> bool { true } }<|fim▁hole|>fn advance_to_event(collider: &mut Collider<TestHbProfile>, time: f64) { advance(collider, time); assert_eq!(collider.next_time(), collider.time()); } fn advance(collider: &mut Collider<TestHbProfile>, time: f64) { while collider.time() < time { assert!(collider.next().is_none()); let new_time = collider.next_time().min(time); collider.set_time(new_time); } assert_eq!(collider.time(), time); } fn advance_through_events(collider: &mut Collider<TestHbProfile>, time: f64) { while collider.time() < time { collider.next(); let new_time = collider.next_time().min(time); collider.set_time(new_time); } assert_eq!(collider.time(), time); } fn sort(mut vector: Vec<TestHbProfile>) -> Vec<TestHbProfile> { vector.sort(); vector } #[test] fn smoke_test() { let mut collider = Collider::<TestHbProfile>::new(4.0, 0.25); let mut hitbox = Shape::square(2.0).place(v2(-10.0, 0.0)).still(); hitbox.vel.value = v2(1.0, 0.0); let overlaps = collider.add_hitbox(0.into(), hitbox); assert_eq!(overlaps, vec![]); let mut hitbox = Shape::circle(2.0).place(v2(10.0, 0.0)).still(); hitbox.vel.value = v2(-1.0, 0.0); let overlaps = collider.add_hitbox(1.into(), hitbox); assert_eq!(overlaps, vec![]); advance_to_event(&mut collider, 9.0); assert_eq!( collider.next(), Some((HbEvent::Collide, 0.into(), 1.into())) ); advance_to_event(&mut collider, 11.125); assert_eq!( collider.next(), Some((HbEvent::Separate, 0.into(), 1.into())) ); advance(&mut collider, 23.0); } #[test] fn test_hitbox_updates() { let mut collider = Collider::<TestHbProfile>::new(4.0, 0.25); let mut hitbox = Shape::square(2.0).place(v2(-10.0, 0.0)).still(); hitbox.vel.value = v2(1.0, 0.0); let overlaps = collider.add_hitbox(0.into(), hitbox); assert!(overlaps.is_empty()); let mut hitbox = Shape::circle(2.0).place(v2(10.0, 0.0)).still(); hitbox.vel.value = v2(1.0, 0.0); let overlaps = collider.add_hitbox(1.into(), hitbox); assert!(overlaps.is_empty()); advance(&mut collider, 11.0); let mut hitbox = collider.get_hitbox(0); assert_eq!(hitbox.value, Shape::square(2.0).place(v2(1.0, 0.0))); assert_eq!(hitbox.vel.value, v2(1.0, 0.0)); assert_eq!(hitbox.vel.resize, v2(0.0, 0.0)); assert_eq!(hitbox.vel.end_time, f64::INFINITY); hitbox.value.pos = v2(0.0, 2.0); hitbox.vel.value = v2(0.0, -1.0); let overlaps = collider.remove_hitbox(0); assert_eq!(overlaps, vec![]); let overlaps = collider.add_hitbox(0.into(), hitbox); assert_eq!(overlaps, vec![]); advance(&mut collider, 14.0); let mut hitbox = collider.get_hitbox(1); assert_eq!(hitbox.value, Shape::circle(2.0).place(v2(24.0, 0.0))); assert_eq!(hitbox.vel.value, v2(1.0, 0.0)); assert_eq!(hitbox.vel.resize, v2(0.0, 0.0)); assert_eq!(hitbox.vel.end_time, f64::INFINITY); hitbox.value.pos = v2(0.0, -8.0); hitbox.vel.value = v2(0.0, 0.0); let overlaps = collider.remove_hitbox(1); assert_eq!(overlaps, vec![]); let overlaps = collider.add_hitbox(1.into(), hitbox); assert_eq!(overlaps, vec![]); advance_to_event(&mut collider, 19.0); assert_eq!( collider.next(), Some((HbEvent::Collide, 0.into(), 1.into())) ); let mut hitbox = collider.get_hitbox(0); assert_eq!(hitbox.value, Shape::square(2.0).place(v2(0.0, -6.0))); assert_eq!(hitbox.vel.value, v2(0.0, -1.0)); assert_eq!(hitbox.vel.resize, v2(0.0, 0.0)); assert_eq!(hitbox.vel.end_time, f64::INFINITY); hitbox.vel.value = v2(0.0, 0.0); collider.set_hitbox_vel(0, hitbox.vel); let mut hitbox = collider.get_hitbox(1); assert_eq!(hitbox.value, Shape::circle(2.0).place(v2(0.0, -8.0))); assert_eq!(hitbox.vel.value, v2(0.0, 0.0)); assert_eq!(hitbox.vel.resize, v2(0.0, 0.0)); assert_eq!(hitbox.vel.end_time, f64::INFINITY); hitbox.vel.value = v2(0.0, 2.0); collider.set_hitbox_vel(1, hitbox.vel); let hitbox = Shape::rect(v2(2.0, 20.0)).place(v2(0.0, 0.0)).still(); assert_eq!( sort(collider.add_hitbox(2.into(), hitbox)), vec![0.into(), 1.into()] ); advance_to_event(&mut collider, 21.125); assert_eq!( collider.next(), Some((HbEvent::Separate, 0.into(), 1.into())) ); advance(&mut collider, 26.125); let overlaps = collider.remove_hitbox(1); assert_eq!(overlaps, vec![2.into()]); advance(&mut collider, 37.125); } #[test] fn test_get_overlaps() { let mut collider = Collider::<TestHbProfile>::new(4.0, 0.25); collider.add_hitbox( 0.into(), Shape::square(2.0) .place(v2(-10.0, 0.0)) .moving(v2(1.0, 0.0)), ); collider.add_hitbox( 1.into(), Shape::circle(2.0) .place(v2(10.0, 0.0)) .moving(v2(-1.0, 0.0)), ); collider.add_hitbox(2.into(), Shape::square(2.0).place(v2(0.0, 0.0)).still()); assert_eq!(collider.get_overlaps(0), vec![]); assert_eq!(collider.get_overlaps(1), vec![]); assert_eq!(collider.get_overlaps(2), vec![]); assert!(!collider.is_overlapping(0, 1)); assert!(!collider.is_overlapping(0, 2)); assert!(!collider.is_overlapping(1, 2)); assert!(!collider.is_overlapping(1, 0)); advance_through_events(&mut collider, 10.0); assert_eq!(sort(collider.get_overlaps(0)), vec![1.into(), 2.into()]); assert_eq!(sort(collider.get_overlaps(1)), vec![0.into(), 2.into()]); assert_eq!(sort(collider.get_overlaps(2)), vec![0.into(), 1.into()]); assert!(collider.is_overlapping(0, 1)); assert!(collider.is_overlapping(0, 2)); assert!(collider.is_overlapping(1, 2)); assert!(collider.is_overlapping(1, 0)); collider.set_hitbox_vel(1, HbVel::moving(v2(1.0, 0.0))); advance_through_events(&mut collider, 20.0); assert_eq!(collider.get_overlaps(0), vec![1.into()]); assert_eq!(collider.get_overlaps(1), vec![0.into()]); assert_eq!(collider.get_overlaps(2), vec![]); assert!(collider.is_overlapping(0, 1)); assert!(!collider.is_overlapping(0, 2)); assert!(!collider.is_overlapping(1, 2)); collider.remove_hitbox(2); assert_eq!(collider.get_overlaps(0), vec![1.into()]); assert_eq!(collider.get_overlaps(1), vec![0.into()]); assert!(collider.is_overlapping(0, 1)); collider.remove_hitbox(1); assert_eq!(collider.get_overlaps(0), vec![]); } #[test] fn test_query_overlaps() { let mut collider = Collider::<TestHbProfile>::new(4.0, 0.25); collider.add_hitbox( 0.into(), Shape::square(2.0).place(v2(-5.0, 0.0)).moving(v2(1.0, 0.0)), ); collider.add_hitbox(1.into(), Shape::circle(2.0).place(v2(0.0, 0.0)).still()); collider.add_hitbox( 2.into(), Shape::circle(2.0) .place(v2(10.0, 0.0)) .moving(v2(-1.0, 0.0)), ); let test_shape = Shape::circle(2.0).place(v2(-1.0, 0.5)); assert_eq!( collider.query_overlaps(&test_shape, &5.into()), vec![1.into()] ); advance(&mut collider, 3.0); assert_eq!( sort(collider.query_overlaps(&test_shape, &5.into())), vec![0.into(), 1.into()] ); } #[test] fn test_separate_initial_overlap() { let mut collider = Collider::<TestHbProfile>::new(4.0, 0.25); let overlaps = collider.add_hitbox( 0.into(), Shape::square(1.).place(v2(0., 0.)).moving(v2(0.0, 1.)), ); assert_eq!(overlaps, vec![]); let overlaps = collider.add_hitbox(1.into(), Shape::square(1.).place(v2(0., 0.)).still()); assert_eq!(overlaps, vec![0.into()]); advance_to_event(&mut collider, 1.25); assert_eq!( collider.next(), Some((HbEvent::Separate, 0.into(), 1.into())) ); advance(&mut collider, 1.5); } //TODO test custom interactivities...<|fim▁end|>
<|file_name|>api.py<|end_file_name|><|fim▁begin|>import eventlet import gettext import sys from staccato.common import config import staccato.openstack.common.wsgi as os_wsgi import staccato.openstack.common.pastedeploy as os_pastedeploy # Monkey patch socket and time eventlet.patcher.monkey_patch(all=False, socket=True, time=True) gettext.install('staccato', unicode=1) def fail(returncode, e): sys.stderr.write("ERROR: %s\n" % e) sys.exit(returncode) def main(): try: conf = config.get_config_object() paste_file = conf.find_file(conf.paste_deploy.config_file) wsgi_app = os_pastedeploy.paste_deploy_app(paste_file, 'staccato-api', conf) server = os_wsgi.Service(wsgi_app, conf.bind_port)<|fim▁hole|> except RuntimeError as e: fail(1, e) main()<|fim▁end|>
server.start() server.wait()
<|file_name|>app.py<|end_file_name|><|fim▁begin|>from flask import Flask, render_template, flash, session, redirect, url_for from wtforms import TextAreaField from wtforms.validators import DataRequired from flask.ext.wtf import Form from flask.ext.wtf.recaptcha import RecaptchaField DEBUG = True SECRET_KEY = 'secret' # keys for localhost. Change as appropriate. RECAPTCHA_PUBLIC_KEY = '6LeYIbsSAAAAACRPIllxA7wvXjIE411PfdB2gt2J' RECAPTCHA_PRIVATE_KEY = '6LeYIbsSAAAAAJezaIq3Ft_hSTo0YtyeFG-JgRtu' app = Flask(__name__) app.config.from_object(__name__) class CommentForm(Form): comment = TextAreaField("Comment", validators=[DataRequired()]) recaptcha = RecaptchaField() @app.route("/") def index(form=None): if form is None: form = CommentForm() comments = session.get("comments", []) return render_template("index.html", comments=comments,<|fim▁hole|> @app.route("/add/", methods=("POST",)) def add_comment(): form = CommentForm() if form.validate_on_submit(): comments = session.pop('comments', []) comments.append(form.comment.data) session['comments'] = comments flash("You have added a new comment") return redirect(url_for("index")) return index(form) if __name__ == "__main__": app.run()<|fim▁end|>
form=form)
<|file_name|>test_db_consistency.py<|end_file_name|><|fim▁begin|>import pytest from django.db import connection, IntegrityError from .models import MyTree <|fim▁hole|> # Django's testcase thing does eventually flush the constraints but to # actually test it *within* a testcase we have to flush it manually. connection.cursor().execute("SET CONSTRAINTS ALL IMMEDIATE") def test_node_creation_simple(db): MyTree.objects.create(label='root1') MyTree.objects.create(label='root2') def test_node_creation_with_no_label(db): # You need a label with pytest.raises(ValueError): MyTree.objects.create(label='') with pytest.raises(ValueError): MyTree.objects.create(label=None) with pytest.raises(ValueError): MyTree.objects.create() def test_root_node_already_exists(db): MyTree.objects.create(label='root1') with pytest.raises(IntegrityError): MyTree.objects.create(label='root1') def test_same_label_but_different_parent(db): root1 = MyTree.objects.create(label='root1') MyTree.objects.create(label='root1', parent=root1) def test_same_label_as_sibling(db): root1 = MyTree.objects.create(label='root1') MyTree.objects.create(label='child', parent=root1) with pytest.raises(IntegrityError): MyTree.objects.create(label='child', parent=root1) def test_parent_is_self_errors(db): root1 = MyTree.objects.create(label='root1') root1.parent = root1 with pytest.raises(IntegrityError): root1.save() flush_constraints() def test_parent_is_remote_ancestor_errors(db): root1 = MyTree.objects.create(label='root1') child2 = MyTree.objects.create(label='child2', parent=root1) desc3 = MyTree.objects.create(label='desc3', parent=child2) with pytest.raises(IntegrityError): # To test this integrity error, have to update table without calling save() # (because save() changes `ltree` to match `parent_id`) MyTree.objects.filter(pk=desc3.pk).update(parent=root1) flush_constraints() def test_parent_is_descendant_errors(db): root1 = MyTree.objects.create(label='root1') child2 = MyTree.objects.create(label='child2', parent=root1) desc3 = MyTree.objects.create(label='desc3', parent=child2) child2.parent = desc3 with pytest.raises(IntegrityError): child2.save() flush_constraints()<|fim▁end|>
def flush_constraints(): # the default db setup is to have constraints DEFERRED. # So IntegrityErrors only happen when the transaction commits.
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># (C) Datadog, Inc. 2018 # All rights reserved<|fim▁hole|><|fim▁end|>
# Licensed under a 3-clause BSD style license (see LICENSE)
<|file_name|>jobsReducer.js<|end_file_name|><|fim▁begin|>import { RECEIVE_ALL_JOBS, RECEIVE_JOB, REQUEST_ALL_JOBS, REQUEST_JOB, RECEIVE_FILTERED_JOBS, REQUEST_FILTERED_JOBS, CREATE_JOBS, PAGINATE_JOBS, UPDATE_JOB, DELETE_JOB } from './constants' const initialState = { fetchingSelected: false, selected: null, fetchingAll: false, all: null, filteredJobs: null, filtered: false, filter: null, // we persist user's search parameters between navigations to/from home and job detail pages offset: 0, pageNum: 1 } const jobsReducer = (state = initialState, action) => { switch (action.type) { case REQUEST_ALL_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: true, all: null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case RECEIVE_ALL_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: action.jobs, filteredJobs: null, filtered: false, filter: null, offset: 0, pageNum: 1 } case REQUEST_FILTERED_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: true, all: state.all ? [...state.all] : null, filteredJobs: null, filtered: state.filteredJobs !== null, filter: action.filter, offset: 0, pageNum: 1 } case RECEIVE_FILTERED_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: action.jobs, filtered: true, filter: {...state.filter}, offset: 0, pageNum: 1 } case PAGINATE_JOBS: return { fetchingSelected: false, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null,<|fim▁hole|> filter: state.filter ? {...state.filter} : null, offset: action.offset, pageNum: action.pageNum } case REQUEST_JOB: return { fetchingSelected: true, selected: null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: state.filteredJobs !== null, filter: state.filter ? {...state.filter} : null, offset: state.offset, pageNum: state.pageNum } case RECEIVE_JOB: return { fetchingSelected: false, selected: action.job, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: state.filteredJobs !== null, filter: state.filter ? {...state.filter} : null, offset: state.offset, pageNum: state.pageNum } case CREATE_JOBS: return { fetchingSelected: false, selected: state.selected ? {...state.selected} : null, fetchingAll: true, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case UPDATE_JOB: return { fetchingSelected: true, selected: state.selected ? {...state.selected} : null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } case DELETE_JOB: return { fetchingSelected: true, selected: state.selected ? {...state.selected} : null, fetchingAll: false, all: state.all ? [...state.all] : null, filteredJobs: state.filteredJobs ? [...state.filteredJobs] : null, filtered: false, filter: null, offset: 0, pageNum: 1 } default: return state } } export default jobsReducer<|fim▁end|>
filtered: state.filteredJobs !== null,
<|file_name|>test.rs<|end_file_name|><|fim▁begin|>macro_rules! enforce { ($($e:expr),+,) => { if $(!$e)||+ { return TestResult::discard(); } } } macro_rules! test { ($e:expr) => { TestResult::from_bool($e) } } trait IsClose { fn is_close(self, rhs: Self) -> bool; } macro_rules! float { ($($ty:ident),+) => {$( mod $ty { impl ::test::IsClose for $ty { fn is_close(self, rhs: $ty) -> bool { const TOL: $ty = 1e-3; (self - rhs).abs() < TOL } } mod linspace { use quickcheck::TestResult; mod rev { use quickcheck::TestResult; // Check that `linspace(..).rev()` yields evenly spaced numbers #[quickcheck] fn evenly_spaced(start: $ty, end: $ty, n: usize) -> TestResult { use test::IsClose; enforce! { start <= end, } let v = ::linspace(start, end, n).rev().collect::<Vec<_>>(); let mut spaces = v.windows(2).map(|w| w[1] - w[0]); test!(match spaces.next() { None => true, Some(first) => spaces.all(|space| space.is_close(first)) }) } // Check that `linspace(..).rev()` produces a monotonically decreasing sequence #[quickcheck] fn monotonic(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start <= end, } let v = ::linspace(start, end, n).rev().collect::<Vec<_>>(); test!(v.windows(2).all(|w| w[1] <= w[0])) } // Check that `linspace(_, _, n).rev()` yields exactly `n` numbers #[quickcheck] fn size(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start <= end, } test!(::linspace(start, end, n).rev().count() == n) } } // Check that `linspace(..)` yields evenly spaced numbers #[quickcheck] fn evenly_spaced(start: $ty, end: $ty, n: usize) -> TestResult { use test::IsClose; enforce! { start <= end, } let v = ::linspace(start, end, n).collect::<Vec<_>>(); let mut spaces = v.windows(2).map(|w| w[1] - w[0]); test!(match spaces.next() { None => true, Some(first) => spaces.all(|space| space.is_close(first)) }) } // Check that `linspace(..)` produces a monotonic increasing sequence #[quickcheck] fn monotonic(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start <= end, } let v = ::linspace(start, end, n).collect::<Vec<_>>(); test!(v.windows(2).all(|w| w[1] >= w[0])) } // Check that `linspace(_, _, n)` yields exactly `n` numbers #[quickcheck] fn size(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start <= end, } test!(::linspace(start, end, n).count() == n) } } mod logspace { use quickcheck::TestResult; mod rev {<|fim▁hole|> // Check that `logspace(..).rev()` yields evenly spaced numbers #[quickcheck] fn evenly_spaced(start: $ty, end: $ty, n: usize) -> TestResult { use test::IsClose; enforce! { start > 0., start <= end, } let v = ::logspace(start, end, n).rev().collect::<Vec<_>>(); let mut spaces = v.windows(2).map(|w| { w[1].ln() - w[0].ln() }); test!(match spaces.next() { None => true, Some(first) => spaces.all(|space| space.is_close(first)) }) } // Check that `logspace(..).rev()` produces a monotonically decreasing sequence #[quickcheck] fn monotonic(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start > 0., start <= end, } let v = ::logspace(start, end, n).rev().collect::<Vec<_>>(); test!(v.windows(2).all(|w| w[1] <= w[0])) } // Check that `logspace(_, _, n).rev()` yields exactly `n` numbers #[quickcheck] fn size(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start > 0., start <= end, } test!(::logspace(start, end, n).count() == n) } } // Check that `logspace(..)` yields evenly spaced numbers #[quickcheck] fn evenly_spaced(start: $ty, end: $ty, n: usize) -> TestResult { use test::IsClose; enforce! { start > 0., start <= end, } let v = ::logspace(start, end, n).collect::<Vec<_>>(); let mut spaces = v.windows(2).map(|w| { w[1].ln() - w[0].ln() }); test!(match spaces.next() { None => true, Some(first) => spaces.all(|space| space.is_close(first)) }) } // Check that `logspace(..)` produces a monotonically increasing sequence #[quickcheck] fn monotonic(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start > 0., start <= end, } let v = ::logspace(start, end, n).collect::<Vec<_>>(); test!(v.windows(2).all(|w| w[1] >= w[0])) } // Check that `logspace(_, _, n)` yields exactly `n` numbers #[quickcheck] fn size(start: $ty, end: $ty, n: usize) -> TestResult { enforce! { start > 0., start <= end, } test!(::logspace(start, end, n).count() == n) } } })+ } } float!(f32, f64);<|fim▁end|>
use quickcheck::TestResult;
<|file_name|>PyDesignAnalysisItem.py<|end_file_name|><|fim▁begin|>from PyQt5.QtCore import * from PyDesignData.PyDesignObject import * from PyDesignModel.PyDesignCalcSheetsItem import PyDesignCalcSheetsItem from PyDesignModel.PyDesignIcons import * from PyDesignModel.PyDesignMaterialsItem import PyDesignMaterialsItem from PyDesignModel.PyDesignModelItem import PyDesignModelItem from PyDesignModel.PyDesignParametersItem import * from PyDesignModel.PyDesignGeometriesItem import * from PyDesignModel.PyDesignMeshesItem import * from PyDesignModel.PyDesignSolversItem import PyDesignSolversItem __author__ = 'magnus' class PyDesignAnalysisItem(PyDesignModelItem): def __init__(self, parent, py_design_analysis): """ :type py_design_analysis: PyDesignAnalysis :param parent: :param py_design_analysis: :return: """ PyDesignModelItem.__init__(self, parent, parent.model) self._data_object = py_design_analysis self._data_dict[PyDesignNamedObject.NAME] = self.data_name self._data_dict[PyDesignCommon.VALUE] = self.data_value '''self._data_dict[PDP.size_temp] = self.data_size_temp self._data_dict[PDP.medium_type] = self.data_medium_type self._data_dict[PDP.size_pres] = self.data_size_pres''' self._set_data_dict[PyDesignNamedObject.NAME] = self.set_data_name self._icon = get_icon("analysis") py_design_analysis.add_listener(self) self._children.append(PyDesignParametersItem(py_design_analysis.properties, self)) self._children.append(PyDesignCalcSheetsItem(py_design_analysis, self)) self._children.append(PyDesignGeometriesItem(py_design_analysis, self)) self._children.append(PyDesignMeshesItem(py_design_analysis, self)) self._children.append(PyDesignMaterialsItem(py_design_analysis, self)) self._children.append(PyDesignSolversItem(py_design_analysis, self)) self._type = "PyDesignAnalysisModelItem" self._context_menu = QMenu() add_prop_menu = self._context_menu.addAction("Add property") add_prop_menu.triggered.connect(self.on_add_property) add_prop_menu = self._context_menu.addAction("Add calculation sheet") add_prop_menu.triggered.connect(self.on_add_sheet) add_prop_menu = self._context_menu.addAction("Add geometry") add_prop_menu.triggered.connect(self.on_add_geometry) add_prop_menu = self._context_menu.addAction("Add mesh") add_prop_menu.triggered.connect(self.on_add_mesh) add_prop_menu = self._context_menu.addAction("Add material") add_prop_menu.triggered.connect(self.on_add_material) add_prop_menu = self._context_menu.addAction("Delete analysis") add_prop_menu.triggered.connect(self.on_delete) def on_add_property(self): PyDesignEventHandlers.on_add_parameter(self._data_object.properties) def on_add_sheet(self): PyDesignEventHandlers.on_add_sheet(self._data_object) def on_add_geometry(self): PyDesignEventHandlers.on_add_geometry(self._data_object, None)<|fim▁hole|> def on_add_mesh(self): pass def on_add_material(self): pass def on_delete(self): pass def data_name(self, int_role): if int_role == Qt.DisplayRole or int_role == Qt.EditRole: return self._data_object.name elif int_role == Qt.DecorationRole: return self._icon else: return None def set_data_name(self, int_role, data): if int_role == Qt.EditRole: self._data_object.name = data return True def data_value(self, int_role): if int_role == Qt.DisplayRole: type_name = "Unknown analysis" type_name = "3D analysis" if self._data_object.analysis_type == 0 else type_name type_name = "2D analysis" if self._data_object.analysis_type == 1 else type_name type_name = "2D analysis axis symmetric" if self._data_object.analysis_type == 2 else type_name return type_name else: return None def data_size_pres(self, int_role): if int_role == Qt.DisplayRole: return self._data_object.size_pres else: return None def data_medium_type(self, int_role): if int_role == Qt.DisplayRole: return self._data_object.medium_type else: return None @staticmethod def item_flags(int_pdp): default_flags = Qt.ItemIsSelectable | Qt.ItemIsEnabled if int_pdp == PyDesignNamedObject.NAME: return default_flags | Qt.ItemIsEditable else: return default_flags def on_context_menu(self, point): self._context_menu.exec_(point) def on_event(self, event): """ :type event: PyDesignEvent :param event: :return: """ self._model.on_item_changed(self) if event.type == PyDesignEvent.EndItemAddedEvent: pass #new_item = PyDesignParameterItem(self, event.value) #self.add_child(new_item) return<|fim▁end|>
<|file_name|>test-router.js<|end_file_name|><|fim▁begin|>"use strict" var o = require("../../ospec/ospec") var callAsync = require("../../test-utils/callAsync") var browserMock = require("../../test-utils/browserMock") var m = require("../../render/hyperscript") var callAsync = require("../../test-utils/callAsync") var coreRenderer = require("../../render/render") var apiRedraw = require("../../api/redraw") var apiRouter = require("../../api/router") var Promise = require("../../promise/promise") o.spec("route", function() { void [{protocol: "http:", hostname: "localhost"}, {protocol: "file:", hostname: "/"}].forEach(function(env) { void ["#", "?", "", "#!", "?!", "/foo"].forEach(function(prefix) { o.spec("using prefix `" + prefix + "` starting on " + env.protocol + "//" + env.hostname, function() { var FRAME_BUDGET = Math.floor(1000 / 60) var $window, root, redrawService, route o.beforeEach(function() { $window = browserMock(env) root = $window.document.body redrawService = apiRedraw($window) route = apiRouter($window, redrawService) route.prefix(prefix) }) o("throws on invalid `root` DOM node", function() { var threw = false try { route(null, '/', {'/':{view: function() {}}}) } catch (e) { threw = true } o(threw).equals(true) }) o("renders into `root`", function() { $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div") } } }) o(root.firstChild.nodeName).equals("DIV") }) o("routed mount points can redraw synchronously (#1275)", function() { var view = o.spy() $window.location.href = prefix + "/" route(root, "/", {"/":{view:view}}) o(view.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) }) o("default route doesn't break back button", function(done) { $window.location.href = "http://old.com" $window.location.href = "http://new.com" route(root, "/a", { "/a" : { view: function() { return m("div") } } }) callAsync(function() { o(root.firstChild.nodeName).equals("DIV") o(route.get()).equals("/a") $window.history.back() o($window.location.pathname).equals("/") o($window.location.hostname).equals("old.com") done() }) }) o("default route does not inherit params", function(done) { $window.location.href = "/invalid?foo=bar" route(root, "/a", { "/a" : { oninit: init, view: function() { return m("div") } } }) function init(vnode) { o(vnode.attrs.foo).equals(undefined) done() } }) o("redraws when render function is executed", function() { var onupdate = o.spy() var oninit = o.spy() $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate }) } } }) o(oninit.callCount).equals(1) redrawService.redraw() o(onupdate.callCount).equals(1) }) o("redraws on events", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: onclick, }) } } }) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) o(onclick.callCount).equals(1) o(onclick.this).equals(root.firstChild) o(onclick.args[0].type).equals("click") o(onclick.args[0].target).equals(root.firstChild) // Wrapped to give time for the rate-limited redraw to fire callAsync(function() { o(onupdate.callCount).equals(1) done() }) }) o("event handlers can skip redraw", function(done) { var onupdate = o.spy() var oninit = o.spy() var onclick = o.spy() var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("div", { oninit: oninit, onupdate: onupdate, onclick: function(e) { e.redraw = false }, }) } } }) root.firstChild.dispatchEvent(e) o(oninit.callCount).equals(1) // Wrapped to ensure no redraw fired callAsync(function() { o(onupdate.callCount).equals(0) done() }) }) o("changes location on route.link", function() { var e = $window.document.createEvent("MouseEvents") e.initEvent("click", true, true) $window.location.href = prefix + "/" route(root, "/", { "/" : { view: function() { return m("a", { href: "/test", oncreate: route.link }) } }, "/test" : { view : function() { return m("div") } } }) var slash = prefix[0] === "/" ? "" : "/" o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "")) root.firstChild.dispatchEvent(e) o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test") }) o("accepts RouteResolver with onmatch that returns Component", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Component }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<Component>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve(Component) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("SPAN") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<undefined>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve() }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns Promise<any>", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") o(this).equals(resolver) return Promise.resolve([]) }, render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") o(this).equals(resolver) return vnode }, } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : resolver }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("accepts RouteResolver with onmatch that returns rejected Promise", function(done) { var matchCount = 0 var renderCount = 0 var spy = o.spy() var Component = { view: function() { return m("span") } } var resolver = { onmatch: function(args, requestedPath) { matchCount++ return Promise.reject(new Error("error")) }, render: function(vnode) { renderCount++ return vnode }, } $window.location.href = prefix + "/test/1" route(root, "/default", { "/default" : {view: spy}, "/test/:id" : resolver }) callAsync(function() { callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(0) o(spy.callCount).equals(1) done() }) }) }) o("accepts RouteResolver without `render` method as payload", function(done) { var matchCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { onmatch: function(args, requestedPath) { matchCount++ o(args.id).equals("abc") o(requestedPath).equals("/abc") return Component }, }, }) callAsync(function() { o(matchCount).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) o("changing `vnode.key` in `render` resets the component", function(done, timeout){ var oninit = o.spy() var Component = { oninit: oninit, view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id": {render: function(vnode) { return m(Component, {key: vnode.attrs.id}) }} }) callAsync(function() { o(oninit.callCount).equals(1) route.set("/def") callAsync(function() { o(oninit.callCount).equals(2) done() }) }) }) o("accepts RouteResolver without `onmatch` method as payload", function() { var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/abc" route(root, "/abc", { "/:id" : { render: function(vnode) { renderCount++ o(vnode.attrs.id).equals("abc") return m(Component) }, }, }) o(root.firstChild.nodeName).equals("DIV") }) o("RouteResolver `render` does not have component semantics", function(done) { var renderCount = 0 var A = { view: function() { return m("div") } } $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { render: function(vnode) { return m("div") }, }, "/b" : { render: function(vnode) { return m("div") }, }, }) var dom = root.firstChild o(root.firstChild.nodeName).equals("DIV") route.set("/b") callAsync(function() { o(root.firstChild).equals(dom) done() }) }) o("calls onmatch and view correct number of times", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ return Component }, render: function(vnode) { renderCount++ return vnode }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1) redrawService.redraw() o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("calls onmatch and view correct number of times when not onmatch returns undefined", function(done) { var matchCount = 0 var renderCount = 0 var Component = { view: function() { return m("div") } } $window.location.href = prefix + "/" route(root, "/", { "/" : { onmatch: function() { matchCount++ }, render: function(vnode) { renderCount++ return {tag: Component} }, }, }) callAsync(function() { o(matchCount).equals(1) o(renderCount).equals(1)<|fim▁hole|> o(matchCount).equals(1) o(renderCount).equals(2) done() }) }) o("onmatch can redirect to another route", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { view: function() { redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver w/ only onmatch", function(done) { var redirected = false var render = o.spy() var view = o.spy(function() {return m("div")}) $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) o(root.childNodes.length).equals(1) o(root.firstChild.nodeName).equals("DIV") done() }) }) }) o("onmatch can redirect to another route that has RouteResolver w/ only render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { render: function(vnode){ redirected = true } } }) callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) o("onmatch can redirect to another route that has RouteResolver whose onmatch resolves asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { route.set("/b") }, render: render }, "/b" : { onmatch: function() { redirected = true return new Promise(function(fulfill){ callAsync(function(){ fulfill({view: view}) }) }) } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect to another route asynchronously", function(done) { var redirected = false var render = o.spy() var view = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { callAsync(function() {route.set("/b")}) return new Promise(function() {}) }, render: render }, "/b" : { onmatch: function() { redirected = true return {view: view} } } }) callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) o(view.callCount).equals(1) done() }) }) }) }) o("onmatch can redirect w/ window.history.back()", function(done) { var render = o.spy() var component = {view: o.spy()} $window.location.href = prefix + "/a" route(root, "/a", { "/a" : { onmatch: function() { return component }, render: function(vnode) { return vnode } }, "/b" : { onmatch: function() { $window.history.back() return new Promise(function() {}) }, render: render } }) callAsync(function() { route.set('/b') callAsync(function() { callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(component.view.callCount).equals(2) done() }) }) }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ onmatch", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { onmatch: function(vnode){ redirected = true return {view: function() {}} } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a RouteResolver w/ render", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { render: function(vnode){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("onmatch can redirect to a non-existent route that defaults to a component", function(done) { var redirected = false var render = o.spy() $window.location.href = prefix + "/a" route(root, "/b", { "/a" : { onmatch: function() { route.set("/c") }, render: render }, "/b" : { view: function(vnode){ redirected = true } } }) callAsync(function() { callAsync(function() { o(render.callCount).equals(0) o(redirected).equals(true) done() }) }) }) o("the previous view redraws while onmatch resolution is pending (#1268)", function(done) { var view = o.spy() var onmatch = o.spy(function() { return new Promise(function() {}) }) $window.location.href = prefix + "/a" route(root, "/", { "/a": {view: view}, "/b": {onmatch: onmatch} }) o(view.callCount).equals(1) o(onmatch.callCount).equals(0) route.set("/b") callAsync(function() { o(view.callCount).equals(1) o(onmatch.callCount).equals(1) redrawService.redraw() o(view.callCount).equals(2) o(onmatch.callCount).equals(1) done() }) }) o("when two async routes are racing, the last one set cancels the finalization of the first", function(done) { var renderA = o.spy() var renderB = o.spy() var onmatchA = o.spy(function(){ return new Promise(function(fulfill) { setTimeout(function(){ fulfill() }, 10) }) }) $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: onmatchA, render: renderA }, "/b": { onmatch: function(){ var p = new Promise(function(fulfill) { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) setTimeout(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) fulfill() p.then(function(){ o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(1) done() }) }, 20) }) return p }, render: renderB } }) callAsync(function() { o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) route.set("/b") o(onmatchA.callCount).equals(1) o(renderA.callCount).equals(0) o(renderB.callCount).equals(0) }) }) o("m.route.set(m.route.get()) re-runs the resolution logic (#1180)", function(done){ var onmatch = o.spy() var render = o.spy(function() {return m("div")}) $window.location.href = prefix + "/" route(root, '/', { "/": { onmatch: onmatch, render: render } }) callAsync(function() { o(onmatch.callCount).equals(1) o(render.callCount).equals(1) route.set(route.get()) callAsync(function() { callAsync(function() { o(onmatch.callCount).equals(2) o(render.callCount).equals(2) done() }) }) }) }) o("m.route.get() returns the last fully resolved route (#1276)", function(done){ $window.location.href = prefix + "/" route(root, "/", { "/": {view: function() {}}, "/2": { onmatch: function() { return new Promise(function() {}) } } }) o(route.get()).equals("/") route.set("/2") callAsync(function() { o(route.get()).equals("/") done() }) }) o("routing with RouteResolver works more than once", function(done) { $window.location.href = prefix + "/a" route(root, '/a', { '/a': { render: function() { return m("a", "a") } }, '/b': { render: function() { return m("b", "b") } } }) route.set('/b') callAsync(function() { route.set('/a') callAsync(function() { o(root.firstChild.nodeName).equals("A") done() }) }) }) o("calling route.set invalidates pending onmatch resolution", function(done) { var rendered = false var resolved $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onmatch: function() { return new Promise(function(resolve) { callAsync(function() { callAsync(function() { resolve({view: function() {rendered = true}}) }) }) }) }, render: function(vnode) { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } } }) route.set("/b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") callAsync(function() { o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) o("route changes activate onbeforeremove", function(done) { var spy = o.spy() $window.location.href = prefix + "/a" route(root, "/a", { "/a": { onbeforeremove: spy, view: function() {} }, "/b": { view: function() {} } }) route.set("/b") callAsync(function() { o(spy.callCount).equals(1) done() }) }) o("asynchronous route.set in onmatch works", function(done) { var rendered = false, resolved route(root, "/a", { "/a": { onmatch: function() { return Promise.resolve().then(function() { route.set("/b") }) }, render: function(vnode) { rendered = true resolved = "a" } }, "/b": { view: function() { resolved = "b" } }, }) callAsync(function() { // tick for popstate for /a callAsync(function() { // tick for promise in onmatch callAsync(function() { // tick for onpopstate for /b o(rendered).equals(false) o(resolved).equals("b") done() }) }) }) }) o("throttles", function(done, timeout) { timeout(200) var i = 0 $window.location.href = prefix + "/" route(root, "/", { "/": {view: function(v) {i++}} }) var before = i redrawService.redraw() redrawService.redraw() redrawService.redraw() redrawService.redraw() var after = i setTimeout(function() { o(before).equals(1) // routes synchronously o(after).equals(2) // redraws synchronously o(i).equals(3) // throttles rest done() }, FRAME_BUDGET * 2) }) o("m.route.param is available outside of route handlers", function(done) { $window.location.href = prefix + "/" route(root, "/1", { "/:id" : { view : function() { o(route.param("id")).equals("1") return m("div") } } }) o(route.param("id")).equals(undefined); o(route.param()).deepEquals(undefined); callAsync(function() { o(route.param("id")).equals("1") o(route.param()).deepEquals({id:"1"}) done() }) }) }) }) }) })<|fim▁end|>
redrawService.redraw()
<|file_name|>error.go<|end_file_name|><|fim▁begin|>package s3util import ( "bytes" "fmt" "io" "net/http"<|fim▁hole|>type respError struct { r *http.Response b bytes.Buffer } func newRespError(r *http.Response) *respError { e := new(respError) e.r = r io.Copy(&e.b, r.Body) r.Body.Close() return e } func (e *respError) Error() string { return fmt.Sprintf( "unwanted http status %d: %q", e.r.StatusCode, e.b.String(), ) }<|fim▁end|>
)
<|file_name|>SHA1.java<|end_file_name|><|fim▁begin|>/** * 对公众平台发送给公众账号的消息加解密示例代码. * * @copyright Copyright (c) 1998-2014 Tencent Inc. */ // ------------------------------------------------------------------------ package com.weixin.sdk.encrypt; import java.security.MessageDigest; import java.util.Arrays; /** * SHA1 class * * 计算公众平台的消息签名接口. */ class SHA1 { /** * 用SHA1算法生成安全签名 * @param token 票据 * @param timestamp 时间戳 * @param nonce 随机字符串 * @param encrypt 密文 * @return 安全签名 <|fim▁hole|> * @throws AesException */ public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException { try { String[] array = new String[] { token, timestamp, nonce, encrypt }; StringBuffer sb = new StringBuffer(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < 4; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuffer hexstr = new StringBuffer(); String shaHex = ""; for (int i = 0; i < digest.length; i++) { shaHex = Integer.toHexString(digest[i] & 0xFF); if (shaHex.length() < 2) { hexstr.append(0); } hexstr.append(shaHex); } return hexstr.toString(); } catch (Exception e) { e.printStackTrace(); throw new AesException(AesException.ComputeSignatureError); } } }<|fim▁end|>
<|file_name|>Util.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.pig.test; import static java.util.regex.Matcher.quoteReplacement; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.apache.pig.ExecType; import org.apache.pig.ExecTypeProvider; import org.apache.pig.LoadCaster; import org.apache.pig.PigException; import org.apache.pig.PigServer; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil; import org.apache.pig.backend.hadoop.executionengine.HExecutionEngine; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.backend.hadoop.executionengine.tez.TezResourceManager; import org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultBagFactory; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.io.FileLocalizer; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.pig.impl.util.LogUtils; import org.apache.pig.newplan.logical.optimizer.LogicalPlanPrinter; import org.apache.pig.newplan.logical.optimizer.SchemaResetter; import org.apache.pig.newplan.logical.optimizer.UidResetter; import org.apache.pig.newplan.logical.relational.LogToPhyTranslationVisitor; import org.apache.pig.newplan.logical.relational.LogicalPlan; import org.apache.pig.newplan.logical.relational.LogicalSchema; import org.apache.pig.newplan.logical.relational.LogicalSchema.LogicalFieldSchema; import org.apache.pig.newplan.logical.visitor.DanglingNestedNodeRemover; import org.apache.pig.newplan.logical.visitor.SortInfoSetter; import org.apache.pig.newplan.logical.visitor.StoreAliasSetter; import org.apache.pig.parser.ParserException; import org.apache.pig.parser.QueryParserDriver; import org.apache.pig.tools.grunt.GruntParser; import org.apache.pig.tools.pigstats.ScriptState; import org.apache.spark.package$; import org.junit.Assert; import com.google.common.base.Function; import com.google.common.collect.Lists; public class Util { private static BagFactory mBagFactory = BagFactory.getInstance(); private static TupleFactory mTupleFactory = TupleFactory.getInstance(); // Commonly-checked system state // ================= public static final boolean WINDOWS /* borrowed from Path.WINDOWS, Shell.WINDOWS */ = System.getProperty("os.name").startsWith("Windows"); public static final String TEST_DIR = System.getProperty("test.build.dir", "build/test"); // Helper Functions // ================= static public Tuple loadFlatTuple(Tuple t, int[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, new Integer(input[i])); } return t; } static public Tuple loadTuple(Tuple t, String[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadTuple(Tuple t, DataByteArray[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadNestTuple(Tuple t, int[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } static public Tuple loadNestTuple(Tuple t, long[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, new Long(input[i])); bag.add(f); } t.set(0, bag); return t; } // this one should handle String, DataByteArray, Long, Integer etc.. static public <T> Tuple loadNestTuple(Tuple t, T[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } /** * Create an array of tuple bags with specified size created by splitting * the input array of primitive types * * @param input Array of primitive types * @param bagSize The number of tuples to be split and copied into each bag * * @return an array of tuple bags with each bag containing bagSize tuples split from the input */ static public <T> Tuple[] splitCreateBagOfTuples(T[] input, int bagSize) throws ExecException { List<Tuple> result = new ArrayList<Tuple>(); for (int from = 0; from < input.length; from += bagSize) { Tuple t = TupleFactory.getInstance().newTuple(1); int to = from + bagSize < input.length ? from + bagSize : input.length; T[] array = Arrays.copyOfRange(input, from, to); result.add(loadNestTuple(t, array)); } return result.toArray(new Tuple[0]); } static public <T>void addToTuple(Tuple t, T[] b) { for(int i = 0; i < b.length; i++) t.append(b[i]); } static public Tuple buildTuple(Object... args) throws ExecException { return TupleFactory.getInstance().newTupleNoCopy(Lists.newArrayList(args)); } static public Tuple buildBinTuple(final Object... args) throws IOException { return TupleFactory.getInstance().newTuple(Lists.transform( Lists.newArrayList(args), new Function<Object, DataByteArray>() { @Override public DataByteArray apply(Object o) { if (o == null) { return null; } try { return new DataByteArray(DataType.toBytes(o)); } catch (ExecException e) { return null; } } })); } static public <T>Tuple createTuple(T[] s) { Tuple t = mTupleFactory.newTuple(); addToTuple(t, s); return t; } static public DataBag createBag(Tuple[] t) { DataBag b = mBagFactory.newDefaultBag(); for(int i = 0; i < t.length; i++)b.add(t[i]); return b; } static public<T> DataBag createBagOfOneColumn(T[] input) throws ExecException { DataBag result = mBagFactory.newDefaultBag(); for (int i = 0; i < input.length; i++) { Tuple t = mTupleFactory.newTuple(1); t.set(0, input[i]); result.add(t); } return result; } static public Map<String, Object> createMap(String[] contents) { Map<String, Object> m = new HashMap<String, Object>(); for(int i = 0; i < contents.length; ) { m.put(contents[i], contents[i+1]); i += 2; } return m; } static public<T> DataByteArray[] toDataByteArrays(T[] input) { DataByteArray[] dbas = new DataByteArray[input.length]; for (int i = 0; i < input.length; i++) { dbas[i] = (input[i] == null)?null:new DataByteArray(input[i].toString().getBytes()); } return dbas; } static public Tuple loadNestTuple(Tuple t, int[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadFlatTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } static public Tuple loadTuple(Tuple t, String[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } /** * Helper to remove colons (if any exist) from paths to sanitize them for * consumption by hdfs. * * @param origPath original path name * @return String sanitized path with anything prior to : removed * @throws IOException */ static public String removeColon(String origPath) { return origPath.replaceAll(":", ""); } /** * Helper to convert \r\n to \n for cross-platform string * matching with checked-in baselines. * * @param origPath original string * @return String newline-standardized string * @throws IOException */ static public String standardizeNewline(String origPath) { return origPath.replaceAll("\r\n", "\n"); } /** * Helper to create a temporary file with given input data for use in test cases. * * @param tmpFilenamePrefix file-name prefix * @param tmpFilenameSuffix file-name suffix * @param inputData input for test cases, each string in inputData[] is written * on one line * @return {@link File} handle to the created temporary file * @throws IOException */ static public File createInputFile(String tmpFilenamePrefix, String tmpFilenameSuffix, String[] inputData) throws IOException { File f = File.createTempFile(tmpFilenamePrefix, tmpFilenameSuffix); f.deleteOnExit(); writeToFile(f, inputData); return f; } static public File createLocalInputFile(String filename, String[] inputData) throws IOException { File f = new File(filename); f.deleteOnExit(); writeToFile(f, inputData); return f; } public static void writeToFile(File f, String[] inputData) throws IOException { PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } /** * Helper to create a dfs file on the Minicluster DFS with given * input data for use in test cases. * * @param miniCluster reference to the Minicluster where the file should be created * @param fileName pathname of the file to be created * @param inputData input for test cases, each string in inputData[] is written * on one line * @throws IOException */ static public void createInputFile(MiniGenericCluster miniCluster, String fileName, String[] inputData) throws IOException { FileSystem fs = miniCluster.getFileSystem(); createInputFile(fs, fileName, inputData); } static public void createInputFile(FileSystem fs, String fileName, String[] inputData) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if(fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the FileSystem"); } FSDataOutputStream stream = fs.create(new Path(fileName)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(stream, "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } static public String[] readOutput(FileSystem fs, String fileName) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } Path path = new Path(fileName); if(!fs.exists(path)) { throw new IOException("Path " + fileName + " does not exist on the FileSystem"); } FileStatus fileStatus = fs.getFileStatus(path); FileStatus[] files; if (fileStatus.isDirectory()) { files = fs.listStatus(path, new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }); } else { files = new FileStatus[] { fileStatus }; } List<String> result = new ArrayList<String>(); for (FileStatus f : files) { FSDataInputStream stream = fs.open(f.getPath()); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line; while ((line = br.readLine()) != null) { result.add(line); } br.close(); } return result.toArray(new String[result.size()]); } /** * Helper to create a dfs file on the MiniCluster dfs. This returns an * outputstream that can be used in test cases to write data. * * @param cluster * reference to the MiniCluster where the file should be created * @param fileName * pathname of the file to be created * @return OutputStream to write any data to the file created on the * MiniCluster. * @throws IOException */ static public OutputStream createInputFile(MiniGenericCluster cluster, String fileName) throws IOException { FileSystem fs = cluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if (fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the minicluster"); } return fs.create(new Path(fileName)); } /** * Helper to create an empty temp file on local file system * which will be deleted on exit * @param prefix * @param suffix * @return File denoting a newly-created empty file * @throws IOException */ static public File createTempFileDelOnExit(String prefix, String suffix) throws IOException { File tmpFile = File.createTempFile(prefix, suffix); tmpFile.deleteOnExit(); return tmpFile; } /** * Helper to remove a dfs file from the minicluster DFS * * @param miniCluster reference to the Minicluster where the file should be deleted * @param fileName pathname of the file to be deleted * @throws IOException */ static public void deleteFile(MiniGenericCluster miniCluster, String fileName) throws IOException { FileSystem fs = miniCluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } /** * Deletes a dfs file from the MiniCluster DFS quietly * * @param miniCluster the MiniCluster where the file should be deleted * @param fileName the path of the file to be deleted */ public static void deleteQuietly(MiniGenericCluster miniCluster, String fileName) { try { deleteFile(miniCluster, fileName); } catch (IOException ignored) { } } static public void deleteFile(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } static public boolean exists(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } return fs.exists(new Path(fileName)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results Array to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Tuple[] expectedResults) { checkQueryOutputs(actualResults, Arrays.asList(expectedResults)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults) { checkQueryOutputs(actualResults, expectedResults.iterator(), null ); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Iterator<Tuple> expectedResults, Integer expectedRows) { int count = 0; while (expectedResults.hasNext()) { Tuple expected = expectedResults.next(); Assert.assertTrue("Actual result has less records than expected results", actualResults.hasNext()); Tuple actual = actualResults.next(); // If this tuple contains any bags, bags will be sorted before comparisons if( !expected.equals(actual) ) { // Using string comparisons since error message is more readable // (only showing the part which differs) Assert.assertEquals(expected.toString(), actual.toString()); // if above goes through, simply failing with object comparisons Assert.assertEquals(expected, actual); } count++; } Assert.assertFalse("Actual result has more records than expected results", actualResults.hasNext()); if (expectedRows != null) { Assert.assertEquals((int)expectedRows, count); } } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResList Expected results to validate against */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, List<Tuple> expectedResList) { List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } checkQueryOutputsAfterSort(actualResList, expectedResList); } /** * Helper function to check if the result of Pig Query is in line with expected results. * It sorts actual and expected results before comparison. * The tuple size in the tuple list can vary. Pass by a two-dimension array, it will be converted to be a tuple list. * e.g. expectedTwoDimensionObjects is [{{10, "will_join", 10, "will_join"}, {11, "will_not_join", null}, {null, 12, "will_not_join"}}], * the field size of these 3 tuples are [4,3,3] * * @param actualResultsIt * @param expectedTwoDimensionObjects represents a tuple list, in which the tuple can have variable size. */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Object[][] expectedTwoDimensionObjects) { List<Tuple> expectedResTupleList = new ArrayList<Tuple>(); for (int i = 0; i < expectedTwoDimensionObjects.length; ++i) { Tuple t = TupleFactory.getInstance().newTuple(); for (int j = 0; j < expectedTwoDimensionObjects[i].length; ++j) { t.append(expectedTwoDimensionObjects[i][j]); } expectedResTupleList.add(t); } checkQueryOutputsAfterSort(actualResultsIt, expectedResTupleList); } static public void checkQueryOutputsAfterSort( List<Tuple> actualResList, List<Tuple> expectedResList) { Collections.sort(actualResList); Collections.sort(expectedResList); checkQueryOutputs(actualResList.iterator(), expectedResList); } /** * Check if subStr is a subString of str . calls org.junit.Assert.fail if it is not * @param str * @param subStr */ static public void checkStrContainsSubStr(String str, String subStr){ if(!str.contains(subStr)){ fail("String '"+ subStr + "' is not a substring of '" + str + "'"); } } /** * Check if query plan for alias argument produces exception with expected * error message in expectedErr argument. * @param query * @param alias * @param expectedErr * @throws IOException */ static public void checkExceptionMessage(String query, String alias, String expectedErr) throws IOException { PigServer pig = new PigServer(ExecType.LOCAL); boolean foundEx = false; try{ Util.registerMultiLineQuery(pig, query); pig.explain(alias, System.out); }catch(FrontendException e){ foundEx = true; checkMessageInException(e, expectedErr); } if(!foundEx) fail("No exception thrown. Exception is expected."); } public static void checkMessageInException(FrontendException e, String expectedErr) { PigException pigEx = LogUtils.getPigException(e); String message = pigEx.getMessage(); checkErrorMessageContainsExpected(message, expectedErr); } public static void checkErrorMessageContainsExpected(String message, String expectedMessage){ if(!message.contains(expectedMessage)){ String msg = "Expected error message containing '" + expectedMessage + "' but got '" + message + "'" ; fail(msg); } } static private String getFSMkDirCommand(String fileName) { Path parentDir = new Path(fileName).getParent(); String mkdirCommand = parentDir.getName().isEmpty() ? "" : "fs -mkdir -p " + parentDir + "\n"; return mkdirCommand; } /** * Utility method to copy a file form local filesystem to the dfs on * the minicluster for testing in mapreduce mode * @param cluster a reference to the minicluster * @param localFileName the pathname of local file * @param fileNameOnCluster the name with which the file should be created on the minicluster * @throws IOException */ static public void copyFromLocalToCluster(MiniGenericCluster cluster, String localFileName, String fileNameOnCluster) throws IOException { if(Util.WINDOWS){ if (!localFileName.contains(":")) { localFileName = localFileName.replace('\\','/'); } else { localFileName = localFileName.replace('/','\\'); } fileNameOnCluster = fileNameOnCluster.replace('\\','/'); } PigServer ps = new PigServer(cluster.getExecType(), cluster.getProperties()); String script = getFSMkDirCommand(fileNameOnCluster) + "fs -put " + localFileName + " " + fileNameOnCluster; GruntParser parser = new GruntParser(new StringReader(script), ps); parser.setInteractive(false); try { parser.parseStopOnError(); } catch (org.apache.pig.tools.pigscript.parser.ParseException e) { throw new IOException(e); } } static public void copyFromLocalToLocal(String fromLocalFileName, String toLocalFileName) throws IOException { FileUtils.copyFile(new File(fromLocalFileName), new File(toLocalFileName)); } static public void copyFromClusterToLocal(MiniGenericCluster cluster, String fileNameOnCluster, String localFileName) throws IOException { if(Util.WINDOWS){ fileNameOnCluster = fileNameOnCluster.replace('\\','/'); localFileName = localFileName.replace('\\','/'); } File parent = new File(localFileName).getParentFile(); if (!parent.exists()) { parent.mkdirs(); } PrintWriter writer = new PrintWriter(new FileWriter(localFileName)); FileSystem fs = FileSystem.get(ConfigurationUtil.toConfiguration( cluster.getProperties())); if(!fs.exists(new Path(fileNameOnCluster))) { throw new IOException("File " + fileNameOnCluster + " does not exists on the minicluster"); } String line = null; FileStatus fst = fs.getFileStatus(new Path(fileNameOnCluster)); if(fst.isDirectory()) { throw new IOException("Only files from cluster can be copied locally," + " " + fileNameOnCluster + " is a directory"); } FSDataInputStream stream = fs.open(new Path(fileNameOnCluster)); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while( (line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); } static public void printQueryOutput(Iterator<Tuple> actualResults, Tuple[] expectedResults) { System.out.println("Expected :") ; for (Tuple expected : expectedResults) { System.out.println(expected.toString()) ; } System.out.println("---End----") ; System.out.println("Actual :") ; while (actualResults.hasNext()) { System.out.println(actualResults.next().toString()) ; } System.out.println("---End----") ; } /** * Helper method to replace all occurrences of "\" with "\\" in a * string. This is useful to fix the file path string on Windows * where "\" is used as the path separator. * * @param str Any string * @return The resulting string */ public static String encodeEscape(String str) { String regex = "\\\\"; String replacement = quoteReplacement("\\\\"); return str.replaceAll(regex, replacement); } public static String generateURI(String filename, PigContext context) throws IOException { if(Util.WINDOWS){ filename = filename.replace('\\','/'); } if (context.getExecType() == ExecType.MAPREDUCE || context.getExecType().name().equals("TEZ") || context.getExecType().name().equals("SPARK")) { return FileLocalizer.hadoopify(filename, context); } else if (context.getExecType().isLocal()) { return filename; } else { throw new IllegalStateException("ExecType: " + context.getExecType()); } } public static Object getPigConstant(String pigConstantAsString) throws ParserException { QueryParserDriver queryParser = new QueryParserDriver( new PigContext(), "util", new HashMap<String, String>() ) ; return queryParser.parseConstant(pigConstantAsString); } /** * Parse list of strings in to list of tuples, convert quoted strings into * @param tupleConstants * @return * @throws ParserException */ public static List<Tuple> getTuplesFromConstantTupleStrings(String[] tupleConstants) throws ParserException { List<Tuple> result = new ArrayList<Tuple>(tupleConstants.length); for(int i = 0; i < tupleConstants.length; i++) { result.add((Tuple) getPigConstant(tupleConstants[i])); } return result; } /** * Parse list of strings in to list of tuples, convert quoted strings into * DataByteArray * @param tupleConstants * @return * @throws ParserException * @throws ExecException */ public static List<Tuple> getTuplesFromConstantTupleStringAsByteArray(String[] tupleConstants) throws ParserException, ExecException { List<Tuple> tuples = getTuplesFromConstantTupleStrings(tupleConstants); for(Tuple t : tuples){ convertStringToDataByteArray(t); } return tuples; } /** * Convert String objects in argument t to DataByteArray objects * @param t * @throws ExecException */ private static void convertStringToDataByteArray(Tuple t) throws ExecException { if(t == null) return; for(int i=0; i<t.size(); i++){ Object col = t.get(i); if(col == null) continue; if(col instanceof String){ DataByteArray dba = (col == null) ? null : new DataByteArray((String)col); t.set(i, dba); }else if(col instanceof Tuple){ convertStringToDataByteArray((Tuple)col); }else if(col instanceof DataBag){ Iterator<Tuple> it = ((DataBag)col).iterator(); while(it.hasNext()){ convertStringToDataByteArray(it.next()); } } } } public static File createFile(String[] data) throws Exception{ return createFile(null,data); } public static File createFile(String filePath, String[] data) throws Exception { File f; if( null == filePath || filePath.isEmpty() ) { f = File.createTempFile("tmp", ""); } else { f = new File(filePath); } if (f.getParent() != null && !(new File(f.getParent())).exists()) { (new File(f.getParent())).mkdirs(); } f.deleteOnExit(); PrintWriter pw = new PrintWriter(f); for (int i=0; i<data.length; i++){ pw.println(data[i]); } pw.close(); return f; } /** * Run default set of optimizer rules on new logical plan * @param lp * @return optimized logical plan * @throws FrontendException */ public static LogicalPlan optimizeNewLP( LogicalPlan lp) throws FrontendException{ DanglingNestedNodeRemover DanglingNestedNodeRemover = new DanglingNestedNodeRemover( lp ); DanglingNestedNodeRemover.visit(); UidResetter uidResetter = new UidResetter( lp ); uidResetter.visit(); SchemaResetter schemaResetter = new SchemaResetter( lp, true /*disable duplicate uid check*/ ); schemaResetter.visit(); StoreAliasSetter storeAliasSetter = new StoreAliasSetter( lp ); storeAliasSetter.visit(); // run optimizer org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer optimizer = new org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer(lp, 100, null); optimizer.optimize(); SortInfoSetter sortInfoSetter = new SortInfoSetter( lp ); sortInfoSetter.visit(); return lp; } /** * migrate old LP(logical plan) to new LP, optimize it, and build physical * plan * @param lp * @param pc PigContext * @return physical plan * @throws Exception */ public static PhysicalPlan buildPhysicalPlanFromNewLP( LogicalPlan lp, PigContext pc) throws Exception { LogToPhyTranslationVisitor visitor = new LogToPhyTranslationVisitor(lp); visitor.setPigContext(pc); visitor.visit();<|fim▁hole|> public static MROperPlan buildMRPlan(PhysicalPlan pp, PigContext pc) throws Exception{ MRCompiler comp = new MRCompiler(pp, pc); comp.compile(); comp.aggregateScalarsFiles(); comp.connectSoftLink(); return comp.getMRPlan(); } public static MROperPlan buildMRPlanWithOptimizer(PhysicalPlan pp, PigContext pc) throws Exception { MapRedUtil.checkLeafIsStore(pp, pc); MapReduceLauncher launcher = new MapReduceLauncher(); return launcher.compile(pp,pc); } public static MROperPlan buildMRPlan(String query, PigContext pc) throws Exception { LogicalPlan lp = Util.parse(query, pc); Util.optimizeNewLP(lp); PhysicalPlan pp = Util.buildPhysicalPlanFromNewLP(lp, pc); MROperPlan mrp = Util.buildMRPlanWithOptimizer(pp, pc); return mrp; } public static void registerMultiLineQuery(PigServer pigServer, String query) throws IOException { File f = File.createTempFile("tmp", ""); PrintWriter pw = new PrintWriter(f); pw.println(query); pw.close(); pigServer.registerScript(f.getCanonicalPath()); } public static int executeJavaCommand(String cmd) throws Exception { return executeJavaCommandAndReturnInfo(cmd).exitCode; } public static class ReadStream implements Runnable { InputStream is; Thread thread; String message = ""; public ReadStream(InputStream is) { this.is = is; } public void start () { thread = new Thread (this); thread.start (); } @Override public void run () { try { InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); while (true) { String s = br.readLine (); if (s == null) break; if (!message.isEmpty()) { message += "\n"; } message += s; } is.close (); } catch (Exception ex) { ex.printStackTrace (); } } public String getMessage() { return message; } } public static ProcessReturnInfo executeJavaCommandAndReturnInfo(String cmd) throws Exception { String javaHome = System.getenv("JAVA_HOME"); if(javaHome != null) { String fileSeparator = System.getProperty("file.separator"); cmd = javaHome + fileSeparator + "bin" + fileSeparator + cmd; } Process cmdProc = Runtime.getRuntime().exec(cmd); ProcessReturnInfo pri = new ProcessReturnInfo(); ReadStream stdoutStream = new ReadStream(cmdProc.getInputStream ()); ReadStream stderrStream = new ReadStream(cmdProc.getErrorStream ()); stdoutStream.start(); stderrStream.start(); cmdProc.waitFor(); pri.exitCode = cmdProc.exitValue(); pri.stdoutContents = stdoutStream.getMessage(); pri.stderrContents = stderrStream.getMessage(); return pri; } public static class ProcessReturnInfo { public int exitCode; public String stderrContents; public String stdoutContents; @Override public String toString() { return "[Exit code: " + exitCode + ", stdout: <" + stdoutContents + ">, " + "stderr: <" + stderrContents + ">"; } } static public boolean deleteDirectory(File path) { if(path.exists()) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return(path.delete()); } /** * @param pigContext * @param fileName * @param input * @throws IOException */ public static void createInputFile(PigContext pigContext, String fileName, String[] input) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); createInputFile(FileSystem.get(conf), fileName, input); } public static String[] readOutput(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); return readOutput(FileSystem.get(conf), fileName); } public static void printPlan(LogicalPlan logicalPlan ) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); LogicalPlanPrinter pp = new LogicalPlanPrinter(logicalPlan,ps); pp.visit(); System.err.println(out.toString()); } public static void printPlan(PhysicalPlan physicalPlan) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); physicalPlan.explain(ps, "text", true); System.err.println(out.toString()); } public static List<Tuple> readFile2TupleList(String file, String delimiter) throws IOException{ List<Tuple> tuples=new ArrayList<Tuple>(); String line=null; BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(file))); while((line=reader.readLine())!=null){ String[] tokens=line.split(delimiter); Tuple tuple=TupleFactory.getInstance().newTuple(Arrays.asList(tokens)); tuples.add(tuple); } reader.close(); return tuples; } /** * Delete the existing logFile for the class and set the logging to a * use a new log file and set log level to DEBUG * @param clazz class for which the log file is being set * @param logFile current log file * @return new log file * @throws Exception */ public static File resetLog(Class<?> clazz, File logFile) throws Exception { if (logFile != null) logFile.delete(); Logger logger = Logger.getLogger(clazz); logger.removeAllAppenders(); logger.setLevel(Level.DEBUG); SimpleLayout layout = new SimpleLayout(); File newLogFile = File.createTempFile("log", ""); FileAppender appender = new FileAppender(layout, newLogFile.toString(), false, false, 0); logger.addAppender(appender); return newLogFile; } /** * Check if logFile (does not/)contains the given list of messages. * @param logFile * @param messages * @param expected if true, the messages are expected in the logFile, * otherwise messages should not be there in the log */ public static void checkLogFileMessage(File logFile, String[] messages, boolean expected) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); String logMessage = ""; String line; while ((line = reader.readLine()) != null) { logMessage = logMessage + line + "\n"; } reader.close(); for (int i = 0; i < messages.length; i++) { boolean present = logMessage.contains(messages[i]); if (expected) { if(!present){ fail("The message " + messages[i] + " is not present in" + "log file contents: " + logMessage); } }else{ if(present){ fail("The message " + messages[i] + " is present in" + "log file contents: " + logMessage); } } } return ; } catch (IOException e) { fail("caught exception while checking log message :" + e); } } public static LogicalPlan buildLp(PigServer pigServer, String query) throws Exception { pigServer.setBatchOn(); pigServer.registerQuery( query ); java.lang.reflect.Method buildLp = pigServer.getClass().getDeclaredMethod("buildLp"); buildLp.setAccessible(true); return (LogicalPlan ) buildLp.invoke( pigServer ); } public static PhysicalPlan buildPp(PigServer pigServer, String query) throws Exception { LogicalPlan lp = buildLp( pigServer, query ); lp.optimize(pigServer.getPigContext()); return ((HExecutionEngine)pigServer.getPigContext().getExecutionEngine()).compile(lp, pigServer.getPigContext().getProperties()); } public static LogicalPlan parse(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } public static LogicalPlan parseAndPreprocess(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } /** * Replaces any alias in given schema that has name that starts with * "NullAlias" with null . it does a case insensitive comparison of * the alias name * @param sch */ public static void schemaReplaceNullAlias(Schema sch){ if(sch == null) return ; for(FieldSchema fs : sch.getFields()){ if(fs.alias != null && fs.alias.toLowerCase().startsWith("nullalias")){ fs.alias = null; } schemaReplaceNullAlias(fs.schema); } } static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Tuple[] expectedResArray) { List<Tuple> list = new ArrayList<Tuple>(); Collections.addAll(list, expectedResArray); checkQueryOutputsAfterSort(actualResultsIt, list); } static public void convertBagToSortedBag(Tuple t) { for (int i=0;i<t.size();i++) { Object obj = null; try { obj = t.get(i); } catch (ExecException e) { // shall not happen } if (obj instanceof DataBag) { DataBag bag = (DataBag)obj; Iterator<Tuple> iter = bag.iterator(); DataBag sortedBag = DefaultBagFactory.getInstance().newSortedBag(null); while (iter.hasNext()) { Tuple t2 = iter.next(); sortedBag.add(t2); convertBagToSortedBag(t2); } try { t.set(i, sortedBag); } catch (ExecException e) { // shall not happen } } } } static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, String schemaString) throws IOException { LogicalSchema resultSchema = org.apache.pig.impl.util.Utils.parseSchema(schemaString); checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, resultSchema); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected string results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResArray Expected string results to validate against * @param schema fieldSchema of expecteResArray * @throws IOException */ static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Collections.sort(actualResList); Collections.sort(expectedResList); Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static String readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String result = ""; String line; while ((line=reader.readLine())!=null) { result += line; result += "\n"; } reader.close(); return result; } /** * this removes the signature from the serialized plan changing the way the * unique signature is generated should not break this test * @param plan the plan to canonicalize * @return the cleaned up plan */ public static String removeSignature(String plan) { return plan.replaceAll("','','[^']*','scope','true'\\)\\)", "','','','scope','true'))"); } public static boolean isHadoop203plus() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.2\\b")) return false; return true; } public static boolean isHadoop205() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.205\\..+")) return true; return false; } public static boolean isHadoop1_x() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b1\\.*\\..+")) return true; return false; } public static boolean isSpark2_2_plus() throws IOException { String sparkVersion = package$.MODULE$.SPARK_VERSION(); return sparkVersion != null && sparkVersion.matches("2\\.([\\d&&[^01]]|[\\d]{2,})\\..*"); } public static void sortQueryOutputsIfNeed(List<Tuple> actualResList, boolean toSort){ if( toSort == true) { for (Tuple t : actualResList) { Util.convertBagToSortedBag(t); } Collections.sort(actualResList); } } public static void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults, boolean checkAfterSort) { if (checkAfterSort) { checkQueryOutputsAfterSort(actualResults, expectedResults); } else { checkQueryOutputs(actualResults, expectedResults); } } static public void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema, boolean checkAfterSort) throws IOException { if (checkAfterSort) { checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, schema); } else { checkQueryOutputs(actualResultsIt, expectedResArray, schema); } } static void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while (actualResultsIt.hasNext()) { actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static void assertParallelValues(long defaultParallel, long requestedParallel, long estimatedParallel, long runtimeParallel, Configuration conf) { assertConfLong(conf, "pig.info.reducers.default.parallel", defaultParallel); assertConfLong(conf, "pig.info.reducers.requested.parallel", requestedParallel); assertConfLong(conf, "pig.info.reducers.estimated.parallel", estimatedParallel); assertConfLong(conf, MRConfiguration.REDUCE_TASKS, runtimeParallel); } public static void assertConfLong(Configuration conf, String param, long expected) { assertEquals("Unexpected value found in configs for " + param, expected, conf.getLong(param, -1)); } /** * Returns a PathFilter that filters out filenames that start with _. * @return PathFilter */ public static PathFilter getSuccessMarkerPathFilter() { return new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }; } /** * * @param expected * Exception class that is expected to be thrown * @param found * Exception that occurred in the test * @param message * expected String to verify against */ public static void assertExceptionAndMessage(Class<?> expected, Exception found, String message) { assertEquals(expected, found.getClass()); assertEquals(found.getMessage(), message); } /** * Called to reset ThreadLocal or static states that PigServer depends on * when a test suite has testcases switching between LOCAL and MAPREDUCE/TEZ * execution modes */ public static void resetStateForExecModeSwitch() { FileLocalizer.setInitialized(false); // For tez testing, we want to avoid TezResourceManager/LocalResource reuse // (when switching between local and mapreduce/tez) TezResourceManager.dropInstance(); // TODO: once we have Tez local mode, we can get rid of this. For now, // if we run this test suite in Tez mode and there are some tests // in LOCAL mode, we need to set ScriptState to // null to force ScriptState gets initialized every time. ScriptState.start(null); } public static boolean isMapredExecType(ExecType execType) { return execType == ExecType.MAPREDUCE; } public static boolean isTezExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("tez")) { return true; } return false; } public static boolean isSparkExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("spark")) { return true; } return false; } public static String findPigJarName() { final String suffix = System.getProperty("hadoopversion").equals("20") ? "1" : "2"; File baseDir = new File("."); String[] jarNames = baseDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.matches("pig.*h" + suffix + "\\.jar")) { return false; } if (name.contains("all")) { return false; } return true; } }); if (jarNames==null || jarNames.length!=1) { throw new RuntimeException("Cannot find pig.jar"); } return jarNames[0]; } public static ExecType getLocalTestMode() throws Exception { String execType = System.getProperty("test.exec.type"); if (execType != null) { if (execType.equals("tez")) { return ExecTypeProvider.fromString("tez_local"); } else if (execType.equals("spark")) { return ExecTypeProvider.fromString("spark_local"); } } return ExecTypeProvider.fromString("local"); } public static void createLogAppender(String appenderName, Writer writer, Class...clazzes) { WriterAppender writerAppender = new WriterAppender(new PatternLayout("%d [%t] %-5p %c %x - %m%n"), writer); writerAppender.setName(appenderName); for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); logger.addAppender(writerAppender); } } public static void removeLogAppender(String appenderName, Class...clazzes) { for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); Appender appender = logger.getAppender(appenderName); appender.close(); logger.removeAppender(appenderName); } } public static Path getFirstPartFile(Path path) throws Exception { FileStatus[] parts = FileSystem.get(path.toUri(), new Configuration()).listStatus(path, new PathFilter() { @Override public boolean accept(Path path) { return path.getName().startsWith("part-"); } }); return parts[0].getPath(); } public static File getFirstPartFile(File dir) throws Exception { File[] parts = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("part-"); }; }); return parts[0]; } @SuppressWarnings("rawtypes") public static String getTestDirectory(Class testClass) { return TEST_DIR + Path.SEPARATOR + "testdata" + Path.SEPARATOR +testClass.getSimpleName(); } }<|fim▁end|>
return visitor.getPhysicalPlan(); }
<|file_name|>endpoint_cache_test.go<|end_file_name|><|fim▁begin|>package loadbalancer_test import ( "io" "testing" "time" "golang.org/x/net/context" "github.com/go-kit/kit/endpoint" "github.com/go-kit/kit/loadbalancer" "github.com/go-kit/kit/log" ) func TestEndpointCache(t *testing.T) { var ( e = func(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil } ca = make(closer) cb = make(closer) c = map[string]io.Closer{"a": ca, "b": cb} f = func(s string) (endpoint.Endpoint, io.Closer, error) { return e, c[s], nil } ec = loadbalancer.NewEndpointCache(f, log.NewNopLogger()) ) // Populate ec.Replace([]string{"a", "b"}) select { case <-ca: t.Errorf("endpoint a closed, not good") case <-cb: t.Errorf("endpoint b closed, not good") case <-time.After(time.Millisecond): t.Logf("no closures yet, good") } // Duplicate, should be no-op ec.Replace([]string{"a", "b"}) select { case <-ca: t.Errorf("endpoint a closed, not good") case <-cb: t.Errorf("endpoint b closed, not good") case <-time.After(time.Millisecond): t.Logf("no closures yet, good") } // Delete b go ec.Replace([]string{"a"}) select { case <-ca: t.Errorf("endpoint a closed, not good") case <-cb: t.Logf("endpoint b closed, good") case <-time.After(time.Millisecond):<|fim▁hole|> // Delete a go ec.Replace([]string{""}) select { // case <-cb: will succeed, as it's closed case <-ca: t.Logf("endpoint a closed, good") case <-time.After(time.Millisecond): t.Errorf("didn't close the deleted instance in time") } } type closer chan struct{} func (c closer) Close() error { close(c); return nil }<|fim▁end|>
t.Errorf("didn't close the deleted instance in time") }
<|file_name|>placeholderhandler.go<|end_file_name|><|fim▁begin|>package compiler import ( "bytes" "fmt" "net/http" "github.com/go-on/lib/html/element" "github.com/go-on/lib/misc/replacer" ) func mkPhHandler(e *element.Element, key string, buf *bytes.Buffer) (phdl []*placeholderHandler) { phdl = []*placeholderHandler{} element.Pre(e, buf) // fmt.Printf("checking %s\n", e.Tag()) if len(e.Children) == 0 || element.Is(e, element.SelfClosing) { // fmt.Printf("no children\n") element.Post(e, buf) return } // fmt.Printf("no children %d\n", len(e.Children)) for i, in := range e.Children { // fmt.Printf("children %T\n", in) switch ch := in.(type) { case *element.Element: phdl = append( phdl, mkPhHandler(ch, fmt.Sprintf("%s/%d", key, i), buf)..., ) case http.Handler: // fmt.Printf("is http.Handler: %T\n", ch) pha := replacer.Placeholder(fmt.Sprintf("%s-%d", key, i)) phdl = append(phdl, &placeholderHandler{pha, ch}) buf.WriteString(pha.String()) default: buf.WriteString(in.String()) } } <|fim▁hole|> return } type placeholderHandler struct { replacer.Placeholder http.Handler }<|fim▁end|>
element.Post(e, buf)
<|file_name|>kinds.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. /*! The kind traits Rust types can be classified in various useful ways according to intrinsic properties of the type. These classifications, often called 'kinds', are represented as traits. They cannot be implemented by user code, but are instead implemented by the compiler automatically for the types to which they apply. The 3 kinds are * Copy - types that may be copied without allocation. This includes scalar types and managed pointers, and exludes owned pointers. It also excludes types that implement `Drop`. * Send - owned types and types containing owned types. These types may be transferred across task boundaries. * Freeze - types that are deeply immutable. `Copy` types include both implicitly copyable types that the compiler will copy automatically and non-implicitly copyable types that require the `copy` keyword to copy. Types that do not implement `Copy` may instead implement `Clone`. */ #[allow(missing_doc)]; #[lang="copy"] pub trait Copy { // Empty. }<|fim▁hole|>pub trait Send { // empty. } #[cfg(not(stage0))] #[lang="send"] pub trait Send { // empty. } #[cfg(stage0)] #[lang="const"] pub trait Freeze { // empty. } #[cfg(not(stage0))] #[lang="freeze"] pub trait Freeze { // empty. } #[lang="sized"] pub trait Sized { // Empty. }<|fim▁end|>
#[cfg(stage0)] #[lang="owned"]
<|file_name|>gesture.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use EventController; use EventSequenceState; use ffi; use gdk; use gdk_ffi; use glib::StaticType; use glib::Value; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::fmt; use std::mem; use std::mem::transmute; glib_wrapper! { pub struct Gesture(Object<ffi::GtkGesture, ffi::GtkGestureClass, GestureClass>) @extends EventController; match fn { get_type => || ffi::gtk_gesture_get_type(), } } pub const NONE_GESTURE: Option<&Gesture> = None; pub trait GestureExt: 'static { fn get_bounding_box(&self) -> Option<gdk::Rectangle>; fn get_bounding_box_center(&self) -> Option<(f64, f64)>; fn get_device(&self) -> Option<gdk::Device>; fn get_group(&self) -> Vec<Gesture>; fn get_last_event<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> Option<gdk::Event>; fn get_last_updated_sequence(&self) -> Option<gdk::EventSequence>; fn get_point<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> Option<(f64, f64)>; fn get_sequence_state(&self, sequence: &gdk::EventSequence) -> EventSequenceState; fn get_sequences(&self) -> Vec<gdk::EventSequence>; fn get_window(&self) -> Option<gdk::Window>; fn group<P: IsA<Gesture>>(&self, gesture: &P); fn handles_sequence<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> bool; fn is_active(&self) -> bool; fn is_grouped_with<P: IsA<Gesture>>(&self, other: &P) -> bool; fn is_recognized(&self) -> bool; fn set_sequence_state(&self, sequence: &gdk::EventSequence, state: EventSequenceState) -> bool; fn set_state(&self, state: EventSequenceState) -> bool; <|fim▁hole|> fn ungroup(&self); fn get_property_n_points(&self) -> u32; fn connect_begin<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_cancel<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_end<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_sequence_state_changed<F: Fn(&Self, &gdk::EventSequence, EventSequenceState) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_update<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_window_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<Gesture>> GestureExt for O { fn get_bounding_box(&self) -> Option<gdk::Rectangle> { unsafe { let mut rect = gdk::Rectangle::uninitialized(); let ret = from_glib(ffi::gtk_gesture_get_bounding_box(self.as_ref().to_glib_none().0, rect.to_glib_none_mut().0)); if ret { Some(rect) } else { None } } } fn get_bounding_box_center(&self) -> Option<(f64, f64)> { unsafe { let mut x = mem::uninitialized(); let mut y = mem::uninitialized(); let ret = from_glib(ffi::gtk_gesture_get_bounding_box_center(self.as_ref().to_glib_none().0, &mut x, &mut y)); if ret { Some((x, y)) } else { None } } } fn get_device(&self) -> Option<gdk::Device> { unsafe { from_glib_none(ffi::gtk_gesture_get_device(self.as_ref().to_glib_none().0)) } } fn get_group(&self) -> Vec<Gesture> { unsafe { FromGlibPtrContainer::from_glib_container(ffi::gtk_gesture_get_group(self.as_ref().to_glib_none().0)) } } fn get_last_event<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> Option<gdk::Event> { let sequence = sequence.into(); unsafe { from_glib_none(ffi::gtk_gesture_get_last_event(self.as_ref().to_glib_none().0, mut_override(sequence.to_glib_none().0))) } } fn get_last_updated_sequence(&self) -> Option<gdk::EventSequence> { unsafe { from_glib_none(ffi::gtk_gesture_get_last_updated_sequence(self.as_ref().to_glib_none().0)) } } fn get_point<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> Option<(f64, f64)> { let sequence = sequence.into(); unsafe { let mut x = mem::uninitialized(); let mut y = mem::uninitialized(); let ret = from_glib(ffi::gtk_gesture_get_point(self.as_ref().to_glib_none().0, mut_override(sequence.to_glib_none().0), &mut x, &mut y)); if ret { Some((x, y)) } else { None } } } fn get_sequence_state(&self, sequence: &gdk::EventSequence) -> EventSequenceState { unsafe { from_glib(ffi::gtk_gesture_get_sequence_state(self.as_ref().to_glib_none().0, mut_override(sequence.to_glib_none().0))) } } fn get_sequences(&self) -> Vec<gdk::EventSequence> { unsafe { FromGlibPtrContainer::from_glib_container(ffi::gtk_gesture_get_sequences(self.as_ref().to_glib_none().0)) } } fn get_window(&self) -> Option<gdk::Window> { unsafe { from_glib_none(ffi::gtk_gesture_get_window(self.as_ref().to_glib_none().0)) } } fn group<P: IsA<Gesture>>(&self, gesture: &P) { unsafe { ffi::gtk_gesture_group(self.as_ref().to_glib_none().0, gesture.as_ref().to_glib_none().0); } } fn handles_sequence<'a, P: Into<Option<&'a gdk::EventSequence>>>(&self, sequence: P) -> bool { let sequence = sequence.into(); unsafe { from_glib(ffi::gtk_gesture_handles_sequence(self.as_ref().to_glib_none().0, mut_override(sequence.to_glib_none().0))) } } fn is_active(&self) -> bool { unsafe { from_glib(ffi::gtk_gesture_is_active(self.as_ref().to_glib_none().0)) } } fn is_grouped_with<P: IsA<Gesture>>(&self, other: &P) -> bool { unsafe { from_glib(ffi::gtk_gesture_is_grouped_with(self.as_ref().to_glib_none().0, other.as_ref().to_glib_none().0)) } } fn is_recognized(&self) -> bool { unsafe { from_glib(ffi::gtk_gesture_is_recognized(self.as_ref().to_glib_none().0)) } } fn set_sequence_state(&self, sequence: &gdk::EventSequence, state: EventSequenceState) -> bool { unsafe { from_glib(ffi::gtk_gesture_set_sequence_state(self.as_ref().to_glib_none().0, mut_override(sequence.to_glib_none().0), state.to_glib())) } } fn set_state(&self, state: EventSequenceState) -> bool { unsafe { from_glib(ffi::gtk_gesture_set_state(self.as_ref().to_glib_none().0, state.to_glib())) } } fn set_window<'a, P: IsA<gdk::Window> + 'a, Q: Into<Option<&'a P>>>(&self, window: Q) { let window = window.into(); unsafe { ffi::gtk_gesture_set_window(self.as_ref().to_glib_none().0, window.map(|p| p.as_ref()).to_glib_none().0); } } fn ungroup(&self) { unsafe { ffi::gtk_gesture_ungroup(self.as_ref().to_glib_none().0); } } fn get_property_n_points(&self) -> u32 { unsafe { let mut value = Value::from_type(<u32 as StaticType>::static_type()); gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"n-points\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().unwrap() } } fn connect_begin<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"begin\0".as_ptr() as *const _, Some(transmute(begin_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_cancel<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"cancel\0".as_ptr() as *const _, Some(transmute(cancel_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_end<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"end\0".as_ptr() as *const _, Some(transmute(end_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_sequence_state_changed<F: Fn(&Self, &gdk::EventSequence, EventSequenceState) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"sequence-state-changed\0".as_ptr() as *const _, Some(transmute(sequence_state_changed_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_update<F: Fn(&Self, &gdk::EventSequence) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"update\0".as_ptr() as *const _, Some(transmute(update_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } fn connect_property_window_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::window\0".as_ptr() as *const _, Some(transmute(notify_window_trampoline::<Self, F> as usize)), Box_::into_raw(f)) } } } unsafe extern "C" fn begin_trampoline<P, F: Fn(&P, &gdk::EventSequence) + 'static>(this: *mut ffi::GtkGesture, sequence: *mut gdk_ffi::GdkEventSequence, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(sequence)) } unsafe extern "C" fn cancel_trampoline<P, F: Fn(&P, &gdk::EventSequence) + 'static>(this: *mut ffi::GtkGesture, sequence: *mut gdk_ffi::GdkEventSequence, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(sequence)) } unsafe extern "C" fn end_trampoline<P, F: Fn(&P, &gdk::EventSequence) + 'static>(this: *mut ffi::GtkGesture, sequence: *mut gdk_ffi::GdkEventSequence, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(sequence)) } unsafe extern "C" fn sequence_state_changed_trampoline<P, F: Fn(&P, &gdk::EventSequence, EventSequenceState) + 'static>(this: *mut ffi::GtkGesture, sequence: *mut gdk_ffi::GdkEventSequence, state: ffi::GtkEventSequenceState, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(sequence), from_glib(state)) } unsafe extern "C" fn update_trampoline<P, F: Fn(&P, &gdk::EventSequence) + 'static>(this: *mut ffi::GtkGesture, sequence: *mut gdk_ffi::GdkEventSequence, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast(), &from_glib_borrow(sequence)) } unsafe extern "C" fn notify_window_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::GtkGesture, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<Gesture> { let f: &F = transmute(f); f(&Gesture::from_glib_borrow(this).unsafe_cast()) } impl fmt::Display for Gesture { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Gesture") } }<|fim▁end|>
fn set_window<'a, P: IsA<gdk::Window> + 'a, Q: Into<Option<&'a P>>>(&self, window: Q);
<|file_name|>form.py<|end_file_name|><|fim▁begin|>""" This module implements the FormRequest class which is a more convenient class (than Request) to generate Requests based on form data. See documentation in docs/topics/request-response.rst """ import six from six.moves.urllib.parse import urljoin, urlencode import lxml.html<|fim▁hole|>from parsel.selector import create_root_node from w3lib.html import strip_html5_whitespace from scrapy.http.request import Request from scrapy.utils.python import to_bytes, is_listlike from scrapy.utils.response import get_base_url class FormRequest(Request): def __init__(self, *args, **kwargs): formdata = kwargs.pop('formdata', None) if formdata and kwargs.get('method') is None: kwargs['method'] = 'POST' super(FormRequest, self).__init__(*args, **kwargs) if formdata: items = formdata.items() if isinstance(formdata, dict) else formdata querystr = _urlencode(items, self.encoding) if self.method == 'POST': self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded') self._set_body(querystr) else: self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr) @classmethod def from_response(cls, response, formname=None, formid=None, formnumber=0, formdata=None, clickdata=None, dont_click=False, formxpath=None, formcss=None, **kwargs): kwargs.setdefault('encoding', response.encoding) if formcss is not None: from parsel.csstranslator import HTMLTranslator formxpath = HTMLTranslator().css_to_xpath(formcss) form = _get_form(response, formname, formid, formnumber, formxpath) formdata = _get_inputs(form, formdata, dont_click, clickdata, response) url = _get_form_url(form, kwargs.pop('url', None)) method = kwargs.pop('method', form.method) return cls(url=url, method=method, formdata=formdata, **kwargs) def _get_form_url(form, url): if url is None: action = form.get('action') if action is None: return form.base_url return urljoin(form.base_url, strip_html5_whitespace(action)) return urljoin(form.base_url, url) def _urlencode(seq, enc): values = [(to_bytes(k, enc), to_bytes(v, enc)) for k, vs in seq for v in (vs if is_listlike(vs) else [vs])] return urlencode(values, doseq=1) def _get_form(response, formname, formid, formnumber, formxpath): """Find the form element """ root = create_root_node(response.text, lxml.html.HTMLParser, base_url=get_base_url(response)) forms = root.xpath('//form') if not forms: raise ValueError("No <form> element found in %s" % response) if formname is not None: f = root.xpath('//form[@name="%s"]' % formname) if f: return f[0] if formid is not None: f = root.xpath('//form[@id="%s"]' % formid) if f: return f[0] # Get form element from xpath, if not found, go up if formxpath is not None: nodes = root.xpath(formxpath) if nodes: el = nodes[0] while True: if el.tag == 'form': return el el = el.getparent() if el is None: break encoded = formxpath if six.PY3 else formxpath.encode('unicode_escape') raise ValueError('No <form> element found with %s' % encoded) # If we get here, it means that either formname was None # or invalid if formnumber is not None: try: form = forms[formnumber] except IndexError: raise IndexError("Form number %d not found in %s" % (formnumber, response)) else: return form def _get_inputs(form, formdata, dont_click, clickdata, response): try: formdata_keys = dict(formdata or ()).keys() except (ValueError, TypeError): raise ValueError('formdata should be a dict or iterable of tuples') if not formdata: formdata = () inputs = form.xpath('descendant::textarea' '|descendant::select' '|descendant::input[not(@type) or @type[' ' not(re:test(., "^(?:submit|image|reset)$", "i"))' ' and (../@checked or' ' not(re:test(., "^(?:checkbox|radio)$", "i")))]]', namespaces={ "re": "http://exslt.org/regular-expressions"}) values = [(k, u'' if v is None else v) for k, v in (_value(e) for e in inputs) if k and k not in formdata_keys] if not dont_click: clickable = _get_clickable(clickdata, form) if clickable and clickable[0] not in formdata and not clickable[0] is None: values.append(clickable) if isinstance(formdata, dict): formdata = formdata.items() values.extend((k, v) for k, v in formdata if v is not None) return values def _value(ele): n = ele.name v = ele.value if ele.tag == 'select': return _select_value(ele, n, v) return n, v def _select_value(ele, n, v): multiple = ele.multiple if v is None and not multiple: # Match browser behaviour on simple select tag without options selected # And for select tags wihout options o = ele.value_options return (n, o[0]) if o else (None, None) elif v is not None and multiple: # This is a workround to bug in lxml fixed 2.3.1 # fix https://github.com/lxml/lxml/commit/57f49eed82068a20da3db8f1b18ae00c1bab8b12#L1L1139 selected_options = ele.xpath('.//option[@selected]') v = [(o.get('value') or o.text or u'').strip() for o in selected_options] return n, v def _get_clickable(clickdata, form): """ Returns the clickable element specified in clickdata, if the latter is given. If not, it returns the first clickable element found """ clickables = [ el for el in form.xpath( 'descendant::input[re:test(@type, "^(submit|image)$", "i")]' '|descendant::button[not(@type) or re:test(@type, "^submit$", "i")]', namespaces={"re": "http://exslt.org/regular-expressions"}) ] if not clickables: return # If we don't have clickdata, we just use the first clickable element if clickdata is None: el = clickables[0] return (el.get('name'), el.get('value') or '') # If clickdata is given, we compare it to the clickable elements to find a # match. We first look to see if the number is specified in clickdata, # because that uniquely identifies the element nr = clickdata.get('nr', None) if nr is not None: try: el = list(form.inputs)[nr] except IndexError: pass else: return (el.get('name'), el.get('value') or '') # We didn't find it, so now we build an XPath expression out of the other # arguments, because they can be used as such xpath = u'.//*' + \ u''.join(u'[@%s="%s"]' % c for c in six.iteritems(clickdata)) el = form.xpath(xpath) if len(el) == 1: return (el[0].get('name'), el[0].get('value') or '') elif len(el) > 1: raise ValueError("Multiple elements found (%r) matching the criteria " "in clickdata: %r" % (el, clickdata)) else: raise ValueError('No clickable element matching clickdata: %r' % (clickdata,))<|fim▁end|>
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|>from django.conf import settings from django.contrib.sites.models import Site from celery import task from tower import ugettext as _ from kitsune.sumo.decorators import timeit from kitsune.sumo import email_utils @task() @timeit def send_award_notification(award): """Sends the award notification email :arg award: the django-badger Award instance """ @email_utils.safe_translation def _make_mail(locale, context, email): subject = _(u"You were awarded the '{title}' badge!").format( title=_(award.badge.title, 'DB: badger.Badge.title')) mail = email_utils.make_mail( subject=subject, text_template='kbadge/email/award_notification.ltxt',<|fim▁hole|> return mail msg = _make_mail( locale=award.user.profile.locale, context={ 'host': Site.objects.get_current().domain, 'award': award, 'badge': award.badge, }, email=award.user.email ) # FIXME: this sends emails to the person who was awarded the # badge. Should we also send an email to the person who awarded # the badge? Currently, I think we shouldn't. email_utils.send_messages([msg])<|fim▁end|>
html_template='kbadge/email/award_notification.html', context_vars=context, from_email=settings.DEFAULT_FROM_EMAIL, to_email=email)
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from django.db import models from imagekit.models.fields import ProcessedImageField from imagekit.processors import ResizeToFill from .utils import unique_filename class DateTimeModel(models.Model): class Meta: abstract = True modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Ability(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) class Type(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) def _build_dict(self, items): lst = [] for i in items: lst.append(dict( name=i.to.name, resource_uri='/api/v1/type/' + str(i.to.id) + '/' )) return lst def weakness_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='weak') if items.exists(): return self._build_dict(items) return [] weaknesses = property(fget=weakness_list) def resistances_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='resist') if items.exists(): return self._build_dict(items) return [] resistances = property(fget=resistances_list) def super_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='super effective') if items.exists(): return self._build_dict(items) return [] supers = property(fget=super_list) def ineffective_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='ineffective') if items.exists(): return self._build_dict(items) return [] ineffectives = property(fget=ineffective_list) def no_list(self): items = TypeChart.objects.filter( frm__name=self.name, ttype='noeffect') if items.exists(): return self._build_dict(items) return [] no_effects = property(fget=no_list) <|fim▁hole|> frm = models.ForeignKey( Type, blank=True, null=True, related_name='type_frm') to = models.ForeignKey( Type, blank=True, null=True, related_name='type_to') TYPES = ( ('weak', 'weak'), ('super effective', 'super effective'), ('resistant', 'resistant'), ('ineffective', 'ineffective'), ('noeffect', 'noeffect'), ('resist', 'resist'), ) ttype = models.CharField( max_length=15, choices=TYPES, blank=True, null=True) class EggGroup(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) def get_pokes(self): pokes = Pokemon.objects.filter( egg_group=self ) lst = [] if pokes.exists(): for p in pokes: lst.append(dict( name=p.name.capitalize(), resource_uri='/api/v1/pokemon/' + str(p.pkdx_id) + '/' )) return lst pokemon = property(fget=get_pokes) class Game(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) generation = models.IntegerField(max_length=4) release_year = models.IntegerField(max_length=6) class Description(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) game = models.ManyToManyField(Game, blank=True, null=True) def get_game_details(self): lst = [] for g in self.game.all(): lst.append(dict( name=g.name, resource_uri='/api/v1/game/' + str(g.id) + '/') ) return lst n_game = property(fget=get_game_details) def get_pokemon(self): nm = self.name.split('_')[0] pokes = Pokemon.objects.filter( name=nm.lower() ) if pokes.exists(): return dict( name=pokes[0].name, resource_uri='/api/v1/pokemon/' + str(pokes[0].pkdx_id) + '/') return [] pokemon = property(fget=get_pokemon) class Move(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) description = models.TextField(max_length=200) etype = models.ManyToManyField(Type, null=True) pp = models.IntegerField(max_length=5) CATEGORY = ( ('physical', 'physical'), ('special', 'special'), ('status', 'status'), ) category = models.CharField(choices=CATEGORY, max_length=10) power = models.IntegerField(max_length=6) accuracy = models.IntegerField(max_length=6) class Sprite(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=50) image = ProcessedImageField( [ResizeToFill(96, 96)], upload_to=unique_filename, format='PNG', options={'quality': 80}) def get_pokemon(self): nm = self.name.split('_')[0] pokes = Pokemon.objects.filter( name=nm.lower() ) if pokes.exists(): return dict( name=pokes[0].name, resource_uri='/api/v1/pokemon/' + str(pokes[0].pkdx_id) + '/') return [] pokemon = property(fget=get_pokemon) class Pokemon(DateTimeModel): def __unicode__(self): return ' - '.join([str(self.pkdx_id), self.name]) name = models.CharField(max_length=50) pkdx_id = models.IntegerField(max_length=4, blank=True) species = models.CharField(max_length=30) height = models.CharField(max_length=10) weight = models.CharField(max_length=10) ev_yield = models.CharField(max_length=20) catch_rate = models.IntegerField(max_length=4) happiness = models.IntegerField(max_length=4) exp = models.IntegerField(max_length=5) GROWTHS = ( ('slow', 'slow'), ('medium slow', 'medium slow'), ('medium', 'medium'), ('medium fast', 'medium fast'), ('fast', 'fast'), ) growth_rate = models.CharField(choices=GROWTHS, max_length=15) male_female_ratio = models.CharField(max_length=10) hp = models.IntegerField(max_length=4) attack = models.IntegerField(max_length=4) defense = models.IntegerField(max_length=4) sp_atk = models.IntegerField(max_length=4) sp_def = models.IntegerField(max_length=4) speed = models.IntegerField(max_length=4) total = models.IntegerField(max_length=6) egg_cycles = models.IntegerField(max_length=6) abilities = models.ManyToManyField( Ability, blank=True, null=True) def ability_names(self): lst = [] for a in self.abilities.all(): lst.append(dict( resource_uri='/api/v1/ability/' + str(a.id) + '/', name=a.name.lower()) ) return lst ability_list = property(fget=ability_names) def get_evolution_details(self): evols = Evolution.objects.filter( frm=self ) if evols.exists(): lst = [] for e in evols: d = dict( to=e.to.name.capitalize(), resource_uri='/api/v1/pokemon/' + str(e.to.pkdx_id) + '/', method=e.method, ) if e.level > 0: d['level'] = e.level if e.detail: d['detail'] = e.detail lst.append(d) return lst return [] evolutions = property(fget=get_evolution_details) types = models.ManyToManyField( Type, blank=True, null=True) def type_list(self): lst = [] for t in self.types.all(): lst.append(dict( resource_uri='/api/v1/type/' + str(t.id) + '/', name=t.name.lower()) ) return lst type_list = property(fget=type_list) egg_group = models.ManyToManyField( EggGroup, blank=True, null=True) def get_eggs(self): lst = [] for e in self.egg_group.all(): lst.append(dict( name=e.name.capitalize(), resource_uri='/api/v1/egg/' + str(e.id) + '/' )) return lst eggs = property(fget=get_eggs) descriptions = models.ManyToManyField( Description, blank=True, null=True) def get_sprites(self): lst = [] for s in self.sprites.all(): lst.append(dict( name=self.name, resource_uri='/api/v1/sprite/' + str(s.id) + '/') ) return lst my_sprites = property(fget=get_sprites) sprites = models.ManyToManyField( Sprite, blank=True, null=True) def get_moves(self): moves = MovePokemon.objects.filter( pokemon=self ) lst = [] if moves.exists(): for m in moves: d = dict( name=m.move.name.capitalize(), resource_uri='/api/v1/move/' + str(m.move.id) + '/', learn_type=m.learn_type ) if m.level > 0: d['level'] = m.level lst.append(d) return lst moves = property(fget=get_moves) class Evolution(DateTimeModel): def __unicode__(self): return self.frm.name + ' to ' + self.to.name frm = models.ForeignKey( Pokemon, null=True, blank=True, related_name='frm_evol_pokemon') to = models.ForeignKey( Pokemon, null=True, blank=True, related_name='to_evol_pokemon') EVOLV_METHODS = ( ('level up', 'level_up'), ('stone', 'stone'), ('trade', 'trade'), ('other', 'other'), ) level = models.IntegerField(max_length=3, default=0) method = models.CharField( choices=EVOLV_METHODS, max_length=10, default=0) detail = models.CharField(max_length=10, null=True, blank=True) class MovePokemon(DateTimeModel): def __unicode__(self): return self.pokemon.name + ' - ' + self.move.name pokemon = models.ForeignKey( Pokemon, related_name='move', null=True, blank=True) move = models.ForeignKey( Move, related_name='pokemon', null=True, blank=True) LEARN = ( ('level up', 'level up'), ('machine', 'machine'), ('egg move', 'egg move'), ('tutor', 'tutor'), ('other', 'other'), ) learn_type = models.CharField( choices=LEARN, max_length=15, default='level up') level = models.IntegerField( max_length=6, default=0, null=True, blank=True) class Pokedex(DateTimeModel): def __unicode__(self): return self.name name = models.CharField(max_length=60) def _all_pokes(self): lst = [] for p in Pokemon.objects.all(): lst.append(dict( name=p.name, resource_uri='api/v1/pokemon/' + str(p.pkdx_id) + '/' )) return lst pokemon = property(fget=_all_pokes)<|fim▁end|>
class TypeChart(DateTimeModel): def __unicode__(self): return ' '.join([self.frm.name, self.ttype, 'against', self.to.name])
<|file_name|>test_lib.js<|end_file_name|><|fim▁begin|>jQuery(function(){ 'use strict'; var Test={};<|fim▁hole|> success: 'Success', failed: 'FAILED', pending: 'Pending...' }; var classes = { success: 'success', failed: 'danger', pending: 'warning' } var row_id_prefix = 'tests_td_'; var textProperty = (document.createElement('span').textContent !== undefined) ? 'textContent' : 'innerText'; var row_template = document.createElement('tr'); row_template.appendChild(document.createElement('td')); row_template.appendChild(document.createElement('td')); row_template.appendChild(document.createElement('td')); var tbody = document.getElementById('results_tbody'); Test.add = function(group, func){ var row; tests.push({group: group, func: func}); row = row_template.cloneNode(true); row.id = 'tests_td_' + (tests.length-1); row.getElementsByTagName('td')[0][textProperty] = group; tbody.appendChild(row); }; function TestController(row){ this._row = row; this._asserted = false; this._status='pending'; } var assertionFailed = {}; TestController.prototype._setStatus=function(status, extra){ var status_td = this._row.getElementsByTagName('td')[1]; var display_string = messages[status]; if(extra){ display_string += " (" + extra + ")"; } status_td[textProperty] = display_string; status_td.className = classes[status]; this._status = status; }; TestController.prototype._setDescription=function(desc){ var desc_td = this._row.getElementsByTagName('td')[2]; desc_td[textProperty] = desc; } TestController.prototype.assert = function(value, desc){ this._asserted = true; if(value !== true){ this._setStatus('failed'); this._setDescription('Assertion failed: ' + desc); throw assertionFailed; } }; TestController.prototype.must_throw = function(func, desc){ var thrown = false; if(!desc){ desc = 'expected to throw exception'; } try{ func(); }catch(e){ thrown = true; } this.assert(thrown, desc); }; TestController.prototype.must_not_be_called = function(desc){ var test_controller = this; if(!desc){ desc = 'function is not called'; } return function(){ test_controller.assert(false, desc); }; } Test.run = function(){ var i = 0, num_tests = tests.length; var t; for(; i< num_tests; ++i){ t = new TestController(document.getElementById('tests_td_' + i)); t._setStatus('pending'); try{ tests[i].func(t); if(t._status === 'pending'){ if(t._asserted){ //Success all tests t._setStatus('success'); }else{ t._setDescription('No assertion was given.'); } } }catch(e){ if(e !== assertionFailed){ t._setStatus('failed','exception'); t._setDescription(e.message); } } } }; window.Test=Test; });<|fim▁end|>
var tests=[]; var messages={
<|file_name|>lib.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/. */ #![cfg(test)]<|fim▁hole|>extern crate servo_config; mod opts; mod prefs;<|fim▁end|>
<|file_name|>subscribeOn.ts<|end_file_name|><|fim▁begin|>import {Observable} from '../../Observable'; import {subscribeOn, SubscribeOnSignature} from '../../operator/subscribeOn'; Observable.prototype.subscribeOn = subscribeOn; declare module '../../Observable' { interface Observable<T> {<|fim▁hole|><|fim▁end|>
subscribeOn: SubscribeOnSignature<T>; } }
<|file_name|>TestUnnestOperator.java<|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. */ package com.facebook.presto.operator.unnest; import com.facebook.presto.Session; import com.facebook.presto.block.BlockAssertions.Encoding; import com.facebook.presto.common.Page; import com.facebook.presto.common.type.ArrayType; import com.facebook.presto.common.type.RowType; import com.facebook.presto.common.type.Type; import com.facebook.presto.metadata.MetadataManager; import com.facebook.presto.operator.DriverContext; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorFactory; import com.facebook.presto.operator.PageAssertions; import com.facebook.presto.spi.plan.PlanNodeId; import com.facebook.presto.testing.MaterializedResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.Collectors; import java.util.stream.IntStream; import static com.facebook.airlift.concurrent.Threads.daemonThreadsNamed; import static com.facebook.presto.RowPagesBuilder.rowPagesBuilder; import static com.facebook.presto.SessionTestUtils.TEST_SESSION; import static com.facebook.presto.block.BlockAssertions.Encoding.DICTIONARY; import static com.facebook.presto.block.BlockAssertions.Encoding.RUN_LENGTH; import static com.facebook.presto.block.BlockAssertions.createMapType; import static com.facebook.presto.common.type.BigintType.BIGINT; import static com.facebook.presto.common.type.BooleanType.BOOLEAN; import static com.facebook.presto.common.type.DecimalType.createDecimalType; import static com.facebook.presto.common.type.Decimals.MAX_SHORT_PRECISION; import static com.facebook.presto.common.type.DoubleType.DOUBLE; import static com.facebook.presto.common.type.IntegerType.INTEGER; import static com.facebook.presto.common.type.RowType.withDefaultFieldNames; import static com.facebook.presto.common.type.SmallintType.SMALLINT; import static com.facebook.presto.common.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.common.type.VarcharType.VARCHAR; import static com.facebook.presto.metadata.MetadataManager.createTestMetadataManager; import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals; import static com.facebook.presto.operator.PageAssertions.assertPageEquals; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildExpectedPage; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.buildOutputTypes; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.calculateMaxCardinalities; import static com.facebook.presto.operator.unnest.TestUnnesterUtil.mergePages; import static com.facebook.presto.testing.MaterializedResult.resultBuilder; import static com.facebook.presto.testing.TestingSession.testSessionBuilder; import static com.facebook.presto.testing.TestingTaskContext.createTaskContext; import static com.facebook.presto.tpch.TpchMetadata.TINY_SCHEMA_NAME; import static com.facebook.presto.util.StructuralTestUtil.arrayBlockOf; import static com.facebook.presto.util.StructuralTestUtil.mapBlockOf; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.NaN; import static java.lang.Double.POSITIVE_INFINITY; import static java.util.concurrent.Executors.newCachedThreadPool; import static java.util.concurrent.Executors.newScheduledThreadPool; import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestUnnestOperator { private static final int PAGE_COUNT = 10; private static final int POSITION_COUNT = 500; private static final ExecutorService EXECUTOR = newCachedThreadPool(daemonThreadsNamed("test-EXECUTOR-%s")); private static final ScheduledExecutorService SCHEDULER = newScheduledThreadPool(1, daemonThreadsNamed("test-%s")); private ExecutorService executor; private ScheduledExecutorService scheduledExecutor; private DriverContext driverContext; @BeforeMethod public void setUp() { executor = newCachedThreadPool(daemonThreadsNamed("test-executor-%s")); scheduledExecutor = newScheduledThreadPool(2, daemonThreadsNamed("test-scheduledExecutor-%s")); driverContext = createTaskContext(executor, scheduledExecutor, TEST_SESSION) .addPipelineContext(0, true, true, false) .addDriverContext(); } @AfterMethod public void tearDown() { executor.shutdownNow(); scheduledExecutor.shutdownNow(); } @Test public void testUnnest() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L) .row(1L, 3L, null, null) .row(2L, 99L, null, null) .row(6L, 7L, 9L, 10L) .row(6L, 8L, 11L, 12L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArray() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(array(bigint))")); Type mapType = metadata.getType(parseTypeSignature("map(array(bigint),array(bigint))")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row( 1L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(2, 4), ImmutableList.of(3, 6)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(4, 8), ImmutableList.of(5, 10)))) .row(2L, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(99, 198)), null) .row(3L, null, null) .pageBreak() .row( 6, arrayBlockOf(new ArrayType(BIGINT), ImmutableList.of(7, 14), ImmutableList.of(8, 16)), mapBlockOf(new ArrayType(BIGINT), new ArrayType(BIGINT), ImmutableMap.of(ImmutableList.of(9, 18), ImmutableList.of(10, 20), ImmutableList.of(11, 22), ImmutableList.of(12, 24)))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, new ArrayType(BIGINT), new ArrayType(BIGINT), new ArrayType(BIGINT)) .row(1L, ImmutableList.of(2L, 4L), ImmutableList.of(4L, 8L), ImmutableList.of(5L, 10L)) .row(1L, ImmutableList.of(3L, 6L), null, null) .row(2L, ImmutableList.of(99L, 198L), null, null) .row(6L, ImmutableList.of(7L, 14L), ImmutableList.of(9L, 18L), ImmutableList.of(10L, 20L)) .row(6L, ImmutableList.of(8L, 16L), ImmutableList.of(11L, 22L), ImmutableList.of(12L, 24L)) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithOrdinality() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(bigint)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,bigint)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(BIGINT, 2, 3), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(4, 5))) .row(2L, arrayBlockOf(BIGINT, 99), null) .row(3L, null, null) .pageBreak() .row(6L, arrayBlockOf(BIGINT, 7, 8), mapBlockOf(BIGINT, BIGINT, ImmutableMap.of(9, 10, 11, 12))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), true); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, BIGINT, BIGINT, BIGINT) .row(1L, 2L, 4L, 5L, 1L) .row(1L, 3L, null, null, 2L) .row(2L, 99L, null, null, 1L) .row(6L, 7L, 9L, 10L, 1L) .row(6L, 8L, 11L, 12L, 2L) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestNonNumericDoubles() { MetadataManager metadata = createTestMetadataManager(); Type arrayType = metadata.getType(parseTypeSignature("array(double)")); Type mapType = metadata.getType(parseTypeSignature("map(bigint,double)")); List<Page> input = rowPagesBuilder(BIGINT, arrayType, mapType) .row(1L, arrayBlockOf(DOUBLE, NEGATIVE_INFINITY, POSITIVE_INFINITY, NaN), mapBlockOf(BIGINT, DOUBLE, ImmutableMap.of(1, NEGATIVE_INFINITY, 2, POSITIVE_INFINITY, 3, NaN))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1, 2), ImmutableList.of(arrayType, mapType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, DOUBLE, BIGINT, DOUBLE) .row(1L, NEGATIVE_INFINITY, 1L, NEGATIVE_INFINITY) .row(1L, POSITIVE_INFINITY, 2L, POSITIVE_INFINITY) .row(1L, NaN, 3L, NaN) .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestWithArrayOfRows() { MetadataManager metadata = createTestMetadataManager(); Type arrayOfRowType = metadata.getType(parseTypeSignature("array(row(bigint, double, varchar))")); Type elementType = RowType.anonymous(ImmutableList.of(BIGINT, DOUBLE, VARCHAR)); List<Page> input = rowPagesBuilder(BIGINT, arrayOfRowType) .row(1, arrayBlockOf(elementType, ImmutableList.of(2, 4.2, "abc"), ImmutableList.of(3, 6.6, "def"))) .row(2, arrayBlockOf(elementType, ImmutableList.of(99, 3.14, "pi"), null)) .row(3, null) .pageBreak() .row(6, arrayBlockOf(elementType, null, ImmutableList.of(8, 1.111, "tt"))) .build(); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), ImmutableList.of(0), ImmutableList.of(BIGINT), ImmutableList.of(1), ImmutableList.of(arrayOfRowType), false); MaterializedResult expected = resultBuilder(driverContext.getSession(), BIGINT, BIGINT, DOUBLE, VARCHAR) .row(1L, 2L, 4.2, "abc") .row(1L, 3L, 6.6, "def") .row(2L, 99L, 3.14, "pi") .row(2L, null, null, null) .row(6L, null, null, null) .row(6L, 8L, 1.111, "tt") .build(); assertOperatorEquals(operatorFactory, driverContext, input, expected); } @Test public void testUnnestSingleArrayUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleMapUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(createMapType(VARCHAR, new ArrayType(BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestSingleArrayOfRowUnnester() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR))))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BOOLEAN); List<Type> unnestTypes = ImmutableList.of(new ArrayType(BOOLEAN), new ArrayType(BOOLEAN)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(SMALLINT); unnestTypes = ImmutableList.of(new ArrayType(SMALLINT), new ArrayType(SMALLINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(INTEGER); unnestTypes = ImmutableList.of(new ArrayType(INTEGER), new ArrayType(INTEGER)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(BIGINT), new ArrayType(BIGINT)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(createDecimalType(MAX_SHORT_PRECISION + 1)); unnestTypes = ImmutableList.of( new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1)), new ArrayType(createDecimalType(MAX_SHORT_PRECISION + 1))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(VARCHAR); unnestTypes = ImmutableList.of(new ArrayType(VARCHAR), new ArrayType(VARCHAR)); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(new ArrayType(BIGINT)), new ArrayType(new ArrayType(VARCHAR))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); replicatedTypes = ImmutableList.of(BIGINT); unnestTypes = ImmutableList.of(new ArrayType(createMapType(BIGINT, BIGINT)), new ArrayType(createMapType(BIGINT, BIGINT))); types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoMapUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of(createMapType(BIGINT, BIGINT), createMapType(VARCHAR, VARCHAR)); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestTwoArrayOfRowUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER))), new ArrayType(withDefaultFieldNames(ImmutableList.of(INTEGER, INTEGER)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); testUnnest(replicatedTypes, unnestTypes, types); } @Test public void testUnnestMultipleUnnesters() { List<Type> replicatedTypes = ImmutableList.of(BIGINT); List<Type> unnestTypes = ImmutableList.of( new ArrayType(BIGINT), createMapType(VARCHAR, VARCHAR), new ArrayType(withDefaultFieldNames(ImmutableList.of(BIGINT, BIGINT, BIGINT))), new ArrayType(withDefaultFieldNames(ImmutableList.of(VARCHAR, VARCHAR, VARCHAR)))); List<Type> types = new ArrayList<>(replicatedTypes); types.addAll(unnestTypes); <|fim▁hole|> protected void testUnnest(List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types) { testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of()); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, false, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.0f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.0f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(DICTIONARY, DICTIONARY)); testUnnest(replicatedTypes, unnestTypes, types, 0.2f, 0.2f, true, ImmutableList.of(RUN_LENGTH, DICTIONARY)); } protected void testUnnest( List<Type> replicatedTypes, List<Type> unnestTypes, List<Type> types, float primitiveNullRate, float nestedNullRate, boolean useBlockView, List<Encoding> wrappings) { List<Page> inputPages = new ArrayList<>(); for (int i = 0; i < PAGE_COUNT; i++) { Page inputPage = PageAssertions.createPageWithRandomData(types, POSITION_COUNT, false, false, primitiveNullRate, nestedNullRate, useBlockView, wrappings); inputPages.add(inputPage); } testUnnest(inputPages, replicatedTypes, unnestTypes, false, false); testUnnest(inputPages, replicatedTypes, unnestTypes, true, false); testUnnest(inputPages, replicatedTypes, unnestTypes, false, true); testUnnest(inputPages, replicatedTypes, unnestTypes, true, true); } private void testUnnest(List<Page> inputPages, List<Type> replicatedTypes, List<Type> unnestTypes, boolean withOrdinality, boolean legacyUnnest) { List<Integer> replicatedChannels = IntStream.range(0, replicatedTypes.size()).boxed().collect(Collectors.toList()); List<Integer> unnestChannels = IntStream.range(replicatedTypes.size(), replicatedTypes.size() + unnestTypes.size()).boxed().collect(Collectors.toList()); OperatorFactory operatorFactory = new UnnestOperator.UnnestOperatorFactory( 0, new PlanNodeId("test"), replicatedChannels, replicatedTypes, unnestChannels, unnestTypes, withOrdinality); Operator unnestOperator = ((UnnestOperator.UnnestOperatorFactory) operatorFactory).createOperator(createDriverContext(), legacyUnnest); for (Page inputPage : inputPages) { int[] maxCardinalities = calculateMaxCardinalities(inputPage, replicatedTypes, unnestTypes); List<Type> outputTypes = buildOutputTypes(replicatedTypes, unnestTypes, withOrdinality, legacyUnnest); Page expectedPage = buildExpectedPage(inputPage, replicatedTypes, unnestTypes, outputTypes, maxCardinalities, withOrdinality, legacyUnnest); unnestOperator.addInput(inputPage); List<Page> outputPages = new ArrayList<>(); while (true) { Page outputPage = unnestOperator.getOutput(); if (outputPage == null) { break; } assertTrue(outputPage.getPositionCount() <= 1000); outputPages.add(outputPage); } Page mergedOutputPage = mergePages(outputTypes, outputPages); assertPageEquals(outputTypes, mergedOutputPage, expectedPage); } } private DriverContext createDriverContext() { Session testSession = testSessionBuilder() .setCatalog("tpch") .setSchema(TINY_SCHEMA_NAME) .build(); return createTaskContext(EXECUTOR, SCHEDULER, testSession) .addPipelineContext(0, true, true, false) .addDriverContext(); } }<|fim▁end|>
testUnnest(replicatedTypes, unnestTypes, types); }
<|file_name|>ion.rs<|end_file_name|><|fim▁begin|>use shell::Shell; use shell::status::*; use std::path::Path; <|fim▁hole|> const DOCPATH: &str = "/usr/share/ion/docs/index.html"; pub(crate) fn ion_docs(_: &[&str], shell: &mut Shell) -> i32 { if !Path::new(DOCPATH).exists() { eprintln!("ion: ion shell documentation is not installed"); return FAILURE; } if let Some(cmd) = shell.get_var("BROWSER".into()) { if let Ok(_) = Command::new(&cmd).arg(DOCPATH).spawn() { return SUCCESS; } } else { eprintln!("ion: BROWSER variable isn't defined"); } FAILURE }<|fim▁end|>
use std::process::Command;
<|file_name|>ToolProtocolHTTP.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2006-2010 Tampere University of Technology # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import httplib import urllib import socket class ToolProtocolHTTP(object): """ HTTP/HTTPS client for TEMA MBT protocol. Discusses with the TEMA test engine. """ # is client connected to the server isConnected = False def __init__(self): self.host = "localhost" self.port = 80 self.php_file = "temagui_http_proxy.php" socket.setdefaulttimeout(1800) def __del__(self): if self.isConnected: http_params = urllib.urlencode({"User" : self.username, "Message" : 'CLOSE', "Parameter" : 'Empty'}) http_data = self.__requestreply(http_params) def __requestreply(self,message ): """ One http(s) request/reply. Message: Message to send string. Returns: Reply string. """ http_data = '' try: http_connection = None if self.protocol == "HTTP": http_connection = httplib.HTTPConnection(self.host, self.port) elif self.protocol == "HTTPS": http_connection = httplib.HTTPSConnection(self.host, self.port) else: return '' http_connection.connect() http_connection.request("POST", self.php_file, message , self.http_headers) http_response = http_connection.getresponse() http_data = http_response.read() http_response.close() http_connection.close() except Exception, e: http_data = '' return http_data def init(self, host, path, port, username, protocol): """ Initialises connection. Sends HELO. host: Server hostname. path: path to http proxy in server. port: port username: wwwgui username protocol: http/https returns: Reply to ACK. On error returns '' """ self.http_headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} self.host = host self.php_file = "/".join(["",path,"temagui_http_proxy.php"]) self.port = port self.username = username self.protocol = protocol.upper() try: # SEND HELO http_params = urllib.urlencode({"User" : username, "Message" : 'HELO', "Parameter" : 'Empty'}) http_data = self.__requestreply(http_params) self.isConnected = True lines = http_data.splitlines() if lines != []: message = lines.pop() if message == "CLOSE": http_data = '' self.isConnected = False except Exception, e: self.isConnected = False return '' return http_data def getKeyword(self): """ Gets keyword from testserver. Sends GET to testserver and waits for reply. Returns: Reply to GET. On error return '' """ http_data = '' try: http_params = urllib.urlencode({"User" : self.username, "Message" : 'GET', "Parameter" : 'Empty'}) http_data = self.__requestreply(http_params) lines = http_data.splitlines() if lines != []: message = lines.pop() if message == "CLOSE": self.isConnected = False return 'ERROR' if message == 'ERR': # TODO: don't send ack. http_data = self.__requestreply(http_params) http_params = urllib.urlencode({"User" : self.username, "Message" : 'ACK', "Parameter" : 'Empty'}) http_data = self.__requestreply(http_params) self.isConnected = False return 'ERROR' if not http_data.startswith("ACK"): print http_data return "ERROR" else: #http_data = http_data.partition("ACK")[2].strip() http_data = http_data.split("ACK")[1].strip() if http_data == '' or http_data == None: http_data = '' self.isConnected = False except Exception, e: self.isConnected = False return http_data def putResult(self, result): """ Puts result to testserver. result: True/False returns: Reply message to PUT """ try: if result:<|fim▁hole|> http_params = urllib.urlencode({"User" : self.username, "Message" : 'PUT', "Parameter" : 'true'}) else: http_params = urllib.urlencode({"User" : self.username, "Message" : 'PUT', "Parameter" : 'false'}) except Exception, e: self.isConnected = False return '' try: http_data = self.__requestreply(http_params) lines = http_data.splitlines() if lines != []: message = lines.pop() if message == "CLOSE": self.isConnected = False return '' if http_data == '': self.isConnected = False except Exception, e: self.isConnected = False http_data = '' return http_data def log(self, msg): """ Sends log message to testserver returns: Reply to message. """ http_data = '' try: http_params = urllib.urlencode({"User" : self.username, "Message" : 'LOG', "Parameter" : msg }) http_data = self.__requestreply(http_params) lines = http_data.splitlines() if lines != []: message = lines.pop() if message == "CLOSE": self.isConnected = False return '' if http_data == '': self.isConnected = False except Exception, e: self.isConnected = False http_data = '' return http_data def bye(self): """ Sends message BYE to testserver. """ http_data = '' try: http_params = urllib.urlencode({"User" : self.username, "Message" : 'BYE', "Parameter" : 'None'}) http_data = self.__requestreply(http_params) self.isConnected = False except Exception, e: self.isConnected = False return '' def hasConnection(self): return self.isConnected if __name__ == "__main__": c = ToolProtocol() print "init -> " + c.init() print "getKeyword -> " + c.getKeyword() print "putResult -> " + c.putResult(True) print "getKeyword -> " + c.getKeyword() print "putResult -> " + c.putResult(False) print "invalid -> " + c.invalid() print "bye -> " + c.bye()<|fim▁end|>
<|file_name|>test_max_cell.py<|end_file_name|><|fim▁begin|>from __future__ import annotations import random import pytest import scitbx.matrix from cctbx import sgtbx from cctbx.sgtbx import bravais_types from dials.algorithms.indexing.max_cell import find_max_cell from dials.array_family import flex @pytest.fixture(params=bravais_types.acentric) def setup(request): space_group_symbol = request.param sgi = sgtbx.space_group_info(space_group_symbol) cs = sgi.any_compatible_crystal_symmetry(volume=random.randint(1e4, 1e6)) ms = cs.build_miller_set(anomalous_flag=True, d_min=3).expand_to_p1() # the reciprocal matrix B = scitbx.matrix.sqr(cs.unit_cell().fractionalization_matrix()).transpose() # randomly select 25% of reflections ms = ms.select(flex.random_permutation(ms.size())[: int(0.25 * ms.size())]) refl = flex.reflection_table() refl["rlp"] = B.elems * ms.indices().as_vec3_double() refl["imageset_id"] = flex.int(len(refl)) refl["xyzobs.mm.value"] = flex.vec3_double(len(refl)) d = {} d["crystal_symmetry"] = cs d["reflections"] = refl return d @pytest.mark.parametrize( "histogram_binning,nearest_neighbor_percentile", [("linear", None), ("log", 0.99)] ) def test_max_cell(setup, histogram_binning, nearest_neighbor_percentile): reflections = setup["reflections"] crystal_symmetry = setup["crystal_symmetry"] max_cell_multiplier = 1.3 max_cell = find_max_cell( reflections, max_cell_multiplier=max_cell_multiplier, histogram_binning=histogram_binning, nearest_neighbor_percentile=nearest_neighbor_percentile,<|fim▁hole|> crystal_symmetry.primitive_setting().unit_cell().parameters()[:3] ) assert max_cell.max_cell > known_max_cell def test_max_cell_low_res_with_high_res_noise(setup): reflections = setup["reflections"] crystal_symmetry = setup["crystal_symmetry"] rlp = reflections["rlp"] # select only low resolution reflections reflections = reflections.select(1 / rlp.norms() > 4) n = int(0.1 * reflections.size()) rlp_noise = flex.vec3_double(*(flex.random_double(n) for i in range(3))) reflections["rlp"].extend(rlp_noise) reflections["imageset_id"].extend(flex.int(rlp_noise.size())) reflections["xyzobs.mm.value"].extend(flex.vec3_double(rlp_noise.size())) max_cell_multiplier = 1.3 max_cell = find_max_cell(reflections, max_cell_multiplier=max_cell_multiplier) known_max_cell = max( crystal_symmetry.primitive_setting().unit_cell().parameters()[:3] ) assert max_cell.max_cell > known_max_cell<|fim▁end|>
) known_max_cell = max(
<|file_name|>mod.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. /*! Module that constructs a control-flow graph representing an item. Uses `Graph` as the underlying representation. */ #![allow(dead_code)] // still a WIP, #6298 use middle::graph; use middle::ty; use syntax::ast; use util::nodemap::NodeMap; mod construct; pub mod graphviz; pub struct CFG { pub exit_map: NodeMap<CFGIndex>, pub graph: CFGGraph, pub entry: CFGIndex, pub exit: CFGIndex, } pub struct CFGNodeData { pub id: ast::NodeId } pub struct CFGEdgeData { pub exiting_scopes: Vec<ast::NodeId> } <|fim▁hole|> pub type CFGGraph = graph::Graph<CFGNodeData, CFGEdgeData>; pub type CFGNode = graph::Node<CFGNodeData>; pub type CFGEdge = graph::Edge<CFGEdgeData>; pub struct CFGIndices { entry: CFGIndex, exit: CFGIndex, } impl CFG { pub fn new(tcx: &ty::ctxt, blk: &ast::Block) -> CFG { construct::construct(tcx, blk) } }<|fim▁end|>
pub type CFGIndex = graph::NodeIndex;
<|file_name|>display.py<|end_file_name|><|fim▁begin|># (c) 2014, Michael DeHaan <[email protected]> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # FIXME: copied mostly from old code, needs py3 improvements from __future__ import (absolute_import, division, print_function) __metaclass__ = type import textwrap import os import random import subprocess import sys from ansible import constants as C from ansible.errors import AnsibleError from ansible.utils.color import stringc class Display: def __init__(self, verbosity=0): self.verbosity = verbosity # list of all deprecation messages to prevent duplicate display self._deprecations = {} self._warns = {} self._errors = {} self.cowsay = None self.noncow = os.getenv("ANSIBLE_COW_SELECTION",None) self.set_cowsay_info() def set_cowsay_info(self): if not C.ANSIBLE_NOCOWS: if os.path.exists("/usr/bin/cowsay"): self.cowsay = "/usr/bin/cowsay" elif os.path.exists("/usr/games/cowsay"): self.cowsay = "/usr/games/cowsay" elif os.path.exists("/usr/local/bin/cowsay"): # BSD path for cowsay self.cowsay = "/usr/local/bin/cowsay" elif os.path.exists("/opt/local/bin/cowsay"): # MacPorts path for cowsay self.cowsay = "/opt/local/bin/cowsay" if self.cowsay and self.noncow == 'random': cmd = subprocess.Popen([self.cowsay, "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = cmd.communicate() cows = out.split() cows.append(False) self.noncow = random.choice(cows) def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False): msg2 = msg if color: msg2 = stringc(msg, color) if not log_only: if not stderr: try: print(msg2) except UnicodeEncodeError: print(msg2.encode('utf-8')) else: try: print(msg2, file=sys.stderr) except UnicodeEncodeError: print(msg2.encode('utf-8'), file=sys.stderr) if C.DEFAULT_LOG_PATH != '': while msg.startswith("\n"): msg = msg.replace("\n","") # FIXME: logger stuff needs to be implemented #if not screen_only: # if color == 'red': # logger.error(msg) # else: # logger.info(msg) def vv(self, msg, host=None): return self.verbose(msg, host=host, caplevel=1) def vvv(self, msg, host=None): return self.verbose(msg, host=host, caplevel=2) def vvvv(self, msg, host=None): return self.verbose(msg, host=host, caplevel=3) def vvvvv(self, msg, host=None): return self.verbose(msg, host=host, caplevel=4) def vvvvvv(self, msg, host=None): return self.verbose(msg, host=host, caplevel=5) def verbose(self, msg, host=None, caplevel=2): # FIXME: this needs to be implemented #msg = utils.sanitize_output(msg) if self.verbosity > caplevel: if host is None: self.display(msg, color='blue') else: self.display("<%s> %s" % (host, msg), color='blue', screen_only=True) def deprecated(self, msg, version, removed=False): ''' used to print out a deprecation message.''' if not removed and not C.DEPRECATION_WARNINGS: return if not removed: if version: new_msg = "\n[DEPRECATION WARNING]: %s. This feature will be removed in version %s." % (msg, version) else: new_msg = "\n[DEPRECATION WARNING]: %s. This feature will be removed in a future release." % (msg) new_msg = new_msg + " Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.\n\n" else: raise AnsibleError("[DEPRECATED]: %s. Please update your playbooks." % msg) wrapped = textwrap.wrap(new_msg, 79) new_msg = "\n".join(wrapped) + "\n" if new_msg not in self._deprecations: self.display(new_msg, color='purple', stderr=True) self._deprecations[new_msg] = 1 def warning(self, msg): new_msg = "\n[WARNING]: %s" % msg wrapped = textwrap.wrap(new_msg, 79) new_msg = "\n".join(wrapped) + "\n" if new_msg not in self._warns: self.display(new_msg, color='bright purple', stderr=True) self._warns[new_msg] = 1 def system_warning(self, msg): if C.SYSTEM_WARNINGS: self.warning(msg) def banner(self, msg, color=None): ''' Prints a header-looking line with stars taking up to 80 columns of width (3 columns, minimum) ''' if self.cowsay: try: self.banner_cowsay(msg) return except OSError: # somebody cleverly deleted cowsay or something during the PB run. heh. pass msg = msg.strip() star_len = (80 - len(msg)) if star_len < 0: star_len = 3 stars = "*" * star_len self.display("\n%s %s" % (msg, stars), color=color) def banner_cowsay(self, msg, color=None): if ": [" in msg: msg = msg.replace("[","") if msg.endswith("]"): msg = msg[:-1] runcmd = [self.cowsay,"-W", "60"] if self.noncow: runcmd.append('-f') runcmd.append(self.noncow) runcmd.append(msg) cmd = subprocess.Popen(runcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = cmd.communicate() self.display("%s\n" % out, color=color) def error(self, msg, wrap_text=True): if wrap_text: new_msg = "\n[ERROR]: %s" % msg wrapped = textwrap.wrap(new_msg, 79) new_msg = "\n".join(wrapped) + "\n"<|fim▁hole|> self.display(new_msg, color='red', stderr=True) self._errors[new_msg] = 1<|fim▁end|>
else: new_msg = msg if new_msg not in self._errors:
<|file_name|>reference-carried-through-struct-field.rs<|end_file_name|><|fim▁begin|>struct Wrap<'a> { w: &'a mut u32 } fn foo() { let mut x = 22; let wrapper = Wrap { w: &mut x };<|fim▁hole|>fn main() { }<|fim▁end|>
x += 1; //~ ERROR cannot use `x` because it was mutably borrowed [E0503] *wrapper.w += 1; }
<|file_name|>fence.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 Dasein Phaos aka. Luxko // // 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|>// <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. //! a fence is used for synchronization of CPUs and GPUs use winapi::ID3D12Fence; use comptr::ComPtr; use error::WinError; use event::Event; /// a fence #[derive(Clone, Debug)] pub struct Fence { pub(crate) ptr: ComPtr<ID3D12Fence>, } impl Fence { /// get the current value of the fence #[inline] pub fn get_completed_value(&mut self) -> u64 { unsafe {self.ptr.GetCompletedValue() } } /// set the `event` if fence value reachs `value` // TODO: event lifetime safety? #[inline] pub fn set_event_on<'a>( &mut self, value: u64, event: &'a Event ) -> Result<(), WinError> {unsafe { WinError::from_hresult( self.ptr.SetEventOnCompletion(value, event.get()) ) }} /// set the fence to the specified value from CPU side #[inline] pub fn signal(&mut self, value: u64) -> Result<(), WinError> { unsafe {WinError::from_hresult( self.ptr.Signal(value) )} } } bitflags!{ /// misc fence options #[repr(C)] pub struct FenceFlags: u32 { const NONE = 0; const SHARED = 0x1; const SHARED_CROSS_ADAPTER = 0x2; } } impl Default for FenceFlags { #[inline] fn default() -> FenceFlags { FenceFlags::NONE } }<|fim▁end|>
<|file_name|>messages.go<|end_file_name|><|fim▁begin|><|fim▁hole|> import ( "fmt" "strings" "github.com/zmj/sfslack/slack" "github.com/zmj/sfslack/workflow" ) const ( wfTypeQueryKey = "wftype" ) func loginMessage(loginURL string) slack.Message { return slack.Message{ Text: fmt.Sprintf("Please %v", slack.FormatURL(loginURL, "log in")), } } func errorMessage(err error) slack.Message { return slack.Message{ Text: errorText(err), } } func errorText(err error) string { return fmt.Sprintf("Oops, something went wrong: %v", err.Error()) } // when is init necessary? var wfTypes = []*workflow.Definition{ workflow.Definitions.Send, workflow.Definitions.Request, } func helpMessage(wfClickURL string) slack.Message { var links []string for _, def := range wfTypes { link := fmt.Sprintf("%v&%v=%v", wfClickURL, wfTypeQueryKey, def.Arg) links = append(links, slack.FormatURL(link, def.Description)) } return slack.Message{ Text: strings.Join(links, " | "), } }<|fim▁end|>
package wfhost
<|file_name|>mt.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // THIS CODE IS GENERATED - DO NOT MODIFY // See angular/tools/gulp-tasks/cldr/extract.js const u = undefined; function plural(n: number): number { if (n === 1) return 1; if (n === 0 || n % 100 === Math.floor(n % 100) && n % 100 >= 2 && n % 100 <= 10) return 3; if (n % 100 === Math.floor(n % 100) && n % 100 >= 11 && n % 100 <= 19) return 4; return 5; } export default [ 'mt', [['am', 'pm'], ['AM', 'PM'], u],<|fim▁hole|> ['Il-Ħadd', 'It-Tnejn', 'It-Tlieta', 'L-Erbgħa', 'Il-Ħamis', 'Il-Ġimgħa', 'Is-Sibt'], ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'] ], [ ['Ħd', 'Tn', 'Tl', 'Er', 'Ħm', 'Ġm', 'Sb'], ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'], ['Il-Ħadd', 'It-Tnejn', 'It-Tlieta', 'L-Erbgħa', 'Il-Ħamis', 'Il-Ġimgħa', 'Is-Sibt'], ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'] ], [ ['J', 'F', 'M', 'A', 'M', 'Ġ', 'L', 'A', 'S', 'O', 'N', 'D'], ['Jan', 'Fra', 'Mar', 'Apr', 'Mej', 'Ġun', 'Lul', 'Aww', 'Set', 'Ott', 'Nov', 'Diċ'], [ 'Jannar', 'Frar', 'Marzu', 'April', 'Mejju', 'Ġunju', 'Lulju', 'Awwissu', 'Settembru', 'Ottubru', 'Novembru', 'Diċembru' ] ], [ ['Jn', 'Fr', 'Mz', 'Ap', 'Mj', 'Ġn', 'Lj', 'Aw', 'St', 'Ob', 'Nv', 'Dċ'], ['Jan', 'Fra', 'Mar', 'Apr', 'Mej', 'Ġun', 'Lul', 'Aww', 'Set', 'Ott', 'Nov', 'Diċ'], [ 'Jannar', 'Frar', 'Marzu', 'April', 'Mejju', 'Ġunju', 'Lulju', 'Awwissu', 'Settembru', 'Ottubru', 'Novembru', 'Diċembru' ] ], [['QK', 'WK'], u, ['Qabel Kristu', 'Wara Kristu']], 0, [6, 0], ['dd/MM/y', 'dd MMM y', 'd \'ta\'’ MMMM y', 'EEEE, d \'ta\'’ MMMM y'], ['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'], ['{1} {0}', u, u, u], ['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'], ['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'], '€', 'ewro', {'JPY': ['JP¥', '¥'], 'USD': ['US$', '$']}, 'ltr', plural ];<|fim▁end|>
u, [ ['Ħd', 'T', 'Tl', 'Er', 'Ħm', 'Ġm', 'Sb'], ['Ħad', 'Tne', 'Tli', 'Erb', 'Ħam', 'Ġim', 'Sib'],
<|file_name|>command.rs<|end_file_name|><|fim▁begin|>use std::fmt; #[derive(Clone, Copy, Debug, PartialEq)] pub enum DroneMode { Normal = 0, TakingOff = 1, Landing = 2, TookOff = 3, // Helper mode, doesn't exist on drone Abort = 4, } pub struct Command { pub pitch: i8, pub yaw: i8, pub roll: i8, pub throttle: i8, pub mode: DroneMode, pub as_array: [u8; 8], } impl Command { pub fn new() -> Command { Command { throttle: 0, yaw: 0, pitch: 0, roll: 0, mode: DroneMode::Normal, as_array: [0; 8] } } pub fn toggle_mode(&mut self, is_toggling: bool) { match self.mode { DroneMode::Normal => if is_toggling { self.mode = DroneMode::TakingOff }, DroneMode::TakingOff => if is_toggling { () } else { self.mode = DroneMode::TookOff }, DroneMode::TookOff => if is_toggling { self.mode = DroneMode::Landing }, DroneMode::Landing => if is_toggling { () } else { self.mode = DroneMode::Normal }, DroneMode::Abort => if is_toggling { self.mode = DroneMode::Normal }, } } /** * as_array[0] = constant * as_array[1] = roll * as_array[2] = pitch * as_array[3] = throttle * as_array[4] = yaw * as_array[5] = mode * as_array[6] = checksum * as_array[7] = constant */ pub fn update_array(&mut self) { self.as_array[0] = 0x66; let commands = [self.roll, self.pitch, self.throttle, self.yaw]; for i in 0..commands.len() { if commands[i] >= 0 { self.as_array[i + 1] = (commands[i] as u8) + 127;<|fim▁hole|> } else { self.as_array[i + 1] = (commands[i] + 127) as u8; } } self.as_array[5] = if self.mode == DroneMode::TookOff { DroneMode::Normal as u8 } else { self.mode as u8 }; self.as_array[6] = (self.as_array[1] ^ self.as_array[2] ^ self.as_array[3] ^ self.as_array[4] ^ self.as_array[5]) & 0xFF; self.as_array[7] = 0x99; } } impl fmt::Debug for Command { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "throttle: {}, yaw: {}, pitch: {}, roll: {}, mode: {:?}", self.throttle, self.yaw, self.pitch, self.roll, self.mode) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_throttle_up() { let mut cmd = Command::new(); cmd.throttle = 127; cmd.update_array(); assert_eq!(cmd.as_array[3], 254); } #[test] fn test_throttle_down() { let mut cmd = Command::new(); cmd.throttle = -127; cmd.update_array(); assert_eq!(cmd.as_array[3], 0); } }<|fim▁end|>
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># # author: Cosmin Basca # # Copyright 2010 University of Zurich # # 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 os import signal from subprocess import Popen, PIPE, STDOUT, call from threading import Thread from natsort import natsorted __author__ = 'basca' __LIB_NAME__ = 'jvmrdftools-assembly-' __LIB__ = os.path.join(os.path.dirname(os.path.realpath(__file__)), "lib") __JARS__ = natsorted([(jar.replace(__LIB_NAME__, "").replace(".jar", ""), os.path.join(__LIB__, jar)) for jar in os.listdir(__LIB__) if jar.startswith(__LIB_NAME__)], key=lambda (ver, jar_file): ver) def latest_jar(): global __JARS__ return __JARS__[-1] class JavaNotFoundException(Exception): pass DEVNULL = open(os.devnull, 'w') XMS = 128 XMX = 2048 def check_java(message=""): if call(['java', '-version'], stderr=DEVNULL) != 0: raise JavaNotFoundException( 'Java is not installed in the system path. {0}'.format(message)) def run_tool(main_class, xms=XMS, xmx=XMX, *options): latest_version, jar_path = latest_jar() command = ["java", "-Xms{0}m".format(xms), "-Xmx{0}m".format(xmx), "-classpath", jar_path, main_class] + \ [str(opt) for opt in options] # call(command, stdout=PIPE, stdin=PIPE, stderr=STDOUT, preexec_fn=os.setsid) call(command)<|fim▁hole|># the specific tools # # ---------------------------------------------------------------------------------------------------------------------- def run_lubm_generator(num_universities, index, generator_seed, ontology, output_path, xms=XMS, xmx=XMX): run_tool("com.rdftools.LubmGenerator", xms, xmx, "--num_universities", num_universities, "--start_index", index, "--seed", generator_seed, "--ontology", ontology, "--output_path", output_path) def run_nxvoid_generator(source, dataset_id, output_path, xms=XMS, xmx=XMX): run_tool("com.rdftools.NxVoidGenerator", xms, xmx, "--source", source, "--dataset_id", dataset_id, "--output_path", output_path) def run_jvmvoid_generator(source, dataset_id, output_path, xms=XMS, xmx=XMX): run_tool("com.rdftools.VoIDGenerator", xms, xmx, "--source", source, "--dataset_id", dataset_id, "--output_path", output_path) def run_rdf2rdf_converter(source, destination, xms=XMS, xmx=XMX): run_tool("com.rdftools.Rdf2RdfConverter", xms, xmx, source, destination)<|fim▁end|>
# ---------------------------------------------------------------------------------------------------------------------- #
<|file_name|>serviceport_test.go<|end_file_name|><|fim▁begin|>// Copyright 2017 The Kubernetes Authors. // // 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 common import ( "reflect" "testing" api "k8s.io/api/core/v1" ) func TestGetServicePorts(t *testing.T) { cases := []struct { apiPorts []api.ServicePort expected []ServicePort }{ {[]api.ServicePort{}, nil}, {<|fim▁hole|> {Port: 5, Protocol: api.ProtocolUDP}, }, []ServicePort{ {Port: 123, Protocol: api.ProtocolTCP}, {Port: 1, Protocol: api.ProtocolUDP}, {Port: 5, Protocol: api.ProtocolUDP}, }, }, } for _, c := range cases { actual := GetServicePorts(c.apiPorts) if !reflect.DeepEqual(actual, c.expected) { t.Errorf("GetServicePorts(%#v) == \ngot %#v, \nexpected %#v", c.apiPorts, actual, c.expected) } } }<|fim▁end|>
[]api.ServicePort{ {Port: 123, Protocol: api.ProtocolTCP}, {Port: 1, Protocol: api.ProtocolUDP},
<|file_name|>hr_attendance_day.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (C) 2018 Compassion CH # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). import logging import pytz from odoo import models, fields, api _logger = logging.getLogger(__name__) class HrAttendanceDay(models.Model): """ The instances of hr.attendance.day is created either at the first attendance of the day or by the method hr.employee._cron_create_attendance() called by a cron everyday. """ _name = "hr.attendance.day" _description = "Attendance day" _order = 'date DESC' _sql_constraints = [('unique_attendance_day', 'unique(date, employee_id)', 'This "Attendance day" already exists for this ' 'employee')] ########################################################################## # FIELDS # ########################################################################## date = fields.Date(required=True, default=fields.Date.today()) employee_id = fields.Many2one( 'hr.employee', "Employee", ondelete="cascade", required=True, default=lambda self: self.env.user.employee_ids[0].id) # Working schedule working_schedule_id = fields.Many2one('resource.calendar', store=True, string='Working schedule', compute='_compute_working_schedule', inverse='_inverse_working_schedule') cal_att_ids = fields.Many2many('resource.calendar.attendance', store=True, compute='_compute_cal_att_ids') working_day = fields.Char(compute='_compute_working_day', readonly=True, store=True) name = fields.Char(compute='_compute_name', store=True) # Leaves leave_ids = fields.Many2many('hr.holidays', string='Leaves') # todo replace by employee_id.is_absent_totay in_leave = fields.Boolean('In leave', compute='_compute_in_leave', store=True) public_holiday_id = fields.Many2one('hr.holidays.public.line', 'Public holidays') # Due hours due_hours = fields.Float('Due hours', compute='_compute_due_hours', readonly=True, store=True) # Attendances attendance_ids = fields.One2many('hr.attendance', 'attendance_day_id', 'Attendances', readonly=True) has_change_day_request = fields.Boolean( compute='_compute_has_change_day_request', store=True, oldname='has_linked_change_day_request' ) # Worked paid_hours = fields.Float( compute='_compute_paid_hours', store=True, readonly=True ) free_breaks_hours = fields.Float(compute='_compute_free_break_hours') total_attendance = fields.Float( compute='_compute_total_attendance', store=True, help='Sum of all attendances of the day' ) coefficient = fields.Float(help='Worked hours coefficient') # Break due_break_min = fields.Float('Minimum break due', compute='_compute_due_break') due_break_total = fields.Float('Total break due', compute='_compute_due_break') break_ids = fields.One2many('hr.attendance.break', 'attendance_day_id', 'Breaks', readonly=True) break_total = fields.Float('Total break', compute='_compute_break_total', store=True) rule_id = fields.Many2one('hr.attendance.rules', 'Rules', compute='_compute_rule_id') day_balance = fields.Float("Day balance", compute='_compute_day_balance', store=True) ########################################################################## # FIELDS METHODS # ########################################################################## @api.multi @api.depends('attendance_ids') def _compute_working_schedule(self): for att_day in self: # Find the correspondent resource.calendar # First check if the attendance has already a resource.calendar schedule = att_day.attendance_ids.mapped('working_schedule_id') if schedule: # if there is more than one resource.calendar take one... schedule = schedule[0] else: # look for a valid contract... # todo: check if att_day.employee_id.current_contract is enough contracts = self.env['hr.contract'].search([ ('employee_id', '=', att_day.employee_id.id), ('date_start', '<=', att_day.date), '|', ('date_end', '=', False), ('date_end', '>=', att_day.date) ], order='date_start desc', limit=1) # ...or take the resource.calendar of employee schedule = contracts.working_hours or ( att_day.employee_id.calendar_id) att_day.working_schedule_id = schedule def _inverse_working_schedule(self): for att_day in self: for att in self.attendance_ids: att.working_schedule_id = att_day.working_schedule_id @api.multi @api.depends('working_schedule_id', 'working_schedule_id.attendance_ids') def _compute_cal_att_ids(self): """ Find the resource.calendar.attendance matching """ for att_day in self: week_day = fields.Date.from_string(att_day.date).weekday() # select the calendar attendance(s) that are valid today. current_cal_att = att_day.working_schedule_id.mapped( 'attendance_ids').filtered( lambda a: int(a.dayofweek) == week_day)<|fim▁hole|> lambda r: r.date_from is not False and r.date_to is not False and r.date_from <= att_day.date <= r.date_to) # Period with only date_to or date_from if not att_schedule: att_schedule = current_cal_att.filtered( lambda r: (r.date_from <= att_day.date and not r.date_to and r.date_from) or (r.date_to >= att_day.date and not r.date_from and r.date_to)) # Default schedule if not att_schedule: att_schedule = current_cal_att.filtered( lambda r: not r.date_from and not r.date_to) att_day.cal_att_ids = att_schedule @api.multi def get_related_forced_due_hours(self): self.ensure_one() return self.env['hr.forced.due.hours'].search([ ('employee_id', '=', self.employee_id.id), ('date', '=', self.date)]) @api.multi @api.depends('due_hours') def _compute_has_change_day_request(self): for att_day in self: res = att_day.get_related_forced_due_hours() att_day.has_change_day_request = len(res) == 1 @api.multi @api.depends('date') def _compute_working_day(self): for att_day in self: att_day.working_day = fields.Date.from_string( att_day.date).strftime('%A').title() @api.multi @api.depends('working_day') def _compute_name(self): for rd in self: rd.name = rd.working_day + ' ' + rd.date @api.multi @api.depends('leave_ids', 'public_holiday_id') def _compute_in_leave(self): for att_day in self: att_day.in_leave = att_day.leave_ids or att_day.public_holiday_id @api.multi @api.depends('working_schedule_id', 'leave_ids', 'public_holiday_id', 'cal_att_ids.due_hours') def _compute_due_hours(self): """First search the due hours based on the contract and after remove some hours if they are public holiday or vacation""" for att_day in self: # Forced due hours (when an user changes work days) forced_hours = att_day.get_related_forced_due_hours() if forced_hours: due_hours = forced_hours.forced_due_hours else: due_hours = sum(att_day.cal_att_ids.mapped('due_hours')) # Public holidays if att_day.public_holiday_id: att_day.due_hours = 0 continue # Leaves due_hours -= att_day.get_leave_time(due_hours) if due_hours < 0: due_hours = 0 att_day.due_hours = due_hours @api.multi @api.depends('attendance_ids.worked_hours') def _compute_total_attendance(self): for att_day in self.filtered('attendance_ids'): att_day.total_attendance = sum( att_day.attendance_ids.mapped( 'worked_hours') or [0]) @api.multi @api.depends('total_attendance', 'coefficient') def _compute_paid_hours(self): """ Paid hours are the sum of the attendances minus the break time added by the system and multiply by the coefficient. """ for att_day in self.filtered('attendance_ids'): paid_hours = att_day.total_attendance # Take only the breaks edited by the system breaks = att_day.break_ids.filtered( lambda r: r.system_modified and not r.is_offered) paid_hours -= sum(breaks.mapped('additional_duration')) att_day.paid_hours = paid_hours * att_day.coefficient @api.multi def _compute_free_break_hours(self): for att_day in self: att_day.free_breaks_hours = sum(att_day.break_ids.filtered( 'is_offered').mapped('total_duration') or [0]) @api.multi @api.depends('attendance_ids') def _compute_rule_id(self): """ To know which working rule is applied on the day, we deduce the free break time offered from the paid hours. """ for att_day in self: if att_day.paid_hours: hours = int(att_day.paid_hours - att_day.free_breaks_hours) else: hours = int(att_day.due_hours - att_day.free_breaks_hours) if hours < 0: hours = 0 att_day.rule_id = self.env['hr.attendance.rules'].search([ ('time_from', '<=', hours), ('time_to', '>', hours), ]) @api.multi def _compute_due_break(self): """Calculation of the break duration due depending of hr.attendance.rules (only for displaying it in the view)""" for att_day in self: if att_day.rule_id: att_day.due_break_min = att_day.rule_id.due_break att_day.due_break_total = att_day.rule_id.due_break_total else: att_day.due_break_min = 0 att_day.due_break_total = 0 @api.multi @api.depends('break_ids', 'break_ids.total_duration') def _compute_break_total(self): for att_day in self: att_day.break_total = sum( att_day.break_ids.mapped('total_duration') or [0]) @api.multi @api.depends('paid_hours', 'due_hours') def _compute_day_balance(self): for att_day in self: att_day.day_balance = att_day.balance_computation() def balance_computation(self): self.ensure_one() sick_leave = self.env.ref('hr_holidays.holiday_status_sl') if sick_leave in self.leave_ids. \ filtered(lambda r: r.state == 'validate'). \ mapped('holiday_status_id'): return 0 else: return self.paid_hours - self.due_hours @api.multi def validate_extend_breaks(self): """ This will extend the break time based on the break attendance rules of the day. The paid hours will be recomputed after that. """ def extend_longest_break(extension_duration): # Extend the break duration att_breaks = att_day.break_ids.filtered( lambda r: not r.is_offered) if att_breaks: att_break = att_breaks.sorted('total_duration')[-1] # if not exist create a new one else: att_break = self.env['hr.attendance.break'].create({ 'employee_id': att_day.employee_id.id, 'attendance_day_id': att_day.id }) att_break.write({ 'additional_duration': extension_duration }) def compute_break_time_to_add(rule): breaks_total = sum( att_day.break_ids.mapped('total_duration') or [0]) due_break_total = rule["due_break_total"] due_break_min_length = rule["due_break"] time_to_add = 0 break_max = max( att_day.break_ids.mapped('total_duration') or [0]) if break_max < due_break_min_length: # We want to extend an non-offered break to at least the # minimum value. break_max_non_offered = max(att_day.break_ids.filtered( lambda b: not b.is_offered).mapped( 'total_duration') or [0]) time_to_add += due_break_min_length - break_max_non_offered breaks_total += time_to_add if breaks_total < due_break_total: time_to_add += due_break_total - breaks_total return time_to_add for att_day in self: logged_hours = att_day.total_attendance - att_day.free_breaks_hours rule = self.env['hr.attendance.rules'].search([ ('time_to', '>', logged_hours), '|', ('time_from', '<=', logged_hours), ('time_from', '=', False), ]) time_to_add = compute_break_time_to_add(rule) if time_to_add != 0: # Ensure we don't fall under another working rule when removing # hours from that day new_logged_hours = logged_hours - time_to_add new_rule = self.env['hr.attendance.rules'].search([ ('time_to', '>', new_logged_hours), '|', ('time_from', '<=', new_logged_hours), ('time_from', '=', False), ]) if new_rule != rule: time_to_add = compute_break_time_to_add(new_rule) time_to_add = max(time_to_add, logged_hours - new_rule.time_to) if time_to_add != 0: extend_longest_break(time_to_add) ########################################################################## # ORM METHODS # ########################################################################## @api.model def create(self, vals): rd = super(HrAttendanceDay, self).create(vals) att_date = fields.Date.from_string(rd.date) # link to leaves (hr.holidays ) date_str = fields.Date.to_string(att_date) rd.leave_ids = self.env['hr.holidays'].search([ ('employee_id', '=', rd.employee_id.id), ('type', '=', 'remove'), ('date_from', '<=', date_str), ('date_to', '>=', date_str)]) # find coefficient week_day = att_date.weekday() co_ids = self.env['hr.weekday.coefficient'].search([ ('day_of_week', '=', week_day)]).filtered( lambda r: r.category_ids & rd.employee_id.category_ids) rd.coefficient = co_ids[0].coefficient if co_ids else 1 # check public holiday if self.env['hr.holidays.public'].is_public_holiday( rd.date, rd.employee_id.id): holidays_lines = self.env['hr.holidays.public'].get_holidays_list( att_date.year, rd.employee_id.id) rd.public_holiday_id = holidays_lines.filtered( lambda r: r.date == rd.date) # find related attendance rd.attendance_ids = self.env['hr.attendance'].search([ ('employee_id', '=', rd.employee_id.id), ('date', '=', rd.date), ]) for leave in rd.leave_ids: leave._compute_att_day() # compute breaks rd.compute_breaks() rd.recompute_period_if_old_day() return rd @api.multi def write(self, vals): res = super(HrAttendanceDay, self).write(vals) if 'paid_hours' in vals: self.recompute_period_if_old_day() return res ########################################################################## # PUBLIC METHODS # ########################################################################## @api.multi def recompute_period_if_old_day(self): for day in self: employee_periods = day.employee_id.period_ids period_of_day = employee_periods.search([ ('start_date', '<=', day.date), ('end_date', '>=', day.date) ], limit=1) if period_of_day: period_of_day.update_period() self.employee_id._compute_balance() @api.multi def open_attendance_day(self): """ Used to bypass opening a attendance in popup mode""" self.ensure_one() return { 'type': 'ir.actions.act_window', 'name': 'Attendance day', 'view_type': 'form', 'view_mode': 'form', 'res_model': self._name, 'res_id': self.id, 'target': 'current', } def get_leave_time(self, due_hours): """ Compute leave duration for the day. :return: deduction to due hours (in hours) :rtype: float [0:24] """ deduction = 0 for leave in self.leave_ids: if leave.state != 'validate' or \ leave.holiday_status_id.keep_due_hours: continue else: utc_start = fields.Datetime.from_string(leave.date_from) utc_end = fields.Datetime.from_string(leave.date_to) # Convert UTC in local timezone user_tz = self.employee_id.user_id.tz if not user_tz: user_tz = u'UTC' local = pytz.timezone(user_tz) utc = pytz.timezone('UTC') local_start = utc.localize(utc_start).astimezone(local) local_end = utc.localize(utc_end).astimezone(local) leave_start_date = local_start.date() leave_end_date = local_end.date() date = fields.Date.from_string(self.date) full_day = due_hours if leave_start_date < date < leave_end_date: deduction += full_day elif date == leave_start_date: # convert time in float start = local_start.hour + local_start.minute / 60. for att in self.cal_att_ids: if att.hour_from <= start < att.hour_to: deduction += att.hour_to - start elif start < att.hour_from: deduction += att.due_hours elif date == leave_end_date: # convert time in float end = local_end.hour + local_end.minute / 60. for att in self.cal_att_ids: if att.hour_from < end <= att.hour_to: deduction += end - att.hour_from elif end > att.hour_to: deduction += att.due_hours else: _logger.error( "This day doesn't correspond to this leave" ) return deduction @api.multi def compute_breaks(self): """ Given the attendance of the employee, check the break time rules and compute the break time of the day. This will then trigger the computation of the paid hours for the day (total attendance - additional break time added) :return: None """ att_day_ids = self.filtered('attendance_ids') att_day_ids.mapped('break_ids').unlink() for att_day in att_day_ids: # add the offered break free_break = self.env['base.config.settings'].get_free_break() if free_break > 0: self.env['hr.attendance.break'].create({ 'employee_id': att_day.employee_id.id, 'attendance_day_id': att_day.id, 'is_offered': True, 'additional_duration': free_break }) att_ids = att_day.attendance_ids iter_att = iter(att_ids.sorted(key=lambda r: r.check_in)) previous_att = iter_att.next() while True: try: attendance = iter_att.next() self.env['hr.attendance.break'].create( { 'employee_id': att_day.employee_id.id, 'attendance_day_id': att_day.id, 'previous_attendance': previous_att.id, 'next_attendance': attendance.id, }) previous_att = attendance except StopIteration: break # Extend the break time if needed att_day.validate_extend_breaks() self._compute_paid_hours() @api.multi def recompute_due_hours(self): self._compute_total_attendance() self._compute_due_hours() self._compute_paid_hours()<|fim▁end|>
# Specific period att_schedule = current_cal_att.filtered(
<|file_name|>document_page.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/>. # ############################################################################## import logging from openerp import models, fields, api _logger = logging.getLogger(__name__) <|fim▁hole|> _inherit = ['mail.thread'] _description = "Document Page" _order = 'name' name = fields.Char('Title', required=True) type = fields.Selection( [('content', 'Content'), ('category', 'Category')], 'Type', help="Page type", default="content" ) parent_id = fields.Many2one( 'document.page', 'Category', domain=[('type', '=', 'category')] ) child_ids = fields.One2many( 'document.page', 'parent_id', 'Children' ) content = fields.Text( "Content" ) display_content = fields.Text( string='Displayed Content', compute='_get_display_content' ) history_ids = fields.One2many( 'document.page.history', 'page_id', 'History' ) menu_id = fields.Many2one( 'ir.ui.menu', "Menu", readonly=True ) create_date = fields.Datetime( "Created on", index=True, readonly=True ) create_uid = fields.Many2one( 'res.users', 'Author', index=True, readonly=True ) write_date = fields.Datetime( "Modification Date", index=True, readonly=True) write_uid = fields.Many2one( 'res.users', "Last Contributor", index=True, readonly=True ) def _get_page_index(self, page, link=True): """Return the index of a document.""" index = [] for subpage in page.child_ids: index += ["<li>" + self._get_page_index(subpage) + "</li>"] r = '' if link: r = '<a href="#id=%s">%s</a>' % (page.id, page.name) if index: r += "<ul>" + "".join(index) + "</ul>" return r def _get_display_content(self): """Return the content of a document.""" for page in self: if page.type == "category": display_content = self._get_page_index(page, link=False) else: display_content = page.content page.display_content = display_content @api.onchange("parent_id") def do_set_content(self): """We Set it the right content to the new parent.""" if self.parent_id and not self.content: if self.parent_id.type == "category": self.content = self.parent_id.content def create_history(self, page_id, content): """Create the first history of a newly created document.""" history = self.env['document.page.history'] return history.create({ "content": content, "page_id": page_id }) @api.multi def write(self, vals): """Write the content and set the history.""" result = super(DocumentPage, self).write(vals) content = vals.get('content') if content: for page in self: self.create_history(page.id, content) return result @api.model @api.returns('self', lambda value: value.id) def create(self, vals): """Create the first history of a document.""" page_id = super(DocumentPage, self).create(vals) content = vals.get('content') if content: self.create_history(page_id.id, content) return page_id<|fim▁end|>
class DocumentPage(models.Model): """This class is use to manage Document.""" _name = "document.page"
<|file_name|>run_exporter.py<|end_file_name|><|fim▁begin|># run using env as parameter: python run_exporter.py cad id api_key import exporter #parse into data type files import dataset_export import update_datastore_content #enter key as an argument from sys import argv script, env, res_id, api_key = argv with open(env + '.csv', 'w') as f: csv_string = exporter.export('https://' + env + '.data.gov.bc.ca', 'columns.json') f.write(csv_string) if __name__ == '__main__': dataset_export.export_type(env)<|fim▁hole|><|fim▁end|>
update_datastore_content.update_resource(env, res_id, api_key)
<|file_name|>test_auth.py<|end_file_name|><|fim▁begin|># Copyright 2012 OpenStack Foundation # All Rights Reserved. # # 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. from oslo_middleware import request_id import webob from tacker import auth from tacker.tests import base class TackerKeystoneContextTestCase(base.BaseTestCase): def setUp(self): super(TackerKeystoneContextTestCase, self).setUp() @webob.dec.wsgify def fake_app(req): self.context = req.environ['tacker.context'] return webob.Response() self.context = None self.middleware = auth.TackerKeystoneContext(fake_app) self.request = webob.Request.blank('/') self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken' def test_no_user_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '401 Unauthorized') def test_with_user_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.user_id, 'testuserid') self.assertEqual(self.context.user, 'testuserid') def test_with_tenant_id(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'test_user_id'<|fim▁hole|> self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.tenant_id, 'testtenantid') self.assertEqual(self.context.tenant, 'testtenantid') def test_roles_no_admin(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_ROLES'] = 'role1, role2 , role3,role4,role5' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.roles, ['role1', 'role2', 'role3', 'role4', 'role5']) self.assertEqual(self.context.is_admin, False) def test_roles_with_admin(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_ROLES'] = ('role1, role2 , role3,role4,role5,' 'AdMiN') response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.roles, ['role1', 'role2', 'role3', 'role4', 'role5', 'AdMiN']) self.assertEqual(self.context.is_admin, True) def test_with_user_tenant_name(self): self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.headers['X_PROJECT_NAME'] = 'testtenantname' self.request.headers['X_USER_NAME'] = 'testusername' response = self.request.get_response(self.middleware) self.assertEqual(response.status, '200 OK') self.assertEqual(self.context.user_id, 'testuserid') self.assertEqual(self.context.user_name, 'testusername') self.assertEqual(self.context.tenant_id, 'testtenantid') self.assertEqual(self.context.tenant_name, 'testtenantname') def test_request_id_extracted_from_env(self): req_id = 'dummy-request-id' self.request.headers['X_PROJECT_ID'] = 'testtenantid' self.request.headers['X_USER_ID'] = 'testuserid' self.request.environ[request_id.ENV_REQUEST_ID] = req_id self.request.get_response(self.middleware) self.assertEqual(req_id, self.context.request_id)<|fim▁end|>
response = self.request.get_response(self.middleware)
<|file_name|>user-service.spec.ts<|end_file_name|><|fim▁begin|>import { UserService } from './user-service'; import { IUser } from './user-model'; import { MockAuthService } from '../../common/services/mock-auth.service'; import { TestBed, getTestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { environment } from '../../../environments/environment'; import { AuthService } from '../../common/services/auth.service'; describe('ContactService', () => { let injector: TestBed; let service: UserService; let authService: MockAuthService; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ UserService, { provide: AuthService, useClass: MockAuthService } ] }); injector = getTestBed(); service = injector.get(UserService); authService = TestBed.get(AuthService); httpMock = injector.get(HttpTestingController); }); afterEach(() => { httpMock.verify(); }); describe('#getUser', () => { it('should return an Observable<IUser>', () => { authService.currentUser = { access_token: '1' }; const dummyUser: IUser = { id: 'john1', username: 'John.Doe@email' }; service.getUser(dummyUser.id).subscribe(user => { expect(user.id).toEqual(dummyUser.id); expect(user.username).toEqual(dummyUser.username); }); const req = httpMock.expectOne(`${environment.serviceRootUrl}Users(${dummyUser.id})`); expect(req.request.method).toBe('GET'); req.flush(dummyUser); }); }); describe('#createUser', () => { it('should return an Observable<IUser>', () => { authService.currentUser = { access_token: '1' }; const dummyUser: IUser = { id: 'john1', username: 'John.Doe@email' };<|fim▁hole|> service.createUser(dummyUser).subscribe(user => { expect(user.id).toEqual(dummyUser.id); expect(user.username).toEqual(dummyUser.username); }); const req = httpMock.expectOne(`${environment.serviceRootUrl}Users`); expect(req.request.method).toBe('POST'); req.flush(dummyUser); }); }); });<|fim▁end|>
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>//! this is the unoptimized version that performs all 100 //! passes, as per the original description of the problem fn main() { // states for the 100 doors // uses a vector of booleans, // where state==false means the door is closed let mut doors = [false; 100]; solve(&mut doors); for (idx, door) in doors.iter().enumerate() { println!("door {} open: {}", idx + 1, door); } }<|fim▁hole|>/// performs all 100 passes and mutates the vector with /// the states in place fn solve(doors: &mut [bool]) { for pass in 1..101 { let mut p = pass; while p <= 100 { // flip the state of the door doors[p - 1] = !doors[p - 1]; p += pass; } } } #[test] fn solution() { let mut doors = [false; 100]; solve(&mut doors); // test that the doors with index corresponding to // a perfect square are now open for i in 1..11 { assert!(doors[i * i - 1]); } }<|fim▁end|>
/// unoptimized solution for the 100 Doors problem,
<|file_name|>test_empty_input.py<|end_file_name|><|fim▁begin|>from io import StringIO from pathlib import Path from cwltool.main import main from .util import get_data <|fim▁hole|> empty_json = "{}" empty_input = StringIO(empty_json) params = [ "--outdir", str(tmp_path), get_data("tests/wf/no-parameters-echo.cwl"), "-", ] try: assert main(params, stdin=empty_input) == 0 except SystemExit as err: assert err.code == 0<|fim▁end|>
def test_empty_input(tmp_path: Path) -> None: """Affirm that an empty input works."""
<|file_name|>HelloWorldTest.java<|end_file_name|><|fim▁begin|>package com.iclockwork.percy.wechat4j; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * HelloWorldTest * * @author: fengwang * @date: 2016/3/9 13:40 * @version: 1.0 * @since: JDK 1.7 */ public class HelloWorldTest { /** * helloworld */<|fim▁hole|> @BeforeMethod public void setUp() throws Exception { helloworld = new HelloWorld(); } @AfterMethod public void tearDown() throws Exception { } @Test public void testHello() throws Exception { helloworld.hello(); } }<|fim▁end|>
private HelloWorld helloworld;
<|file_name|>test_models.py<|end_file_name|><|fim▁begin|>""" Tests for miscellaneous models Author: Chad Fulton License: Simplified-BSD """ from __future__ import division, absolute_import, print_function import numpy as np import pandas as pd import os import re import warnings from statsmodels.tsa.statespace import mlemodel from statsmodels import datasets from numpy.testing import assert_almost_equal, assert_equal, assert_allclose, assert_raises from nose.exc import SkipTest from .results import results_sarimax current_path = os.path.dirname(os.path.abspath(__file__)) class Intercepts(mlemodel.MLEModel): """ Test class for observation and state intercepts (which usually don't get tested in other models). """ def __init__(self, endog, **kwargs): k_states = 3 k_posdef = 3 super(Intercepts, self).__init__( endog, k_states=k_states, k_posdef=k_posdef, **kwargs) self['design'] = np.eye(3) self['obs_cov'] = np.eye(3) self['transition'] = np.eye(3) self['selection'] = np.eye(3) self['state_cov'] = np.eye(3) self.initialize_approximate_diffuse() @property def param_names(self): return ['d.1', 'd.2', 'd.3', 'c.1', 'c.2', 'c.3'] @property def start_params(self): return np.arange(6) def update(self, params, **kwargs): params = super(Intercepts, self).update(params, **kwargs) self['obs_intercept'] = params[:3] self['state_intercept'] = params[3:] class TestIntercepts(object): @classmethod def setup_class(cls, which='mixed', **kwargs): # Results path = current_path + os.sep + 'results/results_intercepts_R.csv' cls.desired = pd.read_csv(path) # Data dta = datasets.macrodata.load_pandas().data dta.index = pd.date_range(start='1959-01-01', end='2009-7-01', freq='QS') obs = dta[['realgdp', 'realcons', 'realinv']].copy() obs = obs / obs.std() if which == 'all': obs.ix[:50, :] = np.nan obs.ix[119:130, :] = np.nan elif which == 'partial': obs.ix[0:50, 0] = np.nan obs.ix[119:130, 0] = np.nan elif which == 'mixed': obs.ix[0:50, 0] = np.nan obs.ix[19:70, 1] = np.nan obs.ix[39:90, 2] = np.nan obs.ix[119:130, 0] = np.nan obs.ix[119:130, 2] = np.nan mod = Intercepts(obs, **kwargs) cls.params = np.arange(6) + 1 cls.model = mod cls.results = mod.smooth(cls.params, return_ssm=True) # Calculate the determinant of the covariance matrices (for easy # comparison to other languages without having to store 2-dim arrays) cls.results.det_scaled_smoothed_estimator_cov = ( np.zeros((1, cls.model.nobs))) cls.results.det_predicted_state_cov = np.zeros((1, cls.model.nobs)) cls.results.det_smoothed_state_cov = np.zeros((1, cls.model.nobs)) cls.results.det_smoothed_state_disturbance_cov = ( np.zeros((1, cls.model.nobs))) for i in range(cls.model.nobs): cls.results.det_scaled_smoothed_estimator_cov[0, i] = ( np.linalg.det( cls.results.scaled_smoothed_estimator_cov[:, :, i])) cls.results.det_predicted_state_cov[0, i] = np.linalg.det( cls.results.predicted_state_cov[:, :, i+1]) cls.results.det_smoothed_state_cov[0, i] = np.linalg.det( cls.results.smoothed_state_cov[:, :, i]) cls.results.det_smoothed_state_disturbance_cov[0, i] = ( np.linalg.det( cls.results.smoothed_state_disturbance_cov[:, :, i])) def test_loglike(self): assert_allclose(np.sum(self.results.llf_obs), -7924.03893566) def test_scaled_smoothed_estimator(self): assert_allclose( self.results.scaled_smoothed_estimator.T, self.desired[['r1', 'r2', 'r3']] ) def test_scaled_smoothed_estimator_cov(self): assert_allclose( self.results.det_scaled_smoothed_estimator_cov.T, self.desired[['detN']] ) def test_forecasts(self): assert_allclose( self.results.forecasts.T, self.desired[['m1', 'm2', 'm3']] ) def test_forecasts_error(self): assert_allclose( self.results.forecasts_error.T, self.desired[['v1', 'v2', 'v3']] ) def test_forecasts_error_cov(self): assert_allclose( self.results.forecasts_error_cov.diagonal(), self.desired[['F1', 'F2', 'F3']] ) def test_predicted_states(self): assert_allclose( self.results.predicted_state[:, 1:].T, self.desired[['a1', 'a2', 'a3']] ) def test_predicted_states_cov(self): assert_allclose( self.results.det_predicted_state_cov.T, self.desired[['detP']] ) def test_smoothed_states(self):<|fim▁hole|> self.results.smoothed_state.T, self.desired[['alphahat1', 'alphahat2', 'alphahat3']] ) def test_smoothed_states_cov(self): assert_allclose( self.results.det_smoothed_state_cov.T, self.desired[['detV']] ) def test_smoothed_forecasts(self): assert_allclose( self.results.smoothed_forecasts.T, self.desired[['muhat1', 'muhat2', 'muhat3']] ) def test_smoothed_state_disturbance(self): assert_allclose( self.results.smoothed_state_disturbance.T, self.desired[['etahat1', 'etahat2', 'etahat3']] ) def test_smoothed_state_disturbance_cov(self): assert_allclose( self.results.det_smoothed_state_disturbance_cov.T, self.desired[['detVeta']] ) def test_smoothed_measurement_disturbance(self): assert_allclose( self.results.smoothed_measurement_disturbance.T, self.desired[['epshat1', 'epshat2', 'epshat3']], atol=1e-9 ) def test_smoothed_measurement_disturbance_cov(self): assert_allclose( self.results.smoothed_measurement_disturbance_cov.diagonal(), self.desired[['Veps1', 'Veps2', 'Veps3']] )<|fim▁end|>
assert_allclose(
<|file_name|>url_extractor.py<|end_file_name|><|fim▁begin|>""" The consumer's code. It takes HTML from the queue and outputs the URIs found in it. """ import asyncio import json import logging from typing import List from urllib.parse import urljoin import aioredis from bs4 import BeautifulSoup from . import app_cli, redis_queue _log = logging.getLogger('url_extractor') def _scrape_urls(html: str, base_url: str) -> List[str]: """Gets all valid links from a site and returns them as URIs (some links may be relative. If the URIs scraped here would go back into the system to have more URIs scraped from their HTML, we would need to filter out all those who are not HTTP or HTTPS. Also, assuming that many consumers and many producers would be running at the same time, connected to one Redis instance, we would need to cache normalized versions or visited URIs without fragments (https://tools.ietf.org/html/rfc3986#section-3.5) so we don't fall into loops. For example two sites referencing each other. The cached entries could have time-to-live (Redis EXPIRE command), so we could refresh our knowledge about a site eventually. """ soup = BeautifulSoup(html, 'html.parser') href = 'href' return [urljoin(base_url, link.get(href)) for link in soup.find_all('a') if link.has_attr(href)] async def _scrape_urls_from_queued_html(redis_pool: aioredis.RedisPool): _log.info('Processing HTML from queue...') while True: try: html_payload = await redis_queue.pop(redis_pool) <|fim▁hole|> output_json = {html_payload.url: scraped_urls} # flush for anyone who is watching the stream print(json.dumps(output_json), flush=True) except redis_queue.QueueEmptyError: # wait for work to become available await asyncio.sleep(1) # pragma: no cover def main(): """Run the URL extractor (the consumer). """ app_cli.setup_logging() args_parser = app_cli.get_redis_args_parser( 'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those ' 'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}') args = args_parser.parse_args() loop = app_cli.get_event_loop() _log.info('Creating a pool of connections to Redis at %s:%d.', args.redis_host, args.redis_port) # the pool won't be closed explicitly, since the process needs to be terminated to stop anyway redis_pool = loop.run_until_complete( aioredis.create_pool((args.redis_host, args.redis_port))) loop.run_until_complete(_scrape_urls_from_queued_html(redis_pool)) if __name__ == '__main__': main()<|fim▁end|>
_log.info('Processing HTML from URL %s', html_payload.url) scraped_urls = _scrape_urls(html_payload.html, html_payload.url) _log.info('Scraped URIs from URL %s', html_payload.url)
<|file_name|>admin.py<|end_file_name|><|fim▁begin|># -*- coding:utf8 -*- from __future__ import unicode_literals from django.contrib import admin from core.models import Post from core.models import Category from core.models import Comment from core.models import Tag from core.forms import PostForm @admin.register(Post) class PostAdmin(admin.ModelAdmin): # raw_id_fields = ('tags',) form = PostForm<|fim▁hole|>admin.site.register(Category) admin.site.register(Comment) admin.site.register(Tag)<|fim▁end|>
class Meta: model = Post
<|file_name|>resolver.rs<|end_file_name|><|fim▁begin|>use std::sync::{Arc,Mutex}; use std::collections::HashMap; use std::io::BufReader; use rustls::{ResolvesServerCert, ClientHello}; use rustls::sign::{CertifiedKey, RSASigningKey}; use rustls::internal::pemfile; use sozu_command::proxy::{CertificateAndKey, CertFingerprint, AddCertificate, RemoveCertificate}; use sozu_command::certificate::calculate_fingerprint_from_der; use trie::TrieNode; struct TlsData { pub cert: CertifiedKey, } pub struct CertificateResolver { pub domains: TrieNode<CertFingerprint>, certificates: HashMap<CertFingerprint, TlsData>, } impl CertificateResolver { pub fn new() -> CertificateResolver { CertificateResolver { domains: TrieNode::root(), certificates: HashMap::new(), } } pub fn add_certificate(&mut self, add_certificate: AddCertificate) -> Option<CertFingerprint> { if let Some(certified_key) = generate_certified_key(add_certificate.certificate) { let fingerprint = calculate_fingerprint_from_der(&certified_key.cert[0].0); if add_certificate.names.is_empty() { //FIXME: waiting for https://github.com/briansmith/webpki/pull/65 to merge to get the DNS names // create a untrusted::Input // let input = untrusted::Input::from(&certs[0].0); // create an EndEntityCert // let ee = webpki::EndEntityCert::from(input).unwrap() // get names // let dns_names = ee.list_dns_names() // names.extend(dns_names.drain(..).map(|name| name.to_String())); error!("the rustls proxy cannot extract the names from the certificate (fingerprint={:?})", fingerprint); return None; } let mut names = add_certificate.names; //info!("cert fingerprint: {:?}", fingerprint); let data = TlsData { cert: certified_key, }; let fingerprint = CertFingerprint(fingerprint); self.certificates.insert(fingerprint.clone(), data); for name in names.drain(..) { self.domains.domain_insert(name.into_bytes(), fingerprint.clone()); } Some(fingerprint) } else { None } } pub fn remove_certificate(&mut self, remove_certificate: RemoveCertificate) { if let Some(_data) = self.certificates.get(&remove_certificate.fingerprint) { //let cert = &data.cert.cert[0]; if remove_certificate.names.is_empty() { //FIXME: waiting for https://github.com/briansmith/webpki/pull/65 to merge to get the DNS names // create a untrusted::Input // let input = untrusted::Input::from(&certs[0].0); // create an EndEntityCert // let ee = webpki::EndEntityCert::from(input).unwrap() // get names // let dns_names = ee.list_dns_names() // names.extend(dns_names.drain(..).map(|name| name.to_String())); unimplemented!("the rustls proxy cannot extract the names from the certificate"); } let names = remove_certificate.names; for name in names { self.domains.domain_remove(&name.into_bytes()); } } self.certificates.remove(&remove_certificate.fingerprint); } } pub struct CertificateResolverWrapper(pub Mutex<CertificateResolver>); impl CertificateResolverWrapper { pub fn new() -> CertificateResolverWrapper { CertificateResolverWrapper(Mutex::new(CertificateResolver::new())) } pub fn add_certificate(&self, add_certificate: AddCertificate) -> Option<CertFingerprint> { if let Ok(ref mut resolver) = self.0.try_lock() { resolver.add_certificate(add_certificate) } else { None } } pub fn remove_certificate(&self, remove_certificate: RemoveCertificate) { if let Ok(ref mut resolver) = self.0.try_lock() { resolver.remove_certificate(remove_certificate) } } } <|fim▁hole|> ) -> Option<CertifiedKey> { let server_name = client_hello.server_name(); let sigschemes = client_hello.sigschemes(); if server_name.is_none() { error!("cannot look up certificate: no SNI from session"); return None; } let name: &str = server_name.unwrap().into(); trace!("trying to resolve name: {:?} for signature scheme: {:?}", name, sigschemes); if let Ok(ref mut resolver) = self.0.try_lock() { //resolver.domains.print(); if let Some(kv) = resolver.domains.domain_lookup(name.as_bytes(), true) { trace!("looking for certificate for {:?} with fingerprint {:?}", name, kv.1); return resolver.certificates.get(&kv.1).as_ref().map(|data| data.cert.clone()); } } error!("could not look up a certificate for server name '{}'", name); None } } pub fn generate_certified_key(certificate_and_key: CertificateAndKey) -> Option<CertifiedKey> { let mut chain = Vec::new(); let mut cert_reader = BufReader::new(certificate_and_key.certificate.as_bytes()); let parsed_certs = pemfile::certs(&mut cert_reader); if let Ok(certs) = parsed_certs { for cert in certs { chain.push(cert); } } else { return None; } for ref cert in certificate_and_key.certificate_chain.iter() { let mut chain_cert_reader = BufReader::new(cert.as_bytes()); if let Ok(parsed_chain_certs) = pemfile::certs(&mut chain_cert_reader) { for cert in parsed_chain_certs { chain.push(cert); } } } let mut key_reader = BufReader::new(certificate_and_key.key.as_bytes()); let parsed_key = pemfile::rsa_private_keys(&mut key_reader); if let Ok(keys) = parsed_key { if !keys.is_empty() { if let Ok(signing_key) = RSASigningKey::new(&keys[0]) { let certified = CertifiedKey::new(chain, Arc::new(Box::new(signing_key))); return Some(certified); } } else { let mut key_reader = BufReader::new(certificate_and_key.key.as_bytes()); let parsed_key = pemfile::pkcs8_private_keys(&mut key_reader); if let Ok(keys) = parsed_key { if !keys.is_empty() { if let Ok(signing_key) = RSASigningKey::new(&keys[0]) { let certified = CertifiedKey::new(chain, Arc::new(Box::new(signing_key))); return Some(certified); } else { if let Ok(k) = rustls::sign::any_ecdsa_type(&keys[0]) { let certified = CertifiedKey::new(chain, Arc::new(k)); return Some(certified); } else { error!("could not decode signing key (tried RSA and ECDSA)"); } } } } } } else { error!("could not parse private key: {:?}", parsed_key); } None }<|fim▁end|>
impl ResolvesServerCert for CertificateResolverWrapper { fn resolve( &self, client_hello: ClientHello
<|file_name|>util.js<|end_file_name|><|fim▁begin|>// -*- Mode: JavaScript; tab-width: 2; indent-tabs-mode: nil; -*- // vim:set ft=javascript ts=2 sw=2 sts=2 cindent: require('./lib/webfont'); //jquery var $ = require('jquery'); var Util = (function(window, undefined) { var fontLoadTimeout = 5000; // 5 seconds var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var isMac = navigator.platform == 'MacIntel'; // XXX should we go broader? var cmp = function(a,b) { return a < b ? -1 : a > b ? 1 : 0; }; var cmpArrayOnFirstElement = function(a,b) { a = a[0]; b = b[0]; return a < b ? -1 : a > b ? 1 : 0; }; var unitAgo = function(n, unit) { if (n == 1) return "" + n + " " + unit + " ago"; return "" + n + " " + unit + "s ago"; }; var formatTimeAgo = function(time) { if (time == -1000) { return "never"; // FIXME make the server return the server time! } var nowDate = new Date(); var now = nowDate.getTime(); var diff = Math.floor((now - time) / 1000); if (!diff) return "just now"; if (diff < 60) return unitAgo(diff, "second"); diff = Math.floor(diff / 60); if (diff < 60) return unitAgo(diff, "minute"); diff = Math.floor(diff / 60); if (diff < 24) return unitAgo(diff, "hour"); diff = Math.floor(diff / 24); if (diff < 7) return unitAgo(diff, "day"); if (diff < 28) return unitAgo(Math.floor(diff / 7), "week"); var thenDate = new Date(time); var result = thenDate.getDate() + ' ' + monthNames[thenDate.getMonth()]; if (thenDate.getYear() != nowDate.getYear()) { result += ' ' + thenDate.getFullYear(); } return result; }; var realBBox = function(span) { var box = span.rect.getBBox(); var chunkTranslation = span.chunk.translation; var rowTranslation = span.chunk.row.translation; box.x += chunkTranslation.x + rowTranslation.x; box.y += chunkTranslation.y + rowTranslation.y; return box; }; var escapeHTML = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }; var escapeHTMLandQuotes = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\"/g,'&quot;'); }; var escapeHTMLwithNewlines = function(str) { return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\n/g,'<br/>'); }; var escapeQuotes = function(str) { // we only use double quotes for HTML attributes return str.replace(/\"/g,'&quot;'); }; var getSpanLabels = function(spanTypes, spanType) { var type = spanTypes[spanType]; return type && type.labels || []; }; var spanDisplayForm = function(spanTypes, spanType) { var labels = getSpanLabels(spanTypes, spanType); return labels[0] || spanType; }; var getArcLabels = function(spanTypes, spanType, arcType, relationTypesHash) { var type = spanTypes[spanType]; var arcTypes = type && type.arcs || []; var arcDesc = null; // also consider matches without suffix number, if any var noNumArcType; if (arcType) { var splitType = arcType.match(/^(.*?)(\d*)$/); noNumArcType = splitType[1]; } $.each(arcTypes, function(arcno, arcDescI) { if (arcDescI.type == arcType || arcDescI.type == noNumArcType) { arcDesc = arcDescI; return false; } }); // fall back to relation types for unconfigured or missing def if (!arcDesc) { arcDesc = $.extend({}, relationTypesHash[arcType] || relationTypesHash[noNumArcType]); } return arcDesc && arcDesc.labels || []; }; var arcDisplayForm = function(spanTypes, spanType, arcType, relationTypesHash) { var labels = getArcLabels(spanTypes, spanType, arcType, relationTypesHash); return labels[0] || arcType; }; // TODO: switching to use of $.param(), this function should // be deprecated and removed. var objectToUrlStr = function(o) { a = []; $.each(o, function(key,value) { a.push(key+"="+encodeURIComponent(value)); }); return a.join("&"); }; // color name RGB list, converted from // http://www.w3schools.com/html/html_colornames.asp // with perl as // perl -e 'print "var colors = {\n"; while(<>) { /(\S+)\s+\#([0-9a-z]{2})([0-9a-z]{2})([0-9a-z]{2})\s*/i or die "Failed to parse $_"; ($r,$g,$b)=(hex($2),hex($3),hex($4)); print " '\''",lc($1),"'\'':\[$r,$g,$b\],\n" } print "};\n" ' var colors = { 'aliceblue':[240,248,255], 'antiquewhite':[250,235,215], 'aqua':[0,255,255], 'aquamarine':[127,255,212], 'azure':[240,255,255], 'beige':[245,245,220], 'bisque':[255,228,196], 'black':[0,0,0], 'blanchedalmond':[255,235,205], 'blue':[0,0,255], 'blueviolet':[138,43,226], 'brown':[165,42,42], 'burlywood':[222,184,135], 'cadetblue':[95,158,160], 'chartreuse':[127,255,0], 'chocolate':[210,105,30], 'coral':[255,127,80], 'cornflowerblue':[100,149,237], 'cornsilk':[255,248,220], 'crimson':[220,20,60], 'cyan':[0,255,255], 'darkblue':[0,0,139], 'darkcyan':[0,139,139], 'darkgoldenrod':[184,134,11], 'darkgray':[169,169,169], 'darkgrey':[169,169,169], 'darkgreen':[0,100,0], 'darkkhaki':[189,183,107], 'darkmagenta':[139,0,139], 'darkolivegreen':[85,107,47], 'darkorange':[255,140,0], 'darkorchid':[153,50,204], 'darkred':[139,0,0], 'darksalmon':[233,150,122], 'darkseagreen':[143,188,143], 'darkslateblue':[72,61,139], 'darkslategray':[47,79,79], 'darkslategrey':[47,79,79], 'darkturquoise':[0,206,209], 'darkviolet':[148,0,211], 'deeppink':[255,20,147], 'deepskyblue':[0,191,255], 'dimgray':[105,105,105], 'dimgrey':[105,105,105], 'dodgerblue':[30,144,255], 'firebrick':[178,34,34], 'floralwhite':[255,250,240], 'forestgreen':[34,139,34], 'fuchsia':[255,0,255], 'gainsboro':[220,220,220], 'ghostwhite':[248,248,255], 'gold':[255,215,0], 'goldenrod':[218,165,32], 'gray':[128,128,128], 'grey':[128,128,128], 'green':[0,128,0], 'greenyellow':[173,255,47], 'honeydew':[240,255,240], 'hotpink':[255,105,180], 'indianred':[205,92,92], 'indigo':[75,0,130], 'ivory':[255,255,240], 'khaki':[240,230,140], 'lavender':[230,230,250], 'lavenderblush':[255,240,245], 'lawngreen':[124,252,0], 'lemonchiffon':[255,250,205], 'lightblue':[173,216,230], 'lightcoral':[240,128,128], 'lightcyan':[224,255,255], 'lightgoldenrodyellow':[250,250,210], 'lightgray':[211,211,211], 'lightgrey':[211,211,211], 'lightgreen':[144,238,144], 'lightpink':[255,182,193], 'lightsalmon':[255,160,122], 'lightseagreen':[32,178,170], 'lightskyblue':[135,206,250], 'lightslategray':[119,136,153], 'lightslategrey':[119,136,153], 'lightsteelblue':[176,196,222], 'lightyellow':[255,255,224], 'lime':[0,255,0], 'limegreen':[50,205,50], 'linen':[250,240,230], 'magenta':[255,0,255], 'maroon':[128,0,0], 'mediumaquamarine':[102,205,170], 'mediumblue':[0,0,205], 'mediumorchid':[186,85,211], 'mediumpurple':[147,112,216], 'mediumseagreen':[60,179,113], 'mediumslateblue':[123,104,238], 'mediumspringgreen':[0,250,154], 'mediumturquoise':[72,209,204], 'mediumvioletred':[199,21,133], 'midnightblue':[25,25,112], 'mintcream':[245,255,250], 'mistyrose':[255,228,225], 'moccasin':[255,228,181], 'navajowhite':[255,222,173], 'navy':[0,0,128], 'oldlace':[253,245,230], 'olive':[128,128,0], 'olivedrab':[107,142,35], 'orange':[255,165,0], 'orangered':[255,69,0], 'orchid':[218,112,214], 'palegoldenrod':[238,232,170], 'palegreen':[152,251,152], 'paleturquoise':[175,238,238], 'palevioletred':[216,112,147], 'papayawhip':[255,239,213], 'peachpuff':[255,218,185], 'peru':[205,133,63], 'pink':[255,192,203], 'plum':[221,160,221], 'powderblue':[176,224,230], 'purple':[128,0,128], 'red':[255,0,0], 'rosybrown':[188,143,143], 'royalblue':[65,105,225], 'saddlebrown':[139,69,19], 'salmon':[250,128,114], 'sandybrown':[244,164,96], 'seagreen':[46,139,87], 'seashell':[255,245,238], 'sienna':[160,82,45], 'silver':[192,192,192], 'skyblue':[135,206,235], 'slateblue':[106,90,205], 'slategray':[112,128,144], 'slategrey':[112,128,144], 'snow':[255,250,250], 'springgreen':[0,255,127], 'steelblue':[70,130,180], 'tan':[210,180,140], 'teal':[0,128,128], 'thistle':[216,191,216], 'tomato':[255,99,71], 'turquoise':[64,224,208], 'violet':[238,130,238], 'wheat':[245,222,179], 'white':[255,255,255], 'whitesmoke':[245,245,245], 'yellow':[255,255,0], 'yellowgreen':[154,205,50], }; // color parsing function originally from // http://plugins.jquery.com/files/jquery.color.js.txt // (with slight modifications) // Parse strings looking for color tuples [255,255,255] var rgbNumRE = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/; var rgbPercRE = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/; var rgbHash6RE = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/; var rgbHash3RE = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/; var strToRgb = function(color) { var result; // Check if we're already dealing with an array of colors // if ( color && color.constructor == Array && color.length == 3 ) // return color; // Look for rgb(num,num,num) if (result = rgbNumRE.exec(color)) return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])]; // Look for rgb(num%,num%,num%) if (result = rgbPercRE.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; // Look for #a0b1c2 if (result = rgbHash6RE.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = rgbHash3RE.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Otherwise, we're most likely dealing with a named color return colors[$.trim(color).toLowerCase()]; }; var rgbToStr = function(rgb) { // TODO: there has to be a better way, even in JS var r = Math.floor(rgb[0]).toString(16); var g = Math.floor(rgb[1]).toString(16); var b = Math.floor(rgb[2]).toString(16); // pad r = r.length < 2 ? '0' + r : r; g = g.length < 2 ? '0' + g : g; b = b.length < 2 ? '0' + b : b; return ('#'+r+g+b); }; // Functions rgbToHsl and hslToRgb originally from // http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript // implementation of functions in Wikipedia // (with slight modifications) // RGB to HSL color conversion var rgbToHsl = function(rgb) { var r = rgb[0]/255, g = rgb[1]/255, b = rgb[2]/255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; if (max == min) { h = s = 0; // achromatic } else { var d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return [h, s, l]; }; var hue2rgb = function(p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1/6) return p + (q - p) * 6 * t; if (t < 1/2) return q; if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; }; var hslToRgb = function(hsl) { var h = hsl[0], s = hsl[1], l = hsl[2]; var r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return [r * 255, g * 255, b * 255]; }; var adjustLightnessCache = {}; // given color string and -1<=adjust<=1, returns color string // where lightness (in the HSL sense) is adjusted by the given // amount, the larger the lighter: -1 gives black, 1 white, and 0 // the given color. var adjustColorLightness = function(colorstr, adjust) { if (!(colorstr in adjustLightnessCache)) { adjustLightnessCache[colorstr] = {} } if (!(adjust in adjustLightnessCache[colorstr])) { var rgb = strToRgb(colorstr); if (rgb === undefined) { // failed color string conversion; just return the input adjustLightnessCache[colorstr][adjust] = colorstr; } else { var hsl = rgbToHsl(rgb); if (adjust > 0.0) { hsl[2] = 1.0 - ((1.0-hsl[2])*(1.0-adjust)); } else { hsl[2] = (1.0+adjust)*hsl[2]; } var lightRgb = hslToRgb(hsl); adjustLightnessCache[colorstr][adjust] = rgbToStr(lightRgb); } } return adjustLightnessCache[colorstr][adjust]; }; // Partially stolen from: http://documentcloud.github.com/underscore/ // MIT-License // TODO: Mention in LICENSE.md var isEqual = function(a, b) { // Check object identity. if (a === b) return true; // Different types? var atype = typeof(a), btype = typeof(b); if (atype != btype) return false; // Basic equality test (watch out for coercions). if (a == b) return true; // One is falsy and the other truthy. if ((!a && b) || (a && !b)) return false; // If a is not an object by this point, we can't handle it. if (atype !== 'object') return false; // Check for different array lengths before comparing contents. if (a.length && (a.length !== b.length)) return false; // Nothing else worked, deep compare the contents. for (var key in b) if (!(key in a)) return false; // Recursive comparison of contents. for (var key in a) if (!(key in b) || !isEqual(a[key], b[key])) return false; return true; }; var keyValRE = /^([^=]+)=(.*)$/; // key=value var isDigitsRE = /^[0-9]+$/; var deparam = function(str) { var args = str.split('&'); var len = args.length; if (!len) return null; var result = {}; for (var i = 0; i < len; i++) { var parts = args[i].match(keyValRE); if (!parts || parts.length != 3) break; var val = []; var arr = parts[2].split(','); var sublen = arr.length; for (var j = 0; j < sublen; j++) { var innermost = []; // map empty arguments ("" in URL) to empty arrays // (innermost remains []) if (arr[j].length) { var arrsplit = arr[j].split('~'); var subsublen = arrsplit.length; for (var k = 0; k < subsublen; k++) { if(arrsplit[k].match(isDigitsRE)) { // convert digits into ints ... innermost.push(parseInt(arrsplit[k], 10)); } else { // ... anything else remains a string. innermost.push(arrsplit[k]); } } } val.push(innermost); } result[parts[1]] = val; } return result; }; var paramArray = function(val) { val = val || []; var len = val.length; var arr = []; for (var i = 0; i < len; i++) { if ($.isArray(val[i])) { arr.push(val[i].join('~')); } else { // non-array argument; this is an error from the caller console.error('param: Error: received non-array-in-array argument [', i, ']', ':', val[i], '(fix caller)'); } } return arr; }; var param = function(args) { if (!args) return ''; var vals = []; for (var key in args) { if (args.hasOwnProperty(key)) { var val = args[key]; if (val == undefined) { console.error('Error: received argument', key, 'with value', val); continue; } // values normally expected to be arrays, but some callers screw // up, so check if ($.isArray(val)) { var arr = paramArray(val); vals.push(key + '=' + arr.join(',')); } else { // non-array argument; this is an error from the caller console.error('param: Error: received non-array argument', key, ':', val, '(fix caller)'); } } } return vals.join('&'); }; var profiles = {}; var profileStarts = {}; var profileOn = false;<|fim▁hole|> var profileClear = function() { if (!profileOn) return; profiles = {}; profileStarts = {}; }; // profileClear var profileStart = function(label) { if (!profileOn) return; profileStarts[label] = new Date(); }; // profileStart var profileEnd = function(label) { if (!profileOn) return; var profileElapsed = new Date() - profileStarts[label] if (!profiles[label]) profiles[label] = 0; profiles[label] += profileElapsed; }; // profileEnd var profileReport = function() { if (!profileOn) return; if (window.console) { $.each(profiles, function(label, time) { console.log("profile " + label, time); }); console.log("-------"); } }; // profileReport var fontsLoaded = false; var fontNotifyList = false; var proceedWithFonts = function() { if (fontsLoaded) return; fontsLoaded = true; $.each(fontNotifyList, function(dispatcherNo, dispatcher) { dispatcher.post('triggerRender'); }); fontNotifyList = null; }; var loadFonts = function(webFontURLs, dispatcher) { if (fontsLoaded) { dispatcher.post('triggerRender'); return; } if (fontNotifyList) { fontNotifyList.push(dispatcher); return; } fontNotifyList = [dispatcher]; var families = []; $.each(webFontURLs, function(urlNo, url) { if (/Astloch/i.test(url)) families.push('Astloch'); else if (/PT.*Sans.*Caption/i.test(url)) families.push('PT Sans Caption'); else if (/Liberation.*Sans/i.test(url)) families.push('Liberation Sans'); }); webFontURLs = { families: families, urls: webFontURLs } var webFontConfig = { custom: webFontURLs, active: proceedWithFonts, inactive: proceedWithFonts, fontactive: function(fontFamily, fontDescription) { // Note: Enable for font debugging // console.log("font active: ", fontFamily, fontDescription); }, fontloading: function(fontFamily, fontDescription) { // Note: Enable for font debugging // console.log("font loading:", fontFamily, fontDescription); }, }; WebFont.load(webFontConfig); setTimeout(function() { if (!fontsLoaded) { console.error('Timeout in loading fonts'); proceedWithFonts(); } }, fontLoadTimeout); }; var areFontsLoaded = function() { return fontsLoaded; }; return { profileEnable: profileEnable, profileClear: profileClear, profileStart: profileStart, profileEnd: profileEnd, profileReport: profileReport, formatTimeAgo: formatTimeAgo, realBBox: realBBox, getSpanLabels: getSpanLabels, spanDisplayForm: spanDisplayForm, getArcLabels: getArcLabels, arcDisplayForm: arcDisplayForm, escapeQuotes: escapeQuotes, escapeHTML: escapeHTML, escapeHTMLandQuotes: escapeHTMLandQuotes, escapeHTMLwithNewlines: escapeHTMLwithNewlines, cmp: cmp, rgbToHsl: rgbToHsl, hslToRgb: hslToRgb, adjustColorLightness: adjustColorLightness, objectToUrlStr: objectToUrlStr, isEqual: isEqual, paramArray: paramArray, param: param, deparam: deparam, isMac: isMac, loadFonts: loadFonts, areFontsLoaded: areFontsLoaded, }; })(window); module.exports = Util;<|fim▁end|>
var profileEnable = function(on) { if (on === undefined) on = true; profileOn = on; }; // profileEnable
<|file_name|>vmwareapi_net.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2011 Citrix Systems, Inc. # Copyright 2011 OpenStack 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 # # 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. """ Implements vlans for vmwareapi. """ from nova import db from nova import exception from nova import flags from nova import log as logging from nova import utils from nova.virt.vmwareapi_conn import VMWareAPISession from nova.virt.vmwareapi import network_utils LOG = logging.getLogger("nova.network.vmwareapi_net") FLAGS = flags.FLAGS flags.DEFINE_string('vlan_interface', 'vmnic0', 'Physical network adapter name in VMware ESX host for '<|fim▁hole|> 'vlan networking') def ensure_vlan_bridge(vlan_num, bridge, net_attrs=None): """Create a vlan and bridge unless they already exist.""" # Open vmwareapi session host_ip = FLAGS.vmwareapi_host_ip host_username = FLAGS.vmwareapi_host_username host_password = FLAGS.vmwareapi_host_password if not host_ip or host_username is None or host_password is None: raise Exception(_("Must specify vmwareapi_host_ip," "vmwareapi_host_username " "and vmwareapi_host_password to use" "connection_type=vmwareapi")) session = VMWareAPISession(host_ip, host_username, host_password, FLAGS.vmwareapi_api_retry_count) vlan_interface = FLAGS.vlan_interface # Check if the vlan_interface physical network adapter exists on the host if not network_utils.check_if_vlan_interface_exists(session, vlan_interface): raise exception.NetworkAdapterNotFound(adapter=vlan_interface) # Get the vSwitch associated with the Physical Adapter vswitch_associated = network_utils.get_vswitch_for_vlan_interface( session, vlan_interface) if vswitch_associated is None: raise exception.SwicthNotFoundForNetworkAdapter(adapter=vlan_interface) # Check whether bridge already exists and retrieve the the ref of the # network whose name_label is "bridge" network_ref = network_utils.get_network_with_the_name(session, bridge) if network_ref is None: # Create a port group on the vSwitch associated with the vlan_interface # corresponding physical network adapter on the ESX host network_utils.create_port_group(session, bridge, vswitch_associated, vlan_num) else: # Get the vlan id and vswitch corresponding to the port group pg_vlanid, pg_vswitch = \ network_utils.get_vlanid_and_vswitch_for_portgroup(session, bridge) # Check if the vswitch associated is proper if pg_vswitch != vswitch_associated: raise exception.InvalidVLANPortGroup(bridge=bridge, expected=vswitch_associated, actual=pg_vswitch) # Check if the vlan id is proper for the port group if pg_vlanid != vlan_num: raise exception.InvalidVLANTag(bridge=bridge, tag=vlan_num, pgroup=pg_vlanid)<|fim▁end|>
<|file_name|>blockdev.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/. // Code to handle a single block device. use std::{fs::OpenOptions, path::Path}; use chrono::{DateTime, TimeZone, Utc}; use serde_json::Value; use devicemapper::{Device, Sectors}; use crate::{ engine::{ engine::BlockDev, strat_engine::{ backstore::{ crypt::CryptHandle, range_alloc::{PerDevSegments, RangeAllocator}, }, metadata::{disown_device, BDAExtendedSize, BlockdevSize, MDADataSize, BDA}, serde_structs::{BaseBlockDevSave, Recordable}, }, types::{DevUuid, DevicePath, EncryptionInfo, KeyDescription, PoolUuid}, }, stratis::{StratisError, StratisResult}, }; #[derive(Debug)] pub enum UnderlyingDevice { Encrypted(CryptHandle), Unencrypted(DevicePath), } impl UnderlyingDevice { pub fn physical_path(&self) -> &Path { match self { UnderlyingDevice::Encrypted(handle) => handle.luks2_device_path(), UnderlyingDevice::Unencrypted(path) => &*path, } } pub fn metadata_path(&self) -> &Path { match self { UnderlyingDevice::Encrypted(handle) => handle.activated_device_path(), UnderlyingDevice::Unencrypted(path) => &*path, } } pub fn crypt_handle(&self) -> Option<&CryptHandle> { match self { UnderlyingDevice::Encrypted(handle) => Some(handle), UnderlyingDevice::Unencrypted(_) => None, } } pub fn crypt_handle_mut(&mut self) -> Option<&mut CryptHandle> { match self { UnderlyingDevice::Encrypted(handle) => Some(handle), UnderlyingDevice::Unencrypted(_) => None, } } } #[derive(Debug)] pub struct StratBlockDev { dev: Device, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, underlying_device: UnderlyingDevice, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate space for the Stratis metadata on the device. /// - dev: the device, identified by number /// - devnode: for encrypted devices, the logical and physical /// paths; for unencrypted devices, the physical path /// - bda: the device's BDA /// - other_segments: segments allocated outside Stratis metadata region /// - user_info: user settable identifying information /// - hardware_info: identifying information in the hardware /// - key_description: optional argument enabling encryption using /// the specified key in the kernel keyring /// Returns an error if it is impossible to allocate all segments on the /// device. /// NOTE: It is possible that the actual device size is greater than /// the recorded device size. In that case, the additional space available /// on the device is simply invisible to the blockdev. Consequently, it /// is invisible to the engine, and is not part of the total size value /// reported on the D-Bus. /// /// Precondition: segments in other_segments do not overlap with Stratis /// metadata region. pub fn new( dev: Device, bda: BDA, other_segments: &[(Sectors, Sectors)], user_info: Option<String>, hardware_info: Option<String>, underlying_device: UnderlyingDevice, ) -> StratisResult<StratBlockDev> { let mut segments = vec![(Sectors(0), bda.extended_size().sectors())]; segments.extend(other_segments); let allocator = RangeAllocator::new(bda.dev_size(), &segments)?; Ok(StratBlockDev { dev, bda, used: allocator,<|fim▁hole|> } /// Returns the blockdev's Device pub fn device(&self) -> &Device { &self.dev } /// Returns the physical path of the block device structure. pub fn physical_path(&self) -> &Path { self.devnode() } /// Returns the path to the unencrypted metadata stored on the block device structure. /// On encrypted devices, this will point to a devicemapper device set up by libcryptsetup. /// On unencrypted devices, this will be the same as the physical device. pub fn metadata_path(&self) -> &Path { self.underlying_device.metadata_path() } /// Remove information that identifies this device as belonging to Stratis /// /// If self.is_encrypted() is true, destroy all keyslots and wipe the LUKS2 header. /// This will render all Stratis and LUKS2 metadata unreadable and unrecoverable /// from the given device. /// /// If self.is_encrypted() is false, wipe the Stratis metadata on the device. /// This will make the Stratis data and metadata invisible to all standard blkid /// and stratisd operations. /// /// Precondition: if self.is_encrypted() == true, the data on /// self.devnode.physical_path() has been encrypted with /// aes-xts-plain64 encryption. pub fn disown(&mut self) -> StratisResult<()> { if let Some(ref mut handle) = self.underlying_device.crypt_handle_mut() { handle.wipe()?; } else { disown_device( &mut OpenOptions::new() .write(true) .open(self.underlying_device.physical_path())?, )?; } Ok(()) } pub fn save_state(&mut self, time: &DateTime<Utc>, metadata: &[u8]) -> StratisResult<()> { let mut f = OpenOptions::new() .write(true) .open(self.underlying_device.metadata_path())?; self.bda.save_state(time, metadata, &mut f) } /// The pool's UUID. pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// The device's UUID. pub fn uuid(&self) -> DevUuid { self.bda.dev_uuid() } /// Find some sector ranges that could be allocated. If more /// sectors are needed than are available, return partial results. /// If all available sectors are desired, don't use this function. /// Define a request_all() function here and have it invoke the /// RangeAllocator::request_all() function. pub fn request_space(&mut self, size: Sectors) -> PerDevSegments { self.used.request(size) } // ALL SIZE METHODS (except size(), which is in BlockDev impl.) /// The number of Sectors on this device used by Stratis for metadata pub fn metadata_size(&self) -> BDAExtendedSize { self.bda.extended_size() } /// The number of Sectors on this device not allocated for any purpose. /// self.total_allocated_size() - self.metadata_size() >= self.available() pub fn available(&self) -> Sectors { self.used.available() } /// The total size of the Stratis block device. pub fn total_size(&self) -> BlockdevSize { self.bda.dev_size() } /// The total size of the allocated portions of the Stratis block device. pub fn total_allocated_size(&self) -> BlockdevSize { self.used.size() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> MDADataSize { self.bda.max_data_size() } /// Set the user info on this blockdev. /// The user_info may be None, which unsets user info. /// Returns true if the user info was changed, otherwise false. pub fn set_user_info(&mut self, user_info: Option<&str>) -> bool { set_blockdev_user_info!(self; user_info) } /// Get the physical path for a block device. pub fn devnode(&self) -> &Path { self.underlying_device.physical_path() } /// Get the encryption_info stored on the given encrypted blockdev. /// /// The `Cow` return type is required due to the optional `CryptHandle` type. /// If the device is not encrypted, it must return an owned `EncryptionInfo` /// structure. pub fn encryption_info(&self) -> Option<&EncryptionInfo> { self.underlying_device .crypt_handle() .map(|ch| ch.encryption_info()) } /// Bind encrypted device using the given clevis configuration. pub fn bind_clevis(&mut self, pin: &str, clevis_info: &Value) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.clevis_bind(pin, clevis_info) } /// Unbind encrypted device using the given clevis configuration. pub fn unbind_clevis(&mut self) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.clevis_unbind() } /// Bind a block device to a passphrase represented by a key description /// in the kernel keyring. pub fn bind_keyring(&mut self, key_desc: &KeyDescription) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.bind_keyring(key_desc) } /// Unbind a block device from a passphrase represented by a key description /// in the kernel keyring. pub fn unbind_keyring(&mut self) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.unbind_keyring() } /// Change the passphrase for a block device to a passphrase represented by a /// key description in the kernel keyring. pub fn rebind_keyring(&mut self, key_desc: &KeyDescription) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.rebind_keyring(key_desc) } /// Regenerate the Clevis bindings for a block device. pub fn rebind_clevis(&mut self) -> StratisResult<()> { let crypt_handle = self.underlying_device.crypt_handle_mut().ok_or_else(|| { StratisError::Msg("This device does not appear to be encrypted".to_string()) })?; crypt_handle.rebind_clevis() } } impl<'a> Into<Value> for &'a StratBlockDev { fn into(self) -> Value { let mut json = json!({ "path": self.underlying_device.physical_path(), "uuid": self.bda.dev_uuid().to_string(), }); let map = json.as_object_mut().expect("just created above"); if let Some(encryption_info) = self .underlying_device .crypt_handle() .map(|ch| ch.encryption_info()) { if let Value::Object(enc_map) = <&EncryptionInfo as Into<Value>>::into(encryption_info) { map.extend(enc_map); } else { unreachable!("EncryptionInfo conversion returns a JSON object"); }; } json } } impl BlockDev for StratBlockDev { fn devnode(&self) -> &Path { self.devnode() } fn metadata_path(&self) -> &Path { self.metadata_path() } fn user_info(&self) -> Option<&str> { self.user_info.as_deref() } fn hardware_info(&self) -> Option<&str> { self.hardware_info.as_deref() } fn initialization_time(&self) -> DateTime<Utc> { // This cast will result in an incorrect, negative value starting in // the year 292,277,026,596. :-) Utc.timestamp(self.bda.initialization_time() as i64, 0) } fn size(&self) -> Sectors { self.total_size().sectors() } fn is_encrypted(&self) -> bool { self.encryption_info().is_some() } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBlockDevSave { BaseBlockDevSave { uuid: self.uuid(), user_info: self.user_info.clone(), hardware_info: self.hardware_info.clone(), } } }<|fim▁end|>
user_info, hardware_info, underlying_device, })
<|file_name|>run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage <|fim▁hole|># See the test.osl source for explanation of this test command = testshade("-g 16 16 test -od uint8 -o Cout out.tif") outputs = [ "out.tif" ]<|fim▁end|>
<|file_name|>urlresolvers.py<|end_file_name|><|fim▁begin|>""" This module converts requested URLs to callback view functions. RegexURLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ from __future__ import unicode_literals import functools import re import warnings from importlib import import_module from threading import local from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.http import Http404 from django.utils import lru_cache, six from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango110Warning from django.utils.encoding import force_str, force_text, iri_to_uri from django.utils.functional import cached_property, lazy from django.utils.http import RFC3986_SUBDELIMS, urlquote from django.utils.module_loading import module_has_submodule from django.utils.regex_helper import normalize from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit from django.utils.translation import get_language, override # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for # the current thread (which is the only one we ever access), it is assumed to # be empty. _prefixes = local() # Overridden URLconfs for each thread are stored here. _urlconfs = local() class ResolverMatch(object): def __init__(self, func, args, kwargs, url_name=None, app_names=None, namespaces=None): self.func = func self.args = args self.kwargs = kwargs self.url_name = url_name # If a URLRegexResolver doesn't have a namespace or app_name, it passes # in an empty value. self.app_names = [x for x in app_names if x] if app_names else [] self.app_name = ':'.join(self.app_names) if namespaces: self.namespaces = [x for x in namespaces if x] else: self.namespaces = [] self.namespace = ':'.join(self.namespaces) if not hasattr(func, '__name__'): # A class-based view self._func_path = '.'.join([func.__class__.__module__, func.__class__.__name__]) else: # A function-based view self._func_path = '.'.join([func.__module__, func.__name__]) view_path = url_name or self._func_path self.view_name = ':'.join(self.namespaces + [view_path]) def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): return "ResolverMatch(func=%s, args=%s, kwargs=%s, url_name=%s, app_names=%s, namespaces=%s)" % ( self._func_path, self.args, self.kwargs, self.url_name, self.app_names, self.namespaces) class Resolver404(Http404): pass class NoReverseMatch(Exception): pass @lru_cache.lru_cache(maxsize=None) def get_callable(lookup_view, can_fail=False): """ Return a callable corresponding to lookup_view. This function is used by both resolve() and reverse(), so can_fail allows the caller to choose between returning the input as is and raising an exception when the input string can't be interpreted as an import path. If lookup_view is already a callable, return it. If lookup_view is a string import path that can be resolved to a callable, import that callable and return it. If lookup_view is some other kind of string and can_fail is True, the string is returned as is. If can_fail is False, an exception is raised (either ImportError or ViewDoesNotExist). """ if callable(lookup_view): return lookup_view if not isinstance(lookup_view, six.string_types): raise ViewDoesNotExist( "'%s' is not a callable or a dot-notation path" % lookup_view ) mod_name, func_name = get_mod_func(lookup_view) if not func_name: # No '.' in lookup_view if can_fail: return lookup_view else: raise ImportError( "Could not import '%s'. The path must be fully qualified." % lookup_view) try: mod = import_module(mod_name) except ImportError: if can_fail: return lookup_view else: parentmod, submod = get_mod_func(mod_name) if submod and not module_has_submodule(import_module(parentmod), submod): raise ViewDoesNotExist( "Could not import '%s'. Parent module %s does not exist." % (lookup_view, mod_name)) else: raise else: try: view_func = getattr(mod, func_name) except AttributeError: if can_fail: return lookup_view else: raise ViewDoesNotExist( "Could not import '%s'. View does not exist in module %s." % (lookup_view, mod_name)) else: if not callable(view_func): # For backwards compatibility this is raised regardless of can_fail raise ViewDoesNotExist( "Could not import '%s.%s'. View is not callable." % (mod_name, func_name)) return view_func @lru_cache.lru_cache(maxsize=None) def get_resolver(urlconf=None): if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF return RegexURLResolver(r'^/', urlconf) @lru_cache.lru_cache(maxsize=None) def get_ns_resolver(ns_pattern, resolver): # Build a namespaced resolver for the given parent urlconf pattern. # This makes it possible to have captured parameters in the parent # urlconf pattern. ns_resolver = RegexURLResolver(ns_pattern, resolver.url_patterns) return RegexURLResolver(r'^/', [ns_resolver]) def get_mod_func(callback): # Converts 'django.views.news.stories.story_detail' to # ['django.views.news.stories', 'story_detail'] try: dot = callback.rindex('.') except ValueError: return callback, '' return callback[:dot], callback[dot + 1:] class LocaleRegexProvider(object): """ A mixin to provide a default regex property which can vary by active language. """ def __init__(self, regex): # regex is either a string representing a regular expression, or a # translatable string (using ugettext_lazy) representing a regular # expression. self._regex = regex self._regex_dict = {} @property def regex(self): """ Returns a compiled regular expression, depending upon the activated language-code. """ language_code = get_language() if language_code not in self._regex_dict: if isinstance(self._regex, six.string_types): regex = self._regex else: regex = force_text(self._regex) try: compiled_regex = re.compile(regex, re.UNICODE) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, six.text_type(e))) self._regex_dict[language_code] = compiled_regex return self._regex_dict[language_code] class RegexURLPattern(LocaleRegexProvider): def __init__(self, regex, callback, default_args=None, name=None): LocaleRegexProvider.__init__(self, regex) # callback is either a string like 'foo.views.news.stories.story_detail' # which represents the path to a module and a view function name, or a # callable object (view). if callable(callback): self._callback = callback else: self._callback = None self._callback_str = callback self.default_args = default_args or {} self.name = name def __repr__(self): return force_str('<%s %s %s>' % (self.__class__.__name__, self.name, self.regex.pattern)) def add_prefix(self, prefix): """ Adds the prefix string to a string-based callback. """ if not prefix or not hasattr(self, '_callback_str'): return self._callback_str = prefix + '.' + self._callback_str def resolve(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. kwargs = match.groupdict() if kwargs: args = () else: args = match.groups() # In both cases, pass any extra_kwargs as **kwargs. kwargs.update(self.default_args) return ResolverMatch(self.callback, args, kwargs, self.name) @property def callback(self): if self._callback is not None: return self._callback self._callback = get_callable(self._callback_str) return self._callback class RegexURLResolver(LocaleRegexProvider): def __init__(self, regex, urlconf_name, default_kwargs=None, app_name=None, namespace=None): LocaleRegexProvider.__init__(self, regex) # urlconf_name is the dotted Python path to the module defining # urlpatterns. It may also be an object with an urlpatterns attribute # or urlpatterns itself. self.urlconf_name = urlconf_name self.callback = None self.default_kwargs = default_kwargs or {} self.namespace = namespace self.app_name = app_name self._reverse_dict = {} self._namespace_dict = {} self._app_dict = {} # set of dotted paths to all functions and classes that are used in # urlpatterns self._callback_strs = set() self._populated = False def __repr__(self): if isinstance(self.urlconf_name, list) and len(self.urlconf_name): # Don't bother to output the whole list, it can be huge urlconf_repr = '<%s list>' % self.urlconf_name[0].__class__.__name__ else: urlconf_repr = repr(self.urlconf_name) return str('<%s %s (%s:%s) %s>') % ( self.__class__.__name__, urlconf_repr, self.app_name, self.namespace, self.regex.pattern) def _populate(self): lookups = MultiValueDict() namespaces = {} apps = {} language_code = get_language() for pattern in reversed(self.url_patterns): if hasattr(pattern, '_callback_str'): self._callback_strs.add(pattern._callback_str) elif hasattr(pattern, '_callback'): callback = pattern._callback if isinstance(callback, functools.partial): callback = callback.func if not hasattr(callback, '__name__'): lookup_str = callback.__module__ + "." + callback.__class__.__name__ else: lookup_str = callback.__module__ + "." + callback.__name__ self._callback_strs.add(lookup_str) p_pattern = pattern.regex.pattern if p_pattern.startswith('^'): p_pattern = p_pattern[1:] if isinstance(pattern, RegexURLResolver): if pattern.namespace: namespaces[pattern.namespace] = (p_pattern, pattern) if pattern.app_name: apps.setdefault(pattern.app_name, []).append(pattern.namespace) else: parent_pat = pattern.regex.pattern for name in pattern.reverse_dict: for matches, pat, defaults in pattern.reverse_dict.getlist(name): new_matches = normalize(parent_pat + pat) lookups.appendlist( name, ( new_matches, p_pattern + pat, dict(defaults, **pattern.default_kwargs), ) ) for namespace, (prefix, sub_pattern) in pattern.namespace_dict.items(): namespaces[namespace] = (p_pattern + prefix, sub_pattern) for app_name, namespace_list in pattern.app_dict.items(): apps.setdefault(app_name, []).extend(namespace_list) self._callback_strs.update(pattern._callback_strs) else: bits = normalize(p_pattern) lookups.appendlist(pattern.callback, (bits, p_pattern, pattern.default_args)) if pattern.name is not None: lookups.appendlist(pattern.name, (bits, p_pattern, pattern.default_args)) self._reverse_dict[language_code] = lookups self._namespace_dict[language_code] = namespaces self._app_dict[language_code] = apps self._populated = True @property def reverse_dict(self): language_code = get_language() if language_code not in self._reverse_dict: self._populate() return self._reverse_dict[language_code] @property def namespace_dict(self): language_code = get_language() if language_code not in self._namespace_dict: self._populate() return self._namespace_dict[language_code] @property def app_dict(self): language_code = get_language() if language_code not in self._app_dict: self._populate() return self._app_dict[language_code] def _is_callback(self, name): if not self._populated: self._populate() return name in self._callback_strs def resolve(self, path): path = force_text(path) # path may be a reverse_lazy object tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([pattern] + t for t in sub_tried) else: tried.append([pattern]) else: if sub_match: # Merge captured arguments in match with submatch sub_match_dict = dict(match.groupdict(), **self.default_kwargs) sub_match_dict.update(sub_match.kwargs) # If there are *any* named groups, ignore all non-named groups. # Otherwise, pass all non-named arguments as positional arguments. sub_match_args = sub_match.args if not sub_match_dict: sub_match_args = match.groups() + sub_match.args return ResolverMatch( sub_match.func, sub_match_args, sub_match_dict, sub_match.url_name, [self.app_name] + sub_match.app_names, [self.namespace] + sub_match.namespaces ) tried.append([pattern]) raise Resolver404({'tried': tried, 'path': new_path}) raise Resolver404({'path': path}) @cached_property def urlconf_module(self): if isinstance(self.urlconf_name, six.string_types): return import_module(self.urlconf_name) else: return self.urlconf_name @cached_property def url_patterns(self): # urlconf_module might be a valid set of patterns, so we default to it patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except TypeError: msg = ( "The included urlconf '{name}' does not appear to have any " "patterns in it. If you see valid patterns in the file then " "the issue is probably caused by a circular import." )<|fim▁hole|> callback = getattr(self.urlconf_module, 'handler%s' % view_type, None) if not callback: # No handler specified in file; use default # Lazy import, since django.urls imports this file from django.conf import urls callback = getattr(urls, 'handler%s' % view_type) return get_callable(callback), {} def reverse(self, lookup_view, *args, **kwargs): return self._reverse_with_prefix(lookup_view, '', *args, **kwargs) def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") text_args = [force_text(v) for v in args] text_kwargs = {k: force_text(v) for (k, v) in kwargs.items()} if not self._populated: self._populate() original_lookup = lookup_view try: if self._is_callback(lookup_view): lookup_view = get_callable(lookup_view, True) except (ImportError, AttributeError) as e: raise NoReverseMatch("Error importing '%s': %s." % (lookup_view, e)) else: if not callable(original_lookup) and callable(lookup_view): warnings.warn( 'Reversing by dotted path is deprecated (%s).' % original_lookup, RemovedInDjango110Warning, stacklevel=3 ) possibilities = self.reverse_dict.getlist(lookup_view) for possibility, pattern, defaults in possibilities: for result, params in possibility: if args: if len(args) != len(params): continue candidate_subs = dict(zip(params, text_args)) else: if (set(kwargs.keys()) | set(defaults.keys()) != set(params) | set(defaults.keys())): continue matches = True for k, v in defaults.items(): if kwargs.get(k, v) != v: matches = False break if not matches: continue candidate_subs = text_kwargs # WSGI provides decoded URLs, without %xx escapes, and the URL # resolver operates on such URLs. First substitute arguments # without quoting to build a decoded URL and look for a match. # Then, if we have a match, redo the substitution with quoted # arguments in order to return a properly encoded URL. candidate_pat = _prefix.replace('%', '%%') + result if re.search('^%s%s' % (re.escape(_prefix), pattern), candidate_pat % candidate_subs, re.UNICODE): # safe characters from `pchar` definition of RFC 3986 url = urlquote(candidate_pat % candidate_subs, safe=RFC3986_SUBDELIMS + str('/~:@')) # Don't allow construction of scheme relative urls. if url.startswith('//'): url = '/%%2F%s' % url[2:] return url # lookup_view can be URL label, or dotted path, or callable, Any of # these can be passed in at the top, but callables are not friendly in # error messages. m = getattr(lookup_view, '__module__', None) n = getattr(lookup_view, '__name__', None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view patterns = [pattern for (possibility, pattern, defaults) in possibilities] raise NoReverseMatch("Reverse for '%s' with arguments '%s' and keyword " "arguments '%s' not found. %d pattern(s) tried: %s" % (lookup_view_s, args, kwargs, len(patterns), patterns)) class LocaleRegexURLResolver(RegexURLResolver): """ A URL resolver that always matches the active language code as URL prefix. Rather than taking a regex argument, we just override the ``regex`` function to always return the active language-code as regex. """ def __init__(self, urlconf_name, default_kwargs=None, app_name=None, namespace=None): super(LocaleRegexURLResolver, self).__init__( None, urlconf_name, default_kwargs, app_name, namespace) @property def regex(self): language_code = get_language() if language_code not in self._regex_dict: regex_compiled = re.compile('^%s/' % language_code, re.UNICODE) self._regex_dict[language_code] = regex_compiled return self._regex_dict[language_code] def resolve(path, urlconf=None): if urlconf is None: urlconf = get_urlconf() return get_resolver(urlconf).resolve(path) def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None): if urlconf is None: urlconf = get_urlconf() resolver = get_resolver(urlconf) args = args or [] kwargs = kwargs or {} prefix = get_script_prefix() if not isinstance(viewname, six.string_types): view = viewname else: parts = viewname.split(':') parts.reverse() view = parts[0] path = parts[1:] if current_app: current_path = current_app.split(':') current_path.reverse() else: current_path = None resolved_path = [] ns_pattern = '' while path: ns = path.pop() current_ns = current_path.pop() if current_path else None # Lookup the name to see if it could be an app identifier try: app_list = resolver.app_dict[ns] # Yes! Path part matches an app in the current Resolver if current_ns and current_ns in app_list: # If we are reversing for a particular app, # use that namespace ns = current_ns elif ns not in app_list: # The name isn't shared by one of the instances # (i.e., the default) so just pick the first instance # as the default. ns = app_list[0] except KeyError: pass if ns != current_ns: current_path = None try: extra, resolver = resolver.namespace_dict[ns] resolved_path.append(ns) ns_pattern = ns_pattern + extra except KeyError as key: if resolved_path: raise NoReverseMatch( "%s is not a registered namespace inside '%s'" % (key, ':'.join(resolved_path))) else: raise NoReverseMatch("%s is not a registered namespace" % key) if ns_pattern: resolver = get_ns_resolver(ns_pattern, resolver) return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))) reverse_lazy = lazy(reverse, six.text_type) def clear_url_caches(): get_callable.cache_clear() get_resolver.cache_clear() get_ns_resolver.cache_clear() def set_script_prefix(prefix): """ Sets the script prefix for the current thread. """ if not prefix.endswith('/'): prefix += '/' _prefixes.value = prefix def get_script_prefix(): """ Returns the currently active script prefix. Useful for client code that wishes to construct their own URLs manually (although accessing the request instance is normally going to be a lot cleaner). """ return getattr(_prefixes, "value", '/') def clear_script_prefix(): """ Unsets the script prefix for the current thread. """ try: del _prefixes.value except AttributeError: pass def set_urlconf(urlconf_name): """ Sets the URLconf for the current thread (overriding the default one in settings). Set to None to revert back to the default. """ if urlconf_name: _urlconfs.value = urlconf_name else: if hasattr(_urlconfs, "value"): del _urlconfs.value def get_urlconf(default=None): """ Returns the root URLconf to use for the current thread if it has been changed from the default one. """ return getattr(_urlconfs, "value", default) def is_valid_path(path, urlconf=None): """ Returns True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding unnecessarily indented try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False def translate_url(url, lang_code): """ Given a URL (absolute or relative), try to get its translated version in the `lang_code` language (either by i18n_patterns or by translated regex). Return the original URL if no translated version is found. """ parsed = urlsplit(url) try: match = resolve(parsed.path) except Resolver404: pass else: to_be_reversed = "%s:%s" % (match.namespace, match.url_name) if match.namespace else match.url_name with override(lang_code): try: url = reverse(to_be_reversed, args=match.args, kwargs=match.kwargs) except NoReverseMatch: pass else: url = urlunsplit((parsed.scheme, parsed.netloc, url, parsed.query, parsed.fragment)) return url<|fim▁end|>
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) return patterns def resolve_error_handler(self, view_type):
<|file_name|>RegisterModal.js<|end_file_name|><|fim▁begin|>import React from 'react'; import xhttp from 'xhttp'; import {Modal, Button, Input, Alert} from 'react-bootstrap'; import ee from './../Emitter.js'; import ModalComponent from '../components/ModalComponent.js' import RegistrationForm from './../forms/RegistrationForm.js' export default class RegisterModal extends ModalComponent { constructor(props) { super(props) ee.addListener('route:/register', this.open.bind(this)); } componentDidUpdate() { if (this.refs.registrationForm) this.refs.registrationForm.ee.removeAllListeners('success') .addListener('success', this.handleRegistrationSuccess.bind(this)); } handleRegistrationSuccess(data) { if (data && data.request_received) ee.emit('alert', {<|fim▁hole|> ee.emit('update_app_data', data); this.close(); } open(props) { if (this.props.user.username) return window.history.pushState({}, '', '/'); super.open(props) } submit() { this.refs.registrationForm.submit(); } render() { return ( <Modal show={this.state.show} onHide={this.close.bind(this)}> <Modal.Header closeButton> <Modal.Title>Register</Modal.Title> </Modal.Header> <Modal.Body> <RegistrationForm ref='registrationForm' /> <hr/> <div className='text-center'> Already registered? Login <a href='/login'>here</a>. </div> </Modal.Body> <Modal.Footer> <Button onClick={this.close.bind(this)}>Close</Button> <Button onClick={this.submit.bind(this)}>Submit</Button> </Modal.Footer> </Modal> ) } }<|fim▁end|>
msg: 'Registration request received. You will receive an email when an admin approves your request.', style: 'success' }) else
<|file_name|>driver_mocks.go<|end_file_name|><|fim▁begin|>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file 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. // Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/amazon-vpc-cni-k8s/plugins/routed-eni/driver (interfaces: NetworkAPIs) // Package mock_driver is a generated GoMock package. package mock_driver import ( net "net" reflect "reflect" gomock "github.com/golang/mock/gomock"<|fim▁hole|>// MockNetworkAPIs is a mock of NetworkAPIs interface type MockNetworkAPIs struct { ctrl *gomock.Controller recorder *MockNetworkAPIsMockRecorder } // MockNetworkAPIsMockRecorder is the mock recorder for MockNetworkAPIs type MockNetworkAPIsMockRecorder struct { mock *MockNetworkAPIs } // NewMockNetworkAPIs creates a new mock instance func NewMockNetworkAPIs(ctrl *gomock.Controller) *MockNetworkAPIs { mock := &MockNetworkAPIs{ctrl: ctrl} mock.recorder = &MockNetworkAPIsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockNetworkAPIs) EXPECT() *MockNetworkAPIsMockRecorder { return m.recorder } // SetupNS mocks base method func (m *MockNetworkAPIs) SetupNS(arg0, arg1, arg2 string, arg3 *net.IPNet, arg4 int, arg5 []string, arg6 bool) error { ret := m.ctrl.Call(m, "SetupNS", arg0, arg1, arg2, arg3, arg4, arg5, arg6) ret0, _ := ret[0].(error) return ret0 } // SetupNS indicates an expected call of SetupNS func (mr *MockNetworkAPIsMockRecorder) SetupNS(arg0, arg1, arg2, arg3, arg4, arg5, arg6 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetupNS", reflect.TypeOf((*MockNetworkAPIs)(nil).SetupNS), arg0, arg1, arg2, arg3, arg4, arg5, arg6) } // TeardownNS mocks base method func (m *MockNetworkAPIs) TeardownNS(arg0 *net.IPNet, arg1 int) error { ret := m.ctrl.Call(m, "TeardownNS", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // TeardownNS indicates an expected call of TeardownNS func (mr *MockNetworkAPIsMockRecorder) TeardownNS(arg0, arg1 interface{}) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TeardownNS", reflect.TypeOf((*MockNetworkAPIs)(nil).TeardownNS), arg0, arg1) }<|fim▁end|>
)
<|file_name|>reaction.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- ############################################################################### # Module to define chemical reaction functionality ############################################################################### from math import exp, log import sqlite3 from numpy import polyval from scipy.optimize import fsolve from PyQt4.QtGui import QApplication from lib import unidades from lib.sql import databank_name class Reaction(object): """Chemical reaction object""" status = 0 msg = QApplication.translate("pychemqt", "undefined") error = 0 kwargs = {"comp": [], "coef": [], "tipo": 0, "fase": 0, "key": 0, "base": 0, "customHr": False, "Hr": 0.0, "formula": False, "conversion": None, "keq": None} kwargsValue = ("Hr",) kwargsList = ("tipo", "fase", "key", "base") kwargsCheck = ("customHr", "formula") calculateValue = ("DeltaP", "DeltaP_f", "DeltaP_ac", "DeltaP_h", "DeltaP_v", "DeltaP_100ft", "V", "f", "Re", "Tout") TEXT_TYPE = [QApplication.translate("pychemqt", "Estequiometric"), QApplication.translate("pychemqt", "Equilibrium"), QApplication.translate("pychemqt", "Kinetic"), QApplication.translate("pychemqt", "Catalitic")] TEXT_PHASE = [QApplication.translate("pychemqt", "Global"), QApplication.translate("pychemqt", "Liquid"), QApplication.translate("pychemqt", "Gas")] TEXT_BASE = [QApplication.translate("pychemqt", "Mole"), QApplication.translate("pychemqt", "Mass"), QApplication.translate("pychemqt", "Partial pressure")] def __init__(self, **kwargs): """constructor, kwargs keys can be: comp: array with index of reaction components coef: array with stequiometric coefficient for each component fase: Phase where reaction work 0 - Global 1 - Liquid 2 - Gas key: Index of key component base 0 - Mol 1 - Mass 2 - Partial pressure Hr: Heat of reaction, calculate from heat of formation if no input formula: boolean to show compound names in formules tipo: Kind of reaction 0 - Stequiometric, without equilibrium or kinetic calculations 1 - Equilibrium, without kinetic calculation 2 - Equilibrium by minimization of Gibbs free energy 3 - Kinetic 4 - Catalytic conversion: conversion value for reaction with tipo=0 keq: equilibrium constant for reation with tipo=1 -it is float if it don't depend with temperature -it is array if it depends with temperature """ self.kwargs = Reaction.kwargs.copy() if kwargs: self.__call__(**kwargs) def __call__(self, **kwargs): oldkwargs = self.kwargs.copy() self.kwargs.update(kwargs) if oldkwargs != self.kwargs and self.isCalculable: self.calculo() @property def isCalculable(self): self.msg = "" self.status = 1 if not self.kwargs["comp"]: self.msg = QApplication.translate("pychemqt", "undefined components") self.status = 0 return if not self.kwargs["coef"]: self.msg = QApplication.translate("pychemqt", "undefined stequiometric") self.status = 0 return if self.kwargs["tipo"] == 0: if self.kwargs["conversion"] is None: self.msg = QApplication.translate("pychemqt", "undefined conversion") self.status = 3 elif self.kwargs["tipo"] == 1: if self.kwargs["keq"] is None: self.msg = QApplication.translate("pychemqt", "undefined equilibrium constants") self.status = 3 elif self.kwargs["tipo"] == 2: pass elif self.kwargs["tipo"] == 3: pass return True def calculo(self): self.componentes = self.kwargs["comp"] self.coef = self.kwargs["coef"] self.tipo = self.kwargs["tipo"] self.base = self.kwargs["base"] self.fase = self.kwargs["fase"] self.calor = self.kwargs["Hr"] self.formulas = self.kwargs["formula"] self.keq = self.kwargs["keq"] databank = sqlite3.connect(databank_name).cursor() databank.execute("select nombre, peso_molecular, formula, \ calor_formacion_gas from compuestos where id IN \ %s" % str(tuple(self.componentes))) nombre = [] peso_molecular = [] formula = [] calor_reaccion = 0 check_estequiometria = 0 for i, compuesto in enumerate(databank): nombre.append(compuesto[0]) peso_molecular.append(compuesto[1]) formula.append(compuesto[2]) calor_reaccion += compuesto[3]*self.coef[i]<|fim▁hole|> self.formula = formula if self.calor: self.Hr = self.kwargs.get("Hr", 0) else: self.Hr = unidades.MolarEnthalpy(calor_reaccion/abs( self.coef[self.base]), "Jkmol") self.error = round(check_estequiometria, 1) self.state = self.error == 0 self.text = self._txt(self.formulas) def conversion(self, corriente, T): """Calculate reaction conversion corriente: Corriente instance for reaction T: Temperature of reaction""" if self.tipo == 0: # Material balance without equilibrium or kinetics considerations alfa = self.kwargs["conversion"] elif self.tipo == 1: # Chemical equilibrium without kinetics if isinstance(self.keq, list): A, B, C, D, E, F, G, H = self.keq keq = exp(A+B/T+C*log(T)+D*T+E*T**2+F*T**3+G*T**4+H*T**5) else: keq = self.keq def f(alfa): conc_out = [ (corriente.caudalunitariomolar[i]+alfa*self.coef[i]) / corriente.Q.m3h for i in range(len(self.componentes))] productorio = 1 for i in range(len(self.componentes)): productorio *= conc_out[i]**self.coef[i] return keq-productorio alfa = fsolve(f, 0.5) print alfa, f(alfa) avance = alfa*self.coef[self.base]*corriente.caudalunitariomolar[self.base] Q_out = [corriente.caudalunitariomolar[i]+avance*self.coef[i] / self.coef[self.base] for i in range(len(self.componentes))] minimo = min(Q_out) if minimo < 0: # The key component is not correct, redo the result indice = Q_out.index(minimo) avance = self.coef[indice]*corriente.caudalunitariomolar[indice] Q_out = [corriente.caudalunitariomolar[i]+avance*self.coef[i] / self.coef[indice] for i in range(len(self.componentes))] h = unidades.Power(self.Hr*self.coef[self.base] / self.coef[indice]*avance, "Jh") else: h = unidades.Power(self.Hr*avance, "Jh") print alfa, avance caudal = sum(Q_out) fraccion = [caudal_i/caudal for caudal_i in Q_out] return fraccion, h # def cinetica(self, tipo, Ko, Ei): # """Método que define la velocidad de reacción""" # # def _txt(self, nombre=False): """Function to get text representation for reaction""" if nombre: txt = self.nombre else: txt = self.formula reactivos = [] productos = [] for i in range(len(self.componentes)): if self.coef[i] == int(self.coef[i]): self.coef[i] = int(self.coef[i]) if self.coef[i] < -1: reactivos.append(str(-self.coef[i])+txt[i]) elif self.coef[i] == -1: reactivos.append(txt[i]) elif -1 < self.coef[i] < 0: reactivos.append(str(-self.coef[i])+txt[i]) elif 0 < self.coef[i] < 1: productos.append(str(self.coef[i])+txt[i]) elif self.coef[i] == 1: productos.append(txt[i]) elif self.coef[i] > 1: productos.append(str(self.coef[i])+txt[i]) return " + ".join(reactivos)+" ---> "+" + ".join(productos) def __repr__(self): if self.status: eq = self._txt() return eq + " " + "Hr= %0.4e Jkmol" % self.Hr else: return str(self.msg) if __name__ == "__main__": # from lib.corriente import Corriente, Mezcla # mezcla=Corriente(300, 1, 1000, Mezcla([1, 46, 47, 62], [0.03, 0.01, 0.96, 0])) # reaccion=Reaction([1, 46, 47, 62], [-2, 0, -1, 2], base=2) # reaccion.conversion(mezcla) # print reaccion reaccion = Reaction(comp=[1, 47, 62], coef=[-2, -1, 2]) print reaccion<|fim▁end|>
check_estequiometria += self.coef[i]*compuesto[1] self.nombre = nombre self.peso_molecular = peso_molecular