repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
ONSdigital/eq-survey-runner | gulp/favicons.js | 163 | import gulp from 'gulp'
import {paths} from './paths'
export function favicons() {
gulp.src(paths.favicons.input)
.pipe(gulp.dest(paths.favicons.output))
}
| mit |
lexmihaylov/burjs | bur.js | 42128 |
/**
* Project bur
* @version 1.3.0
* @author Alexander Mihaylov (lex.mihaylov@gmail.com)
* @license http://opensource.org/licenses/MIT MIT License (MIT)
*
* @Copyright (C) 2013 by Alexander Mihaylov
*
* 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.
*/
(function(root, factory) {
if(typeof(define) === 'function' && define.amd) {
define(['jquery'], factory);
} else if(typeof(root) === 'object' && typeof(root.document) === 'object') {
// check if jquery dependency is met
if (typeof (root.$) !== 'function' ||
typeof (root.$.fn) !== 'object' ||
!root.$.fn.jquery) {
throw new Error("bur.js dependency missing: jQuery");
}
root.bur = factory(root.$);
}
})(this, function($) {
/**
* A library for creating an MVC onepage web applications.
* The library is built for use with jquery and depends on requirejs
* @namespace bur
*/
var bur = {
/**
* @var {string} VERSION library version
*/
VERSION: '0.1.0',
/**
* @var {object} window The javasript window object
* with extended functionality
*/
window: null,
/**
* @var {object} dom The javasript <HTML> object
* with extended functionality
*/
dom: null,
/**
* Checks if the library needs to initialize
* @type Boolean
*/
_isInitialized: false,
/**
* Libaray configurations
*/
_Config: {
/**
* Application directory (ex: js/app/)
*/
appDir: 'js/app/',
/**
* View directory
*/
viewDir: 'js/app/views/',
/**
* Model directory
*/
modelDir: 'js/app/models/',
/**
* Section directory
*/
sectionDir: 'js/app/sections/',
/**
* Template directory
*/
templateDir: 'js/app/templates/'
},
/**
* _set_config
* Setups the application paths
*/
_setAppDir: function(appDir) {
bur._Config.appDir = appDir;
for (var i in bur._Config) {
if (i !== 'appDir') {
bur._Config[i] = appDir + bur._Config[i];
}
}
},
/**
* Initializes the module
* @return {Object}
*/
_init: function() {
if(!bur._isInitialized) {
bur.window = $(window);
bur.dom = $('html');
bur.dom.body = $('body');
bur._isInitialized = true;
}
return bur;
},
/**
* Gives access to the libraries configuration variable
* @param {type} attr
* @param {type} value
* @returns {bur|Object|bur._Config}
*/
config: function(attr, value) {
if($.isPlainObject(attr)) {
if(attr.appDir) {
bur._setAppDir(attr.appDir);
}
bur._Config = $.extend(true, bur._Config, attr);
return bur;
} else if(typeof(attr) === 'string'){
if(!value) {
return bur._Config[attr];
} else {
if(attr === 'appDir') {
bur._setAppDir(value);
} else {
bur._Config[attr] = value;
}
return bur;
}
} else if(!attr) {
return bur._Config;
} else {
return null;
}
}
};
/**
* Class
* Creates a class by passing in a class definition as a javascript object
* @param {Object} definition the class definition object
* @return {function} the newly created class
*/
bur.Class = function(definition) {
// load class helper functions
// define simple constructor
var classDefinition = function() {};
classDefinition.prototype._construct = classDefinition;
if (definition) {
// set construnctor if it exists in definition
if (definition._construct) {
classDefinition.prototype._construct =
classDefinition =
definition._construct;
}
// extend a class if it's set in the definition
if (definition.extends) {
bur.Class._inherits(classDefinition, definition.extends);
// variable to use in the closure
var superClass = definition.extends;
/**
* Provides easy access to the parent class' prototype
*
* @static
* @return {mixed} result of the execution if there is any
*/
classDefinition._super = function(context, method, argv) {
var result;
if(!context) {
throw new Error('Undefined context.');
}
var _this = context;
if(!argv) {
argv = [];
}
if(method) {
if(method instanceof Array) {
argv = method;
method = undefined;
} else if(typeof(method) !== 'string') {
throw new Error('Expected string for method value, but ' + typeof(method) + ' given.');
}
}
if (method) {
// execute a method from the parent prototype
if(superClass.prototype[method] &&
typeof(superClass.prototype[method]) === 'function') {
result = superClass.prototype[method].apply(_this, argv);
} else {
throw new Error("Parent class does not have a method named '" + method + "'.");
}
} else {
// if no method is set, then we execute the parent constructor
result = superClass.apply(_this, argv);
}
return result;
};
}
// implement a object of method and properties
if (definition.implements) {
if (definition.implements instanceof Array) {
var i;
for (i = 0; i < definition.implements.length; i++) {
bur.Class._extendPrototypeOf(classDefinition, definition.implements[i]);
}
} else if (typeof definition.imlements === 'object') {
bur.Class._extendPrototypeOf(classDefinition, definition.implements);
} else {
throw new Error("error implementing object methods");
}
}
// set the prototype object of the class
if (definition.prototype) {
bur.Class._extendPrototypeOf(classDefinition, definition.prototype);
}
if (definition.static) {
for (i in definition.static) {
classDefinition[i] = definition.static[i];
}
}
}
/**
* Provides easy access to the current class' static methods
*
* @return {function} the class' constructor
*/
classDefinition.prototype._self = function() {
return classDefinition;
};
// return the new class
return classDefinition;
};
/**
* <p>Creates a new class and inherits a parent class</p>
* <p><b>Note: when calling a super function use: [ParentClass].prototype.[method].call(this, arguments)</b></p>
*
* @param {object} childClass the class that will inherit the parent class
* @param {object} baseClass the class that this class will inherit
* @private
* @static
*/
bur.Class._inherits = function(childClass, baseClass) {
// inherit parent's methods
var std_class = function() {
};
std_class.prototype = baseClass.prototype;
childClass.prototype = new std_class();
// set the constructor
childClass.prototype._construct =
childClass.prototype.constructor =
childClass;
// return the new class
return childClass;
};
/**
* Copies methods from an object to the class prototype
*
* @param {object} childClass the class that will inherit the methods
* @param {object} methods the object that contains the methods
* @private
* @static
*/
bur.Class._extendPrototypeOf = function(childClass, methods) {
for (var i in methods) {
childClass.prototype[i] = methods[i];
}
return childClass;
};
/**
* Holds utility classes and methods
* @namespace util
*/
bur.util = {};
/**
* Holds functions that help you managa cookies
* @class cookie
* @static
*/
bur.util.cookie = {};
/**
* Create a cookie on the clients browser
*
* @param {String} name
* @param {String} value
* @param {Object} opt
* opt.expires Expiration time in seconds
* opt.path Default value is /
* opt.domain If domain is not set then the current domain
* will be set to cookie
*/
bur.util.cookie.set = function(name, value, opt) {
value = escape(value);
if (!opt)
opt = {};
if (opt.expires) {
var date = new Date();
date.setTime(date.getTime() + parseInt(opt.expires * 1000));
value = value + ';expires=' + date.toGMTString();
}
if (opt.path) {
value = value + ';path=' + opt.path;
} else {
value = value + ';path=/';
}
if (opt.domain) {
value = value + ';domain=' + opt.domain;
}
document.cookie = name + "=" + value + ";";
};
/**
* Retrieve a cookie's value
*
* @param {string} name
*/
bur.util.cookie.get = function(name) {
var expr = new RegExp(name + '=(.*?)(;|$)', 'g');
var matches = expr.exec(document.cookie);
if (!matches || !matches[1]) {
return null;
}
return matches[1];
};
/**
* Deletes cookie
*
* @param {string} name
* @return {mixed} the value of the cookie or null if the cookie does not exist
*/
bur.util.cookie.destroy = function(name) {
bur.util.cookie.set(name, null, {expires: -1});
};
/**
* creates a task that is appended to the event queue
* @class AsyncTask
* @param {function} task the task that will be executed async
* @param {int} timeout delay before task execution
*/
bur.util.AsyncTask = bur.Class({
_construct: function(task, timeout) {
if (task && typeof task === 'function') {
this._task = task;
this._taskID = null;
this._timeout = timeout || 0;
this._onStart = null;
this._onFinish = null;
} else {
throw "Task has to be a function, but '" + typeof (task) + "' given.";
}
}
});
/**
* Adds a callback that will be executed before the task starts
*
* @param {function} fn callback
*/
bur.util.AsyncTask.prototype.onStart = function(fn) {
this._onStart = fn;
return this;
};
/**
* Adds a callback that will be executed when the task finishes
*
* @param {function} fn callback
*/
bur.util.AsyncTask.prototype.onFinish = function(fn) {
this._onFinish = fn;
return this;
};
/**
* starts the task execution
*
*/
bur.util.AsyncTask.prototype.start = function() {
var _this = this;
this._taskID = window.setTimeout(function() {
if (typeof _this._onStart === 'function') {
_this._onStart();
}
var data = _this._task();
_this._taskID = null;
if (typeof _this._onFinish === 'function') {
_this._onFinish(data);
}
}, this._timeout);
return this;
};
/**
* Kills a async task before it has been executed
*/
bur.util.AsyncTask.prototype.kill = function() {
if(this._taskID !== null) {
window.clearTimeout(this._taskID);
}
return this;
};
/**
* Handles collection of objects
* @class Collection
* @param {mixed} args.. elements of the arrays
*/
bur.util.Collection = bur.Class({
extends: Array,
_construct: function() {
bur.util.Collection._super(this);
var argv = this.splice.call(arguments, 0);
for (var i = 0; i < argv.length; i++) {
this.push(argv[i]);
}
}
});
/**
* Iterates through the collection. To break from the loop, use 'return false'
*
* @param {function} fn callback
*/
bur.util.Collection.prototype.each = function(fn) {
for (var i = 0; i < this.length; i++) {
var result = fn(this[i], i);
if (result === false) {
break;
}
}
};
/**
* Checks if the collection has an element with a given index
* @param {type} index
* @returns {Boolean}
*/
bur.util.Collection.prototype.has = function(index) {
return index in this;
};
/**
* Checks if the collecion contains a value
* @param {type} value
* @returns {Boolean}
*/
bur.util.Collection.prototype.contains = function(value) {
return (this.indexOf(value) !== -1);
};
/**
* Removes an item from the collection
*
* @param {int} index item index
*/
bur.util.Collection.prototype.remove = function(index) {
this.splice(index, 1);
};
/**
* Extends the collection with elements from another array
*
* @param {Array|Collection} array secondary array
*/
bur.util.Collection.prototype.extend = function(array) {
if (array instanceof Array) {
for (var i = 0; i < array.length; i++) {
this.push(array[i]);
}
} else {
throw "extend requires an array, but " + typeof (object) + "was given.";
}
return this;
};
/**
* converts the collection to a json string
*
* @return {string}
*/
bur.util.Collection.prototype.toJson = function() {
return JSON.stringify(this);
};
/**
* Handles a HashMap with strings as keys and objects as values
* @class HashMap
* @param {object} map an initial hash map
*/
bur.util.HashMap = bur.Class({
_construct: function(map) {
this._map = {};
if (map) {
if(!$.isPlainObject(map)) {
throw new Error('map has to be a javascript object');
}
for (var i in map) {
if (map.hasOwnProperty(i)) {
this._map[i] = map[i];
}
}
}
}
});
/**
* checks if the hash map contains an element with a given key
* @param {string} key
* @return {boolean}
*/
bur.util.HashMap.prototype.has = function(key) {
return key in this._map;
};
/**
* Iterates through the hash map. To break from the look use 'return false;' inside the callback.
*
* @param {function} fn callback
*/
bur.util.HashMap.prototype.each = function(fn) {
for (var i in this._map) {
if (this._map.hasOwnProperty(i)) {
var result = fn(this._map[i], i);
if (result === false) {
break;
}
}
}
return this;
};
/**
* Adds an element to the hash map
*
* @param {string} key
* @param {string} value
*/
bur.util.HashMap.prototype.add = function(key, value) {
this._map[key] = value;
return this;
};
/**
* Get an item by key
* @param {type} key
* @returns {mixed}
*/
bur.util.HashMap.prototype.get = function(key) {
return this._map[key];
};
/**
* finds the key of a value
*
* @param {mixed} val
* @return {string}
*/
bur.util.HashMap.prototype.keyOf = function(val) {
var retKey = null;
this.each(function(value, key) {
if (value === val) {
retKey = key;
return false;
}
});
return retKey;
};
/**
* Checks if the hash map contains a given value
* @param {type} value
* @returns {Boolean}
*/
bur.util.HashMap.prototype.contains = function(value) {
return (this.keyOf(value) !== null);
};
/**
* Removes an element from the hash map
* @param {string} key
*/
bur.util.HashMap.prototype.remove = function(key) {
delete(this._map[key]);
return this;
};
/**
* Extends the hashmap
*
* @param {object|HashMap} object
*/
bur.util.HashMap.prototype.extend = function(object) {
if ($.isPlainObject(object)) {
for (var i in object) {
if (object.hasOwnProperty(i)) {
this._map[i] = object[i];
}
}
} else {
throw new Error("extend requires an object, but " + typeof (object) + "was given.");
}
return this;
};
/**
* Returns the size of the hash map
* @returns {Number}
*/
bur.util.HashMap.prototype.size = function() {
var counter = 0;
for(var i in this._map) {
if(this._map.hasOwnProperty(i)) {
counter ++;
}
}
return counter;
};
/**
* Converts the hash map to a json string
*
* @return {string}
*/
bur.util.HashMap.prototype.toJson = function() {
return JSON.stringify(this._map);
};
bur.EventBus = bur.Class({
_construct: function () {
/**
* @property {HashMap<String, Array>} _events holds the event callbacks
*/
this._events = new bur.util.HashMap();
}
});
bur.EventBus.prototype._normalizeTypes = function (types) {
if (typeof (types) === 'string') {
if (types.indexOf(',') === -1) {
types = [types];
} else {
types = $.map(types.split(','), $.trim);
}
} else if (!(types instanceof Array)) {
throw new Error("'types' can be a String or Array.");
}
return types;
};
/**
* Adds an event to the event map of the object
* @param {Array|String} types the event'(s) name(s)
* @param {function} callback the callback function
* @param {boolean} one execute the handler once
* @return {bur.EventBus}
*/
bur.EventBus.prototype.on = function (types, callback, /* INTENAL */ one) {
types = this._normalizeTypes(types);
for (var i = 0; i < types.length; ++i) {
var type = types[i];
if (!this._events.has(type)) {
this._events.add(type, new bur.util.Collection);
}
if (one === true) {
var fn = callback;
var _this = this;
callback = function () {
_this.off(type, callback);
fn.apply(this, arguments);
};
}
if (this._events.get(type).indexOf(callback) === -1) {
this._events.get(type).push(callback);
}
}
return this;
};
/**
* Adds an event handler that will be executed once
* @param {type} types
* @param {type} callback
* @return {bur.EventBus}
*/
bur.EventBus.prototype.one = function (types, callback) {
return this.on(types, callback, true);
};
/**
* Unbind an event handler
* @param {type} types handler type(s)
* @param {type} callback handler callback
* @return {bur.EventBus}
*/
bur.EventBus.prototype.off = function (types, callback) {
types = this._normalizeTypes(types);
for (var i = 0; i < types.length; ++i) {
var type = types[i];
if (this._events.has(type)) {
var index = this._events.get(type).indexOf(callback);
if (index !== -1) {
this._events.get(type).remove(index);
}
}
}
return this;
};
/**
* triggers an event from the object's event map
*
* @param {string} type the event name
* @patam {data} data object to be passed to the handler
* @return {bur.EventBus}
*/
bur.EventBus.prototype.trigger = function (type, data) {
if (this._events.has(type)) {
var _this = this;
var event = {
type: type,
timeStamp: Date.now(),
target: this
};
this._events.get(type).each(function (item) {
if (typeof item === 'function') {
item.call(_this, event, data);
}
});
}
return this;
};
/**
* An alias for trigger method
* @param {type} type
* @param {type} data
* @returns {bur.EventBus}
*/
bur.EventBus.prototype.triggerHandler = function (type, data) {
return this.trigger(type, data);
};/**
* Creates a global event bus for communication between different components
* @var {bur.EventBus}
* @namespace bur
*/
bur.Antenna = new bur.EventBus();/**
* Provides functionality for creating UI components
* @class Component
* @param {string} tag tag type as a string (ex: '<div/>')
*/
bur.Component = bur.Class({
extends: $,
_construct: function(object) {
// set a default object
if (!object) {
object = '<div/>';
}
this.constructor = $; // jquery uses it's constructor internaly in some methods
this.init(object); // init the object
}
});
/**
* Get the computed value of a css property
* @param {string} property a css property
* @return {mixed} the computed value of the property
*/
bur.Component.prototype.computedStyle = function(property) {
return window
.getComputedStyle(this.get(0)).getPropertyValue(property);
};
/**
* Get the computed width
* @return {string} computed width
*/
bur.Component.prototype.computedWidth = function() {
return parseFloat(this.computedStyle('width'));
};
/**
* Get the computed height
* @return {string}
*/
bur.Component.prototype.computedHeight = function() {
return parseFloat(this.computedStyle('height'));
};
/*
* We need to override some of the default jQuery methods, so we can be able to
* detect dom incertion
*/
(function() {
var parentMethods = {
// inset inside methods
/*
* append
* appendTo
* html
*/
append: $.fn.append,
/*
* prepend
* prependTo
*/
prepend: $.fn.prepend,
// insert outside methods
/*
* after
* insertAfter
*/
after: $.fn.after,
/*
* before
* insertBefore
*/
before: $.fn.before
};
/**
* Triggers an event if item is a jquery object
* @param {type} item
* @return {undefined}
*/
var onAfterInsert = function(item) {
if (item.triggerHandler) {
if (item.closest('body').length > 0) {
item.triggerHandler('dom:insert');
item.find('*').each(function() {
$(this).triggerHandler('dom:insert');
});
}
}
};
/**
* modifys a dom insertion method
* @param {type} method
* @return {unresolved}
*/
var domEventsModifyer = function(method) {
return function() {
var args = Array.prototype.splice.call(arguments, 0),
result = undefined,
i = 0;
result = parentMethods[method].apply(this, args);
for (i = 0; i < args.length; i++) {
onAfterInsert(args[i]);
}
return result;
};
};
$.fn.append = domEventsModifyer('append');
$.fn.prepend = domEventsModifyer('prepend');
$.fn.after = domEventsModifyer('after');
$.fn.before = domEventsModifyer('before');
})();
/*
* Override $.cleanData method so we can handle external listener map
* and we can emit a dom:destroy event on the objects being removed form the dom
*/
(function() {
/**
* A list of event associations
* @class EventAssocList
* @returns {EventAssocList}
*/
var EventAssocList = function() {
this.list = [];
};
EventAssocList.prototype = {
/**
* Add an event association to the list and bind the event
* @param {type} object
* @param {type} type
* @param {type} fn
* @returns {EventAssocList}
*/
add: function(object, type, fn) {
if (object.length !== undefined) {
for (var i = 0; i < object.length; i++) {
this.add(object[i], type, fn);
}
return this;
}
if (this.key(object, type, fn) === -1) {
this.list.push({
object: object,
type: type,
handler: fn
});
}
if (!object.on) {
object = $(object);
}
object.on(type, fn);
return this;
},
/**
* Get an item by index
* @param {number} index
* @returns {Array}
*/
get: function(index) {
return this.list[index];
},
/**
* Find a element from the list
* @param {type} object
* @param {type} type
* @param {type} fn
* @param {type} selector
* @returns {object}
*/
find: function(object, type, fn) {
var index = this.key(object, type, fn);
return this.get(index);
},
/**
* Get the index of an object in the list
* @param {type} object
* @param {type} type
* @param {type} fn
* @param {type} selector
* @returns {Number}
*/
key: function(object, type, fn) {
var i = 0;
for (; i < this.length(); i++) {
var item = this.list[i];
if (item.object === object &&
item.type === type &&
item.handler === fn) {
return i;
}
}
return -1;
},
/**
* Get the number of items in the list
* @returns {number}
*/
length: function() {
return this.list.length;
},
/**
* Deletes an item associated with an index, and unbinds the
* corresponding event
* @param {type} index
* @returns {EventAssocList}
*/
removeItem: function(index) {
if (index !== -1) {
var event = this.get(index);
var object = event.object;
if (typeof(object.off) !== 'function') {
object = $(object);
}
object.off(event.type, event.handler);
this.list.splice(index, 1);
}
return this;
},
/**
* Remove all the items that match the input parameters
* @param {type} [object]
* @param {type} [type]
* @param {type} [fn]
* @param {type} [selector]
* @returns {EventAssocList}
*/
remove: function(object, type, fn) {
var i;
// .remove() - removes all items
if (!object) {
return this.removeAll();
}
if (object.length !== undefined) {
for (i = 0; i < object.length; i++) {
this.remove(object[i], type, fn);
}
}
var length = this.list.length;
// .remove(object) - removes all items that match the object
if (object && !type) {
for (i = length - 1; i >= 0; i--) {
if (this.list[i].object === object) {
this.removeItem(i);
}
}
return this;
}
// .remove(object, type) - removes all items that match the
// object and event type
if (object && type && !fn) {
for (i = length - 1; i >= 0; i--) {
if (this.list[i].object === object &&
this.list[i].type === type) {
this.removeItem(i);
}
}
return this;
}
// .remove(object, type, fn,[selector]) - removes the item that
// matches the input
return this.removeItem(this.key(object, type, fn));
},
/**
* Removes all the intems in the list and unbinds all of the
* corresponing events
* @returns {EventAssocList}
*/
removeAll: function() {
var i = this.list.length - 1;
for (; i >= 0; i--) {
this.removeItem(i);
}
return this;
}
};
/**
* Data structure that holds element ids and a list of external events
* @static
* @class EventAssocData
* @type {Object}
*/
var EventAssocData = {
/**
* @property {number} assocIndex autoincrementing value used as index for element
*/
assocIndex: 1,
/**
* @property {object} data data structure
*/
data: {},
/**
* @property {string} property element property name in wich the element index will be saved
*/
property: '__event_assoc_data__',
/**
* Checks if object is a valid
* @param {type} object
* @returns {Boolean}
*/
accepts: function(object) {
return object.nodeType ?
object.nodeType === 1 || object.nodeType === 9 : true;
},
/**
* Gets or creates a key and returns it
* @param {object} object
* @returns {Number}
*/
key: function(object) {
if (!EventAssocData.accepts(object)) {
return 0;
}
var key = object[EventAssocData.property];
if (!key) {
var descriptior = {};
key = EventAssocData.assocIndex;
try {
descriptior[EventAssocData.property] = {
value: key
};
Object.defineProperties(object, descriptior);
}
catch (e) {
descriptior[EventAssocData.property] = key;
$.extend(object, descriptior);
}
EventAssocData.assocIndex++;
}
if (!EventAssocData.data[key]) {
EventAssocData.data[key] = new EventAssocList();
}
return key;
},
/**
* checks if an element exists in the data structure
* @param {object} object
* @returns {Boolean}
*/
has: function(object) {
var key = object[EventAssocData.property];
if (key) {
return key in EventAssocData.data;
}
return false;
},
/**
* Get event associations corresponding to a given object
* @param {object} object
* @returns {object}
*/
get: function(object) {
var key = EventAssocData.key(object),
data = EventAssocData.data[key];
return data;
},
/**
* Removes an item from the data struct
* @param {object} object
* @returns {undefined}
*/
remove: function(object) {
if (!EventAssocData.has(object)) {
return;
}
var key = EventAssocData.key(object),
data = EventAssocData.data[key];
if (data) {
data.removeAll();
}
delete(EventAssocData.data[key]);
}
};
/**
* Class that gives fast access to the event association data structure
* @class EventAssoc
* @static
* @type {Object}
*/
var EventAssoc = {
/**
* Adds an item
* @param {type} owner
* @param {type} other
* @param {type} types
* @param {type} fn
* @param {type} selector
* @param {type} data
* @returns {undefined}
*/
add: function(owner, other, types, fn) {
var list = EventAssocData.get(owner);
if (list) {
list.add(other, types, fn);
}
},
/**
* Removes an item
* @param {type} owner
* @param {type} other
* @param {type} types
* @param {type} fn
* @param {type} selector
* @returns {undefined}
*/
remove: function(owner, other, types, fn) {
if (!EventAssocData.has(owner)) {
return;
}
var list = EventAssocData.get(owner);
if (list) {
list.remove(other, types, fn);
}
}
};
var returnFalse = function() {
return false;
};
/**
* Start listening to an external jquery object
* @param {jQuery} other
* @param {string|object} types
* @param {funcion} fn
* @returns {jQuery}
*/
$.fn.listenTo = function(other, types, fn) {
if (!other.on ||
!other.one ||
!other.off
) {
other = $(other);
}
if (fn === false) {
fn = returnFalse;
}
else if (!fn) {
return this;
}
return this.each(function() {
EventAssoc.add(this, other, types, fn);
});
};
/**
* Start listening to an external jquery object (ONCE)
* @param {jQuery} other
* @param {string|object} types
* @param {function} fn
* @returns {jQuery}
*/
$.fn.listenToOnce = function(other, types, fn) {
var _this = this;
callback = function(event) {
_this.stopListening(event);
return fn.apply(this, arguments);
};
return this.listenTo(other, types, callback);
};
/**
* Stop listening to an external jquery object
* @param {jQuery} [other]
* @param {string|object} [types]
* @param {function} [fn]
* @returns {jQuery}
*/
$.fn.stopListening = function(other, types, fn) {
if (other.target && other.handleObj) {
return this.each(function() {
EventAssoc.remove(this, other.target,
other.handleObj.type, other.handleObj.handler);
});
}
if (other && (!other.on ||
!other.one ||
!other.off
)) {
other = $(other);
}
if (fn === false) {
fn = returnFalse;
}
return this.each(function() {
EventAssoc.remove(this, other, types, fn);
});
};
/**
* Get all the event associations connected to the current jQuery object
* @returns {null|Array}
*/
$.fn.externalListeners = function() {
var data = [];
this.each(function() {
if (EventAssocData.has(this)) {
data.push(EventAssocData.get(this));
}
});
if (data.length > 0) {
return data;
}
return null;
};
// override cleanData method to clear existing event associations
// cleans all event associations
// unbinds all the external events
// this will be executed when you use remove() or empty()
var cleanData = $.cleanData;
$.cleanData = function(elems) {
var i = 0;
for (; i < elems.length; i++) {
if (elems[i] !== undefined) {
// emit a destroy event when an element is beening cleaned
// this event won't bubble up because we are using triggerHandler
$(elems[i]).triggerHandler('dom:destroy');
if (EventAssocData.has(elems[i])) {
EventAssocData.remove(elems[i]);
}
}
}
return cleanData(elems);
};
})();/**
* Application Model
* @class bur.Model
*/
bur.Model = bur.Class({
extends: bur.EventBus,
_construct: function() {
bur.ViewModel._super(this);
/**
* @property {Object} _data model data
* @private
*/
this._data = {};
}
});
/**
* Set a model data property
* @param {string} property property name
* @param {mixed} value property value
* @returns {bur.Model}
*/
bur.Model.prototype.set = function(property, value) {
if(typeof(property) === 'object') {
this._data = property;
this.trigger('change:*', property);
this.trigger('change', {property: null, value: property});
}
eval('this._data.' + property + ' = value;');
this.trigger('change:' + property, value);
this.trigger('change', {property: property, value: value});
return this;
};
/**
* Get property's value
* @param {string} property
* @returns {mixed}
*/
bur.Model.prototype.get = function(property) {
if(!property) {
// retuns a reference to the data object
return this._data;
}
return eval('this._data.' + property);
};/**
* Provides functionality for handling templates
* @class View
* @param {string} template the template filename without the extension
* @param {object} context optional context parameter
*
*/
bur.View = bur.Class({
_construct: function(template, context) {
this._template = template;
if(context) {
this._context = context;
} else {
this._context = this;
}
}
});
/**
* Creates an instance of View
*
* @static
* @param {String|Function} template template string or a compiled template function
* @param {Object} context(optional)
* @return {Component}
*/
bur.View.make = function(template, context) {
return new bur.View(template, context);
};
/**
* Compiles and renders the compiled template to html
*
* @param {object} variables variables to pass to the template
* @return {String}
*/
bur.View.prototype.render = function(variables) {
var template = null;
if(typeof(this._template) === 'function') {
template = this._template;
} else {
template = bur.View.Compile(this._template);
}
return template.call(this._context, variables);
};
/**
* Returns compiled template for caching
*
* @param {object} variables variables to pass to the template
* @return {String}
*/
bur.View.prototype.compile = function(variables) {
var template = null;
if(typeof(this._template) === 'function') {
template = this._template;
} else {
template = bur.View.Compile(this._template);
}
return template;
};
/**
* Tmplate regular expression settings
* @var {Object}
*/
bur.View.settings = {
interpolate: /<%=([\s\S]+?)%>/g,
escape: /<%-([\s\S]+?)%>/g,
evaluate: /<%([\s\S]+?)%>/g
};
/**
* Template special chars escape map
* @var {Object}
*/
bur.View.escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
/**
* Template special char regualt expression
* @var {RegExp}
*/
bur.View.escaper = /\\|'|\r|\n|\u2028|\i2028/g;
/**
* Html entities map used for escaping html
* @var {Object}
*/
bur.View.htmlEntities = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
}
/**
* Escapes an html string using the html entity map
* @param {String}
* @return {String}
* @static
*/
bur.View.escapeHtml = function(html) {
return String(html).replace(/[&<>"'\/]/g, function (entity) {
return bur.View.htmlEntities[entity];
});
};
/**
* Compiles a template to javascript code
* Note: this is an adaptation of underscore's template system
*
* @static
* @param {string} html The template code
* @return {function} compiled template
*/
bur.View.Compile = function(template) {
var matcher = new RegExp([
(bur.View.settings.interpolate).source,
(bur.View.settings.escape).source,
(bur.View.settings.evaluate).source
].join('|') + '|$', 'g');
var source = '',
index = 0;
template.replace(matcher, function(match, interpolate, escape, evaluate, offset) {
source += template.slice(index, offset).replace(bur.View.escaper, function(match) {
return '\\' +bur.View.escapes[match];
});
index = offset + match.length;
if(interpolate) {
source += "'+((__v=" + interpolate + ")==null?'':__v)+'";
} else if(escape) {
source += "'+((__v=" + escape + ")==null?'':bur.View.escapeHtml(__v))+'";
} else if(evaluate) {
source += "'; " + evaluate + " __s+='";
}
return match;
});
var source = "var __v,__s=''; with(obj||{}){ __s+='" + source + "'; }; return __s;";
try {
render = new Function('obj, bur', source);
} catch (e) {
e.source = source;
throw e;
}
return function(vars) {
return render.call(this, vars, bur);
};
};
return bur._init();
});
| mit |
rayaman/multi | multi/integration/networkManager/nodeManager.lua | 2016 | --[[
MIT License
Copyright (c) 2020 Ryan Ward
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, sub-license, 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.
]]
local multi, thread = require("multi"):init()
local cmd = require("multi.integration.networkManager.cmds")
local net = require("net")
local bin = require("bin")
local nodes = { -- Testing stuff
}
function multi:newNodeManager(port)
print("Running node manager on port: "..(port or cmd.defaultManagerPort))
local server = net:newTCPServer(port or cmd.defaultManagerPort)
server.OnDataRecieved(function(serv, data, client)
local cmd = data:match("!(.+)!")
data = data:gsub("!"..cmd.."!","")
if cmd == "NODES" then
for i,v in ipairs(nodes) do
-- Sample data
serv:send(client, "!NODE!".. v[1].."|"..v[2].."|"..v[3])
end
elseif cmd == "REG_NODE" then
local name, ip, port = data:match("(.-)|(.-)|(.+)")
table.insert(nodes,{name,ip,port})
print("Registering Node:",name, ip, port)
end
end)
end | mit |
fstoerkle/leaflet-custom-paths | lib/leaflet/0.4/src/map/ext/Map.Geolocation.js | 2041 | /*
* Provides L.Map with convenient shortcuts for W3C geolocation.
*/
L.Map.include({
_defaultLocateOptions: {
watch: false,
setView: false,
maxZoom: Infinity,
timeout: 10000,
maximumAge: 0,
enableHighAccuracy: false
},
locate: function (/*Object*/ options) {
options = this._locationOptions = L.Util.extend(this._defaultLocateOptions, options);
if (!navigator.geolocation) {
return this.fire('locationerror', {
code: 0,
message: "Geolocation not supported."
});
}
var onResponse = L.Util.bind(this._handleGeolocationResponse, this),
onError = L.Util.bind(this._handleGeolocationError, this);
if (options.watch) {
this._locationWatchId = navigator.geolocation.watchPosition(onResponse, onError, options);
} else {
navigator.geolocation.getCurrentPosition(onResponse, onError, options);
}
return this;
},
stopLocate: function () {
if (navigator.geolocation) {
navigator.geolocation.clearWatch(this._locationWatchId);
}
return this;
},
_handleGeolocationError: function (error) {
var c = error.code,
message =
(c === 1 ? "permission denied" :
(c === 2 ? "position unavailable" : "timeout"));
if (this._locationOptions.setView && !this._loaded) {
this.fitWorld();
}
this.fire('locationerror', {
code: c,
message: "Geolocation error: " + message + "."
});
},
_handleGeolocationResponse: function (pos) {
var latAccuracy = 180 * pos.coords.accuracy / 4e7,
lngAccuracy = latAccuracy * 2,
lat = pos.coords.latitude,
lng = pos.coords.longitude,
latlng = new L.LatLng(lat, lng),
sw = new L.LatLng(lat - latAccuracy, lng - lngAccuracy),
ne = new L.LatLng(lat + latAccuracy, lng + lngAccuracy),
bounds = new L.LatLngBounds(sw, ne),
options = this._locationOptions;
if (options.setView) {
var zoom = Math.min(this.getBoundsZoom(bounds), options.maxZoom);
this.setView(latlng, zoom);
}
this.fire('locationfound', {
latlng: latlng,
bounds: bounds,
accuracy: pos.coords.accuracy
});
}
});
| mit |
onebytegone/countryside | app/models/HighlightedPoint.php | 629 | <?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class HighlightedPoint extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'HighlightedPoint';
/**
* The primary key for the table
*
* @var string
*/
protected $primaryKey = 'HighlightedPointID';
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = array('HighlightedPointID', 'MapID');
}
| mit |
sasedev/acf-expert | src/Acf/DataBundle/Entity/Docgroup.php | 8098 | <?php
namespace Acf\DataBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Docgroup
*
* @author sasedev <seif.salah@gmail.com>
* @ORM\Table(name="acf_company_docgroups")
* @ORM\Entity(repositoryClass="Acf\DataBundle\Repository\DocgroupRepository")
* @ORM\HasLifecycleCallbacks
* @UniqueEntity(fields={"label", "parent", "company"}, errorPath="label", groups={"label"})
* @UniqueEntity(fields={"pageUrlFull"}, errorPath="parent", groups={"parent"})
*/
class Docgroup
{
/**
*
* @var string @ORM\Column(name="id", type="guid", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
*/
protected $id;
/**
*
* @var Company @ORM\ManyToOne(targetEntity="Company", inversedBy="docgroups", cascade={"persist"})
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="company_id", referencedColumnName="id")
* })
*/
protected $company;
/**
*
* @var Docgroup @ORM\ManyToOne(targetEntity="Docgroup", inversedBy="childs", cascade={"persist"})
* @ORM\JoinColumns({@ORM\JoinColumn(name="parent_id", referencedColumnName="id")})
*/
protected $parent;
/**
*
* @var string @ORM\Column(name="label", type="text", nullable=false)
*/
protected $label;
/**
*
* @var string @ORM\Column(name="pageurl_full", type="text", nullable=false)
* @Gedmo\Slug(handlers={
* @Gedmo\SlugHandler(class="Gedmo\Sluggable\Handler\TreeSlugHandler", options={
* @Gedmo\SlugHandlerOption(name="parentRelationField", value="parent"),
* @Gedmo\SlugHandlerOption(name="separator", value="/")
* })
* }, separator="_", updatable=true, style="camel", fields={"label"})
*/
protected $pageUrlFull;
/**
*
* @var string @ORM\Column(name="others", type="text", nullable=true)
*/
protected $otherInfos;
/**
*
* @var \DateTime @ORM\Column(name="created_at", type="datetimetz", nullable=true)
*/
protected $dtCrea;
/**
*
* @var \DateTime @ORM\Column(name="updated_at", type="datetimetz", nullable=true)
* @Gedmo\Timestampable(on="update")
*/
protected $dtUpdate;
/**
*
* @var Collection @ORM\OneToMany(targetEntity="Docgroup", mappedBy="parent",cascade={"persist"})
* @ORM\OrderBy({"label" = "ASC"})
*/
protected $childs;
/**
*
* @var Collection @ORM\ManyToMany(targetEntity="Doc", mappedBy="groups", cascade={"persist"})
* @ORM\JoinTable(name="acf_group_docs",
* joinColumns={
* @ORM\JoinColumn(name="group_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* @ORM\JoinColumn(name="doc_id", referencedColumnName="id")
* }
* )
*/
protected $docs;
/**
* Constructor
*/
public function __construct()
{
$this->dtCrea = new \DateTime('now');
$this->childs = new ArrayCollection();
$this->docs = new ArrayCollection();
}
/**
* Get id
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Get company
*
* @return Company
*/
public function getCompany()
{
return $this->company;
}
/**
* Set company
*
* @param Company $company
*
* @return Docgroup
*/
public function setCompany(Company $company = null)
{
$this->company = $company;
return $this;
}
/**
* Get $parent
*
* @return Docgroup
*/
public function getParent()
{
return $this->parent;
}
/**
* Set $parent
*
* @param Docgroup $parent
*
* @return Docgroup $this
*/
public function setParent(Docgroup $parent = null)
{
$this->parent = $parent;
if (null == $parent) {
$this->setPageUrlFull($this->getLabel());
}
return $this;
}
/**
* Get label
*
* @return string
*/
public function getLabel()
{
return $this->label;
}
/**
* Set label
*
* @param string $label
*
* @return Docgroup
*/
public function setLabel($label)
{
$this->label = $label;
return $this;
}
/**
* Get $pageUrlFull
*
* @return string
*/
public function getPageUrlFull()
{
return $this->pageUrlFull;
}
/**
* Set $pageUrlFull
*
* @param string $pageUrlFull
*
* @return Docgroup $this
*/
public function setPageUrlFull($pageUrlFull)
{
$this->pageUrlFull = $pageUrlFull;
return $this;
}
/**
* Get otherInfos
*
* @return string
*/
public function getOtherInfos()
{
return $this->otherInfos;
}
/**
* Set otherInfos
*
* @param string $otherInfos
*
* @return Docgroup
*/
public function setOtherInfos($otherInfos)
{
$this->otherInfos = $otherInfos;
return $this;
}
/**
* Get dtCrea
*
* @return \DateTime
*/
public function getDtCrea()
{
return $this->dtCrea;
}
/**
* Set dtCrea
*
* @param \DateTime $dtCrea
*
* @return Docgroup
*/
public function setDtCrea($dtCrea)
{
$this->dtCrea = $dtCrea;
return $this;
}
/**
* Get dtUpdate
*
* @return \DateTime
*/
public function getDtUpdate()
{
return $this->dtUpdate;
}
/**
* Set dtUpdate
*
* @param \DateTime $dtUpdate
*
* @return Docgroup
*/
public function setDtUpdate($dtUpdate)
{
$this->dtUpdate = $dtUpdate;
return $this;
}
/**
* Add child
*
* @param Docgroup $child
*
* @return Docgroup
*/
public function addChild(Docgroup $child)
{
$this->childs[] = $child;
return $this;
}
/**
* Remove child
*
* @param Docgroup $child
*
* @return Docgroup
*/
public function removeChild(Docgroup $child)
{
$this->childs->removeElement($child);
return $this;
}
/**
* Get childs
*
* @return ArrayCollection
*/
public function getChilds()
{
return $this->childs;
}
/**
* Set $childs
*
* @param Collection $childs
*
* @return Docgroup $this
*/
public function setChilds(Collection $childs)
{
$this->childs = $childs;
return $this;
}
/**
* Add doc
*
* @param Doc $doc
*
* @return Docgroup
*/
public function addDoc(Doc $doc)
{
$this->docs[] = $doc;
$doc->addGroup($this);
return $this;
}
/**
* Remove doc
*
* @param Doc $doc
*
* @return Docgroup
*/
public function removeDoc(Doc $doc)
{
$this->docs->removeElement($doc);
$doc->removeGroup($this);
return $this;
}
/**
* Get docs
*
* @return Collection
*/
public function getDocs()
{
return $this->docs;
}
/**
*
* @param Collection $docs
*
* @return Docgroup
*/
public function setDocs(Collection $docs)
{
$this->docs = $docs;
return $this;
}
/**
*/
public function __clone()
{
if ($this->id) {
$docs = $this->getDocs();
$this->docs = new ArrayCollection();
foreach ($docs as $doc) {
$cloneDoc = clone $doc;
$this->docs->add($cloneDoc);
}
}
}
}
| mit |
karim/adila | database/src/main/java/adila/db/gts28lte_sm2dt715.java | 250 | // This file is automatically generated.
package adila.db;
/*
* Samsung Galaxy Tab S2 8.0
*
* DEVICE: gts28lte
* MODEL: SM-T715
*/
final class gts28lte_sm2dt715 {
public static final String DATA = "Samsung|Galaxy Tab S2 8.0|Galaxy Tab";
}
| mit |
StichtingL3D/tools.l3d.nl | backend/models/table.php | 16942 | <?php
/*------------------------------------------------------------------------------
base model for db tables
------------------------------------------------------------------------------*/
class table {
public $error = false;
public $id = null;
protected $id_isint = true;
protected $index_key = 'id';
private $id_regex = "%d";
protected $table; // defaults to class name
protected $table_data;
protected $table_changes;
public function __construct($id=null) {
// sensible defaults
if (is_null($this->table)) {
$this->table = get_class($this);
if (substr($this->table, -1) != 's') {
$this->table .= 's';
}
}
// hatch onto a table
$this->db_connect();
// singular objects
if (!is_null($id)) {
if (empty($id)) {
throw new Exception('no valid id for '.$this->table.': *empty*');
}
if ($this->id_isint && (!is_numeric($id) || $id <= 0)) {
throw new Exception('no valid id for '.$this->table.': '.$id);
}
// some ids are strings (like session-ids)
if ($this->id_isint == false) {
$this->id_regex = "'%s'";
}
// load the initial object from the db
$this->id = $id;
$this->get_object();
}
}
/*------------------------------------------------------------------------------
selecting singular
------------------------------------------------------------------------------*/
public function get_property($key) {
if (is_null($this->id)) {
throw new Exception('can not use get_property() on plural objects');
}
if (array_key_exists($key, $this->table_data) == false) {
// use array_key_exists() as value could be NULL
throw new Exception('key "'.$key.'" doesn\'t exist in model('.$this->table.')');
}
return $this->table_data[$key];
}
public function get_object() {
if (is_null($this->id)) {
throw new Exception('can not use get_object() on plural objects');
}
if (empty($this->table_data)) {
$sql = "SELECT * FROM `".$this->table."` WHERE `".$this->index_key."` = ".$this->id_regex.";";
$this->table_data = $this->db_select('row', $sql, $this->id);
if ($this->table_data == false) {
throw new Exception('empty result set ('.$this->table.')');
}
}
return $this->table_data;
}
/*--- shortcuts ---*/
public function __get($key) {
return $this->get_property($key);
}
public function __isset($key) {
$value = $this->get_property($key);
return isset($value);
}
/*------------------------------------------------------------------------------
selecting plural
------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
selecting multiple objects
- $keys string or array with asked key(s)
"title" or array("title", "text")
- $where an array containing where statements
array("color", "blue") or array(array("color" => "blue"), array("id", "<", "5"))
- $group a string with the key name to group by
- $order a string with the key name to order by
defaults to ASC, prepend with - for DESC
- $limit an integer limiting the amount of results in the set, defaults to 100
------------------------------------------------------------------------------*/
public function select($keys=false, $where=false, $group=false, $order=false, $limit=100) {
if (!is_null($this->id)) {
throw new Exception('can not use select() on singular objects');
}
$sql_args = array();
// add `%s` for all keys and add the keys to the args array
$key_str = "*";
if ($keys != false && $keys != "*") {
if (!is_array($keys)) {
$keys = array($keys);
}
$key_str = mysql_builder::keys($keys);
$sql_args += $keys;
}
// simple filter using where statements
$where_str = "";
if ($where && is_array($where)) {
$where_str = "WHERE ".mysql_builder::where($where, $sql_args);
}
// grouping
$group_str = "";
if ($group && !is_array($group)) {
$group_str = "GROUP BY `%s`";
$sql_args[] = $group;
}
// ordering
$order_str = "";
if ($order && !is_array($order)) {
$order_str = "ORDER BY `%s`";
// descending
if (strpos($order, '-') === 0) {
$order = substr($order, 1);
$order_str .= " DESC";
}
$sql_args[] = $order;
}
// limiting the amount
$limit_str = "";
if ($limit && is_int($limit)) {
$limit_str = "LIMIT ".$limit;
}
// combining everything
$sql = "SELECT ".$key_str." FROM `".$this->table."` ".$where_str." ".$group_str." ".$order_str." ".$limit_str.";";
array_unshift($sql_args, 'array', $sql);
try {
$all = call_user_func_array(array($this, 'db_select'), $sql_args);
}
catch (Exception $e) {
$this->error = $this->db_error;
$all = array();
}
// nicify the result for single-key selects (i.e. "select keyname from")
if ($keys != false && $keys != "*" && count($keys) === 1) {
foreach ($all as &$row) {
// pick the first (and single) value from the result
$row = current($row);
}
}
return $all;
}
/*------------------------------------------------------------------------------
count rows
count all rows (default)
- SELECT COUNT(*) FROM `table`
count how often a value is used in a key
- SELECT `key`, COUNT(*) FROM `table` GROUP BY `key`
- SELECT `key`, COUNT(*) FROM `table` WHERE `key_2` = 'value' GROUP BY `key`
------------------------------------------------------------------------------*/
public function count($key=false, $where=false) {
if (!is_null($this->id)) {
throw new Exception('can not use count() on singular objects');
}
$sql_args = array();
$sql = "SELECT";
// count all rows, and possibly search for a special key
if ($key) {
$sql .= " `%s`,";
$sql_args[] = $key;
}
$sql .= " COUNT(*)";
// table
$sql .= " FROM `".$this->table."`";
// limit the count to special cases
if ($where) {
$sql .= " WHERE ".mysql_builder::where($where, $sql_args);
}
// grouping by the same key
if ($key) {
$sql .= " GROUP BY `%s`";
$sql_args[] = $key;
}
// order also by this key
if ($key) {
$sql .= " ORDER BY `%s`";
$sql_args[] = $key;
}
// end the sql and start counting
$sql .= ";";
if ($key) {
array_unshift($sql_args, 'array', $sql);
$result = call_user_func_array(array($this, 'db_select'), $sql_args);
$count_array = array();
foreach ($result as $result) {
$index = reset($result);
$count = end($result);
$count_array[$index] = $count;
}
$count = $count_array;
}
else {
array_unshift($sql_args, $sql);
$result = call_user_func_array(array($this, 'db_query'), $sql_args);
$count = $result->fetch_array();
$count = $count[0];
}
return $count;
}
/*------------------------------------------------------------------------------
updating singular
------------------------------------------------------------------------------*/
public function update_property($key, $new_value) {
if (is_null($this->id)) {
throw new Exception('can not use update_property() on plural objects');
}
// stage the new value for later writing
$this->table_data[$key] = $new_value;
$this->table_changes[$key] = $new_value;
}
// doesn't use the write cache ($this->table_changes) as it doesn't fit in a simple way
public function update_counter($key, $operator='+', $amount=1) {
if (is_null($this->id)) {
throw new Exception('can not use update_counter() on plural objects');
}
if (is_int($this->table_data[$key]) == false) {
throw new Exception('can not update counter on non-int field');
}
$operator = ($operator == '+') ? '+' : '-';
$sql = "UPDATE `".$this->table."` SET `%s` = `%s` ".$operator." %d WHERE `".$this->index_key."` = ".$this->id_regex.";";
$this->db_query($sql, $key, $key, $amount, $this->id);
// don't update the cache: it is too expensive for a unimportant counter
}
/*--- shortcuts ---*/
public function __set($key, $new_value) {
return $this->update_property($key, $new_value);
}
public function __unset($key) {
throw new Exception('can not unset table fields', 500);
}
public function empty_property($key) {
return $this->update_property($key, '');
}
public function increase_counter($key, $amount=1) {
return $this->update_counter($key, '+', $amount);
}
public function decrease_counter($key, $amount=1) {
return $this->update_counter($key, '-', $amount);
}
/*------------------------------------------------------------------------------
inserting
when used in a singular object, the model switches to the new object
------------------------------------------------------------------------------*/
/*------------------------------------------------------------------------------
insert a new row
------------------------------------------------------------------------------*/
protected function insert($new_data, $replace=false) {
$sql = ($replace) ? "REPLACE" : "INSERT";
$sql .= " INTO `".$this->table."` SET ";
$sql_args = array();
foreach ($new_data as $key => $value) {
$sql .= "`%s` = ";
if (is_int($value) && $value[0] !== '0') {
// only for integer values
// and not starting with zero, as that would be lost
$sql .= "%d,";
}
else {
$sql .= "'%s',";
}
$sql_args[] = $key;
$sql_args[] = $value;
}
$sql = rtrim($sql, ",");
$sql .= ";";
array_unshift($sql_args, $sql);
call_user_func_array(array($this, 'db_query'), $sql_args);
// switch the model to the new object, and fetch its data from the db
$this->id = $this->db_insert_id;
$this->get_object();
return $this->id;
}
/*------------------------------------------------------------------------------
closing the model
purge the updated keys
------------------------------------------------------------------------------*/
public function __destruct() {
// write changes to the database
if (!is_null($this->id)) {
try {
$this->update_object();
}
catch (Exception $e) {
#TODO: find something better for this -- if error::mail throws an exception we get an endless loop
// email the webmasters as we're not allowed to throw exceptions during destruct
try {
error::mail($e);
}
catch (Exception $e) {
// i said NOT allowed, skip silently
}
}
}
}
protected function update_object() {
if (is_null($this->id)) {
return;
}
if (!is_array($this->table_changes) && count($this->table_changes) < 1) {
return;
}
$sql = "UPDATE `".$this->table."` SET ";
$mysql_args = array();
// collect changes
foreach ($this->table_changes as $key => $new_value) {
$sql .= "`".$key."` = ";
if (is_int($this->table_data[$key]) && is_int($new_value) && $new_value[0] !== '0') {
// only for integer values
// and not starting with zero, as that would be lost
$sql .= "%d,";
}
else {
$sql .= "'%s',";
}
$mysql_args[] = $new_value;
}
$sql = rtrim($sql, ",");
// finish up
$sql .= " WHERE `".$this->index_key."` = ".$this->id_regex.";";
$mysql_args[] = $this->id;
// write all updates to the database
array_unshift($mysql_args, $sql);
call_user_func_array(array($this, 'db_query'), $mysql_args);
}
/*------------------------------------------------------------------------------
queriing mysql
------------------------------------------------------------------------------*/
private $db_connection = false;
// these are updated after each query
protected $db_latest_query;
protected $db_all_queries;
protected $db_errno;
protected $db_error;
protected $db_num_rows;
protected $db_insert_id;
protected $db_affected_rows;
// pass values as arguments to auto-escape them
protected function db_query($sql) {
if (func_num_args() > 1) {
$func_args = func_get_args();
unset($func_args[0]); // $sql
$sql = $this->db_escape_and_merge($sql, $func_args);
}
return $this->db_query_raw($sql);
}
// $type = field | row | array
// pass values as arguments to auto-escape them
protected function db_select($type, $sql) {
if (func_num_args() > 1) {
$func_args = func_get_args();
unset($func_args[0]); // $type
unset($func_args[1]); // $sql
$sql = $this->db_escape_and_merge($sql, $func_args);
}
$result = $this->db_query_raw($sql);
// format the result in the right way
if ($this->db_errno) {
return false;
}
elseif ($type == 'field') {
$row = $result->fetch_array();
$field = $row[0];
return $field;
}
elseif ($type == 'row') {
$row = $result->fetch_assoc();
return $row;
}
else { // array
$array = array();
while ($row = $result->fetch_assoc()) {
$array[] = $row;
}
return $array;
}
}
/*------------------------------------------------------------------------------
mysql helpers
------------------------------------------------------------------------------*/
protected function db_escape($value) {
if ($this->db_connection == false) {
throw new Exception('no mysql db connection', 500);
}
if (is_array($value)) {
throw new Exception('arguments for query() or select() should be values, not an array');
}
return $this->db_connection->real_escape_string($value);
}
private function db_escape_and_merge($sql, $args) {
// escape ..
foreach ($args as &$arg) {
$arg = $this->db_escape($arg);
}
// sprintf's x and X modifiers are not utf-8 safe, don't use them
if (strpos($sql, '%x') || strpos($sql, '%X')) {
throw new Exception('can not use non-safe utf-8 x/X modifiers for vsprintf');
}
// .. & merge
$sql = vsprintf($sql, $args);
return $sql;
}
private function db_query_raw($sql) {
if ($this->db_connection == false) {
throw new Exception('no mysql db connection', 500);
}
// secure too generic update and delete queries
if (strpos($sql, 'UPDATE') === 0 || strpos($sql, 'DELETE') === 0) {
// update and delete queries must have an explicit where or limit statement
if (strpos($sql, 'WHERE') === false && strpos($sql, 'LIMIT') === false) {
throw new Exception('insecure update/delete, use a where or a limit');
}
}
$this->db_latest_query = $sql;
$this->db_all_queries[] = $this->db_latest_query;
$result = $this->db_connection->query($sql);
$this->db_errno = $this->db_connection->errno;
$this->db_error = $this->db_connection->error;
if ($this->db_errno && ENVIRONMENT == 'development') {
$e = new Exception('error in mysql query: '.$this->db_error, $this->db_errno);
error::mail($e, false, $type='mysql');
throw $e;
}
elseif ($this->db_errno) {
$e = new Exception('error in mysql query: '.$this->db_error, $this->db_errno);
error::mail($e, false, $type='mysql');
$e = false;
throw new Exception('error in mysql query');
}
if (strpos($sql, 'SELECT') === 0) {
$this->db_num_rows = $result->num_rows;
}
else {
$this->db_num_rows = false;
}
if (strpos($sql, 'INSERT') === 0) {
$this->db_insert_id = $this->db_connection->insert_id;
}
else {
$this->db_insert_id = false;
}
// check affected_rows first
// sometimes we get an apache segfault when requesting affected_rows without a connection
// tested on php 5.2.10, apache 2(20051115), mysqli 5.1.34
// fixed in php 5.2.13 (https://bugs.php.net/50727)
if (isset($this->db_connection->affected_rows) == true) {
$this->db_affected_rows = $this->db_connection->affected_rows;
}
else {
$this->db_affected_rows = false;
}
return $result;
}
/*------------------------------------------------------------------------------
connect to mysql
------------------------------------------------------------------------------*/
protected function db_config() {
return new config('mysql');
}
protected function db_switch($db_name) {
$this->connection->select_db($db_name);
}
private function db_connect() {
// security: turn off magic quotes for files and databases, deprecated as of PHP 6
if (version_compare(PHP_VERSION, '5.3', '<')) {
ini_set('magic_quotes_runtime', 0);
}
/*--- connect to the database ---*/
$config = $this->db_config();
try {
#echo 'connecting to '.$config['user'].'@'.$config['host'].NLd;
$connection = new mysqli($config['host'], $config['user'], base64_decode($config['pass']), $config['name']);
}
catch (Exception $e) {
error::mail($e, false, $type='mysql');
throw $e;
}
if (version_compare(PHP_VERSION, '5.2.9') >= 0 && isset($connection) && $connection->connect_error) {
$this->db_errno = $connection->connect_errno;
$this->db_error = $connection->connect_error;
}
elseif (mysqli_connect_error()) {
$this->db_errno = mysqli_connect_errno();
$this->db_error = mysqli_connect_error();
}
if ($this->db_errno) {
if ($this->db_errno == '1045') {
$e = new Exception('failed to connect to mysql db: check username/password combination', $this->db_errno);
}
if ($this->db_errno == '1049') {
$e = new Exception('failed to connect to mysql db: create the database (or fix the settings)', $this->db_errno);
}
if ($this->db_errno >= 2000) {
$e = new Exception('failed to connect to mysql db: start mysql (or fix the settings)', $this->db_errno);
}
error::mail($e, false, $type='mysql');
throw $e;
}
$this->db_connection = $connection;
$this->db_query_raw("SET NAMES utf8;");
$this->db_query_raw("SET CHARACTER SET utf8;");
}
}
| mit |
wildsmith/MaterialDesign | src/com/wildsmith/material/playground/viewholders/PlaygroundNavigationCardViewHolder.java | 2746 | package com.wildsmith.material.playground.viewholders;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.util.Pair;
import android.view.View;
import android.widget.TextView;
import com.wildsmith.material.R;
import com.wildsmith.material.playground.detail.PlaygroundDetailActivity;
import com.wildsmith.material.utils.ResourceHelper;
public class PlaygroundNavigationCardViewHolder extends PlaygroundCardViewHolder {
private CardView cardView;
private TextView titleText;
private TextView infoText;
public PlaygroundNavigationCardViewHolder(View view) {
super(view);
cardView = (CardView) view.findViewById(R.id.card_view);
titleText = (TextView) view.findViewById(R.id.navigation_title_text);
infoText = (TextView) view.findViewById(R.id.navigation_info_text);
}
@Override
public void populateView(Context context, Object recyclerObject, int position) {
cardView.setTransitionName("card:view:" + position);
titleText.setTransitionName("nav:title:" + position);
infoText.setTransitionName("nav:info:" + position);
setupCardViewListener();
}
@Override
public View getTitleTextView(View view) {
if (view == null) {
return null;
}
return view.findViewById(R.id.navigation_title_text);
}
@Override
public View getInfoTextView(View view) {
if (view == null) {
return null;
}
return view.findViewById(R.id.navigation_info_text);
}
private void setupCardViewListener() {
cardView.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("unchecked")
@Override
public void onClick(View view) {
Intent intent = new Intent(mActivity, PlaygroundDetailActivity.class);
intent.putExtra("ActionBarShowing", mActivity.getActionBar().isShowing());
final View titleText = getTitleTextView(view);
final String titleViewName = ResourceHelper.getResString(R.string.detail_title_view_name);
final View infoText = getInfoTextView(view);
final String infoViewName = ResourceHelper.getResString(R.string.detail_info_view_name);
ActivityOptions activityOptions =
ActivityOptions.makeSceneTransitionAnimation(mActivity, new Pair<View, String>(titleText, titleViewName),
new Pair<View, String>(infoText, infoViewName));
mActivity.startActivity(intent, activityOptions.toBundle());
}
});
}
} | mit |
gcazaciuc/redux-fractal | src/localReducer.js | 4142 | import * as UIActions from './actions.js';
const stores = {};
const globalActions = {};
const refCounter = {};
const defaultGlobalFilter = () => false;
const initialiseComponentState = (state, payload, componentKey) => {
const { config, store } = payload;
stores[componentKey] = store;
refCounter[componentKey] = refCounter[componentKey] || 0;
refCounter[componentKey]++;
globalActions[componentKey] = config.filterGlobalActions || defaultGlobalFilter;
const initialState = stores[componentKey].getState();
const newComponentsState = Object.assign({}, state, { [componentKey]: initialState });
return newComponentsState;
};
const destroyComponentState = (state, payload, componentKey) => {
refCounter[componentKey] = refCounter[componentKey] || 0;
if (refCounter[componentKey] > 0) {
refCounter[componentKey]--;
}
if (refCounter[componentKey]) {
return state;
}
const newState = Object.assign({}, state);
delete newState[componentKey];
delete refCounter[componentKey];
delete stores[componentKey];
delete globalActions[componentKey];
return newState;
};
const updateSingleComponent = (oldComponentState, action, componentKey) => {
const store = stores[componentKey];
if (store) {
// eslint-disable-next-line
action.meta = Object.assign({}, action.meta, { reduxFractalCurrentComponent: componentKey });
store.originalDispatch(action);
return store.getState();
}
return oldComponentState;
};
const updateComponentState = (state, action, componentKey) => {
const newState = Object.keys(state).reduce((stateAcc, k) => {
const shouldUpdate = componentKey === k ||
(typeof globalActions[k] === 'function' && globalActions[k](action));
let updatedState = state[k];
if (shouldUpdate) {
updatedState = updateSingleComponent(state[k], action, k);
return Object.assign({}, stateAcc, { [k]: updatedState });
}
return stateAcc;
}, {});
return Object.assign({}, state, newState);
};
export default (state = {}, action) => {
const componentKey = action.meta && action.meta.reduxFractalTriggerComponent;
let nextState = null;
switch (action.type) {
case UIActions.CREATE_COMPONENT_STATE:
return initialiseComponentState(
state,
action.payload,
componentKey);
case UIActions.DESTROY_COMPONENT_STATE:
if (!action.payload.persist && stores[componentKey]) {
return destroyComponentState(state, action.payload, componentKey);
}
return state;
case UIActions.DESTROY_ALL_COMPONENTS_STATE:
nextState = state;
Object.keys(state).forEach((k) => {
nextState = destroyComponentState(nextState, {}, k);
});
return nextState;
default:
return updateComponentState(state, action, componentKey);
}
};
export const createStore = (createStoreFn, props, componentKey, existingState, context) => {
if (!stores[componentKey]) {
const getWrappedAction = (action) => {
let wrappedAction = action;
if (typeof action === 'object') {
const actionMeta = Object.assign({},
action.meta,
{ reduxFractalTriggerComponent: componentKey });
wrappedAction = Object.assign({}, action, { meta: actionMeta });
}
return wrappedAction;
};
const localDispatch = (action) => {
const wrappedAction = getWrappedAction(action);
return context.store.dispatch(wrappedAction);
};
const storeResult = createStoreFn(props, existingState, context);
let storeCleanup = () => true;
if (storeResult.store) {
stores[componentKey] = storeResult.store;
}
if (storeResult.cleanup) {
storeCleanup = storeResult.cleanup;
}
if (storeResult.dispatch && storeResult.getState) {
stores[componentKey] = storeResult;
}
stores[componentKey].originalDispatch = stores[componentKey].dispatch;
stores[componentKey].dispatch = localDispatch;
return { store: stores[componentKey], cleanup: storeCleanup };
}
return { store: stores[componentKey] };
};
| mit |
jkk/shinkgs | src/ui/common/Modal.js | 1592 | // @flow
import React, { PureComponent as Component } from "react";
import { A } from "./A";
import { Portal } from "./Portal";
import { isAncestor } from "../../util/dom";
type Props = {
children?: any,
title?: any,
onClose: Function,
};
export class Modal extends Component<Props> {
_mainDiv: ?HTMLElement;
componentDidMount() {
document.addEventListener("keyup", this._onKeyUp);
if (document.body) {
document.body.classList.add("no-scroll");
}
}
componentWillUnmount() {
document.removeEventListener("keyup", this._onKeyUp);
if (document.body) {
document.body.classList.remove("no-scroll");
}
}
render() {
let { children, title, onClose } = this.props;
let className = "Modal Modal-" + (title ? "with-title" : "without-title");
return (
<Portal>
<div className={className} onClick={this._onMaybeClose}>
<div className="Modal-main" ref={this._setMainRef}>
{title ? <div className="Modal-title">{title}</div> : null}
<A className="Modal-close" onClick={onClose}>
×
</A>
<div className="Modal-content">{children}</div>
</div>
</div>
</Portal>
);
}
_setMainRef = (ref: HTMLElement | null) => {
this._mainDiv = ref;
};
_onKeyUp = (e: Object) => {
if (e.key === "Escape" || e.keyCode === 27) {
this.props.onClose();
}
};
_onMaybeClose = (e: Object) => {
if (this._mainDiv && isAncestor(e.target, this._mainDiv)) {
return;
}
this.props.onClose();
};
}
| mit |
greenpeace/p3_footerquiz | js/quiz.js | 8659 | /**
* Greenpeace Quiz
* @package org.greenpeace.js.quiz
* @author Team Narwhal (oh yeah!)
* @copyright Copyright 2012, Greenpeace International
* @license MIT License (opensource.org/licenses/MIT)
*/
$.fn.quiz = (function(config) {
// Configuration
// we merge the default and the given data using 'deep' extend feature
// see. http://api.jquery.com/jQuery.extend/
config = $.extend(true, {
baseUrl : 'http://localhost/greenpeace-quiz',
dataFile : '/js/greenpeace-quiz.json',
selector : {
//container : '', // automatically set @see init
question : '.question .sentence',
correct : '.answer.result',
score : '.score',
options : '.answers.options',
option : '.answers.options .option a',
image : '.illustration',
next : '.nextQuestion',
restart : '.restart',
feedback : '.feedback',
},
template : {
question : '#questionTemplate',
image : '#imageTemplate',
answers : '#answersTemplate',
feedback : '#feedbackTemplate',
score : '#scoreTemplate',
gameover : '#gameoverTemplate',
social : '#socialTemplate',
},
delay : -1 // timer ms delay to autoswitch between answer/question. -1 = manual.
}, config || {});
// The plugin return itself
// for it also may need to chain itself to stuffs to get things done
return this.each(function() {
/**
* Main Game Data
*/
var id; // typically #quiz but could be something else you fancy
var mcq; // where questions meet answers
var mcqLength; // number of questions
var currentScore; // score of the curent user
var currentQuestion; // index of the current question in mcq
var fin; // end of game stuffs
/**
* Initialization method
* Load the data and get the ball rolling
* @param string , the application tag id
*/
function init(o) {
id = o;
config.selector.container = '#' + id;
// check if the data are not already available
// only make one Ajax/JSON call
if (mcq === undefined) {
$.getJSON(
config.baseUrl + config.dataFile,
function(data) {
mcq = data[0]['questions'];
fin = data[0]['gameover'];
maxScore = mcq.length;
onReady();
}
);
} else {
// reset previous answers
var i = 0;
for (;i<maxScore;i++) {
mcq[i]['answer'] = undefined;
}
onReady();
}
}
/**
* Post initialization callback
*/
function onReady() {
setScore(0);
setQuestion(0);
}
/**
* Event callback when the user click on an answer
* @param object, the link clicked
* @param int q, the corresponding question index in mcq
*/
function onAnswerClick(o,q) {
var a;
var msg;
var clas;
//unbind click to the answers
//$(config.selector.option)
// check if this is the right answer
a = (o.id[6] === mcq[q]['solution']);
if (a) {
setScore(currentScore+1);
} else {
setScore(currentScore-1);
}
mcq[q]['answer'] = a;
// Render the feedback template
renderFeedback();
// bind click events with answer buttons
$(config.selector.next).click(function() {
onNextQuestion();
});
// or you could also use a timer if you want
if (config.delay > 0) {
window.setTimeout(
function() {
onNextQuestion();
},
config.delay
);
}
}
/**
* Next Question Callback
* Call the next question or finish the show
*/
function onNextQuestion() {
if (currentQuestion+1 < mcq.length) {
setQuestion(currentQuestion+1);
} else {
setGameOver();
}
}
/**
* Set (and display) the current question
* @param int q, the corresponding question index in mcq
*/
function setQuestion(q) {
var i = 0;
var l = mcq[q]['options'].length;
currentQuestion = q;
// Render the question/answer templates
renderQuestion();
// bind click events with answer buttons
$(config.selector.option).click(function(){
onAnswerClick(this,q);
});
}
/**
* When the last question is asked, and the last button clicked,
* we will realized that we can't eat answers
*/
function setGameOver() {
var msg;
var c = currentScore;
var i = 0;
var f = fin;
var l = f.length;
// display different text/image depending on the score
for (; i < l; i++) {
if (c <= f[i]['threshold']) {
break;
}
}
// Render the contextual game over screen
renderGameOver(i);
// bind init event to restart button
$(config.selector.restart).click(function(){
init(id);
});
}
/**
* Set the current user score
* @param int s, new score
*/
function setScore(s) {
if (s >= 0) {
currentScore = s;
}
}
/**
* Render the question template with some taky annimation
*/
function renderQuestion() {
var q = currentQuestion;
// Reset the view
$(config.selector.container).empty();
// Render the question template
$(config.template.question)
.tmpl([{question : mcq[q]['question']}])
.appendTo(config.selector.container);
// Render the answers template
$(config.template.answers)
.tmpl(mcq[q]['options'])
.appendTo(config.selector.options);
$(config.selector.container)
.css({'margin-left':'100%'})
.animate({
'margin-left': '0%'
}, 100, 'linear');
// Render the image template
$(config.selector.container)
.css('background','transparent url('+mcq[q]['image'][0].url+') right 100px no-repeat')
.animate({
'background-position-y': '0px'
}, 100, 'linear');
}
/**
* Render feedback depending on answer
*/
function renderFeedback() {
var q = currentQuestion;
var correct = mcq[q]['answer'];
var msg;
// message and class change
if (correct) {
correct = 'correct';
msg = mcq[q]['feedback'][1];
} else {
correct = 'wrong';
msg = mcq[q]['feedback'][0];
};
// Reset the view
$(config.selector.container)
.empty();
// Render template
$(config.template.feedback)
.tmpl([{
correct : correct,
msg : msg
}])
.appendTo(config.selector.container)
}
/**
* Render GameOver
* The show isn't over until the fat lady sings
* @param i int, the index of the dynamic finish message/image that applies
*/
function renderGameOver(i) {
// Reset the view
$(config.selector.container)
.empty();
$(config.template.gameover)
.tmpl([{
msg : fin[i]['text'],
currentScore : currentScore,
maxScore : maxScore
}])
.appendTo(config.selector.container);
renderScore();
$(config.template.social)
.tmpl([{
msg : fin[i].social
}])
.appendTo(config.selector.container);
$(config.selector.container)
.animate({
'background-position-y': '130px'
}, 100, 'linear')
.css({'margin-left':'100%'})
.animate({
'margin-left': '0'
}, 100, 'linear');
// Render the image template
$(config.selector.container)
.css('background','transparent url('+fin[i]['image'][0]['url']+') right 100px no-repeat')
.animate({
'background-position-y': '0px'
}, 100, 'linear');
}
/**
* Render Score
*/
function renderScore() {
// Render the score template
// make sure question have been rendered
$(config.template.score)
.tmpl([{
currentScore : currentScore,
maxScore : maxScore
}])
.appendTo(config.selector.score);
}
// Go quiz, give them hell!
init(this.id);
});
});
/*
/
.-. /
.--./ / _.---./
'-, (__..-` \
\ |
`,.__. ^___.-/
`-./ .'...--`
`’
☮ & ♥
*/
$('#quiz').quiz({
//dataFile : 'greenpeace-quiz-fr_fr.json'
});
| mit |
rsaylor73/tp | check_time3.php | 2982 | <?php
session_start();
$sesID = session_id();
// init
include_once "include/settings.php";
include_once "include/mysql.php";
include_once "include/templates.php";
function ensure2Digit($number) {
if($number < 10) {
//$number = '0' . $number;
}
return $number;
}
// Convert seconds into months, days, hours, minutes, and seconds.
function secondsToTime($ss) {
$s = ensure2Digit($ss%60);
$m = ensure2Digit(floor(($ss%3600)/60));
$h = ensure2Digit(floor(($ss%86400)/3600));
$d = ensure2Digit(floor(($ss%2592000)/86400));
$M = ensure2Digit(floor($ss/2592000));
//return "$M:$d:$h:$m:$s";
$data[] = $d;
$data[] = $h;
$data[] = $m;
$data[] = $s;
return $data;
//return "$d Day(s) $h Hour(s) $m Minutes $s Seconds";
}
//$_SESSION['page_eventID'] = "1";
$sql = "
SELECT
DATE_FORMAT(`events`.`end_date`, '%Y-%m-%d') AS 'timestamp'
FROM
`events`,`location`,`category`,`users`
WHERE
`events`.`id` = '$_SESSION[page_eventID]'
AND `events`.`locationID` = `location`.`id`
AND `events`.`categoryID` = `category`.`id`
AND `events`.`userID` = `users`.`id`
";
$result = $tickets->new_mysql($sql);
while ($row = $result->fetch_assoc()) {
$timestamp = $row['timestamp'];
}
$dateTime = new DateTime($timestamp);
$endTime = $dateTime->format('U');
$now = date("U");
$time_left = $endTime - $now;
$time_left2 = secondsToTime($time_left);
$days = $time_left2[0];
$hours = $time_left2[1];
$mins = $time_left2[2];
$secs = $time_left2[3];
//print "$days $hours $mins $secs<br>";
/*
if ($time_left < 0) {
print "<b>End Date has expired</b>";
} else {
print "<h2>Time Left: $time_left2</h1>";
}
*/
require_once "jpgraph/src/jpgraph.php";
require_once "jpgraph/src/jpgraph_canvas.php";
// Caption below the image
$txt="";
$w=550;$h=75;
$xm=20;$ym=20;
$tw=160;
$g = new CanvasGraph($w,$h);
$img = $g->img;
// Alignment for anchor points to use
$time = array($days,$hours,$mins,$secs);
$palign = array(' DAYS','HOURS','MINS','SEC');
$n = count($palign);
$t = new Text($txt);
$y = $ym;
for( $i=0; $i < $n; ++$i ) {
$x = $xm + $i*$tw;
$t->SetColor('black');
$t->SetAlign('left','top');
$t->SetFont(FF_ARIAL,FS_NORMAL,22);
//$t->SetBox();
//$t->SetParagraphAlign($palign[$i]);
$t->Stroke($img, $x,$y);
$img->SetColor('black');
$img->SetFont(FF_ARIAL,FS_NORMAL,22);
$img->SetTextAlign('center','top');
$img->StrokeText($x+0,$y+0,''.$time[$i].'');
$img->StrokeText($x+0,$y+30,''.$palign[$i].'');
}
// .. and send back to browser
//$g->Stroke();
$fileName = ".reports/$rand.png";
$g->img->Stream($fileName);
$image = "<img src=\"$fileName\">";
print "$image";
?>
| mit |
ekretschmann/sparesys | public/modules/schools/controllers/schools.client.controller.js | 10425 | 'use strict';
// Schools controller
angular.module('schools').controller('SchoolsController', ['$window', '$scope', '$timeout', '$state', '$stateParams', '$location', '$modal',
'Authentication', 'Schools', 'Schoolclasses', 'Users',
function ($window, $scope, $timeout, $state, $stateParams, $location, $modal, Authentication, Schools, Schoolclasses, Users) {
$scope.authentication = Authentication;
$scope.scrollDown = function () {
$window.scrollTo(0, document.body.scrollHeight);
angular.element('.focus').trigger('focus');
};
$scope.registerSchoolPopup = function () {
$modal.open({
templateUrl: 'registerSchool.html',
controller: 'RegisterSchoolController'
});
};
$scope.options = {};
$scope.options.searchText = '';
$scope.updateSearch = function () {
if (!$scope.options.searchText) {
$scope.options.searchText = '';
}
Schools.query({
text: $scope.options.searchText
}, function (schools) {
$scope.schools = schools;
});
};
$scope.newClass = {};
$scope.newClass.name = '';
$scope.addSchoolclassToSchool = function () {
var schoolClass = new Schoolclasses({
name: $scope.newClass.name,
school: $scope.school._id
});
schoolClass.$save(function (sc) {
console.log('ga create schoolclass');
console.log('/schools/:id/addclass/:id');
if ($window.ga) {
console.log('sending to ga');
$window.ga('send', 'pageview', '/schools/:id/addclass/:id');
$window.ga('send', 'event', 'user creates schoolclass');
}
$scope.school.schoolclasses.push(schoolClass);
$scope.school.$save(function () {
$timeout(function () {
$window.scrollTo(0, document.body.scrollHeight);
});
});
});
this.newClass.name = '';
angular.element('.focus').trigger('focus');
};
$scope.subscribeTeacherPopup = function (school, user) {
$modal.open({
templateUrl: 'subscribeTeacher.html',
controller: 'SubscribeTeacherModalController',
resolve: {
school: function () {
return school;
},
user: function () {
return user;
}
}
});
};
$scope.unsubscribeTeacherPopup = function (school, user) {
$modal.open({
templateUrl: 'unsubscribeTeacher.html',
controller: 'UnsubscribeTeacherModalController',
resolve: {
school: function () {
return school;
},
user: function () {
return user;
}
}
});
};
$scope.subscribeStudentPopup = function (school, user) {
$scope.school = school;
$modal.open({
templateUrl: 'subscribeStudent.html',
controller: 'SubscribeStudentModalController',
resolve: {
school: function () {
return $scope.school;
},
user: function () {
return user;
}
}
});
};
$scope.unsubscribeStudentPopup = function (school, user) {
$modal.open({
templateUrl: 'unsubscribeStudent.html',
controller: 'UnsubscribeStudentModalController',
resolve: {
school: function () {
return school;
},
user: function () {
return user;
}
}
});
};
$scope.areYouSureToDeleteSchool = function (school) {
//console.log($scope.authentication.user.administersSchools);
var index = $scope.authentication.user.administersSchools.indexOf(school._id);
$modal.open({
templateUrl: 'areYouSureToDeleteSchool.html',
controller: 'DeleteSchoolModalController',
resolve: {
school: function () {
return school;
}
}
}).result.then(function () {
if (index > -1) {
$scope.authentication.user.administersSchools.splice(index, 1);
}
if ($scope.schools) {
$scope.schools = Schools.query();
}
});
};
$scope.areYouSureToRemoveSchoolFromStudent = function (school, user) {
//console.log(school);
//console.log(user);
$modal.open({
templateUrl: 'areYouSureToRemoveSchoolFromStudent.html',
controller: 'RemoveSchoolFromStudentModalController',
resolve: {
school: function () {
return school;
},
user: function () {
return user;
}
}
}).result.then(function () {
Users.get({
userId: user._id
}, function (user) {
$scope.otherUser = user;
});
});
};
$scope.areYouSureToRemoveSchoolFromTeacher = function (school, user) {
$modal.open({
templateUrl: 'areYouSureToRemoveSchoolFromTeacher.html',
controller: 'RemoveSchoolFromTeacherModalController',
resolve: {
school: function () {
return school;
},
user: function () {
return user;
}
}
}).result.then(function () {
Users.get({
userId: user._id
}, function (user) {
$scope.otherUser = user;
});
});
};
$scope.areYouSureToRemoveStudent = function (student) {
$modal.open({
templateUrl: 'areYouSureToRemoveStudent.html',
controller: 'RemoveStudentFromSchoolModalController',
resolve: {
student: function () {
return student;
},
school: function () {
return $scope.school;
}
}
}).result.then(function () {
console.log('finished');
});
};
$scope.removeDeadTeacherId = function (id) {
$scope.school.teachers.splice($scope.school.teachers.indexOf(id), 1);
$scope.school.$update();
};
$scope.areYouSureToRemoveTeacher = function (teacher) {
$modal.open({
templateUrl: 'areYouSureToRemoveTeacher.html',
controller: 'RemoveTeacherFromSchoolModalController',
resolve: {
teacher: function () {
return teacher;
},
school: function () {
return $scope.school;
}
}
}).result.then(function () {
Schools.get({
schoolId: $scope.school._id
}, function (updatedSchool) {
$scope.school = updatedSchool;
});
});
};
$scope.hasClassAssigned = function (userId) {
var found = false;
for (var i = 0; i < $scope.schoolclasses.length; i++) {
for (var j = 0; j < $scope.schoolclasses[i].teachers.length; j++) {
if ($scope.schoolclasses[i].teachers[j] === $scope.authentication.user._id) {
found = true;
}
}
}
return found;
};
// Update existing School
$scope.update = function () {
var school = $scope.school;
school.$update();
};
$scope.find = function () {
$scope.schools = Schools.query();
};
// // Find existing School
$scope.findById = function (id) {
if (id) {
$scope.school = Schools.get({
schoolId: id
}, function (s) {
$scope.schoolclasses = s.schoolclasses;
}, function (err) {
$scope.error = 'school ' + id + ' does not exist';
});
}
};
$scope.schoolclasses = [];
$scope.populateSchoolForUser = function (schoolId, user) {
Schools.get({
schoolId: schoolId
}, function (s) {
$scope.school = s;
$scope.schoolclasses = s.schoolclasses;
$scope.schoolclasses = [];
for (var i = 0; i < $scope.school.schoolclasses.length; i++) {
var schoolclass = $scope.school.schoolclasses[i];
if (user.studentInClasses.indexOf(schoolclass._id) !== -1) {
$scope.schoolclasses.push(schoolclass);
}
}
});
};
// Find existing School
$scope.findOne = function () {
$scope.stateParamId = $stateParams.schoolId;
$scope.school = Schools.get({
schoolId: $stateParams.schoolId
});
};
}
]);
| mit |
518coin/518coin | src/qt/locale/bitcoin_ar.ts | 118252 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="ar" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About 518Coin</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+39"/>
<source><b>518Coin</b> version</source>
<translation>جزء البلاك كوين</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014 The 518Coin 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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>كتاب العنوان</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>أنقر على الماوس مرتين لتعديل العنوان</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>انشأ عنوان جديد</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>قم بنسخ العنوان المختار لحافظة النظام</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&عنوان جديد</translation>
</message>
<message>
<location line="-46"/>
<source>These are your 518Coin 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>هذه هي عناوين البلاك كوين لاستقبال الدفعات. يمكن أن تعطي عنوان مختلف لكل مرسل من اجل أن تتابع من يرسل لك.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>انسخ العنوان</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>اظهار &رمز الاستجابة السريعة</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a 518Coin address</source>
<translation>التوقيع علي رسالة لاثبات بانك تملك عنوان البلاك كوين</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>وقع &الرسالة</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>خذف العنوان الحالي التي تم اختياره من القائمة</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified 518Coin address</source>
<translation>تحقق من الرسالة لتثبت بانه تم توقيعه بعنوان بلاك كوين محدد</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&تحقق الرسالة</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&أمسح</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>نسخ &التسمية</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>تعديل</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>تصدير بيانات كتاب العناوين</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(لا وصف)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>حوار كلمة المرور</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>ادخل كلمة المرور</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>عبارة مرور جديدة</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>ادخل الجملة السرية مرة أخرى</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.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>أدخل عبارة مرور جديدة إلى المحفظة. الرجاء استخدام عبارة مرور تتكون من10 حروف عشوائية على الاقل, أو أكثر من 7 كلمات </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك لفتحها</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>إفتح المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>هذه العملية تحتاج عبارة المرور محفظتك فك تشفيرها</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>فك تشفير المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغيير عبارة المرور</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>أدخل عبارة المرور القديمة والجديدة إلى المحفظة.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>تأكيد التشفير المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>تخذير : اذا تم تشفير المحفظة وضيعت كلمة المرور, لن تستطيع الحصول علي البلاك كوين</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>هل انت متأكد من رغبتك في تشفير المحفظة؟</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 type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>محفظة مشفرة</translation>
</message>
<message>
<location line="-58"/>
<source>518Coin 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>بلاك كوين</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>فشل تشفير المحفظة</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>شل تشفير المحفظة بسبب خطأ داخلي. لم يتم تشفير محفظتك.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>عبارتي المرور ليستا متطابقتان
</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>فشل فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>عبارة المرور التي تم إدخالها لفك شفرة المحفظة غير صحيحة.
</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>فشل فك التشفير المحفظة</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>كلمة مرور المحفظة تم تغييره بشكل ناجح</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation>التوقيع و الرسائل</translation>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>مزامنة مع شبكة ...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>نظرة عامة</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>إظهار نظرة عامة على المحفظة</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>المعاملات</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تصفح التاريخ المعاملات</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&كتاب العنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>تعديل قائمة العنوان المحفوظة</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>&استقبال البلاك كوين</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>اظهار قائمة العناوين التي تستقبل التعاملات</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>&ارسال البلاك كوين</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>الخروج من التطبيق</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about 518Coin</source>
<translation>اظهار المعلومات عن البلاك كوين</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>عن</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>اظهر المعلومات</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>خيارات ...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>تشفير المحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>حفظ ودعم المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغيير كلمة المرور</translation>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><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="-247"/>
<source>&Export...</source>
<translation>&تصدير...</translation>
</message>
<message>
<location line="-62"/>
<source>Send coins to a 518Coin address</source>
<translation>ارسال البلاك كوين الي عنوان اخر</translation>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for 518Coin</source>
<translation>تعديل خيارات التكوين للبلاك كوين</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>ارسال البيانات الحالية الي ملف</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>تشفير او فك التشفير للمحفظة</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>احفظ نسخة احتياطية للمحفظة في مكان آخر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>تغيير عبارة المرور المستخدمة لتشفير المحفظة</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>تأكيد الرسالة</translation>
</message>
<message>
<location line="-200"/>
<source>518Coin</source>
<translation>البلاك كوين</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+178"/>
<source>&About 518Coin</source>
<translation>عن البلاك كوين</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>اظهار/ اخفاء</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>فتح المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>قفل المحفظة</translation>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>ملف</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>الاعدادات</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>مساعدة</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>شريط أدوات علامات التبويب</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>518Coin client</source>
<translation>برنامج البلاك كوين</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to 518Coin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><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.<br>Your weight is %1<br>Network weight is %2<br>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'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><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><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><numerusform></numerusform><numerusform></numerusform><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><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>محين</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>اللحاق بالركب ...</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>تأكيد رسوم المعاملة</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>المعاملات المرسلة</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>المعاملات واردة</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</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 518Coin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>المحفظة مشفرة و مفتوحة حاليا</translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>المحفظة مشفرة و مقفلة حاليا</translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>النسخ الاحتياطي للمحفظة</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>بيانات المحفظة (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>فشل الدعم</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>خطا في محاولة حفظ بيانات الحفظة في مكان جديد</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. 518Coin can no longer continue safely and will quit.</source>
<translation>خطا فادح! بلاك كوين لا يمكن أن يستمر جاري الاغلاق</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>تحذير الشبكة</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>سيطرة الكوين</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>الكمية:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>المبلغ:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>اهمية:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>رسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>لا</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>بعد الرسوم:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>تغيير:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>نعم</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 "medium".
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>(لا وصف)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>عدل العنوان</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>العنوان</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>عنوان تلقي جديد</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>عنوان إرسال جديد</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>تعديل عنوان التلقي
</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>تعديل عنوان الارسال</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>هدا العنوان "%1" موجود مسبقا في دفتر العناوين</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid 518Coin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation> يمكن فتح المحفظة.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>فشل توليد مفتاح جديد.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>518Coin-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 "de_DE" (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>خيارات ...</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>الرئيسي</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 &fee</source>
<translation>ادفع &رسوم المعاملة</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>حجز</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start 518Coin after logging in to the system.</source>
<translation>بد البلاك كوين تلقائي عند الدخول الي الجهاز</translation>
</message>
<message>
<location line="+3"/>
<source>&Start 518Coin 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>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&الشبكة</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the 518Coin 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 &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the 518Coin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</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>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>نافذه</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting 518Coin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show 518Coin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>عرض العناوين في قائمة الصفقة</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>تم</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>الغاء</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>الافتراضي</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 518Coin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>عنوان الوكيل توفيره غير صالح.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>نمودج</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the 518Coin 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 type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>محفظة</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>غير ناضجة</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>الكامل:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>اخر المعملات </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>خارج المزامنه</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>&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>اسم العميل</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>غير معروف</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>نسخه العميل</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>المعلومات</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>الشبكه</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>عدد الاتصالات</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>الفتح</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the 518Coin-Qt help message to get a list with possible 518Coin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>وقت البناء</translation>
</message>
<message>
<location line="-104"/>
<source>518Coin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>518Coin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the 518Coin 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the 518Coin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</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>إرسال Coins</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 518C</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</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>إرسال إلى عدة مستلمين في وقت واحد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>الرصيد:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 518C</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تأكيد الإرسال</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a 518Coin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تأكيد الإرسال Coins</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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>المبلغ المدفوع يجب ان يكون اكبر من 0</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</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 518Coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(لا وصف)</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&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>ادفع الى </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>إدخال تسمية لهذا العنوان لإضافته إلى دفتر العناوين الخاص بك</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation>العنوان لارسال المعاملة الي (مثلا SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</translation>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</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>انسخ العنوان من لوحة المفاتيح</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>خذف هذا المستخدم</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a 518Coin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation>ادخال عنوان البلاك كوين (مثلا SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>التواقيع - التوقيع /تأكيد الرسالة</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&وقع الرسالة</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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>اختيار عنوان من كتاب العناوين</translation>
</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>انسخ العنوان من لوحة المفاتيح</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 type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this 518Coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>مسح الكل</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified 518Coin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a 518Coin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter 518Coin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>العنوان المدخل غير صالح</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>الرجاء التأكد من العنوان والمحاولة مرة اخرى</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>العنوان المدخل لا يشير الى مفتاح</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>المفتاح الخاص للعنوان المدخل غير موجود.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>فشل توقيع الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>الرسالة موقعة.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>فشلت عملية التأكد من الرسالة.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>تم تأكيد الرسالة.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><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% غير متواجد</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>غير مؤكدة/1%</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>تأكيد %1</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>الحالة.</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>المصدر</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>تم اصداره.</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>من</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>الى</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>عنوانه</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>غير مقبولة</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>دين</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>رسوم التحويل</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>تعليق</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>رقم المعاملة</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 "not accepted" and it won'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 type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>معاملة</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>صحيح</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>خاطئ</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>لم يتم حتى الآن البث بنجاح</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>غير معروف</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>تفاصيل المعاملة</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>يبين هذا الجزء وصفا مفصلا لهده المعاملة</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>مفتوح حتى 1٪</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تأكيد الإرسال Coins</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>غير متصل</translation>
</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>لم يتم تلقى هذه الكتلة (Block) من قبل أي العقد الأخرى وربما لن تكون مقبولة!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>ولدت ولكن لم تقبل</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>استقبل من</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>دفع لنفسك</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>غير متوفر</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>حالة المعاملة. تحوم حول هذا الحقل لعرض عدد التأكيدات.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>التاريخ والوقت الذي تم فيه تلقي المعاملة.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع المعاملات</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>عنوان وجهة المعاملة</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>المبلغ الذي أزيل أو أضيف الى الرصيد</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>الكل</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>اليوم</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>هدا الاسبوع</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>هدا الشهر</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>الشهر الماضي</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>هدا العام</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>نطاق</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>استقبل مع</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>أرسل إلى</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>إليك</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>اخرى</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>ادخل عنوان أووصف للبحث</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>الكمية الادني</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation> انسخ عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation> انسخ التسمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>نسخ الكمية</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>نسخ رقم المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>عدل الوصف</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>اظهار تفاصيل المعاملة</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation>تصدير بيانات المعاملة</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تأكيد</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>التاريخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>النوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>وصف</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>عنوان</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>المبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>العنوان</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا في التصدير</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>لا يمكن الكتابة الي الملف %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>نطاق:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>الى</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>518Coin version</source>
<translation>جزع البلاك كوين</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>المستخدم</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or 518coind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>اعرض الأوامر</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>مساعدة في كتابة الاوامر</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>خيارات: </translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: 518coin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: 518coind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>حدد موقع مجلد المعلومات او data directory</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>ضع حجم كاش قاعدة البيانات بالميجابايت (الافتراضي: 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 <port> (default: 51801 or testnet: 41801)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>حدد عنوانك العام هنا</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</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 <port> (default: 51800 or testnet: 41800)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>تحذير صناعة المعاملة فشلت</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>خطا : المحفظة مقفلة, لا يمكن عمل المعاملة</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>استيراد بيانات ملف سلسلة الكتل</translation>
</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>استخدم التحقق من الشبكه</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>قبول الاتصالات من خارج</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong 518Coin will not work properly.</source>
<translation>تحذير : تأكد من ساعة وتاريخ الكمبيوتر! اذا ساعة غير صحيحة بلاك كوين لن يعمل بشكل صحيح</translation>
</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>تحذير : خطا في قراءة wallet.dat! كل المفاتيح تم قرائتة بشكل صحيح لكن بيانات الصفقة او إدخالات كتاب العنوان غير صحيحة او غير موجودة</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>تخذير :wallet.dat غير صالح تم حفظ البيانات. المحفظة الاصلية تم حفظه ك wallet.{timestamp}.bak %s في ; اذا حسابك او صفقاتك غير صحيح يجب عليك استعادة النسخ الاحتياطي</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>محاولة استرجاع المفاتيح الخاصة من wallet.dat الغير صالح</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>خيارات صناعة الكتل</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>فشل في الاستماع على أي منفذ. استخدام الاستماع = 0 إذا كنت تريد هذا.</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: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</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 Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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>تحذير : مساحة القرص منخفض</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>تحذير هذا الجزء قديم, التجديد مطلوب</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat غير صالح لا يمكن الاسترجاع</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</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=518coinrpc
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 "518Coin Alert" admin@foo.com
</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>عند</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</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>ارقاء المحفظة الي اخر نسخة</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>اعادة بحث سلسلة الكتلة لايجاد معالمات المحفظة</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>كمية الكتل التي تريد ان تبحث عنه عند بداية البرنامج (التلقائي 2500, 0 = الكل)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>كمية تأكيد الكتل (0-6 التلقائي 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>نقل كتل من ملف blk000.dat خارجي</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</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>رسالة المساعدة هذه</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. 518Coin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>518Coin</source>
<translation>البلاك كوين</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>تحميل العنوان</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>خظا في تحميل blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطأ عند تنزيل wallet.dat: المحفظة تالفة</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of 518Coin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart 518Coin to complete</source>
<translation>المحفظة يجب أن يعاد كتابته : أعد البلاك كوين لتكتمل</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>خطأ عند تنزيل wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>ارسال....</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>مبلغ خاطئ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>حسابك لا يكفي</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. 518Coin 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=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>تحميل المحفظه</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation> لا يمكن خفض المحفظة</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> لا يمكن كتابة العنوان الافتراضي</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>إعادة مسح</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>انتهاء التحميل</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>خطأ</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS>
| mit |
wix/stylable-components | src/components/checkbox/checkbox.tsx | 4494 | import * as React from 'react';
import {properties, stylable} from 'wix-react-tools';
import {FormInputProps} from '../../types/forms';
import {StylableProps} from '../../types/props';
import {noop} from '../../utils';
import styles from './checkbox.st.css';
export interface CheckBoxProps extends FormInputProps<boolean>, StylableProps {
tickIcon?: React.ReactNode;
indeterminateIcon?: React.ReactNode;
children?: React.ReactNode;
error?: boolean;
indeterminate?: boolean;
['aria-controls']?: string[];
}
export interface CheckBoxState {
isFocused: boolean;
}
@stylable(styles)
@properties
export class CheckBox extends React.Component<CheckBoxProps, CheckBoxState> {
public static defaultProps: Partial<CheckBoxProps> = {
tickIcon: (
<span
className={`${styles.icon} ${styles.tickIcon}`}
data-automation-id="CHECKBOX_TICKMARK"
/>
),
indeterminateIcon: (
<span
className={`${styles.icon} ${styles.indeterminateIcon}`}
data-automation-id="CHECKBOX_INDETERMINATE"
/>
),
onChange: noop,
indeterminate: false,
tabIndex: 0
};
public state: CheckBoxState = {isFocused: false};
private nativeInput: HTMLInputElement;
public render() {
const styleState = {
checked: this.props.value!,
disabled: this.props.disabled!,
readonly: this.props.readOnly!,
indeterminate: this.props.indeterminate!,
focus: this.state.isFocused,
error: this.props.error
};
return (
<div
data-automation-id="CHECKBOX_ROOT"
onClick={this.handleClick}
style-state={styleState}
role="checkbox"
aria-checked={this.props.indeterminate ? 'mixed' : this.props.value}
>
<input
data-automation-id="NATIVE_CHECKBOX"
type="checkbox"
className="nativeCheckbox"
checked={this.props.value}
disabled={this.props.disabled}
onClick={this.handleInputClick}
onChange={this.handleChange}
onFocus={this.handleInputFocus}
onBlur={this.handleInputBlur}
id={this.props.id}
tabIndex={this.props.tabIndex}
autoFocus={this.props.autoFocus}
name={this.props.name}
aria-controls={this.props['aria-controls']}
ref={ref => this.nativeInput = ref!}
/>
<span
className="box"
data-automation-id="CHECKBOX_BOX"
>
{this.props.indeterminate ?
this.props.indeterminateIcon : (this.props.value && this.props.tickIcon)}
</span>
{this.props.children ? (
<div
data-automation-id="CHECKBOX_CHILD_CONTAINER"
className="childContainer"
>
{this.props.children}
</div>
) : null
}
</div>
);
}
private handleClick: React.MouseEventHandler<HTMLDivElement> = e => {
this.handleChange(e);
this.nativeInput && this.nativeInput.focus();
this.setState({isFocused: false});
}
private handleChange = (e: React.SyntheticEvent<HTMLElement>) => {
if (!this.props.disabled && !this.props.readOnly) {
this.props.onChange!({
value: this.props.indeterminate ? true : !this.props.value
});
}
}
// handleInputClick will be called only on pressing "space" key when nativeInput has focus
private handleInputClick: React.MouseEventHandler<HTMLInputElement> = e => {
e.stopPropagation();
this.setState({isFocused: true});
}
private handleInputBlur: React.FocusEventHandler<HTMLInputElement> = () => {
this.state.isFocused && this.setState({isFocused: false});
}
private handleInputFocus: React.FocusEventHandler<HTMLInputElement> = () => {
!this.state.isFocused && this.setState({isFocused: true});
}
}
| mit |
JackPu/atom-weexpack | pkg/commons-node/spec/humanizeKeystroke-spec.js | 3512 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the license found in the LICENSE file in
* the root directory of this source tree.
*
* @flow
*/
import humanizeKeystroke from '../humanizeKeystroke';
describe('nuclide-keystroke-label', () => {
// adapted from https://github.com/atom/underscore-plus/blob/master/spec/underscore-plus-spec.coffee
describe('humanizeKeystroke', () => {
it('replaces single keystroke', () => {
expect(humanizeKeystroke('cmd-O', 'darwin')).toEqual('⌘⇧O');
expect(humanizeKeystroke('cmd-O', 'linux')).toEqual('Cmd+Shift+O');
expect(humanizeKeystroke('cmd-shift-up', 'darwin')).toEqual('⌘⇧↑');
expect(humanizeKeystroke('cmd-shift-up', 'linux')).toEqual('Cmd+Shift+Up');
expect(humanizeKeystroke('cmd-option-down', 'darwin')).toEqual('⌘⌥↓');
expect(humanizeKeystroke('cmd-option-down', 'linux')).toEqual('Cmd+Alt+Down');
expect(humanizeKeystroke('cmd-option-left', 'darwin')).toEqual('⌘⌥←');
expect(humanizeKeystroke('cmd-option-left', 'linux')).toEqual('Cmd+Alt+Left');
expect(humanizeKeystroke('cmd-option-right', 'darwin')).toEqual('⌘⌥→');
expect(humanizeKeystroke('cmd-option-right', 'linux')).toEqual('Cmd+Alt+Right');
expect(humanizeKeystroke('cmd-o', 'darwin')).toEqual('⌘O');
expect(humanizeKeystroke('cmd-o', 'linux')).toEqual('Cmd+O');
expect(humanizeKeystroke('ctrl-2', 'darwin')).toEqual('⌃2');
expect(humanizeKeystroke('ctrl-2', 'linux')).toEqual('Ctrl+2');
expect(humanizeKeystroke('cmd-space', 'darwin')).toEqual('⌘space');
expect(humanizeKeystroke('cmd-space', 'linux')).toEqual('Cmd+Space');
expect(humanizeKeystroke('cmd-|', 'darwin')).toEqual('⌘⇧\\');
expect(humanizeKeystroke('cmd-|', 'linux')).toEqual('Cmd+Shift+\\');
expect(humanizeKeystroke('cmd-}', 'darwin')).toEqual('⌘⇧]');
expect(humanizeKeystroke('cmd-}', 'linux')).toEqual('Cmd+Shift+]');
expect(humanizeKeystroke('cmd--', 'darwin')).toEqual('⌘-');
expect(humanizeKeystroke('cmd--', 'linux')).toEqual('Cmd+-');
});
it('correctly replaces keystrokes with shift and capital letter', () => {
expect(humanizeKeystroke('cmd-shift-P', 'darwin')).toEqual('⌘⇧P');
expect(humanizeKeystroke('cmd-shift-P', 'linux')).toEqual('Cmd+Shift+P');
});
it('replaces multiple keystrokes', () => {
expect(humanizeKeystroke('cmd-O cmd-n', 'darwin')).toEqual('⌘⇧O ⌘N');
expect(humanizeKeystroke('cmd-O cmd-n', 'linux')).toEqual('Cmd+Shift+O Cmd+N');
expect(humanizeKeystroke('cmd-shift-- cmd-n', 'darwin')).toEqual('⌘⇧- ⌘N');
expect(humanizeKeystroke('cmd-shift-- cmd-n', 'linux')).toEqual('Cmd+Shift+- Cmd+N');
expect(humanizeKeystroke('cmd-k right', 'darwin')).toEqual('⌘K →');
expect(humanizeKeystroke('cmd-k right', 'linux')).toEqual('Cmd+K Right');
});
it('formats function keys', () => {
expect(humanizeKeystroke('cmd-f2', 'darwin')).toEqual('⌘F2');
expect(humanizeKeystroke('cmd-f2', 'linux')).toEqual('Cmd+F2');
});
it('handles junk input', () => {
// $FlowFixMe: Deliberately testing invalid input.
expect(humanizeKeystroke()).toEqual(undefined);
// $FlowFixMe: Deliberately testing invalid input.
expect(humanizeKeystroke(null)).toEqual(null);
expect(humanizeKeystroke('')).toEqual('');
});
});
});
| mit |
Limpan/bytardag | web/tests/test_basics.py | 363 | import pytest
def test_app_exists(app):
assert app is not None
def test_app_is_testing(app):
assert app.config['TESTING']
def test_home_page(client):
rv = client.get('/')
assert rv.status_code == 200
assert 'Klädbytardagen'.encode() in rv.data
def test_gdpr_page(client):
rv = client.get('/gdpr')
assert rv.status_code == 200
| mit |
coylums/synergy | SignalR-master/samples/Microsoft.AspNet.SignalR.Samples/Hubs/Test/Default.aspx.cs | 222 | using System;
namespace Microsoft.AspNet.SignalR.Samples.Hubs.Test
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | mit |
ixtreon/musa | TaskList.cs | 192 | using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Musa
{
}
| mit |
UnicornCollege/ucl.itkpd.configurator | client/node_modules/react-dom/lib/DOMPropertyOperations.js | 7606 | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
'use strict';
var DOMProperty = require('./DOMProperty');
var ReactDOMComponentTree = require('./ReactDOMComponentTree');
var ReactInstrumentation = require('./ReactInstrumentation');
var quoteAttributeValueForBrowser = require('./quoteAttributeValueForBrowser');
var warning = require('fbjs/lib/warning');
var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$');
var illegalAttributeNameCache = {};
var validatedAttributeNameCache = {};
function isAttributeNameSafe(attributeName) {
if (validatedAttributeNameCache.hasOwnProperty(attributeName)) {
return true;
}
if (illegalAttributeNameCache.hasOwnProperty(attributeName)) {
return false;
}
if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) {
validatedAttributeNameCache[attributeName] = true;
return true;
}
illegalAttributeNameCache[attributeName] = true;
process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0;
return false;
}
function shouldIgnoreValue(propertyInfo, value) {
return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false;
}
/**
* Operations for dealing with DOM properties.
*/
var DOMPropertyOperations = {
/**
* Creates markup for the ID property.
*
* @param {string} id Unescaped ID.
* @return {string} Markup string.
*/
createMarkupForID: function (id) {
return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id);
},
setAttributeForID: function (node, id) {
node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id);
},
createMarkupForRoot: function () {
return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""';
},
setAttributeForRoot: function (node) {
node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, '');
},
/**
* Creates markup for a property.
*
* @param {string} name
* @param {*} value
* @return {?string} Markup string, or null if the property was invalid.
*/
createMarkupForProperty: function (name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
if (shouldIgnoreValue(propertyInfo, value)) {
return '';
}
var attributeName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
return attributeName + '=""';
}
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
}
return null;
},
/**
* Creates markup for a custom property.
*
* @param {string} name
* @param {*} value
* @return {string} Markup string, or empty string if the property was invalid.
*/
createMarkupForCustomAttribute: function (name, value) {
if (!isAttributeNameSafe(name) || value == null) {
return '';
}
return name + '=' + quoteAttributeValueForBrowser(value);
},
/**
* Sets the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
* @param {*} value
*/
setValueForProperty: function (node, name, value) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(propertyInfo, value)) {
this.deleteValueForProperty(node, name);
return;
} else if (propertyInfo.mustUseProperty) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propertyInfo.propertyName] = value;
} else {
var attributeName = propertyInfo.propertyName;
var namespace = propertyInfo.attributeNamespace;
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
if (namespace) {
node.setAttributeNS(namespace, attributeName, '' + value);
} else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) {
node.setAttribute(attributeName, '');
} else {
node.setAttribute(attributeName, '' + value);
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
DOMPropertyOperations.setValueForAttribute(node, name, value);
return;
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'update attribute',
payload: payload
});
}
},
setValueForAttribute: function (node, name, value) {
if (!isAttributeNameSafe(name)) {
return;
}
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
if (process.env.NODE_ENV !== 'production') {
var payload = {};
payload[name] = value;
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'update attribute',
payload: payload
});
}
},
/**
* Deletes an attributes from a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForAttribute: function (node, name) {
node.removeAttribute(name);
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'remove attribute',
payload: name
});
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function (node, name) {
var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null;
if (propertyInfo) {
var mutationMethod = propertyInfo.mutationMethod;
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (propertyInfo.mustUseProperty) {
var propName = propertyInfo.propertyName;
if (propertyInfo.hasBooleanValue) {
node[propName] = false;
} else {
node[propName] = '';
}
} else {
node.removeAttribute(propertyInfo.propertyName);
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
}
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onHostOperation({
instanceID: ReactDOMComponentTree.getInstanceFromNode(node)._debugID,
type: 'remove attribute',
payload: name
});
}
}
};
module.exports = DOMPropertyOperations; | mit |
cdchild/TransitApp | Transit/Controllers/AccessibleCodesController.cs | 4132 | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Transit.Models;
namespace Transit.Controllers
{
public class AccessibleCodesController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: AccessibleCodes
public async Task<ActionResult> Index()
{
return View(await db.AccessibleCodes.ToListAsync());
}
// GET: AccessibleCodes/Details/5
public async Task<ActionResult> Details(byte? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AccessibleCode accessibleCode = await db.AccessibleCodes.FindAsync(id);
if (accessibleCode == null)
{
return HttpNotFound();
}
return View(accessibleCode);
}
// GET: AccessibleCodes/Create
public ActionResult Create()
{
return View();
}
// POST: AccessibleCodes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "id,label,description")] AccessibleCode accessibleCode)
{
if (ModelState.IsValid)
{
db.AccessibleCodes.Add(accessibleCode);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(accessibleCode);
}
// GET: AccessibleCodes/Edit/5
public async Task<ActionResult> Edit(byte? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AccessibleCode accessibleCode = await db.AccessibleCodes.FindAsync(id);
if (accessibleCode == null)
{
return HttpNotFound();
}
return View(accessibleCode);
}
// POST: AccessibleCodes/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "id,label,description")] AccessibleCode accessibleCode)
{
if (ModelState.IsValid)
{
db.Entry(accessibleCode).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(accessibleCode);
}
// GET: AccessibleCodes/Delete/5
public async Task<ActionResult> Delete(byte? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
AccessibleCode accessibleCode = await db.AccessibleCodes.FindAsync(id);
if (accessibleCode == null)
{
return HttpNotFound();
}
return View(accessibleCode);
}
// POST: AccessibleCodes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(byte id)
{
AccessibleCode accessibleCode = await db.AccessibleCodes.FindAsync(id);
db.AccessibleCodes.Remove(accessibleCode);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| mit |
CS2103AUG2016-T10-C3/main | src/main/java/seedu/emeraldo/logic/commands/HelpCommand.java | 760 | package seedu.emeraldo.logic.commands;
import seedu.emeraldo.commons.core.EventsCenter;
import seedu.emeraldo.commons.events.ui.ShowHelpRequestEvent;
/**
* Format full help instructions for every command for display.
*/
public class HelpCommand extends Command {
public static final String COMMAND_WORD = "help";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Shows program usage instructions.\n"
+ "Example: " + COMMAND_WORD;
public static final String SHOWING_HELP_MESSAGE = "Opened help window.";
public HelpCommand() {}
@Override
public CommandResult execute() {
EventsCenter.getInstance().post(new ShowHelpRequestEvent());
return new CommandResult(SHOWING_HELP_MESSAGE);
}
}
| mit |
sernst/cauldron | cauldron/cli/commands/open/__init__.py | 5560 | import os
import typing
from argparse import ArgumentParser
import cauldron
from cauldron import cli
from cauldron import environ
from cauldron.cli.commands.listing import discovery
from cauldron.cli.commands.open import actions
from cauldron.cli.commands.open import opener
from cauldron.cli.commands.open import remote as remote_opener
from cauldron.cli.interaction import autocompletion
from cauldron.environ import Response
NAME = 'open'
DESCRIPTION = 'Opens a cauldron project'
def populate(
parser: ArgumentParser,
raw_args: typing.List[str],
assigned_args: dict
):
"""..."""
parser.add_argument(
'path',
nargs='?',
default=None,
help=cli.reformat(
"""
A path to the directory containing a cauldron project. Special
location paths can also be used.
"""
)
)
parser.add_argument(
'-s', '--show',
dest='show_in_browser',
default=False,
action='store_true',
help=cli.reformat(
"""
The previously stored state of the project will open in the browser
for display if this flag is included.
"""
)
)
parser.add_argument(
'-l', '--last',
dest='last_opened_project',
default=False,
action='store_true',
help=cli.reformat("""
The open command will open the most recently opened project if this
flag is included.
""")
)
parser.add_argument(
'-r', '--recent',
dest='a_recent_project',
default=False,
action='store_true',
help=cli.reformat(
"""
Displays a list of recently opened projects for you to select from.
"""
)
)
parser.add_argument(
'-a', '--available', '--all',
dest='list_available',
default=False,
action='store_true',
help=cli.reformat(
"""
List all known projects to choose one to open.
"""
)
)
parser.add_argument(
'--forget',
dest='forget',
default=False,
action='store_true',
help=cli.reformat('Forget that this project was opened')
)
def execute(
context: cli.CommandContext,
path: str = None,
last_opened_project: bool = False,
a_recent_project: bool = False,
show_in_browser: bool = False,
list_available: bool = False,
forget: bool = False,
results_path: str = None
) -> Response:
"""..."""
response = context.response
path = path.strip('"') if path else None
if list_available:
path = actions.select_from_available(response)
if not path:
return response
if last_opened_project:
path = actions.fetch_last(response)
if not path:
return response
elif a_recent_project:
path = actions.fetch_recent(response)
if not path:
return response
elif not path or not path.strip():
discovery.echo_known_projects(response)
return response
else:
p = actions.fetch_location(path)
path = p if p else path
if context.remote_connection.active:
environ.remote_connection.reset_sync_time()
response.consume(remote_opener.sync_open(
context=context,
path=path,
forget=forget
))
else:
response.consume(opener.open_project(
path=path,
forget=forget,
results_path=results_path
))
if not response.failed and show_in_browser:
cli.open_in_browser(cauldron.project.internal_project)
return response
def autocomplete(segment: str, line: str, parts: typing.List[str]):
"""
:param segment:
:param line:
:param parts:
:return:
"""
if parts[-1].startswith('-'):
return autocompletion.match_flags(
segment=segment,
value=parts[-1],
shorts=['s', 'l', 'r', 'a'],
longs=['show', 'last', 'recent', 'available', 'forget']
)
if len(parts) == 1:
value = parts[0]
if value.startswith('@examples:'):
path_segment = value.split(':', 1)[-1]
return autocompletion.match_path(
segment,
environ.paths.resources('examples', path_segment),
include_files=False
)
if value.startswith('@home:'):
path_segment = value.split(':', 1)[-1]
return autocompletion.match_path(
segment,
environ.paths.home(path_segment),
include_files=False
)
environ.configs.load()
aliases = environ.configs.fetch('folder_aliases', {})
matches = ['@{}:'.format(x) for x in aliases.keys()]
for m in matches:
if value.startswith(m):
return autocompletion.match_path(
segment,
environ.paths.clean(os.path.join(
aliases[m[1:-1]]['path'],
value[-1].split(':', 1)[-1]
)),
include_files=False
)
matches.append('@examples:')
matches.append('@home:')
if value.startswith('@'):
return autocompletion.matches(segment, value, matches)
return autocompletion.match_path(segment, value)
| mit |
codn/adminpanel | test/dummy/app/controllers/adminpanel/categories_controller.rb | 254 | module Adminpanel
class CategoriesController < Adminpanel::ApplicationController
private
def category_params
params.require(:category).permit(
:mug_ids,
:product_ids,
:name
)
end
end
end
| mit |
dsj7419/GynBot | src/Siotrix.Discord.Core/Extensions/LogsToggleExtensions.cs | 8212 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
namespace Siotrix.Discord
{
public static class LogsToggleExtensions
{
#region normal logs
public static async Task<DiscordGuildLogChannel> GetLogChannelAsync(ulong id)
{
var val = new DiscordGuildLogChannel();
using (var db = new LogDatabase())
{
try
{
val = await db.Glogchannels.FirstOrDefaultAsync(x => x.GuildId == id.ToLong());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return val;
}
public static async Task CreateLogChannelAsync(SocketCommandContext context, SocketChannel channel)
{
var logChannel = new DiscordGuildLogChannel(context.Guild.Id.ToLong(), channel.Id.ToLong(), false);
using (var db = new LogDatabase())
{
try
{
await db.Glogchannels.AddAsync(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task DeleteLogChannelAsync(DiscordGuildLogChannel logChannel)
{
using (var db = new LogDatabase())
{
try
{
db.Glogchannels.Remove(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task SetLogChannel(DiscordGuildLogChannel logChannel, SocketChannel channel)
{
logChannel.SetLogChannel(channel.Id.ToLong());
using (var db = new LogDatabase())
{
try
{
db.Glogchannels.Update(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task SetLogChannelIsActive(DiscordGuildLogChannel logChannel, bool isActive)
{
logChannel.SetLogIsActive(isActive);
using (var db = new LogDatabase())
{
try
{
db.Glogchannels.Update(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
#endregion
#region Moderation logs
public static async Task<DiscordGuildModLogChannel> GetModLogChannelAsync(ulong id)
{
var val = new DiscordGuildModLogChannel();
using (var db = new LogDatabase())
{
try
{
val = await db.Gmodlogchannels.FirstOrDefaultAsync(x => x.GuildId == id.ToLong());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return val;
}
public static async Task CreateModLogChannelAsync(SocketCommandContext context, SocketChannel channel)
{
var logChannel = new DiscordGuildModLogChannel(context.Guild.Id.ToLong(), channel.Id.ToLong(), false);
using (var db = new LogDatabase())
{
try
{
await db.Gmodlogchannels.AddAsync(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task DeleteModLogChannelAsync(DiscordGuildModLogChannel logChannel)
{
using (var db = new LogDatabase())
{
try
{
db.Gmodlogchannels.Remove(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task SetModLogChannel(DiscordGuildModLogChannel logChannel, SocketChannel channel)
{
logChannel.SetModLogChannel(channel.Id.ToLong());
using (var db = new LogDatabase())
{
try
{
db.Gmodlogchannels.Update(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task SetModLogChannelIsActive(DiscordGuildModLogChannel logChannel, bool isActive)
{
logChannel.SetModLogIsActive(isActive);
using (var db = new LogDatabase())
{
try
{
db.Gmodlogchannels.Update(logChannel);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
#endregion
#region Individual logs
public static async Task<IEnumerable<DiscordGuildLogsToggle>> GetLogsToggleAsync(IGuild guild)
{
IEnumerable<DiscordGuildLogsToggle> val = new List<DiscordGuildLogsToggle>();
using (var db = new LogDatabase())
{
try
{
val = await db.LogsToggle.Where(x => x.GuildId == guild.Id.ToLong()).ToListAsync();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return val;
}
public static async Task<DiscordGuildLogsToggle> GetLogToggleAsync(ulong guildId, string logName)
{
var val = new DiscordGuildLogsToggle();
using (var db = new LogDatabase())
{
try
{
val = await db.LogsToggle.FirstOrDefaultAsync(
x => x.GuildId == guildId.ToLong() && x.LogName == logName);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return val;
}
public static async Task CreateLogToggleAsync(ulong guildId, string logName)
{
var newLog = new DiscordGuildLogsToggle(guildId.ToLong(), logName.ToLower());
using (var db = new LogDatabase())
{
try
{
await db.LogsToggle.AddAsync(newLog);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static async Task DeleteLogToggleAsync(DiscordGuildLogsToggle logToggle)
{
using (var db = new LogDatabase())
{
try
{
db.LogsToggle.Remove(logToggle);
await db.SaveChangesAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
#endregion
}
}
| mit |
simpart/trut | doc/design/html/search/files_1.js | 151 | var searchData=
[
['extfunc_2ephp',['ExtFunc.php',['../ExtFunc_8php.html',1,'']]],
['extmod_2ephp',['ExtMod.php',['../ExtMod_8php.html',1,'']]]
];
| mit |
callidus/playbot | playbot/plugins/fortune/data_source.py | 1815 |
from __future__ import absolute_import
import sqlite3 as dbapi
class DataSource(object):
def __init__(self):
self.conn = None
def __del__(self):
if self.conn:
self.conn.close()
def open_db(self, name):
"""open an existing database."""
self.conn = dbapi.connect(name)
def build_db(self, name):
"""build a new database to use."""
self.conn = dbapi.connect(name)
try:
c = self.conn.cursor()
c.execute('CREATE TABLE fortune('
'id INTEGER PRIMARY KEY ASC, data TEXT)')
self.conn.commit()
except Exception:
self.conn.rollback()
raise
def get_count(self):
sql = 'SELECT Count(*) FROM fortune'
c = self.conn.cursor()
c.execute(sql)
return c.fetchone()[0]
def add_fortune(self, data):
c = self.conn.cursor()
sql = 'INSERT INTO fortune (data) VALUES (?)'
try:
c.execute(sql, (data,))
fortuneId = c.lastrowid
self.conn.commit()
return fortuneId
except Exception:
self.conn.rollback()
raise
def del_fortune(self, itemId):
c = self.conn.cursor()
sql = 'DELETE FROM fortune WHERE id=?'
try:
c.execute(sql, (itemId,))
self.conn.commit()
except Exception:
self.conn.rollback()
raise
def get_fortunes(self):
sql = 'SELECT id, data FROM fortune'
c = self.conn.cursor()
c.execute(sql)
return c.fetchall()
def get_fortune(self, id):
sql = 'SELECT data FROM fortune WHERE id=?'
c = self.conn.cursor()
c.execute(sql, (id,))
return c.fetchone()[0]
| mit |
kaiinui/lambda_kit | test/lambda_driver/s3_put_event.js | 1115 | module.exports = {
"Records": [
{
"eventVersion": "2.0",
"eventSource": "aws:s3",
"awsRegion": "us-east-1",
"eventTime": "1970-01-01T00:00:00.000Z",
"eventName": "ObjectCreated:Put",
"userIdentity": {
"principalId": "AIDAJDPLRKLG7UEXAMPLE"
},
"requestParameters": {
"sourceIPAddress": "127.0.0.1"
},
"responseElements": {
"x-amz-request-id": "C3D13FE58DE4C810",
"x-amz-id-2": "FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
},
"s3": {
"s3SchemaVersion": "1.0",
"configurationId": "testConfigRule",
"bucket": {
"name": "sourcebucket",
"ownerIdentity": {
"principalId": "A3NL1KOZZKExample"
},
"arn": "arn:aws:s3:::mybucket"
},
"object": {
"key": "HappyFace.jpg",
"size": 1024,
"eTag": "d41d8cd98f00b204e9800998ecf8427e"
}
}
}
]
}; | mit |
SCPTeam/Safe-Component-Provider | Sat4jCore/src/org/sat4j/minisat/constraints/cnf/HTClause.java | 9661 | /*******************************************************************************
* SAT4J: a SATisfiability library for Java Copyright (C) 2004, 2012 Artois University and CNRS
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU Lesser General Public License Version 2.1 or later (the
* "LGPL"), in which case the provisions of the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of the LGPL, and not to allow others to use your version of
* this file under the terms of the EPL, indicate your decision by deleting
* the provisions above and replace them with the notice and other provisions
* required by the LGPL. If you do not delete the provisions above, a recipient
* may use your version of this file under the terms of the EPL or the LGPL.
*
* Based on the original MiniSat specification from:
*
* An extensible SAT solver. Niklas Een and Niklas Sorensson. Proceedings of the
* Sixth International Conference on Theory and Applications of Satisfiability
* Testing, LNCS 2919, pp 502-518, 2003.
*
* See www.minisat.se for the original solver in C++.
*
* Contributors:
* CRIL - initial API and implementation
*******************************************************************************/
package org.sat4j.minisat.constraints.cnf;
import static org.sat4j.core.LiteralsUtils.neg;
import java.io.Serializable;
import org.sat4j.minisat.core.Constr;
import org.sat4j.minisat.core.ILits;
import org.sat4j.minisat.core.Propagatable;
import org.sat4j.specs.IVecInt;
import org.sat4j.specs.UnitPropagationListener;
/**
* Lazy data structure for clause using the Head Tail data structure from SATO,
* The original scheme is improved by avoiding moving pointers to literals but
* moving the literals themselves.
*
* We suppose here that the clause contains at least 3 literals. Use the
* BinaryClause or UnaryClause clause data structures to deal with binary and
* unit clauses.
*
* @author leberre
* @see BinaryClause
* @see UnitClause
* @since 2.1
*/
public abstract class HTClause implements Propagatable, Constr, Serializable {
private static final long serialVersionUID = 1L;
protected double activity;
protected final int[] middleLits;
protected final ILits voc;
protected int head;
protected int tail;
/**
* Creates a new basic clause
*
* @param voc
* the vocabulary of the formula
* @param ps
* A VecInt that WILL BE EMPTY after calling that method.
*/
public HTClause(IVecInt ps, ILits voc) {
assert ps.size() > 1;
this.head = ps.get(0);
this.tail = ps.last();
final int size = ps.size() - 2;
assert size > 0;
this.middleLits = new int[size];
System.arraycopy(ps.toArray(), 1, this.middleLits, 0, size);
ps.clear();
assert ps.size() == 0;
this.voc = voc;
this.activity = 0;
}
/*
* (non-Javadoc)
*
* @see Constr#calcReason(Solver, Lit, Vec)
*/
public void calcReason(int p, IVecInt outReason) {
if (this.voc.isFalsified(this.head)) {
outReason.push(neg(this.head));
}
final int[] mylits = this.middleLits;
for (int mylit : mylits) {
if (this.voc.isFalsified(mylit)) {
outReason.push(neg(mylit));
}
}
if (this.voc.isFalsified(this.tail)) {
outReason.push(neg(this.tail));
}
}
/*
* (non-Javadoc)
*
* @see Constr#remove(Solver)
*/
public void remove(UnitPropagationListener upl) {
this.voc.watches(neg(this.head)).remove(this);
this.voc.watches(neg(this.tail)).remove(this);
}
/*
* (non-Javadoc)
*
* @see Constr#simplify(Solver)
*/
public boolean simplify() {
if (this.voc.isSatisfied(this.head) || this.voc.isSatisfied(this.tail)) {
return true;
}
for (int middleLit : this.middleLits) {
if (this.voc.isSatisfied(middleLit)) {
return true;
}
}
return false;
}
public boolean propagate(UnitPropagationListener s, int p) {
if (this.head == neg(p)) {
final int[] mylits = this.middleLits;
int temphead = 0;
// moving head on the right
while (temphead < mylits.length
&& this.voc.isFalsified(mylits[temphead])) {
temphead++;
}
assert temphead <= mylits.length;
if (temphead == mylits.length) {
this.voc.watch(p, this);
return s.enqueue(this.tail, this);
}
this.head = mylits[temphead];
mylits[temphead] = neg(p);
this.voc.watch(neg(this.head), this);
return true;
}
assert this.tail == neg(p);
final int[] mylits = this.middleLits;
int temptail = mylits.length - 1;
// moving tail on the left
while (temptail >= 0 && this.voc.isFalsified(mylits[temptail])) {
temptail--;
}
assert -1 <= temptail;
if (-1 == temptail) {
this.voc.watch(p, this);
return s.enqueue(this.head, this);
}
this.tail = mylits[temptail];
mylits[temptail] = neg(p);
this.voc.watch(neg(this.tail), this);
return true;
}
/*
* For learnt clauses only @author leberre
*/
public boolean locked() {
return this.voc.getReason(this.head) == this
|| this.voc.getReason(this.tail) == this;
}
/**
* @return the activity of the clause
*/
public double getActivity() {
return this.activity;
}
@Override
public String toString() {
StringBuffer stb = new StringBuffer();
stb.append(Lits.toString(this.head));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(this.head));
stb.append("]"); //$NON-NLS-1$
stb.append(" "); //$NON-NLS-1$
for (int middleLit : this.middleLits) {
stb.append(Lits.toString(middleLit));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(middleLit));
stb.append("]"); //$NON-NLS-1$
stb.append(" "); //$NON-NLS-1$
}
stb.append(Lits.toString(this.tail));
stb.append("["); //$NON-NLS-1$
stb.append(this.voc.valueToString(this.tail));
stb.append("]"); //$NON-NLS-1$
return stb.toString();
}
/**
* Return the ith literal of the clause. Note that the order of the literals
* does change during the search...
*
* @param i
* the index of the literal
* @return the literal
*/
public int get(int i) {
if (i == 0) {
return this.head;
}
if (i == this.middleLits.length + 1) {
return this.tail;
}
return this.middleLits[i - 1];
}
/**
* @param d
*/
public void rescaleBy(double d) {
this.activity *= d;
}
public int size() {
return this.middleLits.length + 2;
}
public void assertConstraint(UnitPropagationListener s) {
assert this.voc.isUnassigned(this.head);
boolean ret = s.enqueue(this.head, this);
assert ret;
}
public void assertConstraintIfNeeded(UnitPropagationListener s) {
if (voc.isFalsified(this.tail)) {
boolean ret = s.enqueue(this.head, this);
assert ret;
}
}
public ILits getVocabulary() {
return this.voc;
}
public int[] getLits() {
int[] tmp = new int[size()];
System.arraycopy(this.middleLits, 0, tmp, 1, this.middleLits.length);
tmp[0] = this.head;
tmp[tmp.length - 1] = this.tail;
return tmp;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
try {
HTClause wcl = (HTClause) obj;
if (wcl.head != this.head || wcl.tail != this.tail) {
return false;
}
if (this.middleLits.length != wcl.middleLits.length) {
return false;
}
boolean ok;
for (int lit : this.middleLits) {
ok = false;
for (int lit2 : wcl.middleLits) {
if (lit == lit2) {
ok = true;
break;
}
}
if (!ok) {
return false;
}
}
return true;
} catch (ClassCastException e) {
return false;
}
}
@Override
public int hashCode() {
long sum = this.head + this.tail;
for (int p : this.middleLits) {
sum += p;
}
return (int) sum / this.middleLits.length;
}
public boolean canBePropagatedMultipleTimes() {
return false;
}
public Constr toConstraint() {
return this;
}
public void calcReasonOnTheFly(int p, IVecInt trail, IVecInt outReason) {
calcReason(p, outReason);
}
}
| mit |
TalkingData/flclover | test/middleware/logger.js | 1961 | const assert = require('power-assert');
const Flclover = require('../..');
const request = require('supertest');
const fs = require('fs');
const path = require('path');
const sleep = require('ko-sleep');
describe('test/middleware/logger.js', () => {
const baseDir = `${process.cwd()}/test/fixtures/logger`;
const logPath = path.join(`${baseDir}/logs`, 'app.log');
const errorLogPath = path.join(`${baseDir}/logs`, 'error.log');
const app = Flclover({ baseDir });
describe('ctx.logger.info', () => {
request(app.listen())
.get('/')
.end(() => {});
it('should exists file app.log', async () => {
await sleep('1s');
assert(fs.existsSync(logPath));
});
it('should includes home index in log file', async () => {
await sleep('1s');
const content = fs.readFileSync(logPath, 'utf8');
assert(content.match(/home index\n/));
});
});
describe('error', () => {
request(app.listen())
.get('/error')
.end(() => {});
it('should includes Error Stack', async () => {
await sleep('1s');
const content = fs.readFileSync(errorLogPath, 'utf8');
assert(content.match(/app\/controller\/home\.js/));
});
it('should includes Error boom', async () => {
await sleep('1s');
const content = fs.readFileSync(errorLogPath, 'utf8');
assert(content.match(/Error: boom/));
});
});
describe('warn', () => {
request(app.listen())
.get('/warn')
.end(() => {});
it('should includes warn msg', () => {
const content = fs.readFileSync(logPath, 'utf8');
assert(content.match(/warn msg\n/));
});
});
describe('debug', () => {
request(app.listen())
.get('/debug')
.end(() => {});
it('should includes debug msg', async () => {
await sleep('1s');
const content = fs.readFileSync(logPath, 'utf8');
// level: 'INFO',
assert(content.match(/debug msg\n/));
});
});
});
| mit |
coreos/raft | log_entry.go | 2077 | package raft
import (
"bytes"
"encoding/json"
"fmt"
"io"
"code.google.com/p/gogoprotobuf/proto"
"github.com/coreos/raft/protobuf"
)
// A log entry stores a single item in the log.
type LogEntry struct {
pb *protobuf.LogEntry
Position int64 // position in the log file
log *Log
event *ev
}
// Creates a new log entry associated with a log.
func newLogEntry(log *Log, event *ev, index uint64, term uint64, command Command) (*LogEntry, error) {
var buf bytes.Buffer
var commandName string
if command != nil {
commandName = command.CommandName()
if encoder, ok := command.(CommandEncoder); ok {
if err := encoder.Encode(&buf); err != nil {
return nil, err
}
} else {
json.NewEncoder(&buf).Encode(command)
}
}
pb := &protobuf.LogEntry{
Index: proto.Uint64(index),
Term: proto.Uint64(term),
CommandName: proto.String(commandName),
Command: buf.Bytes(),
}
e := &LogEntry{
pb: pb,
log: log,
event: event,
}
return e, nil
}
func (e *LogEntry) Index() uint64 {
return e.pb.GetIndex()
}
func (e *LogEntry) Term() uint64 {
return e.pb.GetTerm()
}
func (e *LogEntry) CommandName() string {
return e.pb.GetCommandName()
}
func (e *LogEntry) Command() []byte {
return e.pb.GetCommand()
}
// Encodes the log entry to a buffer. Returns the number of bytes
// written and any error that may have occurred.
func (e *LogEntry) Encode(w io.Writer) (int, error) {
b, err := proto.Marshal(e.pb)
if err != nil {
return -1, err
}
if _, err = fmt.Fprintf(w, "%8x\n", len(b)); err != nil {
return -1, err
}
return w.Write(b)
}
// Decodes the log entry from a buffer. Returns the number of bytes read and
// any error that occurs.
func (e *LogEntry) Decode(r io.Reader) (int, error) {
var length int
_, err := fmt.Fscanf(r, "%8x\n", &length)
if err != nil {
return -1, err
}
data := make([]byte, length)
_, err = io.ReadFull(r, data)
if err != nil {
return -1, err
}
if err = proto.Unmarshal(data, e.pb); err != nil {
return -1, err
}
return length + 8 + 1, nil
}
| mit |
nodes777/resumeGame | js/platformer.js | 15500 | var platformer = function () {
// module pattern
//-------------------------------------------------------------------------
// POLYFILLS
//-------------------------------------------------------------------------
if (!window.requestAnimationFrame) {
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimationFrame =
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback, element) {
window.setTimeout(callback, 1000 / 60);
};
}
//-------------------------------------------------------------------------
// UTILITIES
//-------------------------------------------------------------------------
function timestamp() {
return window.performance && window.performance.now
? window.performance.now()
: new Date().getTime();
}
function bound(x, min, max) {
return Math.max(min, Math.min(max, x));
}
function get(url, onsuccess) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) onsuccess(request);
};
request.open("GET", url, true);
request.send();
}
function overlap(x1, y1, w1, h1, x2, y2, w2, h2) {
return !(
x1 + w1 - 1 < x2 ||
x2 + w2 - 1 < x1 ||
y1 + h1 - 1 < y2 ||
y2 + h2 - 1 < y1
);
}
//-------------------------------------------------------------------------
// GAME CONSTANTS AND VARIABLES
//-------------------------------------------------------------------------
var MAP = {
tw: 64,
th: 48,
},
TILE = 32,
METER = TILE,
GRAVITY = 9.8 * 6, // default (exagerated) gravity
MAXDX = 15, // default max horizontal speed (15 tiles per second)
MAXDY = 60, // default max vertical speed (60 tiles per second)
ACCEL = 1 / 2, // default take 1/2 second to reach maxdx (horizontal acceleration)
FRICTION = 1 / 6, // default take 1/6 second to stop from maxdx (horizontal friction)
IMPULSE = 1500, // default player jump impulse
COLOR = {
BLACK: "#111111",
YELLOW: "#fffd98",
GREEN: "#40a000",
LIGHTGREEN: "#80e000",
BROWN: "#c06000",
DARKBROWN: "#602000",
BLUE: "#0006FF",
GOLD: "gold",
},
COLORS = [
COLOR.YELLOW,
COLOR.GREEN,
COLOR.BLACK,
COLOR.BROWN,
COLOR.DARKBROWN,
],
KEY = {
SPACE: 32,
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
};
var fps = 60,
step = 1 / fps,
canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
width = (canvas.width = MAP.tw * TILE),
height = (canvas.height = MAP.th * TILE),
player = {},
platforms = [],
cells = [];
var t2p = function (t) {
return t * TILE;
},
p2t = function (p) {
return Math.floor(p / TILE);
},
cell = function (x, y) {
return tcell(p2t(x), p2t(y));
},
tcell = function (tx, ty) {
return cells[tx + ty * MAP.tw];
};
var balls = [];
var coords = {};
var rect = document.getElementById("canvas").getBoundingClientRect();
var top = rect.top + document.body.scrollTop;
var left = rect.left + document.body.scrollLeft;
var platformDOs = [];
//-------------------------------------------------------------------------
// TAYLOR FUNCs
//-------------------------------------------------------------------------.
canvas.addEventListener("click", function (event) {
var x = event.pageX - left,
y = event.pageY - top;
coords.x = x;
coords.y = y;
var lastClicked = 4;
for (var i = 0; i < platforms.length; i++) {
if (
coords.y > platforms[i].clickY &&
coords.y < platforms[i].clickY + platforms[i].clickHeight &&
coords.x > platforms[i].clickX &&
coords.x < platforms[i].clickX + platforms[i].clickWidth
) {
fadeInT(platformDOs[i]);
platforms[i].clicked = true;
platforms[lastClicked].clicked = false;
lastClicked = i;
} else {
//platformDOs[i].fadeOut("slow");
platforms[i].clicked = false;
}
}
});
function fadeInT(el) {
if (el.classList.contains("hidden") || el.classList.contains("fadeOut")) {
el.classList.remove("hidden");
el.classList.remove("fadeOut");
el.classList.add("fadeIn");
}
}
function fadeOutT(el) {
if (el !== null) {
if (el.classList.contains("fadeIn")) {
el.classList.remove("fadeIn");
el.classList.add("fadeOut");
}
}
}
//-------------------------------------------------------------------------
// Explosion on ???
//-------------------------------------------------------------------------.
function Ball(x, y) {
this.x = x;
this.y = y;
this.x_speed = Math.floor(Math.random() * 10 + 1);
this.y_speed = Math.floor(Math.random() * 10 + 1);
this.radius = 5;
}
/* Create Ball methods*/
Ball.prototype.render = function () {
/*Put "pen" down on canvas*/
ctx.beginPath();
/*Draw an arc starting at the x and y, using the radius, and the angle in radians, Counter Clockwise is false*/
ctx.arc(this.x, this.y, this.radius, 2 * Math.PI, false);
ctx.fillStyle = "white";
ctx.fill();
};
function renderBalls() {
for (var i = 0; i < balls.length; i++) {
balls[i].render();
}
}
function updateBalls() {
for (var i = 0; i < balls.length; i++) {
balls[i].x += balls[i].x_speed;
balls[i].y += balls[i].y_speed;
if (balls[i].x > width || balls[i].y > height) {
balls.splice(i, 1);
}
}
}
function spawnBalls() {
if (balls.length < 100) {
var ball = new Ball(100, 200);
balls.push(ball);
}
}
//-------------------------------------------------------------------------
// UPDATE LOOP
//-------------------------------------------------------------------------
function onkey(ev, key, down) {
switch (key) {
case KEY.LEFT:
player.left = down;
ev.preventDefault();
return false;
case KEY.RIGHT:
player.right = down;
ev.preventDefault();
return false;
case KEY.SPACE:
player.jump = down;
ev.preventDefault();
return false;
}
}
function update(dt) {
updatePlayer(dt);
checkPlatforms(player);
updateBalls();
}
function updatePlayer(dt) {
updateEntity(player, dt);
}
function updateEntity(entity, dt) {
var wasleft = entity.dx < 0,
wasright = entity.dx > 0,
falling = entity.falling,
friction = entity.friction * (falling ? 0.5 : 1),
accel = entity.accel * (falling ? 0.5 : 1);
entity.ddx = 0;
entity.ddy = entity.gravity;
if (entity.left) entity.ddx = entity.ddx - accel;
else if (wasleft) entity.ddx = entity.ddx + friction;
if (entity.right) entity.ddx = entity.ddx + accel;
else if (wasright) entity.ddx = entity.ddx - friction;
if (entity.jump && !entity.jumping && !falling) {
entity.ddy = entity.ddy - entity.impulse; // an instant big force impulse
entity.jumping = true;
}
entity.x = entity.x + dt * entity.dx;
entity.y = entity.y + dt * entity.dy;
entity.dx = bound(entity.dx + dt * entity.ddx, -entity.maxdx, entity.maxdx);
entity.dy = bound(entity.dy + dt * entity.ddy, -entity.maxdy, entity.maxdy);
if ((wasleft && entity.dx > 0) || (wasright && entity.dx < 0)) {
entity.dx = 0; // clamp at zero to prevent friction from making us jiggle side to side
}
var tx = p2t(entity.x),
ty = p2t(entity.y),
nx = entity.x % TILE,
ny = entity.y % TILE,
cell = tcell(tx, ty),
cellright = tcell(tx + 1, ty),
celldown = tcell(tx, ty + 1),
celldiag = tcell(tx + 1, ty + 1);
if (entity.dy > 0) {
if ((celldown && !cell) || (celldiag && !cellright && nx)) {
entity.y = t2p(ty);
entity.dy = 0;
entity.falling = false;
entity.jumping = false;
ny = 0;
}
} else if (entity.dy < 0) {
if ((cell && !celldown) || (cellright && !celldiag && nx)) {
entity.y = t2p(ty + 1);
entity.dy = 0;
cell = celldown;
cellright = celldiag;
ny = 0;
}
}
if (entity.dx > 0) {
if ((cellright && !cell) || (celldiag && !celldown && ny)) {
entity.x = t2p(tx);
entity.dx = 0;
}
} else if (entity.dx < 0) {
if ((cell && !cellright) || (celldown && !celldiag && ny)) {
entity.x = t2p(tx + 1);
entity.dx = 0;
}
}
entity.falling = !(celldown || (nx && celldiag));
}
function checkPlatforms(entity) {
//Fade in for overlap or click
for (n = 0; n < platforms.length; n++) {
var entityOverLappingPlatform = overlap(
entity.x,
entity.y,
TILE,
TILE,
platforms[n].start.x,
platforms[n].start.y,
platforms[n].width,
platforms[n].height
);
if (entityOverLappingPlatform) {
fadeInT(platformDOs[n]);
if (n == 4) {
//If you stand on the ??? platform
spawnBalls();
}
//focus on that element so you can tab around on it
platformDOs[n].focus();
}
if (!entityOverLappingPlatform && platforms[n].clicked === false) {
fadeOutT(platformDOs[n]);
if (platformDOs[n]) {
platformDOs[n].blur();
}
}
if (!entityOverLappingPlatform && platforms[n].clicked === true) {
fadeInT(platformDOs[n]);
}
}
}
//-------------------------------------------------------------------------
// RENDERING
//-------------------------------------------------------------------------
function render(ctx, frame, dt) {
ctx.clearRect(0, 0, width, height);
//renderMap(ctx);
//renderHeadlines(platforms);
renderPlayer(ctx, dt);
renderBalls();
}
function renderMap(ctx) {
var x, y, cell;
for (y = 0; y < MAP.th; y++) {
for (x = 0; x < MAP.tw; x++) {
cell = tcell(x, y);
if (cell) {
ctx.fillStyle = COLORS[cell - 1];
ctx.fillRect(x * TILE, y * TILE, TILE, TILE);
}
}
}
}
function renderPlayer(ctx, dt) {
ctx.fillStyle = COLOR.BLUE;
ctx.fillRect(
player.x + player.dx * dt,
player.y + player.dy * dt,
TILE,
TILE
);
}
function renderHeadlines(plats) {
for (n = 0; n < plats.length; n++) {
cachedContext.font = "40px Titillium Web";
cachedContext.fillStyle = COLOR.YELLOW;
cachedContext.fillText(
plats[n].display,
plats[n].start.x,
plats[n].start.y + plats[n].height - 20
);
}
}
function drawMapOnce() {
// create and save the map image
mapCache = document.getElementById("canvas2");
cachedContext = mapCache.getContext("2d");
mapCache.width = canvas.width;
mapCache.height = canvas.height;
renderMap(cachedContext);
renderHeadlines(platforms);
ctx.drawImage(mapCache, 0, 0);
}
//-------------------------------------------------------------------------
// LOAD THE MAP
//-------------------------------------------------------------------------
var w = window.innerWidth;
var h = window.innerHeight;
function setup(map) {
var data = map.layers[0].data,
objects = map.layers[1].objects,
n,
obj,
entity;
for (n = 0; n < objects.length; n++) {
obj = objects[n];
entity = setupEntity(obj);
switch (obj.type) {
case "player":
player = entity;
break;
case "platform":
platforms.push(entity);
break;
}
}
//get the DOM objs to be accessed by jQuery fadeIn later
for (n = 0; n < platforms.length; n++) {
//platformDOs are a collection of jQuery objects right now
//doing getElementId causes fadeout to break because its expecting jquery objects
platformDOs.push(document.getElementById(platforms[n].id));
}
cells = data;
/*Scale the x, y and width and height of the platforms for clicking X and Y*/
var xsRatio = 2048 / 512;
var smRatio = 2048 / 640;
var mdRatio = 2048 / 768;
var lgRatio = 2048 / 896;
var xlRatio = 2048 / 1024;
for (var j = 0; j < platforms.length; j++) {
if (j === 4) {
/*skip the ??? platform, I don't want people to be able to click it*/
platforms[j].clickX = null;
platforms[j].clickY = null;
platforms[j].clickWidth = null;
platforms[j].clickHeight = null;
continue;
}
/*Set the clicking zone based on screen size*/
if (w <= 839 || h <= 529) {
platforms[j].clickX = platforms[j].x / xsRatio;
platforms[j].clickY = platforms[j].y / xsRatio;
platforms[j].clickWidth = platforms[j].width / xsRatio;
platforms[j].clickHeight = platforms[j].height / xsRatio;
} else if (w <= 967 || h <= 625) {
platforms[j].clickX = platforms[j].x / smRatio;
platforms[j].clickY = platforms[j].y / smRatio;
platforms[j].clickWidth = platforms[j].width / smRatio;
platforms[j].clickHeight = platforms[j].height / smRatio;
} else if (w <= 1095 || h <= 721) {
platforms[j].clickX = platforms[j].x / mdRatio;
platforms[j].clickY = platforms[j].y / mdRatio;
platforms[j].clickWidth = platforms[j].width / mdRatio;
platforms[j].clickHeight = platforms[j].height / mdRatio;
} else if (w <= 1223 || h <= 817) {
platforms[j].clickX = platforms[j].x / lgRatio;
platforms[j].clickY = platforms[j].y / lgRatio;
platforms[j].clickWidth = platforms[j].width / lgRatio;
platforms[j].clickHeight = platforms[j].height / lgRatio;
} else if (w > 1223 || h > 817) {
platforms[j].clickX = platforms[j].x / xlRatio;
platforms[j].clickY = platforms[j].y / xlRatio;
platforms[j].clickWidth = platforms[j].width / xlRatio;
platforms[j].clickHeight = platforms[j].height / xlRatio;
} else {
}
}
}
function setupEntity(obj) {
var entity = {};
entity.name = obj.name.charAt(0).toUpperCase() + obj.name.slice(1);
// Rewrote display and id because Tiled updated
entity.display = obj.properties[0].value;
// This is harder to read now, because properties is now an array and not an object
if (obj.properties.length > 1) {
entity.id = obj.properties[1].value;
}
entity.clicked = false;
entity.x = obj.x;
entity.y = obj.y;
entity.width = obj.width;
entity.height = obj.height;
entity.dx = 0;
entity.dy = 0;
entity.gravity = METER * (obj.properties.gravity || GRAVITY);
entity.maxdx = METER * (obj.properties.maxdx || MAXDX);
entity.maxdy = METER * (obj.properties.maxdy || MAXDY);
entity.impulse = METER * (obj.properties.impulse || IMPULSE);
entity.accel = entity.maxdx / (obj.properties.accel || ACCEL);
entity.friction = entity.maxdx / (obj.properties.friction || FRICTION);
entity.player = obj.type == "player";
entity.left = obj.properties.left;
entity.right = obj.properties.right;
entity.start = {
x: obj.x,
y: obj.y,
};
return entity;
}
//-------------------------------------------------------------------------
// THE GAME LOOP
//-------------------------------------------------------------------------
var counter = 0,
dt = 0,
now,
last = timestamp();
fpsmeter = new FPSMeter({
decimals: 0,
graph: true,
theme: "dark",
left: "5px",
});
function frame() {
fpsmeter.tickStart();
now = timestamp();
dt = dt + Math.min(1, (now - last) / 1000);
while (dt > step) {
dt = dt - step;
update(step);
}
render(ctx, counter, dt);
last = now;
counter++;
fpsmeter.tick();
requestAnimationFrame(frame);
}
document.addEventListener(
"keydown",
function (ev) {
return onkey(ev, ev.keyCode, true);
},
false
);
document.addEventListener(
"keyup",
function (ev) {
return onkey(ev, ev.keyCode, false);
},
false
);
/*AJAX call for map, when it's ready start the first frame*/
get("js/taylorMap2-23-2021.json", function (req) {
setup(JSON.parse(req.responseText));
drawMapOnce();
frame();
//pass in player data to the touch events file
touchFile(player);
});
};
platformer();
console.log("Hmmm, maybe try changing the background color to gray \n");
| mit |
yozora-hitagi/Saber | Saber/ReportWindow.xaml.cs | 2493 | using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
using Saber.Helper;
using Saber.Infrastructure;
using Saber.Infrastructure.Logger;
namespace Saber
{
internal partial class ReportWindow
{
public ReportWindow(Exception exception)
{
InitializeComponent();
ErrorTextbox.Document.Blocks.FirstBlock.Margin = new Thickness(0);
SetException(exception);
}
private void SetException(Exception exception)
{
string path = Path.Combine(Constant.DataDirectory, Log.DirectoryName, Constant.Version);
var directory = new DirectoryInfo(path);
var log = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
var paragraph = Hyperlink("Please open new issue in: ", Constant.Saber);
paragraph.Inlines.Add($"1. upload log file: {log.FullName}\n");
paragraph.Inlines.Add($"2. copy below exception message");
ErrorTextbox.Document.Blocks.Add(paragraph);
StringBuilder content = new StringBuilder();
content.AppendLine(ErrorReporting.RuntimeInfo());
content.AppendLine(ErrorReporting.DependenciesInfo());
content.AppendLine($"Date: {DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
content.AppendLine("Exception:");
content.AppendLine(exception.Source);
content.AppendLine(exception.GetType().ToString());
content.AppendLine(exception.Message);
content.AppendLine(exception.StackTrace);
paragraph = new Paragraph();
paragraph.Inlines.Add(content.ToString());
ErrorTextbox.Document.Blocks.Add(paragraph);
}
private Paragraph Hyperlink(string textBeforeUrl, string url)
{
var paragraph = new Paragraph();
paragraph.Margin = new Thickness(0);
var link = new Hyperlink { IsEnabled = true };
link.Inlines.Add(url);
link.NavigateUri = new Uri(url);
link.RequestNavigate += (s, e) => Process.Start(e.Uri.ToString());
link.Click += (s, e) => Process.Start(url);
paragraph.Inlines.Add(textBeforeUrl);
paragraph.Inlines.Add(link);
paragraph.Inlines.Add("\n");
return paragraph;
}
}
}
| mit |
sharifmarat/fortran_to_c_headers | include/other.hpp | 505 | #ifndef F2H_OTHER_HPP
#define F2H_OTHER_HPP
#include <boost/spirit/include/qi.hpp>
#include <vector>
#include "error_handler.hpp"
#include "skipper.hpp"
#include "ast.hpp"
namespace f2h
{
namespace qi = boost::spirit::qi;
template <typename Iterator>
struct Other : qi::grammar<Iterator, ast::Other(), Skipper<Iterator> >
{
Other(ErrorHandler<Iterator>& error_handler);
qi::rule<Iterator, ast::Other(), Skipper<Iterator> > expr;
qi::symbols<char> keywords;
};
}
#endif //F2H_OTHER_HPP
| mit |
schorfES/node-junitwriter | tests/testsuite.js | 12029 | var
Writer = require(process.cwd() + '/lib/Writer'),
Testsuite = require(process.cwd() + '/lib/Testsuite'),
Testcase = require(process.cwd() + '/lib/Testcase')
;
exports['The Testsuite'] = {
'should throw an error when instantiated without passing a name to the constructor': function(test) {
test.throws(
function() { new Testsuite(); },
'A testsuite requires a name',
'The constructor didn\'t fire any error'
);
test.done();
},
'should throw an error when instantiated without passing a parent testsuites option to the constructor': function(test) {
test.throws(
function() { new Testsuite('some name'); },
'A testsuite requires a parent node',
'The constructor didn\'t fire any error'
);
test.done();
},
'should contain a name and tests amount initially': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"/>',
'The testcase not correct formatted'
);
test.done();
},
'should add testcases': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename'),
caseA = suite.addTestcase('testA', 'TestA'),
caseB = suite.addTestcase('testB', 'TestB')
;
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="2"><testcase name="testA" classname="TestA"/><testcase name="testB" classname="TestB"/></testsuite>',
'The testcases are not added'
);
test.ok(
caseA instanceof Testcase,
'The returned case is not an instance of Testcase'
);
test.ok(
caseB instanceof Testcase,
'The returned case is not an instance of Testcase'
);
test.notEqual(
caseA,
caseB,
'The two testcases are the same instance'
);
test.done();
},
'should increase disabled amount': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.incDisabled();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" disabled="1"/>',
'The initial disabled amount is not correct'
);
suite.incDisabled(2);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" disabled="3"/>',
'The increased disabled amount is not correct'
);
test.done();
},
'should increase errors amount': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.incErrors();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" errors="1"/>',
'The initial errors amount is not correct'
);
suite.incErrors(2);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" errors="3"/>',
'The increased errors amount is not correct'
);
test.done();
},
'should increase failures amount': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.incFailures();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" failures="1"/>',
'The initial failures amount is not correct'
);
suite.incFailures(2);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" failures="3"/>',
'The increased failures amount is not correct'
);
test.done();
},
'should increase tests amount': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.incTests();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="1"/>',
'The initial tests amount is not correct'
);
suite.incTests(2);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="3"/>',
'The increased tests amount is not correct'
);
test.done();
},
'should set execution time in seconds of testsuite': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setTime(5);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" time="5"/>',
'The given time is not correct'
);
suite.setTime(200);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" time="200"/>',
'The given time was not overwritten'
);
test.done();
},
'should set name': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setName('foo');
test.equal(
suite.toString(),
'<testsuite name="foo" tests="0"/>',
'The given name is not correct'
);
test.done();
},
'should set timestamp': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename'),
date = new Date()
;
date.setUTCFullYear(2014);
date.setUTCMonth(0);
date.setUTCDate(21);
date.setUTCHours(16);
date.setUTCMinutes(17);
date.setUTCSeconds(18);
date.setUTCMilliseconds(19);
suite.setTimestamp(date);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" timestamp="2014-01-21T16:17:18"/>',
'The timestamp format is not the expeected one'
);
test.done();
},
'should fail when set timestamp without a valid date instance': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
test.throws(
function() {suite.setTimestamp('2014-01-21T16:17:18');},
'Timestamp must be an instance of Date',
'The function didn\'t throw an error when passing a string'
);
test.throws(
function() {suite.setTimestamp(20140121);},
'Timestamp must be an instance of Date',
'The function didn\'t throw an error when passing a number'
);
test.done();
},
'should set hostname': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setHostname('foobar.baz');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" hostname="foobar.baz"/>',
'The given hostname is not correct'
);
suite.setHostname('foo.baz.bar');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" hostname="foo.baz.bar"/>',
'The given hostname was not overwritten'
);
test.done();
},
'should set package': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setPackage('foo.bar.baz');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" package="foo.bar.baz"/>',
'The given package is not correct'
);
suite.setPackage('baz.bar.foo');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" package="baz.bar.foo"/>',
'The given package was not overwritten'
);
test.done();
},
'should set skipped tag': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSkipped(true);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><skipped/></testsuite>',
'The testsuite has no correct skipped tag'
);
test.done();
},
'should not set skipped tag twice': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSkipped(true);
suite.setSkipped(true);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><skipped/></testsuite>',
'The testsuite has multiple skipped tags'
);
test.done();
},
'should remove skipped tag when set to false': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSkipped(true);
suite.setSkipped(false);
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"/>',
'The testsuite still contains a skipped tag'
);
test.done();
},
'should toggle the attribute of the given ID': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.showId();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0" id="0"/>',
'The ID was not displayed'
);
suite.hideId();
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"/>',
'The ID was not removed correctly'
);
test.done();
},
'should add properties': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.addProperty('foo', 123);
suite.addProperty('bar', 'baz');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><properties><property name="foo" value="123"/><property name="bar" value="baz"/></properties></testsuite>',
'The properties are missing'
);
test.done();
},
'should remove properties completely': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.addProperty('foo', 123);
suite.addProperty('bar', 'baz');
suite.removeProperty('foo');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><properties><property name="bar" value="baz"/></properties></testsuite>',
'The properties are not removed correctly'
);
suite.removeProperty('bar');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"/>',
'The properties are not removed completely'
);
test.done();
},
'should update properties': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.addProperty('foo', 123);
suite.updateProperty('foo', 'bar');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><properties><property name="foo" value="bar"/></properties></testsuite>',
'The properties are not removed correctly'
);
test.done();
},
'should set system-out': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSystemOut('some system out');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><system-out>some system out</system-out></testsuite>',
'The system out is not displayed correctly'
);
test.done();
},
'should update system-out': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSystemOut('some system out');
suite.setSystemOut('some another system out');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><system-out>some another system out</system-out></testsuite>',
'The system out is not displayed correctly'
);
test.done();
},
'should set system-err': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSystemError('some system error');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><system-err>some system error</system-err></testsuite>',
'The system error is not displayed correctly'
);
test.done();
},
'should update system-err': function(test) {
var
writer = new Writer(),
suites = writer.getTestsuites(),
suite = suites.addTestsuite('suitename')
;
suite.setSystemError('some system error');
suite.setSystemError('some another system error');
test.equal(
suite.toString(),
'<testsuite name="suitename" tests="0"><system-err>some another system error</system-err></testsuite>',
'The system error is not displayed correctly'
);
test.done();
}
};
| mit |
Lukasa/testifi | testifi/__init__.py | 188 | # -*- coding: utf-8 -*-
"""
testifi
~~~~~~~
Testifi is software designed to test multiple certifi releases against many
TLS-enabled websites.
This module implements the testifi API.
"""
| mit |
hishammk/monthley.com | node_modules/browser-sync-client/dist/index.js | 48861 | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var socket = require("./socket");
var emitter = require("./emitter");
var notify = require("./notify");
var tab = require("./tab");
var utils = require("./browser.utils");
/**
* @constructor
*/
var BrowserSync = function (options) {
this.options = options;
this.socket = socket;
this.emitter = emitter;
this.utils = utils;
this.tabHidden = false;
var bs = this;
/**
* Options set
*/
socket.on("options:set", function (data) {
emitter.emit("notify", "Setting options...");
bs.options = data.options;
});
emitter.on("tab:hidden", function () {
bs.tabHidden = true;
});
emitter.on("tab:visible", function () {
bs.tabHidden = false;
});
};
/**
* Helper to check if syncing is allowed
* @param data
* @param optPath
* @returns {boolean}
*/
BrowserSync.prototype.canSync = function (data, optPath) {
data = data || {};
if (data.override) {
return true;
}
var canSync = true;
if (optPath) {
canSync = this.getOption(optPath);
}
return canSync && data.url === window.location.pathname;
};
/**
* Helper to check if syncing is allowed
* @returns {boolean}
*/
BrowserSync.prototype.getOption = function (path) {
if (path && path.match(/\./)) {
return getByPath(this.options, path);
} else {
var opt = this.options[path];
if (isUndefined(opt)) {
return false;
} else {
return opt;
}
}
};
/**
* @type {Function}
*/
module.exports = BrowserSync;
/**
* @param {String} val
* @returns {boolean}
*/
function isUndefined(val) {
return "undefined" === typeof val;
}
/**
* @param obj
* @param path
*/
function getByPath(obj, path) {
for(var i = 0, tempPath = path.split("."), len = tempPath.length; i < len; i++){
if(!obj || typeof obj !== "object") {
return false;
}
obj = obj[tempPath[i]];
}
if(typeof obj === "undefined") {
return false;
}
return obj;
}
},{"./browser.utils":2,"./emitter":5,"./notify":16,"./socket":17,"./tab":18}],2:[function(require,module,exports){
"use strict";
var utils = exports;
/**
* @returns {window}
*/
utils.getWindow = function () {
return window;
};
/**
* @returns {HTMLDocument}
*/
utils.getDocument = function () {
return document;
};
/**
* @returns {HTMLElement}
*/
utils.getBody = function () {
return document.getElementsByTagName("body")[0];
};
/**
* Get the current x/y position crossbow
* @returns {{x: *, y: *}}
*/
utils.getBrowserScrollPosition = function () {
var $window = exports.getWindow();
var $document = exports.getDocument();
var scrollX;
var scrollY;
var dElement = $document.documentElement;
var dBody = $document.body;
if ($window.pageYOffset !== undefined) {
scrollX = $window.pageXOffset;
scrollY = $window.pageYOffset;
} else {
scrollX = dElement.scrollLeft || dBody.scrollLeft || 0;
scrollY = dElement.scrollTop || dBody.scrollTop || 0;
}
return {
x: scrollX,
y: scrollY
};
};
/**
* @returns {{x: number, y: number}}
*/
utils.getScrollSpace = function () {
var $document = exports.getDocument();
var dElement = $document.documentElement;
var dBody = $document.body;
return {
x: dBody.scrollHeight - dElement.clientWidth,
y: dBody.scrollHeight - dElement.clientHeight
};
};
/**
* Saves scroll position into cookies
*/
utils.saveScrollPosition = function () {
var pos = utils.getBrowserScrollPosition();
pos = [pos.x, pos.y];
utils.getDocument.cookie = "bs_scroll_pos=" + pos.join(",");
};
/**
* Restores scroll position from cookies
*/
utils.restoreScrollPosition = function () {
var pos = utils.getDocument().cookie.replace(/(?:(?:^|.*;\s*)bs_scroll_pos\s*\=\s*([^;]*).*$)|^.*$/, "$1").split(",");
utils.getWindow().scrollTo(pos[0], pos[1]);
};
/**
* @param tagName
* @param elem
* @returns {*|number}
*/
utils.getElementIndex = function (tagName, elem) {
var allElems = utils.getDocument().getElementsByTagName(tagName);
return Array.prototype.indexOf.call(allElems, elem);
};
/**
* Force Change event on radio & checkboxes (IE)
*/
utils.forceChange = function (elem) {
elem.blur();
elem.focus();
};
/**
* @param elem
* @returns {{tagName: (elem.tagName|*), index: *}}
*/
utils.getElementData = function (elem) {
var tagName = elem.tagName;
var index = utils.getElementIndex(tagName, elem);
return {
tagName: tagName,
index: index
};
};
/**
* @param {string} tagName
* @param {number} index
*/
utils.getSingleElement = function (tagName, index) {
var elems = utils.getDocument().getElementsByTagName(tagName);
return elems[index];
};
/**
* Get the body element
*/
utils.getBody = function () {
return utils.getDocument().getElementsByTagName("body")[0];
};
/**
* @param {{x: number, y: number}} pos
*/
utils.setScroll = function (pos) {
utils.getWindow().scrollTo(pos.x, pos.y);
};
/**
* Hard reload
*/
utils.reloadBrowser = function () {
utils.getWindow().location.reload(true);
};
/**
* Foreach polyfill
* @param coll
* @param fn
*/
utils.forEach = function (coll, fn) {
for (var i = 0, n = coll.length; i < n; i += 1) {
fn(coll[i], i, coll);
}
};
/**
* Are we dealing with old IE?
* @returns {boolean}
*/
utils.isOldIe = function () {
return typeof utils.getWindow().attachEvent !== "undefined";
};
/**
* Split the URL information
* @returns {object}
*/
utils.getLocation = function (url) {
var location = utils.getDocument().createElement("a");
location.href = url;
if (location.host === "") {
location.href = location.href;
}
return location;
};
},{}],3:[function(require,module,exports){
if (!("indexOf" in Array.prototype)) {
Array.prototype.indexOf= function(find, i) {
if (i === undefined) {
i = 0;
}
if (i < 0) {
i += this.length;
}
if (i < 0) {
i= 0;
}
for (var n = this.length; i < n; i += 1) {
if (i in this && this[i]===find) {
return i;
}
}
return -1;
};
}
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
Array.prototype.map = function(callback, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling ToObject passing the |this|
// value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal
// method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callback) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array(len)
// where Array is the standard built-in constructor with that name and
// len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal
// method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal
// method of callback with T as the this value and argument
// list containing kValue, k, and O.
mappedValue = callback.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor
// { Value: mappedValue,
// Writable: true,
// Enumerable: true,
// Configurable: true },
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, k, {
// value: mappedValue,
// writable: true,
// enumerable: true,
// configurable: true
// });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun/*, thisArg*/) {
'use strict';
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== 'function') {
throw new TypeError();
}
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t)) {
res.push(val);
}
}
}
return res;
};
}
},{}],4:[function(require,module,exports){
"use strict";
var events = require("./events");
var utils = require("./browser.utils");
var emitter = require("./emitter");
var sync = exports;
var options = {
tagNames: {
"css": "link",
"jpg": "img",
"jpeg": "img",
"png": "img",
"svg": "img",
"gif": "img",
"js": "script"
},
attrs: {
"link": "href",
"img": "src",
"script": "src"
}
};
var hiddenElem;
var OPT_PATH = "codeSync";
var current = function () {
return window.location.pathname;
};
/**
* @param {BrowserSync} bs
*/
sync.init = function (bs) {
if (bs.options.tagNames) {
options.tagNames = bs.options.tagNames;
}
if (bs.options.scrollRestoreTechnique === "window.name") {
sync.saveScrollInName(emitter);
} else {
sync.saveScrollInCookie(utils.getWindow(), utils.getDocument());
}
bs.socket.on("file:reload", sync.reload(bs));
bs.socket.on("browser:reload", function () {
if (bs.canSync({url: current()}, OPT_PATH)) {
sync.reloadBrowser(true, bs);
}
});
};
/**
* Use window.name to store/restore scroll position
*/
sync.saveScrollInName = function () {
var PRE = "<<BS_START>>";
var SUF = "<<BS_END>>";
var regex = new RegExp(PRE + "(.+?)" + SUF);
var $window = utils.getWindow();
var saved = {};
/**
* Listen for the browser:hardReload event.
* When it runs, save the current scroll position
* in window.name
*/
emitter.on("browser:hardReload", function (data) {
var newname = [$window.name, PRE, JSON.stringify({
bs: {
hardReload: true,
scroll: data.scrollPosition
}
}), SUF].join("");
$window.name = newname;
});
/**
* On page load, check window.name for an existing
* BS json blob & parse it.
*/
try {
var json = $window.name.match(regex);
if (json) {
saved = JSON.parse(json[1]);
}
} catch (e) {
saved = {};
}
/**
* If the JSON was parsed correctly, try to
* find a scroll property and restore it.
*/
if (saved.bs && saved.bs.hardReload && saved.bs.scroll) {
utils.setScroll(saved.bs.scroll);
}
/**
* Remove any existing BS json from window.name
* to ensure we don't interfere with any other
* libs who may be using it.
*/
$window.name = $window.name.replace(regex, "");
};
/**
* Use a cookie-drop to save scroll position of
* @param $window
* @param $document
*/
sync.saveScrollInCookie = function ($window, $document) {
if (!utils.isOldIe()) {
return;
}
if ($document.readyState === "complete") {
utils.restoreScrollPosition();
} else {
events.manager.addEvent($document, "readystatechange", function() {
if ($document.readyState === "complete") {
utils.restoreScrollPosition();
}
});
}
emitter.on("browser:hardReload", utils.saveScrollPosition);
};
/**
* @param {string} search
* @param {string} key
* @param {string} suffix
*/
sync.updateSearch = function(search, key, suffix) {
if (search === "") {
return "?" + suffix;
}
return "?" + search
.slice(1)
.split("&")
.map(function (item) {
return item.split("=");
})
.filter(function (tuple) {
return tuple[0] !== key;
})
.map(function (item) {
return [item[0], item[1]].join("=");
})
.concat(suffix)
.join("&");
};
/**
* @param elem
* @param attr
* @param options
* @returns {{elem: HTMLElement, timeStamp: number}}
*/
sync.swapFile = function (elem, attr, options) {
var currentValue = elem[attr];
var timeStamp = new Date().getTime();
var key = "rel";
var suffix = key + "=" + timeStamp;
var anchor = utils.getLocation(currentValue);
var search = sync.updateSearch(anchor.search, key, suffix);
if (options.timestamps === false) {
elem[attr] = anchor.href;
} else {
elem[attr] = anchor.href.split("?")[0] + search;
}
var body = document.body;
setTimeout(function () {
if (!hiddenElem) {
hiddenElem = document.createElement("DIV");
body.appendChild(hiddenElem);
} else {
hiddenElem.style.display = "none";
hiddenElem.style.display = "block";
}
}, 200);
return {
elem: elem,
timeStamp: timeStamp
};
};
sync.getFilenameOnly = function (url) {
return /^[^\?]+(?=\?)/.exec(url);
};
/**
* @param {BrowserSync} bs
* @returns {*}
*/
sync.reload = function (bs) {
/**
* @param data - from socket
*/
return function (data) {
if (!bs.canSync({url: current()}, OPT_PATH)) {
return;
}
var transformedElem;
var options = bs.options;
var emitter = bs.emitter;
if (data.url || !options.injectChanges) {
sync.reloadBrowser(true);
}
if (data.basename && data.ext) {
var domData = sync.getElems(data.ext);
var elems = sync.getMatches(domData.elems, data.basename, domData.attr);
if (elems.length && options.notify) {
emitter.emit("notify", {message: "Injected: " + data.basename});
}
for (var i = 0, n = elems.length; i < n; i += 1) {
transformedElem = sync.swapFile(elems[i], domData.attr, options);
}
}
return transformedElem;
};
};
/**
* @param fileExtension
* @returns {*}
*/
sync.getTagName = function (fileExtension) {
return options.tagNames[fileExtension];
};
/**
* @param tagName
* @returns {*}
*/
sync.getAttr = function (tagName) {
return options.attrs[tagName];
};
/**
* @param elems
* @param url
* @param attr
* @returns {Array}
*/
sync.getMatches = function (elems, url, attr) {
if (url[0] === "*") {
return elems;
}
var matches = [];
var urlMatcher = new RegExp("(^|/)" + url);
for (var i = 0, len = elems.length; i < len; i += 1) {
if (urlMatcher.test(elems[i][attr])) {
matches.push(elems[i]);
}
}
return matches;
};
/**
* @param fileExtension
* @returns {{elems: NodeList, attr: *}}
*/
sync.getElems = function(fileExtension) {
var tagName = sync.getTagName(fileExtension);
var attr = sync.getAttr(tagName);
return {
elems: document.getElementsByTagName(tagName),
attr: attr
};
};
/**
* @param confirm
*/
sync.reloadBrowser = function (confirm) {
emitter.emit("browser:hardReload", {
scrollPosition: utils.getBrowserScrollPosition()
});
if (confirm) {
utils.reloadBrowser();
}
};
},{"./browser.utils":2,"./emitter":5,"./events":6}],5:[function(require,module,exports){
"use strict";
exports.events = {};
/**
* @param name
* @param data
*/
exports.emit = function (name, data) {
var event = exports.events[name];
var listeners;
if (event && event.listeners) {
listeners = event.listeners;
for (var i = 0, n = listeners.length; i < n; i += 1) {
listeners[i](data);
}
}
};
/**
* @param name
* @param func
*/
exports.on = function (name, func) {
var events = exports.events;
if (!events[name]) {
events[name] = {
listeners: [func]
};
} else {
events[name].listeners.push(func);
}
};
},{}],6:[function(require,module,exports){
exports._ElementCache = function () {
var cache = {},
guidCounter = 1,
expando = "data" + (new Date).getTime();
this.getData = function (elem) {
var guid = elem[expando];
if (!guid) {
guid = elem[expando] = guidCounter++;
cache[guid] = {};
}
return cache[guid];
};
this.removeData = function (elem) {
var guid = elem[expando];
if (!guid) return;
delete cache[guid];
try {
delete elem[expando];
}
catch (e) {
if (elem.removeAttribute) {
elem.removeAttribute(expando);
}
}
};
};
/**
* Fix an event
* @param event
* @returns {*}
*/
exports._fixEvent = function (event) {
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
if (!event || !event.stopPropagation) {
var old = event || window.event;
// Clone the old object so that we can modify the values
event = {};
for (var prop in old) {
event[prop] = old[prop];
}
// The event occurred on this element
if (!event.target) {
event.target = event.srcElement || document;
}
// Handle which other element the event is related to
event.relatedTarget = event.fromElement === event.target ?
event.toElement :
event.fromElement;
// Stop the default browser action
event.preventDefault = function () {
event.returnValue = false;
event.isDefaultPrevented = returnTrue;
};
event.isDefaultPrevented = returnFalse;
// Stop the event from bubbling
event.stopPropagation = function () {
event.cancelBubble = true;
event.isPropagationStopped = returnTrue;
};
event.isPropagationStopped = returnFalse;
// Stop the event from bubbling and executing other handlers
event.stopImmediatePropagation = function () {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
};
event.isImmediatePropagationStopped = returnFalse;
// Handle mouse position
if (event.clientX != null) {
var doc = document.documentElement, body = document.body;
event.pageX = event.clientX +
(doc && doc.scrollLeft || body && body.scrollLeft || 0) -
(doc && doc.clientLeft || body && body.clientLeft || 0);
event.pageY = event.clientY +
(doc && doc.scrollTop || body && body.scrollTop || 0) -
(doc && doc.clientTop || body && body.clientTop || 0);
}
// Handle key presses
event.which = event.charCode || event.keyCode;
// Fix button for mouse clicks:
// 0 == left; 1 == middle; 2 == right
if (event.button != null) {
event.button = (event.button & 1 ? 0 :
(event.button & 4 ? 1 :
(event.button & 2 ? 2 : 0)));
}
}
return event;
};
/**
* @constructor
*/
exports._EventManager = function (cache) {
var nextGuid = 1;
this.addEvent = function (elem, type, fn) {
var data = cache.getData(elem);
if (!data.handlers) data.handlers = {};
if (!data.handlers[type])
data.handlers[type] = [];
if (!fn.guid) fn.guid = nextGuid++;
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event) {
if (data.disabled) return;
event = exports._fixEvent(event);
var handlers = data.handlers[event.type];
if (handlers) {
for (var n = 0; n < handlers.length; n++) {
handlers[n].call(elem, event);
}
}
};
}
if (data.handlers[type].length == 1) {
if (document.addEventListener) {
elem.addEventListener(type, data.dispatcher, false);
}
else if (document.attachEvent) {
elem.attachEvent("on" + type, data.dispatcher);
}
}
};
function tidyUp(elem, type) {
function isEmpty(object) {
for (var prop in object) {
return false;
}
return true;
}
var data = cache.getData(elem);
if (data.handlers[type].length === 0) {
delete data.handlers[type];
if (document.removeEventListener) {
elem.removeEventListener(type, data.dispatcher, false);
}
else if (document.detachEvent) {
elem.detachEvent("on" + type, data.dispatcher);
}
}
if (isEmpty(data.handlers)) {
delete data.handlers;
delete data.dispatcher;
}
if (isEmpty(data)) {
cache.removeData(elem);
}
}
this.removeEvent = function (elem, type, fn) {
var data = cache.getData(elem);
if (!data.handlers) return;
var removeType = function (t) {
data.handlers[t] = [];
tidyUp(elem, t);
};
if (!type) {
for (var t in data.handlers) removeType(t);
return;
}
var handlers = data.handlers[type];
if (!handlers) return;
if (!fn) {
removeType(type);
return;
}
if (fn.guid) {
for (var n = 0; n < handlers.length; n++) {
if (handlers[n].guid === fn.guid) {
handlers.splice(n--, 1);
}
}
}
tidyUp(elem, type);
};
this.proxy = function (context, fn) {
if (!fn.guid) {
fn.guid = nextGuid++;
}
var ret = function () {
return fn.apply(context, arguments);
};
ret.guid = fn.guid;
return ret;
};
};
/**
* Trigger a click on an element
* @param elem
*/
exports.triggerClick = function (elem) {
var evObj;
if (document.createEvent) {
window.setTimeout(function () {
evObj = document.createEvent("MouseEvents");
evObj.initEvent("click", true, true);
elem.dispatchEvent(evObj);
}, 0);
} else {
window.setTimeout(function () {
if (document.createEventObject) {
evObj = document.createEventObject();
evObj.cancelBubble = true;
elem.fireEvent("on" + "click", evObj);
}
}, 0);
}
};
var cache = new exports._ElementCache();
var eventManager = new exports._EventManager(cache);
eventManager.triggerClick = exports.triggerClick;
exports.manager = eventManager;
},{}],7:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "click";
var OPT_PATH = "ghostMode.clicks";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
eventManager.addEvent(document.body, EVENT_NAME, exports.browserEvent(bs));
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* Uses event delegation to determine the clicked element
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
if (elem.type === "checkbox" || elem.type === "radio") {
bs.utils.forceChange(elem);
return;
}
bs.socket.emit(EVENT_NAME, bs.utils.getElementData(elem));
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @param {manager} eventManager
* @returns {Function}
*/
exports.socketEvent = function (bs, eventManager) {
return function (data) {
if (!bs.canSync(data, OPT_PATH) || bs.tabHidden) {
return false;
}
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
exports.canEmitEvents = false;
eventManager.triggerClick(elem);
}
};
};
},{}],8:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "input:text";
var OPT_PATH = "ghostMode.forms.inputs";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
eventManager.addEvent(document.body, "keyup", exports.browserEvent(bs));
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
var elem = event.target || event.srcElement;
var data;
if (exports.canEmitEvents) {
if (elem.tagName === "INPUT" || elem.tagName === "TEXTAREA") {
data = bs.utils.getElementData(elem);
data.value = elem.value;
bs.socket.emit(EVENT_NAME, data);
}
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
elem.value = data.value;
return elem;
}
return false;
};
};
},{}],9:[function(require,module,exports){
"use strict";
exports.plugins = {
"inputs": require("./ghostmode.forms.input"),
"toggles": require("./ghostmode.forms.toggles"),
"submit": require("./ghostmode.forms.submit")
};
/**
* Load plugins for enabled options
* @param bs
*/
exports.init = function (bs, eventManager) {
var checkOpt = true;
var options = bs.options.ghostMode.forms;
if (options === true) {
checkOpt = false;
}
function init(name) {
exports.plugins[name].init(bs, eventManager);
}
for (var name in exports.plugins) {
if (!checkOpt) {
init(name);
} else {
if (options[name]) {
init(name);
}
}
}
};
},{"./ghostmode.forms.input":8,"./ghostmode.forms.submit":10,"./ghostmode.forms.toggles":11}],10:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "form:submit";
var OPT_PATH = "ghostMode.forms.submit";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
var browserEvent = exports.browserEvent(bs);
eventManager.addEvent(document.body, "submit", browserEvent);
eventManager.addEvent(document.body, "reset", browserEvent);
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
var data = bs.utils.getElementData(elem);
data.type = event.type;
bs.socket.emit(EVENT_NAME, data);
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
var elem = bs.utils.getSingleElement(data.tagName, data.index);
exports.canEmitEvents = false;
if (elem && data.type === "submit") {
elem.submit();
}
if (elem && data.type === "reset") {
elem.reset();
}
return false;
};
};
},{}],11:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing clicks between browsers
* @type {string}
*/
var EVENT_NAME = "input:toggles";
var OPT_PATH = "ghostMode.forms.toggles";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
var browserEvent = exports.browserEvent(bs);
exports.addEvents(eventManager, browserEvent);
bs.socket.on(EVENT_NAME, exports.socketEvent(bs, eventManager));
};
/**
* @param eventManager
* @param event
*/
exports.addEvents = function (eventManager, event) {
var elems = document.getElementsByTagName("select");
var inputs = document.getElementsByTagName("input");
addEvents(elems);
addEvents(inputs);
function addEvents(domElems) {
for (var i = 0, n = domElems.length; i < n; i += 1) {
eventManager.addEvent(domElems[i], "change", event);
}
}
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.browserEvent = function (bs) {
return function (event) {
if (exports.canEmitEvents) {
var elem = event.target || event.srcElement;
var data;
if (elem.type === "radio" || elem.type === "checkbox" || elem.tagName === "SELECT") {
data = bs.utils.getElementData(elem);
data.type = elem.type;
data.value = elem.value;
data.checked = elem.checked;
bs.socket.emit(EVENT_NAME, data);
}
} else {
exports.canEmitEvents = true;
}
};
};
/**
* @param {BrowserSync} bs
* @returns {Function}
*/
exports.socketEvent = function (bs) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
exports.canEmitEvents = false;
var elem = bs.utils.getSingleElement(data.tagName, data.index);
if (elem) {
if (data.type === "radio") {
elem.checked = true;
}
if (data.type === "checkbox") {
elem.checked = data.checked;
}
if (data.tagName === "SELECT") {
elem.value = data.value;
}
return elem;
}
return false;
};
};
},{}],12:[function(require,module,exports){
"use strict";
var eventManager = require("./events").manager;
exports.plugins = {
"scroll": require("./ghostmode.scroll"),
"clicks": require("./ghostmode.clicks"),
"forms": require("./ghostmode.forms"),
"location": require("./ghostmode.location")
};
/**
* Load plugins for enabled options
* @param bs
*/
exports.init = function (bs) {
for (var name in exports.plugins) {
if (bs.options.ghostMode[name]) {
exports.plugins[name].init(bs, eventManager);
}
}
};
},{"./events":6,"./ghostmode.clicks":7,"./ghostmode.forms":9,"./ghostmode.location":13,"./ghostmode.scroll":14}],13:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing location
* @type {string}
*/
var EVENT_NAME = "browser:location";
var OPT_PATH = "ghostMode.location";
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
*/
exports.init = function (bs) {
bs.socket.on(EVENT_NAME, exports.socketEvent(bs));
};
/**
* Respond to socket event
*/
exports.socketEvent = function (bs) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
if (data.path) {
exports.setPath(data.path);
} else {
exports.setUrl(data.url);
}
};
};
/**
* @param url
*/
exports.setUrl = function (url) {
window.location = url;
};
/**
* @param path
*/
exports.setPath = function (path) {
window.location = window.location.protocol + "//" + window.location.host + path;
};
},{}],14:[function(require,module,exports){
"use strict";
/**
* This is the plugin for syncing scroll between devices
* @type {string}
*/
var WINDOW_EVENT_NAME = "scroll";
var ELEMENT_EVENT_NAME = "scroll:element";
var OPT_PATH = "ghostMode.scroll";
var utils;
exports.canEmitEvents = true;
/**
* @param {BrowserSync} bs
* @param eventManager
*/
exports.init = function (bs, eventManager) {
utils = bs.utils;
var opts = bs.options;
/**
* Window Scroll events
*/
eventManager.addEvent(window, WINDOW_EVENT_NAME, exports.browserEvent(bs));
bs.socket.on(WINDOW_EVENT_NAME, exports.socketEvent(bs));
/**
* element Scroll Events
*/
var cache = {};
addElementScrollEvents("scrollElements", false);
addElementScrollEvents("scrollElementMapping", true);
bs.socket.on(ELEMENT_EVENT_NAME, exports.socketEventForElement(bs, cache));
function addElementScrollEvents (key, map) {
if (!opts[key] || !opts[key].length || !("querySelectorAll" in document)) {
return;
}
utils.forEach(opts[key], function (selector) {
var elems = document.querySelectorAll(selector) || [];
utils.forEach(elems, function (elem) {
var data = utils.getElementData(elem);
data.cacheSelector = data.tagName + ":" + data.index;
data.map = map;
cache[data.cacheSelector] = elem;
eventManager.addEvent(elem, WINDOW_EVENT_NAME, exports.browserEventForElement(bs, elem, data));
});
});
}
};
/**
* @param {BrowserSync} bs
*/
exports.socketEvent = function (bs) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
var scrollSpace = utils.getScrollSpace();
exports.canEmitEvents = false;
if (bs.options && bs.options.scrollProportionally) {
return window.scrollTo(0, scrollSpace.y * data.position.proportional); // % of y axis of scroll to px
} else {
return window.scrollTo(0, data.position.raw.y);
}
};
};
/**
* @param bs
*/
exports.socketEventForElement = function (bs, cache) {
return function (data) {
if (!bs.canSync(data, OPT_PATH)) {
return false;
}
exports.canEmitEvents = false;
function scrollOne (selector, pos) {
if (cache[selector]) {
cache[selector].scrollTop = pos;
}
}
if (data.map) {
return Object.keys(cache).forEach(function (key) {
scrollOne(key, data.position);
});
}
scrollOne(data.elem.cacheSelector, data.position);
};
};
/**
* @param bs
*/
exports.browserEventForElement = function (bs, elem, data) {
return function () {
var canSync = exports.canEmitEvents;
if (canSync) {
bs.socket.emit(ELEMENT_EVENT_NAME, {
position: elem.scrollTop,
elem: data,
map: data.map
});
}
exports.canEmitEvents = true;
};
};
exports.browserEvent = function (bs) {
return function () {
var canSync = exports.canEmitEvents;
if (canSync) {
bs.socket.emit(WINDOW_EVENT_NAME, {
position: exports.getScrollPosition()
});
}
exports.canEmitEvents = true;
};
};
/**
* @returns {{raw: number, proportional: number}}
*/
exports.getScrollPosition = function () {
var pos = utils.getBrowserScrollPosition();
return {
raw: pos, // Get px of x and y axis of scroll
proportional: exports.getScrollTopPercentage(pos) // Get % of y axis of scroll
};
};
/**
* @param {{x: number, y: number}} scrollSpace
* @param scrollPosition
* @returns {{x: number, y: number}}
*/
exports.getScrollPercentage = function (scrollSpace, scrollPosition) {
var x = scrollPosition.x / scrollSpace.x;
var y = scrollPosition.y / scrollSpace.y;
return {
x: x || 0,
y: y
};
};
/**
* Get just the percentage of Y axis of scroll
* @returns {number}
*/
exports.getScrollTopPercentage = function (pos) {
var scrollSpace = utils.getScrollSpace();
var percentage = exports.getScrollPercentage(scrollSpace, pos);
return percentage.y;
};
},{}],15:[function(require,module,exports){
"use strict";
var socket = require("./socket");
var shims = require("./client-shims");
var notify = require("./notify");
var codeSync = require("./code-sync");
var BrowserSync = require("./browser-sync");
var ghostMode = require("./ghostmode");
var emitter = require("./emitter");
var events = require("./events");
var utils = require("./browser.utils");
var shouldReload = false;
var initialised = false;
/**
* @param options
*/
exports.init = function (options) {
if (shouldReload && options.reloadOnRestart) {
utils.reloadBrowser();
}
var BS = window.___browserSync___ || {};
if (!BS.client) {
BS.client = true;
var browserSync = new BrowserSync(options);
// Always init on page load
ghostMode.init(browserSync);
codeSync.init(browserSync);
notify.init(browserSync);
if (options.notify) {
notify.flash("Connected to BrowserSync");
}
}
if (!initialised) {
socket.on("disconnect", function () {
if (options.notify) {
notify.flash("Disconnected from BrowserSync");
}
shouldReload = true;
});
initialised = true;
}
};
/**
* Handle individual socket connections
*/
socket.on("connection", exports.init);
/**debug:start**/
if (window.__karma__) {
window.__bs_scroll__ = require("./ghostmode.scroll");
window.__bs_clicks__ = require("./ghostmode.clicks");
window.__bs_location__ = require("./ghostmode.location");
window.__bs_inputs__ = require("./ghostmode.forms.input");
window.__bs_toggles__ = require("./ghostmode.forms.toggles");
window.__bs_submit__ = require("./ghostmode.forms.submit");
window.__bs_forms__ = require("./ghostmode.forms");
window.__bs_utils__ = require("./browser.utils");
window.__bs_emitter__ = emitter;
window.__bs = BrowserSync;
window.__bs_notify__ = notify;
window.__bs_code_sync__ = codeSync;
window.__bs_ghost_mode__ = ghostMode;
window.__bs_socket__ = socket;
window.__bs_index__ = exports;
}
/**debug:end**/
},{"./browser-sync":1,"./browser.utils":2,"./client-shims":3,"./code-sync":4,"./emitter":5,"./events":6,"./ghostmode":12,"./ghostmode.clicks":7,"./ghostmode.forms":9,"./ghostmode.forms.input":8,"./ghostmode.forms.submit":10,"./ghostmode.forms.toggles":11,"./ghostmode.location":13,"./ghostmode.scroll":14,"./notify":16,"./socket":17}],16:[function(require,module,exports){
"use strict";
var scroll = require("./ghostmode.scroll");
var utils = require("./browser.utils");
var styles = {
display: "none",
padding: "15px",
fontFamily: "sans-serif",
position: "fixed",
fontSize: "0.9em",
zIndex: 9999,
right: 0,
top: 0,
borderBottomLeftRadius: "5px",
backgroundColor: "#1B2032",
margin: 0,
color: "white",
textAlign: "center"
};
var elem;
var options;
var timeoutInt;
/**
* @param {BrowserSync} bs
* @returns {*}
*/
exports.init = function (bs) {
options = bs.options;
var cssStyles = styles;
if (options.notify.styles) {
if (Object.prototype.toString.call(options.notify.styles) === "[object Array]") {
// handle original array behavior, replace all styles with a joined copy
cssStyles = options.notify.styles.join(";");
} else {
for (var key in options.notify.styles) {
if (options.notify.styles.hasOwnProperty(key)) {
cssStyles[key] = options.notify.styles[key];
}
}
}
}
elem = document.createElement("DIV");
elem.id = "__bs_notify__";
if (typeof cssStyles === "string") {
elem.style.cssText = cssStyles;
} else {
for (var rule in cssStyles) {
elem.style[rule] = cssStyles[rule];
}
}
var flashFn = exports.watchEvent(bs);
bs.emitter.on("notify", flashFn);
bs.socket.on("browser:notify", flashFn);
return elem;
};
/**
* @returns {Function}
*/
exports.watchEvent = function (bs) {
return function (data) {
if (bs.options.notify || data.override) {
if (typeof data === "string") {
return exports.flash(data);
}
exports.flash(data.message, data.timeout);
}
};
};
/**
*
*/
exports.getElem = function () {
return elem;
};
/**
* @param message
* @param [timeout]
* @returns {*}
*/
exports.flash = function (message, timeout) {
var elem = exports.getElem();
var $body = utils.getBody();
// return if notify was never initialised
if (!elem) {
return false;
}
elem.innerHTML = message;
elem.style.display = "block";
$body.appendChild(elem);
if (timeoutInt) {
clearTimeout(timeoutInt);
timeoutInt = undefined;
}
timeoutInt = window.setTimeout(function () {
elem.style.display = "none";
if (elem.parentNode) {
$body.removeChild(elem);
}
}, timeout || 2000);
return elem;
};
},{"./browser.utils":2,"./ghostmode.scroll":14}],17:[function(require,module,exports){
"use strict";
/**
* @type {{emit: emit, on: on}}
*/
var BS = window.___browserSync___ || {};
exports.socket = BS.socket || {
emit: function(){},
on: function(){}
};
/**
* @returns {string}
*/
exports.getPath = function () {
return window.location.pathname;
};
/**
* Alias for socket.emit
* @param name
* @param data
*/
exports.emit = function (name, data) {
var socket = exports.socket;
if (socket && socket.emit) {
// send relative path of where the event is sent
data.url = exports.getPath();
socket.emit(name, data);
}
};
/**
* Alias for socket.on
* @param name
* @param func
*/
exports.on = function (name, func) {
exports.socket.on(name, func);
};
},{}],18:[function(require,module,exports){
var utils = require("./browser.utils");
var emitter = require("./emitter");
var $document = utils.getDocument();
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof $document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof $document.mozHidden !== "undefined") {
hidden = "mozHidden";
visibilityChange = "mozvisibilitychange";
} else if (typeof $document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof $document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
// If the page is hidden, pause the video;
// if the page is shown, play the video
function handleVisibilityChange() {
if ($document[hidden]) {
emitter.emit("tab:hidden");
} else {
emitter.emit("tab:visible");
}
}
if (typeof $document.addEventListener === "undefined" ||
typeof $document[hidden] === "undefined") {
//console.log('not supported');
} else {
$document.addEventListener(visibilityChange, handleVisibilityChange, false);
}
},{"./browser.utils":2,"./emitter":5}]},{},[15]);
| mit |
110035/kissy | build/editor/plugin/smiley.js | 3969 | /*
Copyright 2013, KISSY UI Library v1.40dev
MIT Licensed
build time: Jul 3 13:54
*/
/*
Combined processedModules by KISSY Module Compiler:
editor/plugin/smiley
*/
/**
* smiley button
* @author yiminghe@gmail.com
*/
KISSY.add("editor/plugin/smiley", function (S, Editor, Overlay4E) {
var smiley_markup = "<div class='{prefixCls}editor-smiley-sprite'>";
for (var i = 0; i <= 98; i++) {
smiley_markup += "<a href='javascript:void(0)' " +
"data-icon='http://a.tbcdn.cn/sys/wangwang/smiley/48x48/" + i + ".gif'>" +
"</a>"
}
smiley_markup += "</div>";
function Smiley() {
}
S.augment(Smiley, {
pluginRenderUI: function (editor) {
var prefixCls = editor.get('prefixCls');
editor.addButton("smiley", {
tooltip: "插入表情",
checkable: true,
listeners: {
afterSyncUI: function () {
var self = this;
self.on("blur", function () {
// make click event fire
setTimeout(function () {
self.smiley && self.smiley.hide();
}, 150);
});
},
click: function () {
var self = this, smiley, checked = self.get("checked");
if (checked) {
if (!(smiley = self.smiley)) {
smiley = self.smiley = new Overlay4E({
content: S.substitute(smiley_markup, {
prefixCls: prefixCls
}),
focus4e: false,
width: 300,
elCls: prefixCls + "editor-popup",
zIndex: Editor.baseZIndex(Editor.zIndexManager.POPUP_MENU),
mask: false
}).render();
smiley.get("el").on("click", function (ev) {
var t = new S.Node(ev.target),
icon;
if (t.nodeName() == "a" &&
(icon = t.attr("data-icon"))) {
var img = new S.Node("<img " +
"alt='' src='" +
icon + "'/>", null,
editor.get("document")[0]);
editor.insertElement(img);
}
});
smiley.on("hide", function () {
self.set("checked", false);
});
}
smiley.set("align", {
node: this.get("el"),
points: ["bl", "tl"],
overflow: {
adjustX: 1,
adjustY: 1
}
});
smiley.show();
} else {
self.smiley && self.smiley.hide();
}
},
destroy: function () {
if (this.smiley) {
this.smiley.destroy();
}
}
},
mode: Editor.Mode.WYSIWYG_MODE
});
}
});
return Smiley;
}, {
requires: ['editor', './overlay']
});
| mit |
SesameSeed/SesameCoin | src/qt/locale/bitcoin_fa_IR.ts | 107291 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="fa_IR" version="2.0">
<defauSEEDodec>UTF-8</defauSEEDodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About SESAME</source>
<translation>در مورد بیتکویین</translation>
</message>
<message>
<location line="+39"/>
<source><b>SESAME</b> version</source>
<translation><b>SESAME</b> version</translation>
</message>
<message>
<location line="+57"/>
<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 (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The SESAME developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>دفترچه آدرس</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>برای ویرایش آدرس/برچسب دوبار کلیک نمایید</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>یک آدرس جدید بسازید</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>آدرس انتخاب شده را در کلیپ بوردِ سیستم کپی کنید</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>و آدرس جدید</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your SESAME 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 filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>و کپی آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>نشان و کد QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a SESAME address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified SESAME address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>و حذف</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your SESAME addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>کپی و برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>و ویرایش</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>انتقال اطلاعات دفترچه آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>سی.اس.وی. (فایل جداگانه دستوری)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>صدور پیام خطا</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی در فایل نیست %1</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(برچسب ندارد)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>رمز/پَس فرِیز را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>رمز/پَس فرِیز جدید را وارد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>رمز/پَس فرِیز را دوباره وارد کنید</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>رمز/پَس فرِیز جدید را در wallet وارد کنید. برای انتخاب رمز/پَس فرِیز از 10 کاراکتر تصادفی یا بیشتر و یا هشت کلمه یا بیشتر استفاده کنید. </translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>wallet را رمزگذاری کنید</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>برای انجام این عملکرد به رمز/پَس فرِیزِwallet نیاز است تا آن را از حالت قفل درآورد.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>باز کردن قفل wallet </translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>برای کشف رمز wallet، به رمز/پَس فرِیزِwallet نیاز است.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>کشف رمز wallet</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>رمز/پَس فرِیزِ قدیم و جدید را در wallet وارد کنید</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>رمزگذاری wallet را تایید کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SESAMES</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>تایید رمزگذاری</translation>
</message>
<message>
<location line="-56"/>
<source>SESAME will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your SESAMEs from being stolen by malware infecting your computer.</source>
<translation>SESAME برای اتمام فرایند رمزگذاری بسته خواهد شد. به خاطر داشته باشید که رمزگذاری WALLET شما، کامپیوتر شما را از آلودگی به بدافزارها مصون نمی دارد.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>رمزگذاری تایید نشد</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>رمزگذاری به علت خطای داخلی تایید نشد. wallet شما رمزگذاری نشد</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده با هم تطابق ندارند</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>قفل wallet باز نشد</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>رمزهای/پَس فرِیزهایِ وارد شده wallet برای کشف رمز اشتباه است.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>کشف رمز wallet انجام نشد</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>به روز رسانی با شبکه...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>و بازبینی</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>نمای کلی از wallet را نشان بده</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>و تراکنش</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>تاریخچه تراکنش را باز کن</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>فهرست آدرسها و برچسبهای ذخیره شده را ویرایش کن</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>فهرست آدرسها را برای دریافت وجه نشان بده</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>از "درخواست نامه"/ application خارج شو</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about SESAME</source>
<translation>اطلاعات در مورد SESAME را نشان بده</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>درباره و QT</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره QT</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>و انتخابها</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>و رمزگذاری wallet</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>و گرفتن نسخه پیشتیبان از wallet</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغییر رمز/پَس فرِیز</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a SESAME address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for SESAME</source>
<translation>اصلاح انتخابها برای پیکربندی SESAME</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>گرفتن نسخه پیشتیبان در آدرسی دیگر</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>رمز مربوط به رمزگذاریِ wallet را تغییر دهید</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>SESAME</source>
<translation>SESAME</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About SESAME</source>
<translation>&در مورد بیتکویین</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش و</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your SESAME addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified SESAME addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>و فایل</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>و تنظیمات</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>و راهنما</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>نوار ابزار</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>SESAME client</source>
<translation>مشتری SESAME</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to SESAME network</source>
<translation><numerusform>%n ارتباط فعال به شبکه SESAME
%n ارتباط فعال به شبکه SESAME</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<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="-140"/>
<source>Up to date</source>
<translation>روزآمد</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>در حال روزآمد سازی..</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>ارسال تراکنش</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>تراکنش دریافتی</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ: %1⏎ میزان وجه : %2⏎ نوع: %3⏎ آدرس: %4⏎
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid SESAME address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر از حالت قفل در آمده است</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>wallet رمزگذاری شد و در حال حاضر قفل است</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. SESAME can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>هشدار شبکه</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>ویرایش آدرسها</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>برچسب مربوط به این دفترچه آدرس</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>و آدرس</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>برچسب مربوط به این دفترچه آدرس و تنها ب</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>آدرسِ دریافت کننده جدید</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>آدرس ارسال کننده جدید</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>ویرایش آدرسِ دریافت کننده</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>ویرایش آدرسِ ارسال کننده</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>آدرس وارد شده %1 قبلا به فهرست آدرسها اضافه شده بوده است.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid SESAME address.</source>
<translation>آدرس وارد شده "%1" یک آدرس صحیح برای SESAME نسشت</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>عدم توانیی برای قفل گشایی wallet</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>عدم توانیی در ایجاد کلید جدید</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>SESAME-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</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 "de_DE" (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>انتخاب/آپشن</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</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.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start SESAME after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start SESAME on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the SESAME 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 &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the SESAME network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</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>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting SESAME.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show SESAME addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>و نمایش آدرسها در فهرست تراکنش</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>و تایید</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>و رد</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>و به کار گرفتن</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>پیش فرض</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<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 SESAME.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the SESAME network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده ممکن است روزآمد نباشد. wallet شما به صورت خودکار بعد از برقراری اتصال با شبکه SESAME به روز می شود اما این فرایند هنوز تکمیل نشده است.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>تایید نشده</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>کیف پول</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>تراکنشهای اخیر</translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>مانده حساب جاری</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>تعداد تراکنشهایی که نیاز به تایید دارند و هنوز در مانده حساب جاری شما به حساب نیامده اند</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>خارج از روزآمد سازی</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start SESAME: click-to-pay handler</source>
<translation type="unfinished"/>
</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>درخواست وجه</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>میزان وجه:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>برچسب:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>پیام:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>و ذخیره با عنوانِ...</translation>
</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>متن وارد شده طولانی است، متنِ برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>تصاویر با فرمت PNG
(*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</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="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the SESAME-Qt help message to get a list with possible SESAME command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>SESAME - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>SESAME Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the SESAME 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the SESAME RPC console.</source>
<translation>به کنسول آر.پی.سی. SESAME خوش آمدید</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>ارسال همزمان به گیرنده های متعدد</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>تمامی فیلدهای تراکنش حذف شوند</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>مانده حساب:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>تایید عملیات ارسال </translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>و ارسال</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation>%1 به %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>تایید ارسال سکه ها</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>شما مطمئن هستید که می خواهید %1 را ارسال کنید؟</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>و</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>میزان پرداخت باید بیشتر از 0 باشد</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</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>خطا: تراکنش تایید نشد. این خطا ممکن است به این دلیل اتفاق بیافتد که سکه های wallet شما خرج شده باشند مثلا اگر wallet.dat را مپی کرده باشید و سکه های شما در آن کپی استفاده شده باشند اما در اینجا نمایش داده نشده اند.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>فرم</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>و میزان وجه</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>پرداخت و به چه کسی</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>یک برچسب برای این آدرس بنویسید تا به دفترچه آدرسهای شما اضافه شود</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>و برچسب</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</translation>
</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>آدرس را بر کلیپ بورد کپی کنید</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>این گیرنده را حذف کن</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a SESAME address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس SESAME وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>و امضای پیام </translation>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس SESAME وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>آدرس از فهرست آدرس انتخاب کنید</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt و A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>آدرس را بر کلیپ بورد کپی کنید</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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this SESAME address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس SESAME وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified SESAME address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a SESAME address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>یک آدرس SESAME وارد کنید (مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter SESAME signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The SESAME developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1 غیرقابل تایید</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 تاییدها</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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 "not accepted" and it won'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 type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>تا به حال با موفقیت انتشار نیافته است</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ناشناس</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>جزئیات تراکنش</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>این بخش جزئیات تراکنش را نشان می دهد</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>میزان وجه</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>باز کن تا %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>برون خطی (%1 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>تایید نشده (%1 از %2 تاییدها)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1 تاییدها)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>این block توسط گره های دیگری دریافت نشده است و ممکن است قبول نشود</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>تولید شده اما قبول نشده است</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>قبول با </translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>دریافت شده از</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>وجه برای شما </translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>خالی</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت تراکنش. با اشاره به این بخش تعداد تاییدها نمایش داده می شود</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>زمان و تاریخی که تراکنش دریافت شده است</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>آدرس مقصد در تراکنش</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>میزان وجه کم شده یا اضافه شده به حساب</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>این سال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>حدود..</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>دریافت با</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>به شما</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>استخراج شده</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>دیگر</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>آدرس یا برچسب را برای جستجو وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>حداقل میزان وجه</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>آدرس را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>برچسب را کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>میزان وجه کپی شود</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>برچسب را ویرایش کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>داده های تراکنش را صادر کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv) فایل جداگانه دستوری</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>میزان</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>شناسه کاربری</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطا در ارسال</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>قابل کپی به فایل نیست %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>دامنه:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>سکه های ارسالی</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>صدور داده نوار جاری به یک فایل</translation>
</message>
<message>
<location line="+193"/>
<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>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>SESAME version</source>
<translation>نسخه SESAME</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>میزان استفاده:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or SESAMEd</source>
<translation>ارسال دستور به سرور یا SESAMEed</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>فهرست دستورها</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>درخواست کمک برای یک دستور</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>انتخابها:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: SESAME.conf)</source>
<translation>فایل پیکربندیِ را مشخص کنید (پیش فرض: SESAME.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: SESAMEd.pid)</source>
<translation>فایل pid را مشخص کنید (پیش فرض: SESAMEd.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>دایرکتوری داده را مشخص کن</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>حافظه بانک داده را به مگابایت تنظیم کنید (پیش فرض: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>ارتباطات را در <PORT> بشنوید (پیش فرض: 9333 or testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>نگهداری <N> ارتباطات برای قرینه سازی (پیش فرض:125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>آستانه قطع برای قرینه سازی اشتباه (پیش فرض:100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>تعداد ثانیه ها برای اتصال دوباره قرینه های اشتباه (پیش فرض:86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>ارتباطاتِ JSON-RPC را در <port> گوش کنید (پیش فرض:9332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>command line و JSON-RPC commands را قبول کنید</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>به عنوان daemon بک گراند را اجرا کنید و دستورات را قبول نمایید</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>از تستِ شبکه استفاده نمایید</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=SESAMErpc
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 "SESAME Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. SESAME is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<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="+3"/>
<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>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong SESAME will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>برونداد اشکال زدایی با timestamp</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the SESAME Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>ارسال اطلاعات پیگیری/خطایابی به کنسول به جای ارسال به فایل debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>ارسال اطاعات خطایابی/پیگیری به سیستم خطایاب</translation>
</message>
<message>
<location line="+5"/>
<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 type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>تعیین مدت زمان وقفه (time out) به هزارم ثانیه</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>شناسه کاربری برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>رمز برای ارتباطاتِ JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>ارتباطاتِ JSON-RPC را از آدرس آی.پی. مشخصی برقرار کنید.</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>دستورات را به گره اجرا شده در<ip> ارسال کنید (پیش فرض:127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>دستور را وقتی بهترین بلاک تغییر کرد اجرا کن (%s در دستور توسط block hash جایگزین شده است)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین نسخه روزآمد کنید</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>حجم key pool را به اندازه <n> تنظیم کنید (پیش فرض:100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>زنجیره بلاک را برای تراکنش جا افتاده در WALLET دوباره اسکن کنید</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>برای ارتباطاتِ JSON-RPC از OpenSSL (https) استفاده کنید</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>فایل certificate سرور (پیش فرض server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>رمز اختصاصی سرور (پیش فرض: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>ciphers قابل قبول (پیش فرض: default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>این پیام راهنما</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>لود شدن آدرسها..</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در هنگام لود شدن wallet.dat: Wallet corrupted</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of SESAME</source>
<translation>خطا در هنگام لود شدن wallet.dat. به نسخه جدید Bitocin برای wallet نیاز است.</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart SESAME to complete</source>
<translation>wallet نیاز به بازنویسی دارد. SESAME را برای تکمیل عملیات دوباره اجرا کنید.</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>خطا در هنگام لود شدن wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان اشتباه است for -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>میزان اشتباه است</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>وجوه ناکافی</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>لود شدن نمایه بلاکها..</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>یک گره برای اتصال اضافه کنید و تلاش کنید تا اتصال را باز نگاه دارید</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. SESAME is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>هزینه بر اساس کیلو بایت برای اضافه شدن به تراکنشی که ارسال کرده اید</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>wallet در حال لود شدن است...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>قابلیت برگشت به نسخه قبلی برای wallet امکان پذیر نیست</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>اسکنِ دوباره...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>اتمام لود شدن</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>برای استفاده از %s از اختیارات</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>خطا</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>شما باید یک رمز rpcpassword=<password> را در فایل تنظیمات ایجاد کنید⏎ %s ⏎ اگر فایل ایجاد نشده است، آن را با یک فایل "فقط متنی" ایجاد کنید.
</translation>
</message>
</context>
</TS> | mit |
SettRaziel/time_accounting | lib/menu/base_menu.rb | 2884 | # @Author: Benjamin Held
# @Date: 2017-01-29 09:24:31
# @Last Modified by: Benjamin Held
# @Last Modified time: 2017-01-29 09:26:23
module Menu
# This class provides the common methods of the different query menus
# The children need to define the method {Menu::Base.define_menu_items} and
# {Menu::Base.determine_action}. If the child class does not implement this
# method {Menu::Base} raises a NotImplementedError.
class Base
# initialization
# @param [String] description the headline of the menu
def initialize(description=nil)
@menu_items = Hash.new()
if (description == nil)
@menu_description = 'Default menu. Please add description: '
end
define_menu_items
@menu_items = Hash[@menu_items.sort]
end
# method to print the menu to the terminal and wait for input
def print_menu
isFinished = true
while (isFinished)
puts @menu_description
@menu_items.each_pair { |key, value|
puts "(#{key}) #{value}"
}
isFinished = determine_action(get_entry('Select option: '))
end
end
private
# @return [Hash] a hash which maps (number => string) for the menu items
attr :menu_items
# @return [String] a string with the head description of the menu
attr :menu_description
# @abstract subclasses need to implement this method
# @raise [NotImplementedError] if the subclass does not have this method
def define_menu_items
fail NotImplementedError, " Error: the subclass " \
"#{self.name.split('::').last} needs to implement the method: " \
"define_menu_items from its base class".red
end
# @abstract subclasses need to implement this method
# @param [String] input the provided user input
# @raise [NotImplementedError] if the subclass does not have this method
def determine_action(input)
fail NotImplementedError, " Error: the subclass " \
"#{self.name.split('::').last} needs to implement the method: " \
"determine_action from its base class".red
end
# default behavior when a user provides not valid input
def handle_wrong_option
print 'Option not available. '.red
determine_action(get_entry('Select option: '))
end
# method to add a given key/value pair to the menu hash
# @param [String] description the description of the menu item
# @param [Integer] index the index that should be used as key
def add_menu_item(description, index=nil)
index = @menu_items.length + 1 if (index == nil)
@menu_items[index] = description
end
# method to print a given message and read the provided input
# @param [String] message output message
# @return [String] the input from the terminal
def get_entry(message)
print message.blue.bright
gets.chomp
end
end
end
| mit |
zhzhy/cocoapods-generator | lib/cocoapods-generator.rb | 42 | require 'cocoapods-generator/gem_version'
| mit |
pomnikita/sneakers | spec/sneakers/workergroup_spec.rb | 1819 | require 'logger'
require 'spec_helper'
require 'sneakers'
require 'sneakers/runner'
class DummyFlag
def wait_for_set(*)
true
end
end
class DummyEngine
include Sneakers::WorkerGroup
attr_reader :config
def initialize(config)
@config = config
@stop_flag = DummyFlag.new
end
end
class DefaultsWorker
include Sneakers::Worker
from_queue 'defaults'
def work(msg); end
end
class StubbedWorker
attr_reader :opts
def initialize(_, _, opts)
@opts = opts
end
def run
true
end
end
describe Sneakers::WorkerGroup do
let(:logger) { Logger.new('logtest.log') }
let(:connection) { Bunny.new(host: 'any-host.local') }
let(:runner) { Sneakers::Runner.new([DefaultsWorker]) }
let(:runner_config) { runner.instance_variable_get('@runnerconfig') }
let(:config) { runner_config.reload_config! }
let(:engine) { DummyEngine.new(config) }
describe '#run' do
describe 'with connecion provided' do
before do
Sneakers.clear!
Sneakers.configure(connection: connection, log: logger)
end
it 'creates workers with connection: connection' do
DefaultsWorker.stub(:new, ->(*args) { StubbedWorker.new(*args) }) do
engine.run
workers = engine.instance_variable_get('@workers')
workers.first.opts[:connection].must_equal(connection)
end
end
end
describe 'without connecion provided' do
before do
Sneakers.clear!
Sneakers.configure(log: logger)
end
it 'creates workers with connection: nil' do
DefaultsWorker.stub(:new, ->(*args) { StubbedWorker.new(*args) }) do
engine.run
workers = engine.instance_variable_get('@workers')
assert_nil(workers.first.opts[:connection])
end
end
end
end
end
| mit |
eloquent/lockbox-java | src/main/java/co/lqnt/lockbox/BoundEncryptionCipher.java | 2170 | /*
* This file is part of the Lockbox package.
*
* Copyright © 2013 Erin Millard
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package co.lqnt.lockbox;
import co.lqnt.lockbox.key.PrivateKeyInterface;
import co.lqnt.lockbox.key.PublicKeyInterface;
/**
* The standard Lockbox encryption cipher, with a bound key.
*/
public class BoundEncryptionCipher implements BoundEncryptionCipherInterface
{
/**
* Construct a new bound encryption cipher.
*
* @param key The key to use.
*/
public BoundEncryptionCipher(final PublicKeyInterface key)
{
this(key, new EncryptionCipher());
}
/**
* Construct a new bound encryption cipher.
*
* @param key The key to use.
*/
public BoundEncryptionCipher(final PrivateKeyInterface key)
{
this(key.publicKey(), new EncryptionCipher());
}
/**
* Construct a new bound encryption cipher.
*
* @param key The key to use.
* @param cipher The cipher to use.
*/
public BoundEncryptionCipher(
final PublicKeyInterface key,
final EncryptionCipherInterface cipher
) {
this.key = key;
this.cipher = cipher;
}
/**
* Get the key.
*
* @return The key.
*/
public PublicKeyInterface key()
{
return this.key;
}
/**
* Get the cipher.
*
* @return The cipher.
*/
public EncryptionCipherInterface cipher()
{
return this.cipher;
}
/**
* Encrypt a data packet.
*
* @param data The data to encrypt.
*
* @return The encrypted data.
*/
public byte[] encrypt(final byte[] data)
{
return this.cipher().encrypt(this.key(), data);
}
/**
* Encrypt a data packet.
*
* @param data The data to encrypt.
*
* @return The encrypted data.
*/
public String encrypt(final String data)
{
return this.cipher().encrypt(this.key(), data);
}
private PublicKeyInterface key;
private EncryptionCipherInterface cipher;
}
| mit |
TildeWill/wurl | config/initializers/httparty/request.rb | 107 | require 'httparty'
module HTTParty
class Request
def to_s
@raw_request.to_s
end
end
end
| mit |
crr0004/godot | tools/editor/plugins/spatial_editor_plugin.cpp | 122895 | /*************************************************************************/
/* spatial_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/*************************************************************************/
#include "spatial_editor_plugin.h"
#include "print_string.h"
#include "os/keyboard.h"
#include "scene/3d/visual_instance.h"
#include "scene/3d/camera.h"
#include "camera_matrix.h"
#include "sort.h"
#include "tools/editor/editor_node.h"
#include "tools/editor/editor_settings.h"
#include "scene/resources/surface_tool.h"
#include "tools/editor/spatial_editor_gizmos.h"
#include "globals.h"
#include "tools/editor/plugins/animation_player_editor_plugin.h"
#include "tools/editor/animation_editor.h"
#define DISTANCE_DEFAULT 4
#define GIZMO_ARROW_SIZE 0.3
#define GIZMO_RING_HALF_WIDTH 0.1
//#define GIZMO_SCALE_DEFAULT 0.28
#define GIZMO_SCALE_DEFAULT 0.15
//void SpatialEditorViewport::_update_camera();
String SpatialEditorGizmo::get_handle_name(int p_idx) const {
return "";
}
Variant SpatialEditorGizmo::get_handle_value(int p_idx) const{
return Variant();
}
void SpatialEditorGizmo::set_handle(int p_idx,Camera *p_camera, const Point2& p_point) {
}
void SpatialEditorGizmo::commit_handle(int p_idx,const Variant& p_restore,bool p_cancel){
}
bool SpatialEditorGizmo::intersect_frustum(const Camera *p_camera,const Vector<Plane> &p_frustum) {
return false;
}
bool SpatialEditorGizmo::intersect_ray(const Camera *p_camera, const Point2 &p_point, Vector3& r_pos, Vector3& r_normal,int *r_gizmo_handle,bool p_sec_first) {
return false;
}
SpatialEditorGizmo::SpatialEditorGizmo(){
selected=false;
}
int SpatialEditorViewport::get_selected_count() const {
Map<Node*,Object*> &selection = editor_selection->get_selection();
int count=0;
for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->key()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
count++;
}
return count;
}
float SpatialEditorViewport::get_znear() const {
float val = spatial_editor->get_znear();
if (val<0.001)
val=0.001;
return val;
}
float SpatialEditorViewport::get_zfar() const{
float val = spatial_editor->get_zfar();
if (val<0.001)
val=0.001;
return val;
}
float SpatialEditorViewport::get_fov() const{
float val = spatial_editor->get_fov();
if (val<0.001)
val=0.001;
if (val>89)
val=89;
return val;
}
Transform SpatialEditorViewport::_get_camera_transform() const {
return camera->get_global_transform();
}
Vector3 SpatialEditorViewport::_get_camera_pos() const {
return _get_camera_transform().origin;
}
Point2 SpatialEditorViewport::_point_to_screen(const Vector3& p_point) {
return camera->unproject_position(p_point);
}
Vector3 SpatialEditorViewport::_get_ray_pos(const Vector2& p_pos) const {
return camera->project_ray_origin(p_pos);
}
Vector3 SpatialEditorViewport::_get_camera_normal() const {
return -_get_camera_transform().basis.get_axis(2);
}
Vector3 SpatialEditorViewport::_get_ray(const Vector2& p_pos) {
return camera->project_ray_normal(p_pos);
}
/*
void SpatialEditorViewport::_clear_id(Spatial *p_node) {
editor_selection->remove_node(p_node);
}
*/
void SpatialEditorViewport::_clear_selected() {
editor_selection->clear();
}
void SpatialEditorViewport::_select_clicked(bool p_append,bool p_single) {
if (!clicked)
return;
Object *obj = ObjectDB::get_instance(clicked);
if (!obj)
return;
Spatial *sp = obj->cast_to<Spatial>();
if (!sp)
return;
_select(sp, clicked_wants_append,true);
}
void SpatialEditorViewport::_select(Spatial *p_node, bool p_append,bool p_single) {
if (!p_append) {
// should not modify the selection..
editor_selection->clear();
editor_selection->add_node(p_node);
} else {
if (editor_selection->is_selected(p_node) && p_single) {
//erase
editor_selection->remove_node(p_node);
} else {
editor_selection->add_node(p_node);
}
}
}
ObjectID SpatialEditorViewport::_select_ray(const Point2& p_pos, bool p_append,bool &r_includes_current,int *r_gizmo_handle,bool p_alt_select) {
if (r_gizmo_handle)
*r_gizmo_handle=-1;
Vector3 ray=_get_ray(p_pos);
Vector3 pos=_get_ray_pos(p_pos);
Vector<RID> instances=VisualServer::get_singleton()->instances_cull_ray(pos,ray,get_tree()->get_root()->get_world()->get_scenario() );
Set<Ref<SpatialEditorGizmo> > found_gizmos;
//uint32_t closest=0;
// float closest_dist=0;
r_includes_current=false;
List<_RayResult> results;
Vector3 cn=_get_camera_normal();
Plane cplane(pos,cn.normalized());
float min_d=1e20;
for (int i=0;i<instances.size();i++) {
uint32_t id=VisualServer::get_singleton()->instance_get_object_instance_ID(instances[i]);
Object *obj=ObjectDB::get_instance(id);
if (!obj)
continue;
Spatial *spat=obj->cast_to<Spatial>();
if (!spat)
continue;
Ref<SpatialEditorGizmo> seg = spat->get_gizmo();
if (!seg.is_valid())
continue;
if (found_gizmos.has(seg))
continue;
found_gizmos.insert(seg);
Vector3 point;
Vector3 normal;
int handle=-1;
bool inters = seg->intersect_ray(camera,p_pos,point,normal,NULL,p_alt_select);
if (!inters)
continue;
float dist = pos.distance_to(point);
if (dist<0)
continue;
if (editor_selection->is_selected(spat))
r_includes_current=true;
_RayResult res;
res.item=spat;
res.depth=dist;
res.handle=handle;
results.push_back(res);
}
if (results.empty())
return 0;
results.sort();
Spatial *s=NULL;
if (!r_includes_current || results.size()==1 || (r_gizmo_handle && results.front()->get().handle>=0)) {
//return the nearest one
s = results.front()->get().item;
if (r_gizmo_handle)
*r_gizmo_handle=results.front()->get().handle;
} else {
//returns the next one from a curent selection
List<_RayResult>::Element *E=results.front();
List<_RayResult>::Element *S=NULL;
while(true) {
//very strange loop algorithm that complies with object selection standards (tm).
if (S==E) {
//went all around and anothing was found
//since can't rotate the selection
//just return the first one
s=results.front()->get().item;
break;
}
if (!S && editor_selection->is_selected(E->get().item)) {
//found an item currently in the selection,
//so start from this one
S=E;
}
if (S && !editor_selection->is_selected(E->get().item)) {
// free item after a selected item, this one is desired.
s=E->get().item;
break;
}
E=E->next();
if (!E) {
if (!S) {
//did a loop but nothing was selected, select first
s=results.front()->get().item;
break;
}
E=results.front();
}
}
}
if (!s)
return 0;
return s->get_instance_ID();
}
void SpatialEditorViewport::_find_items_at_pos(const Point2& p_pos,bool &r_includes_current,Vector<_RayResult> &results,bool p_alt_select) {
Vector3 ray=_get_ray(p_pos);
Vector3 pos=_get_ray_pos(p_pos);
Vector<RID> instances=VisualServer::get_singleton()->instances_cull_ray(pos,ray,get_tree()->get_root()->get_world()->get_scenario() );
Set<Ref<SpatialEditorGizmo> > found_gizmos;
r_includes_current=false;
for (int i=0;i<instances.size();i++) {
uint32_t id=VisualServer::get_singleton()->instance_get_object_instance_ID(instances[i]);
Object *obj=ObjectDB::get_instance(id);
if (!obj)
continue;
Spatial *spat=obj->cast_to<Spatial>();
if (!spat)
continue;
Ref<SpatialEditorGizmo> seg = spat->get_gizmo();
if (!seg.is_valid())
continue;
if (found_gizmos.has(seg))
continue;
found_gizmos.insert(seg);
Vector3 point;
Vector3 normal;
int handle=-1;
bool inters = seg->intersect_ray(camera,p_pos,point,normal,NULL,p_alt_select);
if (!inters)
continue;
float dist = pos.distance_to(point);
if (dist<0)
continue;
if (editor_selection->is_selected(spat))
r_includes_current=true;
_RayResult res;
res.item=spat;
res.depth=dist;
res.handle=handle;
results.push_back(res);
}
if (results.empty())
return;
results.sort();
}
Vector3 SpatialEditorViewport::_get_screen_to_space(const Vector3& p_pos) {
CameraMatrix cm;
cm.set_perspective(get_fov(),get_size().get_aspect(),get_znear(),get_zfar());
float screen_w,screen_h;
cm.get_viewport_size(screen_w,screen_h);
Transform camera_transform;
camera_transform.translate( cursor.pos );
camera_transform.basis.rotate(Vector3(0,1,0),cursor.y_rot);
camera_transform.basis.rotate(Vector3(1,0,0),cursor.x_rot);
camera_transform.translate(0,0,cursor.distance);
return camera_transform.xform(Vector3( ((p_pos.x/get_size().width)*2.0-1.0)*screen_w, ((1.0-(p_pos.y/get_size().height))*2.0-1.0)*screen_h,-get_znear()));
}
void SpatialEditorViewport::_select_region() {
if (cursor.region_begin==cursor.region_end)
return; //nothing really
Vector3 box[4]={
Vector3(
MIN( cursor.region_begin.x, cursor.region_end.x),
MIN( cursor.region_begin.y, cursor.region_end.y),
0
),
Vector3(
MAX( cursor.region_begin.x, cursor.region_end.x),
MIN( cursor.region_begin.y, cursor.region_end.y),
0
),
Vector3(
MAX( cursor.region_begin.x, cursor.region_end.x),
MAX( cursor.region_begin.y, cursor.region_end.y),
0
),
Vector3(
MIN( cursor.region_begin.x, cursor.region_end.x),
MAX( cursor.region_begin.y, cursor.region_end.y),
0
)
};
Vector<Plane> frustum;
Vector3 cam_pos=_get_camera_pos();
Set<Ref<SpatialEditorGizmo> > found_gizmos;
for(int i=0;i<4;i++) {
Vector3 a=_get_screen_to_space(box[i]);
Vector3 b=_get_screen_to_space(box[(i+1)%4]);
frustum.push_back( Plane(a,b,cam_pos) );
}
Plane near( cam_pos, -_get_camera_normal() );
near.d-=get_znear();
frustum.push_back( near );
Plane far=-near;
far.d+=500.0;
frustum.push_back( far );
Vector<RID> instances=VisualServer::get_singleton()->instances_cull_convex(frustum,get_tree()->get_root()->get_world()->get_scenario());
for (int i=0;i<instances.size();i++) {
uint32_t id=VisualServer::get_singleton()->instance_get_object_instance_ID(instances[i]);
Object *obj=ObjectDB::get_instance(id);
if (!obj)
continue;
Spatial *sp = obj->cast_to<Spatial>();
if (!sp)
continue;
Ref<SpatialEditorGizmo> seg = sp->get_gizmo();
if (!seg.is_valid())
continue;
if (found_gizmos.has(seg))
continue;
if (seg->intersect_frustum(camera,frustum))
_select(sp,true,false);
}
}
void SpatialEditorViewport::_update_name() {
String ortho = orthogonal?"Orthogonal":"Perspective";
if (name!="")
view_menu->set_text("[ "+name+" "+ortho+" ]");
else
view_menu->set_text("[ "+ortho+" ]");
}
void SpatialEditorViewport::_compute_edit(const Point2& p_point) {
_edit.click_ray=_get_ray( Vector2( p_point.x, p_point.y ) );
_edit.click_ray_pos=_get_ray_pos( Vector2( p_point.x, p_point.y ) );
_edit.plane=TRANSFORM_VIEW;
spatial_editor->update_transform_gizmo();
_edit.center=spatial_editor->get_gizmo_transform().origin;
List<Node*> &selection = editor_selection->get_selected_node_list();
// Vector3 center;
// int nc=0;
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
se->original=se->sp->get_global_transform();
// center+=se->original.origin;
// nc++;
}
// if (nc)
// _edit.center=center/float(nc);
}
static int _get_key_modifier(const String& p_property) {
switch(EditorSettings::get_singleton()->get(p_property).operator int()) {
case 0: return 0;
case 1: return KEY_SHIFT;
case 2: return KEY_ALT;
case 3: return KEY_META;
case 4: return KEY_CONTROL;
}
return 0;
}
SpatialEditorViewport::NavigationScheme SpatialEditorViewport::_get_navigation_schema(const String& p_property) {
switch(EditorSettings::get_singleton()->get(p_property).operator int()) {
case 0: return NAVIGATION_GODOT;
case 1: return NAVIGATION_MAYA;
case 2: return NAVIGATION_MODO;
}
return NAVIGATION_GODOT;
}
SpatialEditorViewport::NavigationZoomStyle SpatialEditorViewport::_get_navigation_zoom_style(const String& p_property) {
switch(EditorSettings::get_singleton()->get(p_property).operator int()) {
case 0: return NAVIGATION_ZOOM_VERTICAL;
case 1: return NAVIGATION_ZOOM_HORIZONTAL;
}
return NAVIGATION_ZOOM_VERTICAL;
}
bool SpatialEditorViewport::_gizmo_select(const Vector2& p_screenpos,bool p_hilite_only) {
if (!spatial_editor->is_gizmo_visible())
return false;
if (get_selected_count()==0) {
if (p_hilite_only)
spatial_editor->select_gizmo_hilight_axis(-1);
return false;
}
Vector3 ray_pos=_get_ray_pos( Vector2( p_screenpos.x, p_screenpos.y ) );
Vector3 ray=_get_ray( Vector2( p_screenpos.x, p_screenpos.y ) );
Vector3 cn=_get_camera_normal();
Plane cplane(ray_pos,cn.normalized());
Transform gt = spatial_editor->get_gizmo_transform();
float gs=gizmo_scale;
/*
if (orthogonal) {
gs= cursor.distance/surface->get_size().get_aspect();
} else {
gs = cplane.distance_to(gt.origin);
}
gs*=GIZMO_SCALE_DEFAULT;
*/
if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) {
int col_axis=-1;
float col_d=1e20;
for(int i=0;i<3;i++) {
Vector3 grabber_pos = gt.origin+gt.basis.get_axis(i)*gs;
float grabber_radius = gs*GIZMO_ARROW_SIZE;
Vector3 r;
if (Geometry::segment_intersects_sphere(ray_pos,ray_pos+ray*10000.0,grabber_pos,grabber_radius,&r)) {
float d = r.distance_to(ray_pos);
if (d<col_d) {
col_d=d;
col_axis=i;
}
}
}
if (col_axis!=-1) {
if (p_hilite_only) {
spatial_editor->select_gizmo_hilight_axis(col_axis);
} else {
//handle rotate
_edit.mode=TRANSFORM_TRANSLATE;
_compute_edit(Point2(p_screenpos.x,p_screenpos.y));
_edit.plane=TransformPlane(TRANSFORM_X_AXIS+col_axis);
}
return true;
}
}
if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) {
int col_axis=-1;
float col_d=1e20;
for(int i=0;i<3;i++) {
Plane plane(gt.origin,gt.basis.get_axis(i).normalized());
Vector3 r;
if (!plane.intersects_ray(ray_pos,ray,&r))
continue;
float dist = r.distance_to(gt.origin);
if (dist > gs*(1-GIZMO_RING_HALF_WIDTH) && dist < gs *(1+GIZMO_RING_HALF_WIDTH)) {
float d = ray_pos.distance_to(r);
if (d<col_d) {
col_d=d;
col_axis=i;
}
}
}
if (col_axis!=-1) {
if (p_hilite_only) {
spatial_editor->select_gizmo_hilight_axis(col_axis+3);
} else {
//handle rotate
_edit.mode=TRANSFORM_ROTATE;
_compute_edit(Point2(p_screenpos.x,p_screenpos.y));
_edit.plane=TransformPlane(TRANSFORM_X_AXIS+col_axis);
}
return true;
}
}
if (p_hilite_only)
spatial_editor->select_gizmo_hilight_axis(-1);
return false;
}
void SpatialEditorViewport::_smouseenter() {
if (!surface->has_focus() && (!get_focus_owner() || !get_focus_owner()->is_text_field()))
surface->grab_focus();
}
void SpatialEditorViewport::_list_select(InputEventMouseButton b) {
_find_items_at_pos(Vector2( b.x, b.y ),clicked_includes_current,selection_results,b.mod.shift);
Node *scene=editor->get_edited_scene();
for(int i=0;i<selection_results.size();i++) {
Spatial *item=selection_results[i].item;
if (item!=scene && item->get_owner()!=scene && !scene->is_editable_instance(item->get_owner())) {
//invalid result
selection_results.remove(i);
i--;
}
}
clicked_wants_append=b.mod.shift;
if (selection_results.size() == 1) {
clicked=selection_results[0].item->get_instance_ID();
selection_results.clear();
if (clicked) {
_select_clicked(clicked_wants_append,true);
clicked=0;
}
} else if (!selection_results.empty()) {
NodePath root_path = get_tree()->get_edited_scene_root()->get_path();
StringName root_name = root_path.get_name(root_path.get_name_count()-1);
for (int i = 0; i < selection_results.size(); i++) {
Spatial *spat=selection_results[i].item;
Ref<Texture> icon;
if (spat->has_meta("_editor_icon"))
icon=spat->get_meta("_editor_icon");
else
icon=get_icon( has_icon(spat->get_type(),"EditorIcons")?spat->get_type():String("Object"),"EditorIcons");
String node_path="/"+root_name+"/"+root_path.rel_path_to(spat->get_path());
selection_menu->add_item(spat->get_name());
selection_menu->set_item_icon(i, icon );
selection_menu->set_item_metadata(i, node_path);
selection_menu->set_item_tooltip(i,String(spat->get_name())+
"\nType: "+spat->get_type()+"\nPath: "+node_path);
}
selection_menu->set_global_pos(Vector2( b.global_x, b.global_y ));
selection_menu->popup();
selection_menu->call_deferred("grab_click_focus");
selection_menu->set_invalidate_click_until_motion();
}
}
void SpatialEditorViewport::_sinput(const InputEvent &p_event) {
if (previewing)
return; //do NONE
{
EditorNode *en = editor;
EditorPlugin *over_plugin = en->get_editor_plugin_over();
if (over_plugin) {
bool discard = over_plugin->forward_spatial_input_event(camera,p_event);
if (discard)
return;
}
}
switch(p_event.type) {
case InputEvent::MOUSE_BUTTON: {
const InputEventMouseButton &b=p_event.mouse_button;
switch(b.button_index) {
case BUTTON_WHEEL_UP: {
cursor.distance/=1.08;
if (cursor.distance<0.001)
cursor.distance=0.001;
} break;
case BUTTON_WHEEL_DOWN: {
if (cursor.distance<0.001)
cursor.distance=0.001;
cursor.distance*=1.08;
} break;
case BUTTON_RIGHT: {
NavigationScheme nav_scheme = _get_navigation_schema("3d_editor/navigation_scheme");
if (b.pressed && _edit.gizmo.is_valid()) {
//restore
_edit.gizmo->commit_handle(_edit.gizmo_handle,_edit.gizmo_initial_value,true);
_edit.gizmo=Ref<SpatialEditorGizmo>();
}
if (_edit.mode==TRANSFORM_NONE && b.pressed) {
Plane cursor_plane(cursor.cursor_pos,_get_camera_normal());
Vector3 ray_origin = _get_ray_pos(Vector2(b.x,b.y));
Vector3 ray_dir = _get_ray(Vector2(b.x,b.y));
//gizmo modify
if (b.mod.control) {
Vector<RID> instances=VisualServer::get_singleton()->instances_cull_ray(ray_origin,ray_dir,get_tree()->get_root()->get_world()->get_scenario() );
Plane p(ray_origin,_get_camera_normal());
float min_d=1e10;
bool found=false;
for (int i=0;i<instances.size();i++) {
uint32_t id=VisualServer::get_singleton()->instance_get_object_instance_ID(instances[i]);
Object *obj=ObjectDB::get_instance(id);
if (!obj)
continue;
VisualInstance *vi=obj->cast_to<VisualInstance>();
if (!vi)
continue;
//optimize by checking AABB (although should pre sort by distance)
AABB aabb = vi->get_global_transform().xform(vi->get_aabb());
if (p.distance_to(aabb.get_support(-ray_dir))>min_d)
continue;
DVector<Face3> faces = vi->get_faces(VisualInstance::FACES_SOLID);
int c = faces.size();
if (c>0) {
DVector<Face3>::Read r = faces.read();
for(int j=0;j<c;j++) {
Vector3 inters;
if (r[j].intersects_ray(ray_origin,ray_dir,&inters)) {
float d = p.distance_to(inters);
if (d<0)
continue;
if (d<min_d) {
min_d=d;
found=true;
}
}
}
}
}
if (found) {
//cursor.cursor_pos=ray_origin+ray_dir*min_d;
//VisualServer::get_singleton()->instance_set_transform(cursor_instance,Transform(Matrix3(),cursor.cursor_pos));
}
} else {
Vector3 new_pos;
if (cursor_plane.intersects_ray(ray_origin,ray_dir,&new_pos)) {
//cursor.cursor_pos=new_pos;
//VisualServer::get_singleton()->instance_set_transform(cursor_instance,Transform(Matrix3(),cursor.cursor_pos));
}
}
if (b.mod.alt) {
if (nav_scheme == NAVIGATION_MAYA)
break;
_list_select(b);
return;
}
}
if (_edit.mode!=TRANSFORM_NONE && b.pressed) {
//cancel motion
_edit.mode=TRANSFORM_NONE;
//_validate_selection();
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
sp->set_global_transform( se->original );
}
surface->update();
//VisualServer::get_singleton()->poly_clear(indicators);
set_message("Transform Aborted.",3);
}
} break;
case BUTTON_MIDDLE: {
if (b.pressed && _edit.mode!=TRANSFORM_NONE) {
switch(_edit.plane ) {
case TRANSFORM_VIEW: {
_edit.plane=TRANSFORM_X_AXIS;
set_message("View Plane Transform.",2);
name="";
_update_name();
} break;
case TRANSFORM_X_AXIS: {
_edit.plane=TRANSFORM_Y_AXIS;
set_message("X-Axis Transform.",2);
} break;
case TRANSFORM_Y_AXIS: {
_edit.plane=TRANSFORM_Z_AXIS;
set_message("Y-Axis Transform.",2);
} break;
case TRANSFORM_Z_AXIS: {
_edit.plane=TRANSFORM_VIEW;
set_message("Z-Axis Transform.",2);
} break;
}
}
} break;
case BUTTON_LEFT: {
if (b.pressed) {
NavigationScheme nav_scheme = _get_navigation_schema("3d_editor/navigation_scheme");
if ( (nav_scheme==NAVIGATION_MAYA || nav_scheme==NAVIGATION_MODO) && b.mod.alt) {
break;
}
if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_LIST_SELECT) {
_list_select(b);
break;
}
_edit.mouse_pos=Point2(b.x,b.y);
_edit.snap=false;
_edit.mode=TRANSFORM_NONE;
//gizmo has priority over everything
bool can_select_gizmos=true;
{
int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
can_select_gizmos = view_menu->get_popup()->is_item_checked( idx );
}
if (can_select_gizmos && spatial_editor->get_selected()) {
Ref<SpatialEditorGizmo> seg = spatial_editor->get_selected()->get_gizmo();
if (seg.is_valid()) {
int handle=-1;
Vector3 point;
Vector3 normal;
bool inters = seg->intersect_ray(camera,_edit.mouse_pos,point,normal,&handle,b.mod.shift);
if (inters && handle!=-1) {
_edit.gizmo=seg;
_edit.gizmo_handle=handle;
//_edit.gizmo_initial_pos=seg->get_handle_pos(gizmo_handle);
_edit.gizmo_initial_value=seg->get_handle_value(handle);
break;
}
}
}
if (_gizmo_select(_edit.mouse_pos))
break;
clicked=0;
clicked_includes_current=false;
if ((spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT && b.mod.control) || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) {
/* HANDLE ROTATION */
if (get_selected_count()==0)
break; //bye
//handle rotate
_edit.mode=TRANSFORM_ROTATE;
_compute_edit(Point2(b.x,b.y));
break;
}
if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) {
if (get_selected_count()==0)
break; //bye
//handle rotate
_edit.mode=TRANSFORM_TRANSLATE;
_compute_edit(Point2(b.x,b.y));
break;
}
if (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SCALE) {
if (get_selected_count()==0)
break; //bye
//handle rotate
_edit.mode=TRANSFORM_SCALE;
_compute_edit(Point2(b.x,b.y));
break;
}
// todo scale
int gizmo_handle=-1;
clicked=_select_ray(Vector2( b.x, b.y ),b.mod.shift,clicked_includes_current,&gizmo_handle,b.mod.shift);
//clicking is always deferred to either move or release
clicked_wants_append=b.mod.shift;
if (!clicked) {
if (!clicked_wants_append)
_clear_selected();
//default to regionselect
cursor.region_select=true;
cursor.region_begin=Point2(b.x,b.y);
cursor.region_end=Point2(b.x,b.y);
}
if (clicked && gizmo_handle>=0) {
Object *obj=ObjectDB::get_instance(clicked);
if (obj) {
Spatial *spa = obj->cast_to<Spatial>();
if (spa) {
Ref<SpatialEditorGizmo> seg=spa->get_gizmo();
if (seg.is_valid()) {
_edit.gizmo=seg;
_edit.gizmo_handle=gizmo_handle;
//_edit.gizmo_initial_pos=seg->get_handle_pos(gizmo_handle);
_edit.gizmo_initial_value=seg->get_handle_value(gizmo_handle);
//print_line("GIZMO: "+itos(gizmo_handle)+" FROMPOS: "+_edit.orig_gizmo_pos);
break;
}
}
}
//_compute_edit(Point2(b.x,b.y)); //in case a motion happens..
}
surface->update();
} else {
if (_edit.gizmo.is_valid()) {
_edit.gizmo->commit_handle(_edit.gizmo_handle,_edit.gizmo_initial_value,false);
_edit.gizmo=Ref<SpatialEditorGizmo>();
break;
}
if (clicked) {
_select_clicked(clicked_wants_append,true);
//clickd processing was deferred
clicked=0;
}
if (cursor.region_select) {
_select_region();
cursor.region_select=false;
surface->update();
}
if (_edit.mode!=TRANSFORM_NONE) {
static const char* _transform_name[4]={"None","Rotate","Translate","Scale"};
undo_redo->create_action(_transform_name[_edit.mode]);
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
undo_redo->add_do_method(sp,"set_global_transform",sp->get_global_transform());
undo_redo->add_undo_method(sp,"set_global_transform",se->original);
}
undo_redo->commit_action();
_edit.mode=TRANSFORM_NONE;
//VisualServer::get_singleton()->poly_clear(indicators);
set_message("");
}
surface->update();
}
} break;
}
} break;
case InputEvent::MOUSE_MOTION: {
const InputEventMouseMotion &m=p_event.mouse_motion;
_edit.mouse_pos=Point2(p_event.mouse_motion.x,p_event.mouse_motion.y);
if (spatial_editor->get_selected()) {
Ref<SpatialEditorGizmo> seg = spatial_editor->get_selected()->get_gizmo();
if (seg.is_valid()) {
int selected_handle=-1;
int handle=-1;
Vector3 point;
Vector3 normal;
bool inters = seg->intersect_ray(camera,_edit.mouse_pos,point,normal,&handle,false);
if (inters && handle!=-1) {
selected_handle=handle;
}
if (selected_handle!=spatial_editor->get_over_gizmo_handle()) {
spatial_editor->set_over_gizmo_handle(selected_handle);
spatial_editor->get_selected()->update_gizmo();
if (selected_handle!=-1)
spatial_editor->select_gizmo_hilight_axis(-1);
}
}
}
if (spatial_editor->get_over_gizmo_handle()==-1 && !(m.button_mask&1) && !_edit.gizmo.is_valid()) {
_gizmo_select(_edit.mouse_pos,true);
}
NavigationScheme nav_scheme = _get_navigation_schema("3d_editor/navigation_scheme");
NavigationMode nav_mode = NAVIGATION_NONE;
if (_edit.gizmo.is_valid()) {
Plane plane=Plane(_edit.gizmo_initial_pos,_get_camera_normal());
Vector3 ray_pos=_get_ray_pos( Vector2( m.x, m.y ) );
Vector3 ray=_get_ray( Vector2( m.x, m.y ) );
//Vector3 intersection;
//if (!plane.intersects_ray(ray_pos,ray,&intersection))
// break;
_edit.gizmo->set_handle(_edit.gizmo_handle,camera,Vector2(m.x,m.y));
Variant v = _edit.gizmo->get_handle_value(_edit.gizmo_handle);
String n = _edit.gizmo->get_handle_name(_edit.gizmo_handle);
set_message(n+": "+String(v));
} else if (m.button_mask&1) {
if (nav_scheme == NAVIGATION_MAYA && m.mod.alt) {
nav_mode = NAVIGATION_ORBIT;
} else if (nav_scheme == NAVIGATION_MODO && m.mod.alt && m.mod.shift) {
nav_mode = NAVIGATION_PAN;
} else if (nav_scheme == NAVIGATION_MODO && m.mod.alt && m.mod.control) {
nav_mode = NAVIGATION_ZOOM;
} else if (nav_scheme == NAVIGATION_MODO && m.mod.alt) {
nav_mode = NAVIGATION_ORBIT;
} else {
if (clicked) {
if (!clicked_includes_current) {
_select_clicked(clicked_wants_append,true);
//clickd processing was deferred
}
_compute_edit(_edit.mouse_pos);
clicked=0;
_edit.mode=TRANSFORM_TRANSLATE;
}
if (cursor.region_select && nav_mode == NAVIGATION_NONE) {
cursor.region_end=Point2(m.x,m.y);
surface->update();
return;
}
if (_edit.mode==TRANSFORM_NONE && nav_mode == NAVIGATION_NONE)
break;
Vector3 ray_pos=_get_ray_pos( Vector2( m.x, m.y ) );
Vector3 ray=_get_ray( Vector2( m.x, m.y ) );
switch(_edit.mode) {
case TRANSFORM_SCALE: {
Plane plane=Plane(_edit.center,_get_camera_normal());
Vector3 intersection;
if (!plane.intersects_ray(ray_pos,ray,&intersection))
break;
Vector3 click;
if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
break;
float center_click_dist = click.distance_to(_edit.center);
float center_inters_dist = intersection.distance_to(_edit.center);
if (center_click_dist==0)
break;
float scale = (center_inters_dist / center_click_dist)*100.0;
if (_edit.snap || spatial_editor->is_snap_enabled()) {
scale = Math::stepify(scale,spatial_editor->get_scale_snap());
}
set_message("Scaling to "+String::num(scale,1)+"%.");
scale/=100.0;
Transform r;
r.basis.scale(Vector3(scale,scale,scale));
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform original=se->original;
Transform base=Transform( Matrix3(), _edit.center);
Transform t=base * (r * (base.inverse() * original));
sp->set_global_transform(t);
}
surface->update();
} break;
case TRANSFORM_TRANSLATE: {
Vector3 motion_mask;
Plane plane;
switch( _edit.plane ) {
case TRANSFORM_VIEW:
motion_mask=Vector3(0,0,0);
plane=Plane(_edit.center,_get_camera_normal());
break;
case TRANSFORM_X_AXIS:
motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(0);
plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
break;
case TRANSFORM_Y_AXIS:
motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(1);
plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
break;
case TRANSFORM_Z_AXIS:
motion_mask=spatial_editor->get_gizmo_transform().basis.get_axis(2);
plane=Plane(_edit.center,motion_mask.cross(motion_mask.cross(_get_camera_normal())).normalized());
break;
}
Vector3 intersection;
if (!plane.intersects_ray(ray_pos,ray,&intersection))
break;
Vector3 click;
if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
break;
//_validate_selection();
Vector3 motion = intersection-click;
if (motion_mask!=Vector3()) {
motion=motion_mask.dot(motion)*motion_mask;
}
float snap=0;
if (_edit.snap || spatial_editor->is_snap_enabled()) {
snap = spatial_editor->get_translate_snap();
motion.snap(snap);
}
//set_message("Translating: "+motion);
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp) {
continue;
}
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se) {
continue;
}
Transform t=se->original;
t.origin+=motion;
sp->set_global_transform(t);
}
} break;
case TRANSFORM_ROTATE: {
Plane plane;
switch( _edit.plane ) {
case TRANSFORM_VIEW:
plane=Plane(_edit.center,_get_camera_normal());
break;
case TRANSFORM_X_AXIS:
plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(0));
break;
case TRANSFORM_Y_AXIS:
plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(1));
break;
case TRANSFORM_Z_AXIS:
plane=Plane(_edit.center,spatial_editor->get_gizmo_transform().basis.get_axis(2));
break;
}
Vector3 intersection;
if (!plane.intersects_ray(ray_pos,ray,&intersection))
break;
Vector3 click;
if (!plane.intersects_ray(_edit.click_ray_pos,_edit.click_ray,&click))
break;
Vector3 y_axis=(click-_edit.center).normalized();
Vector3 x_axis=plane.normal.cross(y_axis).normalized();
float angle=Math::atan2( x_axis.dot(intersection-_edit.center), y_axis.dot(intersection-_edit.center) );
if (_edit.snap || spatial_editor->is_snap_enabled()) {
float snap = spatial_editor->get_rotate_snap();
if (snap) {
angle=Math::rad2deg(angle)+snap*0.5; //else it wont reach +180
angle-=Math::fmod(angle,snap);
set_message("Rotating "+rtos(angle)+" degrees.");
angle=Math::deg2rad(angle);
} else
set_message("Rotating "+rtos(Math::rad2deg(angle))+" degrees.");
} else {
set_message("Rotating "+rtos(Math::rad2deg(angle))+" degrees.");
}
Transform r;
r.basis.rotate(plane.normal,-angle);
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform original=se->original;
Transform base=Transform( Matrix3(), _edit.center);
Transform t=base * (r * (base.inverse() * original));
sp->set_global_transform(t);
}
surface->update();
/*
VisualServer::get_singleton()->poly_clear(indicators);
Vector<Vector3> points;
Vector<Vector3> empty;
Vector<Color> colors;
points.push_back(intersection);
points.push_back(_edit.original.origin);
colors.push_back( Color(255,155,100) );
colors.push_back( Color(255,155,100) );
VisualServer::get_singleton()->poly_add_primitive(indicators,points,empty,colors,empty);
*/
} break;
default:{}
}
}
} else if (m.button_mask&2) {
if (nav_scheme == NAVIGATION_MAYA && m.mod.alt) {
nav_mode = NAVIGATION_ZOOM;
}
} else if (m.button_mask&4) {
if (nav_scheme == NAVIGATION_GODOT) {
int mod = 0;
if (m.mod.shift)
mod=KEY_SHIFT;
if (m.mod.alt)
mod=KEY_ALT;
if (m.mod.control)
mod=KEY_CONTROL;
if (m.mod.meta)
mod=KEY_META;
if (mod == _get_key_modifier("3d_editor/pan_modifier"))
nav_mode = NAVIGATION_PAN;
else if (mod == _get_key_modifier("3d_editor/zoom_modifier"))
nav_mode = NAVIGATION_ZOOM;
else if (mod == _get_key_modifier("3d_editor/orbit_modifier"))
nav_mode = NAVIGATION_ORBIT;
} else if (nav_scheme == NAVIGATION_MAYA) {
if (m.mod.alt)
nav_mode = NAVIGATION_PAN;
}
}
switch(nav_mode) {
case NAVIGATION_PAN:{
real_t pan_speed = 1/150.0;
int pan_speed_modifier = 10;
if (nav_scheme==NAVIGATION_MAYA && m.mod.shift)
pan_speed *= pan_speed_modifier;
Transform camera_transform;
camera_transform.translate(cursor.pos);
camera_transform.basis.rotate(Vector3(0,1,0),cursor.y_rot);
camera_transform.basis.rotate(Vector3(1,0,0),cursor.x_rot);
Vector3 translation(-m.relative_x*pan_speed,m.relative_y*pan_speed,0);
translation*=cursor.distance/DISTANCE_DEFAULT;
camera_transform.translate(translation);
cursor.pos=camera_transform.origin;
} break;
case NAVIGATION_ZOOM: {
real_t zoom_speed = 1/80.0;
int zoom_speed_modifier = 10;
if (nav_scheme==NAVIGATION_MAYA && m.mod.shift)
zoom_speed *= zoom_speed_modifier;
NavigationZoomStyle zoom_style = _get_navigation_zoom_style("3d_editor/zoom_style");
if (zoom_style == NAVIGATION_ZOOM_HORIZONTAL) {
if ( m.relative_x > 0)
cursor.distance*=1-m.relative_x*zoom_speed;
else if (m.relative_x < 0)
cursor.distance/=1+m.relative_x*zoom_speed;
}
else {
if ( m.relative_y > 0)
cursor.distance*=1+m.relative_y*zoom_speed;
else if (m.relative_y < 0)
cursor.distance/=1-m.relative_y*zoom_speed;
}
} break;
case NAVIGATION_ORBIT: {
cursor.x_rot+=m.relative_y/80.0;
cursor.y_rot+=m.relative_x/80.0;
if (cursor.x_rot>Math_PI/2.0)
cursor.x_rot=Math_PI/2.0;
if (cursor.x_rot<-Math_PI/2.0)
cursor.x_rot=-Math_PI/2.0;
name="";
_update_name();
} break;
default: {}
}
} break;
case InputEvent::KEY: {
const InputEventKey &k = p_event.key;
if (!k.pressed)
break;
switch(k.scancode) {
case KEY_S: {
if (_edit.mode!=TRANSFORM_NONE) {
_edit.snap=true;
}
} break;
case KEY_KP_7: {
cursor.y_rot=0;
if (k.mod.shift) {
cursor.x_rot=-Math_PI/2.0;
set_message("Bottom View.",2);
name="Bottom";
_update_name();
} else {
cursor.x_rot=Math_PI/2.0;
set_message("Top View.",2);
name="Top";
_update_name();
}
} break;
case KEY_KP_1: {
cursor.x_rot=0;
if (k.mod.shift) {
cursor.y_rot=Math_PI;
set_message("Rear View.",2);
name="Rear";
_update_name();
} else {
cursor.y_rot=0;
set_message("Front View.",2);
name="Front";
_update_name();
}
} break;
case KEY_KP_3: {
cursor.x_rot=0;
if (k.mod.shift) {
cursor.y_rot=Math_PI/2.0;
set_message("Left View.",2);
name="Left";
_update_name();
} else {
cursor.y_rot=-Math_PI/2.0;
set_message("Right View.",2);
name="Right";
_update_name();
}
} break;
case KEY_KP_5: {
//orthogonal = !orthogonal;
_menu_option(orthogonal?VIEW_PERSPECTIVE:VIEW_ORTHOGONAL);
_update_name();
} break;
case KEY_K: {
if (!get_selected_count() || _edit.mode!=TRANSFORM_NONE)
break;
if (!AnimationPlayerEditor::singleton->get_key_editor()->has_keying()) {
set_message("Keying is disabled (no key inserted).");
break;
}
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
emit_signal("transform_key_request",sp,"",sp->get_transform());
}
set_message("Animation Key Inserted.");
} break;
case KEY_F: {
if (k.pressed && k.mod.shift && k.mod.control) {
_menu_option(VIEW_ALIGN_SELECTION_WITH_VIEW);
} else if (k.pressed) {
_menu_option(VIEW_CENTER_TO_SELECTION);
}
} break;
case KEY_SPACE: {
if (!k.pressed)
emit_signal("toggle_maximize_view", this);
} break;
}
} break;
}
}
void SpatialEditorViewport::set_message(String p_message,float p_time) {
message=p_message;
message_time=p_time;
}
void SpatialEditorViewport::_notification(int p_what) {
if (p_what==NOTIFICATION_VISIBILITY_CHANGED) {
bool visible=is_visible();
set_process(visible);
call_deferred("update_transform_gizmo_view");
}
if (p_what==NOTIFICATION_RESIZED) {
call_deferred("update_transform_gizmo_view");
}
if (p_what==NOTIFICATION_PROCESS) {
//force editr camera
/*
current_camera=get_root_node()->get_current_camera();
if (current_camera!=camera) {
}
*/
if (orthogonal) {
Size2 size=get_size();
Size2 vpsize = Point2(cursor.distance*size.get_aspect(),cursor.distance/size.get_aspect());
//camera->set_orthogonal(size.width*cursor.distance,get_znear(),get_zfar());
camera->set_orthogonal(2*cursor.distance,0.1,8192);
} else
camera->set_perspective(get_fov(),get_znear(),get_zfar());
Transform camera_transform;
camera_transform.translate( cursor.pos );
camera_transform.basis.rotate(Vector3(0,1,0),cursor.y_rot);
camera_transform.basis.rotate(Vector3(1,0,0),cursor.x_rot);
if (orthogonal)
camera_transform.translate(0,0,4096);
else
camera_transform.translate(0,0,cursor.distance);
if (camera->get_global_transform()!=camera_transform) {
camera->set_global_transform( camera_transform );
update_transform_gizmo_view();
}
Map<Node*,Object*> &selection = editor_selection->get_selection();
bool changed=false;
bool exist=false;
for(Map<Node*,Object*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->key()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
/*
??
if (!se->poly_instance.is_valid())
continue;
if (!ObjectDB::get_instance( E->key() )) {
VisualServer::get_singleton()->free( se->poly_instance );
se->poly_instance=RID();
continue;
}
*/
VisualInstance *vi=sp->cast_to<VisualInstance>();
if (se->aabb.has_no_surface()) {
se->aabb=vi?vi->get_aabb():AABB( Vector3(-0.2,-0.2,-0.2),Vector3(0.4,0.4,0.4));
}
Transform t=sp->get_global_transform();
t.translate(se->aabb.pos);
t.basis.scale( se->aabb.size );
exist=true;
if (se->last_xform==t)
continue;
changed=true;
se->last_xform=t;
VisualServer::get_singleton()->instance_set_transform(se->sbox_instance,t);
}
if (changed || (spatial_editor->is_gizmo_visible() && !exist)) {
spatial_editor->update_transform_gizmo();
}
if (message_time>0) {
if (message!=last_message) {
surface->update();
last_message=message;
}
message_time-=get_fixed_process_delta_time();
if (message_time<0)
surface->update();
}
//grid
Vector3 grid_cam_axis=_get_camera_normal();
/*
for(int i=0;i<3;i++) {
Vector3 axis;
axis[i]=1;
bool should_be_visible= grid_enabled && (grid_enable[i] || (Math::abs(grid_cam_axis.dot(axis))>0.99 && orthogonal));
if (should_be_visible!=grid_visible[i]) {
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,should_be_visible);
grid_visible[i]=should_be_visible;
}
}
if (last_grid_snap!=spatial_editor->get_translate_snap()) {
last_grid_snap=spatial_editor->get_translate_snap()
Transform gridt;
gridt.basis.scale(Vector3(last_grid_snap,last_grid_snap,last_grid_snap));
for(int i=0;i<3;i++)
VisualServer::get_singleton()->instance_set_transform(grid_instance[i],gridt);
}*/
}
if (p_what==NOTIFICATION_ENTER_TREE) {
surface->connect("draw",this,"_draw");
surface->connect("input_event",this,"_sinput");
surface->connect("mouse_enter",this,"_smouseenter");
preview_camera->set_icon(get_icon("Camera","EditorIcons"));
_init_gizmo_instance(index);
}
if (p_what==NOTIFICATION_EXIT_TREE) {
_finish_gizmo_instances();
}
if (p_what==NOTIFICATION_MOUSE_ENTER) {
}
if (p_what==NOTIFICATION_DRAW) {
}
}
void SpatialEditorViewport::_draw() {
if (surface->has_focus()) {
Size2 size = surface->get_size();
Rect2 r =Rect2(Point2(),size);
get_stylebox("EditorFocus","EditorStyles")->draw(surface->get_canvas_item(),r);
}
RID ci=surface->get_canvas_item();
if (cursor.region_select) {
VisualServer::get_singleton()->canvas_item_add_rect(ci,Rect2(cursor.region_begin,cursor.region_end-cursor.region_begin),Color(0.7,0.7,1.0,0.3));
}
if (message_time>0) {
Ref<Font> font = get_font("font","Label");
Point2 msgpos=Point2(5,get_size().y-20);
font->draw(ci,msgpos+Point2(1,1),message,Color(0,0,0,0.8));
font->draw(ci,msgpos+Point2(-1,-1),message,Color(0,0,0,0.8));
font->draw(ci,msgpos,message,Color(1,1,1,1));
}
if (_edit.mode==TRANSFORM_ROTATE) {
Point2 center = _point_to_screen(_edit.center);
VisualServer::get_singleton()->canvas_item_add_line(ci,_edit.mouse_pos, center, Color(0.4,0.7,1.0,0.8));
}
if (previewing) {
Size2 ss = Size2( Globals::get_singleton()->get("display/width"), Globals::get_singleton()->get("display/height") );
float aspect = ss.get_aspect();
Size2 s = get_size();
Rect2 draw_rect;
switch(previewing->get_keep_aspect_mode()) {
case Camera::KEEP_WIDTH: {
draw_rect.size = Size2(s.width,s.width/aspect);
draw_rect.pos.x=0;
draw_rect.pos.y=(s.height-draw_rect.size.y)*0.5;
} break;
case Camera::KEEP_HEIGHT: {
draw_rect.size = Size2(s.height*aspect,s.height);
draw_rect.pos.y=0;
draw_rect.pos.x=(s.width-draw_rect.size.x)*0.5;
} break;
}
draw_rect = Rect2(Vector2(),s).clip(draw_rect);
surface->draw_line(draw_rect.pos,draw_rect.pos+Vector2(draw_rect.size.x,0),Color(0.6,0.6,0.1,0.5),2.0);
surface->draw_line(draw_rect.pos+Vector2(draw_rect.size.x,0),draw_rect.pos+draw_rect.size,Color(0.6,0.6,0.1,0.5),2.0);
surface->draw_line(draw_rect.pos+draw_rect.size,draw_rect.pos+Vector2(0,draw_rect.size.y),Color(0.6,0.6,0.1,0.5),2.0);
surface->draw_line(draw_rect.pos,draw_rect.pos+Vector2(0,draw_rect.size.y),Color(0.6,0.6,0.1,0.5),2.0);
}
}
void SpatialEditorViewport::_menu_option(int p_option) {
switch(p_option) {
case VIEW_TOP: {
cursor.x_rot=Math_PI/2.0;
cursor.y_rot=0;
name="Top";
_update_name();
} break;
case VIEW_BOTTOM: {
cursor.x_rot=-Math_PI/2.0;
cursor.y_rot=0;
name="Bottom";
_update_name();
} break;
case VIEW_LEFT: {
cursor.y_rot=Math_PI/2.0;
cursor.x_rot=0;
name="Left";
_update_name();
} break;
case VIEW_RIGHT: {
cursor.y_rot=-Math_PI/2.0;
cursor.x_rot=0;
name="Right";
_update_name();
} break;
case VIEW_FRONT: {
cursor.y_rot=0;
cursor.x_rot=0;
name="Front";
_update_name();
} break;
case VIEW_REAR: {
cursor.y_rot=Math_PI;
cursor.x_rot=0;
name="Rear";
_update_name();
} break;
case VIEW_CENTER_TO_SELECTION: {
if (!get_selected_count())
break;
Vector3 center;
int count=0;
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
center+=sp->get_global_transform().origin;
count++;
}
center/=float(count);
cursor.pos=center;
} break;
case VIEW_ALIGN_SELECTION_WITH_VIEW: {
if (!get_selected_count())
break;
Transform camera_transform = camera->get_global_transform();
List<Node*> &selection = editor_selection->get_selected_node_list();
undo_redo->create_action("Align with view");
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform xform = camera_transform;
xform.scale_basis(sp->get_scale());
undo_redo->add_do_method(sp,"set_global_transform",xform);
undo_redo->add_undo_method(sp,"set_global_transform",sp->get_global_transform());
}
undo_redo->commit_action();
} break;
case VIEW_ENVIRONMENT: {
int idx = view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT);
bool current = view_menu->get_popup()->is_item_checked( idx );
current=!current;
if (current) {
camera->set_environment(RES());
} else {
camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
}
view_menu->get_popup()->set_item_checked( idx, current );
} break;
case VIEW_PERSPECTIVE: {
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), false );
orthogonal=false;
call_deferred("update_transform_gizmo_view");
_update_name();
} break;
case VIEW_ORTHOGONAL: {
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ORTHOGONAL), true );
orthogonal=true;
call_deferred("update_transform_gizmo_view");
_update_name();
} break;
case VIEW_AUDIO_LISTENER: {
int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
bool current = view_menu->get_popup()->is_item_checked( idx );
current=!current;
viewport->set_as_audio_listener(current);
view_menu->get_popup()->set_item_checked( idx, current );
} break;
case VIEW_GIZMOS: {
int idx = view_menu->get_popup()->get_item_index(VIEW_GIZMOS);
bool current = view_menu->get_popup()->is_item_checked( idx );
current=!current;
if (current)
camera->set_visible_layers( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+index))|(1<<GIZMO_EDIT_LAYER)|(1<<GIZMO_GRID_LAYER) );
else
camera->set_visible_layers( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+index))|(1<<GIZMO_GRID_LAYER) );
view_menu->get_popup()->set_item_checked( idx, current );
} break;
}
}
void SpatialEditorViewport::_preview_exited_scene() {
preview_camera->set_pressed(false);
_toggle_camera_preview(false);
view_menu->show();
}
void SpatialEditorViewport::_init_gizmo_instance(int p_idx) {
uint32_t layer=1<<(GIZMO_BASE_LAYER+p_idx);//|(1<<GIZMO_GRID_LAYER);
for(int i=0;i<3;i++) {
move_gizmo_instance[i]=VS::get_singleton()->instance_create();
VS::get_singleton()->instance_set_base(move_gizmo_instance[i],spatial_editor->get_move_gizmo(i)->get_rid());
VS::get_singleton()->instance_set_scenario(move_gizmo_instance[i],get_tree()->get_root()->get_world()->get_scenario());
VS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i],VS::INSTANCE_FLAG_VISIBLE,false);
//VS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i],VS::INSTANCE_FLAG_DEPH_SCALE,true);
VS::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i],VS::INSTANCE_FLAG_CAST_SHADOW,false);
VS::get_singleton()->instance_set_layer_mask(move_gizmo_instance[i],layer);
rotate_gizmo_instance[i]=VS::get_singleton()->instance_create();
VS::get_singleton()->instance_set_base(rotate_gizmo_instance[i],spatial_editor->get_rotate_gizmo(i)->get_rid());
VS::get_singleton()->instance_set_scenario(rotate_gizmo_instance[i],get_tree()->get_root()->get_world()->get_scenario());
VS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i],VS::INSTANCE_FLAG_VISIBLE,false);
//VS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i],VS::INSTANCE_FLAG_DEPH_SCALE,true);
VS::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i],VS::INSTANCE_FLAG_CAST_SHADOW,false);
VS::get_singleton()->instance_set_layer_mask(rotate_gizmo_instance[i],layer);
}
}
void SpatialEditorViewport::_finish_gizmo_instances() {
for(int i=0;i<3;i++) {
VS::get_singleton()->free(move_gizmo_instance[i]);
VS::get_singleton()->free(rotate_gizmo_instance[i]);
}
}
void SpatialEditorViewport::_toggle_camera_preview(bool p_activate) {
ERR_FAIL_COND(p_activate && !preview);
ERR_FAIL_COND(!p_activate && !previewing);
if (!p_activate) {
previewing->disconnect("exit_tree",this,"_preview_exited_scene");
previewing=NULL;
VS::get_singleton()->viewport_attach_camera( viewport->get_viewport(), camera->get_camera() ); //restore
if (!preview)
preview_camera->hide();
view_menu->show();
surface->update();
} else {
previewing=preview;
previewing->connect("exit_tree",this,"_preview_exited_scene");
VS::get_singleton()->viewport_attach_camera( viewport->get_viewport(), preview->get_camera() ); //replace
view_menu->hide();
surface->update();
}
}
void SpatialEditorViewport::_selection_result_pressed(int p_result) {
if (selection_results.size() <= p_result)
return;
clicked=selection_results[p_result].item->get_instance_ID();
if (clicked) {
_select_clicked(clicked_wants_append,true);
clicked=0;
}
}
void SpatialEditorViewport::_selection_menu_hide() {
selection_results.clear();
selection_menu->clear();
selection_menu->set_size(Vector2(0, 0));
}
void SpatialEditorViewport::set_can_preview(Camera* p_preview) {
preview=p_preview;
if (!preview_camera->is_pressed()) {
if (p_preview) {
preview_camera->show();
} else {
preview_camera->hide();
}
}
}
void SpatialEditorViewport::update_transform_gizmo_view() {
if (!is_visible())
return;
Transform xform = spatial_editor->get_gizmo_transform();
Transform camera_xform = camera->get_transform();
Vector3 camz = -camera_xform.get_basis().get_axis(2).normalized();
Vector3 camy = -camera_xform.get_basis().get_axis(1).normalized();
Plane p(camera_xform.origin,camz);
float gizmo_d = Math::abs( p.distance_to(xform.origin ));
float d0 = camera->unproject_position(camera_xform.origin+camz*gizmo_d).y;
float d1 = camera->unproject_position(camera_xform.origin+camz*gizmo_d+camy).y;
float dd = Math::abs(d0-d1);
if (dd==0)
dd=0.0001;
float gsize = EditorSettings::get_singleton()->get("3d_editor/manipulator_gizmo_size");
gizmo_scale=(gsize/Math::abs(dd));
Vector3 scale = Vector3(1,1,1) * gizmo_scale;
xform.basis.scale(scale);
//xform.basis.scale(GIZMO_SCALE_DEFAULT*Vector3(1,1,1));
for(int i=0;i<3;i++) {
VisualServer::get_singleton()->instance_set_transform(move_gizmo_instance[i], xform );
VisualServer::get_singleton()->instance_geometry_set_flag(move_gizmo_instance[i],VS::INSTANCE_FLAG_VISIBLE,spatial_editor->is_gizmo_visible()&& (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_MOVE) );
VisualServer::get_singleton()->instance_set_transform(rotate_gizmo_instance[i], xform );
VisualServer::get_singleton()->instance_geometry_set_flag(rotate_gizmo_instance[i],VS::INSTANCE_FLAG_VISIBLE,spatial_editor->is_gizmo_visible() && (spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_SELECT || spatial_editor->get_tool_mode()==SpatialEditor::TOOL_MODE_ROTATE) );
}
}
void SpatialEditorViewport::set_state(const Dictionary& p_state) {
cursor.pos=p_state["pos"];
cursor.x_rot=p_state["x_rot"];
cursor.y_rot=p_state["y_rot"];
cursor.distance=p_state["distance"];
bool env = p_state["use_environment"];
bool orth = p_state["use_orthogonal"];
if (orth)
_menu_option(VIEW_ORTHOGONAL);
else
_menu_option(VIEW_PERSPECTIVE);
if (env != camera->get_environment().is_valid())
_menu_option(VIEW_ENVIRONMENT);
if (p_state.has("listener")) {
bool listener = p_state["listener"];
int idx = view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER);
viewport->set_as_audio_listener(listener);
view_menu->get_popup()->set_item_checked( idx, listener );
}
if (p_state.has("previewing")) {
Node *pv = EditorNode::get_singleton()->get_edited_scene()->get_node(p_state["previewing"]);
if (pv && pv->cast_to<Camera>()) {
previewing=pv->cast_to<Camera>();
previewing->connect("exit_tree",this,"_preview_exited_scene");
VS::get_singleton()->viewport_attach_camera( viewport->get_viewport(), previewing->get_camera() ); //replace
view_menu->hide();
surface->update();
preview_camera->set_pressed(true);
preview_camera->show();
}
}
}
Dictionary SpatialEditorViewport::get_state() const {
Dictionary d;
d["pos"]=cursor.pos;
d["x_rot"]=cursor.x_rot;
d["y_rot"]=cursor.y_rot;
d["distance"]=cursor.distance;
d["use_environment"]=camera->get_environment().is_valid();
d["use_orthogonal"]=camera->get_projection()==Camera::PROJECTION_ORTHOGONAL;
d["listener"]=viewport->is_audio_listener();
if (previewing) {
d["previewing"]=EditorNode::get_singleton()->get_edited_scene()->get_path_to(previewing);
}
return d;
}
void SpatialEditorViewport::_bind_methods(){
ObjectTypeDB::bind_method(_MD("_draw"),&SpatialEditorViewport::_draw);
ObjectTypeDB::bind_method(_MD("_smouseenter"),&SpatialEditorViewport::_smouseenter);
ObjectTypeDB::bind_method(_MD("_sinput"),&SpatialEditorViewport::_sinput);
ObjectTypeDB::bind_method(_MD("_menu_option"),&SpatialEditorViewport::_menu_option);
ObjectTypeDB::bind_method(_MD("_toggle_camera_preview"),&SpatialEditorViewport::_toggle_camera_preview);
ObjectTypeDB::bind_method(_MD("_preview_exited_scene"),&SpatialEditorViewport::_preview_exited_scene);
ObjectTypeDB::bind_method(_MD("update_transform_gizmo_view"),&SpatialEditorViewport::update_transform_gizmo_view);
ObjectTypeDB::bind_method(_MD("_selection_result_pressed"),&SpatialEditorViewport::_selection_result_pressed);
ObjectTypeDB::bind_method(_MD("_selection_menu_hide"),&SpatialEditorViewport::_selection_menu_hide);
ADD_SIGNAL( MethodInfo("toggle_maximize_view", PropertyInfo(Variant::OBJECT, "viewport")) );
}
void SpatialEditorViewport::reset() {
orthogonal=false;
message_time=0;
message="";
last_message="";
name="Top";
cursor.x_rot=0;
cursor.y_rot=0;
cursor.distance=4;
cursor.region_select=false;
_update_name();
}
SpatialEditorViewport::SpatialEditorViewport(SpatialEditor *p_spatial_editor, EditorNode *p_editor, int p_index) {
_edit.mode=TRANSFORM_NONE;
_edit.plane=TRANSFORM_VIEW;
_edit.edited_gizmo=0;
_edit.snap=1;
_edit.gizmo_handle=0;
index=p_index;
editor=p_editor;
editor_selection=editor->get_editor_selection();;
undo_redo=editor->get_undo_redo();
clicked=0;
clicked_includes_current=false;
orthogonal=false;
message_time=0;
spatial_editor=p_spatial_editor;
Control *c=memnew(Control);
add_child(c);
c->set_area_as_parent_rect();
viewport = memnew( Viewport );
viewport->set_disable_input(true);
c->add_child(viewport);
surface = memnew( Control );
add_child(surface);
surface->set_area_as_parent_rect();
camera = memnew(Camera);
camera->set_disable_gizmo(true);
camera->set_visible_layers( ((1<<20)-1)|(1<<(GIZMO_BASE_LAYER+p_index))|(1<<GIZMO_EDIT_LAYER)|(1<<GIZMO_GRID_LAYER) );
//camera->set_environment(SpatialEditor::get_singleton()->get_viewport_environment());
viewport->add_child(camera);
camera->make_current();
surface->set_focus_mode(FOCUS_ALL);
view_menu = memnew( MenuButton );
surface->add_child(view_menu);
view_menu->set_pos( Point2(4,4));
view_menu->set_self_opacity(0.5);
view_menu->get_popup()->add_item("Top (Num7)",VIEW_TOP);
view_menu->get_popup()->add_item("Bottom (Shift+Num7)",VIEW_BOTTOM);
view_menu->get_popup()->add_item("Left (Num3)",VIEW_LEFT);
view_menu->get_popup()->add_item("Right (Shift+Num3)",VIEW_RIGHT);
view_menu->get_popup()->add_item("Front (Num1)",VIEW_FRONT);
view_menu->get_popup()->add_item("Rear (Shift+Num1)",VIEW_REAR);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_item("Perspective (Num5)",VIEW_PERSPECTIVE);
view_menu->get_popup()->add_check_item("Orthogonal (Num5)",VIEW_ORTHOGONAL);
view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_PERSPECTIVE),true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_item("Environment",VIEW_ENVIRONMENT);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_ENVIRONMENT),true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_item("Audio Listener",VIEW_AUDIO_LISTENER);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_check_item("Gizmos",VIEW_GIZMOS);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(VIEW_GIZMOS),true);
view_menu->get_popup()->add_separator();
view_menu->get_popup()->add_item("Selection (F)",VIEW_CENTER_TO_SELECTION);
view_menu->get_popup()->add_item("Align with view (Ctrl+Shift+F)",VIEW_ALIGN_SELECTION_WITH_VIEW);
view_menu->get_popup()->connect("item_pressed",this,"_menu_option");
preview_camera = memnew( Button );
preview_camera->set_toggle_mode(true);
preview_camera->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_END,90);
preview_camera->set_anchor_and_margin(MARGIN_TOP,ANCHOR_BEGIN,10);
preview_camera->set_text("preview");
surface->add_child(preview_camera);
preview_camera->hide();
preview_camera->connect("toggled",this,"_toggle_camera_preview");
previewing=NULL;
preview=NULL;
gizmo_scale=1.0;
selection_menu = memnew( PopupMenu );
add_child(selection_menu);
selection_menu->set_custom_minimum_size(Vector2(100, 0));
selection_menu->connect("item_pressed", this, "_selection_result_pressed");
selection_menu->connect("popup_hide", this, "_selection_menu_hide");
if (p_index==0) {
view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(VIEW_AUDIO_LISTENER),true);
viewport->set_as_audio_listener(true);
}
name="Top";
_update_name();
EditorSettings::get_singleton()->connect("settings_changed",this,"update_transform_gizmo_view");
}
SpatialEditor *SpatialEditor::singleton=NULL;
SpatialEditorSelectedItem::~SpatialEditorSelectedItem() {
if (sbox_instance.is_valid())
VisualServer::get_singleton()->free(sbox_instance);
}
void SpatialEditor::select_gizmo_hilight_axis(int p_axis) {
for(int i=0;i<3;i++) {
move_gizmo[i]->surface_set_material(0,i==p_axis?gizmo_hl:gizmo_color[i]);
rotate_gizmo[i]->surface_set_material(0,(i+3)==p_axis?gizmo_hl:gizmo_color[i]);
}
}
void SpatialEditor::update_transform_gizmo() {
List<Node*> &selection = editor_selection->get_selected_node_list();
AABB center;
bool first=true;
Matrix3 gizmo_basis;
bool local_gizmo_coords = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS) );
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
Transform xf = se->sp->get_global_transform();
if (first) {
center.pos=xf.origin;
first=false;
if (local_gizmo_coords) {
gizmo_basis=xf.basis;
gizmo_basis.orthonormalize();
}
} else {
center.expand_to(xf.origin);
gizmo_basis=Matrix3();
}
// count++;
}
Vector3 pcenter = center.pos+center.size*0.5;
gizmo.visible=!first;
gizmo.transform.origin=pcenter;
gizmo.transform.basis=gizmo_basis;
for(int i=0;i<4;i++) {
viewports[i]->update_transform_gizmo_view();
}
}
Object *SpatialEditor::_get_editor_data(Object *p_what) {
Spatial *sp = p_what->cast_to<Spatial>();
if (!sp)
return NULL;
SpatialEditorSelectedItem *si = memnew( SpatialEditorSelectedItem );
si->sp=sp;
si->sbox_instance=VisualServer::get_singleton()->instance_create2(selection_box->get_rid(),sp->get_world()->get_scenario());
VS::get_singleton()->instance_geometry_set_flag(si->sbox_instance,VS::INSTANCE_FLAG_CAST_SHADOW,false);
RID inst = sp->call("_get_visual_instance_rid");
// if (inst.is_valid())
// si->aabb = VisualServer::get_singleton()->instance_get_base_aabb(inst);
if (get_tree()->is_editor_hint())
editor->call("edit_node",sp);
return si;
}
void SpatialEditor::_generate_selection_box() {
AABB aabb( Vector3(), Vector3(1,1,1) );
aabb.grow_by( aabb.get_longest_axis_size()/20.0 );
Ref<SurfaceTool> st = memnew( SurfaceTool );
st->begin(Mesh::PRIMITIVE_LINES);
for (int i=0;i<12;i++) {
Vector3 a,b;
aabb.get_edge(i,a,b);
/*Vector<Vector3> points;
Vector<Color> colors;
points.push_back(a);
points.push_back(b);*/
st->add_color( Color(1.0,1.0,0.8,0.8) );
st->add_vertex(a);
st->add_color( Color(1.0,1.0,0.8,0.4) );
st->add_vertex(a.linear_interpolate(b,0.2));
st->add_color( Color(1.0,1.0,0.8,0.4) );
st->add_vertex(a.linear_interpolate(b,0.8));
st->add_color( Color(1.0,1.0,0.8,0.8) );
st->add_vertex(b);
}
Ref<FixedMaterial> mat = memnew( FixedMaterial );
mat->set_flag(Material::FLAG_UNSHADED,true);
mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,Color(1,1,1));
mat->set_fixed_flag(FixedMaterial::FLAG_USE_ALPHA,true);
mat->set_fixed_flag(FixedMaterial::FLAG_USE_COLOR_ARRAY,true);
st->set_material(mat);
selection_box = st->commit();
}
Dictionary SpatialEditor::get_state() const {
Dictionary d;
d["snap_enabled"]=snap_enabled;
d["translate_snap"]=get_translate_snap();
d["rotate_snap"]=get_rotate_snap();
d["scale_snap"]=get_scale_snap();
int local_coords_index=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
d["local_coords"]=transform_menu->get_popup()->is_item_checked( local_coords_index );
int vc=0;
if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT) ))
vc=1;
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS) ))
vc=2;
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS) ))
vc=3;
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS) ))
vc=4;
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT) ))
vc=5;
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT) ))
vc=6;
d["viewport_mode"]=vc;
Array vpdata;
for(int i=0;i<4;i++) {
vpdata.push_back( viewports[i]->get_state() );
}
d["viewports"]=vpdata;
d["default_light"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT) );;
d["ambient_light_color"]=settings_ambient_color->get_color();
d["default_srgb"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_SRGB) );;
d["show_grid"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID) );;
d["show_origin"]=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN) );;
d["fov"]=get_fov();
d["znear"]=get_znear();
d["zfar"]=get_zfar();
d["deflight_rot_x"]=settings_default_light_rot_x;
d["deflight_rot_y"]=settings_default_light_rot_y;
return d;
}
void SpatialEditor::set_state(const Dictionary& p_state) {
Dictionary d = p_state;
if (d.has("snap_enabled")) {
snap_enabled=d["snap_enabled"];
int snap_enabled_idx=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_USE_SNAP);
transform_menu->get_popup()->set_item_checked( snap_enabled_idx, snap_enabled );
}
if (d.has("translate_snap"))
snap_translate->set_text(d["translate_snap"]);
if (d.has("rotate_snap"))
snap_rotate->set_text(d["rotate_snap"]);
if (d.has("scale_snap"))
snap_scale->set_text(d["scale_snap"]);
if (d.has("local_coords")) {
int local_coords_idx=transform_menu->get_popup()->get_item_index(MENU_TRANSFORM_LOCAL_COORDS);
transform_menu->get_popup()->set_item_checked( local_coords_idx, d["local_coords"] );
update_transform_gizmo();
}
if (d.has("viewport_mode")) {
int vc = d["viewport_mode"];
if (vc==1)
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
else if (vc==2)
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
else if (vc==3)
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
else if (vc==4)
_menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
else if (vc==5)
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
else if (vc==6)
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
}
if (d.has("viewports")) {
Array vp = d["viewports"];
ERR_FAIL_COND(vp.size()>4);
for(int i=0;i<4;i++) {
viewports[i]->set_state(vp[i]);
}
}
if (d.has("zfar"))
settings_zfar->set_val(float(d["zfar"]));
if (d.has("znear"))
settings_znear->set_val(float(d["znear"]));
if (d.has("fov"))
settings_fov->set_val(float(d["fov"]));
if (d.has("default_light")) {
bool use = d["default_light"];
bool existing = light_instance.is_valid();
if (use!=existing) {
if (existing) {
VisualServer::get_singleton()->free(light_instance);
light_instance=RID();
} else {
light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
}
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), light_instance.is_valid() );
}
}
if (d.has("ambient_light_color")) {
settings_ambient_color->set_color(d["ambient_light_color"]);
viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,d["ambient_light_color"]);
}
if (d.has("default_srgb")) {
bool use = d["default_srgb"];
viewport_environment->set_enable_fx(Environment::FX_SRGB,use);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_DEFAULT_SRGB), use );
}
if (d.has("show_grid")) {
bool use = d["show_grid"];
if (use!=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID))) {
_menu_item_pressed(MENU_VIEW_GRID);
}
}
if (d.has("show_origin")) {
bool use = d["show_origin"];
if (use!=view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN))) {
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), use );
VisualServer::get_singleton()->instance_geometry_set_flag(origin_instance,VS::INSTANCE_FLAG_VISIBLE,use);
}
}
if (d.has("deflight_rot_x"))
settings_default_light_rot_x=d["deflight_rot_x"];
if (d.has("deflight_rot_y"))
settings_default_light_rot_y=d["deflight_rot_y"];
_update_default_light_angle();
}
void SpatialEditor::edit(Spatial *p_spatial) {
if (p_spatial!=selected) {
if (selected) {
Ref<SpatialEditorGizmo> seg = selected->get_gizmo();
if (seg.is_valid()) {
seg->set_selected(false);
selected->update_gizmo();
}
}
selected=p_spatial;
over_gizmo_handle=-1;
if (selected) {
Ref<SpatialEditorGizmo> seg = selected->get_gizmo();
if (seg.is_valid()) {
seg->set_selected(true);
selected->update_gizmo();
}
}
}
if (p_spatial) {
//_validate_selection();
//if (selected.has(p_spatial->get_instance_ID()) && selected.size()==1)
// return;
//_select(p_spatial->get_instance_ID(),false,true);
// should become the selection
}
}
void SpatialEditor::_xform_dialog_action() {
Transform t;
//translation
Vector3 scale;
Vector3 rotate;
Vector3 translate;
for(int i=0;i<3;i++) {
translate[i]=xform_translate[i]->get_text().to_double();
rotate[i]=Math::deg2rad(xform_rotate[i]->get_text().to_double());
scale[i]=xform_scale[i]->get_text().to_double();
}
t.origin=translate;
for(int i=0;i<3;i++) {
if (!rotate[i])
continue;
Vector3 axis;
axis[i]=1.0;
t.basis.rotate(axis,rotate[i]);
}
for(int i=0;i<3;i++) {
if (scale[i]==1)
continue;
t.basis.set_axis(i,t.basis.get_axis(i)*scale[i]);
}
undo_redo->create_action("XForm Dialog");
List<Node*> &selection = editor_selection->get_selected_node_list();
for(List<Node*>::Element *E=selection.front();E;E=E->next()) {
Spatial *sp = E->get()->cast_to<Spatial>();
if (!sp)
continue;
SpatialEditorSelectedItem *se=editor_selection->get_node_editor_data<SpatialEditorSelectedItem>(sp);
if (!se)
continue;
bool post = xform_type->get_selected()>0;
Transform tr = sp->get_global_transform();
if (post)
tr = tr * t;
else {
tr.basis = t.basis * tr.basis;
tr.origin+=t.origin;
}
undo_redo->add_do_method(sp,"set_global_transform",tr);
undo_redo->add_undo_method(sp,"set_global_transform",sp->get_global_transform());
}
undo_redo->commit_action();
}
void SpatialEditor::_menu_item_pressed(int p_option) {
switch(p_option) {
case MENU_TOOL_SELECT:
case MENU_TOOL_MOVE:
case MENU_TOOL_ROTATE:
case MENU_TOOL_SCALE:
case MENU_TOOL_LIST_SELECT: {
for(int i=0;i<TOOL_MAX;i++)
tool_button[i]->set_pressed(i==p_option);
tool_mode=(ToolMode)p_option;
static const char *_mode[]={"Selection Mode.","Translation Mode.","Rotation Mode.","Scale Mode.","List Selection Mode."};
// set_message(_mode[p_option],3);
update_transform_gizmo();
} break;
case MENU_TRANSFORM_USE_SNAP: {
bool is_checked = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(p_option) );
snap_enabled=!is_checked;
transform_menu->get_popup()->set_item_checked( transform_menu->get_popup()->get_item_index(p_option), snap_enabled );
} break;
case MENU_TRANSFORM_CONFIGURE_SNAP: {
snap_dialog->popup_centered(Size2(200,180));
} break;
case MENU_TRANSFORM_LOCAL_COORDS: {
bool is_checked = transform_menu->get_popup()->is_item_checked( transform_menu->get_popup()->get_item_index(p_option) );
transform_menu->get_popup()->set_item_checked( transform_menu->get_popup()->get_item_index(p_option), !is_checked );
update_transform_gizmo();
} break;
case MENU_TRANSFORM_DIALOG: {
for(int i=0;i<3;i++) {
xform_translate[i]->set_text("0");
xform_rotate[i]->set_text("0");
xform_scale[i]->set_text("1");
}
xform_dialog->popup_centered(Size2(200,200));
} break;
case MENU_VIEW_USE_DEFAULT_LIGHT: {
bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
if (is_checked) {
VisualServer::get_singleton()->free(light_instance);
light_instance=RID();
} else {
light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
_update_default_light_angle();
}
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), light_instance.is_valid() );
} break;
case MENU_VIEW_USE_DEFAULT_SRGB: {
bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
if (is_checked) {
viewport_environment->set_enable_fx(Environment::FX_SRGB,false);
} else {
viewport_environment->set_enable_fx(Environment::FX_SRGB,true);
}
is_checked = ! is_checked;
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), is_checked );
} break;
case MENU_VIEW_USE_1_VIEWPORT: {
for(int i=1;i<4;i++) {
viewports[i]->hide();
}
viewports[0]->set_area_as_parent_rect();
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
} break;
case MENU_VIEW_USE_2_VIEWPORTS: {
for(int i=1;i<4;i++) {
if (i==1 || i==3)
viewports[i]->hide();
else
viewports[i]->show();
}
viewports[0]->set_area_as_parent_rect();
viewports[0]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
viewports[2]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
} break;
case MENU_VIEW_USE_2_VIEWPORTS_ALT: {
for(int i=1;i<4;i++) {
if (i==1 || i==3)
viewports[i]->hide();
else
viewports[i]->show();
}
viewports[0]->set_area_as_parent_rect();
viewports[0]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
viewports[2]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
} break;
case MENU_VIEW_USE_3_VIEWPORTS: {
for(int i=1;i<4;i++) {
if (i==1)
viewports[i]->hide();
else
viewports[i]->show();
}
viewports[0]->set_area_as_parent_rect();
viewports[0]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
viewports[2]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[2]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
viewports[3]->set_area_as_parent_rect();
viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
viewports[3]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
} break;
case MENU_VIEW_USE_3_VIEWPORTS_ALT: {
for(int i=1;i<4;i++) {
if (i==1)
viewports[i]->hide();
else
viewports[i]->show();
}
viewports[0]->set_area_as_parent_rect();
viewports[0]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[0]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
viewports[2]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
viewports[2]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[3]->set_area_as_parent_rect();
viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), true );
} break;
case MENU_VIEW_USE_4_VIEWPORTS: {
for(int i=1;i<4;i++) {
viewports[i]->show();
}
viewports[0]->set_area_as_parent_rect();
viewports[0]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[0]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[1]->set_area_as_parent_rect();
viewports[1]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
viewports[1]->set_anchor_and_margin(MARGIN_BOTTOM,ANCHOR_RATIO,0.5);
viewports[2]->set_area_as_parent_rect();
viewports[2]->set_anchor_and_margin(MARGIN_RIGHT,ANCHOR_RATIO,0.5);
viewports[2]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
viewports[3]->set_area_as_parent_rect();
viewports[3]->set_anchor_and_margin(MARGIN_LEFT,ANCHOR_RATIO,0.5);
viewports[3]->set_anchor_and_margin(MARGIN_TOP,ANCHOR_RATIO,0.5);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT), false );
} break;
case MENU_VIEW_DISPLAY_NORMAL: {
VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_DISABLED );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
} break;
case MENU_VIEW_DISPLAY_WIREFRAME: {
VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_WIREFRAME );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
} break;
case MENU_VIEW_DISPLAY_OVERDRAW: {
VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_OVERDRAW );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), true );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), false );
} break;
case MENU_VIEW_DISPLAY_SHADELESS: {
VisualServer::get_singleton()->scenario_set_debug( get_tree()->get_root()->get_world()->get_scenario(), VisualServer::SCENARIO_DEBUG_SHADELESS );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_NORMAL), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_WIREFRAME), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_OVERDRAW), false );
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_DISPLAY_SHADELESS), true );
} break;
case MENU_VIEW_ORIGIN: {
bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
is_checked=!is_checked;
VisualServer::get_singleton()->instance_geometry_set_flag(origin_instance,VS::INSTANCE_FLAG_VISIBLE,is_checked);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), is_checked);
} break;
case MENU_VIEW_GRID: {
bool is_checked = view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(p_option) );
grid_enabled=!is_checked;
for(int i=0;i<3;++i) {
if (grid_enable[i]) {
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,grid_enabled);
grid_visible[i]=grid_enabled;
}
}
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(p_option), grid_enabled );
} break;
case MENU_VIEW_CAMERA_SETTINGS: {
settings_dialog->popup_centered(settings_vbc->get_combined_minimum_size()+Size2(50,50));
} break;
}
}
void SpatialEditor::_init_indicators() {
//make sure that the camera indicator is not selectable
light=VisualServer::get_singleton()->light_create( VisualServer::LIGHT_DIRECTIONAL );
//VisualServer::get_singleton()->light_set_shadow( light, true );
light_instance=VisualServer::get_singleton()->instance_create2(light,get_tree()->get_root()->get_world()->get_scenario());
light_transform.rotate(Vector3(1,0,0),Math_PI/5.0);
VisualServer::get_singleton()->instance_set_transform(light_instance,light_transform);
//RID mat = VisualServer::get_singleton()->fixed_material_create();
///VisualServer::get_singleton()->fixed_material_set_flag(mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA,true);
//VisualServer::get_singleton()->fixed_material_set_flag(mat, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true);
{
indicator_mat = VisualServer::get_singleton()->fixed_material_create();
VisualServer::get_singleton()->material_set_flag( indicator_mat, VisualServer::MATERIAL_FLAG_UNSHADED, true );
VisualServer::get_singleton()->material_set_flag( indicator_mat, VisualServer::MATERIAL_FLAG_ONTOP, false );
VisualServer::get_singleton()->fixed_material_set_flag(indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA,true);
VisualServer::get_singleton()->fixed_material_set_flag(indicator_mat, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true);
DVector<Color> grid_colors[3];
DVector<Vector3> grid_points[3];
Vector<Color> origin_colors;
Vector<Vector3> origin_points;
for(int i=0;i<3;i++) {
Vector3 axis;
axis[i]=1;
Vector3 axis_n1;
axis_n1[(i+1)%3]=1;
Vector3 axis_n2;
axis_n2[(i+2)%3]=1;
origin_colors.push_back(Color(axis.x,axis.y,axis.z));
origin_colors.push_back(Color(axis.x,axis.y,axis.z));
origin_points.push_back(axis*4096);
origin_points.push_back(axis*-4096);
#define ORIGIN_GRID_SIZE 25
for(int j=-ORIGIN_GRID_SIZE;j<=ORIGIN_GRID_SIZE;j++) {
grid_colors[i].push_back(Color(axis.x,axis.y,axis.z,0.2));
grid_colors[i].push_back(Color(axis.x,axis.y,axis.z,0.2));
grid_colors[i].push_back(Color(axis.x,axis.y,axis.z,0.2));
grid_colors[i].push_back(Color(axis.x,axis.y,axis.z,0.2));
grid_points[i].push_back(axis_n1*ORIGIN_GRID_SIZE+axis_n2*j);
grid_points[i].push_back(-axis_n1*ORIGIN_GRID_SIZE+axis_n2*j);
grid_points[i].push_back(axis_n2*ORIGIN_GRID_SIZE+axis_n1*j);
grid_points[i].push_back(-axis_n2*ORIGIN_GRID_SIZE+axis_n1*j);
}
grid[i] = VisualServer::get_singleton()->mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
d[VisualServer::ARRAY_VERTEX]=grid_points[i];
d[VisualServer::ARRAY_COLOR]=grid_colors[i];
VisualServer::get_singleton()->mesh_add_surface(grid[i],VisualServer::PRIMITIVE_LINES,d);
VisualServer::get_singleton()->mesh_surface_set_material(grid[i],0,indicator_mat);
grid_instance[i] = VisualServer::get_singleton()->instance_create2(grid[i],get_tree()->get_root()->get_world()->get_scenario());
grid_visible[i]=false;
grid_enable[i]=false;
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,false);
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_CAST_SHADOW,false);
VS::get_singleton()->instance_set_layer_mask(grid_instance[i],1<<SpatialEditorViewport::GIZMO_GRID_LAYER);
}
origin = VisualServer::get_singleton()->mesh_create();
Array d;
d.resize(VS::ARRAY_MAX);
d[VisualServer::ARRAY_VERTEX]=origin_points;
d[VisualServer::ARRAY_COLOR]=origin_colors;
VisualServer::get_singleton()->mesh_add_surface(origin,VisualServer::PRIMITIVE_LINES,d);
VisualServer::get_singleton()->mesh_surface_set_material(origin,0,indicator_mat);
// origin = VisualServer::get_singleton()->poly_create();
// VisualServer::get_singleton()->poly_add_primitive(origin,origin_points,Vector<Vector3>(),origin_colors,Vector<Vector3>());
// VisualServer::get_singleton()->poly_set_material(origin,indicator_mat,true);
origin_instance = VisualServer::get_singleton()->instance_create2(origin,get_tree()->get_root()->get_world()->get_scenario());
VS::get_singleton()->instance_set_layer_mask(origin_instance,1<<SpatialEditorViewport::GIZMO_GRID_LAYER);
VisualServer::get_singleton()->instance_geometry_set_flag(origin_instance,VS::INSTANCE_FLAG_CAST_SHADOW,false);
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[1],VS::INSTANCE_FLAG_VISIBLE,true);
grid_enable[1]=true;
grid_visible[1]=true;
grid_enabled=true;
last_grid_snap=1;
}
{
cursor_mesh = VisualServer::get_singleton()->mesh_create();
DVector<Vector3> cursor_points;
float cs = 0.25;
cursor_points.push_back(Vector3(+cs,0,0));
cursor_points.push_back(Vector3(-cs,0,0));
cursor_points.push_back(Vector3(0,+cs,0));
cursor_points.push_back(Vector3(0,-cs,0));
cursor_points.push_back(Vector3(0,0,+cs));
cursor_points.push_back(Vector3(0,0,-cs));
cursor_material=VisualServer::get_singleton()->fixed_material_create();
VisualServer::get_singleton()->fixed_material_set_param(cursor_material,VS::FIXED_MATERIAL_PARAM_DIFFUSE,Color(0,1,1));
VisualServer::get_singleton()->material_set_flag( cursor_material, VisualServer::MATERIAL_FLAG_UNSHADED, true );
VisualServer::get_singleton()->fixed_material_set_flag(cursor_material, VisualServer::FIXED_MATERIAL_FLAG_USE_ALPHA,true);
VisualServer::get_singleton()->fixed_material_set_flag(cursor_material, VisualServer::FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true);
Array d;
d.resize(VS::ARRAY_MAX);
d[VS::ARRAY_VERTEX]=cursor_points;
VisualServer::get_singleton()->mesh_add_surface(cursor_mesh,VS::PRIMITIVE_LINES,d);
VisualServer::get_singleton()->mesh_surface_set_material(cursor_mesh,0,cursor_material);
cursor_instance = VisualServer::get_singleton()->instance_create2(cursor_mesh,get_tree()->get_root()->get_world()->get_scenario());
VS::get_singleton()->instance_set_layer_mask(cursor_instance,1<<SpatialEditorViewport::GIZMO_GRID_LAYER);
VisualServer::get_singleton()->instance_geometry_set_flag(cursor_instance,VS::INSTANCE_FLAG_CAST_SHADOW,false);
}
{
//move gizmo
float gizmo_alph = EditorSettings::get_singleton()->get("3d_editor/manipulator_gizmo_opacity");
gizmo_hl = Ref<FixedMaterial>( memnew( FixedMaterial ) );
gizmo_hl->set_flag(Material::FLAG_UNSHADED, true);
gizmo_hl->set_flag(Material::FLAG_ONTOP, true);
gizmo_hl->set_fixed_flag(FixedMaterial::FLAG_USE_ALPHA, true);
gizmo_hl->set_parameter(FixedMaterial::PARAM_DIFFUSE,Color(1,1,1,gizmo_alph+0.2f));
for(int i=0;i<3;i++) {
move_gizmo[i]=Ref<Mesh>( memnew( Mesh ) );
rotate_gizmo[i]=Ref<Mesh>( memnew( Mesh ) );
Ref<FixedMaterial> mat = memnew( FixedMaterial );
mat->set_flag(Material::FLAG_UNSHADED, true);
mat->set_flag(Material::FLAG_ONTOP, true);
mat->set_fixed_flag(FixedMaterial::FLAG_USE_ALPHA, true);
Color col;
col[i]=1.0;
col.a= gizmo_alph;
mat->set_parameter(FixedMaterial::PARAM_DIFFUSE,col);
gizmo_color[i]=mat;
Vector3 ivec;
ivec[i]=1;
Vector3 nivec;
nivec[(i+1)%3]=1;
nivec[(i+2)%3]=1;
Vector3 ivec2;
ivec2[(i+1)%3]=1;
Vector3 ivec3;
ivec3[(i+2)%3]=1;
{
Ref<SurfaceTool> surftool = memnew( SurfaceTool );
surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
//translate
const int arrow_points=5;
Vector3 arrow[5]={
nivec*0.0+ivec*0.0,
nivec*0.01+ivec*0.0,
nivec*0.01+ivec*1.0,
nivec*0.1+ivec*1.0,
nivec*0.0+ivec*(1+GIZMO_ARROW_SIZE),
};
int arrow_sides=6;
for(int k = 0; k < 7 ; k++) {
Matrix3 ma(ivec,Math_PI*2*float(k)/arrow_sides);
Matrix3 mb(ivec,Math_PI*2*float(k+1)/arrow_sides);
for(int j=0;j<arrow_points-1;j++) {
Vector3 points[4]={
ma.xform(arrow[j]),
mb.xform(arrow[j]),
mb.xform(arrow[j+1]),
ma.xform(arrow[j+1]),
};
surftool->add_vertex(points[0]);
surftool->add_vertex(points[1]);
surftool->add_vertex(points[2]);
surftool->add_vertex(points[0]);
surftool->add_vertex(points[2]);
surftool->add_vertex(points[3]);
}
}
surftool->set_material(mat);
surftool->commit(move_gizmo[i]);
}
{
Ref<SurfaceTool> surftool = memnew( SurfaceTool );
surftool->begin(Mesh::PRIMITIVE_TRIANGLES);
Vector3 circle[5]={
ivec*0.02+ivec2*0.02+ivec2*1.0,
ivec*-0.02+ivec2*0.02+ivec2*1.0,
ivec*-0.02+ivec2*-0.02+ivec2*1.0,
ivec*0.02+ivec2*-0.02+ivec2*1.0,
ivec*0.02+ivec2*0.02+ivec2*1.0,
};
for(int k = 0; k < 33 ; k++) {
Matrix3 ma(ivec,Math_PI*2*float(k)/32);
Matrix3 mb(ivec,Math_PI*2*float(k+1)/32);
for(int j=0;j<4;j++) {
Vector3 points[4]={
ma.xform(circle[j]),
mb.xform(circle[j]),
mb.xform(circle[j+1]),
ma.xform(circle[j+1]),
};
surftool->add_vertex(points[0]);
surftool->add_vertex(points[1]);
surftool->add_vertex(points[2]);
surftool->add_vertex(points[0]);
surftool->add_vertex(points[2]);
surftool->add_vertex(points[3]);
}
}
surftool->set_material(mat);
surftool->commit(rotate_gizmo[i]);
}
}
}
/*for(int i=0;i<4;i++) {
viewports[i]->init_gizmo_instance(i);
}*/
_generate_selection_box();
//get_scene()->get_root_node()->cast_to<EditorNode>()->get_scene_root()->add_child(camera);
//current_camera=camera;
}
void SpatialEditor::_finish_indicators() {
VisualServer::get_singleton()->free(origin_instance);
VisualServer::get_singleton()->free(origin);
for(int i=0;i<3;i++) {
VisualServer::get_singleton()->free(grid_instance[i]);
VisualServer::get_singleton()->free(grid[i]);
}
VisualServer::get_singleton()->free(light_instance);
VisualServer::get_singleton()->free(light);
//VisualServer::get_singleton()->free(poly);
//VisualServer::get_singleton()->free(indicators_instance);
//VisualServer::get_singleton()->free(indicators);
VisualServer::get_singleton()->free(cursor_instance);
VisualServer::get_singleton()->free(cursor_mesh);
VisualServer::get_singleton()->free(indicator_mat);
VisualServer::get_singleton()->free(cursor_material);
}
void SpatialEditor::_instance_scene() {
#if 0
EditorNode *en = get_scene()->get_root_node()->cast_to<EditorNode>();
ERR_FAIL_COND(!en);
String path = en->get_scenes_dock()->get_selected_path();
if (path=="") {
set_message("No scene selected to instance!");
return;
}
undo_redo->create_action("Instance at Cursor");
Node* scene = en->request_instance_scene(path);
if (!scene) {
set_message("Could not instance scene!");
undo_redo->commit_action(); //bleh
return;
}
Spatial *s = scene->cast_to<Spatial>();
if (s) {
undo_redo->add_do_method(s,"set_global_transform",Transform(Matrix3(),cursor.cursor_pos));
}
undo_redo->commit_action();
#endif
}
void SpatialEditor::_unhandled_key_input(InputEvent p_event) {
if (!is_visible() || get_viewport()->gui_has_modal_stack())
return;
{
EditorNode *en = editor;
EditorPlugin *over_plugin = en->get_editor_plugin_over();
if (over_plugin && over_plugin->forward_input_event(p_event)) {
return; //ate the over input event
}
}
switch(p_event.type) {
case InputEvent::KEY: {
const InputEventKey &k=p_event.key;
if (!k.pressed)
break;
switch(k.scancode) {
case KEY_Q: _menu_item_pressed(MENU_TOOL_SELECT); break;
case KEY_W: _menu_item_pressed(MENU_TOOL_MOVE); break;
case KEY_E: _menu_item_pressed(MENU_TOOL_ROTATE); break;
case KEY_R: _menu_item_pressed(MENU_TOOL_SCALE); break;
#if 0
#endif
}
} break;
}
}
void SpatialEditor::_notification(int p_what) {
if (p_what==NOTIFICATION_READY) {
tool_button[SpatialEditor::TOOL_MODE_SELECT]->set_icon( get_icon("ToolSelect","EditorIcons") );
tool_button[SpatialEditor::TOOL_MODE_MOVE]->set_icon( get_icon("ToolMove","EditorIcons") );
tool_button[SpatialEditor::TOOL_MODE_ROTATE]->set_icon( get_icon("ToolRotate","EditorIcons") );
tool_button[SpatialEditor::TOOL_MODE_SCALE]->set_icon( get_icon("ToolScale","EditorIcons") );
tool_button[SpatialEditor::TOOL_MODE_LIST_SELECT]->set_icon( get_icon("ListSelect","EditorIcons") );
instance_button->set_icon( get_icon("SpatialAdd","EditorIcons") );
instance_button->hide();
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT),get_icon("Panels1","EditorIcons"));
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS),get_icon("Panels2","EditorIcons"));
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT),get_icon("Panels2Alt","EditorIcons"));
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS),get_icon("Panels3","EditorIcons"));
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT),get_icon("Panels3Alt","EditorIcons"));
view_menu->get_popup()->set_item_icon(view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS),get_icon("Panels4","EditorIcons"));
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
get_tree()->connect("node_removed",this,"_node_removed");
VS::get_singleton()->scenario_set_fallback_environment(get_viewport()->find_world()->get_scenario(),viewport_environment->get_rid());
}
if (p_what==NOTIFICATION_ENTER_TREE) {
gizmos = memnew( SpatialEditorGizmos );
_init_indicators();
_update_default_light_angle();
}
if (p_what==NOTIFICATION_EXIT_TREE) {
_finish_indicators();
memdelete( gizmos );
}
}
void SpatialEditor::add_control_to_menu_panel(Control *p_control) {
hbc_menu->add_child(p_control);
}
void SpatialEditor::set_can_preview(Camera* p_preview) {
for(int i=0;i<4;i++) {
viewports[i]->set_can_preview(p_preview);
}
}
VSplitContainer *SpatialEditor::get_shader_split() {
return shader_split;
}
HSplitContainer *SpatialEditor::get_palette_split() {
return palette_split;
}
void SpatialEditor::_request_gizmo(Object* p_obj) {
Spatial *sp=p_obj->cast_to<Spatial>();
if (!sp)
return;
if (editor->get_edited_scene() && (sp==editor->get_edited_scene() || sp->get_owner()==editor->get_edited_scene())) {
Ref<SpatialEditorGizmo> seg = gizmos->get_gizmo(sp);
if (seg.is_valid()) {
sp->set_gizmo(seg);
}
for (List<EditorPlugin*>::Element *E=gizmo_plugins.front();E;E=E->next()) {
if (E->get()->create_spatial_gizmo(sp)) {
seg = sp->get_gizmo();
if (sp==selected && seg.is_valid()) {
seg->set_selected(true);
selected->update_gizmo();
}
return;
}
}
if (seg.is_valid() && sp==selected) {
seg->set_selected(true);
selected->update_gizmo();
}
}
}
void SpatialEditor::_toggle_maximize_view(Object* p_viewport) {
if (!p_viewport) return;
SpatialEditorViewport *current_viewport = p_viewport->cast_to<SpatialEditorViewport>();
if (!current_viewport) return;
int index=-1;
bool maximized = false;
for(int i=0;i<4;i++) {
if (viewports[i]==current_viewport) {
index=i;
if ( current_viewport->get_global_rect() == viewport_base->get_global_rect() )
maximized=true;
break;
}
}
if (index==-1) return;
if (!maximized) {
for(int i=0;i<4;i++) {
if (i==index)
viewports[i]->set_area_as_parent_rect();
else
viewports[i]->hide();
}
} else {
for(int i=0;i<4;i++)
viewports[i]->show();
if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_1_VIEWPORT) ))
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS) ))
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS);
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_2_VIEWPORTS_ALT) ))
_menu_item_pressed(MENU_VIEW_USE_2_VIEWPORTS_ALT);
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS) ))
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS);
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_3_VIEWPORTS_ALT) ))
_menu_item_pressed(MENU_VIEW_USE_3_VIEWPORTS_ALT);
else if (view_menu->get_popup()->is_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_USE_4_VIEWPORTS) ))
_menu_item_pressed(MENU_VIEW_USE_4_VIEWPORTS);
}
}
void SpatialEditor::_node_removed(Node* p_node) {
if (p_node==selected)
selected=NULL;
}
void SpatialEditor::_bind_methods() {
// ObjectTypeDB::bind_method("_input_event",&SpatialEditor::_input_event);
ObjectTypeDB::bind_method("_unhandled_key_input",&SpatialEditor::_unhandled_key_input);
ObjectTypeDB::bind_method("_node_removed",&SpatialEditor::_node_removed);
ObjectTypeDB::bind_method("_menu_item_pressed",&SpatialEditor::_menu_item_pressed);
ObjectTypeDB::bind_method("_xform_dialog_action",&SpatialEditor::_xform_dialog_action);
ObjectTypeDB::bind_method("_instance_scene",&SpatialEditor::_instance_scene);
ObjectTypeDB::bind_method("_get_editor_data",&SpatialEditor::_get_editor_data);
ObjectTypeDB::bind_method("_request_gizmo",&SpatialEditor::_request_gizmo);
ObjectTypeDB::bind_method("_default_light_angle_input",&SpatialEditor::_default_light_angle_input);
ObjectTypeDB::bind_method("_update_ambient_light_color",&SpatialEditor::_update_ambient_light_color);
ObjectTypeDB::bind_method("_toggle_maximize_view",&SpatialEditor::_toggle_maximize_view);
ADD_SIGNAL( MethodInfo("transform_key_request") );
}
void SpatialEditor::clear() {
settings_fov->set_val(EDITOR_DEF("3d_editor/default_fov",60.0));
settings_znear->set_val(EDITOR_DEF("3d_editor/default_z_near",0.1));
settings_zfar->set_val(EDITOR_DEF("3d_editor/default_z_far",1500.0));
for(int i=0;i<4;i++) {
viewports[i]->reset();
}
_menu_item_pressed(MENU_VIEW_USE_1_VIEWPORT);
_menu_item_pressed(MENU_VIEW_DISPLAY_NORMAL);
VisualServer::get_singleton()->instance_geometry_set_flag(origin_instance,VS::INSTANCE_FLAG_VISIBLE,true);
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_ORIGIN), true);
for(int i=0;i<3;++i) {
if (grid_enable[i]) {
VisualServer::get_singleton()->instance_geometry_set_flag(grid_instance[i],VS::INSTANCE_FLAG_VISIBLE,true);
grid_visible[i]=true;
}
}
for(int i=0;i<4;i++) {
viewports[i]->view_menu->get_popup()->set_item_checked(view_menu->get_popup()->get_item_index(SpatialEditorViewport::VIEW_AUDIO_LISTENER),i==0);
viewports[i]->viewport->set_as_audio_listener(i==0);
}
view_menu->get_popup()->set_item_checked( view_menu->get_popup()->get_item_index(MENU_VIEW_GRID), true );
settings_default_light_rot_x=Math_PI*0.3;
settings_default_light_rot_y=Math_PI*0.2;
viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,Color(0.15,0.15,0.15));
settings_ambient_color->set_color(Color(0.15,0.15,0.15));
if (!light_instance.is_valid())
_menu_item_pressed(MENU_VIEW_USE_DEFAULT_LIGHT);
_update_default_light_angle();
}
void SpatialEditor::_update_ambient_light_color(const Color& p_color) {
viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,settings_ambient_color->get_color());
}
void SpatialEditor::_update_default_light_angle() {
Transform t;
t.basis.rotate(Vector3(1,0,0),settings_default_light_rot_x);
t.basis.rotate(Vector3(0,1,0),settings_default_light_rot_y);
settings_dlight->set_transform(t);
if (light_instance.is_valid()) {
VS::get_singleton()->instance_set_transform(light_instance,t);
}
}
void SpatialEditor::_default_light_angle_input(const InputEvent& p_event) {
if (p_event.type==InputEvent::MOUSE_MOTION && p_event.mouse_motion.button_mask&(0x1|0x2|0x4)) {
settings_default_light_rot_y = Math::fposmod(settings_default_light_rot_y - p_event.mouse_motion.relative_x*0.01,Math_PI*2.0);
settings_default_light_rot_x = Math::fposmod(settings_default_light_rot_x - p_event.mouse_motion.relative_y*0.01,Math_PI*2.0);
_update_default_light_angle();
}
}
SpatialEditor::SpatialEditor(EditorNode *p_editor) {
gizmo.visible=true;
gizmo.scale=1.0;
viewport_environment = Ref<Environment>( memnew( Environment ) );
undo_redo=p_editor->get_undo_redo();
VBoxContainer *vbc = this;
custom_camera=NULL;
singleton=this;
editor=p_editor;
editor_selection=editor->get_editor_selection();
editor_selection->add_editor_plugin(this);
snap_enabled=false;
tool_mode = TOOL_MODE_SELECT;
//set_focus_mode(FOCUS_ALL);
hbc_menu = memnew( HBoxContainer );
vbc->add_child(hbc_menu);
Vector<Variant> button_binds;
button_binds.resize(1);
tool_button[TOOL_MODE_SELECT] = memnew( ToolButton );
hbc_menu->add_child( tool_button[TOOL_MODE_SELECT] );
tool_button[TOOL_MODE_SELECT]->set_toggle_mode(true);
tool_button[TOOL_MODE_SELECT]->set_flat(true);
tool_button[TOOL_MODE_SELECT]->set_pressed(true);
button_binds[0]=MENU_TOOL_SELECT;
tool_button[TOOL_MODE_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds);
tool_button[TOOL_MODE_SELECT]->set_tooltip("Select Mode (Q)\n"+keycode_get_string(KEY_MASK_CMD)+"Drag: Rotate\nAlt+Drag: Move\nAlt+RMB: Depth list selection");
tool_button[TOOL_MODE_MOVE] = memnew( ToolButton );
hbc_menu->add_child( tool_button[TOOL_MODE_MOVE] );
tool_button[TOOL_MODE_MOVE]->set_toggle_mode(true);
tool_button[TOOL_MODE_MOVE]->set_flat(true);
button_binds[0]=MENU_TOOL_MOVE;
tool_button[TOOL_MODE_MOVE]->connect("pressed", this,"_menu_item_pressed",button_binds);
tool_button[TOOL_MODE_MOVE]->set_tooltip("Move Mode (W)");
tool_button[TOOL_MODE_ROTATE] = memnew( ToolButton );
hbc_menu->add_child( tool_button[TOOL_MODE_ROTATE] );
tool_button[TOOL_MODE_ROTATE]->set_toggle_mode(true);
tool_button[TOOL_MODE_ROTATE]->set_flat(true);
button_binds[0]=MENU_TOOL_ROTATE;
tool_button[TOOL_MODE_ROTATE]->connect("pressed", this,"_menu_item_pressed",button_binds);
tool_button[TOOL_MODE_ROTATE]->set_tooltip("Rotate Mode (E)");
tool_button[TOOL_MODE_SCALE] = memnew( ToolButton );
hbc_menu->add_child( tool_button[TOOL_MODE_SCALE] );
tool_button[TOOL_MODE_SCALE]->set_toggle_mode(true);
tool_button[TOOL_MODE_SCALE]->set_flat(true);
button_binds[0]=MENU_TOOL_SCALE;
tool_button[TOOL_MODE_SCALE]->connect("pressed", this,"_menu_item_pressed",button_binds);
tool_button[TOOL_MODE_SCALE]->set_tooltip("Scale Mode (R)");
instance_button = memnew( Button );
hbc_menu->add_child( instance_button );
instance_button->set_flat(true);
instance_button->connect("pressed",this,"_instance_scene");
instance_button->hide();
VSeparator *vs = memnew( VSeparator );
hbc_menu->add_child(vs);
tool_button[TOOL_MODE_LIST_SELECT] = memnew( ToolButton );
hbc_menu->add_child( tool_button[TOOL_MODE_LIST_SELECT] );
tool_button[TOOL_MODE_LIST_SELECT]->set_toggle_mode(true);
tool_button[TOOL_MODE_LIST_SELECT]->set_flat(true);
button_binds[0]=MENU_TOOL_LIST_SELECT;
tool_button[TOOL_MODE_LIST_SELECT]->connect("pressed", this,"_menu_item_pressed",button_binds);
tool_button[TOOL_MODE_LIST_SELECT]->set_tooltip("Show a list of all objects at the position clicked\n(same as Alt+RMB in selet mode).");
vs = memnew( VSeparator );
hbc_menu->add_child(vs);
PopupMenu *p;
transform_menu = memnew( MenuButton );
transform_menu->set_text("Transform");
hbc_menu->add_child( transform_menu );
p = transform_menu->get_popup();
p->add_check_item("Use Snap",MENU_TRANSFORM_USE_SNAP);
p->add_item("Configure Snap..",MENU_TRANSFORM_CONFIGURE_SNAP);
p->add_separator();
p->add_check_item("Local Coords",MENU_TRANSFORM_LOCAL_COORDS);
//p->set_item_checked(p->get_item_count()-1,true);
p->add_separator();
p->add_item("Transform Dialog..",MENU_TRANSFORM_DIALOG);
p->connect("item_pressed", this,"_menu_item_pressed");
view_menu = memnew( MenuButton );
view_menu->set_text("View");
view_menu->set_pos( Point2( 212,0) );
hbc_menu->add_child( view_menu );
p = view_menu->get_popup();
p->add_check_item("Use Default Light",MENU_VIEW_USE_DEFAULT_LIGHT);
p->add_check_item("Use Default sRGB",MENU_VIEW_USE_DEFAULT_SRGB);
p->add_separator();
p->add_check_item("1 Viewport",MENU_VIEW_USE_1_VIEWPORT,KEY_MASK_CMD+KEY_1);
p->add_check_item("2 Viewports",MENU_VIEW_USE_2_VIEWPORTS,KEY_MASK_CMD+KEY_2);
p->add_check_item("2 Viewports (Alt)",MENU_VIEW_USE_2_VIEWPORTS_ALT,KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_2);
p->add_check_item("3 Viewports",MENU_VIEW_USE_3_VIEWPORTS,KEY_MASK_CMD+KEY_3);
p->add_check_item("3 Viewports (Alt)",MENU_VIEW_USE_3_VIEWPORTS_ALT,KEY_MASK_SHIFT+KEY_MASK_CMD+KEY_3);
p->add_check_item("4 Viewports",MENU_VIEW_USE_4_VIEWPORTS,KEY_MASK_CMD+KEY_4);
p->add_separator();
p->add_check_item("Display Normal",MENU_VIEW_DISPLAY_NORMAL);
p->add_check_item("Display Wireframe",MENU_VIEW_DISPLAY_WIREFRAME);
p->add_check_item("Display Overdraw",MENU_VIEW_DISPLAY_OVERDRAW);
p->add_check_item("Display Shadeless",MENU_VIEW_DISPLAY_SHADELESS);
p->add_separator();
p->add_check_item("View Origin",MENU_VIEW_ORIGIN);
p->add_check_item("View Grid",MENU_VIEW_GRID);
p->add_separator();
p->add_item("Settings",MENU_VIEW_CAMERA_SETTINGS);
p->set_item_checked( p->get_item_index(MENU_VIEW_USE_DEFAULT_LIGHT), true );
p->set_item_checked( p->get_item_index(MENU_VIEW_DISPLAY_NORMAL), true );
p->set_item_checked( p->get_item_index(MENU_VIEW_ORIGIN), true );
p->set_item_checked( p->get_item_index(MENU_VIEW_GRID), true );
p->connect("item_pressed", this,"_menu_item_pressed");
/* REST OF MENU */
palette_split = memnew( HSplitContainer);
palette_split->set_v_size_flags(SIZE_EXPAND_FILL);
vbc->add_child(palette_split);
shader_split = memnew( VSplitContainer );
shader_split->set_h_size_flags(SIZE_EXPAND_FILL);
palette_split->add_child(shader_split);
viewport_base = memnew( Control );
shader_split->add_child(viewport_base);
viewport_base->set_v_size_flags(SIZE_EXPAND_FILL);
for(int i=0;i<4;i++) {
viewports[i] = memnew( SpatialEditorViewport(this,editor,i) );
viewports[i]->connect("toggle_maximize_view",this,"_toggle_maximize_view");
viewport_base->add_child(viewports[i]);
}
//vbc->add_child(viewport_base);
/* SNAP DIALOG */
snap_dialog = memnew( ConfirmationDialog );
snap_dialog->set_title("Snap Settings");
add_child(snap_dialog);
VBoxContainer *snap_dialog_vbc = memnew( VBoxContainer );
snap_dialog->add_child(snap_dialog_vbc);
snap_dialog->set_child_rect(snap_dialog_vbc);
snap_translate = memnew( LineEdit );
snap_translate->set_text("1");
snap_dialog_vbc->add_margin_child("Translate Snap:",snap_translate);
snap_rotate = memnew( LineEdit );
snap_rotate->set_text("5");
snap_dialog_vbc->add_margin_child("Rotate Snap (deg.):",snap_rotate);
snap_scale = memnew( LineEdit );
snap_scale->set_text("5");
snap_dialog_vbc->add_margin_child("Scale Snap (%):",snap_scale);
/* SETTINGS DIALOG */
settings_dialog = memnew( ConfirmationDialog );
settings_dialog->set_title("Viewport Settings");
add_child(settings_dialog);
settings_vbc = memnew( VBoxContainer );
settings_vbc->set_custom_minimum_size(Size2(200,0));
settings_dialog->add_child(settings_vbc);
settings_dialog->set_child_rect(settings_vbc);
settings_light_base = memnew( Control );
settings_light_base->set_custom_minimum_size(Size2(128,128));
settings_light_base->connect("input_event",this,"_default_light_angle_input");
settings_vbc->add_margin_child("Default Light Normal:",settings_light_base);
settings_light_vp = memnew( Viewport );
settings_light_vp->set_disable_input(true);
settings_light_vp->set_use_own_world(true);
settings_light_base->add_child(settings_light_vp);
settings_dlight = memnew( DirectionalLight );
settings_light_vp->add_child(settings_dlight);
settings_sphere = memnew( ImmediateGeometry );
settings_sphere->begin(Mesh::PRIMITIVE_TRIANGLES,Ref<Texture>());
settings_sphere->set_color(Color(1,1,1));
settings_sphere->add_sphere(32,16,1);
settings_sphere->end();
settings_light_vp->add_child(settings_sphere);
settings_camera = memnew( Camera );
settings_light_vp->add_child(settings_camera);
settings_camera->set_translation(Vector3(0,0,2));
settings_camera->set_orthogonal(2.1,0.1,5);
settings_default_light_rot_x=Math_PI*0.3;
settings_default_light_rot_y=Math_PI*0.2;
settings_ambient_color = memnew( ColorPickerButton );
settings_vbc->add_margin_child("Ambient Light Color:",settings_ambient_color);
settings_ambient_color->connect("color_changed",this,"_update_ambient_light_color");
viewport_environment->set_enable_fx(Environment::FX_AMBIENT_LIGHT,true);
viewport_environment->fx_set_param(Environment::FX_PARAM_AMBIENT_LIGHT_COLOR,Color(0.15,0.15,0.15));
settings_ambient_color->set_color(Color(0.15,0.15,0.15));
settings_fov = memnew( SpinBox );
settings_fov->set_max(179);
settings_fov->set_min(1);
settings_fov->set_step(0.01);
settings_fov->set_val(EDITOR_DEF("3d_editor/default_fov",60.0));
settings_vbc->add_margin_child("Perspective FOV (deg.):",settings_fov);
settings_znear = memnew( SpinBox );
settings_znear->set_max(10000);
settings_znear->set_min(0.1);
settings_znear->set_step(0.01);
settings_znear->set_val(EDITOR_DEF("3d_editor/default_z_near",0.1));
settings_vbc->add_margin_child("View Z-Near:",settings_znear);
settings_zfar = memnew( SpinBox );
settings_zfar->set_max(10000);
settings_zfar->set_min(0.1);
settings_zfar->set_step(0.01);
settings_zfar->set_val(EDITOR_DEF("3d_editor/default_z_far",1500));
settings_vbc->add_margin_child("View Z-Far:",settings_zfar);
//settings_dialog->get_cancel()->hide();
/* XFORM DIALOG */
xform_dialog = memnew( ConfirmationDialog );
xform_dialog->set_title("Transform Change");
add_child(xform_dialog);
Label *l = memnew(Label);
l->set_text("Translate:");
l->set_pos(Point2(5,5));
xform_dialog->add_child(l);
for(int i=0;i<3;i++) {
xform_translate[i] = memnew( LineEdit );
xform_translate[i]->set_pos( Point2(15+i*60,22) );
xform_translate[i]->set_size( Size2(50,12 ) );
xform_dialog->add_child( xform_translate[i] );
}
l = memnew(Label);
l->set_text("Rotate (deg.):");
l->set_pos(Point2(5,45));
xform_dialog->add_child(l);
for(int i=0;i<3;i++) {
xform_rotate[i] = memnew( LineEdit );
xform_rotate[i]->set_pos( Point2(15+i*60,62) );
xform_rotate[i]->set_size( Size2(50,22 ) );
xform_dialog->add_child(xform_rotate[i]);
}
l = memnew(Label);
l->set_text("Scale (ratio):");
l->set_pos(Point2(5,85));
xform_dialog->add_child(l);
for(int i=0;i<3;i++) {
xform_scale[i] = memnew( LineEdit );
xform_scale[i]->set_pos( Point2(15+i*60,102) );
xform_scale[i]->set_size( Size2(50,22 ) );
xform_dialog->add_child(xform_scale[i]);
}
l = memnew(Label);
l->set_text("Transform Type");
l->set_pos(Point2(5,125));
xform_dialog->add_child(l);
xform_type = memnew( OptionButton );
xform_type->set_anchor( MARGIN_RIGHT, ANCHOR_END );
xform_type->set_begin( Point2(15,142) );
xform_type->set_end( Point2(15,75) );
xform_type->add_item("Pre");
xform_type->add_item("Post");
xform_dialog->add_child(xform_type);
xform_dialog->connect("confirmed", this,"_xform_dialog_action");
scenario_debug=VisualServer::SCENARIO_DEBUG_DISABLED;
selected=NULL;
set_process_unhandled_key_input(true);
add_to_group("_spatial_editor_group");
EDITOR_DEF("3d_editor/manipulator_gizmo_size",80);
EditorSettings::get_singleton()->add_property_hint(PropertyInfo(Variant::INT,"3d_editor/manipulator_gizmo_size",PROPERTY_HINT_RANGE,"16,1024,1"));
EDITOR_DEF("3d_editor/manipulator_gizmo_opacity",0.2);
over_gizmo_handle=-1;
}
SpatialEditor::~SpatialEditor() {
}
void SpatialEditorPlugin::make_visible(bool p_visible) {
if (p_visible) {
spatial_editor->show();
spatial_editor->set_process(true);
//VisualServer::get_singleton()->viewport_set_hide_scenario(editor->get_scene_root()->get_viewport(),false);
spatial_editor->grab_focus();
} else {
spatial_editor->hide();
spatial_editor->set_process(false);
//VisualServer::get_singleton()->viewport_set_hide_scenario(editor->get_scene_root()->get_viewport(),true);
}
}
void SpatialEditorPlugin::edit(Object *p_object) {
spatial_editor->edit(p_object->cast_to<Spatial>());
}
bool SpatialEditorPlugin::handles(Object *p_object) const {
return p_object->is_type("Spatial");
}
Dictionary SpatialEditorPlugin::get_state() const {
return spatial_editor->get_state();
}
void SpatialEditorPlugin::set_state(const Dictionary& p_state) {
spatial_editor->set_state(p_state);
}
void SpatialEditor::snap_cursor_to_plane(const Plane& p_plane) {
// cursor.pos=p_plane.project(cursor.pos);
}
void SpatialEditorPlugin::_bind_methods() {
ObjectTypeDB::bind_method("snap_cursor_to_plane",&SpatialEditorPlugin::snap_cursor_to_plane);
}
void SpatialEditorPlugin::snap_cursor_to_plane(const Plane& p_plane) {
spatial_editor->snap_cursor_to_plane(p_plane);
}
SpatialEditorPlugin::SpatialEditorPlugin(EditorNode *p_node) {
editor=p_node;
spatial_editor = memnew( SpatialEditor(p_node) );
editor->get_viewport()->add_child(spatial_editor);
spatial_editor->set_area_as_parent_rect();
spatial_editor->hide();
spatial_editor->connect("transform_key_request",editor,"_transform_keyed");
//spatial_editor->set_process(true);
}
SpatialEditorPlugin::~SpatialEditorPlugin() {
}
| mit |
guluc3m/gul-gultalks | db/migrate/20140826143607_create_speakers.rb | 462 | class CreateSpeakers < ActiveRecord::Migration[4.2]
def change
create_table :speakers do |t|
t.string :name, limit: 64, null: false
t.string :email, limit: 64, null: false
t.string :twitter, limit: 64
t.integer :event_id, null: false
t.boolean :certificate, default: false
t.boolean :confirmed, default: true
t.timestamps
end
end
def self.up
add_index :event_speakers, [:email, :event_id]
end
end
| mit |
gwu-libraries/launchpad | lp/ui/static/js/launchpad.js | 5470 | function showmore(id) {
var objt = document.getElementById("toggle-"+id);
var objb = document.getElementById("brief-"+id);
var objf = document.getElementById("full-"+id);
if(objf.style.display == 'block') {
objf.style.display='none';
objb.style.display='block';
objt.innerHTML="<a href=javascript:showmore('1');>[+] Show</a>";
}
else {
objf.style.display='block';
objb.style.display='none';
objt.innerHTML="<a href=javascript:showmore('1');>[-] Hide</a>";
}
}
function toggle_visibility(tbid,lnkid) {
if(document.all) {
document.getElementById(tbid).style.display = document.getElementById(tbid).style.display == "block" ? "none" : "block";
} else {
document.getElementById(tbid).style.display = document.getElementById(tbid).style.display == "table" ? "none" : "table";
}
document.getElementById(lnkid).value = document.getElementById(lnkid).value == "[-] Hide " ? "[+] Show " : "[-] Hide ";
}
var newwindow;
function sms(url) {
newwindow = window.open(url, 'name', 'height=590,width=400,toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0');
if (window.focus) {
newwindow.focus();
};
}
function cittogtxt(elemid) {
if ($(elemid).text() == 'Hide') {
$(elemid).text('Show');
} else {
$(elemid).text('Hide');
}
}
function check_availability() {
$(".offer").each(function(i, e) {
var offer = $(e);
var bibid = offer.attr('id');
// the id looks like offer-{bibid}
bibid = bibid.split('-')[1];
var url = '/availability?bibid=' + bibid;
$.ajax(url).done(add_availability);
});
}
function add_availability(availability) {
// first we need to collect up some of the availability information
// by location so we can have single lines for multiple items at the
// same location
var locations = {};
var callnumbers = {};
var descriptions = {}
for (var i = 0; i < availability.offers.length; i++) {
a = availability.offers[i];
var loc = a.availabilityAtOrFrom;
if (! locations[loc]) {
locations[loc] = 0
}
if (a.availability == "http://schema.org/InStock" ||
a.availability == "http://schema.org/InStoreOnly") {
locations[loc] += 1;
}
callnumbers[loc] = a.sku;
descriptions[loc] = a.description;
}
// get the offer element on the page
if (availability.summon) {
var offer = $('#offer-' + availability.summon);
} else {
var offer = $('#offer-' + availability.wrlc);
}
// if no availability information was available then hide the offer
if (availability.offers.length == 0) {
offer.hide();
}
// update the offer with the availability information
var locationCount = 0;
for (loc in locations) {
// if there are more than one locations then the original needs to
// be copied and added to the DOM so we can have a separate line
// for each unique location
locationCount += 1;
if (locationCount > 1) {
var o = offer.clone();
o.attr('id', o.attr('id') + '-' + locationCount);
offer.after(o);
offer = o;
}
if (locations[loc] > 1) {
var il = '(' + locations[loc] + ')';
offer.find('span[itemprop="description"]').text('Available');
} else {
offer.find('span[itemprop="description"]').text(descriptions[loc]);
}
offer.find('span[itemprop="availabilityAtOrFrom"]').text(loc);
if (callnumbers[loc]) {
offer.find('span[itemprop="sku"]').text(callnumbers[loc]);
}
}
}
$(document).ready(function() {
$('#cover-image').load(function() {
if ($('#cover-image').width() == 1) {
$('#cover').toggle(200);
};
$(".item_body").hide();
$(".item_head").click(function() {
$(this).next(".item_body").slideToggle(250);
});
});
$('img.cover-thumbnail').load(function(e) {
var img = $(this);
// sometimes summon api returns empty images with this width
if (img.width() != 99.79999995231628) {
$(this).show();
$(this).parents("article").css("min-height", "80px");
}
});
$("#citation_toggle").click(function() {
$("#citation_data").toggle('fast', function() { });
cittogtxt("#citation_toggle");
});
check_availability();
});
<!-- placeholder non-html5 fix -->
$(document).ready(function(){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
});
$('#online').click(function() {
$('#search').submit();
});
});
<!-- toggle Show/Hide for subjects -->
$(document).ready(function(){
$('.subjectsList, .periodicalsList').click(function(){
$(this).text(function(i,currentcontent){
return currentcontent == '[+] Show' ? '[-] Hide' : '[+] Show';
});
});
});
| mit |
otakuto/TomatoTool | Graphic/Palette/TransitionPalette.cs | 2754 | using System;
using System.Collections.Generic;
namespace TomatoTool
{
public class TransitionPalette
:
ROMObject
{
private uint address;
public override uint ObjectID
{
get
{
return address;
}
set
{
address = value;
}
}
private bool saved;
public override bool Saved
{
get
{
return saved;
}
set
{
saved = value;
}
}
public override uint Size
{
get
{
return MAIN_SIZE + ((uint)(palette.Count) * TomatoTool.Palette.SIZE);
}
}
public const uint ALIGNMENT = 4;
public override uint Alignment
{
get
{
return ALIGNMENT;
}
}
private byte overwritePaletteNumber;
public byte OverwritePaletteNumber
{
get
{
return overwritePaletteNumber;
}
set
{
if (value < 0x20)
{
overwritePaletteNumber = value;
}
else
{
throw new ArgumentOutOfRangeException();
}
}
}
private byte updateInterval;
public byte UpdateInterval
{
get
{
return updateInterval;
}
set
{
updateInterval = value;
}
}
private List<Palette> palette;
public List<Palette> Palette
{
get
{
return palette;
}
set
{
palette = value;
}
}
private byte number;
public byte Number
{
get
{
return number;
}
set
{
number = value;
}
}
//予想だと全部0x01
private byte unknownValue1;
public const uint MAIN_SIZE = 8;
public TransitionPalette(TomatoAdventure tomatoAdventure, uint address)
{
load(tomatoAdventure, address);
}
public void load(TomatoAdventure tomatoAdventure, uint address)
{
this.address = address;
unknownValue1 = tomatoAdventure.read(address);
overwritePaletteNumber = tomatoAdventure.read(address + 1);
updateInterval = tomatoAdventure.read(address + 2);
palette = new List<Palette>();
for (uint i = 0; i < tomatoAdventure.read(address + 3); ++i)
{
palette.Add(new Palette(tomatoAdventure, tomatoAdventure.readAsAddress(address + 4) + (i * TomatoTool.Palette.SIZE)));
}
}
public void save(TomatoAdventure tomatoAdventure, uint address)
{
this.address = address;
tomatoAdventure.write(address, unknownValue1);
tomatoAdventure.write(address + 1, overwritePaletteNumber);
tomatoAdventure.write(address + 2, updateInterval);
tomatoAdventure.write(address + 3, (byte)palette.Count);
for (uint i = 0; i < palette.Count; ++i)
{
palette[(int)i].save(tomatoAdventure, address + MAIN_SIZE + (i * TomatoTool.Palette.SIZE));
}
tomatoAdventure.writeAsAddress(address + 4, palette[0].ObjectID);
}
public Palette getPalette(ushort frame)
{
return palette[(frame / updateInterval) % palette.Count];
}
}
}
| mit |
rlworkgroup/metaworld | metaworld/envs/mujoco/sawyer_xyz/v2/sawyer_coffee_button_v2.py | 4374 | import numpy as np
from gym.spaces import Box
from metaworld.envs import reward_utils
from metaworld.envs.asset_path_utils import full_v2_path_for
from metaworld.envs.mujoco.sawyer_xyz.sawyer_xyz_env import SawyerXYZEnv, _assert_task_is_set
class SawyerCoffeeButtonEnvV2(SawyerXYZEnv):
def __init__(self):
self.max_dist = 0.03
hand_low = (-0.5, .4, 0.05)
hand_high = (0.5, 1., 0.5)
obj_low = (-0.1, 0.8, -.001)
obj_high = (0.1, 0.9, +.001)
# goal_low[3] would be .1, but objects aren't fully initialized until a
# few steps after reset(). In that time, it could be .01
goal_low = obj_low + np.array([-.001, -.22 + self.max_dist, .299])
goal_high = obj_high + np.array([+.001, -.22 + self.max_dist, .301])
super().__init__(
self.model_name,
hand_low=hand_low,
hand_high=hand_high,
)
self.init_config = {
'obj_init_pos': np.array([0, 0.9, 0.28]),
'obj_init_angle': 0.3,
'hand_init_pos': np.array([0., .4, .2]),
}
self.goal = np.array([0, 0.78, 0.33])
self.obj_init_pos = self.init_config['obj_init_pos']
self.obj_init_angle = self.init_config['obj_init_angle']
self.hand_init_pos = self.init_config['hand_init_pos']
self._random_reset_space = Box(
np.array(obj_low),
np.array(obj_high),
)
self.goal_space = Box(np.array(goal_low), np.array(goal_high))
@property
def model_name(self):
return full_v2_path_for('sawyer_xyz/sawyer_coffee.xml')
@_assert_task_is_set
def evaluate_state(self, obs, action):
(
reward,
tcp_to_obj,
tcp_open,
obj_to_target,
near_button,
button_pressed
) = self.compute_reward(action, obs)
info = {
'success': float(obj_to_target <= 0.02),
'near_object': float(tcp_to_obj <= 0.05),
'grasp_success': float(tcp_open > 0),
'grasp_reward': near_button,
'in_place_reward': button_pressed,
'obj_to_target': obj_to_target,
'unscaled_reward': reward,
}
return reward, info
@property
def _target_site_config(self):
return [('coffee_goal', self._target_pos)]
def _get_id_main_object(self):
return None
def _get_pos_objects(self):
return self._get_site_pos('buttonStart')
def _get_quat_objects(self):
return np.array([1., 0., 0., 0.])
def _set_obj_xyz(self, pos):
qpos = self.data.qpos.flatten()
qvel = self.data.qvel.flatten()
qpos[0:3] = pos.copy()
qvel[9:15] = 0
self.set_state(qpos, qvel)
def reset_model(self):
self._reset_hand()
self.obj_init_pos = self._get_state_rand_vec() if self.random_init \
else self.init_config['obj_init_pos']
self.sim.model.body_pos[self.model.body_name2id(
'coffee_machine'
)] = self.obj_init_pos
pos_mug = self.obj_init_pos + np.array([.0, -.22, .0])
self._set_obj_xyz(pos_mug)
pos_button = self.obj_init_pos + np.array([.0, -.22, .3])
self._target_pos = pos_button + np.array([.0, self.max_dist, .0])
return self._get_obs()
def compute_reward(self, action, obs):
del action
obj = obs[4:7]
tcp = self.tcp_center
tcp_to_obj = np.linalg.norm(obj - tcp)
tcp_to_obj_init = np.linalg.norm(obj - self.init_tcp)
obj_to_target = abs(self._target_pos[1] - obj[1])
tcp_closed = max(obs[3], 0.0)
near_button = reward_utils.tolerance(
tcp_to_obj,
bounds=(0, 0.05),
margin=tcp_to_obj_init,
sigmoid='long_tail',
)
button_pressed = reward_utils.tolerance(
obj_to_target,
bounds=(0, 0.005),
margin=self.max_dist,
sigmoid='long_tail',
)
reward = 2 * reward_utils.hamacher_product(tcp_closed, near_button)
if tcp_to_obj <= 0.05:
reward += 8 * button_pressed
return (
reward,
tcp_to_obj,
obs[3],
obj_to_target,
near_button,
button_pressed
)
| mit |
leifg/formulon | src/validations.js | 2137 | import ArgumentError from './errors/ArgumentError';
export const minNumOfParams = (expectedMinNumOfParams) => (fnName) => (params) => {
if (params.length < expectedMinNumOfParams) {
ArgumentError.throwIncorrectNumberOfArguments(fnName, expectedMinNumOfParams, params.length);
}
};
export const maxNumOfParams = (expectedMaxNumOfParams) => (fnName) => (params) => {
if (params.length > expectedMaxNumOfParams) {
ArgumentError.throwIncorrectNumberOfArguments(fnName, expectedMaxNumOfParams, params.length);
}
};
export const paramTypes = (...paramTypeList) => (fnName) => (params) => {
const comparableArray = params.map((literal, index) => [
literal.dataType, paramTypeList[index] || paramTypeList[paramTypeList.length - 1],
]);
// fill with last element of params, parameterlist is smaller than params
comparableArray.forEach(([received, expected]) => {
// allow null input in all functions
if (received !== 'null') {
if (Array.isArray(expected)) {
if (expected.indexOf(received) === -1) {
ArgumentError.throwWrongType(fnName, expected, received);
}
} else if (received !== expected) {
ArgumentError.throwWrongType(fnName, expected, received);
}
}
});
};
export const sameParamType = () => (fnName) => (params) => {
if (params.length > 0) {
params.filter((param) => param.dataType !== 'null').reduce((acc, current) => {
if (acc.dataType !== current.dataType) {
ArgumentError.throwWrongType(fnName, acc.dataType, current.dataType);
}
return current;
});
}
};
// special validation, to assure that all cases in a CASE statement match the input data type
export const caseParams = () => (fnName) => (params) => {
const expectedType = params[0].dataType === 'picklist' ? 'text' : params[0].dataType;
const cases = params.filter((_elem, index) => (
index % 2 === 1 && index !== (params.length - 1)
));
const differentCase = cases.find((elem) => elem.dataType !== expectedType);
if (differentCase) {
ArgumentError.throwWrongType(fnName, expectedType, differentCase.dataType);
}
};
| mit |
codehakase/studyLog | resources/views/tasks/index.blade.php | 2653 | @extends('layouts.app')
@section('content')
<!-- Bootstrap Boilerplate... -->
<div class="panel-body">
<!-- Display Validation Errors -->
@include('includes.flash')
<!-- New Task Form -->
<form action="{{ url('task') }}" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Task Name -->
<div class="form-group">
<label for="task-name" class="col-sm-3 control-label">Task</label>
<div class="col-sm-6">
<input type="text" name="name" id="task-name" class="form-control">
</div>
</div>
<!-- Add Task Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Task
</button>
</div>
</div>
</form>
</div>
@if(count($tasks) > 0)
<div class="col-lg-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">
Current Tasks
</div>
<div class="penel-body">
<table class="table table-striped task-table">
<thead>
<th>Task</th>
<th> </th>
<th> </th>
</thead>
<tbody>
@foreach($tasks as $task)
<tr>
<td class="table-text">
<div class="{{$task->status == 1 ? 'done': ''}}">{{ $task->name }}</div>
</td>
<td>
<form action="{{ url('task/'. $task->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger"> <i class="fa fa-btn fa-trash"></i> Delete</button>
</form>
</td>
<td>
@if($task->status == 1)
Completed
@else
<form action="{{ url('task/'. $task->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<button type="submit" class="btn btn-default"> Mark Done</button>
</form>
@endif
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
@endif
@endsection | mit |
maiktheknife/Scout | app/src/main/java/de/mm/android/longitude/fragment/SettingsFragment.java | 7243 | package de.mm.android.longitude.fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.MultiSelectListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.preference.TwoStatePreference;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.Set;
import de.mm.android.longitude.R;
import de.mm.android.longitude.common.ButtonPreference;
import de.mm.android.longitude.common.Constants;
import de.mm.android.longitude.location.Tracking;
import de.mm.android.longitude.util.NetworkUtil;
public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
public interface ISettings {
void onSignOut();
void onInstantUploadClicked();
void onGCMRegIDRenovationClicked();
void onLicensePressed();
}
public static SettingsFragment newInstance() {
return new SettingsFragment();
}
private static final String TAG = SettingsFragment.class.getSimpleName();
private ISettings callBack;
/* LifeCycle */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(Constants.PREFS_NAME_SETTINGS);
getPreferenceManager().setSharedPreferencesMode(Context.MODE_PRIVATE);
addPreferencesFromResource(R.xml.prefs_settings);
if (getActivity() instanceof ISettings) {
callBack = (ISettings) getActivity();
} else {
throw new IllegalStateException(getActivity().getClass().getName() + " must implement " + ISettings.class.getName());
}
}
@Override
public void onStart() {
super.onStart();
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable final Bundle savedInstanceState) {
View v = super.onCreateView(inflater, container, savedInstanceState);
findPreference(getString(R.string.prefs_key_location_instantupload)).setOnPreferenceClickListener(preference -> {
callBack.onInstantUploadClicked();
return true;
});
findPreference(getString(R.string.prefs_key_gcm_renovate)).setOnPreferenceClickListener(preference -> {
callBack.onGCMRegIDRenovationClicked();
return true;
});
findPreference(getString(R.string.prefs_key_about_license)).setOnPreferenceClickListener(preference -> {
callBack.onLicensePressed();
return true;
});
((ButtonPreference) findPreference(getString(R.string.prefs_key_account_email))).setOnButtonClickListener(callBack::onSignOut);
/* Set Values */
Preference p5 = findPreference(getString(R.string.prefs_key_about_version));
String thisVersion;
try {
PackageInfo pi = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
thisVersion = pi.versionName + " (" + pi.versionCode + ")";
} catch (PackageManager.NameNotFoundException e) {
thisVersion = "Could not get version name from manifest!";
}
p5.setSummary(thisVersion);
return v;
}
@Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
/* OnSharedPreferenceChangeListener */
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceGroup) { // PreferenceCategory oder PreferenceScreen
PreferenceGroup pCat = (PreferenceGroup) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p == null || p instanceof PreferenceScreen || p instanceof PreferenceCategory || p.getKey() == null) {
return;
}
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
} else if (p instanceof MultiSelectListPreference) {
MultiSelectListPreference m = (MultiSelectListPreference) p;
String s = "";
Set<String> c = m.getValues();
CharSequence[] x = m.getEntryValues();
CharSequence[] y = m.getEntries();
for (int i = 0; i < x.length; i++) {
if (c.contains(x[i])) {
s += y[i] + ", ";
}
}
if (s.length() > 2) {
s = s.substring(0, s.length() - 2);
} else {
s = "Keine";
}
m.setSummary(s);
} else if (p.getKey().equals(getString(R.string.prefs_key_account_email))){
String account = getPreferenceManager().getSharedPreferences().getString(getString(R.string.prefs_key_account_email), "");
p.setSummary(account);
} else if (p.getKey().equals(getString(R.string.prefs_key_location_tracking))) {
TwoStatePreference box = (TwoStatePreference) p;
if (box.isChecked()) {
new Tracking().start(getActivity());
} else {
new Tracking().stop(getActivity());
}
} else if (p.getKey().equals(getString(R.string.prefs_key_location_interval))) {
new Tracking().start(getActivity());
} else if (p.getKey().equals(getString(R.string.prefs_key_location_locating))) {
String locating = "";
boolean isGPS = NetworkUtil.isGPSEnabled(getActivity());
boolean isNetwork = NetworkUtil.isNetworkEnabled(getActivity());
if (isGPS && isNetwork) {
locating += "Netzwerk und GPS ";
} else if (isGPS) {
locating += "GPS ";
} else if (isNetwork) {
locating += "Netzwerk";
} else {
locating = "deaktiviert";
}
p.setSummary(locating);
}
}
} | mit |
nvlbg/SimpleGraph | src/simple-graph.js | 31227 | ;(function() {
"use strict";
var buckets;
if (typeof require !== "undefined") {
buckets = require("../lib/buckets.js");
} else if (typeof window !== "undefined") {
buckets = window.buckets;
}
var util = {
isObject: function(test) {
return Object.prototype.toString.call(test) === "[object Object]";
},
multiBagContains: function(bag, key) {
return typeof bag.dictionary.table[key] !== "undefined" &&
!bag.dictionary.table[key].value.isEmpty();
},
multiBagRemove: function(bag, key) {
var element = bag.dictionary.table[key];
if (!buckets.isUndefined(element)) {
bag.nElements -= element.value.size();
delete bag.dictionary.table[key];
bag.dictionary.nElements--;
return true;
}
return false;
},
multiBagContainsUndirectedEdge: function(bag, key) {
var element = bag.dictionary.table[key];
var ret = false;
if (!buckets.isUndefined(element)) {
element.value.forEach(function(edge) {
if (edge._directed === false) {
ret = true;
return false;
}
});
}
return ret;
},
s4: function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
},
guid: function() {
return util.s4() + util.s4() + '-' + util.s4() + '-' + util.s4() + '-' +
util.s4() + '-' + util.s4() + util.s4() + util.s4();
}
};
/**
* Enumeration for the direction property of a graph.
*
* @class sg.DIRECTION
* @static
* @final
*/
var DIRECTION = {
/**
* Indicates that the graph is not directed
*
* @property UNDIRECTED
* @static
* @final
*/
UNDIRECTED: 0,
/**
* Indicates that the graph is directed
*
* @property DIRECTED
* @static
* @final
*/
DIRECTED: 1,
/**
* Indicates that the graph is mixed (e.g. some edges are directed, others not)
*
* @property MIXED
* @static
* @final
*/
MIXED: 2,
/**
* Checks if the passed parameter is a DIRECTION
*
* @method isDirection
* @static
* @final
* @param dir
* @return {Boolean}
* @example
* sg.DIRECTION.isDirection( sg.DIRECTION.DIRECTED ); // true
* sg.DIRECTION.isDirection( "mixed" ); // false
* sg.DIRECTION.isDirection( true ); // false
*/
isDirection: function(dir) {
return dir === DIRECTION.UNDIRECTED ||
dir === DIRECTION.DIRECTED ||
dir === DIRECTION.MIXED;
}
};
/**
* Represents a graph node.
*
* @class sg.Node
* @constructor
* @param {String} id Node's identificator.
* Two nodes in a graph cannot have the same id.
* ***Must not be empty string***
* @param {Object} [options] Optional data object the user can store in the node.
* @example
* var a = new sg.Node("Example");
* var b = new sg.Node("Data", { index: 10 });
* var test = b.options.index < 100;
*/
function Node(id, options) {
if (typeof id !== "string" || id === "") {
throw "Invalid value for id.";
}
if (options && !util.isObject(options)) {
throw "The options param should be object.";
}
/**
* The node's identifier
*
* @private
* @property _id
* @type {String}
*/
this._id = id;
/**
* The graph of which the node is a member or undefined
*
* @private
* @property _graph
* @type {sg.Graph|undefined}
* @default undefined
*/
this._graph = undefined;
/**
* The edges connected to this node. ***Use only for reading!***
* The purpose of this property is for fast reading. If you change
* some elements you may brake something with the graph.
*
* **See also**: {{#crossLink "sg.Node/getEdges"}}getEdges{{/crossLink}}
*
* @property edges
* @type buckets.MultiBag of EdgeConnection
* @example
* var count = node.edges.size()
* node.edges.forEach(function(edge) {
* console.log( edge.options.value );
* });
*/
this.edges = new buckets.MultiBag(function(e) {
return e.node._id;
}, function(e) {
return e.edge._guid;
});
/**
* Custom object for storing arbitrary data
*
* @property options
* @type Object
* @defaut {}
* @example
* node.options.label = "My node";
* console.log( node.options.label ); // "My node"
*/
this.options = options || {};
}
/**
* Adds the appropriate EdgeConnection to Node.edges
*
* @private
* @method _addEdge
* @param {Edge|EdgeConnection} edge
*/
Node.prototype._addEdge = function(edge) {
if (!(edge instanceof Edge) && !(edge instanceof EdgeConnection)) {
throw "edge should be Edge or EdgeConnection.";
}
if (edge instanceof Edge) {
if (edge._sourceNode === this) {
this.edges.add(edge._sourceConnection);
}
if (edge._targetNode === this) {
this.edges.add(edge._targetConnection);
}
}
if (edge instanceof EdgeConnection) {
this.edges.add(edge);
}
};
/**
* Removes the appropriate EdgeConnection from Node.edges
*
* @private
* @method _removeEdge
* @param {Edge|EdgeConnection} edge
*/
Node.prototype._removeEdge = function(edge) {
if (!(edge instanceof Edge) && !(edge instanceof EdgeConnection)) {
throw "edge should be Edge or EdgeConnection.";
}
if (edge instanceof Edge) {
// remove both, because it can be a self-loop, and no error if not
this.edges.remove(edge._sourceConnection);
this.edges.remove(edge._targetConnection);
}
if (edge instanceof EdgeConnection) {
this.edges.remove(edge);
}
};
/**
* Adds the node in the passed graph. Shortcut for
* *{{#crossLink "sg.Graph/addNode"}}sg.Graph.addNode{{/crossLink}}*
*
* @method addToGraph
* @param {sg.Graph} graph
* @return {sg.Node} Reference to *this* node for method chaining
* @chainable
*/
Node.prototype.addToGraph = function(g) {
if (this._graph !== undefined) {
throw "This node is already in a graph.";
}
if (!(g instanceof Graph)) {
throw "The passed parameter is not a sg.Graph.";
}
g.addNode(this);
return this;
};
/**
* Removes the node from the graph containing him. Shortcut for
* *{{#crossLink "sg.Graph/removeNode"}}sg.Graph.removeNode{{/crossLink}}*
*
* @method removeFromGraph
* @return {sg.Node} Reference to *this* node for method chaining
* @chainable
*/
Node.prototype.removeFromGraph = function() {
if (this._graph === undefined) {
throw "The node is not in a graph.";
}
this._graph.removeNode(this);
return this;
};
/**
* Connect this node with another one
*
* @method connect
* @param {sg.Node|String} node The node you want to connect to this node
* @param {Object} [options] This object is passed to the Edge's constructor
* @return {sg.Node} Reference to *this* node for method chaining
* @chainable
*/
Node.prototype.connect = function(node, options) {
if (this._graph === undefined) {
throw "The node is not in a graph.";
}
this._graph.connect(this, node, options);
return this;
};
/**
* Detach this node from another one
*
* @method detach
* @param {sg.Node|String} node The node you want to detach from this node
* @return {sg.Node} Reference to *this* node for method chaining
* @chainable
*/
Node.prototype.detach = function(node) {
if (this._graph === undefined) {
throw "The node is not in a graph.";
}
this._graph.detach(this, node);
return this;
};
/**
* Getter for the node's identifier
*
* @method getId
* @return {String} The node's identifier
*/
Node.prototype.getId = function() {
return this._id;
};
/**
* Get an array containing all edges connected with the node.
* Adding/removing elements from the array won't affect the graph.
*
* @method getEdges
* @return {Array} Array of *EdgeConnection*s
*/
Node.prototype.getEdges = function() {
return this.edges.toArray();
};
/**
* Private class. Represents an edge (e.g. connection between 2 nodes).
*
* ***This class shouldn't be instanciated!***
*
* @class Edge
* @constructor
* @param {sg.Node} source Source node
* @param {sg.Node} target Target node
* @param {Object} [options] Optional data object the user can store in the edge.
* The options object may have the following properties
* (and/or any of your own):
* @param {Boolean} [options.directed=false] If true, the edge is directed source->target.
* If false, the edge has no direction.
*/
function Edge(a, b, options) {
if (!(a instanceof Node) || !(b instanceof Node)) {
throw "Params are not of type sg.Node.";
}
if (options && !util.isObject(options)) {
throw "The options param should be object.";
}
if (options && options.directed && typeof options.directed !== "boolean") {
throw "options.directed must be a boolean.";
}
/**
* Custom object for storing arbitrary data
*
* @property options
* @type Object
* @default {}
*/
this.options = options || {};
/**
* Edge's global unique identifier
*
* @private
* @property _guid
*/
this._guid = util.guid();
/**
* Key used for grouping edges between 2 nodes
*
* @private
* @property _key
*/
this._key = a._id + b._id;
/**
* If true, the edge is directed source->target. If false, the edge has no direction
*
* @private
* @property _directed
* @type Boolean
* @default false
*/
this._directed = options && options.directed ? options.directed : false;
/**
* The first end of the edge (e.g. the source node)
*
* @private
* @property _sourceNode
* @type sg.Node
*/
this._sourceNode = a;
/**
* The second end of the edge (e.g. the target node)
*
* @private
* @property _targetNode
* @type sg.Node
*/
this._targetNode = b;
/**
* The EdgeConnection that the source node need to have
*
* @private
* @property _sourceConnection
* @type EdgeConnection
*/
this._sourceConnection = new EdgeConnection(this, this._targetNode, this.options);
/**
* The EdgeConnection that the target node needs to have
*
* @private
* @property _targetConnection
* @type EdgeConnection
*/
this._targetConnection = new EdgeConnection(this, this._sourceNode, this.options);
/**
* The graph of which the edge is a member or undefined
*
* @private
* @property _graph
* @type {sg.Graph|undefined}
* @default undefined
*/
this._graph = undefined;
}
/**
* Getter for the source node
*
* @method getSource
* @return {sg.Node} The source node of the edge
*/
Edge.prototype.getSource = function() {
return this._sourceNode;
};
/**
* Getter for the target node
*
* @method getTarget
* @return {sg.Node} The target node of the edge
*/
Edge.prototype.getTarget = function() {
return this._targetNode;
};
/**
* Removes the edge from the graph containing him
*
* @chainable
* @method removeFromGraph
* @return {Edge} Reference to *this* edge for method chaining
*/
Edge.prototype.removeFromGraph = function() {
if (this._graph === undefined) {
throw "The edge is not in a graph.";
}
this._graph._removeEdge(this);
return this;
};
/**
* Getter/setter for the edge's direction
*
* @method directed
* @param {Boolean} [direction] The new direction of the edge
* @return {Boolean|Edge}
* If used as getter, returns whether or not the edge is directed.
* If used as setter, reference to *this* edge for method chaining.
*/
Edge.prototype.directed = function(d) {
if (d !== undefined) {
if (typeof d !== "boolean") {
throw "directed should be boolean.";
}
if (this._graph._direction !== DIRECTION.MIXED) {
throw "the graph direction should be mixed.";
}
this._directed = d;
return this;
}
return this._directed;
};
/**
* Private class. Represents a one-way edge,
* so each node can store only what it needs.
* Each edge has 2 EdgeConnections - one for each node.
*
* ***This class shouldn't be instanciated!***
*
* @class EdgeConnection
* @constructor
* @param {Edge} edge
* @param {sg.Node} node
* @param {Object} [options]
*/
function EdgeConnection(edge, node, options) {
/*jshint validthis:true */
if (!(edge instanceof Edge)) {
throw "The edge param should be Edge.";
}
if (!(node instanceof Node)) {
throw "The node param should be sg.Node.";
}
if (options && !util.isObject(options)) {
throw "The options param should be object.";
}
/**
* Reference to the edge
*
* @property edge
* @type {Edge}
*/
this.edge = edge;
/**
* Reference to one of the nodes in the edge
*
* @property node
* @type {sg.Node}
*/
this.node = node;
/**
* Reference to the Edge's options
*
* @property options
* @type {Object}
* @default {}
*/
this.options = options || {};
}
/**
* Represents a graph.
*
* @class sg.Graph
* @constructor
* @param {Object} [options] Optional data object the user can store in the graph.
* You can use this object for setting these properties:
* @param {sg.DIRECTION} [options.direction=sg.DIRECTION.UNDIRECTED]
* The direction of the graph
* @param {Boolean} [options.override=false]
* If true, adding a node with the same id as another one in the graph
* will override the old one.
* If false, an exception will be thrown.
* @param {Boolean} [options.multigraph=false] Indicates if the graph is a multigraph
* @param {Boolean} [options.selfloops=false] Indicates if selfloops are allowed
*/
function Graph(options) {
if (options && !util.isObject(options)) {
throw "The options param should be object.";
}
if (options && options.direction && !DIRECTION.isDirection(options.direction)) {
throw "Unknown direction.";
}
if (options && options.override && typeof options.override !== "boolean") {
throw "override should be boolean.";
}
if (options && options.multigraph && typeof options.multigraph !== "boolean") {
throw "multigraph should be boolean.";
}
if (options && options.selfloops && typeof options.selfloops !== "boolean") {
throw "selfloops should be boolean";
}
/**
* The direction of the graph
*
* @private
* @property _direction
* @type sg.DIRECTION
* @default sg.DIRECTION.UNDIRECTED
*/
this._direction = options && options.direction ? options.direction : DIRECTION.UNDIRECTED;
/**
* Indicates if the graph is a multigraph
*
* @private
* @property _multigraph
* @type Boolean
* @default false
*/
this._multigraph = options && options.multigraph ? options.multigraph : false;
/**
* If true, adding a node with the same id as another one in the graph
* will override the old one.
* If false, an exception will be thrown.
*
* @property override
* @type Boolean
* @default false
*/
this.override = options && options.override ? options.override : false;
/**
* Indicates if selfloops are allowed
*
* @property selfloops
* @type Boolean
* @default false
*/
this.selfloops = options && options.selfloops ? options.selfloops : false;
/**
* Custom object for storing arbitrary data
*
* @property options
* @type Object
* @default {}
*/
this.options = options || {};
/**
* A dictionary containing the graph nodes.
* ***Use only for reading!***
* The purpose of this property is for fast reading. If you change
* some elements you may brake something with the graph.
*
* @property nodes
* @type buckets.Dictionary of String->sg.Node
*/
this.nodes = new buckets.Dictionary();
/**
* The edges in the graph.
* ***Use only for reading!***
* The purpose of this property is for fast reading. If you change
* some elements you may brake something with the graph.
*
* @property edges
* @type buckets.MultiBag of Edge
*/
this.edges = new buckets.MultiBag(function(e) {
return e._key;
}, function(e) {
return e._guid;
});
}
/**
* Removes edge from the graph
*
* @private
* @method _removeEdge
* @param {Edge|EdgeConnection} edge
*/
Graph.prototype._removeEdge = function(edge) {
/*jshint expr:true */
if (!(edge instanceof Edge) && !(edge instanceof EdgeConnection)) {
throw "edge sgould be Edge or EdgeConnection.";
}
if (edge instanceof EdgeConnection) {
edge = edge.edge;
}
edge._sourceNode._removeEdge(edge);
!edge._directed && edge._targetNode._removeEdge(edge);
this.edges.remove(edge);
};
/**
* Add node to the graph
*
* @method addNode
* @param {String|sg.Node} node
* If {String}, new sg.Node will be created with this string as its id, and will be added to the graph.
* If {sg.Node}, the node will be added to the graph.
*/
Graph.prototype.addNode = function(node) {
if ((typeof node !== "string" || node === "") && !(node instanceof Node)) {
throw "Invalid node: " + node;
}
var id = node._id || node;
if ( !this.override && this.nodes.get(id) !== undefined ) {
throw "A node with id \"" + id + "\" already exists in this graph." +
"(Use the option override if needed)";
}
if ( node instanceof Node && node._graph !== undefined ) {
throw "The node \"" + id + "\" is in another graph.";
}
node = node instanceof Node ? node : new Node(id);
this.nodes.set(id, node);
node._graph = this;
};
/**
* Removes node from the graph
*
* @method removeNode
* @param {String|sg.Node} node
* If {String}, the node with id the string will be removed from the graph.
* If {sg.Node}, the node will be removed from the graph.
*/
Graph.prototype.removeNode = function(node) {
if ((typeof node !== "string" || node === "") && !(node instanceof Node)) {
throw "Invalid node: " + node;
}
var id = node._id || node;
if (this.nodes.get(id) === undefined ||
(node instanceof Node && this.nodes.get(id) !== node)) {
throw "The passed node is not in this graph.";
}
node = this.nodes.get(id);
this.edges.forEach(function(edge) {
var source = edge._sourceNode;
var target = edge._targetNode;
if (source === node || target === node) {
if (source !== node) {
source._removeEdge(edge);
}
if (target !== node) {
target._removeEdge(edge);
}
this.edges.remove(edge);
}
}.bind(this));
node._graph = undefined;
node.edges.clear();
this.nodes.remove(id);
};
/**
* Creates an edge between two nodes
*
* @method connect
* @param {sg.Node|String} source The source node (or its id)
* @param {sg.Node|String} target The target node (or its id)
* @param {Object} [options] Optional options object passed to the Edge's
* constructor.
* See *{{#crossLink "Edge"}}Edge{{/crossLink}}*
* for more details.
*/
Graph.prototype.connect = function(a, b, options) {
/*jshint expr:true */
var aId = a._id || a;
var bId = b._id || b;
if (this.nodes.get(aId) === undefined) {
throw "Node \"" + aId + "\" isn't in the graph.";
}
if (this.nodes.get(bId) === undefined) {
throw "Node \"" + bId + "\" isn't in the graph.";
}
if (!this._multigraph &&
(util.multiBagContains(this.edges, aId + bId) ||
util.multiBagContainsUndirectedEdge(this.edges, bId + aId))
) {
throw "Edge between " + aId + " and " + bId + " already exists.";
}
if (!this.selfloops && aId === bId) {
throw "Slefloops are not allowed.";
}
if (options && !util.isObject(options)) {
throw "Options must be an object.";
}
var source = this.nodes.get(aId);
var target = this.nodes.get(bId);
options = options || {};
if (this._direction === DIRECTION.UNDIRECTED) {
options.directed = false;
} else if (this._direction === DIRECTION.DIRECTED) {
options.directed = true;
}
var edge = new Edge(source, target, options);
edge._graph = this;
source._addEdge(edge._sourceConnection);
!options.directed && source !== target && target._addEdge(edge._targetConnection);
this.edges.add(edge);
};
/**
* Removes ***all*** edges between two nodes.
* ***Be careful!*** This method does not differ directed edges, so calling this
* method with the nodes (a, b) will remove all edges (b, a) as well.
*
* **See also**: *{{#crossLink "Edge/removeFromGraph"}}Edge.removeFromGraph{{/crossLink}}*
*
* @method detach
* @param {sg.Node|String} source The source node (or its id)
* @param {sg.Node|String} target The target node (or its id)
*/
Graph.prototype.detach = function(a, b) {
var aId = a._id || a;
var bId = b._id || b;
if (this.nodes.get(aId) === undefined) {
throw "Node \"" + aId + "\" isn't in the graph.";
}
if (this.nodes.get(bId) === undefined) {
throw "Node \"" + bId + "\" isn't in the graph.";
}
if (util.multiBagRemove(this.edges, aId + bId) ||
util.multiBagRemove(this.edges, bId + aId)) {
util.multiBagRemove(this.nodes.get(aId).edges, bId);
util.multiBagRemove(this.nodes.get(bId).edges, aId);
}
};
/**
* Get node by its id
*
* @method getNode
* @param {String} id The id of the wanted node
* @return {sg.Node} The node itself
*/
Graph.prototype.getNode = function(id) {
return this.nodes.get(id);
};
/**
* Getter/setter for the graph's direction
*
* @method direction
* @chainable
* @param {sg.DIRECTION} [direction] The new desired direction of the graph
* @return {sg.Graph|sg.DIRECTION}
* If used as getter, will return the current graph's direction.
* If used as setter, will return reference to *this* graph for method chaining.
*/
Graph.prototype.direction = function(direction) {
if (direction !== undefined) {
if (!DIRECTION.isDirection(direction)) {
throw "Unknown direction.";
}
if (direction === this._direction) {
return this;
}
if (direction === DIRECTION.UNDIRECTED ||
direction === DIRECTION.DIRECTED) {
var directed = direction === DIRECTION.DIRECTED;
this.edges.forEach(function(edge) {
if (edge._directed !== directed) {
if (edge._directed === true) {
edge._targetNode._addEdge( edge._targetConnection );
} else {
edge._targetNode._removeEdge( edge._targetConnection );
}
edge._directed = directed;
}
});
}
this._direction = direction;
return this;
}
return this._direction;
};
/**
* Getter/setter for the graph's multigraph property
*
* @method multigraph
* @chainable
* @param {Boolean} [multigraph] The new desired multigraph property
* @return {sg.Graph|Boolean}
* If used as getter, will return the current multigraph property (e.g. Boolean).
* If used as setter, will return reference to *this* graph for method chaining.
*/
Graph.prototype.multigraph = function(multigraph) {
if (multigraph !== undefined) {
if (typeof multigraph !== "boolean") {
throw "multigraph should be boolean.";
}
if (multigraph === this._multigraph) {
return this;
}
if (this._multigraph === true) {
this.edges.normalize();
}
this._multigraph = multigraph;
return this;
}
return this._multigraph;
};
/**
* Getter/setter for the graph's override property
*
* @method override
* @chainable
* @param {Boolean} [override] The new desired override property
* @return {sg.Graph|Boolean}
* If used as getter, will return the current override property (e.g. Boolean).
* If used as setter, will return reference to *this* graph for method chaining.
*/
Graph.prototype.override = function(override) {
if (override !== undefined) {
if (typeof override !== "boolean") {
throw "override should be boolean.";
}
this.override = override;
return this;
}
return this.override;
};
/**
* Getter/setter for the graph's selfloops property
*
* @method selfloops
* @chainable
* @param {Boolean} [selfloops] The new desired selfloops property
* @return {sg.Graph|Boolean}
* If used as getter, will return the current selfloops property (e.g. Boolean).
* If used as setter, will return reference to *this* graph for method chaining.
*/
Graph.prototype.selfloops = function(selfloops) {
if (selfloops !== undefined) {
if (typeof selfloops !== "boolean") {
throw "selfloops should be boolean.";
}
this.selfloops = selfloops;
return this;
}
return this.selfloops;
};
function AbstractRenderer(graph) {
this.refresh = function() { throw "Unimplemented method."; };
this.draw = function() { throw "Unimplemented method."; };
}
function ConsoleRenderer(g) {
if (!(g instanceof sg.Graph)) {
throw "I don't know how to render " + g;
}
var graph = g;
this.refresh = function() { return; };
this.draw = function() {
graph.nodes.forEach(function(key, node) {
var line = [key, ": "];
var edges = node.getEdges();
edges.forEach(function(edge) {
line.push(edge.node.getId());
line.push(",");
});
line.pop();
console.log(line.join(""));
});
};
}
ConsoleRenderer.prototype = new AbstractRenderer();
/**
* Simple Graph - a library for manipulating graphs
*
* @module sg
* @requires Buckets
*/
var sg = {
DIRECTION: DIRECTION,
Node: Node,
Graph: Graph,
Renderer: {
AbstractRenderer: AbstractRenderer,
ConsoleRenderer : ConsoleRenderer
}
};
if (typeof JASMINE_TEST !== "undefined") {
sg.Edge = Edge;
sg.EdgeConnection = EdgeConnection;
}
if (typeof module !== "undefined") { module.exports = sg; }
else if (typeof window !== "undefined") { window.sg = window.sg || sg; }
}());
| mit |
tanguygiga/dta-formation | DTA-Chat/src/dta/chat/model/observer/ChatObserver.java | 123 | package dta.chat.model.observer;
public interface ChatObserver<T> {
void update(ChatObservable<T> observable, T obj);
}
| mit |
AlexandreGenecque/MoteurRechercheCHU | src/MoteurRechercheBundle/Form/NaturePrelevementType.php | 828 | <?php
namespace MoteurRechercheBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class NaturePrelevementType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nomNaturePrelevement')
->add('precisionPrelevement')
->add('analyses')
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MoteurRechercheBundle\Entity\NaturePrelevement'
));
}
}
| mit |
uniquoooo/CSManager | src/Manager/Migrations/Servers.php | 683 | <?php
/*
* This file is apart of the CSManager project.
*
* Copyright (c) 2016 David Cole <david@team-reflex.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the LICENSE file.
*/
namespace Manager\Migrations;
class Servers
{
/**
* Runs the migrations.
*
* @param Blueprint $table
*
* @return void
*/
public function up($table)
{
$table->increments('id');
$table->string('name');
$table->string('ip');
$table->integer('port')->default(27015);
$table->string('gotv_ip');
$table->string('rcon');
$table->timestamps();
}
}
| mit |
betabrand/goad | Godeps/_workspace/src/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_test.go | 67611 | package query_test
import (
"bytes"
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
"net/http"
"net/url"
"testing"
"time"
"github.com/aws/aws-sdk-go/awstesting"
"github.com/aws/aws-sdk-go/private/util"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/client"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/session"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/private/protocol/query"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/aws/aws-sdk-go/private/signer/v4"
"github.com/gophergala2016/goad/Godeps/_workspace/src/github.com/stretchr/testify/assert"
)
var _ bytes.Buffer // always import bytes
var _ http.Request
var _ json.Marshaler
var _ time.Time
var _ xmlutil.XMLNode
var _ xml.Attr
var _ = awstesting.GenerateAssertions
var _ = ioutil.Discard
var _ = util.Trim("")
var _ = url.Values{}
var _ = io.EOF
var _ = aws.String
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService1ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService1ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService1ProtocolTest client from just a session.
// svc := outputservice1protocoltest.New(mySession)
//
// // Create a OutputService1ProtocolTest client with additional configuration
// svc := outputservice1protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService1ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService1ProtocolTest {
c := p.ClientConfig("outputservice1protocoltest", cfgs...)
return newOutputService1ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService1ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService1ProtocolTest {
svc := &OutputService1ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice1protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService1ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService1ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService1TestCaseOperation1 = "OperationName"
// OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation.
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *request.Request, output *OutputService1TestShapeOutputService1TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService1TestCaseOperation1,
}
if input == nil {
input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService1TestShapeOutputService1TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (*OutputService1TestShapeOutputService1TestCaseOperation1Output, error) {
req, out := c.OutputService1TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService1TestShapeOutputService1TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService1TestShapeOutputService1TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Char *string `type:"character"`
Double *float64 `type:"double"`
FalseBool *bool `type:"boolean"`
Float *float64 `type:"float"`
Long *int64 `type:"long"`
Num *int64 `locationName:"FooNum" type:"integer"`
Str *string `type:"string"`
Timestamp *time.Time `type:"timestamp" timestampFormat:"iso8601"`
TrueBool *bool `type:"boolean"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService2ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService2ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService2ProtocolTest client from just a session.
// svc := outputservice2protocoltest.New(mySession)
//
// // Create a OutputService2ProtocolTest client with additional configuration
// svc := outputservice2protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService2ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService2ProtocolTest {
c := p.ClientConfig("outputservice2protocoltest", cfgs...)
return newOutputService2ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService2ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService2ProtocolTest {
svc := &OutputService2ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice2protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService2ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService2ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService2TestCaseOperation1 = "OperationName"
// OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation.
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *request.Request, output *OutputService2TestShapeOutputService2TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService2TestCaseOperation1,
}
if input == nil {
input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService2TestShapeOutputService2TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (*OutputService2TestShapeOutputService2TestCaseOperation1Output, error) {
req, out := c.OutputService2TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService2TestShapeOutputService2TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService2TestShapeOutputService2TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Num *int64 `type:"integer"`
Str *string `type:"string"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService3ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService3ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService3ProtocolTest client from just a session.
// svc := outputservice3protocoltest.New(mySession)
//
// // Create a OutputService3ProtocolTest client with additional configuration
// svc := outputservice3protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService3ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService3ProtocolTest {
c := p.ClientConfig("outputservice3protocoltest", cfgs...)
return newOutputService3ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService3ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService3ProtocolTest {
svc := &OutputService3ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice3protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService3ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService3ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService3TestCaseOperation1 = "OperationName"
// OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation.
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *request.Request, output *OutputService3TestShapeOutputService3TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService3TestCaseOperation1,
}
if input == nil {
input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService3TestShapeOutputService3TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (*OutputService3TestShapeOutputService3TestCaseOperation1Output, error) {
req, out := c.OutputService3TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService3TestShapeOutputService3TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService3TestShapeOutputService3TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Blob []byte `type:"blob"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService4ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService4ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService4ProtocolTest client from just a session.
// svc := outputservice4protocoltest.New(mySession)
//
// // Create a OutputService4ProtocolTest client with additional configuration
// svc := outputservice4protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService4ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService4ProtocolTest {
c := p.ClientConfig("outputservice4protocoltest", cfgs...)
return newOutputService4ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService4ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService4ProtocolTest {
svc := &OutputService4ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice4protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService4ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService4ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService4TestCaseOperation1 = "OperationName"
// OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation.
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *request.Request, output *OutputService4TestShapeOutputService4TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService4TestCaseOperation1,
}
if input == nil {
input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService4TestShapeOutputService4TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (*OutputService4TestShapeOutputService4TestCaseOperation1Output, error) {
req, out := c.OutputService4TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService4TestShapeOutputService4TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService4TestShapeOutputService4TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService5ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService5ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService5ProtocolTest client from just a session.
// svc := outputservice5protocoltest.New(mySession)
//
// // Create a OutputService5ProtocolTest client with additional configuration
// svc := outputservice5protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService5ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService5ProtocolTest {
c := p.ClientConfig("outputservice5protocoltest", cfgs...)
return newOutputService5ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService5ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService5ProtocolTest {
svc := &OutputService5ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice5protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService5ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService5ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService5TestCaseOperation1 = "OperationName"
// OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation.
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *request.Request, output *OutputService5TestShapeOutputService5TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService5TestCaseOperation1,
}
if input == nil {
input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService5TestShapeOutputService5TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (*OutputService5TestShapeOutputService5TestCaseOperation1Output, error) {
req, out := c.OutputService5TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService5TestShapeOutputService5TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService5TestShapeOutputService5TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `locationNameList:"item" type:"list"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService6ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService6ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService6ProtocolTest client from just a session.
// svc := outputservice6protocoltest.New(mySession)
//
// // Create a OutputService6ProtocolTest client with additional configuration
// svc := outputservice6protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService6ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService6ProtocolTest {
c := p.ClientConfig("outputservice6protocoltest", cfgs...)
return newOutputService6ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService6ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService6ProtocolTest {
svc := &OutputService6ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice6protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService6ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService6ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService6TestCaseOperation1 = "OperationName"
// OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation.
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *request.Request, output *OutputService6TestShapeOutputService6TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService6TestCaseOperation1,
}
if input == nil {
input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService6TestShapeOutputService6TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (*OutputService6TestShapeOutputService6TestCaseOperation1Output, error) {
req, out := c.OutputService6TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService6TestShapeOutputService6TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService6TestShapeOutputService6TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService7ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService7ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService7ProtocolTest client from just a session.
// svc := outputservice7protocoltest.New(mySession)
//
// // Create a OutputService7ProtocolTest client with additional configuration
// svc := outputservice7protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService7ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService7ProtocolTest {
c := p.ClientConfig("outputservice7protocoltest", cfgs...)
return newOutputService7ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService7ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService7ProtocolTest {
svc := &OutputService7ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice7protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService7ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService7ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService7TestCaseOperation1 = "OperationName"
// OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation.
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *request.Request, output *OutputService7TestShapeOutputService7TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService7TestCaseOperation1,
}
if input == nil {
input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService7TestShapeOutputService7TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (*OutputService7TestShapeOutputService7TestCaseOperation1Output, error) {
req, out := c.OutputService7TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService7TestShapeOutputService7TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService7TestShapeOutputService7TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
ListMember []*string `type:"list" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService8ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService8ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService8ProtocolTest client from just a session.
// svc := outputservice8protocoltest.New(mySession)
//
// // Create a OutputService8ProtocolTest client with additional configuration
// svc := outputservice8protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService8ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService8ProtocolTest {
c := p.ClientConfig("outputservice8protocoltest", cfgs...)
return newOutputService8ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService8ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService8ProtocolTest {
svc := &OutputService8ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice8protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService8ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService8ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService8TestCaseOperation1 = "OperationName"
// OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation.
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *request.Request, output *OutputService8TestShapeOutputService8TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService8TestCaseOperation1,
}
if input == nil {
input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService8TestShapeOutputService8TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (*OutputService8TestShapeOutputService8TestCaseOperation1Output, error) {
req, out := c.OutputService8TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService8TestShapeOutputService8TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService8TestShapeOutputService8TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
List []*OutputService8TestShapeStructureShape `type:"list"`
}
type OutputService8TestShapeStructureShape struct {
_ struct{} `type:"structure"`
Bar *string `type:"string"`
Baz *string `type:"string"`
Foo *string `type:"string"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService9ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService9ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService9ProtocolTest client from just a session.
// svc := outputservice9protocoltest.New(mySession)
//
// // Create a OutputService9ProtocolTest client with additional configuration
// svc := outputservice9protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService9ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService9ProtocolTest {
c := p.ClientConfig("outputservice9protocoltest", cfgs...)
return newOutputService9ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService9ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService9ProtocolTest {
svc := &OutputService9ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice9protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService9ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService9ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService9TestCaseOperation1 = "OperationName"
// OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation.
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *request.Request, output *OutputService9TestShapeOutputService9TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService9TestCaseOperation1,
}
if input == nil {
input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService9TestShapeOutputService9TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (*OutputService9TestShapeOutputService9TestCaseOperation1Output, error) {
req, out := c.OutputService9TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService9TestShapeOutputService9TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService9TestShapeOutputService9TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
List []*OutputService9TestShapeStructureShape `type:"list" flattened:"true"`
}
type OutputService9TestShapeStructureShape struct {
_ struct{} `type:"structure"`
Bar *string `type:"string"`
Baz *string `type:"string"`
Foo *string `type:"string"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService10ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService10ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService10ProtocolTest client from just a session.
// svc := outputservice10protocoltest.New(mySession)
//
// // Create a OutputService10ProtocolTest client with additional configuration
// svc := outputservice10protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService10ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService10ProtocolTest {
c := p.ClientConfig("outputservice10protocoltest", cfgs...)
return newOutputService10ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService10ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService10ProtocolTest {
svc := &OutputService10ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice10protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService10ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService10ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService10TestCaseOperation1 = "OperationName"
// OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation.
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *request.Request, output *OutputService10TestShapeOutputService10TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService10TestCaseOperation1,
}
if input == nil {
input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService10TestShapeOutputService10TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (*OutputService10TestShapeOutputService10TestCaseOperation1Output, error) {
req, out := c.OutputService10TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService10TestShapeOutputService10TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService10TestShapeOutputService10TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
List []*string `locationNameList:"NamedList" type:"list" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService11ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService11ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService11ProtocolTest client from just a session.
// svc := outputservice11protocoltest.New(mySession)
//
// // Create a OutputService11ProtocolTest client with additional configuration
// svc := outputservice11protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService11ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService11ProtocolTest {
c := p.ClientConfig("outputservice11protocoltest", cfgs...)
return newOutputService11ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService11ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService11ProtocolTest {
svc := &OutputService11ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice11protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService11ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService11ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService11TestCaseOperation1 = "OperationName"
// OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation.
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *request.Request, output *OutputService11TestShapeOutputService11TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService11TestCaseOperation1,
}
if input == nil {
input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService11TestShapeOutputService11TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (*OutputService11TestShapeOutputService11TestCaseOperation1Output, error) {
req, out := c.OutputService11TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService11TestShapeOutputService11TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService11TestShapeOutputService11TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*OutputService11TestShapeStructType `type:"map"`
}
type OutputService11TestShapeStructType struct {
_ struct{} `type:"structure"`
Foo *string `locationName:"foo" type:"string"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService12ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService12ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService12ProtocolTest client from just a session.
// svc := outputservice12protocoltest.New(mySession)
//
// // Create a OutputService12ProtocolTest client with additional configuration
// svc := outputservice12protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService12ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService12ProtocolTest {
c := p.ClientConfig("outputservice12protocoltest", cfgs...)
return newOutputService12ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService12ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService12ProtocolTest {
svc := &OutputService12ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice12protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService12ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService12ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService12TestCaseOperation1 = "OperationName"
// OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation.
func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *request.Request, output *OutputService12TestShapeOutputService12TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService12TestCaseOperation1,
}
if input == nil {
input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService12TestShapeOutputService12TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (*OutputService12TestShapeOutputService12TestCaseOperation1Output, error) {
req, out := c.OutputService12TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService12TestShapeOutputService12TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService12TestShapeOutputService12TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `type:"map" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService13ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService13ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService13ProtocolTest client from just a session.
// svc := outputservice13protocoltest.New(mySession)
//
// // Create a OutputService13ProtocolTest client with additional configuration
// svc := outputservice13protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService13ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService13ProtocolTest {
c := p.ClientConfig("outputservice13protocoltest", cfgs...)
return newOutputService13ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService13ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService13ProtocolTest {
svc := &OutputService13ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice13protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService13ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService13ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService13TestCaseOperation1 = "OperationName"
// OutputService13TestCaseOperation1Request generates a request for the OutputService13TestCaseOperation1 operation.
func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *request.Request, output *OutputService13TestShapeOutputService13TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService13TestCaseOperation1,
}
if input == nil {
input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService13TestShapeOutputService13TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (*OutputService13TestShapeOutputService13TestCaseOperation1Output, error) {
req, out := c.OutputService13TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService13TestShapeOutputService13TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService13TestShapeOutputService13TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `locationName:"Attribute" locationNameKey:"Name" locationNameValue:"Value" type:"map" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService14ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService14ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService14ProtocolTest client from just a session.
// svc := outputservice14protocoltest.New(mySession)
//
// // Create a OutputService14ProtocolTest client with additional configuration
// svc := outputservice14protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService14ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService14ProtocolTest {
c := p.ClientConfig("outputservice14protocoltest", cfgs...)
return newOutputService14ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService14ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService14ProtocolTest {
svc := &OutputService14ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice14protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService14ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService14ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService14TestCaseOperation1 = "OperationName"
// OutputService14TestCaseOperation1Request generates a request for the OutputService14TestCaseOperation1 operation.
func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *request.Request, output *OutputService14TestShapeOutputService14TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService14TestCaseOperation1,
}
if input == nil {
input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService14TestShapeOutputService14TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (*OutputService14TestShapeOutputService14TestCaseOperation1Output, error) {
req, out := c.OutputService14TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService14TestShapeOutputService14TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService14TestShapeOutputService14TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Map map[string]*string `locationNameKey:"foo" locationNameValue:"bar" type:"map" flattened:"true"`
}
//The service client's operations are safe to be used concurrently.
// It is not safe to mutate any of the client's properties though.
type OutputService15ProtocolTest struct {
*client.Client
}
// New creates a new instance of the OutputService15ProtocolTest client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a OutputService15ProtocolTest client from just a session.
// svc := outputservice15protocoltest.New(mySession)
//
// // Create a OutputService15ProtocolTest client with additional configuration
// svc := outputservice15protocoltest.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func NewOutputService15ProtocolTest(p client.ConfigProvider, cfgs ...*aws.Config) *OutputService15ProtocolTest {
c := p.ClientConfig("outputservice15protocoltest", cfgs...)
return newOutputService15ProtocolTestClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion)
}
// newClient creates, initializes and returns a new service client instance.
func newOutputService15ProtocolTestClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string) *OutputService15ProtocolTest {
svc := &OutputService15ProtocolTest{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: "outputservice15protocoltest",
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBack(v4.Sign)
svc.Handlers.Build.PushBack(query.Build)
svc.Handlers.Unmarshal.PushBack(query.Unmarshal)
svc.Handlers.UnmarshalMeta.PushBack(query.UnmarshalMeta)
svc.Handlers.UnmarshalError.PushBack(query.UnmarshalError)
return svc
}
// newRequest creates a new request for a OutputService15ProtocolTest operation and runs any
// custom request initialization.
func (c *OutputService15ProtocolTest) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
return req
}
const opOutputService15TestCaseOperation1 = "OperationName"
// OutputService15TestCaseOperation1Request generates a request for the OutputService15TestCaseOperation1 operation.
func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1Request(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (req *request.Request, output *OutputService15TestShapeOutputService15TestCaseOperation1Output) {
op := &request.Operation{
Name: opOutputService15TestCaseOperation1,
}
if input == nil {
input = &OutputService15TestShapeOutputService15TestCaseOperation1Input{}
}
req = c.newRequest(op, input, output)
output = &OutputService15TestShapeOutputService15TestCaseOperation1Output{}
req.Data = output
return
}
func (c *OutputService15ProtocolTest) OutputService15TestCaseOperation1(input *OutputService15TestShapeOutputService15TestCaseOperation1Input) (*OutputService15TestShapeOutputService15TestCaseOperation1Output, error) {
req, out := c.OutputService15TestCaseOperation1Request(input)
err := req.Send()
return out, err
}
type OutputService15TestShapeOutputService15TestCaseOperation1Input struct {
_ struct{} `type:"structure"`
}
type OutputService15TestShapeOutputService15TestCaseOperation1Output struct {
_ struct{} `type:"structure"`
Foo *string `type:"string"`
}
//
// Tests begin here
//
func TestOutputService1ProtocolTestScalarMembersCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService1ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Str>myname</Str><FooNum>123</FooNum><FalseBool>false</FalseBool><TrueBool>true</TrueBool><Float>1.2</Float><Double>1.3</Double><Long>200</Long><Char>a</Char><Timestamp>2015-01-25T08:00:00Z</Timestamp></OperationNameResult><ResponseMetadata><RequestId>request-id</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService1TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "a", *out.Char)
assert.Equal(t, 1.3, *out.Double)
assert.Equal(t, false, *out.FalseBool)
assert.Equal(t, 1.2, *out.Float)
assert.Equal(t, int64(200), *out.Long)
assert.Equal(t, int64(123), *out.Num)
assert.Equal(t, "myname", *out.Str)
assert.Equal(t, time.Unix(1.4221728e+09, 0).UTC().String(), out.Timestamp.String())
assert.Equal(t, true, *out.TrueBool)
}
func TestOutputService2ProtocolTestNotAllMembersInResponseCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService2ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Str>myname</Str></OperationNameResult><ResponseMetadata><RequestId>request-id</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService2TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "myname", *out.Str)
}
func TestOutputService3ProtocolTestBlobCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService3ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Blob>dmFsdWU=</Blob></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService3TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "value", string(out.Blob))
}
func TestOutputService4ProtocolTestListsCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService4ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><ListMember><member>abc</member><member>123</member></ListMember></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService4TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "abc", *out.ListMember[0])
assert.Equal(t, "123", *out.ListMember[1])
}
func TestOutputService5ProtocolTestListWithCustomMemberNameCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService5ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><ListMember><item>abc</item><item>123</item></ListMember></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService5TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "abc", *out.ListMember[0])
assert.Equal(t, "123", *out.ListMember[1])
}
func TestOutputService6ProtocolTestFlattenedListCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService6ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><ListMember>abc</ListMember><ListMember>123</ListMember></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService6TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "abc", *out.ListMember[0])
assert.Equal(t, "123", *out.ListMember[1])
}
func TestOutputService7ProtocolTestFlattenedSingleElementListCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService7ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><ListMember>abc</ListMember></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService7TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "abc", *out.ListMember[0])
}
func TestOutputService8ProtocolTestListOfStructuresCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService8ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse xmlns=\"https://service.amazonaws.com/doc/2010-05-08/\"><OperationNameResult><List><member><Foo>firstfoo</Foo><Bar>firstbar</Bar><Baz>firstbaz</Baz></member><member><Foo>secondfoo</Foo><Bar>secondbar</Bar><Baz>secondbaz</Baz></member></List></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService8TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "firstbar", *out.List[0].Bar)
assert.Equal(t, "firstbaz", *out.List[0].Baz)
assert.Equal(t, "firstfoo", *out.List[0].Foo)
assert.Equal(t, "secondbar", *out.List[1].Bar)
assert.Equal(t, "secondbaz", *out.List[1].Baz)
assert.Equal(t, "secondfoo", *out.List[1].Foo)
}
func TestOutputService9ProtocolTestFlattenedListOfStructuresCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService9ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse xmlns=\"https://service.amazonaws.com/doc/2010-05-08/\"><OperationNameResult><List><Foo>firstfoo</Foo><Bar>firstbar</Bar><Baz>firstbaz</Baz></List><List><Foo>secondfoo</Foo><Bar>secondbar</Bar><Baz>secondbaz</Baz></List></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService9TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "firstbar", *out.List[0].Bar)
assert.Equal(t, "firstbaz", *out.List[0].Baz)
assert.Equal(t, "firstfoo", *out.List[0].Foo)
assert.Equal(t, "secondbar", *out.List[1].Bar)
assert.Equal(t, "secondbaz", *out.List[1].Baz)
assert.Equal(t, "secondfoo", *out.List[1].Foo)
}
func TestOutputService10ProtocolTestFlattenedListWithLocationNameCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService10ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse xmlns=\"https://service.amazonaws.com/doc/2010-05-08/\"><OperationNameResult><NamedList>a</NamedList><NamedList>b</NamedList></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService10TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "a", *out.List[0])
assert.Equal(t, "b", *out.List[1])
}
func TestOutputService11ProtocolTestNormalMapCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService11ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse xmlns=\"https://service.amazonaws.com/doc/2010-05-08\"><OperationNameResult><Map><entry><key>qux</key><value><foo>bar</foo></value></entry><entry><key>baz</key><value><foo>bam</foo></value></entry></Map></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService11TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "bam", *out.Map["baz"].Foo)
assert.Equal(t, "bar", *out.Map["qux"].Foo)
}
func TestOutputService12ProtocolTestFlattenedMapCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService12ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Map><key>qux</key><value>bar</value></Map><Map><key>baz</key><value>bam</value></Map></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService12TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "bam", *out.Map["baz"])
assert.Equal(t, "bar", *out.Map["qux"])
}
func TestOutputService13ProtocolTestFlattenedMapInShapeDefinitionCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService13ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Attribute><Name>qux</Name><Value>bar</Value></Attribute></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService13TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "bar", *out.Map["qux"])
}
func TestOutputService14ProtocolTestNamedMapCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService14ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><OperationNameResult><Map><foo>qux</foo><bar>bar</bar></Map><Map><foo>baz</foo><bar>bam</bar></Map></OperationNameResult><ResponseMetadata><RequestId>requestid</RequestId></ResponseMetadata></OperationNameResponse>"))
req, out := svc.OutputService14TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "bam", *out.Map["baz"])
assert.Equal(t, "bar", *out.Map["qux"])
}
func TestOutputService15ProtocolTestEmptyStringCase1(t *testing.T) {
sess := session.New()
svc := NewOutputService15ProtocolTest(sess, &aws.Config{Endpoint: aws.String("https://test")})
buf := bytes.NewReader([]byte("<OperationNameResponse><Foo/><RequestId>requestid</RequestId></OperationNameResponse>"))
req, out := svc.OutputService15TestCaseOperation1Request(nil)
req.HTTPResponse = &http.Response{StatusCode: 200, Body: ioutil.NopCloser(buf), Header: http.Header{}}
// set headers
// unmarshal response
query.UnmarshalMeta(req)
query.Unmarshal(req)
assert.NoError(t, req.Error)
// assert response
assert.NotNil(t, out) // ensure out variable is used
assert.Equal(t, "", *out.Foo)
}
| mit |
Neko81795/ASideScrollBonanza | ASSB/ASSB/EventSystem/ObjectEventManager.hpp | 987 | #pragma once
#include <vector>
#include "ODefines.hpp"
#include "EventSystem.hpp"
namespace EventSystem
{
// Handles connecting and disconnecting of events based on their IDs.
// This service is provided for objects only, and is not something that
// is provided for global functions that are part of the event system.
class ObjectEventManager
{
public:
// Constructor and Destructor
ObjectEventManager(EventSystem &es);
virtual ~ObjectEventManager();
// Member Functions
template <typename Caller, typename EventType>
void Connect(Caller *c, void(Caller::*func)(EventType *));
template <typename Caller, typename EventToBind>
void ConnectVague(Caller *c, void(Caller::*func)(Event *));
//void Disconnect(O_ID toDisconnect);
private:
// Variables
std::vector<O_ID> connections_;
EventSystem &eventSystem_;
ObjectEventManager& operator=(const ObjectEventManager& other) = delete;
};
}
#include "ObjectEventManager.tpp"
| mit |
sakura-internet/saklient.node | src/saklient/cloud/errors/ServiceTemporarilyUnavailableException.ts | 950 | /// <reference path="../../../node.d.ts" />
export = ServiceTemporarilyUnavailableException;
import HttpServiceUnavailableException = require('../../errors/HttpServiceUnavailableException');
'use strict';
/**
* サービスが利用できません。この機能は一時的に利用できない状態にあります。メンテナンス情報、サポートサイトをご確認ください。
*/
class ServiceTemporarilyUnavailableException extends HttpServiceUnavailableException {
/**
* @constructor
* @public
* @param {number} status
* @param {string} code=null
* @param {string} message=""
*/
constructor(status:number, code:string=null, message:string="") {
super(status, code, message == null || message == "" ? "サービスが利用できません。この機能は一時的に利用できない状態にあります。メンテナンス情報、サポートサイトをご確認ください。" : message);
}
}
| mit |
sumitarora/angular2-practice | webpack.config.js | 2402 | // @AngularClass
/*
* Helper: root(), and rootDir() are defined at the bottom
*/
var path = require('path');
var webpack = require('webpack');
// Webpack Plugins
var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin;
/*
* Config
*/
module.exports = {
// for faster builds use 'eval'
devtool: 'source-map',
debug: true,
entry: {
'vendor': './src/vendor.ts',
'app': './src/bootstrap.ts' // our angular app
},
// Config for our build files
output: {
path: root('__build__'),
filename: '[name].js',
sourceMapFilename: '[name].map',
chunkFilename: '[id].chunk.js'
},
resolve: {
// ensure loader extensions match
extensions: ['','.ts','.js','.json', '.css', '.html']
},
module: {
preLoaders: [ { test: /\.ts$/, loader: 'tslint-loader' } ],
loaders: [
// Support for .ts files.
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'ignoreDiagnostics': [
2403, // 2403 -> Subsequent variable declarations
2300, // 2300 Duplicate identifier
2374, // 2374 -> Duplicate number index signature
2375 // 2375 -> Duplicate string index signature
]
},
exclude: [ /\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/ ]
},
// Support for *.json files.
{ test: /\.json$/, loader: 'json-loader' },
// Support for CSS as raw text
{ test: /\.css$/, loader: 'raw-loader' },
// support for .html as raw text
{ test: /\.html$/, loader: 'raw-loader' },
],
noParse: [ /zone\.js\/dist\/.+/, /angular2\/bundles\/.+/ ]
},
plugins: [
new CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.js', minChunks: Infinity }),
new CommonsChunkPlugin({ name: 'common', filename: 'common.js', minChunks: 2, chunks: ['app', 'vendor'] })
],
// Other module loader config
tslint: {
emitErrors: false,
failOnHint: false
},
// our Webpack Development Server config
devServer: {
historyApiFallback: true,
contentBase: 'src/public',
publicPath: '/__build__'
}
};
// Helper functions
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [__dirname].concat(args));
}
function rootNode(args) {
args = Array.prototype.slice.call(arguments, 0);
return root.apply(path, ['node_modules'].concat(args));
}
| mit |
xing/hops | packages/react/router/index.js | 529 | import { withRouter } from 'react-router-dom';
export const Miss = withRouter(({ staticContext }) => {
if (staticContext) {
staticContext.miss = true;
}
return null;
});
export const Status = withRouter(({ staticContext, code }) => {
if (staticContext) {
staticContext.status = code;
}
return null;
});
export const Header = withRouter(({ staticContext, name = '', value = '' }) => {
if (staticContext) {
staticContext.headers = { ...staticContext.headers, [name]: value };
}
return null;
});
| mit |
JonnyBGod/RealityConnect-Hackathon | chat/scripts/tiles.js | 22459 | /*! Tiles.js | http://thinkpixellab.com/tilesjs | 2012-12-03 */
// single namespace export
var Tiles = {};
(function($) {
var Tile = Tiles.Tile = function(tileId, element) {
this.id = tileId;
// position and dimensions of tile inside the parent panel
this.top = 0;
this.left = 0;
this.width = 0;
this.height = 0;
// cache the tile container element
this.$el = $(element || document.createElement('div'));
};
Tile.prototype.appendTo = function($parent, fadeIn, delay, duration) {
this.$el
.hide()
.appendTo($parent);
if (fadeIn) {
this.$el.delay(delay).fadeIn(duration);
}
else {
this.$el.show();
}
};
Tile.prototype.remove = function(animate, duration) {
if (animate) {
this.$el.fadeOut({
complete: function() {
$(this).remove();
}
});
}
else {
this.$el.remove();
}
};
// updates the tile layout with optional animation
Tile.prototype.resize = function(cellRect, pixelRect, animate, duration, onComplete) {
// store the list of needed changes
var cssChanges = {},
changed = false;
// update position and dimensions
if (this.left !== pixelRect.x) {
cssChanges.left = pixelRect.x;
this.left = pixelRect.x;
changed = true;
}
if (this.top !== pixelRect.y) {
cssChanges.top = pixelRect.y;
this.top = pixelRect.y;
changed = true;
}
if (this.width !== pixelRect.width) {
cssChanges.width = pixelRect.width;
this.width = pixelRect.width;
changed = true;
}
if (this.height !== pixelRect.height) {
cssChanges.height = pixelRect.height;
this.height = pixelRect.height;
changed = true;
}
// Sometimes animation fails to set the css top and left correctly
// in webkit. We'll validate upon completion of the animation and
// set the properties again if they don't match the expected values.
var tile = this,
validateChangesAndComplete = function() {
var el = tile.$el[0];
if (tile.left !== el.offsetLeft) {
//console.log ('mismatch left:' + tile.left + ' actual:' + el.offsetLeft + ' id:' + tile.id);
tile.$el.css('left', tile.left);
}
if (tile.top !== el.offsetTop) {
//console.log ('mismatch top:' + tile.top + ' actual:' + el.offsetTop + ' id:' + tile.id);
tile.$el.css('top', tile.top);
}
if (onComplete) {
onComplete();
}
};
// make css changes with animation when requested
if (animate && changed) {
this.$el.animate(cssChanges, {
duration: duration,
easing: 'swing',
complete: validateChangesAndComplete
});
}
else {
if (changed) {
this.$el.css(cssChanges);
}
setTimeout(validateChangesAndComplete, duration);
}
};
})(jQuery);
/*
A grid template specifies the layout of variably sized tiles. A single
cell tile should use the period character. Larger tiles may be created
using any character that is unused by a adjacent tile. Whitespace is
ignored when parsing the rows.
Examples:
var simpleTemplate = [
' A A . B ',
' A A . B ',
' . C C . ',
]
var complexTemplate = [
' J J . . E E ',
' . A A . E E ',
' B A A F F . ',
' B . D D . H ',
' C C D D G H ',
' C C . . G . ',
];
*/
(function($) {
// remove whitespace and create 2d array
var parseCells = function(rows) {
var cells = [],
numRows = rows.length,
x, y, row, rowLength, cell;
// parse each row
for(y = 0; y < numRows; y++) {
row = rows[y];
cells[y] = [];
// parse the cells in a single row
for (x = 0, rowLength = row.length; x < rowLength; x++) {
cell = row[x];
if (cell !== ' ') {
cells[y].push(cell);
}
}
}
// TODO: check to make sure the array isn't jagged
return cells;
};
function Rectangle(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Rectangle.prototype.copy = function() {
return new Rectangle(this.x, this.y, this.width, this.height);
};
Tiles.Rectangle = Rectangle;
// convert a 2d array of cell ids to a list of tile rects
var parseRects = function(cells) {
var rects = [],
numRows = cells.length,
numCols = numRows === 0 ? 0 : cells[0].length,
cell, height, width, x, y, rectX, rectY;
// make a copy of the cells that we can modify
cells = cells.slice();
for (y = 0; y < numRows; y++) {
cells[y] = cells[y].slice();
}
// iterate through every cell and find rectangles
for (y = 0; y < numRows; y++) {
for(x = 0; x < numCols; x++) {
cell = cells[y][x];
// skip cells that are null
if (cell == null) {
continue;
}
width = 1;
height = 1;
if (cell !== Tiles.Template.SINGLE_CELL) {
// find the width by going right until cell id no longer matches
while(width + x < numCols &&
cell === cells[y][x + width]) {
width++;
}
// now find height by going down
while (height + y < numRows &&
cell === cells[y + height][x]) {
height++;
}
}
// null out all cells for the rect
for(rectY = 0; rectY < height; rectY++) {
for(rectX = 0; rectX < width; rectX++) {
cells[y + rectY][x + rectX] = null;
}
}
// add the rect
rects.push(new Rectangle(x, y, width, height));
}
}
return rects;
};
Tiles.Template = function(rects, numCols, numRows) {
this.rects = rects;
this.numTiles = this.rects.length;
this.numRows = numRows;
this.numCols = numCols;
};
Tiles.Template.prototype.copy = function() {
var copyRects = [],
len, i;
for (i = 0, len = this.rects.length; i < len; i++) {
copyRects.push(this.rects[i].copy());
}
return new Tiles.Template(copyRects, this.numCols, this.numRows);
};
// appends another template (assumes both are full rectangular grids)
Tiles.Template.prototype.append = function(other) {
if (this.numCols !== other.numCols) {
throw 'Appended templates must have the same number of columns';
}
// new rects begin after the last current row
var startY = this.numRows,
i, len, rect;
// copy rects from the other template
for (i = 0, len = other.rects.length; i < len; i++) {
rect = other.rects[i];
this.rects.push(
new Rectangle(rect.x, startY + rect.y, rect.width, rect.height));
}
this.numRows += other.numRows;
};
Tiles.Template.fromJSON = function(rows) {
// convert rows to cells and then to rects
var cells = parseCells(rows),
rects = parseRects(cells);
return new Tiles.Template(
rects,
cells.length > 0 ? cells[0].length : 0,
cells.length);
};
Tiles.Template.prototype.toJSON = function() {
// for now we'll assume 26 chars is enough (we don't solve graph coloring)
var LABELS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
NUM_LABELS = LABELS.length,
labelIndex = 0,
rows = [],
i, len, rect, x, y, label;
// fill in single tiles for each cell
for (y = 0; y < this.numRows; y++) {
rows[y] = [];
for (x = 0; x < this.numCols; x++) {
rows[y][x] = Tiles.Template.SINGLE_CELL;
}
}
// now fill in bigger tiles
for (i = 0, len = this.rects.length; i < len; i++) {
rect = this.rects[i];
if (rect.width > 1 || rect.height > 1) {
// mark the tile position with a label
label = LABELS[labelIndex];
for(y = 0; y < rect.height; y++) {
for(x = 0; x < rect.width; x++) {
rows[rect.y + y][rect.x + x] = label;
}
}
// advance the label index
labelIndex = (labelIndex + 1) % NUM_LABELS;
}
}
// turn the rows into strings
for (y = 0; y < this.numRows; y++) {
rows[y] = rows[y].join('');
}
return rows;
};
// period used to designate a single 1x1 cell tile
Tiles.Template.SINGLE_CELL = '.';
})(jQuery);
// template provider which returns simple templates with 1x1 tiles
Tiles.UniformTemplates = {
get: function(numCols, targetTiles) {
var numRows = Math.ceil(targetTiles / numCols),
rects = [],
x, y;
// create the rects for 1x1 tiles
for (y = 0; y < numRows; y++) {
for (x = 0; x < numCols; x++) {
rects.push(new Tiles.Rectangle(x, y, 1, 1));
}
}
return new Tiles.Template(rects, numCols, numRows);
}
};
(function($) {
var Grid = Tiles.Grid = function(element) {
this.$el = $(element);
// animation lasts 500 ms by default
this.animationDuration = 500;
// min width and height of a cell in the grid
this.cellSizeMin = 150;
// the default set of factories used when creating templates
this.templateFactory = Tiles.UniformTemplates;
// defines the page size for prioritization of positions and tiles
this.priorityPageSize = Number.MAX_VALUE;
// spacing between tiles
this.cellPadding = 10;
// actual width and height of a cell in the grid
this.cellSize = 0;
// number of tile cell columns
this.numCols = 1;
// cache the current template
this.template = null;
// flag that tracks whether a redraw is necessary
this.isDirty = true;
this.tiles = [];
// keep track of added and removed tiles so we can update tiles
// and the render the grid independently.
this.tilesAdded = [];
this.tilesRemoved = [];
};
Grid.prototype.getContentWidth = function() {
// by default, the entire container width is used when drawing tiles
return this.$el.width();
};
// gets the number of columns during a resize
Grid.prototype.resizeColumns = function() {
var panelWidth = this.getContentWidth();
// ensure we have at least one column
return Math.max(1, Math.floor((panelWidth + this.cellPadding) /
(this.cellSizeMin + this.cellPadding)));
};
// gets the cell size during a grid resize
Grid.prototype.resizeCellSize = function() {
var panelWidth = this.getContentWidth();
return Math.ceil((panelWidth + this.cellPadding) / this.numCols) -
this.cellPadding;
};
Grid.prototype.resize = function() {
var newCols = this.resizeColumns();
if (this.numCols !== newCols && newCols > 0) {
this.numCols = newCols;
this.isDirty = true;
}
var newCellSize = this.resizeCellSize();
if (this.cellSize !== newCellSize && newCellSize > 0) {
this.cellSize = newCellSize;
this.isDirty = true;
}
};
// refresh all tiles based on the current content
Grid.prototype.updateTiles = function(newTileIds) {
// ensure we dont have duplicate ids
newTileIds = uniques(newTileIds);
var numTiles = newTileIds.length,
newTiles = [],
i, tile, tileId, index;
// retain existing tiles and queue remaining tiles for removal
for (i = this.tiles.length - 1; i >= 0; i--) {
tile = this.tiles[i];
index = $.inArray(tile.id, newTileIds);
if (index < 0) {
this.tilesRemoved.push(tile);
//console.log('Removing tile: ' + tile.id)
}
else {
newTiles[index] = tile;
}
}
// clear existing tiles
this.tiles = [];
// make sure we have tiles for new additions
for (i = 0; i < numTiles; i++) {
tile = newTiles[i];
if (!tile) {
tileId = newTileIds[i];
// see if grid has a custom tile factory
if (this.createTile) {
tile = this.createTile(tileId);
// skip the tile if it couldn't be created
if (!tile) {
//console.log('Tile element could not be created, id: ' + tileId);
continue;
}
} else {
tile = new Tiles.Tile(tileId);
}
// add tiles to queue (will be appended to DOM during redraw)
this.tilesAdded.push(tile);
//console.log('Adding tile: ' + tile.id);
}
this.tiles.push(tile);
}
};
// helper to return unique items
function uniques(items) {
var results = [],
numItems = items ? items.length : 0,
i, item;
for (i = 0; i < numItems; i++) {
item = items[i];
if ($.inArray(item, results) === -1) {
results.push(item);
}
}
return results;
}
// prepend new tiles
Grid.prototype.insertTiles = function(newTileIds) {
this.addTiles(newTileIds, true);
};
// append new tiles
Grid.prototype.addTiles = function(newTileIds, prepend) {
if (!newTileIds || newTileIds.length === 0) {
return;
}
var prevTileIds = [],
prevTileCount = this.tiles.length,
i;
// get the existing tile ids
for (i = 0; i < prevTileCount; i++) {
prevTileIds.push(this.tiles[i].id);
}
var tileIds = prepend ? newTileIds.concat(prevTileIds)
: prevTileIds.concat(newTileIds);
this.updateTiles(tileIds);
};
Grid.prototype.removeTiles = function(removeTileIds) {
if (!removeTileIds || removeTileIds.length === 0) {
return;
}
var updateTileIds = [],
i, len, id;
// get the set of ids which have not been removed
for (i = 0, len = this.tiles.length; i < len; i++) {
id = this.tiles[i].id;
if ($.inArray(id, removeTileIds) === -1) {
updateTileIds.push(id);
}
}
this.updateTiles(updateTileIds);
};
Grid.prototype.createTemplate = function(numCols, targetTiles) {
// ensure that we have at least one column
numCols = Math.max(1, numCols);
var template = this.templateFactory.get(numCols, targetTiles);
if (!template) {
// fallback in case the default factory can't generate a good template
template = Tiles.UniformTemplates.get(numCols, targetTiles);
}
return template;
};
// ensures we have a good template for the specified numbef of tiles
Grid.prototype.ensureTemplate = function(numTiles) {
// verfiy that the current template is still valid
if (!this.template || this.template.numCols !== this.numCols) {
this.template = this.createTemplate(this.numCols, numTiles);
this.isDirty = true;
} else {
// append another template if we don't have enough rects
var missingRects = numTiles - this.template.rects.length;
if (missingRects > 0) {
this.template.append(
this.createTemplate(this.numCols, missingRects));
this.isDirty = true;
}
}
};
// helper that returns true if a tile was in the viewport or will be given
// the new pixel rect coordinates and dimensions
function wasOrWillBeVisible(viewRect, tile, newRect) {
var viewMaxY = viewRect.y + viewRect.height,
viewMaxX = viewRect.x + viewRect.width;
// note: y axis is the more common exclusion, so check that first
// was the tile visible?
if (tile) {
if (!((tile.top > viewMaxY) || (tile.top + tile.height < viewRect.y) ||
(tile.left > viewMaxX) || (tile.left + tile.width < viewRect.x))) {
return true;
}
}
if (newRect) {
// will it be visible?
if (!((newRect.y > viewMaxY) || (newRect.y + newRect.height < viewRect.y) ||
(newRect.x > viewMaxX) || (newRect.x + newRect.width < viewRect.x))) {
return true;
}
}
return false;
}
Grid.prototype.shouldRedraw = function() {
// see if we need to calculate the cell size
if (this.cellSize <= 0) {
this.resize();
}
// verify that we have a template
this.ensureTemplate(this.tiles.length);
// only redraw when necessary
var shouldRedraw = (this.isDirty ||
this.tilesAdded.length > 0 ||
this.tilesRemoved.length > 0);
return shouldRedraw;
};
// redraws the grid after tile collection changes
Grid.prototype.redraw = function(animate, onComplete) {
// see if we should redraw
if (!this.shouldRedraw()) {
if (onComplete) {
onComplete(false); // tell callback that we did not redraw
}
return;
}
var numTiles = this.tiles.length,
pageSize = this.priorityPageSize,
duration = this.animationDuration,
cellPlusPadding = this.cellSize + this.cellPadding,
tileIndex = 0,
appendDelay = 0,
viewRect = new Tiles.Rectangle(
this.$el.scrollLeft(),
this.$el.scrollTop(),
this.$el.width(),
this.$el.height()),
tile, added, pageRects, pageTiles, i, len, cellRect, pixelRect,
animateTile, priorityRects, priorityTiles;
// chunk tile layout by pages which are internally prioritized
for (tileIndex = 0; tileIndex < numTiles; tileIndex += pageSize) {
// get the next page of rects and tiles
pageRects = this.template.rects.slice(tileIndex, tileIndex + pageSize);
pageTiles = this.tiles.slice(tileIndex, tileIndex + pageSize);
// create a copy that can be ordered
priorityRects = pageRects.slice(0);
priorityTiles = pageTiles.slice(0);
// prioritize the page of rects and tiles
if (this.prioritizePage) {
this.prioritizePage(priorityRects, priorityTiles);
}
// place all the tiles for the current page
for (i = 0, len = priorityTiles.length; i < len; i++) {
tile = priorityTiles[i];
added = $.inArray(tile, this.tilesAdded) >= 0;
cellRect = priorityRects[i];
pixelRect = new Tiles.Rectangle(
cellRect.x * cellPlusPadding,
cellRect.y * cellPlusPadding,
(cellRect.width * cellPlusPadding) - this.cellPadding,
(cellRect.height * cellPlusPadding) - this.cellPadding);
tile.resize(
cellRect,
pixelRect,
animate && !added && wasOrWillBeVisible(viewRect, tile, pixelRect),
duration);
if (added) {
// decide whether to animate (fadeIn) and get the duration
animateTile = animate && wasOrWillBeVisible(viewRect, null, pixelRect);
if (animateTile && this.getAppendDelay) {
appendDelay = this.getAppendDelay(
cellRect, pageRects, priorityRects,
tile, pageTiles, priorityTiles);
} else {
appendDelay = 0;
}
tile.appendTo(this.$el, animateTile, appendDelay, duration);
}
}
}
// fade out all removed tiles
for (i = 0, len = this.tilesRemoved.length; i < len; i++) {
tile = this.tilesRemoved[i];
animateTile = animate && wasOrWillBeVisible(viewRect, tile, null);
tile.remove(animateTile, duration);
}
// clear pending queues for add / remove
this.tilesRemoved = [];
this.tilesAdded = [];
this.isDirty = false;
if (onComplete) {
setTimeout(function() { onComplete(true); }, duration + 10);
}
};
})(jQuery); | mit |
raphaelcosta/i18n_alchemy | lib/i18n_alchemy/proxy.rb | 4775 | module I18n
module Alchemy
# Depend on AS::Basic/ProxyObject which has a "blank slate" - no methods.
base_proxy = defined?(ActiveSupport::ProxyObject) ?
ActiveSupport::ProxyObject : ActiveSupport::BasicObject
class Proxy < base_proxy
include AttributesParsing
# TODO: cannot assume _id is always a foreign key.
# Find a better way to find that and skip these columns.
def initialize(target, attributes = nil)
@target = target
@target_class = target.class
@localized_attributes = {}
@localized_associations = []
build_methods
if active_record_compatible?
build_attributes
build_associations
end
assign_attributes(attributes) if attributes
end
# Override to_param to always return the +proxy.to_param+. This allow us
# to integrate with action view.
def to_param
@target.to_param
end
# Override to_json to always call +to_json+ on the target object, instead of
# serializing the proxy object, that may issue circular references on Ruby 1.8.
def to_json(options = nil)
@target.to_json(options)
end
# Override to_model to always return the proxy, otherwise it returns the
# target object. This allows us to integrate with action view.
def to_model
self
end
# Allow calling localized methods with :send. This allows us to integrate
# with action view methods.
alias :send :__send__
# Allow calling localized methods with :try. If the method is not declared
# here, it'll be delegated to the target, losing localization capabilities.
def try(*a, &b)
__send__(*a, &b)
end
# Delegate all method calls that are not translated to the target object.
# As the proxy does not have any other method, there is no need to
# override :respond_to, just delegate it to the target as well.
def method_missing(*args, &block)
@target.send(*args, &block)
end
private
def active_record_compatible?
@target_class.respond_to?(:columns) && @target_class.respond_to?(:nested_attributes_options)
end
def build_attributes
@target_class.columns.each do |column|
column_name = column.name
next if skip_column?(column_name)
parser = detect_parser_from_column(column)
build_attribute(column_name, parser)
end
end
def build_methods
@target_class.localized_methods.each_pair do |method, parser_type|
method = method.to_s
parser = detect_parser(parser_type)
build_attribute(method, parser)
end
end
def build_associations
@target_class.nested_attributes_options.each_key do |association_name|
create_localized_association(association_name)
end
end
def build_attribute(name, parser)
return unless parser
create_localized_attribute(name, parser)
define_localized_methods(name)
end
def create_localized_association(association_name)
@localized_associations <<
AssociationParser.new(@target_class, association_name)
end
def create_localized_attribute(column_name, parser)
@localized_attributes[column_name] =
Attribute.new(@target, column_name, parser)
end
def define_localized_methods(column_name)
target = @target
class << self; self; end.instance_eval do
define_method(column_name) do
@localized_attributes[column_name].read
end
# Before type cast must be localized to integrate with action view.
method_name = "#{column_name}_before_type_cast"
define_method(method_name) do
@localized_attributes[column_name].read
end if target.respond_to?(method_name)
method_name = "#{column_name}="
define_method(method_name) do |value|
@localized_attributes[column_name].write(value)
end if target.respond_to?(method_name)
end
end
def detect_parser_from_column(column)
detect_parser(column.number? ? :number : column.type)
end
def detect_parser(type_or_parser)
case type_or_parser
when :number
NumericParser
when :date
DateParser
when :datetime, :timestamp
TimeParser
when ::Module
type_or_parser
end
end
def skip_column?(column_name)
column_name == @target_class.primary_key ||
column_name.ends_with?("_id") ||
@localized_attributes.key?(column_name)
end
end
end
end
| mit |
quchunguang/test | bookalp/reciprocal/reciprocal.hpp | 108 | #ifdef __cplusplus
extern "C" {
#endif
extern double reciprocal (int i);
#ifdef __cplusplus
}
#endif
| mit |
YungSang/node-zmq | src/zmq_node.cc | 3898 | #include "zmq_node.h"
namespace zmq_node {
void
Init(v8::Handle<v8::Object> target) {
v8::HandleScope scope;
NODE_SET_METHOD(target, "version", Version);
NODE_SET_METHOD(target, "sleep", Sleep);
NODE_SET_METHOD(target, "nanosleep", NanoSleep);
// Socket types
ZMQ_NODE_DEFINE_CONSTANT(target, "PAIR", ZMQ_PAIR);
ZMQ_NODE_DEFINE_CONSTANT(target, "PUB", ZMQ_PUB);
ZMQ_NODE_DEFINE_CONSTANT(target, "SUB", ZMQ_SUB);
ZMQ_NODE_DEFINE_CONSTANT(target, "REQ", ZMQ_REQ);
ZMQ_NODE_DEFINE_CONSTANT(target, "REP", ZMQ_REP);
ZMQ_NODE_DEFINE_CONSTANT(target, "XREQ", ZMQ_XREQ);
ZMQ_NODE_DEFINE_CONSTANT(target, "XREP", ZMQ_XREP);
ZMQ_NODE_DEFINE_CONSTANT(target, "PULL", ZMQ_PULL);
ZMQ_NODE_DEFINE_CONSTANT(target, "PUSH", ZMQ_PUSH);
ZMQ_NODE_DEFINE_CONSTANT(target, "UPSTREAM", ZMQ_UPSTREAM);
ZMQ_NODE_DEFINE_CONSTANT(target, "DOWNSTREAM", ZMQ_DOWNSTREAM);
// Socket options
ZMQ_NODE_DEFINE_CONSTANT(target, "HWM", ZMQ_HWM);
ZMQ_NODE_DEFINE_CONSTANT(target, "SWAP", ZMQ_SWAP);
ZMQ_NODE_DEFINE_CONSTANT(target, "AFFINITY", ZMQ_AFFINITY);
ZMQ_NODE_DEFINE_CONSTANT(target, "IDENTITY", ZMQ_IDENTITY);
ZMQ_NODE_DEFINE_CONSTANT(target, "SUBSCRIBE", ZMQ_SUBSCRIBE);
ZMQ_NODE_DEFINE_CONSTANT(target, "UNSUBSCRIBE", ZMQ_UNSUBSCRIBE);
ZMQ_NODE_DEFINE_CONSTANT(target, "RATE", ZMQ_RATE);
ZMQ_NODE_DEFINE_CONSTANT(target, "RECOVERY_IVL", ZMQ_RECOVERY_IVL);
ZMQ_NODE_DEFINE_CONSTANT(target, "MCAST_LOOP", ZMQ_MCAST_LOOP);
ZMQ_NODE_DEFINE_CONSTANT(target, "SNDBUF", ZMQ_SNDBUF);
ZMQ_NODE_DEFINE_CONSTANT(target, "RCVBUF", ZMQ_RCVBUF);
ZMQ_NODE_DEFINE_CONSTANT(target, "RCVMORE", ZMQ_RCVMORE);
// Send/recv options
ZMQ_NODE_DEFINE_CONSTANT(target, "NOBLOCK", ZMQ_NOBLOCK);
ZMQ_NODE_DEFINE_CONSTANT(target, "SNDMORE", ZMQ_SNDMORE);
// Poll events
ZMQ_NODE_DEFINE_CONSTANT(target, "POLLIN", ZMQ_POLLIN);
ZMQ_NODE_DEFINE_CONSTANT(target, "POLLOUT", ZMQ_POLLOUT);
ZMQ_NODE_DEFINE_CONSTANT(target, "POLLERR", ZMQ_POLLERR);
// Device types
ZMQ_NODE_DEFINE_CONSTANT(target, "STREAMER", ZMQ_STREAMER);
ZMQ_NODE_DEFINE_CONSTANT(target, "FORWARDER", ZMQ_FORWARDER);
ZMQ_NODE_DEFINE_CONSTANT(target, "QUEUE", ZMQ_QUEUE);
}
v8::Handle<v8::Value>
Version(const v8::Arguments& args) {
v8::HandleScope scope;
int major, minor, patch;
char version[10];
zmq_version(&major, &minor, &patch);
sprintf(version, "%d.%d.%d", major, minor, patch);
return v8::String::New(version);
}
v8::Handle<v8::Value>
Sleep(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New("Must pass the number of seconds to sleep")));
}
if (!args[0]->IsNumber()) {
return v8::ThrowException(v8::Exception::TypeError(
v8::String::New("First argument must be an integer")));
}
int seconds = (int) args[0]->ToInteger()->Value();
zmq_sleep(seconds);
return v8::Undefined();
}
v8::Handle<v8::Value>
NanoSleep(const v8::Arguments& args) {
v8::HandleScope scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::Exception::Error(
v8::String::New("Must pass the number of nanoseconds to sleep")));
}
if (!args[0]->IsNumber()) {
return v8::ThrowException(v8::Exception::TypeError(
v8::String::New("First argument must be an integer")));
}
int nanoSeconds = (int) args[0]->ToInteger()->Value();
struct timespec t;
t.tv_sec = (int)(nanoSeconds / 1000000000);
t.tv_nsec = nanoSeconds % 1000000000;
nanosleep(&t, NULL);
return v8::Undefined();
}
} // namespace zmq_node
#include "stopwatch.h"
#include "socket.h"
#include "context.h"
extern "C" {
void init (v8::Handle<v8::Object> target) {
v8::HandleScope scope;
zmq_node::Init(target);
zmq_node::Stopwatch::Init(target);
zmq_node::Context::Init(target);
zmq_node::Socket::Init(target);
}
}
| mit |
Dasc3er/Sito-studentesco | database/migrations/20161202133548_create_course_user.php | 559 | <?php
use Phinx\Migration\AbstractMigration;
class CreateCourseUser extends AbstractMigration
{
public function change()
{
$table = $this->table('course_user');
$table->addColumn('course_id', 'integer')
->addColumn('user_id', 'integer')
->addTimestamps(null, null)
->addForeignKey('course_id', 'courses', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
->addForeignKey('user_id', 'users', 'id', ['delete' => 'CASCADE', 'update' => 'NO_ACTION'])
->create();
}
}
| mit |
gdbelvin/PrivText | Android/src/edu/jhu/bouncycastle/crypto/engines/AESEngine.java | 28131 | /*
* Copyright (c) 2000 - 2011 The Legion Of The Bouncy Castle
* (http://www.bouncycastle.org)
*
* 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.
*/
package edu.jhu.bouncycastle.crypto.engines;
import edu.jhu.bouncycastle.crypto.BlockCipher;
import edu.jhu.bouncycastle.crypto.CipherParameters;
import edu.jhu.bouncycastle.crypto.DataLengthException;
import edu.jhu.bouncycastle.crypto.params.KeyParameter;
/**
* an implementation of the AES (Rijndael), from FIPS-197.
* <p>
* For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>.
*
* This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at
* <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a>
*
* There are three levels of tradeoff of speed vs memory
* Because java has no preprocessor, they are written as three separate classes from which to choose
*
* The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption
* and 4 for decryption.
*
* The middle performance version uses only one 256 word table for each, for a total of 2Kbytes,
* adding 12 rotate operations per round to compute the values contained in the other tables from
* the contents of the first.
*
* The slowest version uses no static tables at all and computes the values in each round.
* <p>
* This file contains the middle performance version with 2Kbytes of static tables for round precomputation.
*
*/
public class AESEngine
implements BlockCipher
{
// The S box
private static final byte[] S = {
(byte)99, (byte)124, (byte)119, (byte)123, (byte)242, (byte)107, (byte)111, (byte)197,
(byte)48, (byte)1, (byte)103, (byte)43, (byte)254, (byte)215, (byte)171, (byte)118,
(byte)202, (byte)130, (byte)201, (byte)125, (byte)250, (byte)89, (byte)71, (byte)240,
(byte)173, (byte)212, (byte)162, (byte)175, (byte)156, (byte)164, (byte)114, (byte)192,
(byte)183, (byte)253, (byte)147, (byte)38, (byte)54, (byte)63, (byte)247, (byte)204,
(byte)52, (byte)165, (byte)229, (byte)241, (byte)113, (byte)216, (byte)49, (byte)21,
(byte)4, (byte)199, (byte)35, (byte)195, (byte)24, (byte)150, (byte)5, (byte)154,
(byte)7, (byte)18, (byte)128, (byte)226, (byte)235, (byte)39, (byte)178, (byte)117,
(byte)9, (byte)131, (byte)44, (byte)26, (byte)27, (byte)110, (byte)90, (byte)160,
(byte)82, (byte)59, (byte)214, (byte)179, (byte)41, (byte)227, (byte)47, (byte)132,
(byte)83, (byte)209, (byte)0, (byte)237, (byte)32, (byte)252, (byte)177, (byte)91,
(byte)106, (byte)203, (byte)190, (byte)57, (byte)74, (byte)76, (byte)88, (byte)207,
(byte)208, (byte)239, (byte)170, (byte)251, (byte)67, (byte)77, (byte)51, (byte)133,
(byte)69, (byte)249, (byte)2, (byte)127, (byte)80, (byte)60, (byte)159, (byte)168,
(byte)81, (byte)163, (byte)64, (byte)143, (byte)146, (byte)157, (byte)56, (byte)245,
(byte)188, (byte)182, (byte)218, (byte)33, (byte)16, (byte)255, (byte)243, (byte)210,
(byte)205, (byte)12, (byte)19, (byte)236, (byte)95, (byte)151, (byte)68, (byte)23,
(byte)196, (byte)167, (byte)126, (byte)61, (byte)100, (byte)93, (byte)25, (byte)115,
(byte)96, (byte)129, (byte)79, (byte)220, (byte)34, (byte)42, (byte)144, (byte)136,
(byte)70, (byte)238, (byte)184, (byte)20, (byte)222, (byte)94, (byte)11, (byte)219,
(byte)224, (byte)50, (byte)58, (byte)10, (byte)73, (byte)6, (byte)36, (byte)92,
(byte)194, (byte)211, (byte)172, (byte)98, (byte)145, (byte)149, (byte)228, (byte)121,
(byte)231, (byte)200, (byte)55, (byte)109, (byte)141, (byte)213, (byte)78, (byte)169,
(byte)108, (byte)86, (byte)244, (byte)234, (byte)101, (byte)122, (byte)174, (byte)8,
(byte)186, (byte)120, (byte)37, (byte)46, (byte)28, (byte)166, (byte)180, (byte)198,
(byte)232, (byte)221, (byte)116, (byte)31, (byte)75, (byte)189, (byte)139, (byte)138,
(byte)112, (byte)62, (byte)181, (byte)102, (byte)72, (byte)3, (byte)246, (byte)14,
(byte)97, (byte)53, (byte)87, (byte)185, (byte)134, (byte)193, (byte)29, (byte)158,
(byte)225, (byte)248, (byte)152, (byte)17, (byte)105, (byte)217, (byte)142, (byte)148,
(byte)155, (byte)30, (byte)135, (byte)233, (byte)206, (byte)85, (byte)40, (byte)223,
(byte)140, (byte)161, (byte)137, (byte)13, (byte)191, (byte)230, (byte)66, (byte)104,
(byte)65, (byte)153, (byte)45, (byte)15, (byte)176, (byte)84, (byte)187, (byte)22,
};
// The inverse S-box
private static final byte[] Si = {
(byte)82, (byte)9, (byte)106, (byte)213, (byte)48, (byte)54, (byte)165, (byte)56,
(byte)191, (byte)64, (byte)163, (byte)158, (byte)129, (byte)243, (byte)215, (byte)251,
(byte)124, (byte)227, (byte)57, (byte)130, (byte)155, (byte)47, (byte)255, (byte)135,
(byte)52, (byte)142, (byte)67, (byte)68, (byte)196, (byte)222, (byte)233, (byte)203,
(byte)84, (byte)123, (byte)148, (byte)50, (byte)166, (byte)194, (byte)35, (byte)61,
(byte)238, (byte)76, (byte)149, (byte)11, (byte)66, (byte)250, (byte)195, (byte)78,
(byte)8, (byte)46, (byte)161, (byte)102, (byte)40, (byte)217, (byte)36, (byte)178,
(byte)118, (byte)91, (byte)162, (byte)73, (byte)109, (byte)139, (byte)209, (byte)37,
(byte)114, (byte)248, (byte)246, (byte)100, (byte)134, (byte)104, (byte)152, (byte)22,
(byte)212, (byte)164, (byte)92, (byte)204, (byte)93, (byte)101, (byte)182, (byte)146,
(byte)108, (byte)112, (byte)72, (byte)80, (byte)253, (byte)237, (byte)185, (byte)218,
(byte)94, (byte)21, (byte)70, (byte)87, (byte)167, (byte)141, (byte)157, (byte)132,
(byte)144, (byte)216, (byte)171, (byte)0, (byte)140, (byte)188, (byte)211, (byte)10,
(byte)247, (byte)228, (byte)88, (byte)5, (byte)184, (byte)179, (byte)69, (byte)6,
(byte)208, (byte)44, (byte)30, (byte)143, (byte)202, (byte)63, (byte)15, (byte)2,
(byte)193, (byte)175, (byte)189, (byte)3, (byte)1, (byte)19, (byte)138, (byte)107,
(byte)58, (byte)145, (byte)17, (byte)65, (byte)79, (byte)103, (byte)220, (byte)234,
(byte)151, (byte)242, (byte)207, (byte)206, (byte)240, (byte)180, (byte)230, (byte)115,
(byte)150, (byte)172, (byte)116, (byte)34, (byte)231, (byte)173, (byte)53, (byte)133,
(byte)226, (byte)249, (byte)55, (byte)232, (byte)28, (byte)117, (byte)223, (byte)110,
(byte)71, (byte)241, (byte)26, (byte)113, (byte)29, (byte)41, (byte)197, (byte)137,
(byte)111, (byte)183, (byte)98, (byte)14, (byte)170, (byte)24, (byte)190, (byte)27,
(byte)252, (byte)86, (byte)62, (byte)75, (byte)198, (byte)210, (byte)121, (byte)32,
(byte)154, (byte)219, (byte)192, (byte)254, (byte)120, (byte)205, (byte)90, (byte)244,
(byte)31, (byte)221, (byte)168, (byte)51, (byte)136, (byte)7, (byte)199, (byte)49,
(byte)177, (byte)18, (byte)16, (byte)89, (byte)39, (byte)128, (byte)236, (byte)95,
(byte)96, (byte)81, (byte)127, (byte)169, (byte)25, (byte)181, (byte)74, (byte)13,
(byte)45, (byte)229, (byte)122, (byte)159, (byte)147, (byte)201, (byte)156, (byte)239,
(byte)160, (byte)224, (byte)59, (byte)77, (byte)174, (byte)42, (byte)245, (byte)176,
(byte)200, (byte)235, (byte)187, (byte)60, (byte)131, (byte)83, (byte)153, (byte)97,
(byte)23, (byte)43, (byte)4, (byte)126, (byte)186, (byte)119, (byte)214, (byte)38,
(byte)225, (byte)105, (byte)20, (byte)99, (byte)85, (byte)33, (byte)12, (byte)125,
};
// vector used in calculating key schedule (powers of x in GF(256))
private static final int[] rcon = {
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 };
// precomputation tables of calculations for rounds
private static final int[] T0 =
{
0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff,
0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102,
0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d,
0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa,
0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41,
0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453,
0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d,
0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83,
0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2,
0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795,
0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a,
0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df,
0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912,
0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc,
0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7,
0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413,
0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040,
0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d,
0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0,
0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed,
0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a,
0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78,
0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080,
0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1,
0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020,
0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18,
0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488,
0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a,
0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0,
0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54,
0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b,
0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad,
0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992,
0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd,
0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3,
0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda,
0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8,
0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4,
0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a,
0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697,
0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96,
0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c,
0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7,
0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969,
0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9,
0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9,
0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715,
0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5,
0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65,
0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929,
0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d,
0x3a16162c};
private static final int[] Tinv0 =
{
0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b,
0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad,
0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526,
0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d,
0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03,
0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458,
0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899,
0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d,
0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1,
0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f,
0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3,
0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3,
0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a,
0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506,
0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05,
0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd,
0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491,
0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6,
0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7,
0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000,
0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd,
0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68,
0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4,
0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c,
0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e,
0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af,
0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644,
0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8,
0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85,
0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc,
0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411,
0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322,
0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6,
0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850,
0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e,
0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf,
0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd,
0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa,
0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea,
0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235,
0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1,
0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43,
0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1,
0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb,
0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a,
0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7,
0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418,
0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478,
0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16,
0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08,
0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48,
0x4257b8d0};
private int shift(
int r,
int shift)
{
return (r >>> shift) | (r << -shift);
}
/* multiply four bytes in GF(2^8) by 'x' {02} in parallel */
private static final int m1 = 0x80808080;
private static final int m2 = 0x7f7f7f7f;
private static final int m3 = 0x0000001b;
private int FFmulX(int x)
{
return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3));
}
/*
The following defines provide alternative definitions of FFmulX that might
give improved performance if a fast 32-bit multiply is not available.
private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); }
private static final int m4 = 0x1b1b1b1b;
private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); }
*/
private int inv_mcol(int x)
{
int f2 = FFmulX(x);
int f4 = FFmulX(f2);
int f8 = FFmulX(f4);
int f9 = x ^ f8;
return f2 ^ f4 ^ f8 ^ shift(f2 ^ f9, 8) ^ shift(f4 ^ f9, 16) ^ shift(f9, 24);
}
private int subWord(int x)
{
return (S[x&255]&255 | ((S[(x>>8)&255]&255)<<8) | ((S[(x>>16)&255]&255)<<16) | S[(x>>24)&255]<<24);
}
/**
* Calculate the necessary round keys
* The number of calculations depends on key size and block size
* AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits
* This code is written assuming those are the only possible values
*/
private int[][] generateWorkingKey(
byte[] key,
boolean forEncryption)
{
int KC = key.length / 4; // key length in words
int t;
if (((KC != 4) && (KC != 6) && (KC != 8)) || ((KC * 4) != key.length))
{
throw new IllegalArgumentException("Key length not 128/192/256 bits.");
}
ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes
int[][] W = new int[ROUNDS+1][4]; // 4 words in a block
//
// copy the key into the round key array
//
t = 0;
int i = 0;
while (i < key.length)
{
W[t >> 2][t & 3] = (key[i]&0xff) | ((key[i+1]&0xff) << 8) | ((key[i+2]&0xff) << 16) | (key[i+3] << 24);
i+=4;
t++;
}
//
// while not enough round key material calculated
// calculate new values
//
int k = (ROUNDS + 1) << 2;
for (i = KC; (i < k); i++)
{
int temp = W[(i-1)>>2][(i-1)&3];
if ((i % KC) == 0)
{
temp = subWord(shift(temp, 8)) ^ rcon[(i / KC)-1];
}
else if ((KC > 6) && ((i % KC) == 4))
{
temp = subWord(temp);
}
W[i>>2][i&3] = W[(i - KC)>>2][(i-KC)&3] ^ temp;
}
if (!forEncryption)
{
for (int j = 1; j < ROUNDS; j++)
{
for (i = 0; i < 4; i++)
{
W[j][i] = inv_mcol(W[j][i]);
}
}
}
return W;
}
private int ROUNDS;
private int[][] WorkingKey = null;
private int C0, C1, C2, C3;
private boolean forEncryption;
private static final int BLOCK_SIZE = 16;
/**
* default constructor - 128 bit block size.
*/
public AESEngine()
{
}
/**
* initialise an AES cipher.
*
* @param forEncryption whether or not we are for encryption.
* @param params the parameters required to set up the cipher.
* @exception IllegalArgumentException if the params argument is
* inappropriate.
*/
public void init(
boolean forEncryption,
CipherParameters params)
{
if (params instanceof KeyParameter)
{
WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption);
this.forEncryption = forEncryption;
return;
}
throw new IllegalArgumentException("invalid parameter passed to AES init - " + params.getClass().getName());
}
public String getAlgorithmName()
{
return "AES";
}
public int getBlockSize()
{
return BLOCK_SIZE;
}
public int processBlock(
byte[] in,
int inOff,
byte[] out,
int outOff)
{
if (WorkingKey == null)
{
throw new IllegalStateException("AES engine not initialised");
}
if ((inOff + (32 / 2)) > in.length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + (32 / 2)) > out.length)
{
throw new DataLengthException("output buffer too short");
}
if (forEncryption)
{
unpackBlock(in, inOff);
encryptBlock(WorkingKey);
packBlock(out, outOff);
}
else
{
unpackBlock(in, inOff);
decryptBlock(WorkingKey);
packBlock(out, outOff);
}
return BLOCK_SIZE;
}
public void reset()
{
}
private void unpackBlock(
byte[] bytes,
int off)
{
int index = off;
C0 = (bytes[index++] & 0xff);
C0 |= (bytes[index++] & 0xff) << 8;
C0 |= (bytes[index++] & 0xff) << 16;
C0 |= bytes[index++] << 24;
C1 = (bytes[index++] & 0xff);
C1 |= (bytes[index++] & 0xff) << 8;
C1 |= (bytes[index++] & 0xff) << 16;
C1 |= bytes[index++] << 24;
C2 = (bytes[index++] & 0xff);
C2 |= (bytes[index++] & 0xff) << 8;
C2 |= (bytes[index++] & 0xff) << 16;
C2 |= bytes[index++] << 24;
C3 = (bytes[index++] & 0xff);
C3 |= (bytes[index++] & 0xff) << 8;
C3 |= (bytes[index++] & 0xff) << 16;
C3 |= bytes[index++] << 24;
}
private void packBlock(
byte[] bytes,
int off)
{
int index = off;
bytes[index++] = (byte)C0;
bytes[index++] = (byte)(C0 >> 8);
bytes[index++] = (byte)(C0 >> 16);
bytes[index++] = (byte)(C0 >> 24);
bytes[index++] = (byte)C1;
bytes[index++] = (byte)(C1 >> 8);
bytes[index++] = (byte)(C1 >> 16);
bytes[index++] = (byte)(C1 >> 24);
bytes[index++] = (byte)C2;
bytes[index++] = (byte)(C2 >> 8);
bytes[index++] = (byte)(C2 >> 16);
bytes[index++] = (byte)(C2 >> 24);
bytes[index++] = (byte)C3;
bytes[index++] = (byte)(C3 >> 8);
bytes[index++] = (byte)(C3 >> 16);
bytes[index++] = (byte)(C3 >> 24);
}
private void encryptBlock(int[][] KW)
{
int r, r0, r1, r2, r3;
C0 ^= KW[0][0];
C1 ^= KW[0][1];
C2 ^= KW[0][2];
C3 ^= KW[0][3];
r = 1;
while (r < ROUNDS - 1)
{
r0 = T0[C0&255] ^ shift(T0[(C1>>8)&255], 24) ^ shift(T0[(C2>>16)&255],16) ^ shift(T0[(C3>>24)&255],8) ^ KW[r][0];
r1 = T0[C1&255] ^ shift(T0[(C2>>8)&255], 24) ^ shift(T0[(C3>>16)&255], 16) ^ shift(T0[(C0>>24)&255], 8) ^ KW[r][1];
r2 = T0[C2&255] ^ shift(T0[(C3>>8)&255], 24) ^ shift(T0[(C0>>16)&255], 16) ^ shift(T0[(C1>>24)&255], 8) ^ KW[r][2];
r3 = T0[C3&255] ^ shift(T0[(C0>>8)&255], 24) ^ shift(T0[(C1>>16)&255], 16) ^ shift(T0[(C2>>24)&255], 8) ^ KW[r++][3];
C0 = T0[r0&255] ^ shift(T0[(r1>>8)&255], 24) ^ shift(T0[(r2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0];
C1 = T0[r1&255] ^ shift(T0[(r2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(r0>>24)&255], 8) ^ KW[r][1];
C2 = T0[r2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(r0>>16)&255], 16) ^ shift(T0[(r1>>24)&255], 8) ^ KW[r][2];
C3 = T0[r3&255] ^ shift(T0[(r0>>8)&255], 24) ^ shift(T0[(r1>>16)&255], 16) ^ shift(T0[(r2>>24)&255], 8) ^ KW[r++][3];
}
r0 = T0[C0&255] ^ shift(T0[(C1>>8)&255], 24) ^ shift(T0[(C2>>16)&255], 16) ^ shift(T0[(C3>>24)&255], 8) ^ KW[r][0];
r1 = T0[C1&255] ^ shift(T0[(C2>>8)&255], 24) ^ shift(T0[(C3>>16)&255], 16) ^ shift(T0[(C0>>24)&255], 8) ^ KW[r][1];
r2 = T0[C2&255] ^ shift(T0[(C3>>8)&255], 24) ^ shift(T0[(C0>>16)&255], 16) ^ shift(T0[(C1>>24)&255], 8) ^ KW[r][2];
r3 = T0[C3&255] ^ shift(T0[(C0>>8)&255], 24) ^ shift(T0[(C1>>16)&255], 16) ^ shift(T0[(C2>>24)&255], 8) ^ KW[r++][3];
// the final round's table is a simple function of S so we don't use a whole other four tables for it
C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((S[(r2>>16)&255]&255)<<16) ^ (S[(r3>>24)&255]<<24) ^ KW[r][0];
C1 = (S[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (S[(r0>>24)&255]<<24) ^ KW[r][1];
C2 = (S[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2];
C3 = (S[r3&255]&255) ^ ((S[(r0>>8)&255]&255)<<8) ^ ((S[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3];
}
private void decryptBlock(int[][] KW)
{
int r, r0, r1, r2, r3;
C0 ^= KW[ROUNDS][0];
C1 ^= KW[ROUNDS][1];
C2 ^= KW[ROUNDS][2];
C3 ^= KW[ROUNDS][3];
r = ROUNDS-1;
while (r>1)
{
r0 = Tinv0[C0&255] ^ shift(Tinv0[(C3>>8)&255], 24) ^ shift(Tinv0[(C2>>16)&255], 16) ^ shift(Tinv0[(C1>>24)&255], 8) ^ KW[r][0];
r1 = Tinv0[C1&255] ^ shift(Tinv0[(C0>>8)&255], 24) ^ shift(Tinv0[(C3>>16)&255], 16) ^ shift(Tinv0[(C2>>24)&255], 8) ^ KW[r][1];
r2 = Tinv0[C2&255] ^ shift(Tinv0[(C1>>8)&255], 24) ^ shift(Tinv0[(C0>>16)&255], 16) ^ shift(Tinv0[(C3>>24)&255], 8) ^ KW[r][2];
r3 = Tinv0[C3&255] ^ shift(Tinv0[(C2>>8)&255], 24) ^ shift(Tinv0[(C1>>16)&255], 16) ^ shift(Tinv0[(C0>>24)&255], 8) ^ KW[r--][3];
C0 = Tinv0[r0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(r2>>16)&255], 16) ^ shift(Tinv0[(r1>>24)&255], 8) ^ KW[r][0];
C1 = Tinv0[r1&255] ^ shift(Tinv0[(r0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(r2>>24)&255], 8) ^ KW[r][1];
C2 = Tinv0[r2&255] ^ shift(Tinv0[(r1>>8)&255], 24) ^ shift(Tinv0[(r0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2];
C3 = Tinv0[r3&255] ^ shift(Tinv0[(r2>>8)&255], 24) ^ shift(Tinv0[(r1>>16)&255], 16) ^ shift(Tinv0[(r0>>24)&255], 8) ^ KW[r--][3];
}
r0 = Tinv0[C0&255] ^ shift(Tinv0[(C3>>8)&255], 24) ^ shift(Tinv0[(C2>>16)&255], 16) ^ shift(Tinv0[(C1>>24)&255], 8) ^ KW[r][0];
r1 = Tinv0[C1&255] ^ shift(Tinv0[(C0>>8)&255], 24) ^ shift(Tinv0[(C3>>16)&255], 16) ^ shift(Tinv0[(C2>>24)&255], 8) ^ KW[r][1];
r2 = Tinv0[C2&255] ^ shift(Tinv0[(C1>>8)&255], 24) ^ shift(Tinv0[(C0>>16)&255], 16) ^ shift(Tinv0[(C3>>24)&255], 8) ^ KW[r][2];
r3 = Tinv0[C3&255] ^ shift(Tinv0[(C2>>8)&255], 24) ^ shift(Tinv0[(C1>>16)&255], 16) ^ shift(Tinv0[(C0>>24)&255], 8) ^ KW[r][3];
// the final round's table is a simple function of Si so we don't use a whole other four tables for it
C0 = (Si[r0&255]&255) ^ ((Si[(r3>>8)&255]&255)<<8) ^ ((Si[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0];
C1 = (Si[r1&255]&255) ^ ((Si[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (Si[(r2>>24)&255]<<24) ^ KW[0][1];
C2 = (Si[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (Si[(r3>>24)&255]<<24) ^ KW[0][2];
C3 = (Si[r3&255]&255) ^ ((Si[(r2>>8)&255]&255)<<8) ^ ((Si[(r1>>16)&255]&255)<<16) ^ (Si[(r0>>24)&255]<<24) ^ KW[0][3];
}
}
| mit |
python-cmd2/cmd2 | tests/test_cmd2.py | 89821 | # coding=utf-8
# flake8: noqa E302
"""
Cmd2 unit/functional testing
"""
import builtins
import io
import os
import signal
import sys
import tempfile
from code import (
InteractiveConsole,
)
from unittest import (
mock,
)
import pytest
import cmd2
from cmd2 import (
COMMAND_NAME,
ansi,
clipboard,
constants,
exceptions,
plugin,
utils,
)
from .conftest import (
HELP_HISTORY,
SET_TXT,
SHORTCUTS_TXT,
complete_tester,
normalize,
odd_file_names,
run_cmd,
verify_help_text,
)
def CreateOutsimApp():
c = cmd2.Cmd()
c.stdout = utils.StdSim(c.stdout)
return c
@pytest.fixture
def outsim_app():
return CreateOutsimApp()
def test_version(base_app):
assert cmd2.__version__
@pytest.mark.skipif(sys.version_info >= (3, 8), reason="failing in CI systems for Python 3.8 and 3.9")
def test_not_in_main_thread(base_app, capsys):
import threading
cli_thread = threading.Thread(name='cli_thread', target=base_app.cmdloop)
cli_thread.start()
cli_thread.join()
out, err = capsys.readouterr()
assert "cmdloop must be run in the main thread" in err
def test_empty_statement(base_app):
out, err = run_cmd(base_app, '')
expected = normalize('')
assert out == expected
def test_base_help(base_app):
out, err = run_cmd(base_app, 'help')
assert base_app.last_result is True
verify_help_text(base_app, out)
def test_base_help_verbose(base_app):
out, err = run_cmd(base_app, 'help -v')
assert base_app.last_result is True
verify_help_text(base_app, out)
# Make sure :param type lines are filtered out of help summary
help_doc = base_app.do_help.__func__.__doc__
help_doc += "\n:param fake param"
base_app.do_help.__func__.__doc__ = help_doc
out, err = run_cmd(base_app, 'help --verbose')
assert base_app.last_result is True
verify_help_text(base_app, out)
assert ':param' not in ''.join(out)
def test_base_argparse_help(base_app):
# Verify that "set -h" gives the same output as "help set" and that it starts in a way that makes sense
out1, err1 = run_cmd(base_app, 'set -h')
out2, err2 = run_cmd(base_app, 'help set')
assert out1 == out2
assert out1[0].startswith('Usage: set')
assert out1[1] == ''
assert out1[2].startswith('Set a settable parameter')
def test_base_invalid_option(base_app):
out, err = run_cmd(base_app, 'set -z')
assert err[0] == 'Usage: set [-h] [param] [value]'
assert 'Error: unrecognized arguments: -z' in err[1]
def test_base_shortcuts(base_app):
out, err = run_cmd(base_app, 'shortcuts')
expected = normalize(SHORTCUTS_TXT)
assert out == expected
assert base_app.last_result is True
def test_command_starts_with_shortcut():
with pytest.raises(ValueError) as excinfo:
app = cmd2.Cmd(shortcuts={'help': 'fake'})
assert "Invalid command name 'help'" in str(excinfo.value)
def test_base_set(base_app):
# force editor to be 'vim' so test is repeatable across platforms
base_app.editor = 'vim'
out, err = run_cmd(base_app, 'set')
expected = normalize(SET_TXT)
assert out == expected
assert len(base_app.last_result) == len(base_app.settables)
for param in base_app.last_result:
assert base_app.last_result[param] == base_app.settables[param].get_value()
def test_set(base_app):
out, err = run_cmd(base_app, 'set quiet True')
expected = normalize(
"""
quiet - was: False
now: True
"""
)
assert out == expected
assert base_app.last_result is True
out, err = run_cmd(base_app, 'set quiet')
expected = normalize(
"""
Name Value Description
===================================================================================================
quiet True Don't print nonessential feedback
"""
)
assert out == expected
assert len(base_app.last_result) == 1
assert base_app.last_result['quiet'] is True
def test_set_val_empty(base_app):
base_app.editor = "fake"
out, err = run_cmd(base_app, 'set editor ""')
assert base_app.editor == ''
assert base_app.last_result is True
def test_set_val_is_flag(base_app):
base_app.editor = "fake"
out, err = run_cmd(base_app, 'set editor "-h"')
assert base_app.editor == '-h'
assert base_app.last_result is True
def test_set_not_supported(base_app):
out, err = run_cmd(base_app, 'set qqq True')
expected = normalize(
"""
Parameter 'qqq' not supported (type 'set' for list of parameters).
"""
)
assert err == expected
assert base_app.last_result is False
def test_set_no_settables(base_app):
base_app._settables.clear()
out, err = run_cmd(base_app, 'set quiet True')
expected = normalize("There are no settable parameters")
assert err == expected
assert base_app.last_result is False
@pytest.mark.parametrize(
'new_val, is_valid, expected',
[
(ansi.AllowStyle.NEVER, True, ansi.AllowStyle.NEVER),
('neVeR', True, ansi.AllowStyle.NEVER),
(ansi.AllowStyle.TERMINAL, True, ansi.AllowStyle.TERMINAL),
('TeRMInal', True, ansi.AllowStyle.TERMINAL),
(ansi.AllowStyle.ALWAYS, True, ansi.AllowStyle.ALWAYS),
('AlWaYs', True, ansi.AllowStyle.ALWAYS),
('invalid', False, ansi.AllowStyle.TERMINAL),
],
)
def test_set_allow_style(base_app, new_val, is_valid, expected):
# Initialize allow_style for this test
ansi.allow_style = ansi.AllowStyle.TERMINAL
# Use the set command to alter it
out, err = run_cmd(base_app, 'set allow_style {}'.format(new_val))
assert base_app.last_result is is_valid
# Verify the results
assert ansi.allow_style == expected
if is_valid:
assert not err
assert out
# Reset allow_style to its default since it's an application-wide setting that can affect other unit tests
ansi.allow_style = ansi.AllowStyle.TERMINAL
def test_set_with_choices(base_app):
"""Test choices validation of Settables"""
fake_choices = ['valid', 'choices']
base_app.fake = fake_choices[0]
fake_settable = cmd2.Settable('fake', type(base_app.fake), "fake description", base_app, choices=fake_choices)
base_app.add_settable(fake_settable)
# Try a valid choice
out, err = run_cmd(base_app, f'set fake {fake_choices[1]}')
assert base_app.last_result is True
assert not err
# Try an invalid choice
out, err = run_cmd(base_app, 'set fake bad_value')
assert base_app.last_result is False
assert err[0].startswith("Error setting fake: invalid choice")
class OnChangeHookApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.add_settable(utils.Settable('quiet', bool, "my description", self, onchange_cb=self._onchange_quiet))
def _onchange_quiet(self, name, old, new) -> None:
"""Runs when quiet is changed via set command"""
self.poutput("You changed " + name)
@pytest.fixture
def onchange_app():
app = OnChangeHookApp()
return app
def test_set_onchange_hook(onchange_app):
out, err = run_cmd(onchange_app, 'set quiet True')
expected = normalize(
"""
You changed quiet
quiet - was: False
now: True
"""
)
assert out == expected
assert onchange_app.last_result is True
def test_base_shell(base_app, monkeypatch):
m = mock.Mock()
monkeypatch.setattr("{}.Popen".format('subprocess'), m)
out, err = run_cmd(base_app, 'shell echo a')
assert out == []
assert m.called
def test_shell_last_result(base_app):
base_app.last_result = None
run_cmd(base_app, 'shell fake')
assert base_app.last_result is not None
def test_shell_manual_call(base_app):
# Verifies crash from Issue #986 doesn't happen
cmds = ['echo "hi"', 'echo "there"', 'echo "cmd2!"']
cmd = ';'.join(cmds)
base_app.do_shell(cmd)
cmd = '&&'.join(cmds)
base_app.do_shell(cmd)
def test_base_error(base_app):
out, err = run_cmd(base_app, 'meow')
assert "is not a recognized command" in err[0]
def test_run_script(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'script.txt')
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, 'run_script {}'.format(filename))
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding='utf-8') as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
def test_run_script_with_empty_args(base_app):
out, err = run_cmd(base_app, 'run_script')
assert "the following arguments are required" in err[1]
assert base_app.last_result is None
def test_run_script_with_invalid_file(base_app, request):
# Path does not exist
out, err = run_cmd(base_app, 'run_script does_not_exist.txt')
assert "Problem accessing script from " in err[0]
assert base_app.last_result is False
# Path is a directory
test_dir = os.path.dirname(request.module.__file__)
out, err = run_cmd(base_app, 'run_script {}'.format(test_dir))
assert "Problem accessing script from " in err[0]
assert base_app.last_result is False
def test_run_script_with_empty_file(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'empty.txt')
out, err = run_cmd(base_app, 'run_script {}'.format(filename))
assert not out and not err
assert base_app.last_result is True
def test_run_script_with_binary_file(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'binary.bin')
out, err = run_cmd(base_app, 'run_script {}'.format(filename))
assert "is not an ASCII or UTF-8 encoded text file" in err[0]
assert base_app.last_result is False
def test_run_script_with_python_file(base_app, request):
m = mock.MagicMock(name='input', return_value='2')
builtins.input = m
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'pyscript', 'stop.py')
out, err = run_cmd(base_app, 'run_script {}'.format(filename))
assert "appears to be a Python file" in err[0]
assert base_app.last_result is False
def test_run_script_with_utf8_file(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'utf8.txt')
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, 'run_script {}'.format(filename))
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding='utf-8') as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
def test_run_script_nested_run_scripts(base_app, request):
# Verify that running a script with nested run_script commands works correctly,
# and runs the nested script commands in the correct order.
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'scripts', 'nested.txt')
# Run the top level script
initial_run = 'run_script ' + filename
run_cmd(base_app, initial_run)
assert base_app.last_result is True
# Check that the right commands were executed.
expected = (
"""
%s
_relative_run_script precmds.txt
set allow_style Always
help
shortcuts
_relative_run_script postcmds.txt
set allow_style Never"""
% initial_run
)
out, err = run_cmd(base_app, 'history -s')
assert out == normalize(expected)
def test_runcmds_plus_hooks(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
prefilepath = os.path.join(test_dir, 'scripts', 'precmds.txt')
postfilepath = os.path.join(test_dir, 'scripts', 'postcmds.txt')
base_app.runcmds_plus_hooks(['run_script ' + prefilepath, 'help', 'shortcuts', 'run_script ' + postfilepath])
expected = """
run_script %s
set allow_style Always
help
shortcuts
run_script %s
set allow_style Never""" % (
prefilepath,
postfilepath,
)
out, err = run_cmd(base_app, 'history -s')
assert out == normalize(expected)
def test_runcmds_plus_hooks_ctrl_c(base_app, capsys):
"""Test Ctrl-C while in runcmds_plus_hooks"""
import types
def do_keyboard_interrupt(self, _):
raise KeyboardInterrupt('Interrupting this command')
setattr(base_app, 'do_keyboard_interrupt', types.MethodType(do_keyboard_interrupt, base_app))
# Default behavior is to not stop runcmds_plus_hooks() on Ctrl-C
base_app.history.clear()
base_app.runcmds_plus_hooks(['help', 'keyboard_interrupt', 'shortcuts'])
out, err = capsys.readouterr()
assert not err
assert len(base_app.history) == 3
# Ctrl-C should stop runcmds_plus_hooks() in this case
base_app.history.clear()
base_app.runcmds_plus_hooks(['help', 'keyboard_interrupt', 'shortcuts'], stop_on_keyboard_interrupt=True)
out, err = capsys.readouterr()
assert err.startswith("Interrupting this command")
assert len(base_app.history) == 2
def test_relative_run_script(base_app, request):
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'script.txt')
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Get output out the script
script_out, script_err = run_cmd(base_app, '_relative_run_script {}'.format(filename))
assert base_app.last_result is True
assert base_app._script_dir == []
assert base_app._current_script_dir is None
# Now run the commands manually and compare their output to script's
with open(filename, encoding='utf-8') as file:
script_commands = file.read().splitlines()
manual_out = []
manual_err = []
for cmdline in script_commands:
out, err = run_cmd(base_app, cmdline)
manual_out.extend(out)
manual_err.extend(err)
assert script_out == manual_out
assert script_err == manual_err
@pytest.mark.parametrize('file_name', odd_file_names)
def test_relative_run_script_with_odd_file_names(base_app, file_name, monkeypatch):
"""Test file names with various patterns"""
# Mock out the do_run_script call to see what args are passed to it
run_script_mock = mock.MagicMock(name='do_run_script')
monkeypatch.setattr("cmd2.Cmd.do_run_script", run_script_mock)
run_cmd(base_app, "_relative_run_script {}".format(utils.quote_string(file_name)))
run_script_mock.assert_called_once_with(utils.quote_string(file_name))
def test_relative_run_script_requires_an_argument(base_app):
out, err = run_cmd(base_app, '_relative_run_script')
assert 'Error: the following arguments' in err[1]
assert base_app.last_result is None
def test_in_script(request):
class HookApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.register_cmdfinalization_hook(self.hook)
def hook(self: cmd2.Cmd, data: plugin.CommandFinalizationData) -> plugin.CommandFinalizationData:
if self.in_script():
self.poutput("WE ARE IN SCRIPT")
return data
hook_app = HookApp()
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'script.txt')
out, err = run_cmd(hook_app, 'run_script {}'.format(filename))
assert "WE ARE IN SCRIPT" in out[-1]
def test_system_exit_in_command(base_app, capsys):
"""Test raising SystemExit in a command"""
import types
exit_code = 5
def do_system_exit(self, _):
raise SystemExit(exit_code)
setattr(base_app, 'do_system_exit', types.MethodType(do_system_exit, base_app))
stop = base_app.onecmd_plus_hooks('system_exit')
assert stop
assert base_app.exit_code == exit_code
def test_passthrough_exception_in_command(base_app):
"""Test raising a PassThroughException in a command"""
import types
def do_passthrough(self, _):
wrapped_ex = OSError("Pass me up")
raise exceptions.PassThroughException(wrapped_ex=wrapped_ex)
setattr(base_app, 'do_passthrough', types.MethodType(do_passthrough, base_app))
with pytest.raises(OSError) as excinfo:
base_app.onecmd_plus_hooks('passthrough')
assert 'Pass me up' in str(excinfo.value)
def test_output_redirection(base_app):
fd, filename = tempfile.mkstemp(prefix='cmd2_test', suffix='.txt')
os.close(fd)
try:
# Verify that writing to a file works
run_cmd(base_app, 'help > {}'.format(filename))
with open(filename) as f:
content = f.read()
verify_help_text(base_app, content)
# Verify that appending to a file also works
run_cmd(base_app, 'help history >> {}'.format(filename))
with open(filename) as f:
appended_content = f.read()
assert appended_content.startswith(content)
assert len(appended_content) > len(content)
except Exception:
raise
finally:
os.remove(filename)
def test_output_redirection_to_nonexistent_directory(base_app):
filename = '~/fakedir/this_does_not_exist.txt'
out, err = run_cmd(base_app, 'help > {}'.format(filename))
assert 'Failed to redirect' in err[0]
out, err = run_cmd(base_app, 'help >> {}'.format(filename))
assert 'Failed to redirect' in err[0]
def test_output_redirection_to_too_long_filename(base_app):
filename = (
'~/sdkfhksdjfhkjdshfkjsdhfkjsdhfkjdshfkjdshfkjshdfkhdsfkjhewfuihewiufhweiufhiweufhiuewhiuewhfiuwehfia'
'ewhfiuewhfiuewhfiuewhiuewhfiuewhfiuewfhiuwehewiufhewiuhfiweuhfiuwehfiuewfhiuwehiuewfhiuewhiewuhfiueh'
'fiuwefhewiuhewiufhewiufhewiufhewiufhewiufhewiufhewiufhewiuhewiufhewiufhewiuheiufhiuewheiwufhewiufheu'
'fheiufhieuwhfewiuhfeiufhiuewfhiuewheiwuhfiuewhfiuewhfeiuwfhewiufhiuewhiuewhfeiuwhfiuwehfuiwehfiuehie'
'whfieuwfhieufhiuewhfeiuwfhiuefhueiwhfw'
)
out, err = run_cmd(base_app, 'help > {}'.format(filename))
assert 'Failed to redirect' in err[0]
out, err = run_cmd(base_app, 'help >> {}'.format(filename))
assert 'Failed to redirect' in err[0]
def test_feedback_to_output_true(base_app):
base_app.feedback_to_output = True
base_app.timing = True
f, filename = tempfile.mkstemp(prefix='cmd2_test', suffix='.txt')
os.close(f)
try:
run_cmd(base_app, 'help > {}'.format(filename))
with open(filename) as f:
content = f.readlines()
assert content[-1].startswith('Elapsed: ')
except:
raise
finally:
os.remove(filename)
def test_feedback_to_output_false(base_app):
base_app.feedback_to_output = False
base_app.timing = True
f, filename = tempfile.mkstemp(prefix='feedback_to_output', suffix='.txt')
os.close(f)
try:
out, err = run_cmd(base_app, 'help > {}'.format(filename))
with open(filename) as f:
content = f.readlines()
assert not content[-1].startswith('Elapsed: ')
assert err[0].startswith('Elapsed')
except:
raise
finally:
os.remove(filename)
def test_disallow_redirection(base_app):
# Set allow_redirection to False
base_app.allow_redirection = False
filename = 'test_allow_redirect.txt'
# Verify output wasn't redirected
out, err = run_cmd(base_app, 'help > {}'.format(filename))
verify_help_text(base_app, out)
# Verify that no file got created
assert not os.path.exists(filename)
def test_pipe_to_shell(base_app):
if sys.platform == "win32":
# Windows
command = 'help | sort'
else:
# Mac and Linux
# Get help on help and pipe it's output to the input of the word count shell command
command = 'help help | wc'
out, err = run_cmd(base_app, command)
assert out and not err
def test_pipe_to_shell_and_redirect(base_app):
filename = 'out.txt'
if sys.platform == "win32":
# Windows
command = 'help | sort > {}'.format(filename)
else:
# Mac and Linux
# Get help on help and pipe it's output to the input of the word count shell command
command = 'help help | wc > {}'.format(filename)
out, err = run_cmd(base_app, command)
assert not out and not err
assert os.path.exists(filename)
os.remove(filename)
def test_pipe_to_shell_error(base_app):
# Try to pipe command output to a shell command that doesn't exist in order to produce an error
out, err = run_cmd(base_app, 'help | foobarbaz.this_does_not_exist')
assert not out
assert "Pipe process exited with code" in err[0]
@pytest.mark.skipif(not clipboard.can_clip, reason="Pyperclip could not find a copy/paste mechanism for your system")
def test_send_to_paste_buffer(base_app):
# Test writing to the PasteBuffer/Clipboard
run_cmd(base_app, 'help >')
paste_contents = cmd2.cmd2.get_paste_buffer()
verify_help_text(base_app, paste_contents)
# Test appending to the PasteBuffer/Clipboard
run_cmd(base_app, 'help history >>')
appended_contents = cmd2.cmd2.get_paste_buffer()
assert appended_contents.startswith(paste_contents)
assert len(appended_contents) > len(paste_contents)
def test_base_timing(base_app):
base_app.feedback_to_output = False
out, err = run_cmd(base_app, 'set timing True')
expected = normalize(
"""timing - was: False
now: True
"""
)
assert out == expected
if sys.platform == 'win32':
assert err[0].startswith('Elapsed: 0:00:00')
else:
assert err[0].startswith('Elapsed: 0:00:00.0')
def _expected_no_editor_error():
expected_exception = 'OSError'
# If PyPy, expect a different exception than with Python 3
if hasattr(sys, "pypy_translation_info"):
expected_exception = 'EnvironmentError'
expected_text = normalize(
"""
EXCEPTION of type '{}' occurred with message: Please use 'set editor' to specify your text editing program of choice.
To enable full traceback, run the following command: 'set debug true'
""".format(
expected_exception
)
)
return expected_text
def test_base_debug(base_app):
# Purposely set the editor to None
base_app.editor = None
# Make sure we get an exception, but cmd2 handles it
out, err = run_cmd(base_app, 'edit')
expected = _expected_no_editor_error()
assert err == expected
# Set debug true
out, err = run_cmd(base_app, 'set debug True')
expected = normalize(
"""
debug - was: False
now: True
"""
)
assert out == expected
# Verify that we now see the exception traceback
out, err = run_cmd(base_app, 'edit')
assert err[0].startswith('Traceback (most recent call last):')
def test_debug_not_settable(base_app):
# Set debug to False and make it unsettable
base_app.debug = False
base_app.remove_settable('debug')
# Cause an exception
out, err = run_cmd(base_app, 'bad "quote')
# Since debug is unsettable, the user will not be given the option to enable a full traceback
assert err == ['Invalid syntax: No closing quotation']
def test_remove_settable_keyerror(base_app):
with pytest.raises(KeyError):
base_app.remove_settable('fake')
def test_edit_file(base_app, request, monkeypatch):
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = 'fooedit'
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name='Popen')
monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'script.txt')
run_cmd(base_app, 'edit {}'.format(filename))
# We think we have an editor, so should expect a Popen call
m.assert_called_once()
@pytest.mark.parametrize('file_name', odd_file_names)
def test_edit_file_with_odd_file_names(base_app, file_name, monkeypatch):
"""Test editor and file names with various patterns"""
# Mock out the do_shell call to see what args are passed to it
shell_mock = mock.MagicMock(name='do_shell')
monkeypatch.setattr("cmd2.Cmd.do_shell", shell_mock)
base_app.editor = 'fooedit'
file_name = utils.quote_string('nothingweird.py')
run_cmd(base_app, "edit {}".format(utils.quote_string(file_name)))
shell_mock.assert_called_once_with('"fooedit" {}'.format(utils.quote_string(file_name)))
def test_edit_file_with_spaces(base_app, request, monkeypatch):
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = 'fooedit'
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name='Popen')
monkeypatch.setattr("subprocess.Popen", m)
test_dir = os.path.dirname(request.module.__file__)
filename = os.path.join(test_dir, 'my commands.txt')
run_cmd(base_app, 'edit "{}"'.format(filename))
# We think we have an editor, so should expect a Popen call
m.assert_called_once()
def test_edit_blank(base_app, monkeypatch):
# Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
base_app.editor = 'fooedit'
# Mock out the subprocess.Popen call so we don't actually open an editor
m = mock.MagicMock(name='Popen')
monkeypatch.setattr("subprocess.Popen", m)
run_cmd(base_app, 'edit')
# We have an editor, so should expect a Popen call
m.assert_called_once()
def test_base_py_interactive(base_app):
# Mock out the InteractiveConsole.interact() call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='interact')
InteractiveConsole.interact = m
run_cmd(base_app, "py")
# Make sure our mock was called once and only once
m.assert_called_once()
def test_base_cmdloop_with_startup_commands():
intro = 'Hello World, this is an intro ...'
# Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
testargs = ["prog", 'quit']
expected = intro + '\n'
with mock.patch.object(sys, 'argv', testargs):
app = CreateOutsimApp()
app.use_rawinput = True
# Run the command loop with custom intro
app.cmdloop(intro=intro)
out = app.stdout.getvalue()
assert out == expected
def test_base_cmdloop_without_startup_commands():
# Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
testargs = ["prog"]
with mock.patch.object(sys, 'argv', testargs):
app = CreateOutsimApp()
app.use_rawinput = True
app.intro = 'Hello World, this is an intro ...'
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input', return_value='quit')
builtins.input = m
expected = app.intro + '\n'
# Run the command loop
app.cmdloop()
out = app.stdout.getvalue()
assert out == expected
def test_cmdloop_without_rawinput():
# Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
testargs = ["prog"]
with mock.patch.object(sys, 'argv', testargs):
app = CreateOutsimApp()
app.use_rawinput = False
app.echo = False
app.intro = 'Hello World, this is an intro ...'
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input', return_value='quit')
builtins.input = m
expected = app.intro + '\n'
with pytest.raises(OSError):
app.cmdloop()
out = app.stdout.getvalue()
assert out == expected
@pytest.mark.skipif(sys.platform.startswith('win'), reason="stty sane only run on Linux/Mac")
def test_stty_sane(base_app, monkeypatch):
"""Make sure stty sane is run on Linux/Mac after each command if stdin is a terminal"""
with mock.patch('sys.stdin.isatty', mock.MagicMock(name='isatty', return_value=True)):
# Mock out the subprocess.Popen call so we don't actually run stty sane
m = mock.MagicMock(name='Popen')
monkeypatch.setattr("subprocess.Popen", m)
base_app.onecmd_plus_hooks('help')
m.assert_called_once_with(['stty', 'sane'])
def test_sigint_handler(base_app):
# No KeyboardInterrupt should be raised when using sigint_protection
with base_app.sigint_protection:
base_app.sigint_handler(signal.SIGINT, 1)
# Without sigint_protection, a KeyboardInterrupt is raised
with pytest.raises(KeyboardInterrupt):
base_app.sigint_handler(signal.SIGINT, 1)
def test_raise_keyboard_interrupt(base_app):
with pytest.raises(KeyboardInterrupt) as excinfo:
base_app._raise_keyboard_interrupt()
assert 'Got a keyboard interrupt' in str(excinfo.value)
class HookFailureApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# register a postparsing hook method
self.register_postparsing_hook(self.postparsing_precmd)
def postparsing_precmd(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
"""Simulate precmd hook failure."""
data.stop = True
return data
@pytest.fixture
def hook_failure():
app = HookFailureApp()
return app
def test_precmd_hook_success(base_app):
out = base_app.onecmd_plus_hooks('help')
assert out is False
def test_precmd_hook_failure(hook_failure):
out = hook_failure.onecmd_plus_hooks('help')
assert out is True
class SayApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_say(self, arg):
self.poutput(arg)
@pytest.fixture
def say_app():
app = SayApp(allow_cli_args=False)
app.stdout = utils.StdSim(app.stdout)
return app
def test_ctrl_c_at_prompt(say_app):
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input')
m.side_effect = ['say hello', KeyboardInterrupt(), 'say goodbye', 'eof']
builtins.input = m
say_app.cmdloop()
# And verify the expected output to stdout
out = say_app.stdout.getvalue()
assert out == 'hello\n^C\ngoodbye\n\n'
class ShellApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.default_to_shell = True
def test_default_to_shell(base_app, monkeypatch):
if sys.platform.startswith('win'):
line = 'dir'
else:
line = 'ls'
base_app.default_to_shell = True
m = mock.Mock()
monkeypatch.setattr("{}.Popen".format('subprocess'), m)
out, err = run_cmd(base_app, line)
assert out == []
assert m.called
def test_escaping_prompt():
from cmd2.rl_utils import (
rl_escape_prompt,
rl_unescape_prompt,
)
# This prompt has nothing which needs to be escaped
prompt = '(Cmd) '
assert rl_escape_prompt(prompt) == prompt
# This prompt has color which needs to be escaped
color = ansi.Fg.CYAN
prompt = ansi.style('InColor', fg=color)
escape_start = "\x01"
escape_end = "\x02"
escaped_prompt = rl_escape_prompt(prompt)
if sys.platform.startswith('win'):
# PyReadline on Windows doesn't need to escape invisible characters
assert escaped_prompt == prompt
else:
assert escaped_prompt.startswith(escape_start + color + escape_end)
assert escaped_prompt.endswith(escape_start + ansi.Fg.RESET + escape_end)
assert rl_unescape_prompt(escaped_prompt) == prompt
class HelpApp(cmd2.Cmd):
"""Class for testing custom help_* methods which override docstring help."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_squat(self, arg):
"""This docstring help will never be shown because the help_squat method overrides it."""
pass
def help_squat(self):
self.stdout.write('This command does diddly squat...\n')
def do_edit(self, arg):
"""This overrides the edit command and does nothing."""
pass
# This command will be in the "undocumented" section of the help menu
def do_undoc(self, arg):
pass
def do_multiline_docstr(self, arg):
"""
This documentation
is multiple lines
and there are no
tabs
"""
pass
@pytest.fixture
def help_app():
app = HelpApp()
return app
def test_custom_command_help(help_app):
out, err = run_cmd(help_app, 'help squat')
expected = normalize('This command does diddly squat...')
assert out == expected
assert help_app.last_result is True
def test_custom_help_menu(help_app):
out, err = run_cmd(help_app, 'help')
verify_help_text(help_app, out)
def test_help_undocumented(help_app):
out, err = run_cmd(help_app, 'help undoc')
assert err[0].startswith("No help on undoc")
assert help_app.last_result is False
def test_help_overridden_method(help_app):
out, err = run_cmd(help_app, 'help edit')
expected = normalize('This overrides the edit command and does nothing.')
assert out == expected
assert help_app.last_result is True
def test_help_multiline_docstring(help_app):
out, err = run_cmd(help_app, 'help multiline_docstr')
expected = normalize('This documentation\nis multiple lines\nand there are no\ntabs')
assert out == expected
assert help_app.last_result is True
class HelpCategoriesApp(cmd2.Cmd):
"""Class for testing custom help_* methods which override docstring help."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@cmd2.with_category('Some Category')
def do_diddly(self, arg):
"""This command does diddly"""
pass
# This command will be in the "Some Category" section of the help menu even though it has no docstring
@cmd2.with_category("Some Category")
def do_cat_nodoc(self, arg):
pass
def do_squat(self, arg):
"""This docstring help will never be shown because the help_squat method overrides it."""
pass
def help_squat(self):
self.stdout.write('This command does diddly squat...\n')
def do_edit(self, arg):
"""This overrides the edit command and does nothing."""
pass
cmd2.categorize((do_squat, do_edit), 'Custom Category')
# This command will be in the "undocumented" section of the help menu
def do_undoc(self, arg):
pass
@pytest.fixture
def helpcat_app():
app = HelpCategoriesApp()
return app
def test_help_cat_base(helpcat_app):
out, err = run_cmd(helpcat_app, 'help')
assert helpcat_app.last_result is True
verify_help_text(helpcat_app, out)
def test_help_cat_verbose(helpcat_app):
out, err = run_cmd(helpcat_app, 'help --verbose')
assert helpcat_app.last_result is True
verify_help_text(helpcat_app, out)
class SelectApp(cmd2.Cmd):
def do_eat(self, arg):
"""Eat something, with a selection of sauces to choose from."""
# Pass in a single string of space-separated selections
sauce = self.select('sweet salty', 'Sauce? ')
result = '{food} with {sauce} sauce, yum!'
result = result.format(food=arg, sauce=sauce)
self.stdout.write(result + '\n')
def do_study(self, arg):
"""Learn something, with a selection of subjects to choose from."""
# Pass in a list of strings for selections
subject = self.select(['math', 'science'], 'Subject? ')
result = 'Good luck learning {}!\n'.format(subject)
self.stdout.write(result)
def do_procrastinate(self, arg):
"""Waste time in your manner of choice."""
# Pass in a list of tuples for selections
leisure_activity = self.select(
[('Netflix and chill', 'Netflix'), ('YouTube', 'WebSurfing')], 'How would you like to procrastinate? '
)
result = 'Have fun procrasinating with {}!\n'.format(leisure_activity)
self.stdout.write(result)
def do_play(self, arg):
"""Play your favorite musical instrument."""
# Pass in an uneven list of tuples for selections
instrument = self.select([('Guitar', 'Electric Guitar'), ('Drums',)], 'Instrument? ')
result = 'Charm us with the {}...\n'.format(instrument)
self.stdout.write(result)
def do_return_type(self, arg):
"""Test that return values can be non-strings"""
choice = self.select([(1, 'Integer'), ("test_str", 'String'), (self.do_play, 'Method')], 'Choice? ')
result = f'The return type is {type(choice)}\n'
self.stdout.write(result)
@pytest.fixture
def select_app():
app = SelectApp()
return app
def test_select_options(select_app, monkeypatch):
# Mock out the read_input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'bacon'
out, err = run_cmd(select_app, "eat {}".format(food))
expected = normalize(
"""
1. sweet
2. salty
{} with salty sauce, yum!
""".format(
food
)
)
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Sauce? ')
# And verify the expected output to stdout
assert out == expected
def test_select_invalid_option_too_big(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input')
# If side_effect is an iterable then each call to the mock will return the next value from the iterable.
read_input_mock.side_effect = ['3', '1'] # First pass an invalid selection, then pass a valid one
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'fish'
out, err = run_cmd(select_app, "eat {}".format(food))
expected = normalize(
"""
1. sweet
2. salty
'3' isn't a valid choice. Pick a number between 1 and 2:
{} with sweet sauce, yum!
""".format(
food
)
)
# Make sure our mock was called exactly twice with the expected arguments
arg = 'Sauce? '
calls = [mock.call(arg), mock.call(arg)]
read_input_mock.assert_has_calls(calls)
assert read_input_mock.call_count == 2
# And verify the expected output to stdout
assert out == expected
def test_select_invalid_option_too_small(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input')
# If side_effect is an iterable then each call to the mock will return the next value from the iterable.
read_input_mock.side_effect = ['0', '1'] # First pass an invalid selection, then pass a valid one
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'fish'
out, err = run_cmd(select_app, "eat {}".format(food))
expected = normalize(
"""
1. sweet
2. salty
'0' isn't a valid choice. Pick a number between 1 and 2:
{} with sweet sauce, yum!
""".format(
food
)
)
# Make sure our mock was called exactly twice with the expected arguments
arg = 'Sauce? '
calls = [mock.call(arg), mock.call(arg)]
read_input_mock.assert_has_calls(calls)
assert read_input_mock.call_count == 2
# And verify the expected output to stdout
assert out == expected
def test_select_list_of_strings(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "study")
expected = normalize(
"""
1. math
2. science
Good luck learning {}!
""".format(
'science'
)
)
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Subject? ')
# And verify the expected output to stdout
assert out == expected
def test_select_list_of_tuples(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "procrastinate")
expected = normalize(
"""
1. Netflix
2. WebSurfing
Have fun procrasinating with {}!
""".format(
'YouTube'
)
)
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('How would you like to procrastinate? ')
# And verify the expected output to stdout
assert out == expected
def test_select_uneven_list_of_tuples(select_app, monkeypatch):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value='2')
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "play")
expected = normalize(
"""
1. Electric Guitar
2. Drums
Charm us with the {}...
""".format(
'Drums'
)
)
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Instrument? ')
# And verify the expected output to stdout
assert out == expected
@pytest.mark.parametrize(
'selection, type_str',
[
('1', "<class 'int'>"),
('2', "<class 'str'>"),
('3', "<class 'method'>"),
],
)
def test_select_return_type(select_app, monkeypatch, selection, type_str):
# Mock out the input call so we don't actually wait for a user's response on stdin
read_input_mock = mock.MagicMock(name='read_input', return_value=selection)
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
out, err = run_cmd(select_app, "return_type")
expected = normalize(
"""
1. Integer
2. String
3. Method
The return type is {}
""".format(
type_str
)
)
# Make sure our mock was called with the expected arguments
read_input_mock.assert_called_once_with('Choice? ')
# And verify the expected output to stdout
assert out == expected
def test_select_eof(select_app, monkeypatch):
# Ctrl-D during select causes an EOFError that just reprompts the user
read_input_mock = mock.MagicMock(name='read_input', side_effect=[EOFError, 2])
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
food = 'fish'
out, err = run_cmd(select_app, "eat {}".format(food))
# Make sure our mock was called exactly twice with the expected arguments
arg = 'Sauce? '
calls = [mock.call(arg), mock.call(arg)]
read_input_mock.assert_has_calls(calls)
assert read_input_mock.call_count == 2
def test_select_ctrl_c(outsim_app, monkeypatch, capsys):
# Ctrl-C during select prints ^C and raises a KeyboardInterrupt
read_input_mock = mock.MagicMock(name='read_input', side_effect=KeyboardInterrupt)
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
with pytest.raises(KeyboardInterrupt):
outsim_app.select([('Guitar', 'Electric Guitar'), ('Drums',)], 'Instrument? ')
out = outsim_app.stdout.getvalue()
assert out.rstrip().endswith('^C')
class HelpNoDocstringApp(cmd2.Cmd):
greet_parser = cmd2.Cmd2ArgumentParser()
greet_parser.add_argument('-s', '--shout', action="store_true", help="N00B EMULATION MODE")
@cmd2.with_argparser(greet_parser, with_unknown_args=True)
def do_greet(self, opts, arg):
arg = ''.join(arg)
if opts.shout:
arg = arg.upper()
self.stdout.write(arg + '\n')
def test_help_with_no_docstring(capsys):
app = HelpNoDocstringApp()
app.onecmd_plus_hooks('greet -h')
out, err = capsys.readouterr()
assert err == ''
assert (
out
== """Usage: greet [-h] [-s]
optional arguments:
-h, --help show this help message and exit
-s, --shout N00B EMULATION MODE
"""
)
class MultilineApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, multiline_commands=['orate'], **kwargs)
orate_parser = cmd2.Cmd2ArgumentParser()
orate_parser.add_argument('-s', '--shout', action="store_true", help="N00B EMULATION MODE")
@cmd2.with_argparser(orate_parser, with_unknown_args=True)
def do_orate(self, opts, arg):
arg = ''.join(arg)
if opts.shout:
arg = arg.upper()
self.stdout.write(arg + '\n')
@pytest.fixture
def multiline_app():
app = MultilineApp()
return app
def test_multiline_complete_empty_statement_raises_exception(multiline_app):
with pytest.raises(exceptions.EmptyStatement):
multiline_app._complete_statement('')
def test_multiline_complete_statement_without_terminator(multiline_app):
# Mock out the input call so we don't actually wait for a user's response
# on stdin when it looks for more input
m = mock.MagicMock(name='input', return_value='\n')
builtins.input = m
command = 'orate'
args = 'hello world'
line = '{} {}'.format(command, args)
statement = multiline_app._complete_statement(line)
assert statement == args
assert statement.command == command
assert statement.multiline_command == command
def test_multiline_complete_statement_with_unclosed_quotes(multiline_app):
# Mock out the input call so we don't actually wait for a user's response
# on stdin when it looks for more input
m = mock.MagicMock(name='input', side_effect=['quotes', '" now closed;'])
builtins.input = m
line = 'orate hi "partially open'
statement = multiline_app._complete_statement(line)
assert statement == 'hi "partially open\nquotes\n" now closed'
assert statement.command == 'orate'
assert statement.multiline_command == 'orate'
assert statement.terminator == ';'
def test_multiline_input_line_to_statement(multiline_app):
# Verify _input_line_to_statement saves the fully entered input line for multiline commands
# Mock out the input call so we don't actually wait for a user's response
# on stdin when it looks for more input
m = mock.MagicMock(name='input', side_effect=['person', '\n'])
builtins.input = m
line = 'orate hi'
statement = multiline_app._input_line_to_statement(line)
assert statement.raw == 'orate hi\nperson\n'
assert statement == 'hi person'
assert statement.command == 'orate'
assert statement.multiline_command == 'orate'
def test_clipboard_failure(base_app, capsys):
# Force cmd2 clipboard to be disabled
base_app._can_clip = False
# Redirect command output to the clipboard when a clipboard isn't present
base_app.onecmd_plus_hooks('help > ')
# Make sure we got the error output
out, err = capsys.readouterr()
assert out == ''
assert 'Cannot redirect to paste buffer;' in err and 'pyperclip' in err
class CommandResultApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_affirmative(self, arg):
self.last_result = cmd2.CommandResult(arg, data=True)
def do_negative(self, arg):
self.last_result = cmd2.CommandResult(arg, data=False)
def do_affirmative_no_data(self, arg):
self.last_result = cmd2.CommandResult(arg)
def do_negative_no_data(self, arg):
self.last_result = cmd2.CommandResult('', arg)
@pytest.fixture
def commandresult_app():
app = CommandResultApp()
return app
def test_commandresult_truthy(commandresult_app):
arg = 'foo'
run_cmd(commandresult_app, 'affirmative {}'.format(arg))
assert commandresult_app.last_result
assert commandresult_app.last_result == cmd2.CommandResult(arg, data=True)
run_cmd(commandresult_app, 'affirmative_no_data {}'.format(arg))
assert commandresult_app.last_result
assert commandresult_app.last_result == cmd2.CommandResult(arg)
def test_commandresult_falsy(commandresult_app):
arg = 'bar'
run_cmd(commandresult_app, 'negative {}'.format(arg))
assert not commandresult_app.last_result
assert commandresult_app.last_result == cmd2.CommandResult(arg, data=False)
run_cmd(commandresult_app, 'negative_no_data {}'.format(arg))
assert not commandresult_app.last_result
assert commandresult_app.last_result == cmd2.CommandResult('', arg)
def test_is_text_file_bad_input(base_app):
# Test with a non-existent file
with pytest.raises(OSError):
utils.is_text_file('does_not_exist.txt')
# Test with a directory
with pytest.raises(OSError):
utils.is_text_file('.')
def test_eof(base_app):
# Only thing to verify is that it returns True
assert base_app.do_eof('')
assert base_app.last_result is True
def test_quit(base_app):
# Only thing to verify is that it returns True
assert base_app.do_quit('')
assert base_app.last_result is True
def test_echo(capsys):
app = cmd2.Cmd()
app.echo = True
commands = ['help history']
app.runcmds_plus_hooks(commands)
out, err = capsys.readouterr()
assert out.startswith('{}{}\n'.format(app.prompt, commands[0]) + HELP_HISTORY.split()[0])
def test_read_input_rawinput_true(capsys, monkeypatch):
prompt_str = 'the_prompt'
input_str = 'some input'
app = cmd2.Cmd()
app.use_rawinput = True
# Mock out input() to return input_str
monkeypatch.setattr("builtins.input", lambda *args: input_str)
# isatty is True
with mock.patch('sys.stdin.isatty', mock.MagicMock(name='isatty', return_value=True)):
line = app.read_input(prompt_str)
assert line == input_str
# Run custom history code
import readline
readline.add_history('old_history')
custom_history = ['cmd1', 'cmd2']
line = app.read_input(prompt_str, history=custom_history, completion_mode=cmd2.CompletionMode.NONE)
assert line == input_str
readline.clear_history()
# Run all completion modes
line = app.read_input(prompt_str, completion_mode=cmd2.CompletionMode.NONE)
assert line == input_str
line = app.read_input(prompt_str, completion_mode=cmd2.CompletionMode.COMMANDS)
assert line == input_str
# custom choices
custom_choices = ['choice1', 'choice2']
line = app.read_input(prompt_str, completion_mode=cmd2.CompletionMode.CUSTOM, choices=custom_choices)
assert line == input_str
# custom choices_provider
line = app.read_input(
prompt_str, completion_mode=cmd2.CompletionMode.CUSTOM, choices_provider=cmd2.Cmd.get_all_commands
)
assert line == input_str
# custom completer
line = app.read_input(prompt_str, completion_mode=cmd2.CompletionMode.CUSTOM, completer=cmd2.Cmd.path_complete)
assert line == input_str
# custom parser
line = app.read_input(prompt_str, completion_mode=cmd2.CompletionMode.CUSTOM, parser=cmd2.Cmd2ArgumentParser())
assert line == input_str
# isatty is False
with mock.patch('sys.stdin.isatty', mock.MagicMock(name='isatty', return_value=False)):
# echo True
app.echo = True
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == input_str
assert out == "{}{}\n".format(prompt_str, input_str)
# echo False
app.echo = False
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == input_str
assert not out
def test_read_input_rawinput_false(capsys, monkeypatch):
prompt_str = 'the_prompt'
input_str = 'some input'
def make_app(isatty: bool, empty_input: bool = False):
"""Make a cmd2 app with a custom stdin"""
app_input_str = '' if empty_input else input_str
fakein = io.StringIO('{}'.format(app_input_str))
fakein.isatty = mock.MagicMock(name='isatty', return_value=isatty)
new_app = cmd2.Cmd(stdin=fakein)
new_app.use_rawinput = False
return new_app
# isatty True
app = make_app(isatty=True)
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == input_str
assert out == prompt_str
# isatty True, empty input
app = make_app(isatty=True, empty_input=True)
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == 'eof'
assert out == prompt_str
# isatty is False, echo is True
app = make_app(isatty=False)
app.echo = True
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == input_str
assert out == "{}{}\n".format(prompt_str, input_str)
# isatty is False, echo is False
app = make_app(isatty=False)
app.echo = False
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == input_str
assert not out
# isatty is False, empty input
app = make_app(isatty=False, empty_input=True)
line = app.read_input(prompt_str)
out, err = capsys.readouterr()
assert line == 'eof'
assert not out
def test_read_command_line_eof(base_app, monkeypatch):
read_input_mock = mock.MagicMock(name='read_input', side_effect=EOFError)
monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
line = base_app._read_command_line("Prompt> ")
assert line == 'eof'
def test_poutput_string(outsim_app):
msg = 'This is a test'
outsim_app.poutput(msg)
out = outsim_app.stdout.getvalue()
expected = msg + '\n'
assert out == expected
def test_poutput_zero(outsim_app):
msg = 0
outsim_app.poutput(msg)
out = outsim_app.stdout.getvalue()
expected = str(msg) + '\n'
assert out == expected
def test_poutput_empty_string(outsim_app):
msg = ''
outsim_app.poutput(msg)
out = outsim_app.stdout.getvalue()
expected = '\n'
assert out == expected
def test_poutput_none(outsim_app):
msg = None
outsim_app.poutput(msg)
out = outsim_app.stdout.getvalue()
expected = 'None\n'
assert out == expected
def test_poutput_ansi_always(outsim_app):
msg = 'Hello World'
ansi.allow_style = ansi.AllowStyle.ALWAYS
colored_msg = ansi.style(msg, fg=ansi.Fg.CYAN)
outsim_app.poutput(colored_msg)
out = outsim_app.stdout.getvalue()
expected = colored_msg + '\n'
assert colored_msg != msg
assert out == expected
def test_poutput_ansi_never(outsim_app):
msg = 'Hello World'
ansi.allow_style = ansi.AllowStyle.NEVER
colored_msg = ansi.style(msg, fg=ansi.Fg.CYAN)
outsim_app.poutput(colored_msg)
out = outsim_app.stdout.getvalue()
expected = msg + '\n'
assert colored_msg != msg
assert out == expected
# These are invalid names for aliases and macros
invalid_command_name = [
'""', # Blank name
constants.COMMENT_CHAR,
'!no_shortcut',
'">"',
'"no>pe"',
'"no spaces"',
'"nopipe|"',
'"noterm;"',
'noembedded"quotes',
]
def test_get_alias_completion_items(base_app):
run_cmd(base_app, 'alias create fake run_pyscript')
run_cmd(base_app, 'alias create ls !ls -hal')
results = base_app._get_alias_completion_items()
assert len(results) == len(base_app.aliases)
for cur_res in results:
assert cur_res in base_app.aliases
# Strip trailing spaces from table output
assert cur_res.description.rstrip() == base_app.aliases[cur_res]
def test_get_macro_completion_items(base_app):
run_cmd(base_app, 'macro create foo !echo foo')
run_cmd(base_app, 'macro create bar !echo bar')
results = base_app._get_macro_completion_items()
assert len(results) == len(base_app.macros)
for cur_res in results:
assert cur_res in base_app.macros
# Strip trailing spaces from table output
assert cur_res.description.rstrip() == base_app.macros[cur_res].value
def test_get_settable_completion_items(base_app):
results = base_app._get_settable_completion_items()
assert len(results) == len(base_app.settables)
for cur_res in results:
cur_settable = base_app.settables.get(cur_res)
assert cur_settable is not None
# These CompletionItem descriptions are a two column table (Settable Value and Settable Description)
# First check if the description text starts with the value
str_value = str(cur_settable.get_value())
assert cur_res.description.startswith(str_value)
# The second column is likely to have wrapped long text. So we will just examine the
# first couple characters to look for the Settable's description.
assert cur_settable.description[0:10] in cur_res.description
def test_alias_no_subcommand(base_app):
out, err = run_cmd(base_app, 'alias')
assert "Usage: alias [-h]" in err[0]
assert "Error: the following arguments are required: SUBCOMMAND" in err[1]
def test_alias_create(base_app):
# Create the alias
out, err = run_cmd(base_app, 'alias create fake run_pyscript')
assert out == normalize("Alias 'fake' created")
assert base_app.last_result is True
# Use the alias
out, err = run_cmd(base_app, 'fake')
assert "the following arguments are required: script_path" in err[1]
# See a list of aliases
out, err = run_cmd(base_app, 'alias list')
assert out == normalize('alias create fake run_pyscript')
assert len(base_app.last_result) == len(base_app.aliases)
assert base_app.last_result['fake'] == "run_pyscript"
# Look up the new alias
out, err = run_cmd(base_app, 'alias list fake')
assert out == normalize('alias create fake run_pyscript')
assert len(base_app.last_result) == 1
assert base_app.last_result['fake'] == "run_pyscript"
# Overwrite alias
out, err = run_cmd(base_app, 'alias create fake help')
assert out == normalize("Alias 'fake' overwritten")
assert base_app.last_result is True
# Look up the updated alias
out, err = run_cmd(base_app, 'alias list fake')
assert out == normalize('alias create fake help')
assert len(base_app.last_result) == 1
assert base_app.last_result['fake'] == "help"
def test_alias_create_with_quoted_tokens(base_app):
"""Demonstrate that quotes in alias value will be preserved"""
alias_name = "fake"
alias_command = 'help ">" "out file.txt" ";"'
create_command = f"alias create {alias_name} {alias_command}"
# Create the alias
out, err = run_cmd(base_app, create_command)
assert out == normalize("Alias 'fake' created")
# Look up the new alias and verify all quotes are preserved
out, err = run_cmd(base_app, 'alias list fake')
assert out == normalize(create_command)
assert len(base_app.last_result) == 1
assert base_app.last_result[alias_name] == alias_command
@pytest.mark.parametrize('alias_name', invalid_command_name)
def test_alias_create_invalid_name(base_app, alias_name, capsys):
out, err = run_cmd(base_app, 'alias create {} help'.format(alias_name))
assert "Invalid alias name" in err[0]
assert base_app.last_result is False
def test_alias_create_with_command_name(base_app):
out, err = run_cmd(base_app, 'alias create help stuff')
assert "Alias cannot have the same name as a command" in err[0]
assert base_app.last_result is False
def test_alias_create_with_macro_name(base_app):
macro = "my_macro"
run_cmd(base_app, 'macro create {} help'.format(macro))
out, err = run_cmd(base_app, 'alias create {} help'.format(macro))
assert "Alias cannot have the same name as a macro" in err[0]
assert base_app.last_result is False
def test_alias_that_resolves_into_comment(base_app):
# Create the alias
out, err = run_cmd(base_app, 'alias create fake ' + constants.COMMENT_CHAR + ' blah blah')
assert out == normalize("Alias 'fake' created")
# Use the alias
out, err = run_cmd(base_app, 'fake')
assert not out
assert not err
def test_alias_list_invalid_alias(base_app):
# Look up invalid alias
out, err = run_cmd(base_app, 'alias list invalid')
assert "Alias 'invalid' not found" in err[0]
assert base_app.last_result == {}
def test_alias_delete(base_app):
# Create an alias
run_cmd(base_app, 'alias create fake run_pyscript')
# Delete the alias
out, err = run_cmd(base_app, 'alias delete fake')
assert out == normalize("Alias 'fake' deleted")
assert base_app.last_result is True
def test_alias_delete_all(base_app):
out, err = run_cmd(base_app, 'alias delete --all')
assert out == normalize("All aliases deleted")
assert base_app.last_result is True
def test_alias_delete_non_existing(base_app):
out, err = run_cmd(base_app, 'alias delete fake')
assert "Alias 'fake' does not exist" in err[0]
assert base_app.last_result is True
def test_alias_delete_no_name(base_app):
out, err = run_cmd(base_app, 'alias delete')
assert "Either --all or alias name(s)" in err[0]
assert base_app.last_result is False
def test_multiple_aliases(base_app):
alias1 = 'h1'
alias2 = 'h2'
run_cmd(base_app, 'alias create {} help'.format(alias1))
run_cmd(base_app, 'alias create {} help -v'.format(alias2))
out, err = run_cmd(base_app, alias1)
verify_help_text(base_app, out)
out, err = run_cmd(base_app, alias2)
verify_help_text(base_app, out)
def test_macro_no_subcommand(base_app):
out, err = run_cmd(base_app, 'macro')
assert "Usage: macro [-h]" in err[0]
assert "Error: the following arguments are required: SUBCOMMAND" in err[1]
def test_macro_create(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake run_pyscript')
assert out == normalize("Macro 'fake' created")
assert base_app.last_result is True
# Use the macro
out, err = run_cmd(base_app, 'fake')
assert "the following arguments are required: script_path" in err[1]
# See a list of macros
out, err = run_cmd(base_app, 'macro list')
assert out == normalize('macro create fake run_pyscript')
assert len(base_app.last_result) == len(base_app.macros)
assert base_app.last_result['fake'] == "run_pyscript"
# Look up the new macro
out, err = run_cmd(base_app, 'macro list fake')
assert out == normalize('macro create fake run_pyscript')
assert len(base_app.last_result) == 1
assert base_app.last_result['fake'] == "run_pyscript"
# Overwrite macro
out, err = run_cmd(base_app, 'macro create fake help')
assert out == normalize("Macro 'fake' overwritten")
assert base_app.last_result is True
# Look up the updated macro
out, err = run_cmd(base_app, 'macro list fake')
assert out == normalize('macro create fake help')
assert len(base_app.last_result) == 1
assert base_app.last_result['fake'] == "help"
def test_macro_create_with_quoted_tokens(base_app):
"""Demonstrate that quotes in macro value will be preserved"""
macro_name = "fake"
macro_command = 'help ">" "out file.txt" ";"'
create_command = f"macro create {macro_name} {macro_command}"
# Create the macro
out, err = run_cmd(base_app, create_command)
assert out == normalize("Macro 'fake' created")
# Look up the new macro and verify all quotes are preserved
out, err = run_cmd(base_app, 'macro list fake')
assert out == normalize(create_command)
assert len(base_app.last_result) == 1
assert base_app.last_result[macro_name] == macro_command
@pytest.mark.parametrize('macro_name', invalid_command_name)
def test_macro_create_invalid_name(base_app, macro_name):
out, err = run_cmd(base_app, 'macro create {} help'.format(macro_name))
assert "Invalid macro name" in err[0]
assert base_app.last_result is False
def test_macro_create_with_command_name(base_app):
out, err = run_cmd(base_app, 'macro create help stuff')
assert "Macro cannot have the same name as a command" in err[0]
assert base_app.last_result is False
def test_macro_create_with_alias_name(base_app):
macro = "my_macro"
run_cmd(base_app, 'alias create {} help'.format(macro))
out, err = run_cmd(base_app, 'macro create {} help'.format(macro))
assert "Macro cannot have the same name as an alias" in err[0]
assert base_app.last_result is False
def test_macro_create_with_args(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake {1} {2}')
assert out == normalize("Macro 'fake' created")
# Run the macro
out, err = run_cmd(base_app, 'fake help -v')
verify_help_text(base_app, out)
def test_macro_create_with_escaped_args(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake help {{1}}')
assert out == normalize("Macro 'fake' created")
# Run the macro
out, err = run_cmd(base_app, 'fake')
assert err[0].startswith('No help on {1}')
def test_macro_usage_with_missing_args(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake help {1} {2}')
assert out == normalize("Macro 'fake' created")
# Run the macro
out, err = run_cmd(base_app, 'fake arg1')
assert "expects at least 2 arguments" in err[0]
def test_macro_usage_with_exta_args(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake help {1}')
assert out == normalize("Macro 'fake' created")
# Run the macro
out, err = run_cmd(base_app, 'fake alias create')
assert "Usage: alias create" in out[0]
def test_macro_create_with_missing_arg_nums(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake help {1} {3}')
assert "Not all numbers between 1 and 3" in err[0]
assert base_app.last_result is False
def test_macro_create_with_invalid_arg_num(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake help {1} {-1} {0}')
assert "Argument numbers must be greater than 0" in err[0]
assert base_app.last_result is False
def test_macro_create_with_unicode_numbered_arg(base_app):
# Create the macro expecting 1 argument
out, err = run_cmd(base_app, 'macro create fake help {\N{ARABIC-INDIC DIGIT ONE}}')
assert out == normalize("Macro 'fake' created")
# Run the macro
out, err = run_cmd(base_app, 'fake')
assert "expects at least 1 argument" in err[0]
def test_macro_create_with_missing_unicode_arg_nums(base_app):
out, err = run_cmd(base_app, 'macro create fake help {1} {\N{ARABIC-INDIC DIGIT THREE}}')
assert "Not all numbers between 1 and 3" in err[0]
assert base_app.last_result is False
def test_macro_that_resolves_into_comment(base_app):
# Create the macro
out, err = run_cmd(base_app, 'macro create fake {1} blah blah')
assert out == normalize("Macro 'fake' created")
# Use the macro
out, err = run_cmd(base_app, 'fake ' + constants.COMMENT_CHAR)
assert not out
assert not err
def test_macro_list_invalid_macro(base_app):
# Look up invalid macro
out, err = run_cmd(base_app, 'macro list invalid')
assert "Macro 'invalid' not found" in err[0]
assert base_app.last_result == {}
def test_macro_delete(base_app):
# Create an macro
run_cmd(base_app, 'macro create fake run_pyscript')
# Delete the macro
out, err = run_cmd(base_app, 'macro delete fake')
assert out == normalize("Macro 'fake' deleted")
assert base_app.last_result is True
def test_macro_delete_all(base_app):
out, err = run_cmd(base_app, 'macro delete --all')
assert out == normalize("All macros deleted")
assert base_app.last_result is True
def test_macro_delete_non_existing(base_app):
out, err = run_cmd(base_app, 'macro delete fake')
assert "Macro 'fake' does not exist" in err[0]
assert base_app.last_result is True
def test_macro_delete_no_name(base_app):
out, err = run_cmd(base_app, 'macro delete')
assert "Either --all or macro name(s)" in err[0]
assert base_app.last_result is False
def test_multiple_macros(base_app):
macro1 = 'h1'
macro2 = 'h2'
run_cmd(base_app, 'macro create {} help'.format(macro1))
run_cmd(base_app, 'macro create {} help -v'.format(macro2))
out, err = run_cmd(base_app, macro1)
verify_help_text(base_app, out)
out2, err2 = run_cmd(base_app, macro2)
verify_help_text(base_app, out2)
assert len(out2) > len(out)
def test_nonexistent_macro(base_app):
from cmd2.parsing import (
StatementParser,
)
exception = None
try:
base_app._resolve_macro(StatementParser().parse('fake'))
except KeyError as e:
exception = e
assert exception is not None
def test_perror_style(base_app, capsys):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.perror(msg)
out, err = capsys.readouterr()
assert err == ansi.style_error(msg) + end
def test_perror_no_style(base_app, capsys):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.perror(msg, apply_style=False)
out, err = capsys.readouterr()
assert err == msg + end
def test_pwarning_style(base_app, capsys):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.pwarning(msg)
out, err = capsys.readouterr()
assert err == ansi.style_warning(msg) + end
def test_pwarning_no_style(base_app, capsys):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.pwarning(msg, apply_style=False)
out, err = capsys.readouterr()
assert err == msg + end
def test_pexcept_style(base_app, capsys):
msg = Exception('testing...')
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.pexcept(msg)
out, err = capsys.readouterr()
assert err.startswith(ansi.style_error("EXCEPTION of type 'Exception' occurred with message: testing..."))
def test_pexcept_no_style(base_app, capsys):
msg = Exception('testing...')
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.pexcept(msg, apply_style=False)
out, err = capsys.readouterr()
assert err.startswith("EXCEPTION of type 'Exception' occurred with message: testing...")
def test_pexcept_not_exception(base_app, capsys):
# Pass in a msg that is not an Exception object
msg = False
ansi.allow_style = ansi.AllowStyle.ALWAYS
base_app.pexcept(msg)
out, err = capsys.readouterr()
assert err.startswith(ansi.style_error(msg))
def test_ppaged(outsim_app):
msg = 'testing...'
end = '\n'
outsim_app.ppaged(msg)
out = outsim_app.stdout.getvalue()
assert out == msg + end
def test_ppaged_blank(outsim_app):
msg = ''
outsim_app.ppaged(msg)
out = outsim_app.stdout.getvalue()
assert not out
def test_ppaged_none(outsim_app):
msg = None
outsim_app.ppaged(msg)
out = outsim_app.stdout.getvalue()
assert not out
def test_ppaged_strips_ansi_when_redirecting(outsim_app):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.TERMINAL
outsim_app._redirecting = True
outsim_app.ppaged(ansi.style(msg, fg=ansi.Fg.RED))
out = outsim_app.stdout.getvalue()
assert out == msg + end
def test_ppaged_strips_ansi_when_redirecting_if_always(outsim_app):
msg = 'testing...'
end = '\n'
ansi.allow_style = ansi.AllowStyle.ALWAYS
outsim_app._redirecting = True
colored_msg = ansi.style(msg, fg=ansi.Fg.RED)
outsim_app.ppaged(colored_msg)
out = outsim_app.stdout.getvalue()
assert out == colored_msg + end
# we override cmd.parseline() so we always get consistent
# command parsing by parent methods we don't override
# don't need to test all the parsing logic here, because
# parseline just calls StatementParser.parse_command_only()
def test_parseline_empty(base_app):
statement = ''
command, args, line = base_app.parseline(statement)
assert not command
assert not args
assert not line
def test_parseline(base_app):
statement = " command with 'partially completed quotes "
command, args, line = base_app.parseline(statement)
assert command == 'command'
assert args == "with 'partially completed quotes"
assert line == statement.strip()
def test_onecmd_raw_str_continue(outsim_app):
line = "help"
stop = outsim_app.onecmd(line)
out = outsim_app.stdout.getvalue()
assert not stop
verify_help_text(outsim_app, out)
def test_onecmd_raw_str_quit(outsim_app):
line = "quit"
stop = outsim_app.onecmd(line)
out = outsim_app.stdout.getvalue()
assert stop
assert out == ''
def test_onecmd_add_to_history(outsim_app):
line = "help"
saved_hist_len = len(outsim_app.history)
# Allow command to be added to history
outsim_app.onecmd(line, add_to_history=True)
new_hist_len = len(outsim_app.history)
assert new_hist_len == saved_hist_len + 1
saved_hist_len = new_hist_len
# Prevent command from being added to history
outsim_app.onecmd(line, add_to_history=False)
new_hist_len = len(outsim_app.history)
assert new_hist_len == saved_hist_len
def test_get_all_commands(base_app):
# Verify that the base app has the expected commands
commands = base_app.get_all_commands()
expected_commands = [
'_relative_run_script',
'alias',
'edit',
'eof',
'help',
'history',
'ipy',
'macro',
'py',
'quit',
'run_pyscript',
'run_script',
'set',
'shell',
'shortcuts',
]
assert commands == expected_commands
def test_get_help_topics(base_app):
# Verify that the base app has no additional help_foo methods
custom_help = base_app.get_help_topics()
assert len(custom_help) == 0
def test_get_help_topics_hidden():
# Verify get_help_topics() filters out hidden commands
class TestApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_my_cmd(self, args):
pass
def help_my_cmd(self, args):
pass
app = TestApp()
assert 'my_cmd' in app.get_help_topics()
app.hidden_commands.append('my_cmd')
assert 'my_cmd' not in app.get_help_topics()
class ReplWithExitCode(cmd2.Cmd):
"""Example cmd2 application where we can specify an exit code when existing."""
def __init__(self):
super().__init__(allow_cli_args=False)
@cmd2.with_argument_list
def do_exit(self, arg_list) -> bool:
"""Exit the application with an optional exit code.
Usage: exit [exit_code]
Where:
* exit_code - integer exit code to return to the shell"""
# If an argument was provided
if arg_list:
try:
self.exit_code = int(arg_list[0])
except ValueError:
self.perror("{} isn't a valid integer exit code".format(arg_list[0]))
self.exit_code = 1
# Return True to stop the command loop
return True
def postloop(self) -> None:
"""Hook method executed once when the cmdloop() method is about to return."""
self.poutput('exiting with code: {}'.format(self.exit_code))
@pytest.fixture
def exit_code_repl():
app = ReplWithExitCode()
app.stdout = utils.StdSim(app.stdout)
return app
def test_exit_code_default(exit_code_repl):
app = exit_code_repl
app.use_rawinput = True
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input', return_value='exit')
builtins.input = m
expected = 'exiting with code: 0\n'
# Run the command loop
app.cmdloop()
out = app.stdout.getvalue()
assert out == expected
def test_exit_code_nonzero(exit_code_repl):
app = exit_code_repl
app.use_rawinput = True
# Mock out the input call so we don't actually wait for a user's response on stdin
m = mock.MagicMock(name='input', return_value='exit 23')
builtins.input = m
expected = 'exiting with code: 23\n'
# Run the command loop
app.cmdloop()
out = app.stdout.getvalue()
assert out == expected
class AnsiApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def do_echo(self, args):
self.poutput(args)
self.perror(args)
def do_echo_error(self, args):
self.poutput(ansi.style(args, fg=ansi.Fg.RED))
# perror uses colors by default
self.perror(args)
def test_ansi_pouterr_always_tty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.ALWAYS
mocker.patch.object(app.stdout, 'isatty', return_value=True)
mocker.patch.object(sys.stderr, 'isatty', return_value=True)
app.onecmd_plus_hooks('echo_error oopsie')
out, err = capsys.readouterr()
# if colors are on, the output should have some ANSI style sequences in it
assert len(out) > len('oopsie\n')
assert 'oopsie' in out
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
# but this one shouldn't
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == 'oopsie\n'
# errors always have colors
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
def test_ansi_pouterr_always_notty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.ALWAYS
mocker.patch.object(app.stdout, 'isatty', return_value=False)
mocker.patch.object(sys.stderr, 'isatty', return_value=False)
app.onecmd_plus_hooks('echo_error oopsie')
out, err = capsys.readouterr()
# if colors are on, the output should have some ANSI style sequences in it
assert len(out) > len('oopsie\n')
assert 'oopsie' in out
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
# but this one shouldn't
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == 'oopsie\n'
# errors always have colors
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
def test_ansi_terminal_tty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.TERMINAL
mocker.patch.object(app.stdout, 'isatty', return_value=True)
mocker.patch.object(sys.stderr, 'isatty', return_value=True)
app.onecmd_plus_hooks('echo_error oopsie')
# if colors are on, the output should have some ANSI style sequences in it
out, err = capsys.readouterr()
assert len(out) > len('oopsie\n')
assert 'oopsie' in out
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
# but this one shouldn't
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == 'oopsie\n'
assert len(err) > len('oopsie\n')
assert 'oopsie' in err
def test_ansi_terminal_notty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.TERMINAL
mocker.patch.object(app.stdout, 'isatty', return_value=False)
mocker.patch.object(sys.stderr, 'isatty', return_value=False)
app.onecmd_plus_hooks('echo_error oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
def test_ansi_never_tty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.NEVER
mocker.patch.object(app.stdout, 'isatty', return_value=True)
mocker.patch.object(sys.stderr, 'isatty', return_value=True)
app.onecmd_plus_hooks('echo_error oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
def test_ansi_never_notty(mocker, capsys):
app = AnsiApp()
ansi.allow_style = ansi.AllowStyle.NEVER
mocker.patch.object(app.stdout, 'isatty', return_value=False)
mocker.patch.object(sys.stderr, 'isatty', return_value=False)
app.onecmd_plus_hooks('echo_error oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
app.onecmd_plus_hooks('echo oopsie')
out, err = capsys.readouterr()
assert out == err == 'oopsie\n'
class DisableCommandsApp(cmd2.Cmd):
"""Class for disabling commands"""
category_name = "Test Category"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@cmd2.with_category(category_name)
def do_has_helper_funcs(self, arg):
self.poutput("The real has_helper_funcs")
def help_has_helper_funcs(self):
self.poutput('Help for has_helper_funcs')
def complete_has_helper_funcs(self, *args):
return ['result']
@cmd2.with_category(category_name)
def do_has_no_helper_funcs(self, arg):
"""Help for has_no_helper_funcs"""
self.poutput("The real has_no_helper_funcs")
@pytest.fixture
def disable_commands_app():
app = DisableCommandsApp()
return app
def test_disable_and_enable_category(disable_commands_app):
##########################################################################
# Disable the category
##########################################################################
message_to_print = 'These commands are currently disabled'
disable_commands_app.disable_category(disable_commands_app.category_name, message_to_print)
# Make sure all the commands and help on those commands displays the message
out, err = run_cmd(disable_commands_app, 'has_helper_funcs')
assert err[0].startswith(message_to_print)
out, err = run_cmd(disable_commands_app, 'help has_helper_funcs')
assert err[0].startswith(message_to_print)
out, err = run_cmd(disable_commands_app, 'has_no_helper_funcs')
assert err[0].startswith(message_to_print)
out, err = run_cmd(disable_commands_app, 'help has_no_helper_funcs')
assert err[0].startswith(message_to_print)
# Make sure neither function completes
text = ''
line = 'has_helper_funcs {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
first_match = complete_tester(text, line, begidx, endidx, disable_commands_app)
assert first_match is None
text = ''
line = 'has_no_helper_funcs {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
first_match = complete_tester(text, line, begidx, endidx, disable_commands_app)
assert first_match is None
# Make sure both commands are invisible
visible_commands = disable_commands_app.get_visible_commands()
assert 'has_helper_funcs' not in visible_commands
assert 'has_no_helper_funcs' not in visible_commands
# Make sure get_help_topics() filters out disabled commands
help_topics = disable_commands_app.get_help_topics()
assert 'has_helper_funcs' not in help_topics
##########################################################################
# Enable the category
##########################################################################
disable_commands_app.enable_category(disable_commands_app.category_name)
# Make sure all the commands and help on those commands are restored
out, err = run_cmd(disable_commands_app, 'has_helper_funcs')
assert out[0] == "The real has_helper_funcs"
out, err = run_cmd(disable_commands_app, 'help has_helper_funcs')
assert out[0] == "Help for has_helper_funcs"
out, err = run_cmd(disable_commands_app, 'has_no_helper_funcs')
assert out[0] == "The real has_no_helper_funcs"
out, err = run_cmd(disable_commands_app, 'help has_no_helper_funcs')
assert out[0] == "Help for has_no_helper_funcs"
# has_helper_funcs should complete now
text = ''
line = 'has_helper_funcs {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
first_match = complete_tester(text, line, begidx, endidx, disable_commands_app)
assert first_match is not None and disable_commands_app.completion_matches == ['result ']
# has_no_helper_funcs had no completer originally, so there should be no results
text = ''
line = 'has_no_helper_funcs {}'.format(text)
endidx = len(line)
begidx = endidx - len(text)
first_match = complete_tester(text, line, begidx, endidx, disable_commands_app)
assert first_match is None
# Make sure both commands are visible
visible_commands = disable_commands_app.get_visible_commands()
assert 'has_helper_funcs' in visible_commands
assert 'has_no_helper_funcs' in visible_commands
# Make sure get_help_topics() contains our help function
help_topics = disable_commands_app.get_help_topics()
assert 'has_helper_funcs' in help_topics
def test_enable_enabled_command(disable_commands_app):
# Test enabling a command that is not disabled
saved_len = len(disable_commands_app.disabled_commands)
disable_commands_app.enable_command('has_helper_funcs')
# The number of disabled_commands should not have changed
assert saved_len == len(disable_commands_app.disabled_commands)
def test_disable_fake_command(disable_commands_app):
with pytest.raises(AttributeError):
disable_commands_app.disable_command('fake', 'fake message')
def test_disable_command_twice(disable_commands_app):
saved_len = len(disable_commands_app.disabled_commands)
message_to_print = 'These commands are currently disabled'
disable_commands_app.disable_command('has_helper_funcs', message_to_print)
# The length of disabled_commands should have increased one
new_len = len(disable_commands_app.disabled_commands)
assert saved_len == new_len - 1
saved_len = new_len
# Disable again and the length should not change
disable_commands_app.disable_command('has_helper_funcs', message_to_print)
new_len = len(disable_commands_app.disabled_commands)
assert saved_len == new_len
def test_disabled_command_not_in_history(disable_commands_app):
message_to_print = 'These commands are currently disabled'
disable_commands_app.disable_command('has_helper_funcs', message_to_print)
saved_len = len(disable_commands_app.history)
run_cmd(disable_commands_app, 'has_helper_funcs')
assert saved_len == len(disable_commands_app.history)
def test_disabled_message_command_name(disable_commands_app):
message_to_print = '{} is currently disabled'.format(COMMAND_NAME)
disable_commands_app.disable_command('has_helper_funcs', message_to_print)
out, err = run_cmd(disable_commands_app, 'has_helper_funcs')
assert err[0].startswith('has_helper_funcs is currently disabled')
@pytest.mark.parametrize('silence_startup_script', [True, False])
def test_startup_script(request, capsys, silence_startup_script):
test_dir = os.path.dirname(request.module.__file__)
startup_script = os.path.join(test_dir, '.cmd2rc')
app = cmd2.Cmd(allow_cli_args=False, startup_script=startup_script, silence_startup_script=silence_startup_script)
assert len(app._startup_commands) == 1
app._startup_commands.append('quit')
app.cmdloop()
out, err = capsys.readouterr()
if silence_startup_script:
assert not out
else:
assert out
out, err = run_cmd(app, 'alias list')
assert len(out) > 1
assert 'alias create ls' in out[0]
@pytest.mark.parametrize('startup_script', odd_file_names)
def test_startup_script_with_odd_file_names(startup_script):
"""Test file names with various patterns"""
# Mock os.path.exists to trick cmd2 into adding this script to its startup commands
saved_exists = os.path.exists
os.path.exists = mock.MagicMock(name='exists', return_value=True)
app = cmd2.Cmd(allow_cli_args=False, startup_script=startup_script)
assert len(app._startup_commands) == 1
assert app._startup_commands[0] == "run_script {}".format(utils.quote_string(os.path.abspath(startup_script)))
# Restore os.path.exists
os.path.exists = saved_exists
def test_transcripts_at_init():
transcript_files = ['foo', 'bar']
app = cmd2.Cmd(allow_cli_args=False, transcript_files=transcript_files)
assert app._transcript_files == transcript_files
| mit |
thetodd/em5_status | game_plugin/game_plugin/gui/GuiManager.cpp | 1172 | #include "game_plugin/PrecompiledHeader.h"
#include "game_plugin/gui/GuiManager.h"
#include "game_plugin/gui/FMSGui.h"
#include <em5/gui/IngameHud.h>
#include <em5/gui/hud/BaseHudLayer.h>
#include <em5/gui/EmergencyGui.h>
#include <em5/EM5Helper.h>
namespace flo11
{
GuiManager::GuiManager():
mContext(nullptr)
{
//nothing to do here
}
GuiManager::~GuiManager()
{
mStartupMessageProxy.unregister();
mShutdownMessageProxy.unregister();
}
void GuiManager::init()
{
mStartupMessageProxy.registerAt(qsf::MessageConfiguration(em5::Messages::GAME_STARTUP_FINISHED), boost::bind(&GuiManager::startup, this, _1));
mShutdownMessageProxy.registerAt(qsf::MessageConfiguration(em5::Messages::GAME_SHUTDOWN_STARTING), boost::bind(&GuiManager::shutdown, this, _1));
}
void GuiManager::startup(const qsf::MessageParameters& parameters)
{
//actual guis
mContext = &EM5_GUI.getIngameHud().getBaseHudLayer().getGuiContext();
FMSGui::init(*mContext);
}
void GuiManager::shutdown(const qsf::MessageParameters& parameters)
{
//actual guis
FMSGui::shutdown();
}
} | mit |
vsco/domino | domino_test.go | 21213 | package domino
import (
// "fmt"
"context"
"fmt"
"net/http"
"strconv"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/stretchr/testify/assert"
)
const localDynamoHost = "http://127.0.0.1:4569"
type UserTable struct {
DynamoTable
emailField String
passwordField String
registrationDate Numeric
loginCount Numeric
lastLoginDate Numeric
visits NumericSet
preferences Map
name String
lastName String
locales StringSet
degrees NumericSet
registrationDateIndex LocalSecondaryIndex
nameGlobalIndex GlobalSecondaryIndex
}
type User struct {
Email string `dynamodbav:"email,omitempty"`
Password string `dynamodbav:"password,omitempty"`
Visits []int64 `dynamodbav:"visits,numberset,omitempty"`
Degrees []float64 `dynamodbav:"degrees,numberset,omitempty"`
Locales []string `dynamodbav:"locales,stringset,omitempty"`
LoginCount int `dynamodbav:"loginCount,omitempty"`
LoginDate int64 `dynamodbav:"lastLoginDate,omitempty"`
RegDate int64 `dynamodbav:"registrationDate,omitempty"`
Preferences map[string]string `dynamodbav:"preferences,omitempty"`
}
func NewUserTable() UserTable {
pk := StringField("email")
rk := StringField("password")
firstName := StringField("firstName")
lastName := StringField("lastName")
reg := NumericField("registrationDate")
nameGlobalIndex := GlobalSecondaryIndex{
Name: "name-index",
PartitionKey: firstName,
RangeKey: lastName,
ProjectionType: ProjectionTypeALL,
}
registrationDateIndex := LocalSecondaryIndex{
Name: "registrationDate-index",
PartitionKey: pk,
SortKey: reg,
}
return UserTable{
DynamoTable{
Name: "users",
PartitionKey: pk,
RangeKey: rk,
GlobalSecondaryIndexes: []GlobalSecondaryIndex{
nameGlobalIndex,
},
LocalSecondaryIndexes: []LocalSecondaryIndex{
registrationDateIndex,
},
},
pk, //email
rk, //password
reg, //registration
NumericField("loginCount"),
NumericField("lastLoginDate"),
NumericSetField("visits"),
MapField("preferences"),
firstName,
lastName,
StringSetField("locales"),
NumericSetField("degrees"),
registrationDateIndex,
nameGlobalIndex,
}
}
func NewDB() DynamoDBIFace {
region := "us-west-2"
creds := credentials.NewStaticCredentials("123", "123", "")
config := aws.
NewConfig().
WithRegion(region).
WithCredentials(creds).
WithEndpoint(localDynamoHost).
WithHTTPClient(http.DefaultClient)
sess := session.New(config)
return dynamodb.New(sess)
}
func TestCreateTable(t *testing.T) {
ctx := context.Background()
db := NewDB()
table := NewUserTable()
err := table.CreateTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
err = table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
// Test nil range key
table.RangeKey = nil
table.LocalSecondaryIndexes = nil // Illegal to have an lsi, and no range key
err = table.CreateTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
err = table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
// Test nil gsi range key
table.nameGlobalIndex.RangeKey = nil
err = table.CreateTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
err = table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
}
func TestGetItem(t *testing.T) {
ctx := context.Background()
table := NewUserTable()
db := NewDB()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
item := User{Email: "naveen@email.com", Password: "password"}
err = table.PutItem(item).ExecuteWith(ctx, db).Result(nil)
assert.Nil(t, err)
var r *User = &User{}
err = table.GetItem(KeyValue{"naveen@email.com", "password"}).
SetConsistentRead(true).
ExecuteWith(ctx, db).
Result(r)
assert.Nil(t, err)
assert.Equal(t, &User{Email: "naveen@email.com", Password: "password"}, r)
}
func TestGetItemEmpty(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
out := table.GetItem(KeyValue{"naveen@email.com", "password"}).ExecuteWith(ctx, db)
assert.Nil(t, out.Error())
assert.Empty(t, out.Item)
}
func TestBatchPutItem(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
items := []interface{}{}
for i := 0; i < 100; i++ {
row := User{Email: fmt.Sprintf("%dbob@email.com", i), Password: "password"}
items = append(items, row)
}
q := table.
BatchWriteItem().
PutItems(items...).
DeleteItems(
KeyValue{"name@email.com", "password"},
)
unprocessed := []*User{}
f := func() interface{} {
user := User{}
unprocessed = append(unprocessed, &user)
return &user
}
err = q.ExecuteWith(ctx, db).Results(f)
assert.Empty(t, unprocessed)
assert.NoError(t, err)
keys := []KeyValue{}
for i := 0; i < 100; i++ {
key := KeyValue{fmt.Sprintf("%dbob@email.com", i), "password"}
keys = append(keys, key)
}
g := table.
BatchGetItem(keys...)
users := []*User{}
nextItem := func() interface{} {
user := User{}
users = append(users, &user)
return &user
}
err = g.ExecuteWith(ctx, db).Results(nextItem)
assert.NotEmpty(t, users)
}
func TestBatchGetItem(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
u := &User{Email: "bob@email.com", Password: "password"}
items := []interface{}{u}
kvs := []KeyValue{}
for i := 0; i < 198; i++ {
items = append(items, &User{Email: "bob@email.com", Password: "password" + strconv.Itoa(i)})
kvs = append(kvs, KeyValue{"bob@email.com", "password" + strconv.Itoa(i)})
}
ui := []*User{}
w := table.BatchWriteItem().PutItems(items...)
f := func() interface{} {
u := User{}
ui = append(ui, &u)
return &u
}
err = w.ExecuteWith(ctx, db).Results(f)
assert.NoError(t, err)
assert.Empty(t, ui)
g := table.BatchGetItem(kvs...)
users := []*User{}
nextItem := func() interface{} {
user := User{}
users = append(users, &user)
return &user
}
err = g.ExecuteWith(ctx, db).Results(nextItem)
assert.NoError(t, err)
assert.Equal(t, len(users), 198)
// TransactGetItems
users = []*User{}
tg := table.TransactGetItems(kvs...)
b, berr := tg.Build()
assert.NoError(t, berr)
assert.Equal(t, 20, len(b))
err = tg.ExecuteWith(ctx, db).Results(nextItem)
assert.NoError(t, err)
assert.Equal(t, len(users), 198)
}
func TestUpdateItem(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
item := User{Email: "name@email.com", Password: "password", Degrees: []float64{1, 2}, Locales: []string{"eu"}, Preferences: map[string]string{"update_email": "test"}}
q := table.PutItem(item)
err = q.ExecuteWith(ctx, db).Result(nil)
assert.NoError(t, err)
u := table.
UpdateItem(KeyValue{"name@email.com", "password"}).
SetUpdateExpression(
table.loginCount.Increment(1),
table.lastLoginDate.SetField(time.Now().UnixNano(), false),
table.registrationDate.SetField(time.Now().UnixNano(), true),
table.visits.AddInteger(time.Now().UnixNano()),
table.preferences.Remove("update_email"),
table.preferences.Set("test", "value"),
table.locales.AddString("us"),
table.degrees.DeleteFloat(1),
)
err = u.ExecuteWith(ctx, db).Result(nil)
if err != nil {
fmt.Println(err.Error())
}
assert.Nil(t, err)
out := table.GetItem(KeyValue{"name@email.com", "password"}).ExecuteWith(ctx, db)
assert.NotEmpty(t, out.Item)
item = User{}
out.Result(&item)
assert.Equal(t, item.LoginCount, 1)
assert.NotNil(t, item.LoginDate)
assert.NotNil(t, item.RegDate)
assert.Equal(t, 1, len(item.Visits))
assert.Equal(t, "value", item.Preferences["test"])
assert.Equal(t, []float64{2}, item.Degrees)
assert.Subset(t, []string{"eu", "us"}, item.Locales)
assert.Subset(t, item.Locales, []string{"eu", "us"})
u = table.
UpdateItem(KeyValue{"name@email.com", "password"}).
SetConditionExpression(table.loginCount.Equals(0)).
SetUpdateExpression(table.loginCount.Increment(2))
failed := u.ExecuteWith(ctx, db).ConditionalCheckFailed()
out = table.GetItem(KeyValue{"name@email.com", "password"}).ExecuteWith(ctx, db)
assert.True(t, failed)
}
func TestRemoveAttribute(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.Nil(t, err)
q := table.PutItem(User{Email: "brendanr@email.com", Password: "password", LoginCount: 5})
err = q.ExecuteWith(ctx, db).Result(nil)
assert.Nil(t, err)
// remove
u := table.
UpdateItem(KeyValue{"brendanr@email.com", "password"}).
SetUpdateExpression(
table.registrationDate.SetField(time.Now().UnixNano(), true),
table.loginCount.RemoveField(),
)
err = u.ExecuteWith(ctx, db).Result(nil)
assert.Nil(t, err)
g := table.GetItem(KeyValue{"brendanr@email.com", "password"})
user := &User{}
err = g.ExecuteWith(ctx, db).Result(user)
assert.NoError(t, err)
assert.NotNil(t, user)
assert.Equal(t, 0, user.LoginCount)
}
func TestPutItem(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
item := User{Email: "joe@email.com", Password: "password"}
q := table.PutItem(item).SetConditionExpression(
And(
table.emailField.NotExists(),
table.passwordField.NotExists(),
),
)
err = q.ExecuteWith(ctx, db).Result(nil)
assert.NoError(t, err)
v := table.
UpdateItem(
KeyValue{"joe@email.com", "password"},
).
SetUpdateExpression(
table.loginCount.Increment(1),
table.registrationDate.SetField(time.Now().UnixNano(), false),
)
err = v.ExecuteWith(ctx, db).Result(nil)
assert.NoError(t, err)
g := table.GetItem(KeyValue{"joe@email.com", "password"})
out := g.ExecuteWith(ctx, db)
assert.NotEmpty(t, out.Item)
}
func TestTransactWriteItems(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
users := []User{}
items := make(map[string]User)
updates := make(map[interface{}]KeyValue)
deletes := make(map[interface{}]KeyValue)
conditions := make(map[interface{}]KeyValue)
q := table.TransactWriteItems().WithClientRequestToken("token")
for i := 0; i < 2; i++ {
ikey := fmt.Sprintf("joe@email%d.com", i)
items[ikey] = User{Email: ikey, Password: "password", LoginCount: 1}
users = append(users, items[ikey])
updates[ikey] = KeyValue{ikey, "password"}
dkey := fmt.Sprintf("test%d@email.com", i)
deletes[dkey] = KeyValue{dkey, "password"}
conditions[ikey] = KeyValue{ikey, "password"}
q = q.PutItem(items[ikey], table.registrationDate.Equals(123)).
UpdateItem(updates[ikey], table.emailField.SetField("nonname@email.com", false), table.emailField.Equals(ikey)).
DeleteItem(deletes[dkey], table.registrationDate.Equals(123)).
ConditionCheck(conditions[ikey], table.registrationDate.Equals(123))
}
var out *dynamodb.TransactWriteItemsInput
out, err = q.Build()
assert.NoError(t, err)
assert.Equal(t, 2*4, len(out.TransactItems))
assert.Equal(t, aws.String("token"), out.ClientRequestToken)
for _, it := range out.TransactItems {
if it.Put != nil {
v, _ := dynamodbattribute.MarshalMap(items[*it.Put.Item["email"].S])
assert.Equal(t, v, it.Put.Item)
assert.NotNil(t, it.Put.ConditionExpression)
} else if it.Delete != nil {
m := make(map[string]*dynamodb.AttributeValue)
appendKeyAttribute(&m, table.DynamoTable, deletes[*it.Delete.Key["email"].S])
assert.Equal(t, m, it.Delete.Key)
assert.NotNil(t, it.Delete.ConditionExpression)
} else if it.Update != nil {
m := make(map[string]*dynamodb.AttributeValue)
appendKeyAttribute(&m, table.DynamoTable, updates[*it.Update.Key["email"].S])
assert.Equal(t, m, it.Update.Key)
assert.NotNil(t, it.Update.UpdateExpression)
assert.NotNil(t, it.Update.ConditionExpression)
} else if it.ConditionCheck != nil {
m := make(map[string]*dynamodb.AttributeValue)
appendKeyAttribute(&m, table.DynamoTable, conditions[*it.ConditionCheck.Key["email"].S])
assert.Equal(t, m, it.ConditionCheck.Key)
assert.NotNil(t, it.ConditionCheck.ConditionExpression)
}
}
// Put
qb := table.TransactWriteItems()
for _, v := range items {
qb = qb.PutItem(v)
}
_, err = qb.ExecuteWith(ctx, db).Results()
assert.NoError(t, err)
var results []User
err = table.Scan().ExecuteWith(ctx, db).Results(func() interface{} {
results = append(results, User{})
return &results[len(results)-1]
})
assert.NoError(t, err)
assert.ElementsMatch(t, users, results)
// Update
q = table.TransactWriteItems()
for _, v := range updates {
q = q.UpdateItem(v, table.name.SetField("nonname", false), table.loginCount.Equals(1))
}
_, err = q.ExecuteWith(ctx, db).Results()
assert.NoError(t, err)
// Condition Check
q = table.TransactWriteItems()
for _, v := range conditions {
q = q.ConditionCheck(v, table.name.Equals("nonname"))
}
_, err = q.ExecuteWith(ctx, db).Results()
assert.NoError(t, err)
q = table.TransactWriteItems()
for _, v := range conditions {
q = q.ConditionCheck(v, table.name.Equals("nonname2"))
}
_, err = q.ExecuteWith(ctx, db).Results()
assert.Error(t, err)
// Delete
q = table.TransactWriteItems()
for _, v := range updates {
q = q.DeleteItem(v, table.loginCount.Equals(1))
}
_, err = q.ExecuteWith(ctx, db).Results()
assert.NoError(t, err)
results = nil
err = table.Scan().ExecuteWith(ctx, db).Results(func() interface{} {
results = append(results, User{})
return &results[len(results)-1]
})
assert.NoError(t, err)
assert.Equal(t, 0, len(results))
}
func TestExpressions(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
expr := Or(
table.registrationDate.Equals(123),
table.lastName.Contains("25"),
Not(table.registrationDate.Equals(345)),
And(
table.visits.Size(lte, 25),
table.name.Size(gte, 25),
),
table.registrationDate.Equals("test"),
table.registrationDate.LessThanOrEq("test"),
table.registrationDate.Between("0", "1"),
table.registrationDate.In("0", "1"),
)
p := table.passwordField.Equals("password")
q := table.
Query(
table.emailField.Equals("name@email.com"),
&p,
).
SetLimit(100).
SetScanForward(true).
SetFilterExpression(expr)
expectedFilter := "registrationDate = :filter_1 OR contains(lastName,:filter_2) OR (NOT registrationDate = :filter_3) OR (size(visits) <=:filter_4 AND size(firstName) >=:filter_5) OR registrationDate = :filter_6 OR registrationDate <= :filter_7 OR (registrationDate between :filter_8 and :filter_9) OR (registrationDate in (:filter_10,:filter_11))"
assert.Equal(t, expectedFilter, *q.Build().FilterExpression)
channel := make(chan *User)
errChan := q.ExecuteWith(ctx, db).StreamWithChannel(channel)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-channel:
case err = <-errChan:
return
}
}
}()
wg.Wait()
assert.NoError(t, err)
}
func TestDynamoQuery(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
me := &User{Email: "name@email.com", Password: "password"}
items := []interface{}{me}
for i := 0; i < 1000; i++ {
e := "name@email.com"
items = append(items, &User{Email: e, Password: "password" + strconv.Itoa(i)})
}
ui := []*User{}
w := table.BatchWriteItem().PutItems(items...)
f := func() interface{} {
u := User{}
ui = append(ui, &u)
return &u
}
err = w.ExecuteWith(ctx, db).Results(f)
assert.NoError(t, err)
assert.Empty(t, ui)
limit := 100
p := table.passwordField.BeginsWith("password")
q := table.
Query(
table.emailField.Equals("name@email.com"),
&p,
).
SetLimit(limit).
SetPageSize(10).
SetScanForward(true)
results := []*User{}
err = q.ExecuteWith(ctx, db).Results(func() interface{} {
r := &User{}
results = append(results, r)
return r
})
assert.NoError(t, err)
assert.Equal(t, limit, len(results))
var values []DynamoDBValue
for {
var v []DynamoDBValue
var lastKey DynamoDBValue
v, lastKey, err = q.ExecuteWith(ctx, db).ResultsList()
if len(v) <= 0 || lastKey == nil {
break
}
values = append(values, v...)
q = q.WithLastEvaluatedKey(lastKey)
assert.NoError(t, err)
}
assert.Equal(t, 1000, len(values))
}
func TestDynamoStreamQuery(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
me := &User{Email: "name@email.com", Password: "password"}
items := []interface{}{me}
for i := 0; i < 1000; i++ {
e := "name@email.com"
items = append(items, &User{Email: e, Password: "password" + strconv.Itoa(i)})
}
ui := []*User{}
w := table.BatchWriteItem().PutItems(items...)
f := func() interface{} {
u := User{}
ui = append(ui, &u)
return &u
}
err = w.ExecuteWith(ctx, db).Results(f)
assert.NoError(t, err)
assert.Empty(t, ui)
set := false
ff := func(c *dynamodb.ConsumedCapacity) {
set = true
}
limit := 10
p := table.passwordField.BeginsWith("password")
q := table.
Query(
table.emailField.Equals("name@email.com"),
&p,
).SetLimit(limit).WithConsumedCapacityHandler(ff).SetScanForward(true)
users := []User{}
channel := make(chan *User)
_ = q.ExecuteWith(ctx, db).StreamWithChannel(channel)
for u := range channel {
users = append(users, *u)
}
assert.True(t, set)
assert.NoError(t, err)
assert.Equal(t, limit, len(users))
}
func TestDynamoQueryError(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
me := &User{Email: "name@email.com", Password: "password"}
items := []interface{}{me}
for i := 0; i < 1000; i++ {
e := "name@email.com"
items = append(items, &User{Email: e, Password: "password" + strconv.Itoa(i)})
}
_ = table.BatchWriteItem().PutItems(items...).ExecuteWith(ctx, db).Results(nil)
channel := make(chan *User)
errChan := table.
Query(
table.registrationDate.Equals("name@email.com"),
nil,
).
SetScanForward(true).
ExecuteWith(ctx, db).
StreamWithChannel(channel)
users := []interface{}{}
SELECT:
for {
select {
case u := <-channel:
if u != nil {
users = append(users, u)
} else {
break SELECT
}
case err = <-errChan:
break SELECT
}
}
assert.NotNil(t, err)
}
func TestDynamoScan(t *testing.T) {
table := NewUserTable()
db := NewDB()
ctx := context.Background()
err := table.CreateTable().ExecuteWith(ctx, db)
defer table.DeleteTable().ExecuteWith(ctx, db)
assert.NoError(t, err)
me := &User{Email: "name@email.com", Password: "password"}
items := []interface{}{me}
for i := 0; i < 1000; i++ {
e := "name@email.com"
items = append(items, &User{Email: e, Password: "password" + strconv.Itoa(i)})
}
ui := []*User{}
w := table.BatchWriteItem().PutItems(items...)
f := func() interface{} {
u := User{}
ui = append(ui, &u)
return &u
}
err = w.ExecuteWith(ctx, db).Results(f)
assert.NoError(t, err)
assert.Empty(t, ui)
limit := 1000
users := []interface{}{}
channel := make(chan *User)
q := table.Scan().SetLimit(limit)
errChan := q.ExecuteWith(ctx, db).StreamWithChannel(channel)
SELECT:
for {
select {
case u := <-channel:
if u != nil {
users = append(users, u)
} else {
break SELECT
}
case err = <-errChan:
break SELECT
}
}
assert.NoError(t, err)
assert.Equal(t, limit, len(users))
var values []DynamoDBValue
for {
var v []DynamoDBValue
var lastKey DynamoDBValue
v, lastKey, err = q.ExecuteWith(ctx, db).ResultsList()
if len(v) <= 0 || lastKey == nil {
break
}
values = append(values, v...)
q = q.WithLastEvaluatedKey(lastKey)
assert.NoError(t, err)
assert.Equal(t, limit, len(v))
}
values = append(values, values...)
assert.True(t, len(values) >= limit)
}
| mit |
mrkosterix/lua-commons | lua-commons-configuration/lua-commons-configuration-modules/lua-commons-configuration-basic/src/test/java/org/lua/commons/configuration/basic/TestBasicConfigurationApi.java | 1521 | package org.lua.commons.configuration.basic;
import java.io.File;
import org.lua.commons.configuration.FileLuaConfiguration;
import org.lua.commons.configuration.LuaConfiguration;
import org.lua.commons.configuration.LuaConfigurationException;
import org.lua.commons.customapi.container.LuaContainer;
import org.lua.commons.impl.nativelua.NativeLuaStateApiFactory;
import org.lua.commons.nativeapi.LuaStateApiProvider;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class TestBasicConfigurationApi {
LuaContainer container;
LuaConfiguration configuration;
@BeforeMethod
public void initLua() {
LuaStateApiProvider.setFactory(new NativeLuaStateApiFactory());
container = new LuaContainer();
container.addLib(null, new BasicConfigurationApi(), null, null);
configuration = new FileLuaConfiguration(container, new File(
"src/test/resources/test.conf"));
}
@AfterMethod
public void closeLua() {
configuration.close();
}
@Test(expectedExceptions = LuaConfigurationException.class)
public void testErrorFunction() {
configuration.getString("test_error");
}
@Test
public void testBasicFunctions() {
Assert.assertEquals(configuration.getString("test_next"), "key");
Assert.assertEquals(configuration.getInt("test_tonumber"), 92);
Assert.assertEquals(configuration.getString("test_tostring"), "124.5");
Assert.assertEquals(configuration.getString("test_type"), "string");
}
}
| mit |
greenren/local-coffee-roasters | resources/views/roasters/index.blade.php | 621 | @extends('layouts.master')
@section('header')
<h1>Local Coffee Roasters</h1>
@stop
@section('content')
@if (count($roasters))
<ul class="list-unstyled">
@foreach($roasters as $roaster)
<li>
<h2>
<a href="{{ url('roaster', $roaster->slug) }}">{{ $roaster->name }}</a>
</h2>
<p>{{ $roaster->city }}, {{ $roaster->state }}, {{ $roaster->country }}</p>
</li>
@endforeach
</ul>
@else
<p>Could not find any local coffee roasters.</p>
@endif
@stop
| mit |
bitrise-tools/codesigndoc | cmd/root.go | 1260 | package cmd
import (
"fmt"
"os"
"github.com/bitrise-io/go-utils/log"
"github.com/spf13/cobra"
)
var (
enableVerboseLog = false
)
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "codesigndoc",
Short: "Your friendly iOS Code Signing Doctor",
Long: `Your friendly iOS Code Signing Doctor
Using this tool is as easy as running "codesigndoc scan xcode/xamarin" and following the guide it prints.
At the end of the process you'll have all the code signing files
(.p12 Identity file including the Certificate and Private Key,
and the required Provisioning Profiles) required to do a successful Archive of your iOS project.`,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
log.SetEnableDebugLog(enableVerboseLog)
log.Debugf("EnableDebugLog: %v", enableVerboseLog)
return nil
},
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
RootCmd.PersistentFlags().BoolVarP(&enableVerboseLog, "verbose", "v", false, "Enable verbose logging")
}
| mit |
epignosisx/scsyncr | src/ScSyncr.Agent/ScSyncrRoute.cs | 396 | using System.Web.Routing;
namespace ScSyncr.Agent
{
public class ScSyncrRoute : Route
{
private static readonly ScSyncrRoute singleton = new ScSyncrRoute();
public static ScSyncrRoute Singleton
{
get { return singleton; }
}
private ScSyncrRoute() : base("scsyncr/{command}", new ScSyncrRouteHandler())
{
}
}
}
| mit |
xuorig/graphql-schema_comparator | lib/graphql/schema_comparator/diff/schema.rb | 4429 | module GraphQL
module SchemaComparator
module Diff
class Schema
def initialize(old_schema, new_schema)
@old_schema = old_schema
@new_schema = new_schema
@old_types = old_schema.types
@new_types = new_schema.types
@old_directives = old_schema.directives
@new_directives = new_schema.directives
end
def diff
changes = []
# Removed and Added Types
changes += removed_types.map { |type| Changes::TypeRemoved.new(type) }
changes += added_types.map { |type| Changes::TypeAdded.new(type) }
# Type Diff for common types
each_common_type do |old_type, new_type|
changes += changes_in_type(old_type, new_type)
end
# Diff Schemas
changes += changes_in_schema
# Diff Directives
changes += changes_in_directives
changes
end
def changes_in_type(old_type, new_type)
changes = []
if old_type.kind != new_type.kind
changes << Changes::TypeKindChanged.new(old_type, new_type)
else
case old_type.kind.name
when "ENUM"
changes += Diff::Enum.new(old_type, new_type).diff
when "UNION"
changes += Diff::Union.new(old_type, new_type).diff
when "INPUT_OBJECT"
changes += Diff::InputObject.new(old_type, new_type).diff
when "OBJECT"
changes += Diff::ObjectType.new(old_type, new_type).diff
when "INTERFACE"
changes += Diff::Interface.new(old_type, new_type).diff
end
end
if old_type.description != new_type.description
changes << Changes::TypeDescriptionChanged.new(old_type, new_type)
end
changes
end
def changes_in_schema
changes = []
if old_schema.query&.graphql_name != new_schema.query&.graphql_name
changes << Changes::SchemaQueryTypeChanged.new(old_schema, new_schema)
end
if old_schema.mutation&.graphql_name != new_schema.mutation&.graphql_name
changes << Changes::SchemaMutationTypeChanged.new(old_schema, new_schema)
end
if old_schema.subscription&.graphql_name != new_schema.subscription&.graphql_name
changes << Changes::SchemaSubscriptionTypeChanged.new(old_schema, new_schema)
end
changes
end
def changes_in_directives
changes = []
changes += removed_directives.map { |directive| Changes::DirectiveRemoved.new(directive) }
changes += added_directives.map { |directive| Changes::DirectiveAdded.new(directive) }
each_common_directive do |old_directive, new_directive|
changes += Diff::Directive.new(old_directive, new_directive).diff
end
changes
end
private
def each_common_type(&block)
intersection = old_types.keys & new_types.keys
intersection.each do |common_type_name|
old_type = old_schema.types[common_type_name]
new_type = new_schema.types[common_type_name]
block.call(old_type, new_type)
end
end
def removed_types
(old_types.keys - new_types.keys).map { |type_name| old_schema.types[type_name] }
end
def added_types
(new_types.keys - old_types.keys).map { |type_name| new_schema.types[type_name] }
end
def removed_directives
(old_directives.keys - new_directives.keys).map { |directive_name| old_schema.directives[directive_name] }
end
def added_directives
(new_directives.keys - old_directives.keys).map { |directive_name| new_schema.directives[directive_name] }
end
def each_common_directive(&block)
intersection = old_directives.keys & new_directives.keys
intersection.each do |common_directive_name|
old_directive = old_schema.directives[common_directive_name]
new_directive = new_schema.directives[common_directive_name]
block.call(old_directive, new_directive)
end
end
attr_reader :old_schema, :new_schema, :old_types, :new_types, :old_directives, :new_directives
end
end
end
end
| mit |
garno/FiveSystem | lib/five_system/linux.rb | 105 | module FiveSystem
module Linux
autoload :LoadAverage, 'fivesystem/linux/load_average'
end
end
| mit |
SETTER2000/kadr | assets/js/private/admin/AdminModule.js | 4423 | angular.module('AdminModule', ['ui.router', 'ngResource', 'ngAnimate','ngMaterial'])
.config(function ($stateProvider) {
$stateProvider
.state('home.admin', {
url: 'admin',
// templateUrl: '/js/private/admin/tpl/admin.tpl.html'
//controller: function () {
//
//}
views: {
'@': {
templateUrl: '/js/private/admin/tpl/admin.tpl.html',
controller: 'AdminController'
},
/**
* Абсолютное позиционирование вида 'sidebar' в состоянии home.admin.
* <div ui-view='sidebar'/> внутри /js/private/admin/tpl/admin.tpl.html
* "sidebar@home.admin": { какой-то код }
* То есть, при выборе определенного состояния (ищи строку типа .state('home.admin', и т.д...),
* мы в templateUrl этого состояния, вставляем небольшой кусочек разметки <div ui-view='sidebar'/>
* с указанием вида, в данном случаи sidebar, который будет выводится вместо этой разметки.
* А вид (views), который будет выведен вместо именованой разметки <div ui-view='sidebar'/>,
* может быть определен в любом модуле, который связан в системе.
* В данном примере сайдбар будет выведен только, конкретно на странице /admin, но если
* убрать имя состояния (hime.admin), то вид будет показан в корневом безымянном состоянии и
* будет уже виден в каждом состоянии которое имеет разметку <div ui-view='sidebar'/>
* А так как корневой шаблон views/page/showhomepage.ejs содержит несколько тегов разметки:
* <div ui-view></div>
* <div ui-view="sidebar"></div>
* <div ui-view="body"></div>
* то сайдбар при не определённом состоянии для вывода, будет виден на всех страницах, которые
* заменяют разметку <div ui-view></div>, так как он вставляется рядом
* в разметке <div ui-view="sidebar"></div>
* <div ui-view></div> - это тег отображающий вид, причём любой вид, читай безымянный
* <div ui-view="sidebar"></div> - этот тег отображает именованный вид, имя вида sidebar
*/
//'sidebar@home.admin': {
// templateUrl: '/js/private/tpl/sidebar.tpl.html'
//}
}
})
;
})
// .constant('CONF_MODULE', {baseUrl: '/user/:userId'})
// .factory('Users', function ($resource, CONF_MODULE) {
// var Users = $resource(
// CONF_MODULE.baseUrl,
// {userId: '@id'},
// // Определяем собственный метод update на обоих уровнях, класса и экземпляра
// {
// update: {
// method: 'PUT'
// }
// }
// );
//
// Users.prototype.getFullName = function () {
// return this.lastName + ' ' + this.firstName + ' ' + this.patronymicName;
// };
//
// Users.prototype.ok = function () {
// return alert('Сотрудник: ' + this.getFullName() + ' изменён!');
// };
// Users.prototype.lastDateSetting = function () {
// return new Date();
// };
//
// return Users;
// })
; | mit |
spthaolt/jemul8 | demos/floppy/demo.js | 1499 | /**
* jemul8 - JavaScript x86 Emulator
* http://jemul8.com/
*
* Copyright 2013 jemul8.com (http://github.com/asmblah/jemul8)
* Released under the MIT license
* http://jemul8.com/MIT-LICENSE.txt
*/
/*global define */
define({
cache: false
}, [
"../../jemul8"
], function (
jemul8
) {
"use strict";
var environment = jemul8.getEnvironment(),
driveType = environment.getOption("driveType"),
diskType = environment.getOption("diskType"),
emulator,
path = environment.getOption("flp");
if (!driveType) {
throw new Error("Argument 'driveType' is missing");
}
if (!diskType) {
throw new Error("Argument 'diskType' is missing");
}
if (!path) {
throw new Error("Argument 'flp' is missing");
}
emulator = jemul8.createEmulator({
"cmos": {
"bios": "docs/bochs-20100605/bios/BIOS-bochs-legacy"
},
"vga": {
"bios": "docs/bochs-20100605/bios/VGABIOS-lgpl-latest"
},
"floppy": [{
"driveType": driveType,
"diskType": diskType,
"path": "../../boot/" + path,
"loaded": true
}],
"ne2k": {
"ioAddress": 0x300,
"irq": 3
}
});
emulator.loadPlugin("canvas.vga.renderer");
emulator.loadPlugin("keyboard.input");
emulator.loadPlugin("network.loopback");
emulator.init().done(function () {
emulator.run();
});
});
| mit |
danielgerlag/jworkflow | jworkflow.kernel/src/main/java/net/jworkflow/kernel/interfaces/ExecutionResultProcessor.java | 445 | package net.jworkflow.kernel.interfaces;
import net.jworkflow.kernel.models.*;
public interface ExecutionResultProcessor {
void processExecutionResult(WorkflowInstance workflow, WorkflowDefinition def, ExecutionPointer pointer, WorkflowStep step, ExecutionResult result, WorkflowExecutorResult workflowResult);
void handleStepException(WorkflowInstance workflow, WorkflowDefinition def, ExecutionPointer pointer, WorkflowStep step);
}
| mit |
DFearing/ContactPusher | ContactPusher.Web.UI/Controllers/HomeController.cs | 395 | using ContactPusher.Core;
using System.Web.Mvc;
namespace ContactPusher.Web.UI.Controllers
{
public class HomeController : BaseController
{
public HomeController(IRepository repository, IGoogleServices googleServices) : base(repository, googleServices)
{
}
public ActionResult Index()
{
return View();
}
public ActionResult Rejected()
{
return View();
}
}
} | mit |
cosmow/riak-odm | lib/CosmoW/ODM/Riak/Mapping/Annotations/EmbeddedDocument.php | 1145 | <?php
/*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace CosmoW\ODM\Riak\Mapping\Annotations;
/** @Annotation */
final class EmbeddedDocument extends AbstractDocument
{
public $indexes = array();
}
| mit |
IssueSquare/blog-daddy | app/vendor/github.com/minio/minio-go/api-put-object.go | 8103 | /*
* Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015, 2016 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package minio
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"runtime/debug"
"sort"
"strings"
"github.com/minio/minio-go/pkg/encrypt"
"github.com/minio/minio-go/pkg/s3utils"
)
// PutObjectOptions represents options specified by user for PutObject call
type PutObjectOptions struct {
UserMetadata map[string]string
Progress io.Reader
ContentType string
ContentEncoding string
ContentDisposition string
CacheControl string
EncryptMaterials encrypt.Materials
NumThreads uint
}
// getNumThreads - gets the number of threads to be used in the multipart
// put object operation
func (opts PutObjectOptions) getNumThreads() (numThreads int) {
if opts.NumThreads > 0 {
numThreads = int(opts.NumThreads)
} else {
numThreads = totalWorkers
}
return
}
// Header - constructs the headers from metadata entered by user in
// PutObjectOptions struct
func (opts PutObjectOptions) Header() (header http.Header) {
header = make(http.Header)
if opts.ContentType != "" {
header["Content-Type"] = []string{opts.ContentType}
} else {
header["Content-Type"] = []string{"application/octet-stream"}
}
if opts.ContentEncoding != "" {
header["Content-Encoding"] = []string{opts.ContentEncoding}
}
if opts.ContentDisposition != "" {
header["Content-Disposition"] = []string{opts.ContentDisposition}
}
if opts.CacheControl != "" {
header["Cache-Control"] = []string{opts.CacheControl}
}
if opts.EncryptMaterials != nil {
header[amzHeaderIV] = []string{opts.EncryptMaterials.GetIV()}
header[amzHeaderKey] = []string{opts.EncryptMaterials.GetKey()}
header[amzHeaderMatDesc] = []string{opts.EncryptMaterials.GetDesc()}
}
for k, v := range opts.UserMetadata {
if !strings.HasPrefix(strings.ToLower(k), "x-amz-meta-") && !isStandardHeader(k) {
header["X-Amz-Meta-"+k] = []string{v}
} else {
header[k] = []string{v}
}
}
return
}
// validate() checks if the UserMetadata map has standard headers or client side
// encryption headers and raises an error if so.
func (opts PutObjectOptions) validate() (err error) {
for k := range opts.UserMetadata {
if isStandardHeader(k) || isCSEHeader(k) {
return ErrInvalidArgument(k + " unsupported request parameter for user defined metadata")
}
}
return nil
}
// completedParts is a collection of parts sortable by their part numbers.
// used for sorting the uploaded parts before completing the multipart request.
type completedParts []CompletePart
func (a completedParts) Len() int { return len(a) }
func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber }
// PutObject creates an object in a bucket.
//
// You must have WRITE permissions on a bucket to create an object.
//
// - For size smaller than 64MiB PutObject automatically does a
// single atomic Put operation.
// - For size larger than 64MiB PutObject automatically does a
// multipart Put operation.
// - For size input as -1 PutObject does a multipart Put operation
// until input stream reaches EOF. Maximum object size that can
// be uploaded through this operation will be 5TiB.
func (c Client) PutObject(bucketName, objectName string, reader io.Reader, objectSize int64,
opts PutObjectOptions) (n int64, err error) {
return c.PutObjectWithContext(context.Background(), bucketName, objectName, reader, objectSize, opts)
}
func (c Client) putObjectCommon(ctx context.Context, bucketName, objectName string, reader io.Reader, size int64, opts PutObjectOptions) (n int64, err error) {
// Check for largest object size allowed.
if size > int64(maxMultipartPutObjectSize) {
return 0, ErrEntityTooLarge(size, maxMultipartPutObjectSize, bucketName, objectName)
}
// NOTE: Streaming signature is not supported by GCS.
if s3utils.IsGoogleEndpoint(c.endpointURL) {
// Do not compute MD5 for Google Cloud Storage.
return c.putObjectNoChecksum(ctx, bucketName, objectName, reader, size, opts)
}
if c.overrideSignerType.IsV2() {
if size >= 0 && size < minPartSize {
return c.putObjectNoChecksum(ctx, bucketName, objectName, reader, size, opts)
}
return c.putObjectMultipart(ctx, bucketName, objectName, reader, size, opts)
}
if size < 0 {
return c.putObjectMultipartStreamNoLength(ctx, bucketName, objectName, reader, opts)
}
if size < minPartSize {
return c.putObjectNoChecksum(ctx, bucketName, objectName, reader, size, opts)
}
// For all sizes greater than 64MiB do multipart.
return c.putObjectMultipartStream(ctx, bucketName, objectName, reader, size, opts)
}
func (c Client) putObjectMultipartStreamNoLength(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (n int64, err error) {
// Input validation.
if err = s3utils.CheckValidBucketName(bucketName); err != nil {
return 0, err
}
if err = s3utils.CheckValidObjectName(objectName); err != nil {
return 0, err
}
// Total data read and written to server. should be equal to
// 'size' at the end of the call.
var totalUploadedSize int64
// Complete multipart upload.
var complMultipartUpload completeMultipartUpload
// Calculate the optimal parts info for a given size.
totalPartsCount, partSize, _, err := optimalPartInfo(-1)
if err != nil {
return 0, err
}
// Initiate a new multipart upload.
uploadID, err := c.newUploadID(ctx, bucketName, objectName, opts)
if err != nil {
return 0, err
}
defer func() {
if err != nil {
c.abortMultipartUpload(ctx, bucketName, objectName, uploadID)
}
}()
// Part number always starts with '1'.
partNumber := 1
// Initialize parts uploaded map.
partsInfo := make(map[int]ObjectPart)
// Create a buffer.
buf := make([]byte, partSize)
defer debug.FreeOSMemory()
for partNumber <= totalPartsCount {
length, rErr := io.ReadFull(reader, buf)
if rErr == io.EOF && partNumber > 1 {
break
}
if rErr != nil && rErr != io.ErrUnexpectedEOF {
return 0, rErr
}
// Update progress reader appropriately to the latest offset
// as we read from the source.
rd := newHook(bytes.NewReader(buf[:length]), opts.Progress)
// Proceed to upload the part.
var objPart ObjectPart
objPart, err = c.uploadPart(ctx, bucketName, objectName, uploadID, rd, partNumber,
nil, nil, int64(length), opts.UserMetadata)
if err != nil {
return totalUploadedSize, err
}
// Save successfully uploaded part metadata.
partsInfo[partNumber] = objPart
// Save successfully uploaded size.
totalUploadedSize += int64(length)
// Increment part number.
partNumber++
// For unknown size, Read EOF we break away.
// We do not have to upload till totalPartsCount.
if rErr == io.EOF {
break
}
}
// Loop over total uploaded parts to save them in
// Parts array before completing the multipart request.
for i := 1; i < partNumber; i++ {
part, ok := partsInfo[i]
if !ok {
return 0, ErrInvalidArgument(fmt.Sprintf("Missing part number %d", i))
}
complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{
ETag: part.ETag,
PartNumber: part.PartNumber,
})
}
// Sort all completed parts.
sort.Sort(completedParts(complMultipartUpload.Parts))
if _, err = c.completeMultipartUpload(ctx, bucketName, objectName, uploadID, complMultipartUpload); err != nil {
return totalUploadedSize, err
}
// Return final size.
return totalUploadedSize, nil
}
| mit |
karou/karou-yuanze | src/Albatross/DailyBundle/AlbatrossDailyBundle.php | 136 | <?php
namespace Albatross\DailyBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class AlbatrossDailyBundle extends Bundle
{
}
| mit |
peercoin/peercoin | src/qt/locale/bitcoin_vi.ts | 140555 | <TS language="vi" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Phải chuột để sửa địa chỉ hoặc nhãn</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Tạo một địa chỉ mới</translation>
</message>
<message>
<source>&New</source>
<translation>&Mới</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Sao chép các địa chỉ đã được chọn vào bộ nhớ tạm thời của hệ thống</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Sao chép</translation>
</message>
<message>
<source>C&lose</source>
<translation>Đ&óng lại</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Xóa địa chỉ đang chọn từ danh sách</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Enter address or label to search</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Xuất dữ liệu trong thẻ hiện tại ra file</translation>
</message>
<message>
<source>&Export</source>
<translation>&Xuất</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Xóa</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Chọn địa chỉ để gửi coins đến</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Chọn địa chỉ để nhận coins với</translation>
</message>
<message>
<source>C&hoose</source>
<translation>C&họn</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Địa chỉ đang gửi</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Địa chỉ đang nhận</translation>
</message>
<message>
<source>These are your Peercoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Đây là những địa chỉ đang thực hiện thanh toán. Luôn kiểm tra số lượng và địa chỉ nhận trước khi gửi coins.</translation>
</message>
<message>
<source>These are your Peercoin addresses for receiving payments. Use the 'Create new receiving address' button in the receive tab to create new addresses.</source>
<translation>Những địa chỉ Peercoin này để bạn nhận thanh toán. Sử dụng 'Tạo địa chỉ nhận mới'</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Copy Địa Chỉ</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Copy &Nhãn</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Edit</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Xuất List Địa Chỉ</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Xuất Thất Bại</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Có lỗi khi đang save list địa chỉ đến %1. Vui lòng thử lại.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Nhãn</translation>
</message>
<message>
<source>Address</source>
<translation>Địa chỉ</translation>
</message>
<message>
<source>(no label)</source>
<translation>(không nhãn)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Log Cụm Mật Khẩu</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Nhập cụm mật khẩu</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Cụm mật khẩu mới</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Lặp lại cụm mật khẩu mới</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Ví mã hóa</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Quá trình này cần cụm mật khẩu của bạn để mở khóa ví.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Mở khóa ví</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Quá trình này cần cụm mật khẩu của bạn để giải mã ví.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Giải mã ví</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Đổi cụm mật khẩu</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Xác nhận mã hóa ví</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>Cảnh báo: Nếu bạn mã hóa ví và mất cụm mật khẩu, bạn sẽ <b>MẤT TẤT CẢ BITCOIN</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Bạn có chắc bạn muốn mã hóa ví của mình?</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Ví đã được mã hóa</translation>
</message>
<message>
<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>QUAN TRỌNG: Bất cứ backup nào bạn từng làm trước đây từ ví của bạn nên được thay thế tạo mới, file mã hóa ví. Vì lý do bảo mật, các backup trước đây của các ví chưa mã hóa sẽ bị vô tác dụng ngay khi bạn bắt đầu sử dụng mới, ví đã được mã hóa.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>Quá trình mã hóa ví thất bại</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Quá trình mã hóa ví thất bại do một lỗi nội tại. Ví của bạn vẫn chưa được mã hóa.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Cụm mật khẩu được cung cấp không đúng.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Mở khóa ví thất bại</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cụm mật khẩu đã nhập để giải mã ví không đúng.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Giải mã ví thất bại</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Cụm mật khẩu thay đổi thành công.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Cảnh báo: chữ Viết Hoa đang bật!</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP/Netmask</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Cấm Đến</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Chữ ký &lời nhắn...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Đồng bộ hóa với network...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Tổng quan</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Hiển thị tổng quan ví</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Các Giao Dịch</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Trình duyệt lịch sử giao dịch</translation>
</message>
<message>
<source>E&xit</source>
<translation>T&hoát</translation>
</message>
<message>
<source>Quit application</source>
<translation>Đóng ứng dụng</translation>
</message>
<message>
<source>&About %1</source>
<translation>&Khoảng %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Hiện thông tin khoảng %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Về &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Hiện thông tin về Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Tùy chọn...</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>Sửa đổi tùy chỉnh cấu hình cho %1</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Mã Hóa Ví...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Backup Ví...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Thay Đổi Cụm Mật Khẩu...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Mở &URI...</translation>
</message>
<message>
<source>Wallet:</source>
<translation>Ví tiền</translation>
</message>
<message>
<source>Click to disable network activity.</source>
<translation>Click để vô hiệu hoạt động mạng.</translation>
</message>
<message>
<source>Network activity disabled.</source>
<translation>Hoạt động mạng được vô hiệu.</translation>
</message>
<message>
<source>Click to enable network activity again.</source>
<translation>Click để mở hoạt động mạng trở lại.</translation>
</message>
<message>
<source>Syncing Headers (%1%)...</source>
<translation>Đồng bộ hóa tiêu đề (%1%)...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Khôi phục các khối trên ổ đĩa...</translation>
</message>
<message>
<source>Proxy is <b>enabled</b>: %1</source>
<translation>Proxy là <b> cho phép </b>: %1</translation>
</message>
<message>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Backup ví đến một địa chỉ khác</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Thay đổi cụm mật khẩu cho ví đã mã hóa</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Lời nhắn xác nhận...</translation>
</message>
<message>
<source>&Send</source>
<translation>&Gửi</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Nhận</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Hiển thị / Ẩn</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Hiện hoặc ẩn cửa sổ chính</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Mã hóa private key thuộc về ví của bạn</translation>
</message>
<message>
<source>Sign messages with your Peercoin addresses to prove you own them</source>
<translation>Đăng ký lời nhắn với địa chỉ Peercoin của bạn để chứng minh quyền sở hữu chúng</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Peercoin addresses</source>
<translation>Xác minh lời nhắn để chắc chắn đã được đăng ký với địa chỉ Peercoin xác định</translation>
</message>
<message>
<source>&File</source>
<translation>&File</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Settings</translation>
</message>
<message>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Các thanh công cụ</translation>
</message>
<message>
<source>Request payments (generates QR codes and peercoin: URIs)</source>
<translation>Yêu cầu thanh toán (tạo QR code và peercoin: URIs)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Hiển thị danh sách các địa chỉ và nhãn đã dùng để gửi</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Hiển thị danh sách các địa chỉ và nhãn đã dùng để nhận</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>&Tùy chỉnh Command-line</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Peercoin network</source>
<translation><numerusform>%n kết nối đến Peercoin network</numerusform></translation>
</message>
<message>
<source>Indexing blocks on disk...</source>
<translation>Khối đang được ghi nhận trên đĩa...</translation>
</message>
<message>
<source>Processing blocks on disk...</source>
<translation>Khối đang được xử lý trên đĩa...</translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>Hoàn thành %n khối của lịch sử giao dịch.</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 phia sau</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Khối nhận cuối cùng đã được tạo %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Các giao dịch sau giao dịch này sẽ không được hiển thị.</translation>
</message>
<message>
<source>Error</source>
<translation>Lỗi</translation>
</message>
<message>
<source>Warning</source>
<translation>Cảnh báo</translation>
</message>
<message>
<source>Information</source>
<translation>Thông tin</translation>
</message>
<message>
<source>Up to date</source>
<translation>Đã cập nhật</translation>
</message>
<message>
<source>&Sending addresses</source>
<translation>&Các địa chỉ đang gửi</translation>
</message>
<message>
<source>&Receiving addresses</source>
<translation>&Các địa chỉ đang nhận</translation>
</message>
<message>
<source>Open Wallet</source>
<translation>Mớ ví</translation>
</message>
<message>
<source>Open a wallet</source>
<translation>Mở một ví</translation>
</message>
<message>
<source>Close Wallet...</source>
<translation>Đóng ví...</translation>
</message>
<message>
<source>Close wallet</source>
<translation>Đông ví</translation>
</message>
<message>
</message>
<message>
<source>default wallet</source>
<translation>ví mặc định</translation>
</message>
<message>
<source>No wallets available</source>
<translation>Không có ví nào</translation>
</message>
<message>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<source>Minimize</source>
<translation>Thu nhỏ</translation>
</message>
<message>
<source>Zoom</source>
<translation>Phóng</translation>
</message>
<message>
<source>Main Window</source>
<translation>Màn hình chính</translation>
</message>
<message>
<source>%1 client</source>
<translation>%1 khách</translation>
</message>
<message>
<source>Connecting to peers...</source>
<translation>Đang kết nối đến peers...</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Đang bắt kịp...</translation>
</message>
<message>
<source>Error: %1</source>
<translation>Error: %1</translation>
</message>
<message>
<source>Warning: %1</source>
<translation>Cảnh báo: %1</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Ngày %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Số lượng: %1
</translation>
</message>
<message>
<source>Wallet: %1
</source>
<translation>Ví: %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Loại: %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Nhãn: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Địa chỉ: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Giao dịch đã gửi</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Giao dịch đang nhận</translation>
</message>
<message>
<source>HD key generation is <b>enabled</b></source>
<translation>Khởi tạo HD key <b>enabled</b></translation>
</message>
<message>
<source>HD key generation is <b>disabled</b></source>
<translation>Khởi tạo HD key <b>disabled</b></translation>
</message>
<message>
<source>Private key <b>disabled</b></source>
<translation>Khóa riên tư <b>đã tắt</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Ví thì <b>encrypted</b> và hiện tại <b>unlocked</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Ví thì <b>encrypted</b> và hiện tại <b>locked</b></translation>
</message>
<message>
<source>A fatal error occurred. Peercoin can no longer continue safely and will quit.</source>
<translation>Một lỗi nghiêm trọng vừa xảy ra. Peercoin có thể không còn tiếp tục an toàn và sẽ bị bỏ.</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Lựa chọn Coin</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Số lượng:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Số lượng:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Phí:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Rác:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Sau Phí:</translation>
</message>
<message>
<source>Change:</source>
<translation>Thay đổi:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(không)chọn tất cả</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Tree mode</translation>
</message>
<message>
<source>List mode</source>
<translation>List mode</translation>
</message>
<message>
<source>Amount</source>
<translation>Số lượng</translation>
</message>
<message>
<source>Received with label</source>
<translation>Đã nhận với nhãn</translation>
</message>
<message>
<source>Received with address</source>
<translation>Đã nhận với địa chỉ</translation>
</message>
<message>
<source>Date</source>
<translation>Ngày</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Xác nhận</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Đã xác nhận</translation>
</message>
<message>
<source>Copy address</source>
<translation>Sao chép địa chỉ</translation>
</message>
<message>
<source>Copy label</source>
<translation>Sao chép nhãn</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Sao chép số lượng</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Sao chép ID giao dịch</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Khóa unspent</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Mở khóa unspent</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Sao chép số lượng</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Sao chép phí</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Sao chép sau phí</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Sao chép bytes</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Sao chép rác</translation>
</message>
<message>
<source>Copy change</source>
<translation>Sao chép thay đổi</translation>
</message>
<message>
<source>(%1 locked)</source>
<translation>(%1 đã khóa)</translation>
</message>
<message>
<source>yes</source>
<translation>có</translation>
</message>
<message>
<source>no</source>
<translation>không</translation>
</message>
<message>
<source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source>
<translation>Label này chuyển sang đỏ nếu bất cứ giao dịch nhận nào có số lượng nhỏ hơn ngưỡng dust.</translation>
</message>
<message>
<source>Can vary +/- %1 satoshi(s) per input.</source>
<translation>Có thể thay đổi +/-%1 satoshi(s) trên input.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(không nhãn)</translation>
</message>
<message>
<source>change from %1 (%2)</source>
<translation>change từ %1 (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(change)</translation>
</message>
</context>
<context>
<name>CreateWalletActivity</name>
</context>
<context>
<name>CreateWalletDialog</name>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Edit Address</translation>
</message>
<message>
<source>&Label</source>
<translation>Nhãn dữ liệu</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>Label liên kết với list address ban đầu này</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>Label liên kết với list address ban đầu này. Điều này chỉ được điều chỉnh cho địa chỉ gửi.</translation>
</message>
<message>
<source>&Address</source>
<translation>Địa chỉ</translation>
</message>
<message>
<source>New sending address</source>
<translation>Address đang gửi mới</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Edit address đang nhận</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Edit address đang gửi</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Peercoin address.</source>
<translation>Address đã nhập "%1" không valid Peercoin address.</translation>
</message>
<message>
<source>Address "%1" already exists as a receiving address with label "%2" and so cannot be added as a sending address.</source>
<translation>Địa chỉ "%1" đã tồn tại như địa chỉ nhận với nhãn "%2" và vì vậy không thể thêm như là địa chỉ gửi.</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book with label "%2".</source>
<translation>Địa chỉ nhập "%1" đã có trong sổ địa chỉ với nhãn "%2".</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Không thể unlock wallet.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Khởi tạo key mới thất bại.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Một danh mục dữ liệu mới sẽ được tạo.</translation>
</message>
<message>
<source>name</source>
<translation>tên</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>Danh mục đã tồn tại. Thêm %1 nếu bạn dự định creat một danh mục mới ở đây.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Path đã tồn tại, và không là danh mục.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Không thể create dữ liệu danh mục tại đây.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>phiên bản</translation>
</message>
<message>
<source>About %1</source>
<translation>About %1</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Command-line options</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Welcome</translation>
</message>
<message>
<source>Welcome to %1.</source>
<translation>Welcome to %1.</translation>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where %1 will store its data.</source>
<translation>Đây là lần đầu chương trình khởi chạy, bạn có thể chọn nơi %1 sẽ lưu trữ data.</translation>
</message>
<message>
<source>When you click OK, %1 will begin to download and process the full %4 block chain (%2GB) starting with the earliest transactions in %3 when %4 initially launched.</source>
<translation>Khi bạn click OK, %1 sẽ bắt đầu download và process the full %4 block chain (%2GB) starting with the earliest transactions in %3 when %4 initially launched.</translation>
</message>
<message>
<source>This initial synchronisation is very demanding, and may expose hardware problems with your computer that had previously gone unnoticed. Each time you run %1, it will continue downloading where it left off.</source>
<translation>Đồng bộ hóa ban đầu này rất đòi hỏi, và có thể phơi bày các sự cố về phần cứng với máy tính của bạn trước đó đã không được chú ý. Mỗi khi bạn chạy %1, nó sẽ tiếp tục tải về nơi nó dừng lại.</translation>
</message>
<message>
<source>If you have chosen to limit block chain storage (pruning), the historical data must still be downloaded and processed, but will be deleted afterward to keep your disk usage low.</source>
<translation>Nếu bạn đã chọn giới hạn block chain lưu trữ (pruning),dữ liệu lịch sử vẫn phải được tải xuống và xử lý, nhưng sẽ bị xóa sau đó để giữ cho việc sử dụng đĩa của bạn ở mức usage thấp.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Sử dụng default danh mục đa ta</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Sử dụng custom danh mục data:</translation>
</message>
<message>
<source>Peercoin</source>
<translation>Peercoin</translation>
</message>
<message>
<source>At least %1 GB of data will be stored in this directory, and it will grow over time.</source>
<translation>Ít nhất %1 GB data sẽ được trữ tại danh mục này, và nó sẽ lớn theo thời gian.</translation>
</message>
<message>
<source>Approximately %1 GB of data will be stored in this directory.</source>
<translation>Gần đúng %1 GB of data sẽ được lưu giữ trong danh mục này.</translation>
</message>
<message>
<source>%1 will download and store a copy of the Peercoin block chain.</source>
<translation>%1 sẽ download và lưu trữ một bản copy của Peercoin block chain.</translation>
</message>
<message>
<source>The wallet will also be stored in this directory.</source>
<translation>Wallet sẽ cùng được lưu giữ trong danh mục này.</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Error: Danh mục data xác định "%1" không thể được tạo.</translation>
</message>
<message>
<source>Error</source>
<translation>Lỗi</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n GB of free space available</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(of %n GB cần thiết)</numerusform></translation>
</message>
</context>
<context>
<name>ModalOverlay</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>Recent transactions may not yet be visible, and therefore your wallet's balance might be incorrect. This information will be correct once your wallet has finished synchronizing with the peercoin network, as detailed below.</source>
<translation>Giao dịch gần đây có thể chưa được hiển thị, và vì vậy số dư wallet của bạn có thể không dúng. Thông tin này sẽ được làm đúng khi wallet hoàn thành đồng bộ với peercoin network, như chi tiết bên dưới.</translation>
</message>
<message>
<source>Attempting to spend peercoins that are affected by not-yet-displayed transactions will not be accepted by the network.</source>
<translation>Cố gắng spend các peercoins bị ảnh hưởng bởi các giao dịch chưa được hiển thị sẽ không được chấp nhận bởi mạng.</translation>
</message>
<message>
<source>Number of blocks left</source>
<translation>Số của blocks còn lại</translation>
</message>
<message>
<source>Unknown...</source>
<translation>Unknown...</translation>
</message>
<message>
<source>Last block time</source>
<translation>Thời gian block cuối cùng</translation>
</message>
<message>
<source>Progress</source>
<translation>Tiến độ</translation>
</message>
<message>
<source>Progress increase per hour</source>
<translation>Tiến độ tăng mỗi giờ</translation>
</message>
<message>
<source>calculating...</source>
<translation>Đang tính...</translation>
</message>
<message>
<source>Estimated time left until synced</source>
<translation>Ước tính thời gian còn lại đến khi đồng bộ</translation>
</message>
<message>
<source>Hide</source>
<translation>Ẩn</translation>
</message>
<message>
<source>Unknown. Syncing Headers (%1, %2%)...</source>
<translation>Không biết. Đang đồng bộ Headers (%1, %2%)...</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
</context>
<context>
<name>OpenWalletActivity</name>
<message>
<source>default wallet</source>
<translation>ví mặc định</translation>
</message>
<message>
<source>Opening Wallet <b>%1</b>...</source>
<translation>Đang mở ví <b> %1</b>...</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Tùy chỉnh</translation>
</message>
<message>
<source>&Main</source>
<translation>&Chính</translation>
</message>
<message>
<source>Automatically start %1 after logging in to the system.</source>
<translation>Tự động bắt đầu %1 sau khi đăng nhập vào system.</translation>
</message>
<message>
<source>&Start %1 on system login</source>
<translation>&Bắt đầu %1 trên đăng nhập system</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Size of &database cache</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Number of script &verification threads</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>Shows if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source>
<translation>Hiển thị nếu cung cấp default SOCKS5 proxy is used to reach peers via this network type.</translation>
</message>
<message>
<source>Use separate SOCKS&5 proxy to reach peers via Tor hidden services:</source>
<translation>Dùng riêng lẻ proxy SOCKS&5 để nối tới nốt mạng khác qua dịch vị ẩn Tor:</translation>
</message>
<message>
<source>Hide the icon from the system tray.</source>
<translation>Ẩn biểu tượng ở khay hệ thống</translation>
</message>
<message>
<source>&Hide tray icon</source>
<translation>&Ẩn biểu tượng khay</translation>
</message>
<message>
<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 Exit in the menu.</source>
<translation>Minimize thay vì thoát khỏi ứng dụng khi cửa sổ đóng lại. Khi bật tùy chọn này, ứng dụng sẽ chỉ được đóng sau khi chọn Exit trong menu.</translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>Bên thứ ba URLs (e.g. a block explorer) xuất hiện trong thẻ giao dịch như context menu items. %s in the URL thì được thay thế bởi transaction hash. Multiple URLs are separated by vertical bar |.</translation>
</message>
<message>
<source>Open the %1 configuration file from the working directory.</source>
<translation>Mở %1 configuration file từ danh mục làm việc working directory.</translation>
</message>
<message>
<source>Open Configuration File</source>
<translation>Mở File cấu hình</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Reset tất cả client options to default.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Reset Tùy chọn</translation>
</message>
<message>
<source>&Network</source>
<translation>&Network</translation>
</message>
<message>
<source>Disables some advanced features but all blocks will still be fully validated. Reverting this setting requires re-downloading the entire blockchain. Actual disk usage may be somewhat higher.</source>
<translation>Tăt một số tính năng nâng cao nhưng tất cả các khối vẫn tiếp tục được xác nhận đầy đủ. Hoàn nguyên cài đặt này yêu cầu tải xuống lại toàn bộ blockchain. Sử dụng dung lượng đĩa lưu trữ thực tế có thể cao hơn một chút.</translation>
</message>
<message>
<source>Prune &block storage to</source>
<translation>Cắt tỉa và lưu trữ khối tới</translation>
</message>
<message>
<source>GB</source>
<translation>GB</translation>
</message>
<message>
<source>Reverting this setting requires re-downloading the entire blockchain.</source>
<translation>Hoàn nguyên cài đặt này yêu cầu tải xuống lại toàn bộ blockchain.</translation>
</message>
<message>
<source>MiB</source>
<translation>MiB</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = auto, <0 = leave that many cores free)</translation>
</message>
<message>
<source>W&allet</source>
<translation>W&allet</translation>
</message>
<message>
<source>Expert</source>
<translation>Expert</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Enable coin &control features</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>&Spend unconfirmed change</translation>
</message>
<message>
<source>Automatically open the Peercoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatically open the Peercoin client port on the router. This only works when your router supports UPnP and it is enabled.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Map port using &UPnP</translation>
</message>
<message>
<source>Accept connections from outside.</source>
<translation>Chấp nhận kết nối từ bên ngoài</translation>
</message>
<message>
<source>Allow incomin&g connections</source>
<translation>Chấp nhận kết nối đang tới</translation>
</message>
<message>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>&Connect qua SOCKS5 proxy (default proxy):</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port of the proxy (e.g. 9050)</translation>
</message>
<message>
<source>Used for reaching peers via:</source>
<translation>Sử dụng reaching peers via:</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>Connect to the Peercoin network through a separate SOCKS5 proxy for Tor hidden services.</source>
<translation>Kết nối đến Peercoin network qua một nhánh rời SOCKS5 proxy của Tor hidden services.</translation>
</message>
<message>
<source>&Window</source>
<translation>&Window</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Hiển thị chỉ thẻ icon sau khi thu nhỏ cửa sổ.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimize đến thẻ thay vì taskbar</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>M&inimize on close</translation>
</message>
<message>
<source>&Display</source>
<translation>&Display</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>Giao diện người dùng &language:</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting %1.</source>
<translation>Giao diện ngôn ngữ người dùng có thể được thiết lập tại đây. Tùy chọn này sẽ có hiệu lực sau khi khởi động lại %1.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Unit để hiện số lượng tại đây:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Chọn default đơn vị phân chia để hiện giao diện và đang gửi coins.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Cho hiển thị tính năng coin control hoặc không.</translation>
</message>
<message>
<source>&Third party transaction URLs</source>
<translation>&Các URL giao dịch của bên thứ ba</translation>
</message>
<message>
<source>Options set in this dialog are overridden by the command line or in the configuration file:</source>
<translation>Các tùy chọn được đặt trong hộp thoại này bị ghi đè bởi dòng lệnh hoặc trong tệp cấu hình:</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Hủy</translation>
</message>
<message>
<source>default</source>
<translation>default</translation>
</message>
<message>
<source>none</source>
<translation>không có gì</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Confirm tùy chọn reset</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Client yêu cầu khởi động lại để thay đổi có hiệu lực.</translation>
</message>
<message>
<source>Client will be shut down. Do you want to proceed?</source>
<translation>Client sẽ đóng lại. Tiếp tục chứ?</translation>
</message>
<message>
<source>Configuration options</source>
<translation>Tùy chọn cấu hình</translation>
</message>
<message>
<source>The configuration file is used to specify advanced user options which override GUI settings. Additionally, any command-line options will override this configuration file.</source>
<translation>File cấu hình được sử dụng để chỉ định các tùy chọn nâng cao của người dùng mà ghi đè GUI settings. Ngoài ra, bất kỳ tùy chọn dòng lệnh sẽ ghi đè lên tập tin cấu hình này.</translation>
</message>
<message>
<source>Error</source>
<translation>Lỗi</translation>
</message>
<message>
<source>The configuration file could not be opened.</source>
<translation>Không thẻ mở tệp cấu hình.</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Việc change này sẽ cần một client restart.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>Cung cấp proxy address thì invalid.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Peercoin network after a connection is established, but this process has not completed yet.</source>
<translation>Thông tin được hiển thị có thể đã lỗi thời. Cái wallet tự động đồng bộ với Peercoin network sau một connection được thiết lập, nhưng quá trình này vẫn chưa completed yet.</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>Chỉ-xem:</translation>
</message>
<message>
<source>Available:</source>
<translation>Có hiệu lực:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Số dư khả dụng:</translation>
</message>
<message>
<source>Pending:</source>
<translation>Đang xử lý:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Tất cả giao dịch vẫn chưa được confirmed, và chưa tính vào số dư có thể chi tiêu</translation>
</message>
<message>
<source>Immature:</source>
<translation>Chưa hoàn thiện:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Mined balance chưa matured hẳn</translation>
</message>
<message>
<source>Balances</source>
<translation>Số dư</translation>
</message>
<message>
<source>Total:</source>
<translation>Tổng cộng:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Tổng số dư hiện tại</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>Số dư hiện tại trong địa chỉ watch-only</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Có thể sử dụng</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Giao dịch gần đây</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Giao dịch chưa được xác nhận đến watch-only addresses</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Mined số dư trong watch-only address chưa matured hẳn</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Tổng số dư hiện tại trong watch-only addresses</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>Payment request error</source>
<translation>Payment request error</translation>
</message>
<message>
<source>Cannot start peercoin: click-to-pay handler</source>
<translation>Không thể khởi tạo peercoin: click-to-pay handler</translation>
</message>
<message>
<source>URI handling</source>
<translation>URI handling</translation>
</message>
<message>
<source>'bitcoin://' is not a valid URI. Use 'bitcoin:' instead.</source>
<translation>'bitcoin://' không khả dụng URI. Dùng thay vì 'bitcoin:' .</translation>
</message>
<message>
<source>Invalid payment address %1</source>
<translation>Invalid payment address %1</translation>
</message>
<message>
<source>URI cannot be parsed! This can be caused by an invalid Peercoin address or malformed URI parameters.</source>
<translation>URI không thể phân tích cú pháp! Đây có thể gây nên bởi invalid Peercoin address hoặc URI không đúng định dạng tham số.</translation>
</message>
<message>
<source>Payment request file handling</source>
<translation>Payment request file đang xử lý</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>User Đặc Vụ</translation>
</message>
<message>
<source>Node/Service</source>
<translation>Node/Dịch vụ</translation>
</message>
<message>
<source>NodeId</source>
<translation>NodeID</translation>
</message>
<message>
<source>Ping</source>
<translation>Ping</translation>
</message>
<message>
<source>Sent</source>
<translation>Gửi</translation>
</message>
<message>
<source>Received</source>
<translation>Nhận</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Số lượng</translation>
</message>
<message>
<source>Enter a Peercoin address (e.g. %1)</source>
<translation>Nhập một Peercoin address (e.g. %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 d</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 giờ</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 phút</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 giây</translation>
</message>
<message>
<source>None</source>
<translation>None</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
<message numerus="yes">
<source>%n second(s)</source>
<translation><numerusform>%n giây</numerusform></translation>
</message>
<message numerus="yes">
<source>%n minute(s)</source>
<translation><numerusform>%n phút</numerusform></translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n giờ</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n ngày</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n tuần</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 và %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n năm</numerusform></translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation>Error: Xác định data directory "%1" không tồn tại.</translation>
</message>
<message>
<source>Error: Cannot parse configuration file: %1.</source>
<translation>Lỗi: không thể phân giải tệp cài đặt cấu hình: %1.</translation>
</message>
<message>
<source>Error: %1</source>
<translation>Error: %1</translation>
</message>
<message>
<source>%1 didn't yet exit safely...</source>
<translation>%1 vẫn chưa thoát an toàn...</translation>
</message>
<message>
<source>unknown</source>
<translation>unknown</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Lưu ảnh...</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Sao chép ảnh</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Đang tính toán URI quá dài, cố gắng giảm text cho label / message.</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Error đang mã hóa URI đến QR Code.</translation>
</message>
<message>
<source>QR code support not available.</source>
<translation>Sự hổ trợ mã QR không sẵn có</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>Lưu QR Code</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>PNG Image (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>Client version</source>
<translation>Client version</translation>
</message>
<message>
<source>&Information</source>
<translation>&Thông tin</translation>
</message>
<message>
<source>General</source>
<translation>Tổng thể</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Sử dụng phiên bản BerkeleyDB</translation>
</message>
<message>
<source>Datadir</source>
<translation>Datadir</translation>
</message>
<message>
<source>To specify a non-default location of the data directory use the '%1' option.</source>
<translation>Để chỉ ra một nơi không mặt định của thư mục dữ liệu hãy dùng tùy chọn '%1'</translation>
</message>
<message>
<source>Blocksdir</source>
<translation>Thư mục chứa các khối Blocksdir</translation>
</message>
<message>
<source>To specify a non-default location of the blocks directory use the '%1' option.</source>
<translation>Để chỉ ra một nơi không mặt định của thư mục các khối hãy dùng tùy chọn '%1'</translation>
</message>
<message>
<source>Startup time</source>
<translation>Startup lúc</translation>
</message>
<message>
<source>Network</source>
<translation>Mạng</translation>
</message>
<message>
<source>Name</source>
<translation>Tên</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Số lượng connections</translation>
</message>
<message>
<source>Block chain</source>
<translation>Block chain</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Số blocks hiện tại</translation>
</message>
<message>
<source>Memory Pool</source>
<translation>Pool Bộ Nhớ</translation>
</message>
<message>
<source>Current number of transactions</source>
<translation>Số giao dịch hiện tại</translation>
</message>
<message>
<source>Memory usage</source>
<translation>Bộ nhớ usage</translation>
</message>
<message>
<source>Wallet: </source>
<translation>Ví :</translation>
</message>
<message>
<source>(none)</source>
<translation>(không)</translation>
</message>
<message>
<source>&Reset</source>
<translation>&Reset</translation>
</message>
<message>
<source>Received</source>
<translation>Nhận</translation>
</message>
<message>
<source>Sent</source>
<translation>Gửi</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Peers</translation>
</message>
<message>
<source>Banned peers</source>
<translation>Bị khóa peers</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Chọn một peer để xem thông tin chi tiết.</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>Whitelisted</translation>
</message>
<message>
<source>Direction</source>
<translation>Direction</translation>
</message>
<message>
<source>Version</source>
<translation>Phiên bản</translation>
</message>
<message>
<source>Starting Block</source>
<translation>Block Bắt Đầu</translation>
</message>
<message>
<source>Synced Headers</source>
<translation>Headers đã được đồng bộ</translation>
</message>
<message>
<source>Synced Blocks</source>
<translation>Blocks đã được đồng bộ</translation>
</message>
<message>
<source>User Agent</source>
<translation>User đặc vụ</translation>
</message>
<message>
<source>Open the %1 debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Mở cái %1 debug log file từ danh mục dữ liệu hiện tại. Điều này cần vài giây cho large log files.</translation>
</message>
<message>
<source>Decrease font size</source>
<translation>Giảm font size</translation>
</message>
<message>
<source>Increase font size</source>
<translation>Tăng font size</translation>
</message>
<message>
<source>Services</source>
<translation>Dịch vụ</translation>
</message>
<message>
<source>Ban Score</source>
<translation>Cấm Score</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Connection Thời Gian</translation>
</message>
<message>
<source>Last Send</source>
<translation>Gửi Sau Cùng</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Nhận Sau Cùng</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Ping Time</translation>
</message>
<message>
<source>The duration of a currently outstanding ping.</source>
<translation>Thời hạn của một ping hiện đang nổi trội.</translation>
</message>
<message>
<source>Ping Wait</source>
<translation>Ping Chờ</translation>
</message>
<message>
<source>Min Ping</source>
<translation>Ping Nhỏ Nhất</translation>
</message>
<message>
<source>Time Offset</source>
<translation>Thời gian Offset</translation>
</message>
<message>
<source>Last block time</source>
<translation>Thời gian block cuối cùng</translation>
</message>
<message>
<source>&Open</source>
<translation>&Open</translation>
</message>
<message>
<source>&Console</source>
<translation>&BangDieuKhien</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>&Network Traffic</translation>
</message>
<message>
<source>Totals</source>
<translation>Totals</translation>
</message>
<message>
<source>In:</source>
<translation>In:</translation>
</message>
<message>
<source>Out:</source>
<translation>Out:</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Debug file log</translation>
</message>
<message>
<source>Clear console</source>
<translation>Xóa console</translation>
</message>
<message>
<source>1 &hour</source>
<translation>1 &hour</translation>
</message>
<message>
<source>1 &day</source>
<translation>1 &day</translation>
</message>
<message>
<source>1 &week</source>
<translation>1 &week</translation>
</message>
<message>
<source>1 &year</source>
<translation>1 &year</translation>
</message>
<message>
<source>&Disconnect</source>
<translation>&Disconnect</translation>
</message>
<message>
<source>Ban for</source>
<translation>Ban for</translation>
</message>
<message>
<source>&Unban</source>
<translation>&Unban</translation>
</message>
<message>
<source>Welcome to the %1 RPC console.</source>
<translation>Welcome to the %1 RPC console.</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and %1 to clear screen.</source>
<translation>Use up and down arrows to navigate history, and %1 to clear screen.</translation>
</message>
<message>
<source>Type %1 for an overview of available commands.</source>
<translation>Nhậ p %1 để biết tổng quan về các lệnh có sẵn.</translation>
</message>
<message>
<source>For more information on using this console type %1.</source>
<translation>Để biết thêm thông tin về việc sử dụng bảng điều khiển này, hãy nhập %1.</translation>
</message>
<message>
<source>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.</source>
<translation>WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramifications of a command.</translation>
</message>
<message>
<source>Network activity disabled</source>
<translation>Network activity disabled</translation>
</message>
<message>
<source>Executing command without any wallet</source>
<translation>Đang chạy lệnh khi không có ví nào</translation>
</message>
<message>
<source>Executing command using "%1" wallet</source>
<translation>Chạy lệnh bằng ví "%1"</translation>
</message>
<message>
<source>(node id: %1)</source>
<translation>(node id: %1)</translation>
</message>
<message>
<source>via %1</source>
<translation>via %1</translation>
</message>
<message>
<source>never</source>
<translation>không bao giờ</translation>
</message>
<message>
<source>Inbound</source>
<translation>Inbound</translation>
</message>
<message>
<source>Outbound</source>
<translation>Outbound</translation>
</message>
<message>
<source>Yes</source>
<translation>Yes</translation>
</message>
<message>
<source>No</source>
<translation>No</translation>
</message>
<message>
<source>Unknown</source>
<translation>Không biết</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>&Amount:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Message:</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Peercoin network.</source>
<translation>Một optional lời nhắn để đính kèm đến payment request, cái mà sẽ được hiển thị khi mà request đang mở. Lưu ý: Tin nhắn này sẽ không được gửi với payment over the Peercoin network.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>Một optional label để liên kết với address đang nhận mới.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Sử dụng form cho request thanh toán. Tất cả chỗ trống là <b>optional</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>Một optional giá trị để request. Để lại đây khoảng trống hoặc zero để không request một giá trị xác định.</translation>
</message>
<message>
<source>&Create new receiving address</source>
<translation>&Tạo địa chỉ nhận mới</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Xóa hết các khoảng trống của form.</translation>
</message>
<message>
<source>Clear</source>
<translation>Xóa</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Yêu cầu lịch sử giao dịch</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Hiển thị request đã chọn (does the same as double clicking an entry)</translation>
</message>
<message>
<source>Show</source>
<translation>Hiển thị</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Xóa bỏ mục đang chọn từ danh sách</translation>
</message>
<message>
<source>Remove</source>
<translation>Gỡ bỏ</translation>
</message>
<message>
<source>Copy URI</source>
<translation>Sao chép URI</translation>
</message>
<message>
<source>Copy label</source>
<translation>Sao chép nhãn</translation>
</message>
<message>
<source>Copy message</source>
<translation>Sao chép tin nhắn</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Sao chép số lượng</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>QR Code</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Sao chép &URI</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Sao chép địa chỉ</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Lưu ảnh...</translation>
</message>
<message>
<source>Request payment to %1</source>
<translation>Request payment đến %1</translation>
</message>
<message>
<source>Payment information</source>
<translation>Payment thông tin</translation>
</message>
<message>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<source>Address</source>
<translation>Địa chỉ</translation>
</message>
<message>
<source>Amount</source>
<translation>Số lượng</translation>
</message>
<message>
<source>Label</source>
<translation>Nhãn</translation>
</message>
<message>
<source>Message</source>
<translation>Tin nhắn</translation>
</message>
<message>
<source>Wallet</source>
<translation>Ví</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Ngày</translation>
</message>
<message>
<source>Label</source>
<translation>Nhãn</translation>
</message>
<message>
<source>Message</source>
<translation>Tin nhắn</translation>
</message>
<message>
<source>(no label)</source>
<translation>(không nhãn)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(no tin nhắn)</translation>
</message>
<message>
<source>(no amount requested)</source>
<translation>(không amount yêu cầu)</translation>
</message>
<message>
<source>Requested</source>
<translation>Đã yêu cầu</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Gửi Coins</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Coin Control Tính-năng</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Đang nhập...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>được chọn một cách hoàn toàn tự động</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Không đủ tiền kìa!</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Số lượng:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Số lượng:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Phí:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Sau Phí:</translation>
</message>
<message>
<source>Change:</source>
<translation>Thay đổi:</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Nếu cái này được bật, nhưng việc change address thì trống hoặc invalid, change sẽ được gửi cho một address vừa được tạo mới.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Custom change address</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Transaction Fee:</translation>
</message>
<message>
<source>Choose...</source>
<translation>Chọn...</translation>
</message>
<message>
<source>Using the fallbackfee can result in sending a transaction that will take several hours or days (or never) to confirm. Consider choosing your fee manually or wait until you have validated the complete chain.</source>
<translation>Sử dụng fallbackfee có thể dẫn đến hết quả đang gửi một transaction mà nó sẽ mất hàng giờ hoặc ngày (hoặc chẳng bao giờ) được confirm. Suy nghĩ chọn fee của bạn bình thường hoặc chờ cho đến khi validated hoàn thành chain.</translation>
</message>
<message>
<source>Warning: Fee estimation is currently not possible.</source>
<translation>Warning: Fee ước tính hiện tại không khả thi.</translation>
</message>
<message>
<source>Specify a custom fee per kB (1,000 bytes) of the transaction's virtual size.
Note: Since the fee is calculated on a per-byte basis, a fee of "100 satoshis per kB" for a transaction size of 500 bytes (half of 1 kB) would ultimately yield a fee of only 50 satoshis.</source>
<translation>Chỉ định một khoản phí tùy chỉnh cho mỗi kB (1.000 byte) kích thước ảo của giao dịch.
Lưu ý: Vì phí được tính trên cơ sở mỗi byte, nên phí "100 satoshi trên mỗi kB" cho kích thước giao dịch là 500 byte (một nửa của 1 kB) cuối cùng sẽ mang lại một khoản phí chỉ 50 satoshi.</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>trên mỗi kilobyte</translation>
</message>
<message>
<source>Hide</source>
<translation>Ẩn</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Khuyên dùng:</translation>
</message>
<message>
<source>Custom:</source>
<translation>Custom:</translation>
</message>
<message>
<source>(Smart fee not initialized yet. This usually takes a few blocks...)</source>
<translation>(Thông minh fee vẫn chưa được khởi tạo. Điều này thường mất vài blocks...)</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Gửi đến tập thể người nhận một lần</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Add &Recipient</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Xóa hết các khoảng trống của form.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Rác:</translation>
</message>
<message>
<source>When there is less transaction volume than space in the blocks, miners as well as relaying nodes may enforce a minimum fee. Paying only this minimum fee is just fine, but be aware that this can result in a never confirming transaction once there is more demand for bitcoin transactions than the network can process.</source>
<translation>Khi có khối lượng giao dịch ít hơn chổ trống trong các khối, các nhà đào mỏ cũng như các nút chuyển tiếp có thể thực thi chỉ với một khoản phí tối thiểu. Chỉ trả khoản phí tối thiểu này là tốt, nhưng lưu ý rằng điều này có thể dẫn đến một giao dịch không bao giờ xác nhận một khi có nhu cầu giao dịch bitcoin nhiều hơn khả năng mạng có thể xử lý.</translation>
</message>
<message>
<source>A too low fee might result in a never confirming transaction (read the tooltip)</source>
<translation>Một khoản phí quá thấp có thể dẫn đến một giao dịch không bao giờ xác nhận (đọc chú giải công cụ)</translation>
</message>
<message>
<source>Confirmation time target:</source>
<translation>Thời gian xác nhận đối tượng:</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<source>Balance:</source>
<translation>Số dư:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Confirm hành động gửi</translation>
</message>
<message>
<source>S&end</source>
<translation>S&end</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Sao chép số lượng</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Sao chép số lượng</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Sao chép phí</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Sao chép sau phí</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Sao chép bytes</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Sao chép rác</translation>
</message>
<message>
<source>Copy change</source>
<translation>Sao chép thay đổi</translation>
</message>
<message>
<source>%1 (%2 blocks)</source>
<translation>%1 (%2 blocks)</translation>
</message>
<message>
<source> from wallet '%1'</source>
<translation>từ ví '%1'</translation>
</message>
<message>
<source>%1 to '%2'</source>
<translation>%1 tới '%2'</translation>
</message>
<message>
<source>%1 to %2</source>
<translation>%1 đến%2</translation>
</message>
<message>
<source>Are you sure you want to send?</source>
<translation>Bạn chắc chắn muốn gửi chứ?</translation>
</message>
<message>
<source>or</source>
<translation>hoặc</translation>
</message>
<message>
<source>Please, review your transaction.</source>
<translation>Làm ơn xem xét đánh giá giao dịch của bạn.</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<source>Total Amount</source>
<translation>Tổng số</translation>
</message>
<message>
<source>To review recipient list click "Show Details..."</source>
<translation>Để xem nhận xét người nhận, nhấn "Xem chi tiết..."</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Confirm gửi coins</translation>
</message>
<message>
<source>The recipient address is not valid. Please recheck.</source>
<translation>Địa chỉ người nhận address thì không valid. Kiểm tra lại đi.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>Giả trị để pay cần phải lớn hơn 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Số tiền vượt quá số dư của bạn.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Tổng số lớn hơn số dư của bạn khi %1 transaction fee được tính vào.</translation>
</message>
<message>
<source>Duplicate address found: addresses should only be used once each.</source>
<translation>Trùng address được tìm thấy: địa chỉ chỉ nên được dùng một lần.</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>Transaction khởi tạo thất bại!</translation>
</message>
<message>
<source>A fee higher than %1 is considered an absurdly high fee.</source>
<translation>Một fee lớn hơn %1 được coi là ngớ ngẩn cao fee.</translation>
</message>
<message>
<source>Payment request expired.</source>
<translation>Payment request hết hạn.</translation>
</message>
<message numerus="yes">
<source>Estimated to begin confirmation within %n block(s).</source>
<translation><numerusform>Dự kiến bắt đầu xác nhận trong vòng %n blocks.</numerusform></translation>
</message>
<message>
<source>Warning: Invalid Peercoin address</source>
<translation>Warning: Invalid Peercoin address</translation>
</message>
<message>
<source>Warning: Unknown change address</source>
<translation>Warning: Không biết change address</translation>
</message>
<message>
<source>Confirm custom change address</source>
<translation>Confirm custom change address</translation>
</message>
<message>
<source>The address you selected for change is not part of this wallet. Any or all funds in your wallet may be sent to this address. Are you sure?</source>
<translation>The address bạn đã chọn dành cho change thì không phải part of this wallet. Bất kỳ hay tất cả funds in your wallet có thể được gửi đến address này. Bạn chắc chứ?</translation>
</message>
<message>
<source>(no label)</source>
<translation>(không nhãn)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>A&mount:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Pay &To:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Label:</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Chọn mới thì address</translation>
</message>
<message>
<source>The Peercoin address to send the payment to</source>
<translation>The Peercoin address để gửi the payment đến</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Paste address từ clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Xóa bỏ entry này</translation>
</message>
<message>
<source>The fee will be deducted from the amount being sent. The recipient will receive less peercoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source>
<translation>The fee sẽ được khấu trừ từ số tiền đang gửi. Người nhận sẽ receive ít peercoins hơn bạn gõ vào khoảng trống. Nếu nhiều người gửi được chọn, fee sẽ được chia đều.</translation>
</message>
<message>
<source>S&ubtract fee from amount</source>
<translation>S&ubtract fee từ amount</translation>
</message>
<message>
<source>Use available balance</source>
<translation>Sử dụng số dư sẵn có</translation>
</message>
<message>
<source>Message:</source>
<translation>Tin nhắn:</translation>
</message>
<message>
<source>This is an unauthenticated payment request.</source>
<translation>Đây là một chưa được chứng thực payment request.</translation>
</message>
<message>
<source>This is an authenticated payment request.</source>
<translation>Đây là một chưa được chứng thực payment request.</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Nhập một label cho cái address này để thêm vào danh sách địa chỉ đã sử dụng</translation>
</message>
<message>
<source>A message that was attached to the peercoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Peercoin network.</source>
<translation>Một tin nhắn được đính kèm với số peercoin: URI mà sẽ được lưu giữ với transaction dành cho tài liệu tham khảo. Lưu ý: Tin nhắn này sẽ không được gửi thông qua Peercoin network.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Pay Đến:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Bản ghi nhớ:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>%1 is shutting down...</source>
<translation>%1 đang shutting down...</translation>
</message>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>Đừng tắt máy tính đến khi cửa sổ này đóng.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Chữ ký - Sign / Verify a Message</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Sign Tin nhắn</translation>
</message>
<message>
<source>You can sign messages/agreements with your addresses to prove you can receive peercoins sent to them. Be careful not to sign anything vague or random, 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>Bạn có thể ký/đồng ý với địa chỉ chứng minh bạn có thể receive peercoins đã gửi đến chúng. Cẩn thận không ký bất cứ không rõ hay random, như các cuộc tấn công lừa đảo có thể cố lừa bạn ký tên vào danh tính của bạn.. Chỉ ký các bản tuyên bố hoàn chỉnh mà bạn đồng ý.</translation>
</message>
<message>
<source>The Peercoin address to sign the message with</source>
<translation>The Peercoin address để ký với tin nhắn</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Chọn mới thì address</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Paste address từ clipboard</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Nhập tin nhắn bạn muốn ký tại đây</translation>
</message>
<message>
<source>Signature</source>
<translation>Signature</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Copy hiện tại signature tới system clipboard</translation>
</message>
<message>
<source>Sign the message to prove you own this Peercoin address</source>
<translation>Ký tin nhắn để chứng minh bạn sở hữu Peercoin address này</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Sign &Message</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Reset tất cả khoảng chữ ký nhắn</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Clear &All</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Verify Tin nhắn</translation>
</message>
<message>
<source>Enter the receiver's 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. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source>
<translation>Nhập vào address người nhận, tin nhắn (chắc rằng bạn copy line breaks, khoảng trống, tabs, etc. chính xác) và signature bên dưới verify tin nhắn. Cẩn thận không đọc nhiều hơn từ signature so với cái được ký trong bản thân tin nhắn, để tránh bị lừa bới man-in-the-middle tấn công. Lưu ý rằng điều này chỉ chứng nhận nhóm những người nhân với address, nó không thể chứng minh bên gửi có bất kỳ transaction!</translation>
</message>
<message>
<source>The Peercoin address the message was signed with</source>
<translation>The Peercoin address tin nhắn đã ký với</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Peercoin address</source>
<translation>Verify tin nhắn để chắc rằng nó đã được ký với xác định Peercoin address</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>Verify &Message</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Reset tất cả verify khoảng trống nhắn</translation>
</message>
<message>
<source>Click "Sign Message" to generate signature</source>
<translation>Click "Sign Message" để generate signature</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>Đã nhập address thì invalid.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Vui lòng kiểm tra address và thử lại.</translation>
</message>
<message>
<source>The entered address does not refer to a key.</source>
<translation>Đã nhập address không refer to a key.</translation>
</message>
<message>
<source>Wallet unlock was cancelled.</source>
<translation>Wallet unlock đã được hủy.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>Private key cho address đã nhập thì không có sẵn.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Message signing failed.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Message signed.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>The signature could not be decoded.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Please check the signature and try again.</translation>
</message>
<message>
<source>The signature did not match the message digest.</source>
<translation>The signature did not match the message digest.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Message verification failed.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Message verified.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Mở cho %n nhiều hơn blocks</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<source>conflicted with a transaction with %1 confirmations</source>
<translation>conflicted with a transaction with %1 confirmations</translation>
</message>
<message>
<source>0/unconfirmed, %1</source>
<translation>0/unconfirmed, %1</translation>
</message>
<message>
<source>in memory pool</source>
<translation>in memory pool</translation>
</message>
<message>
<source>not in memory pool</source>
<translation>not in memory pool</translation>
</message>
<message>
<source>abandoned</source>
<translation>abandoned</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/unconfirmed</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<source>Status</source>
<translation>Status</translation>
</message>
<message>
<source>Date</source>
<translation>Ngày</translation>
</message>
<message>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<source>Generated</source>
<translation>Generated</translation>
</message>
<message>
<source>From</source>
<translation>From</translation>
</message>
<message>
<source>unknown</source>
<translation>unknown</translation>
</message>
<message>
<source>To</source>
<translation>To</translation>
</message>
<message>
<source>own address</source>
<translation>own address</translation>
</message>
<message>
<source>watch-only</source>
<translation>watch-only</translation>
</message>
<message>
<source>label</source>
<translation>label</translation>
</message>
<message>
<source>Credit</source>
<translation>Credit</translation>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation><numerusform>Hoàn thiện trong %n nhiều hơn blocks</numerusform></translation>
</message>
<message>
<source>not accepted</source>
<translation>not accepted</translation>
</message>
<message>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<source>Total debit</source>
<translation>Total debit</translation>
</message>
<message>
<source>Total credit</source>
<translation>Total credit</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Transaction fee</translation>
</message>
<message>
<source>Net amount</source>
<translation>Net amount</translation>
</message>
<message>
<source>Message</source>
<translation>Tin nhắn</translation>
</message>
<message>
<source>Comment</source>
<translation>Comment</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>Transaction ID</translation>
</message>
<message>
<source>Transaction total size</source>
<translation>Transaction total size</translation>
</message>
<message>
<source>Transaction virtual size</source>
<translation>Kích cỡ giao dịch ảo</translation>
</message>
<message>
<source>Output index</source>
<translation>Output index</translation>
</message>
<message>
<source>Merchant</source>
<translation>Merchant</translation>
</message>
<message>
<source>Generated coins must mature %1 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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Generated coins must mature %1 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 "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</translation>
</message>
<message>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<source>Amount</source>
<translation>Giá trị</translation>
</message>
<message>
<source>true</source>
<translation>true</translation>
</message>
<message>
<source>false</source>
<translation>false</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>This pane shows a detailed description of the transaction</translation>
</message>
<message>
<source>Details for %1</source>
<translation>Details for %1</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Ngày</translation>
</message>
<message>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<source>Label</source>
<translation>Nhãn</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>Mở cho %n nhiều hơn blocks</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>Open until %1</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Unconfirmed</translation>
</message>
<message>
<source>Abandoned</source>
<translation>Abandoned</translation>
</message>
<message>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirming (%1 of %2 recommended confirmations)</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmed (%1 confirmations)</translation>
</message>
<message>
<source>Conflicted</source>
<translation>Xung đột</translation>
</message>
<message>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 confirmations, will be available after %2)</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Generated but not accepted</translation>
</message>
<message>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<source>Received from</source>
<translation>Received from</translation>
</message>
<message>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Payment to yourself</translation>
</message>
<message>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<source>watch-only</source>
<translation>watch-only</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<source>(no label)</source>
<translation>(không nhãn)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaction status. Hover over this field to show number of confirmations.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Date and time that the transaction was received.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Type of transaction.</translation>
</message>
<message>
<source>Whether or not a watch-only address is involved in this transaction.</source>
<translation>Whether or not a watch-only address is involved in this transaction.</translation>
</message>
<message>
<source>User-defined intent/purpose of the transaction.</source>
<translation>User-defined intent/purpose of the transaction.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Amount removed from or added to balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Tất cả</translation>
</message>
<message>
<source>Today</source>
<translation>Hôm nay</translation>
</message>
<message>
<source>This week</source>
<translation>Tuần này</translation>
</message>
<message>
<source>This month</source>
<translation>Tháng này</translation>
</message>
<message>
<source>Last month</source>
<translation>Tháng trước</translation>
</message>
<message>
<source>This year</source>
<translation>Năm nay</translation>
</message>
<message>
<source>Range...</source>
<translation>Range...</translation>
</message>
<message>
<source>Received with</source>
<translation>Received with</translation>
</message>
<message>
<source>Sent to</source>
<translation>Sent to</translation>
</message>
<message>
<source>To yourself</source>
<translation>To yourself</translation>
</message>
<message>
<source>Mined</source>
<translation>Mined</translation>
</message>
<message>
<source>Other</source>
<translation>Other</translation>
</message>
<message>
<source>Enter address, transaction id, or label to search</source>
<translation>Nhập địa chỉ, số id giao dịch, hoặc nhãn để tìm kiếm</translation>
</message>
<message>
<source>Min amount</source>
<translation>Min amount</translation>
</message>
<message>
<source>Abandon transaction</source>
<translation>Abandon transaction</translation>
</message>
<message>
<source>Increase transaction fee</source>
<translation>Increase transaction fee</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copy address</translation>
</message>
<message>
<source>Copy label</source>
<translation>Sao chép nhãn</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Sao chép số lượng</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Sao chép ID giao dịch</translation>
</message>
<message>
<source>Copy raw transaction</source>
<translation>Copy raw transaction</translation>
</message>
<message>
<source>Copy full transaction details</source>
<translation>Copy full transaction details</translation>
</message>
<message>
<source>Edit label</source>
<translation>Edit label</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Show transaction details</translation>
</message>
<message>
<source>Export Transaction History</source>
<translation>Export Transaction History</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Đã xác nhận</translation>
</message>
<message>
<source>Watch-only</source>
<translation>Watch-only</translation>
</message>
<message>
<source>Date</source>
<translation>Ngày</translation>
</message>
<message>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<source>Label</source>
<translation>Nhãn</translation>
</message>
<message>
<source>Address</source>
<translation>Địa chỉ</translation>
</message>
<message>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Xuất Thất Bại</translation>
</message>
<message>
<source>There was an error trying to save the transaction history to %1.</source>
<translation>There was an error trying to save the transaction history to %1.</translation>
</message>
<message>
<source>Exporting Successful</source>
<translation>Exporting Successful</translation>
</message>
<message>
<source>The transaction history was successfully saved to %1.</source>
<translation>The transaction history was successfully saved to %1.</translation>
</message>
<message>
<source>Range:</source>
<translation>Range:</translation>
</message>
<message>
<source>to</source>
<translation>to</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Unit to show amounts in. Click to select another unit.</translation>
</message>
</context>
<context>
<name>WalletController</name>
<message>
<source>Close wallet</source>
<translation>Đông ví</translation>
</message>
<message>
<source>Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled.</source>
<translation>Đóng ví thời gian dài sẽ dẫn đến phải đồng bộ hóa lại cả chuỗi nếu cắt tỉa pruning được kích hoạt</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
<message>
<source>No wallet has been loaded.</source>
<translation>No wallet has been loaded.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Gửi Coins</translation>
</message>
<message>
<source>Fee bump error</source>
<translation>Fee bơm error</translation>
</message>
<message>
<source>Increasing transaction fee failed</source>
<translation>Increasing transaction fee failed</translation>
</message>
<message>
<source>Do you want to increase the fee?</source>
<translation>Do you want to increase the fee?</translation>
</message>
<message>
<source>Current fee:</source>
<translation>Current fee:</translation>
</message>
<message>
<source>Increase:</source>
<translation>Increase:</translation>
</message>
<message>
<source>New fee:</source>
<translation>New fee:</translation>
</message>
<message>
<source>Confirm fee bump</source>
<translation>Confirm fee bump</translation>
</message>
<message>
<source>Can't sign transaction.</source>
<translation>Can't sign transaction.</translation>
</message>
<message>
<source>Could not commit transaction</source>
<translation>Could not commit transaction</translation>
</message>
<message>
<source>default wallet</source>
<translation>ví mặc định</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Xuất</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Xuất dữ liệu trong thẻ hiện tại ra file</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Backup Wallet</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>Wallet Data (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>Backup Failed</translation>
</message>
<message>
<source>There was an error trying to save the wallet data to %1.</source>
<translation>There was an error trying to save the wallet data to %1.</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>Backup Successful</translation>
</message>
<message>
<source>The wallet data was successfully saved to %1.</source>
<translation>The wallet data was successfully saved to %1.</translation>
</message>
<message>
<source>Cancel</source>
<translation>Hủy</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Distributed under the MIT software license, see the accompanying file %s or %s</source>
<translation>Distributed under the MIT software license, see the accompanying file %s or %s</translation>
</message>
<message>
<source>Prune configured below the minimum of %d MiB. Please use a higher number.</source>
<translation>Prune configured below the minimum of %d MiB. Please use a higher number.</translation>
</message>
<message>
<source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source>
<translation>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</translation>
</message>
<message>
<source>Error: A fatal internal error occurred, see debug.log for details</source>
<translation>Error: A fatal internal error occurred, see debug.log for details</translation>
</message>
<message>
<source>Pruning blockstore...</source>
<translation>Pruning blockstore...</translation>
</message>
<message>
<source>Unable to start HTTP server. See debug log for details.</source>
<translation>Unable to start HTTP server. See debug log for details.</translation>
</message>
<message>
<source>The %s developers</source>
<translation>The %s developers</translation>
</message>
<message>
<source>Can't generate a change-address key. No keys in the internal keypool and can't generate any keys.</source>
<translation>Không thể tạo khóa địa chỉ thay đổi. Không có các khóa trong hồ khóa keypool nội bộ và không thể tạo bất kì khóa nào.</translation>
</message>
<message>
<source>Cannot obtain a lock on data directory %s. %s is probably already running.</source>
<translation>Cannot obtain a lock on data directory %s. %s is probably already running.</translation>
</message>
<message>
<source>Cannot provide specific connections and have addrman find outgoing connections at the same.</source>
<translation>Không thể cung cấp kết nối nào và có addrman tìm kết nối đi cùng một lúc.</translation>
</message>
<message>
<source>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Error reading %s! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</translation>
</message>
<message>
<source>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</source>
<translation>Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.</translation>
</message>
<message>
<source>Please contribute if you find %s useful. Visit %s for further information about the software.</source>
<translation>Please contribute if you find %s useful. Visit %s for further information about the software.</translation>
</message>
<message>
<source>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</source>
<translation>The block database contains a block which appears to be from the future. This may be due to your computer's date and time being set incorrectly. Only rebuild the block database if you are sure that your computer's date and time are correct</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</translation>
</message>
<message>
<source>This is the transaction fee you may discard if change is smaller than dust at this level</source>
<translation>This is the transaction fee you may discard if change is smaller than dust at this level</translation>
</message>
<message>
<source>Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.</source>
<translation>Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.</translation>
</message>
<message>
<source>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</source>
<translation>Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</translation>
</message>
<message>
<source>%d of last 100 blocks have unexpected version</source>
<translation>%d of last 100 blocks have unexpected version</translation>
</message>
<message>
<source>%s corrupt, salvage failed</source>
<translation>%s corrupt, salvage failed</translation>
</message>
<message>
<source>-maxmempool must be at least %d MB</source>
<translation>-maxmempool must be at least %d MB</translation>
</message>
<message>
<source>Cannot resolve -%s address: '%s'</source>
<translation>Cannot resolve -%s address: '%s'</translation>
</message>
<message>
<source>Change index out of range</source>
<translation>Change index out of range</translation>
</message>
<message>
<source>Config setting for %s only applied on %s network when in [%s] section.</source>
<translation>Cài dặt thuộc tính cho %s chỉ có thể áp dụng cho mạng %s trong khi [%s] .</translation>
</message>
<message>
<source>Copyright (C) %i-%i</source>
<translation>Copyright (C) %i-%i</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Corrupted block database detected</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Do you want to rebuild the block database now?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Error initializing block database</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Error initializing wallet database environment %s!</translation>
</message>
<message>
<source>Error loading %s</source>
<translation>Error loading %s</translation>
</message>
<message>
<source>Error loading %s: Private keys can only be disabled during creation</source>
<translation>Lỗi tải %s: Khóa riêng tư chỉ có thể không kích hoạt trong suốt quá trình tạo.</translation>
</message>
<message>
<source>Error loading %s: Wallet corrupted</source>
<translation>Error loading %s: Wallet corrupted</translation>
</message>
<message>
<source>Error loading %s: Wallet requires newer version of %s</source>
<translation>Error loading %s: Wallet requires newer version of %s</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Error loading block database</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Error opening block database</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Failed to listen on any port. Use -listen=0 if you want this.</translation>
</message>
<message>
<source>Failed to rescan the wallet during initialization</source>
<translation>Lỗi quét lại ví trong xuất quá trình khởi tạo</translation>
</message>
<message>
<source>Importing...</source>
<translation>Importing...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Incorrect or no genesis block found. Wrong datadir for network?</translation>
</message>
<message>
<source>Initialization sanity check failed. %s is shutting down.</source>
<translation>Initialization sanity check failed. %s is shutting down.</translation>
</message>
<message>
<source>Invalid P2P permission: '%s'</source>
<translation>Quyền P2P không hợp lệ: '%s'</translation>
</message>
<message>
<source>Invalid amount for -%s=<amount>: '%s'</source>
<translation>Invalid amount for -%s=<amount>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -discardfee=<amount>: '%s'</source>
<translation>Invalid amount for -discardfee=<amount>: '%s'</translation>
</message>
<message>
<source>Invalid amount for -fallbackfee=<amount>: '%s'</source>
<translation>Invalid amount for -fallbackfee=<amount>: '%s'</translation>
</message>
<message>
<source>Specified blocks directory "%s" does not exist.</source>
<translation>Thư mục chứa các khối được chỉ ra "%s" không tồn tại</translation>
</message>
<message>
<source>Upgrading txindex database</source>
<translation>Đang nâng cấp dữ liệu txindex</translation>
</message>
<message>
<source>Loading P2P addresses...</source>
<translation>Loading P2P addresses...</translation>
</message>
<message>
<source>Error: Disk space is too low!</source>
<translation>Lỗi: Chổ tróng đĩa lưu trữ còn quá ít!</translation>
</message>
<message>
<source>Loading banlist...</source>
<translation>Loading banlist...</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Not enough file descriptors available.</translation>
</message>
<message>
<source>Prune cannot be configured with a negative value.</source>
<translation>Prune cannot be configured with a negative value.</translation>
</message>
<message>
<source>Prune mode is incompatible with -txindex.</source>
<translation>Prune mode is incompatible with -txindex.</translation>
</message>
<message>
<source>Replaying blocks...</source>
<translation>Replaying blocks...</translation>
</message>
<message>
<source>Rewinding blocks...</source>
<translation>Rewinding blocks...</translation>
</message>
<message>
<source>The source code is available from %s.</source>
<translation>The source code is available from %s.</translation>
</message>
<message>
<source>Transaction fee and change calculation failed</source>
<translation>Transaction fee and change calculation failed</translation>
</message>
<message>
<source>Unable to bind to %s on this computer. %s is probably already running.</source>
<translation>Unable to bind to %s on this computer. %s is probably already running.</translation>
</message>
<message>
<source>Unable to generate keys</source>
<translation>Không thể tạo khóa</translation>
</message>
<message>
<source>Unsupported logging category %s=%s.</source>
<translation>Unsupported logging category %s=%s.</translation>
</message>
<message>
<source>Upgrading UTXO database</source>
<translation>Upgrading UTXO database</translation>
</message>
<message>
<source>User Agent comment (%s) contains unsafe characters.</source>
<translation>User Agent comment (%s) contains unsafe characters.</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Verifying blocks...</translation>
</message>
<message>
<source>Wallet needed to be rewritten: restart %s to complete</source>
<translation>Wallet needed to be rewritten: restart %s to complete</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>Error: Listening for incoming connections failed (listen returned error %s)</translation>
</message>
<message>
<source>The transaction amount is too small to send after the fee has been deducted</source>
<translation>The transaction amount is too small to send after the fee has been deducted</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source>
<translation>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Error reading from database, shutting down.</translation>
</message>
<message>
<source>Error upgrading chainstate database</source>
<translation>Error upgrading chainstate database</translation>
</message>
<message>
<source>Error: Disk space is low for %s</source>
<translation>Lỗi: Đĩa trống ít quá cho %s</translation>
</message>
<message>
<source>Invalid -onion address or hostname: '%s'</source>
<translation>Invalid -onion address or hostname: '%s'</translation>
</message>
<message>
<source>Invalid -proxy address or hostname: '%s'</source>
<translation>Invalid -proxy address or hostname: '%s'</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>Invalid netmask specified in -whitelist: '%s'</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>Need to specify a port with -whitebind: '%s'</translation>
</message>
<message>
<source>Prune mode is incompatible with -blockfilterindex.</source>
<translation>Chế độ prune không tương thích với -blockfilterindex.</translation>
</message>
<message>
<source>Reducing -maxconnections from %d to %d, because of system limitations.</source>
<translation>Reducing -maxconnections from %d to %d, because of system limitations.</translation>
</message>
<message>
<source>Section [%s] is not recognized.</source>
<translation>Mục [%s] không được nhìn nhận.</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Signing transaction failed</translation>
</message>
<message>
<source>Specified -walletdir "%s" does not exist</source>
<translation>Thư mục ví được nêu -walletdir "%s" không tồn tại</translation>
</message>
<message>
<source>Specified -walletdir "%s" is a relative path</source>
<translation>Chỉ định -walletdir "%s" là đường dẫn tương đối</translation>
</message>
<message>
<source>Specified -walletdir "%s" is not a directory</source>
<translation>Chỉ định -walletdir "%s" không phải là một thư mục</translation>
</message>
<message>
<source>The specified config file %s does not exist
</source>
<translation>Tệp cấu hình đã chỉ định %s không tồn tại
</translation>
</message>
<message>
<source>The transaction amount is too small to pay the fee</source>
<translation>The transaction amount is too small to pay the fee</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>This is experimental software.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Transaction amount too small</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Transaction too large</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>Unable to bind to %s on this computer (bind returned error %s)</translation>
</message>
<message>
<source>Unable to create the PID file '%s': %s</source>
<translation>Không thể tạo tệp PID '%s': %s</translation>
</message>
<message>
<source>Unable to generate initial keys</source>
<translation>Không thể tạo khóa ban đầu</translation>
</message>
<message>
<source>Unknown -blockfilterindex value %s.</source>
<translation>Không rõ giá trị -blockfilterindex %s.</translation>
</message>
<message>
<source>Verifying wallet(s)...</source>
<translation>Verifying wallet(s)...</translation>
</message>
<message>
<source>Warning: unknown new rules activated (versionbit %i)</source>
<translation>Warning: unknown new rules activated (versionbit %i)</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Zapping all transactions from wallet...</translation>
</message>
<message>
<source>This is the transaction fee you may pay when fee estimates are not available.</source>
<translation>This is the transaction fee you may pay when fee estimates are not available.</translation>
</message>
<message>
<source>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</source>
<translation>Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.</translation>
</message>
<message>
<source>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Warning: Wallet file corrupt, data salvaged! Original %s saved as %s in %s; if your balance or transactions are incorrect you should restore from a backup.</translation>
</message>
<message>
<source>%s is set very high!</source>
<translation>%s is set very high!</translation>
</message>
<message>
<source>Error loading wallet %s. Duplicate -wallet filename specified.</source>
<translation>Error loading wallet %s. Duplicate -wallet filename specified.</translation>
</message>
<message>
<source>Starting network threads...</source>
<translation>Starting network threads...</translation>
</message>
<message>
<source>The wallet will avoid paying less than the minimum relay fee.</source>
<translation>Wallet sẽ hủy thanh toán nhỏ hơn phí relay.</translation>
</message>
<message>
<source>This is the minimum transaction fee you pay on every transaction.</source>
<translation>Đây là minimum transaction fee bạn pay cho mỗi transaction.</translation>
</message>
<message>
<source>This is the transaction fee you will pay if you send a transaction.</source>
<translation>Đây là transaction fee bạn sẽ pay nếu gửi transaction.</translation>
</message>
<message>
<source>Transaction amounts must not be negative</source>
<translation>Transaction amounts phải không âm</translation>
</message>
<message>
<source>Transaction has too long of a mempool chain</source>
<translation>Transaction có chuỗi mempool chain quá dài</translation>
</message>
<message>
<source>Transaction must have at least one recipient</source>
<translation>Transaction phải có ít nhất một người nhận</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Unknown network được xác định trong -onlynet: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Không đủ tiền</translation>
</message>
<message>
<source>Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified.</source>
<translation>Không thể nâng cấp một địa chỉ HD tách rời mà không nâng cấp hỗ trợ keypool tách rời trước. Làm ơn dùng upgradewallet=169900 hoặc -upgradewallet với không có chỉ ra phiên bản.</translation>
</message>
<message>
<source>Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.</source>
<translation>Dự toán phí không thành công. Fallbackfee bị vô hiệu hóa. Đợi sau một vài khối hoặc kích hoạt -fallbackfee.</translation>
</message>
<message>
<source>Warning: Private keys detected in wallet {%s} with disabled private keys</source>
<translation>Cảnh báo: các khóa riêng tư được tìm thấy trong ví {%s} với khóa riêng tư không kích hoạt</translation>
</message>
<message>
<source>Cannot write to data directory '%s'; check permissions.</source>
<translation>Không thể ghi vào thư mục dữ liệu '%s'; kiểm tra lại quyền.</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Đang tải block index...</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Loading wallet...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Không thể downgrade wallet</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Rescanning...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Done loading</translation>
</message>
</context>
</TS> | mit |
katsuroo/trustroots | public/modules/core/controllers/footer.client.controller.js | 2487 | 'use strict';
angular.module('core').controller('FooterController', ['$scope', 'Authentication', 'Menus',
function($scope, Authentication, Menus) {
$scope.isTransparent = false;
$scope.isHidden = false;
$scope.photo_credits = [];
/*
* Please try to keep this updated while you add/change/remove images from different pages
*/
var photos = {
'bokehblue': {
'name': 'Sandra',
'url': 'https://www.flickr.com/photos/artfullife/3589991695',
'license': 'CC',
'license_url': 'https://creativecommons.org/licenses/by-sa/2.0/'
},
'sierranevada': {
'name': 'Simona',
'url': 'http://www.wanderlust.lt',
'license': 'CC',
'license_url': 'http://creativecommons.org/licenses/by-nc-nd/4.0/'
},
'hitchroad': {
'name': 'Andrew W Bugelli',
'url': 'http://www.containstraces.blogspot.com/'
},
'forestpath': {
'name': 'Johnson',
'url': 'https://www.flickr.com/photos/54459164@N00/15506455245',
'license': 'CC',
'license_url': 'https://creativecommons.org/licenses/by-nc-sa/2.0/'
},
'horizonballoon': {
'name': 'Wesley Stanford',
'url': 'http://www.dualhorizons.blogspot.co.uk/'
}
};
// Changing footer styles/contents after navigation
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
$scope.isTransparent = (['home', 'forgot', 'signin', 'welcome'].indexOf(toState.name) > -1) ? true : false;
$scope.isHidden = (['listMessages', 'search'].indexOf(toState.name) > -1) ? true : false;
// Set photo credits for this page
if( ['home'].indexOf(toState.name) > -1 ) {
$scope.photo_credits = [ photos.sierranevada, photos.hitchroad ];
}
else if( ['forgot', 'signin', 'welcome', 'statistics', 'media'].indexOf(toState.name) > -1 ) {
$scope.photo_credits = [ photos.bokehblue ];
}
else if( ['about'].indexOf(toState.name) > -1 ) {
$scope.photo_credits = [ photos.bokehblue, photos.forestpath ];
}
else if( ['foundation', 'donate', 'donate-help', 'donate-policy'].indexOf(toState.name) > -1 ) {
$scope.photo_credits = [ photos.forestpath ];
}
else if( ['faq'].indexOf(toState.name) > -1 ) {
$scope.photo_credits = [ photos.horizonballoon ];
}
else {
$scope.photo_credits = [];
}
});
}
]);
| mit |
sparkoo/boxitory | src/main/java/cz/sparko/boxitory/service/filesystem/BoxPathType.java | 98 | package cz.sparko.boxitory.service.filesystem;
public enum BoxPathType {
RAW,
BOXITORY
}
| mit |
dawidfiruzek/dagger2-mvp-example | app/src/test/java/pl/dawidfiruzek/dagger2mvpexample/ExampleUnitTest.java | 326 | package pl.dawidfiruzek.dagger2mvpexample;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
nodeGame/nodegame-widgets | widgets/DebugWall.js | 11165 | /**
* # DebugWall
* Copyright(c) 2021 Stefano Balietti
* MIT Licensed
*
* Creates a wall where all incoming and outgoing messages are printed
*
* www.nodegame.org
*/
(function(node) {
"use strict";
node.widgets.register('DebugWall', DebugWall);
// ## Meta-data
DebugWall.version = '1.1.0';
DebugWall.description = 'Intercepts incoming and outgoing messages, and ' +
'logs and prints them numbered and timestamped. Warning! Modifies ' +
'core functions, therefore its usage in production is ' +
'not recommended.';
DebugWall.title = 'Debug Wall';
DebugWall.className = 'debugwall';
// ## Dependencies
DebugWall.dependencies = {
JSUS: {}
};
/**
* ## DebugWall constructor
*
* Creates a new DebugWall oject
*/
function DebugWall() {
/**
* ### DebugWall.buttonsDiv
*
* Div contains controls for the display info inside the wall.
*/
this.buttonsDiv = null;
/**
* ### DebugWall.hidden
*
* Keep tracks of what is hidden in the wall
*/
this.hiddenTypes = {};
/**
* ### DebugWall.counterIn
*
* Counts number of incoming message printed on wall
*/
this.counterIn = 0;
/**
* ### DebugWall.counterOut
*
* Counts number of outgoing message printed on wall
*/
this.counterOut = 0;
/**
* ### DebugWall.counterLog
*
* Counts number of log entries printed on wall
*/
this.counterLog = 0;
/**
* ### DebugWall.wall
*
* The table element in which to write
*/
this.wall = null;
/**
* ### DebugWall.wallDiv
*
* The div element containing the wall (for scrolling)
*/
this.wallDiv = null;
/**
* ### DebugWall.origMsgInCb
*
* The original function that receives incoming msgs
*/
this.origMsgInCb = null;
/**
* ### DebugWall.origMsgOutCb
*
* The original function that sends msgs
*/
this.origMsgOutCb = null;
/**
* ### DebugWall.origLogCb
*
* The original log callback
*/
this.origLogCb = null;
}
// ## DebugWall methods
/**
* ### DebugWall.init
*
* Initializes the instance
*
* @param {object} opts Optional. Configuration options
*
* - msgIn: If FALSE, incoming messages are ignored.
* - msgOut: If FALSE, outgoing messages are ignored.
* - log: If FALSE, log messages are ignored.
* - hiddenTypes: An object containing what is currently hidden
* in the wall.
*/
DebugWall.prototype.init = function(opts) {
var that;
that = this;
if (opts.msgIn !== false) {
this.origMsgInCb = node.socket.onMessage;
node.socket.onMessage = function(msg) {
that.write('in', that.makeTextIn(msg));
that.origMsgInCb.call(node.socket, msg);
};
}
if (opts.msgOut !== false) {
this.origMsgOutCb = node.socket.send;
node.socket.send = function(msg) {
that.write('out', that.makeTextOut(msg));
that.origMsgOutCb.call(node.socket, msg);
};
}
if (opts.log !== false) {
this.origLogCb = node.log;
node.log = function(txt, level, prefix) {
that.write(level || 'info',
that.makeTextLog(txt, level, prefix));
that.origLogCb.call(node, txt, level, prefix);
};
}
if (opts.hiddenTypes) {
if ('object' !== typeof opts.hiddenTypes) {
throw new TypeError('DebugWall.init: hiddenTypes must be ' +
'object. Found: ' + opts.hiddenTypes);
}
this.hiddenTypes = opts.hiddenTypes;
}
this.on('destroyed', function() {
if (that.origLogCb) node.log = that.origLogCb;
if (that.origMsgOutCb) node.socket.send = that.origMsgOutCb;
if (that.origMsgInCb) node.socket.onMessage = that.origMsgInCb;
});
};
DebugWall.prototype.append = function() {
var displayIn, displayOut, displayLog, that;
var btnGroup, cb;
this.buttonsDiv = W.add('div', this.bodyDiv, {
className: 'wallbuttonsdiv'
});
btnGroup = W.add('div', this.buttonsDiv, {
className: 'btn-group',
role: 'group',
'aria-label': 'Toggle visibility of messages on wall'
});
// Incoming.
W.add('input', btnGroup, {
id: 'debug-wall-incoming',
// name: 'debug-wall-check',
className: 'btn-check',
autocomplete: "off",
checked: true,
type: 'checkbox'
});
displayIn = W.add('label', btnGroup, {
className: "btn btn-outline-primary",
'for': "debug-wall-incoming",
innerHTML: 'Incoming'
});
// Outgoing.
W.add('input', btnGroup, {
id: 'debug-wall-outgoing',
className: 'btn-check',
// name: 'debug-wall-check',
autocomplete: "off",
checked: true,
type: 'checkbox'
});
displayOut = W.add('label', btnGroup, {
className: "btn btn-outline-primary",
'for': "debug-wall-outgoing",
innerHTML: 'Outgoing'
});
// Log.
W.add('input', btnGroup, {
id: 'debug-wall-log',
className: 'btn-check',
// name: 'debug-wall-check',
autocomplete: "off",
checked: true,
type: 'checkbox'
});
displayLog = W.add('label', btnGroup, {
className: "btn btn-outline-primary",
'for': "debug-wall-log",
innerHTML: 'Log'
});
that = this;
W.add('button', this.buttonsDiv, {
className: "btn btn-outline-danger me-2",
innerHTML: 'Clear'
})
.onclick = function() { that.clear(); };
this.buttonsDiv.appendChild(btnGroup);
cb = function(type) {
var items, i, vis, className;
className = 'wall_' + type;
items = that.wall.getElementsByClassName(className);
if (!items || !items.length) return;
vis = items[0].style.display === '' ? 'none' : '';
for (i = 0; i < items.length; i++) {
items[i].style.display = vis;
}
that.hiddenTypes[type] = !!vis;
};
displayIn.onclick = function() { cb('in'); };
displayOut.onclick = function() { cb('out'); };
displayLog.onclick = function() { cb('log'); };
this.wallDiv = W.add('div', this.bodyDiv, { className: 'walldiv' });
this.wall = W.add('table', this.wallDiv);
};
/**
* ### DebugWall.write
*
* Writes argument as first entry of this.wall if document is fully loaded
*
* @param {string} type 'in', 'out', or 'log' (different levels)
* @param {string} text The text to write
*/
DebugWall.prototype.shouldHide = function(type) {
return this.hiddenTypes[type];
};
/**
* ### DebugWall.write
*
* Writes argument as first entry of this.wall if document is fully loaded
*
* @param {string} type 'in', 'out', or 'log' (different levels)
* @param {string} text The text to write
*/
DebugWall.prototype.clear = function() {
this.wall.innerHTML = '';
};
/**
* ### DebugWall.write
*
* Writes argument as first entry of this.wall if document is fully loaded
*
* @param {string} type 'in', 'out', or 'log' (different levels)
* @param {string} text The text to write
*/
DebugWall.prototype.write = function(type, text) {
var spanContainer, spanDots, spanExtra, counter, className;
var limit;
var TR, TDtext;
if (this.isAppended()) {
counter = type === 'in' ? ++this.counterIn :
(type === 'out' ? ++this.counterOut : ++this.counterLog);
limit = 200;
className = 'wall_' + type;
TR = W.add('tr', this.wall, { className: className });
if (type !== 'in' && type !== 'out') TR.className += ' wall_log';
if (this.shouldHide(type, text)) TR.style.display = 'none';
W.add('td', TR, { innerHTML: counter });
W.add('td', TR, { innerHTML: type });
W.add('td', TR, { innerHTML: J.getTimeM()});
TDtext = W.add('td', TR);
if (text.length > limit) {
spanContainer = W.add('span', TDtext, {
className: className + '_click' ,
innerHTML: text.substr(0, limit)
});
spanExtra = W.add('span', spanContainer, {
className: className + '_extra',
innerHTML: text.substr(limit, text.length),
id: 'wall_' + type + '_' + counter,
style: { display: 'none' }
});
spanDots = W.add('span', spanContainer, {
className: className + '_dots',
innerHTML: ' ...',
id: 'wall_' + type + '_' + counter
});
spanContainer.onclick = function() {
if (spanDots.style.display === 'none') {
spanDots.style.display = '';
spanExtra.style.display = 'none';
}
else {
spanDots.style.display = 'none';
spanExtra.style.display = '';
}
};
}
else {
spanContainer = W.add('span', TDtext, {
innerHTML: text
});
}
this.wallDiv.scrollTop = this.wallDiv.scrollHeight;
}
else {
node.warn('Wall not appended, cannot write.');
}
};
DebugWall.prototype.makeTextIn = function(msg) {
var text, d;
d = new Date(msg.created);
text = d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() +
':' + d.getMilliseconds();
text += ' | ' + msg.to + ' | ' + msg.target +
' | ' + msg.action + ' | ' + msg.text + ' | ' + msg.data;
return text;
};
DebugWall.prototype.makeTextOut = function(msg) {
var text;
text = msg.from + ' | ' + msg.target + ' | ' + msg.action + ' | ' +
msg.text + ' | ' + msg.data;
return text;
};
DebugWall.prototype.makeTextLog = function(text) {
return text;
};
})(node);
| mit |
chuyik/TeamNotes | app/models/knowledge.rb | 217 | class Knowledge < ActiveRecord::Base
has_many :comments, :dependent => :destroy
accepts_nested_attributes_for :comments, allow_destroy: true
validates :title, presence: true
validates :content, presence: true
end
| mit |
youmi/nativead | YMNativeAdS-android/library/src/main/java/net/youmi/ads/base/download/store/AbsDownloadDir.java | 7050 | package net.youmi.ads.base.download.store;
import net.youmi.ads.base.download.model.FileDownloadTask;
import net.youmi.ads.base.log.DLog;
import net.youmi.ads.base.utils.FileUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
/**
* @author zhitao
* @since 2017-04-14 15:21
*/
public abstract class AbsDownloadDir {
/**
* 不限制所有文件的缓存 总体积
*/
public static final long UN_LIMT_STORE_SIZE = -1;
/**
* 不限制每个文件的缓存时间
*/
public static final long UN_LIMT_STORE_TIME = -1;
/**
* 每个文件缓存的时间
*/
private long mDirPerFileCacheTime_ms = UN_LIMT_STORE_TIME;
/**
* 所有缓存文件的总体积
*/
private long mDirMaxCacheSize_KB = UN_LIMT_STORE_SIZE;
/**
* 文件缓存目录
*/
private File mCacheDir;
/**
* @param dir 目录位置
* @param dirMaxCacheSize_KB 全部文件的最大限制大小 (KB) 传入{@link #UN_LIMT_STORE_SIZE} 表示不限制目录缓存总体积
* @param dirPerFileCacheTime_ms 每个文件的缓存时间 (ms) 传入{@link #UN_LIMT_STORE_TIME} 表示不限制每个文件的缓存时间
*/
public AbsDownloadDir(File dir, long dirMaxCacheSize_KB, long dirPerFileCacheTime_ms) {
mCacheDir = dir;
mDirMaxCacheSize_KB = dirMaxCacheSize_KB;
mDirPerFileCacheTime_ms = dirPerFileCacheTime_ms;
}
/**
* @param dirPath 目录路径地址
* @param dirMaxCacheSize_KB 全部文件的最大限制大小 (KB) 传入{@link #UN_LIMT_STORE_SIZE} 标识不限制目录缓存总体积
* @param dirPerFileCacheTime_ms 每个文件的缓存时间 (ms) 传入{@link #UN_LIMT_STORE_TIME} 标识不限制每个文件的缓存时间
*/
public AbsDownloadDir(String dirPath, long dirMaxCacheSize_KB, long dirPerFileCacheTime_ms) {
this(new File(dirPath), dirMaxCacheSize_KB, dirPerFileCacheTime_ms);
}
/**
* @return 检查存放目录以及传入参数是否有效
*/
public boolean isDirValid() {
if (mCacheDir == null) {
return false;
}
if (mCacheDir.exists() && !mCacheDir.isDirectory()) {
return false;
}
// 检查文件夹是否存在,如果不存在,重新建立文件夹
if (!mCacheDir.exists() && !mCacheDir.mkdirs()) {
return false;
}
if (mDirMaxCacheSize_KB <= 0 && mDirMaxCacheSize_KB != UN_LIMT_STORE_SIZE) {
return false;
}
if (mDirPerFileCacheTime_ms <= 0 && mDirPerFileCacheTime_ms != UN_LIMT_STORE_SIZE) {
return false;
}
return true;
}
/**
* 根据下载任务对象来生成缓存文件的文件名,规则可随意
* <p>
* e.g.
* <p>
* new File(md5(url)+".cache");
*
* @param fileDownloadTask 下载任务
*
* @return 缓存文件
*/
public abstract File newDownloadTempFile(FileDownloadTask fileDownloadTask);
/**
* 根据下载任务对象来生成最终下载完成的文件的文件名,规则可随意
* <p>
* e.g.
* <p>
* new File(md5(url));
*
* @param fileDownloadTask 下载任务
*
* @return 最终存储的下载文件
*/
public abstract File newDownloadStoreFile(FileDownloadTask fileDownloadTask);
/**
* @return 下载文件目录
*/
public File getDir() {
return mCacheDir;
}
/**
* 优化传入来的目录
* <ol>
* <li>根据缓存时间,将已经超过缓存时间的文件进行删除</li>
* <li>检查当前目录的总体积是否还是超过最大限制大小,如果是的话,在根据文件的最后编辑时间排序,将最久的文件删除,直至当前目录总体积小于限制体积</li>
* </ol>
* 目前有个取舍的问题:
* 为了防止删除太久,会设置一个定时器10000,也就是说如果目录里面有超过10000个文件的话,那么最多可能删除10000个文件,
* 如果删除了10000个文件还是不能满足最大限制要求,那么也会停止
*
* @return <ul>
* <li>true:优化成功</li>
* <li>false:优化失败</li>
* </ul>
*/
public boolean optDir() {
// 如果不限制的话,那么就返回已经优化成功
if (mDirMaxCacheSize_KB == UN_LIMT_STORE_SIZE && mDirPerFileCacheTime_ms == UN_LIMT_STORE_TIME) {
return true;
}
try {
// 获取当前目录的所有文件列表
File[] files = mCacheDir.listFiles();
if (files == null || files.length == 0) {
return true;
}
// 所有文件的总长度
long countLen = 0;
// 用于收集还没有超过缓存时间的文件待排序列表
List<File> fileList = new ArrayList<>();
// 将已经超过缓存时间的文件删除,同时收集剩下的文件
for (File file : files) {
if (file == null || !file.exists()) {
continue;
}
// 1. 先检查有没有超期了,文件超期就删除
if (isFileTimeOut(file)) {
FileUtils.delete(file);
continue;
}
// 2. 如果这个目录设置了总体积限制,那么就要收集没有超时的文件
// 只有需要检查目录大小的情况下才需要计算文件大小,以及把文件放入待排序列表中
if (mDirMaxCacheSize_KB != UN_LIMT_STORE_SIZE) {
countLen += file.length();// 文件未超期或未被删除,就用来检查总容量
fileList.add(file);// 加入到待排序列表中
}
}
// 按lastModify进行,从旧到新
Collections.sort(fileList, new FileLastModifyCom());// 这里需要添加排序算法
// 使用链接将文件进行排序,文件比较旧的排在前面,如果超过目录缓存的总大小,删除排在前面的文件。
Iterator<File> iterator = fileList.iterator();
if (DLog.isDownloadLog) {
DLog.i("准备删除旧的但未过时的文件");
}
int a = 10000;
// 如果剩余文件长度大于限制长度,就需要不断循环删除
while (countLen > mDirMaxCacheSize_KB && iterator.hasNext()) {
try {
File gfFile = iterator.next();
iterator.remove();
countLen -= gfFile.length();
FileUtils.delete(gfFile);
} catch (Throwable e) {
DLog.e(e);
}
--a;
if (a < 0) {
// 防止死循环
break;
}
}
return true;
} catch (Throwable e) {
DLog.e(e);
}
return false;
}
/**
* 检查当前目录的指定文件是否已经超过缓存时间
*
* @param file 待检测文件
*
* @return true: 超时; false:还没有超时
*/
private boolean isFileTimeOut(File file) {
if (file == null) {
return false;
}
if (mDirPerFileCacheTime_ms == UN_LIMT_STORE_TIME) {
return false;
}
if (System.currentTimeMillis() - file.lastModified() > mDirPerFileCacheTime_ms) {
return true;
}
return false;
}
private static class FileLastModifyCom implements Comparator<File> {
@Override
public int compare(File lhs, File rhs) {
try {
if (lhs.lastModified() < rhs.lastModified()) {
return -1;
}
return 1;
} catch (Throwable e) {
DLog.e(e);
}
return 0;
}
}
}
| mit |
david-leal/nau | head/src/nau/render/opengl/glUniform.cpp | 18663 | #include "nau.h"
#include "nau/slogger.h"
#include "nau/render/opengl/glUniform.h"
using namespace nau::render;
std::map<GLenum, std::string> GLUniform::spGLSLType;
//std::map<int, int> GLUniform::spGLSLTypeSize;
std::map<GLenum, Enums::DataType> GLUniform::spSimpleType;
bool GLUniform::Inited = Init();
GLUniform::GLUniform() :
m_Loc(-1),
m_Size(0),
m_Cardinality(0)
{
}
GLUniform::~GLUniform() {
}
void
GLUniform::reset() {
m_Loc = -1;
}
int
GLUniform::getCardinality() {
return (m_Cardinality);
}
void
GLUniform::setValues(void *v) {
switch (m_SimpleType) {
case Enums::INT :
case Enums::BOOL:
case Enums::FLOAT:
case Enums::UINT:
case Enums::SAMPLER:
case Enums::DOUBLE:
memcpy(m_Values.get(), v, m_Size);
break;
default:
memcpy(m_Values.get(), ((Data *)v)->getPtr(), m_Size);
}
}
void
GLUniform::setArrayValue(int index, void *v) {
// memcpy(m_Values + (Enums::getSize(m_SimpleType) * index), v, Enums::getSize(m_SimpleType));
}
void*
GLUniform::getValues(void) {
return m_Values.get();
}
int
GLUniform::getLoc(void) {
return m_Loc;
}
void
GLUniform::setLoc(int loc) {
m_Loc = loc;
}
int
GLUniform::getArraySize(void) {
return m_ArraySize;
}
void
GLUniform::setGLType(int type, int arraySize) {
if (type != 0 && spSimpleType.count((GLenum)type) == 0)
SLOG("%d - gluniform.cpp - uniform type not supported in NAU", type);
m_GLType = type;
m_SimpleType = spSimpleType[(GLenum)type];
m_ArraySize = arraySize;
m_Size = Enums::getSize(m_SimpleType) * m_ArraySize;
m_Cardinality = Enums::getCardinality(m_SimpleType);
char *c = (char *)malloc(m_Size);
m_Values.reset(c);
//m_Values = (void *)malloc(m_Size);
}
int
GLUniform::getGLType() {
return (m_GLType);
}
std::string
GLUniform::getStringGLType() {
return spGLSLType[(GLenum)m_GLType];
}
void
GLUniform::setValueInProgram() {
switch (m_SimpleType) {
// inst, bools and samplers
case Enums::INT:
case Enums::BOOL:
case Enums::SAMPLER:
glUniform1iv(m_Loc, m_ArraySize, (GLint *)m_Values.get());
break;
case Enums::IVEC2:
case Enums::BVEC2:
glUniform2iv(m_Loc, m_ArraySize, (GLint *)m_Values.get());
break;
case Enums::IVEC3:
case Enums::BVEC3:
glUniform3iv(m_Loc, m_ArraySize, (GLint *)m_Values.get());
break;
case Enums::IVEC4:
case Enums::BVEC4:
glUniform4iv(m_Loc, m_ArraySize, (GLint *)m_Values.get());
break;
// unsigned ints
case Enums::UINT:
glUniform1uiv(m_Loc, m_ArraySize, (GLuint *)m_Values.get());
break;
case Enums::UIVEC2:
glUniform2uiv(m_Loc, m_ArraySize, (GLuint *)m_Values.get());
break;
case Enums::UIVEC3:
glUniform3uiv(m_Loc, m_ArraySize, (GLuint *)m_Values.get());
break;
case Enums::UIVEC4:
glUniform4uiv(m_Loc, m_ArraySize, (GLuint *)m_Values.get());
break;
// floats
case Enums::FLOAT:
glUniform1fv(m_Loc, m_ArraySize, (GLfloat *)m_Values.get());
break;
case Enums::VEC2:
glUniform2fv(m_Loc, m_ArraySize, (GLfloat *)m_Values.get());
break;
case Enums::VEC3:
glUniform3fv(m_Loc, m_ArraySize, (GLfloat *)m_Values.get());
break;
case Enums::VEC4:
glUniform4fv(m_Loc, m_ArraySize, (GLfloat *)m_Values.get());
break;
// doubles
case Enums::DOUBLE:
glUniform1dv(m_Loc, m_ArraySize, (GLdouble *)m_Values.get());
break;
case Enums::DVEC2:
glUniform2dv(m_Loc, m_ArraySize, (GLdouble *)m_Values.get());
break;
case Enums::DVEC3:
glUniform3dv(m_Loc, m_ArraySize, (GLdouble *)m_Values.get());
break;
case Enums::DVEC4:
glUniform4dv(m_Loc, m_ArraySize, (GLdouble *)m_Values.get());
break;
// float matrices
case Enums::MAT2:
glUniformMatrix2fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT3:
glUniformMatrix3fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT4:
glUniformMatrix4fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT2x3:
glUniformMatrix2x3fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT2x4:
glUniformMatrix2x4fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT3x2:
glUniformMatrix3x2fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
case Enums::MAT3x4:
glUniformMatrix3x4fv(m_Loc, m_ArraySize, GL_FALSE, (GLfloat *)m_Values.get());
break;
// double matrices
case Enums::DMAT2:
glUniformMatrix2dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT3:
glUniformMatrix3dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT4:
glUniformMatrix4dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT2x3:
glUniformMatrix2x3dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT2x4:
glUniformMatrix2x4dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT3x2:
glUniformMatrix3x2dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
case Enums::DMAT3x4:
glUniformMatrix3x4dv(m_Loc, m_ArraySize, GL_FALSE, (GLdouble *)m_Values.get());
break;
default:
assert(false && "missing data types in switch statement");
}
}
bool
GLUniform::Init() {
spSimpleType[GL_SAMPLER_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_1D_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_1D_ARRAY_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_ARRAY_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_CUBE_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_SAMPLER_2D_RECT_SHADOW] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_SAMPLER_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_SAMPLER_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_IMAGE_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_1D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_2D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_3D] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_2D_RECT] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_CUBE] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_BUFFER] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_1D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_2D_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE] = Enums::DataType::SAMPLER;
spSimpleType[GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY] = Enums::DataType::SAMPLER;
spSimpleType[GL_BOOL] = Enums::DataType::BOOL;
spSimpleType[GL_BOOL_VEC2] = Enums::DataType::BVEC2;
spSimpleType[GL_BOOL_VEC3] = Enums::DataType::BVEC3;
spSimpleType[GL_BOOL_VEC4] = Enums::DataType::BVEC4;
spSimpleType[GL_INT] = Enums::DataType::INT;
spSimpleType[GL_INT_VEC2] = Enums::DataType::IVEC2;
spSimpleType[GL_INT_VEC3] = Enums::DataType::IVEC3;
spSimpleType[GL_INT_VEC4] = Enums::DataType::IVEC4;
spSimpleType[GL_UNSIGNED_INT] = Enums::DataType::UINT;
spSimpleType[GL_UNSIGNED_INT_VEC2] = Enums::DataType::UIVEC2;
spSimpleType[GL_UNSIGNED_INT_VEC3] = Enums::DataType::UIVEC3;
spSimpleType[GL_UNSIGNED_INT_VEC4] = Enums::DataType::UIVEC4;
spSimpleType[GL_FLOAT] = Enums::DataType::FLOAT;
spSimpleType[GL_FLOAT_VEC2] = Enums::DataType::VEC2;
spSimpleType[GL_FLOAT_VEC3] = Enums::DataType::VEC3;
spSimpleType[GL_FLOAT_VEC4] = Enums::DataType::VEC4;
spSimpleType[GL_FLOAT_MAT2] = Enums::DataType::MAT2;
spSimpleType[GL_FLOAT_MAT3] = Enums::DataType::MAT3;
spSimpleType[GL_FLOAT_MAT4] = Enums::DataType::MAT4;
spSimpleType[GL_FLOAT_MAT2x3] = Enums::DataType::MAT2x3;
spSimpleType[GL_FLOAT_MAT2x4] = Enums::DataType::MAT2x4;
spSimpleType[GL_FLOAT_MAT3x2] = Enums::DataType::MAT3x2;
spSimpleType[GL_FLOAT_MAT3x4] = Enums::DataType::MAT3x4;
spSimpleType[GL_FLOAT_MAT4x2] = Enums::DataType::MAT4x2;
spSimpleType[GL_FLOAT_MAT4x3] = Enums::DataType::MAT4x3;
spSimpleType[GL_DOUBLE] = Enums::DataType::DOUBLE;
spSimpleType[GL_DOUBLE_VEC2] = Enums::DataType::DVEC2;
spSimpleType[GL_DOUBLE_VEC3] = Enums::DataType::DVEC3;
spSimpleType[GL_DOUBLE_VEC4] = Enums::DataType::DVEC4;
spSimpleType[GL_DOUBLE_MAT2] = Enums::DataType::DMAT2;
spSimpleType[GL_DOUBLE_MAT3] = Enums::DataType::DMAT3;
spSimpleType[GL_DOUBLE_MAT4] = Enums::DataType::DMAT4;
spSimpleType[GL_DOUBLE_MAT2x3] = Enums::DataType::DMAT2x3;
spSimpleType[GL_DOUBLE_MAT2x4] = Enums::DataType::DMAT2x4;
spSimpleType[GL_DOUBLE_MAT3x2] = Enums::DataType::DMAT3x2;
spSimpleType[GL_DOUBLE_MAT3x4] = Enums::DataType::DMAT3x4;
spSimpleType[GL_DOUBLE_MAT4x2] = Enums::DataType::DMAT4x2;
spSimpleType[GL_DOUBLE_MAT4x3] = Enums::DataType::DMAT4x3;
//
spGLSLType[GL_FLOAT] = "GL_FLOAT";
spGLSLType[GL_FLOAT_VEC2] = "GL_FLOAT_VEC2";
spGLSLType[GL_FLOAT_VEC3] = "GL_FLOAT_VEC3";
spGLSLType[GL_FLOAT_VEC4] = "GL_FLOAT_VEC4";
spGLSLType[GL_DOUBLE] = "GL_DOUBLE";
spGLSLType[GL_DOUBLE_VEC2] = "GL_DOUBLE_VEC2";
spGLSLType[GL_DOUBLE_VEC3] = "GL_DOUBLE_VEC3";
spGLSLType[GL_DOUBLE_VEC4] = "GL_DOUBLE_VEC4";
spGLSLType[GL_BOOL] = "GL_BOOL";
spGLSLType[GL_BOOL_VEC2] = "GL_BOOL_VEC2";
spGLSLType[GL_BOOL_VEC3] = "GL_BOOL_VEC3";
spGLSLType[GL_BOOL_VEC4] = "GL_BOOL_VEC4";
spGLSLType[GL_INT] = "GL_INT";
spGLSLType[GL_INT_VEC2] = "GL_INT_VEC2";
spGLSLType[GL_INT_VEC3] = "GL_INT_VEC3";
spGLSLType[GL_INT_VEC4] = "GL_INT_VEC4";
spGLSLType[GL_UNSIGNED_INT] = "GL_UNSIGNED_INT";
spGLSLType[GL_UNSIGNED_INT_VEC2] = "GL_UNSIGNED_INT_VEC2";
spGLSLType[GL_UNSIGNED_INT_VEC3] = "GL_UNSIGNED_INT_VEC3";
spGLSLType[GL_UNSIGNED_INT_VEC4] = "GL_UNSIGNED_INT_VEC4";
spGLSLType[GL_FLOAT_MAT2] = "GL_FLOAT_MAT2";
spGLSLType[GL_FLOAT_MAT3] = "GL_FLOAT_MAT3";
spGLSLType[GL_FLOAT_MAT4] = "GL_FLOAT_MAT4";
spGLSLType[GL_FLOAT_MAT2x3] = "GL_FLOAT_MAT2x3";
spGLSLType[GL_FLOAT_MAT2x4] = "GL_FLOAT_MAT2x4";
spGLSLType[GL_FLOAT_MAT3x2] = "GL_FLOAT_MAT3x2";
spGLSLType[GL_FLOAT_MAT3x4] = "GL_FLOAT_MAT3x4";
spGLSLType[GL_FLOAT_MAT4x2] = "GL_FLOAT_MAT4x2";
spGLSLType[GL_FLOAT_MAT4x3] = "GL_FLOAT_MAT4x3";
spGLSLType[GL_DOUBLE_MAT2] = "GL_DOUBLE_MAT2";
spGLSLType[GL_DOUBLE_MAT3] = "GL_DOUBLE_MAT3";
spGLSLType[GL_DOUBLE_MAT4] = "GL_DOUBLE_MAT4";
spGLSLType[GL_DOUBLE_MAT2x3] = "GL_DOUBLE_MAT2x3";
spGLSLType[GL_DOUBLE_MAT2x4] = "GL_DOUBLE_MAT2x4";
spGLSLType[GL_DOUBLE_MAT3x2] = "GL_DOUBLE_MAT3x2";
spGLSLType[GL_DOUBLE_MAT3x4] = "GL_DOUBLE_MAT3x4";
spGLSLType[GL_DOUBLE_MAT4x2] = "GL_DOUBLE_MAT4x2";
spGLSLType[GL_DOUBLE_MAT4x3] = "GL_DOUBLE_MAT4x3";
spGLSLType[GL_SAMPLER_1D] = "GL_SAMPLER_1D";
spGLSLType[GL_SAMPLER_2D] = "GL_SAMPLER_2D";
spGLSLType[GL_SAMPLER_3D] = "GL_SAMPLER_3D";
spGLSLType[GL_SAMPLER_CUBE] = "GL_SAMPLER_CUBE";
spGLSLType[GL_SAMPLER_1D_SHADOW] = "GL_SAMPLER_1D_SHADOW";
spGLSLType[GL_SAMPLER_2D_SHADOW] = "GL_SAMPLER_2D_SHADOW";
spGLSLType[GL_SAMPLER_1D_ARRAY] = "GL_SAMPLER_1D_ARRAY";
spGLSLType[GL_SAMPLER_2D_ARRAY] = "GL_SAMPLER_2D_ARRAY";
spGLSLType[GL_SAMPLER_1D_ARRAY_SHADOW] = "GL_SAMPLER_1D_ARRAY_SHADOW";
spGLSLType[GL_SAMPLER_2D_ARRAY_SHADOW] = "GL_SAMPLER_2D_ARRAY_SHADOW";
spGLSLType[GL_SAMPLER_2D_MULTISAMPLE] = "GL_SAMPLER_2D_MULTISAMPLE";
spGLSLType[GL_SAMPLER_2D_MULTISAMPLE_ARRAY] = "GL_SAMPLER_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_SAMPLER_CUBE_SHADOW] = "GL_SAMPLER_CUBE_SHADOW";
spGLSLType[GL_SAMPLER_BUFFER] = "GL_SAMPLER_BUFFER";
spGLSLType[GL_SAMPLER_2D_RECT] = "GL_SAMPLER_2D_RECT";
spGLSLType[GL_SAMPLER_2D_RECT_SHADOW] = "GL_SAMPLER_2D_RECT_SHADOW";
spGLSLType[GL_INT_SAMPLER_1D] = "GL_INT_SAMPLER_1D";
spGLSLType[GL_INT_SAMPLER_2D] = "GL_INT_SAMPLER_2D";
spGLSLType[GL_INT_SAMPLER_3D] = "GL_INT_SAMPLER_3D";
spGLSLType[GL_INT_SAMPLER_CUBE] = "GL_INT_SAMPLER_CUBE";
spGLSLType[GL_INT_SAMPLER_1D_ARRAY] = "GL_INT_SAMPLER_1D_ARRAY";
spGLSLType[GL_INT_SAMPLER_2D_ARRAY] = "GL_INT_SAMPLER_2D_ARRAY";
spGLSLType[GL_INT_SAMPLER_2D_MULTISAMPLE] = "GL_INT_SAMPLER_2D_MULTISAMPLE";
spGLSLType[GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY] = "GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_INT_SAMPLER_BUFFER] = "GL_INT_SAMPLER_BUFFER";
spGLSLType[GL_INT_SAMPLER_2D_RECT] = "GL_INT_SAMPLER_2D_RECT";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_1D] = "GL_UNSIGNED_INT_SAMPLER_1D";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_2D] = "GL_UNSIGNED_INT_SAMPLER_2D";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_3D] = "GL_UNSIGNED_INT_SAMPLER_3D";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_CUBE] = "GL_UNSIGNED_INT_SAMPLER_CUBE";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_1D_ARRAY] = "GL_UNSIGNED_INT_SAMPLER_1D_ARRAY";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_2D_ARRAY] = "GL_UNSIGNED_INT_SAMPLER_2D_ARRAY";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE] = "GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY] = "GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_BUFFER] = "GL_UNSIGNED_INT_SAMPLER_BUFFER";
spGLSLType[GL_UNSIGNED_INT_SAMPLER_2D_RECT] = "GL_UNSIGNED_INT_SAMPLER_2D_RECT";
spGLSLType[GL_IMAGE_1D] = "GL_IMAGE_1D";
spGLSLType[GL_IMAGE_2D] = "GL_IMAGE_2D";
spGLSLType[GL_IMAGE_3D] = "GL_IMAGE_3D";
spGLSLType[GL_IMAGE_2D_RECT] = "GL_IMAGE_2D_RECT";
spGLSLType[GL_IMAGE_CUBE] = "GL_IMAGE_CUBE";
spGLSLType[GL_IMAGE_BUFFER] = "GL_IMAGE_BUFFER";
spGLSLType[GL_IMAGE_1D_ARRAY] = "GL_IMAGE_1D_ARRAY";
spGLSLType[GL_IMAGE_2D_ARRAY] = "GL_IMAGE_2D_ARRAY";
spGLSLType[GL_IMAGE_2D_MULTISAMPLE] = "GL_IMAGE_2D_MULTISAMPLE";
spGLSLType[GL_IMAGE_2D_MULTISAMPLE_ARRAY] = "GL_IMAGE_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_INT_IMAGE_1D] = "GL_INT_IMAGE_1D";
spGLSLType[GL_INT_IMAGE_2D] = "GL_INT_IMAGE_2D";
spGLSLType[GL_INT_IMAGE_3D] = "GL_INT_IMAGE_3D";
spGLSLType[GL_INT_IMAGE_2D_RECT] = "GL_INT_IMAGE_2D_RECT";
spGLSLType[GL_INT_IMAGE_CUBE] = "GL_INT_IMAGE_CUBE";
spGLSLType[GL_INT_IMAGE_BUFFER] = "GL_INT_IMAGE_BUFFER";
spGLSLType[GL_INT_IMAGE_1D_ARRAY] = "GL_INT_IMAGE_1D_ARRAY";
spGLSLType[GL_INT_IMAGE_2D_ARRAY] = "GL_INT_IMAGE_2D_ARRAY";
spGLSLType[GL_INT_IMAGE_2D_MULTISAMPLE] = "GL_INT_IMAGE_2D_MULTISAMPLE";
spGLSLType[GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY] = "GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_UNSIGNED_INT_IMAGE_1D] = "GL_UNSIGNED_INT_IMAGE_1D";
spGLSLType[GL_UNSIGNED_INT_IMAGE_2D] = "GL_UNSIGNED_INT_IMAGE_2D";
spGLSLType[GL_UNSIGNED_INT_IMAGE_3D] = "GL_UNSIGNED_INT_IMAGE_3D";
spGLSLType[GL_UNSIGNED_INT_IMAGE_2D_RECT] = "GL_UNSIGNED_INT_IMAGE_2D_RECT";
spGLSLType[GL_UNSIGNED_INT_IMAGE_CUBE] = "GL_UNSIGNED_INT_IMAGE_CUBE";
spGLSLType[GL_UNSIGNED_INT_IMAGE_BUFFER] = "GL_UNSIGNED_INT_IMAGE_BUFFER";
spGLSLType[GL_UNSIGNED_INT_IMAGE_1D_ARRAY] = "GL_UNSIGNED_INT_IMAGE_1D_ARRAY";
spGLSLType[GL_UNSIGNED_INT_IMAGE_2D_ARRAY] = "GL_UNSIGNED_INT_IMAGE_2D_ARRAY";
spGLSLType[GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE] = "GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE";
spGLSLType[GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY] = "GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY";
spGLSLType[GL_UNSIGNED_INT_ATOMIC_COUNTER] = "GL_UNSIGNED_INT_ATOMIC_COUNTER";
return true;
} | mit |
agilitix/agilib | AxFixEngine/Engine/IFixEngine.cs | 429 | using System.Collections.Generic;
using AxFixEngine.Dialects;
using AxFixEngine.Handlers;
using QuickFix;
namespace AxFixEngine.Engine
{
public interface IFixEngine
{
string ConfigFile { get; }
IList<SessionID> Sessions { get; }
IFixDialects Dialects { get; }
IFixMessageHandlers Handlers { get; }
void CreateApplication();
void Start();
void Stop();
}
}
| mit |
danielwertheim/mynatsclient | src/main/MyNatsClient.Encodings.Json/JsonSettings.cs | 835 | using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace MyNatsClient.Encodings.Json
{
public class JsonSettings
{
public static JsonSerializerSettings Create()
{
var settings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind,
ContractResolver = new DefaultContractResolver
{
NamingStrategy = new DefaultNamingStrategy
{
ProcessDictionaryKeys = false
}
}
};
settings.Converters.Add(new StringEnumConverter());
return settings;
}
}
} | mit |
ysaito-lev218/console-sample | app/Handlers/Events/QueryLogTracker.php | 578 | <?php
namespace App\Handlers\Events;
use Log;
//use App\Events\illuminate.query;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class QueryLogTracker
{
/**
* Create the event handler.
*
*/
public function __construct()
{
//
}
/**
* Handle the event.
*
* @param illuminate.query $event
* @return void
*/
public function handle($query, $bindings)
{
//
Log::debug('EXECUTE SQL:[' . $query . ']', ['BINDINGS' => json_encode($bindings)]);
}
}
| mit |
HotcakesCommerce/core | Website/DesktopModules/Hotcakes/Core/Admin/Catalog/FileVaultDetailsView.aspx.cs | 11038 | #region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2019 Hotcakes Commerce, LLC
// Copyright (c) 2020 Upendo Ventures, LLC
//
// 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.
#endregion
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hotcakes.Commerce;
using Hotcakes.Commerce.Globalization;
using Hotcakes.Commerce.Membership;
using Hotcakes.Modules.Core.Admin.AppCode;
using Hotcakes.Modules.Core.Admin.Controls;
namespace Hotcakes.Modules.Core.Admin.Catalog
{
partial class FileVaultDetailsView : BaseAdminPage
{
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
PageTitle = Localization.GetString("PageTitle");
CurrentTab = AdminTabType.Catalog;
ValidateCurrentUserHasPermission(SystemPermissions.CatalogView);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("~/DesktopModules/Hotcakes/Core/Admin/Catalog/default.aspx");
}
else
{
ViewState["id"] = Request.QueryString["id"];
}
LocalizeView();
BindProductsGrid();
PopulateFileInfo();
}
}
private void LocalizeView()
{
var localization = Factory.Instance.CreateLocalizationHelper(LocalResourceFile);
LocalizationUtils.LocalizeGridView(ProductsGridView, localization);
}
protected void BindProductsGrid()
{
ProductsGridView.DataSource = HccApp.CatalogServices.FindProductsForFile((string) ViewState["id"]);
ProductsGridView.DataBind();
}
protected void PopulateFileInfo()
{
var file = HccApp.CatalogServices.ProductFiles.Find((string) ViewState["id"]);
lblFileName.Text = file.FileName;
DescriptionTextBox.Text = file.ShortDescription;
}
protected void ProductsGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var key = (string) ProductsGridView.DataKeys[e.RowIndex].Value;
var file = HccApp.CatalogServices.ProductFiles.Find((string) ViewState["id"]);
HccApp.CatalogServices.ProductFiles.RemoveAssociatedProduct(file.Bvin, key);
BindProductsGrid();
}
protected void btnBrowseProducts_Click(object sender, EventArgs e)
{
pnlProductPicker.Visible = !pnlProductPicker.Visible;
if (NewSkuField.Text.Trim().Length > 0)
{
if (pnlProductPicker.Visible)
{
ProductPicker1.Keyword = NewSkuField.Text;
ProductPicker1.LoadSearch();
}
}
}
private void AddProductBySku()
{
MessageBox1.ClearMessage();
if (NewSkuField.Text.Trim().Length < 1)
{
MessageBox1.ShowWarning(Localization.GetString("NoSkuError"));
}
else
{
var p = HccApp.CatalogServices.Products.FindBySku(NewSkuField.Text.Trim());
if (p != null)
{
if (p.Sku == string.Empty)
{
MessageBox1.ShowWarning(Localization.GetString("InnvalidSku"));
}
else
{
var file = HccApp.CatalogServices.ProductFiles.Find((string) ViewState["id"]);
if (file != null)
{
if (HccApp.CatalogServices.ProductFiles.AddAssociatedProduct(file.Bvin, p.Bvin, 0, 0))
{
MessageBox1.ShowOk(Localization.GetString("ProductAddSuccess"));
}
else
{
MessageBox1.ShowError(Localization.GetString("ProductAddFailure"));
}
}
}
}
}
BindProductsGrid();
}
protected void btnAddProductBySku_Click(object sender, EventArgs e)
{
AddProductBySku();
}
protected void btnProductPickerCancel_Click(object sender, EventArgs e)
{
MessageBox1.ClearMessage();
pnlProductPicker.Visible = false;
}
protected void btnProductPickerOkay_Click(object sender, EventArgs e)
{
MessageBox1.ClearMessage();
if (ProductPicker1.SelectedProducts.Count > 0)
{
var p = HccApp.CatalogServices.Products.Find(ProductPicker1.SelectedProducts[0]);
if (p != null)
{
NewSkuField.Text = p.Sku;
}
AddProductBySku();
pnlProductPicker.Visible = false;
}
else
{
MessageBox1.ShowWarning(Localization.GetString("NoProductSelected"));
}
}
protected void ProductsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
if (Page.IsValid)
{
var key = (string) ProductsGridView.DataKeys[e.RowIndex].Value;
var file = HccApp.CatalogServices.ProductFiles.FindByBvinAndProductBvin((string) ViewState["id"], key);
var row = ProductsGridView.Rows[e.RowIndex];
var tb = (TextBox) row.FindControl("MaxDownloadsTextBox");
var tp = (TimespanPicker) row.FindControl("TimespanPicker");
if (tb != null)
{
var val = 0;
if (int.TryParse(tb.Text, out val))
{
file.MaxDownloads = val;
}
else
{
file.MaxDownloads = 0;
}
}
if (tp != null)
{
file.SetMinutes(tp.Months, tp.Days, tp.Hours, tp.Minutes);
}
if (HccApp.CatalogServices.ProductFiles.Update(file))
{
MessageBox1.ShowOk(Localization.GetString("FileUpdateSuccess"));
}
else
{
MessageBox1.ShowError(Localization.GetString("FileUpdateFailure"));
}
BindProductsGrid();
}
}
protected void ProductsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var key = (string) ProductsGridView.DataKeys[e.Row.RowIndex].Value;
var file = HccApp.CatalogServices.ProductFiles.FindByBvinAndProductBvin((string) ViewState["id"], key);
var tb = (TextBox) e.Row.FindControl("MaxDownloadsTextBox");
var tp = (TimespanPicker) e.Row.FindControl("TimespanPicker");
if (tb != null)
{
tb.Text = file.MaxDownloads.ToString();
}
if (tp != null)
{
var minutes = file.AvailableMinutes;
tp.Months = minutes/43200;
minutes = minutes%43200;
tp.Days = minutes/1440;
minutes = minutes%1440;
tp.Hours = minutes/60;
minutes = minutes%60;
tp.Minutes = minutes;
}
}
}
protected void SaveImageButton_Click(object sender, EventArgs e)
{
var file = HccApp.CatalogServices.ProductFiles.Find((string) ViewState["id"]);
if (file != null)
{
file.ShortDescription = DescriptionTextBox.Text;
if (HccApp.CatalogServices.ProductFiles.Update(file))
{
MessageBox1.ShowOk(Localization.GetString("FileUpdateSuccess"));
}
else
{
MessageBox1.ShowError(Localization.GetString("FileUpdateFailure"));
}
}
}
protected void CancelImageButton_Click(object sender, EventArgs e)
{
Response.Redirect("~/DesktopModules/Hotcakes/Core/Admin/Catalog/FileVault.aspx");
}
protected void FileReplaceCancelImageButton_Click(object sender, EventArgs e)
{
FilePicker1.Clear();
ReplacePanel.Visible = false;
}
protected void FileReplaceSaveImageButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
var file = HccApp.CatalogServices.ProductFiles.Find((string) ViewState["id"]);
if (file != null)
{
FilePicker1.DownloadOrLinkFile(file, MessageBox1);
ReplacePanel.Visible = false;
PopulateFileInfo();
}
else
{
MessageBox1.ShowError(Localization.GetString("FileUpdateFailure"));
}
}
}
protected void ReplaceImageButton_Click(object sender, EventArgs e)
{
ReplacePanel.Visible = true;
}
protected void btnCloseVariants_Click(object sender, EventArgs e)
{
MessageBox1.ClearMessage();
pnlProductChoices.Visible = false;
}
}
} | mit |
ReIR/BestNid | src/app/Http/Controllers/Admin/UsersController.php | 1033 | <?php namespace App\Http\Controllers\Admin;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Request;
use App\User;
class UsersController extends Controller {
public function __construct() {
$this->middleware('authAdmin');
}
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
if (Request::has('initialDate') && Request::has('finalDate')){
$initialDate = Request::get('initialDate');
$finalDate = Request::get('finalDate');
// check if is a bad range of dates
if ( $finalDate < $initialDate ) {
return redirect()
->route('admin.users.index')
->with('error', 'Rango de fechas inválido');
}
$usersBetween= User::whereBetween('created_at', [$initialDate, date('Y-m-d', strtotime('+1 days'.$finalDate))])->get();
return view('admin.users.index')
->with('users', $usersBetween);
}
$users = User::all();
return view ('admin.users.index')
->with('users', $users);
}
}
| mit |
RDRdeveloper82/tiendaFlag | frontend/components/NavBar.php | 7720 | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace frontend\components;
use Yii;
use yii\bootstrap\BootstrapPluginAsset;
use yii\bootstrap\Html;
use yii\bootstrap\Widget;
use yii\helpers\ArrayHelper;
/**
* NavBar renders a navbar HTML component.
*
* Any content enclosed between the [[begin()]] and [[end()]] calls of NavBar
* is treated as the content of the navbar. You may use widgets such as [[Nav]]
* or [[\yii\widgets\Menu]] to build up such content. For example,
*
* ```php
* use yii\bootstrap\NavBar;
* use yii\widgets\Menu;
*
* NavBar::begin(['brandLabel' => 'NavBar Test']);
* echo Nav::widget([
* 'items' => [
* ['label' => 'Home', 'url' => ['/site/index']],
* ['label' => 'About', 'url' => ['/site/about']],
* ],
* ]);
* NavBar::end();
* ```
*
* @see http://getbootstrap.com/components/#navbar
* @author Antonio Ramirez <amigo.cobos@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class NavBar extends Widget
{
/**
* @var array the HTML attributes for the widget container tag. The following special options are recognized:
*
* - tag: string, defaults to "nav", the name of the container tag.
*
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $options = [];
/**
* @var array the HTML attributes for the container tag. The following special options are recognized:
*
* - tag: string, defaults to "div", the name of the container tag.
*
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $containerOptions = [];
/**
* @var string|boolean the text of the brand of false if it's not used. Note that this is not HTML-encoded.
* @see http://getbootstrap.com/components/#navbar
*/
public $brandLabel = false;
/**
* @param array|string|boolean $url the URL for the brand's hyperlink tag. This parameter will be processed by [[Url::to()]]
* and will be used for the "href" attribute of the brand link. Default value is false that means
* [[\yii\web\Application::homeUrl]] will be used.
*/
public $brandUrl = false;
/**
* @var array the HTML attributes of the brand link.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $brandOptions = [];
/**
* @var string text to show for screen readers for the button to toggle the navbar.
*/
public $screenReaderToggleText = 'Toggle navigation';
/**
* @var boolean whether the navbar content should be included in an inner div container which by default
* adds left and right padding. Set this to false for a 100% width navbar.
*/
public $renderInnerContainer = true;
/**
* @var array the HTML attributes of the inner container.
* @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
*/
public $innerContainerOptions = [];
/**
* Initializes the widget.
*/
public function init()
{
parent::init();
$this->clientOptions = false;
Html::addCssClass($this->options, 'navbar');
if ($this->options['class'] === 'navbar') {
Html::addCssClass($this->options, 'navbar-default');
}
Html::addCssClass($this->brandOptions, 'navbar-brand');
if (empty($this->options['role'])) {
$this->options['role'] = 'navigation';
}
$options = $this->options;
$tag = ArrayHelper::remove($options, 'tag', 'nav');
echo Html::beginTag($tag, $options);
echo '
<div class="navbar-top">
<div class="container">
<ul class="userMenu">
<li class="phone-number">
<a href="callto:' . Yii::$app->params['contactPhone'] . '" target="_blank">
<span>
<i class="glyphicon glyphicon-phone-alt"></i>
</span>
<span class="hidden-xs" style="margin-left:5px">
' . Yii::$app->params['contactPhone'] . '
</span>
</a>
</li>
<li>
<a href="mailto:' . Yii::$app->params['contactEmail'] . '" target="_blank">
<span>
<i class="glyphicon glyphicon-envelope"></i>
</span>
<span class="hidden-xs" style="margin-left:5px">
' . Yii::$app->params['contactEmail'] . '
</span>
</a>
</li>
</ul>
<div class="pull-right">
<ul class="userMenu">
<li>
<a href="' . Yii::$app->params['socialLinks']['twitter'] . '" class="soclink" target="_blank">
<span class="fa-stack">
<i class="fa fa-square-o fa-stack-2x"></i>
<i class="fa fa-twitter fa-stack-1x"></i>
</span>
</a>
</li>
<li>
<a href="' . Yii::$app->params['socialLinks']['facebook'] . '" class="soclink" target="_blank">
<span class="fa-stack">
<i class="fa fa-square-o fa-stack-2x"></i>
<i class="fa fa-facebook fa-stack-1x"></i>
</span>
</a>
</li>
</ul>
</div>
</div>
</div>
';
if ($this->renderInnerContainer) {
if (!isset($this->innerContainerOptions['class'])) {
Html::addCssClass($this->innerContainerOptions, 'container');
}
echo Html::beginTag('div', $this->innerContainerOptions);
}
echo Html::beginTag('div', ['class' => 'navbar-header']);
if (!isset($this->containerOptions['id'])) {
$this->containerOptions['id'] = "{$this->options['id']}-collapse";
}
echo $this->renderToggleButton();
if ($this->brandLabel !== false) {
Html::addCssClass($this->brandOptions, 'navbar-brand');
echo Html::a($this->brandLabel, $this->brandUrl === false ? Yii::$app->homeUrl : $this->brandUrl,
$this->brandOptions);
}
echo Html::endTag('div');
Html::addCssClass($this->containerOptions, 'collapse');
Html::addCssClass($this->containerOptions, 'navbar-collapse');
$options = $this->containerOptions;
$tag = ArrayHelper::remove($options, 'tag', 'div');
echo Html::beginTag($tag, $options);
}
/**
* Renders the widget.
*/
public function run()
{
$tag = ArrayHelper::remove($this->containerOptions, 'tag', 'div');
echo Html::endTag($tag);
if ($this->renderInnerContainer) {
echo Html::endTag('div');
}
$tag = ArrayHelper::remove($this->options, 'tag', 'nav');
echo Html::endTag($tag, $this->options);
BootstrapPluginAsset::register($this->getView());
}
/**
* Renders collapsible toggle button.
* @return string the rendering toggle button.
*/
protected function renderToggleButton()
{
$bar = Html::tag('span', '', ['class' => 'icon-bar']);
$screenReader = "<span class=\"sr-only\">{$this->screenReaderToggleText}</span>";
return Html::button("{$screenReader}\n{$bar}\n{$bar}\n{$bar}", [
'class' => 'navbar-toggle',
'data-toggle' => 'collapse',
'data-target' => "#{$this->containerOptions['id']}",
]);
}
}
| mit |
js1972/openui5-clickpanel | application.js | 1516 | // local controller
sap.ui.controller("my.controller", {
onInit: function() {
var panel = this.byId("panel");
// This is a hack way of enabling a click in the header of a Panel to toggle expand/collapse.
panel.addDelegate({
onclick: function(oEvent) {
if (oEvent.target === panel.$().find(".sapMPanelHdr").get(0)) {
panel.setExpanded(!panel.getExpanded());
}
}
});
// This is another test but using a panel with a header toolbar - its not quite working properly yet.
var panel2 = this.byId("panel2");
panel2.addDelegate({
onclick: function(oEvent) {
if ($(oEvent.target).hasClass("sapUiIcon")) {
return;
}
if ($(oEvent.target).find(".sapUiIcon").get(0)) {
return;
}
if (panel2.$().find("#__toolbar0").get(0)) {
panel2.setExpanded(!panel2.getExpanded());
}
}
});
},
//dummy code
onSelect: function(evt){
window.open("", "_blank");
}
});
// Instantiate the new control
sap.ui.require(["programic/ClickPanel"], function (ClickPanel) {
var myControl = new ClickPanel("panel3", {
expandable: true,
expandIcon: "sap-icon://add",
collapseIcon: "sap-icon://less",
headerText: "Testing... 1... 2... 3... (added dynamically)",
content: new sap.m.Text("txt1", {text: "Hell there! I've been added dynamically in JavaScript..."})
});
myControl.placeAt("content");
});
var oView = sap.ui.xmlview({
viewContent: jQuery('#myView').html()
});
oView.placeAt('content');
| mit |
mneumann/izhikevich-neurons | src/network/neuron_id.rs | 307 | #[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct NeuronId(u32);
impl NeuronId {
#[inline(always)]
pub fn index(&self) -> usize {
self.0 as usize
}
}
impl From<usize> for NeuronId {
#[inline(always)]
fn from(index: usize) -> Self {
NeuronId(index as u32)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.