code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; public class ArraysIndices { public static void main(String[] args) { int[][] t = new int[0][0]; System.out.println("t = " + t); System.out.println("Arrays.toString(t) = " + Arrays.toString(t)); System.out.println("Arrays.deepToString(t) = " + Arrays.deepToString(t)); if (t.length == 0) { System.out.println("Массив пустой"); } else { boolean allEmpty = true; for (int[] tt : t) { if (tt.length == 0) { allEmpty = false; break; } } if (allEmpty) System.out.println("Массив пустой"); } int[][] A = { {1, 2}, {3, 4}}; System.out.println("Shape = " + A); System.out.println("Arrays.toString(Shape) = " + Arrays.toString(A)); System.out.println("Arrays.deepToString(Shape) = " + Arrays.deepToString(A)); // Классы "Расширяемые массивы" LinkedList<Integer> ll = new LinkedList<>(); ArrayList<Integer> al = new ArrayList<>(); al.add(100); al.remove(0); System.out.println("al.size() = " + al.size()); } }
levelp/java_beginners_homework
lesson_04/java/ArraysIndices.java
Java
mit
1,373
/** * Creates a new Element * * @class Element * @extends EventTarget * @description todoc * @property {ClassList} classList * @property {Vector2} velocity **/ function Element() { EventTarget.call(this); Storage.call(this); addElementPropertyHandlers.call(this); this.uuid = generateUUID(); this.velocity = new Vector2(0, 0); this.classList = new ClassList(); this.classList.add(elementProto.elementType, 0); forIn(elementClass, this.addProp, this); } /** @lends Element# **/ var elementProto = Element.prototype = Object.create(EventTarget.prototype); elementProto.constructor = Element; var addElementPropertyHandlers = (function() { /** * Creates a new ElementProperty * * @class ElementProperty * @param {String} propertyKey * @param {*} primitiveValue * @param {Boolean} inheritable * @description todoc **/ function ElementProperty(propertyKey, primitiveValue, inheritable) { this.key = propertyKey; this.edit(primitiveValue, inheritable); this.initialValue = this.value; this.value = 'inherit'; } /** @lends ElementProperty# **/ var elementPropertyProto = ElementProperty.prototype = stdClass(); elementPropertyProto.constructor = ElementProperty; /** * Edits the property, sets it's primitiveValue and inheritable properties * * @param {*} primitiveValue * @param {Boolean} [inheritable] * @returns {ElementProperty} this **/ elementPropertyProto.edit = function(primitiveValue, inheritable) { var parsed = parseMethod(primitiveValue); this.primitiveValue = primitiveValue; this.value = isNull(parsed) ? primitiveValue : parsed; this.type = isFunction(this.value) ? 'method' : 'property'; if (isBoolean(inheritable)) this.inheritable = inheritable; return this; }; return function propertyHandlers() { var _properties = stdClass(); /** * Adds a property to the Element * * @alias Element#addProp * @param {String} propertyKey * @param {*} primitiveValue * @param {Boolean} [inheritable] * @returns {Element} this * @todo Need to rewrite the property handler methods **/ this.addProp = function(propertyKey, primitiveValue, inheritable) { if (!isBoolean(inheritable)) inheritable = true; if (this.hasProp(propertyKey)) { warning(this.toString() + ' already has property ' + propertyKey); } _properties[propertyKey] = new ElementProperty(propertyKey, primitiveValue, inheritable); Object.defineProperty(this, propertyKey, { configurable: true, enumerable: false, get: function () { var val = _properties[propertyKey].value; if (val === 'inherit') val = this.classList.execute(function(className) { var classData = $classes.get(className); if ( !isNull(classData) && !isUndefined(classData[propertyKey]) && classData[propertyKey] !== 'inherit' ) return classData[propertyKey] === 'initial' ? _properties[propertyKey].initialValue : classData[propertyKey]; }, this); return isFunction(val) ? val.call(this) : val; }, set: function (propertyVal) { return _properties[propertyKey].edit(propertyVal).value; } }); return this; }; /** * Adds a property to the Element if it doesn't has it already * * @alias Element#addPropSafe * @param {String} propertyKey * @param {*} primitiveValue * @param {Boolean} [inheritable] * @returns {Element} this **/ this.addPropSafe = function(propertyKey, primitiveValue, inheritable) { if (!this.hasProp(propertyKey)) this.addProp(propertyKey, primitiveValue, inheritable); return this; }; /** * Checks if the Element has a specific property * * @alias Element#hasProp * @param {String} propertyKey * @returns {Boolean} **/ this.hasProp = function(propertyKey) { return has(_properties, propertyKey); }; /** * Removes a property from the Element * * @alias Element#removeProp * @param {String} propertyKey * @returns {Element} this **/ this.removeProp = function(propertyKey) { if (has(_properties, propertyKey)) { delete _properties[propertyKey]; delete this[propertyKey]; } return this; }; /** * Edits a property of the Element * * @alias Element#setProp * @param {String} propertyKey * @param {*} primitiveValue * @param {Boolean} [inheritable] * @returns {Element} this **/ this.setProp = function(propertyKey, primitiveValue, inheritable) { if (has(_properties, propertyKey)) { _properties[propertyKey].edit(primitiveValue, inheritable); } return this; }; /** * Returns an ElementProperty of the Element by key * * @alias Element#getProp * @param {String} propertyKey * @returns {?ElementProperty} **/ this.getProp = function(propertyKey) { return _properties[propertyKey] || null; }; /** * Returns all ElementProperty from the Element (reduced by the given filter) * * @alias Element#getProps * @param {Function} [filter] * @returns {Array} **/ this.getProps = function(filter) { var props = []; forIn(_properties, function(propertyKey, property) { if (isUndefined(filter) || filter.call(this, propertyKey, property) === true) props.push(property); return false; }, this); return props; }; return this; }; }()); /** * The type of the element * * @type String * @default 'Element' * @readonly **/ elementProto.elementType = 'Element'; /** * The name of the element * * @type String * @default 'Element' * @readonly **/ elementProto.elementName = 'Element'; /** * The id of the element * * @type String * @default null * @readonly **/ elementProto.id = null; /** * The uuid of the element * * @type String * @default null * @readonly **/ elementProto.uuid = null; Object.defineProperty(elementProto, 'className', { /** * The classes of the element * * @name Element#className * @type String * @readonly **/ get: function() { return this.classList.all().join(' '); } }); /** * The parentLayer of the element * * @type Layer * @default null * @readonly **/ elementProto.parentLayer = null; /** * The parentElement of the element * * @type ContainerElement * @default null * @readonly **/ elementProto.parentElement = null; Object.defineProperty(elementProto, 'vX', { /** * The horizontal velocity of the element * * @name Element#vX * @type Number **/ get: function() { return this.velocity.x; }, set: function(xVal) { return this.velocity.setX(xVal).x; } }); Object.defineProperty(elementProto, 'vY', { /** * The vertical velocity of the element * * @name Element#vY * @type Number **/ get: function() { return this.velocity.y; }, set: function(yVal) { return this.velocity.setY(yVal).y; } }); /** * The x position of the element * * @type Number|String * @default 0 **/ elementProto.x = 0; /** * The y position of the element * * @type Number|String * @default 0 **/ elementProto.y = 0; /** * The maximum x position of the element * * @type Number|String * @default 'none' **/ elementProto.maxX = 'none'; /** * The maximum y position of the element * * @type Number|String * @default 'none' **/ elementProto.maxY = 'none'; /** * The minimum x position of the element * * @type Number|String * @default 'none' **/ elementProto.minX = 'none'; /** * The minimum y position of the element * * @type Number|String * @default 'none' **/ elementProto.minY = 'none'; /** * The horizontal offset of the element * * @type Number|String * @default 0 **/ elementProto.offsetX = 0; /** * The vertical offset of the element * * @type Number|String * @default 0 **/ elementProto.offsetY = 0; /** * The width of the element * * @type Number|String * @default 0 **/ elementProto.width = 0; /** * The height of the element * * @type Number|String * @default 0 **/ elementProto.height = 0; /** * The maximum width of the element * * @type Number|String * @default 'none' **/ elementProto.maxWidth = 'none'; /** * The maximum height of the element * * @type Number|String * @default 'none' **/ elementProto.maxHeight = 'none'; /** * The minimum width of the element * * @type Number|String * @default 'none' **/ elementProto.minWidth = 'none'; /** * The minimum height of the element * * @type Number|String * @default 'none' **/ elementProto.minHeight = 'none'; /** * The top position of the element on the screen, including margin * * @type Number * @default 0 * @readonly **/ elementProto.top = 0; /** * The right position of the element on the screen, including margin * * @type Number * @default 0 * @readonly **/ elementProto.right = 0; /** * The bottom position of the element on the screen, including margin * * @type Number * @default 0 * @readonly **/ elementProto.bottom = 0; /** * The left position of the element on the screen, including margin * * @type Number * @default 0 * @readonly **/ elementProto.left = 0; /** * The x position of the element, relative to the scene * * @type Number * @default 0 * @readonly **/ elementProto.screenX = 0; /** * The y position of the element, relative to the scene * * @type Number * @default 0 * @readonly **/ elementProto.screenY = 0; /** * The x position of the element, relative to it's parent * * @type Number * @default 0 * @readonly **/ elementProto.parentX = 0; /** * The y position of the element, relative to it's parent * * @type Number * @default 0 * @readonly **/ elementProto.parentY = 0; /** * The layout width of the element * * @type Number * @default 0 * @readonly **/ elementProto.renderWidth = 0; /** * The layout height of the element * * @type Number * @default 0 * @readonly **/ elementProto.renderHeight = 0; Object.defineProperties(elementProto, { screenXC: { /** * The horizontal center position of the element, relative to the scene * * @name Element#screenXC * @type Number * @readonly **/ get: function() { return this.screenX + this.renderWidth / 2 } }, screenYC: { /** * The vertical center position of the element, relative to the scene * * @name Element#screenYC * @type Number * @readonly **/ get: function() { return this.screenY + this.renderHeight / 2 } }, screenXE: { /** * The horizontal end position of the element, relative to the scene * * @name Element#screenXE * @type Number * @readonly **/ get: function() { return this.screenX + this.renderWidth } }, screenYE: { /** * The vertical end position of the element, relative to the scene * * @name Element#screenYE * @type Number * @readonly **/ get: function() { return this.screenY + this.renderHeight } }, parentXC: { /** * The horizontal center position of the element, relative to it's parent * * @name Element#parentXC * @type Number * @readonly **/ get: function() { return this.parentX + this.renderWidth / 2 } }, parentYC: { /** * The vertical center position of the element, relative to it's parent * * @name Element#parentYC * @type Number * @readonly **/ get: function() { return this.parentY + this.renderHeight / 2 } }, parentXE: { /** * The horizontal end position of the element, relative to it's parent * * @name Element#parentXE * @type Number * @readonly **/ get: function() { return this.parentX + this.renderWidth } }, parentYE: { /** * The vertical end position of the element, relative to it's parent * * @name Element#parentYE * @type Number * @readonly **/ get: function() { return this.parentY + this.renderHeight } } }); /** * The width ratio of the element * * @type Number * @default 1 **/ elementProto.scaleX = 1; /** * The height ratio of the element * * @type Number * @default 1 **/ elementProto.scaleY = 1; /** * The clockwise rotation of the entry * * @type Number * @default 0 **/ elementProto.angle = 0; /** * If the element should be mirrored horizontally * * @type Boolean * @default false **/ elementProto.flipX = false; /** * If the element should be mirrored vertically * * @type Boolean * @default false **/ elementProto.flipY = false; /** * The flow of the element * * @type ('none'|'horizontal'|'vertical') * @default 'none' **/ elementProto.flow = 'none'; /** * The wrap of the element * * @type Boolean * @default true **/ elementProto.wrap = true; /** * The dragging status of the element * * @type Boolean * @default false * @todo Implement dragState **/ elementProto.dragState = false; /** * The focus status of the element * * @type Boolean * @default false * @todo Implement onFocus **/ elementProto.onFocus = false; /** * If the element allows mouse events through transparent pixel * * @type Boolean * @default true * @todo Implement isBlock **/ elementProto.isBlock = true; /** * The cursor type of the element * * @type String * @default 'default' * @todo Implement cursor **/ elementProto.cursor = 'default'; /** * If the element allows drop on it * * @type Boolean * @default false * @todo Implement allowDrop **/ elementProto.allowDrop = false; /** * The title of the element * * @type String * @default '' * @todo Implement title **/ elementProto.title = ''; /** * The transparency of the element * * @type Number * @default 1 * @todo Implement opacity **/ elementProto.opacity = 1; /** * The background of the element * * @type String * @default '' **/ elementProto.background = ''; /** * The mask id of the element * * @type String * @default '' **/ elementProto.mask = ''; /** * The horizontal align of the element * * @type ('left'|'center'|'right') * @default 'left' **/ elementProto.horizontalAlign = 'left'; /** * The vertical align of the element * * @type ('top'|'middle'|'bottom') * @default 'top' **/ elementProto.verticalAlign = 'top'; /** * The top margin of the element * * @type String|Number * @default 0 **/ elementProto.marginTop = 0; /** * The right margin of the element * * @type String|Number * @default 0 **/ elementProto.marginRight = 0; /** * The bottom margin of the element * * @type String|Number * @default 0 **/ elementProto.marginBottom = 0; /** * The left margin of the element * * @type String|Number * @default 0 **/ elementProto.marginLeft = 0; Object.defineProperty(elementProto, 'margin', { /** * The margin of the element * * @name Element#margin * @type String **/ get: function() { return this.marginTop + ' ' + this.marginRight + ' ' + this.marginBottom + ' ' + this.marginLeft; }, set: function(margin) { var pieces = margin.split(' ') , len = pieces.length; if (len === 1) { this.marginTop = pieces[0]; this.marginRight = pieces[0]; this.marginBottom = pieces[0]; this.marginLeft = pieces[0]; } else if (len === 2) { this.marginTop = pieces[0]; this.marginRight = pieces[1]; this.marginBottom = pieces[0]; this.marginLeft = pieces[1]; } else if (len === 3) { this.marginTop = pieces[0]; this.marginRight = pieces[1]; this.marginBottom = pieces[2]; this.marginLeft = pieces[1]; } else { this.marginTop = pieces[0]; this.marginRight = pieces[1]; this.marginBottom = pieces[2]; this.marginLeft = pieces[3]; } return this.margin; } }); /** * The top padding of the element * * @type String|Number * @default 0 **/ elementProto.paddingTop = 0; /** * The right padding of the element * * @type String|Number * @default 0 **/ elementProto.paddingRight = 0; /** * The bottom padding of the element * * @type String|Number * @default 0 **/ elementProto.paddingBottom = 0; /** * The left padding of the element * * @type String|Number * @default 0 **/ elementProto.paddingLeft = 0; Object.defineProperty(elementProto, 'padding', { /** * The padding of the element * * @name Element#padding * @type String **/ get: function() { return this.paddingTop + ' ' + this.paddingRight + ' ' + this.paddingBottom + ' ' + this.paddingLeft; }, set: function(padding) { var pieces = padding.split(' ') , len = pieces.length; if (len === 1) { this.paddingTop = pieces[0]; this.paddingRight = pieces[0]; this.paddingBottom = pieces[0]; this.paddingLeft = pieces[0]; } else if (len === 2) { this.paddingTop = pieces[0]; this.paddingRight = pieces[1]; this.paddingBottom = pieces[0]; this.paddingLeft = pieces[1]; } else if (len === 3) { this.paddingTop = pieces[0]; this.paddingRight = pieces[1]; this.paddingBottom = pieces[2]; this.paddingLeft = pieces[1]; } else { this.paddingTop = pieces[0]; this.paddingRight = pieces[1]; this.paddingBottom = pieces[2]; this.paddingLeft = pieces[3]; } return this.padding; } }); /** * The border of the element * * @name Element#border * @type String **/ Object.defineProperty(elementProto, 'border', { get: undefined, set: function(border) { var pieces = border.split(' ') , len = pieces.length; if (len >= 1) { this.borderTopWidth = pieces[0]; this.borderRightWidth = pieces[0]; this.borderBottomWidth = pieces[0]; this.borderLeftWidth = pieces[0]; } if (len >= 2) { this.borderTopStyle = pieces[1]; this.borderRightStyle = pieces[1]; this.borderBottomStyle = pieces[1]; this.borderLeftStyle = pieces[1]; } if (len === 3) { this.borderTopColor = pieces[2]; this.borderRightColor = pieces[2]; this.borderBottomColor = pieces[2]; this.borderLeftColor = pieces[2]; } return border; } }); /** * The top border of the element * * @name Element#borderTop * @type String **/ Object.defineProperty(elementProto, 'borderTop', { get: undefined, set: function(borderTop) { var pieces = borderTop.split(' ') , len = pieces.length; if (len >= 1) this.borderTopWidth = pieces[0]; if (len >= 2) this.borderTopStyle = pieces[1]; if (len === 3) this.borderTopColor = pieces[2]; return borderTop; } }); /** * The right border of the element * * @name Element#borderRight * @type String **/ Object.defineProperty(elementProto, 'borderRight', { get: undefined, set: function(borderRight) { var pieces = borderRight.split(' ') , len = pieces.length; if (len >= 1) this.borderRightWidth = pieces[0]; if (len >= 2) this.borderRightStyle = pieces[1]; if (len === 3) this.borderRightColor = pieces[2]; return borderRight; } }); /** * The bottom border of the element * * @name Element#borderBottom * @type String **/ Object.defineProperty(elementProto, 'borderBottom', { get: undefined, set: function(borderBottom) { var pieces = borderBottom.split(' ') , len = pieces.length; if (len >= 1) this.borderBottomWidth = pieces[0]; if (len >= 2) this.borderBottomStyle = pieces[1]; if (len === 3) this.borderBottomColor = pieces[2]; return borderBottom; } }); /** * The left border of the element * * @name Element#borderLeft * @type String **/ Object.defineProperty(elementProto, 'borderLeft', { get: undefined, set: function(borderLeft) { var pieces = borderLeft.split(' ') , len = pieces.length; if (len >= 1) this.borderLeftWidth = pieces[0]; if (len >= 2) this.borderLeftStyle = pieces[1]; if (len === 3) this.borderLeftColor = pieces[2]; return borderLeft; } }); /** * The top border width of the element * * @type String|Number * @default 0 **/ elementProto.borderTopWidth = 0; /** * The right border width of the element * * @type String|Number * @default 0 **/ elementProto.borderRightWidth = 0; /** * The bottom border width of the element * * @type String|Number * @default 0 **/ elementProto.borderBottomWidth = 0; /** * The left border width of the element * * @type String|Number * @default 0 **/ elementProto.borderLeftWidth = 0; Object.defineProperty(elementProto, 'borderWidth', { /** * The width of the element's border * * @name Element#borderWidth * @type String **/ get: function() { return this.borderTopWidth + ' ' + this.borderRightWidth + ' ' + this.borderBottomWidth + ' ' + this.borderLeftWidth; }, set: function(borderWidth) { var pieces = borderWidth.split(' ') , len = pieces.length; if (len === 1) { this.borderTopWidth = pieces[0]; this.borderRightWidth = pieces[0]; this.borderBottomWidth = pieces[0]; this.borderLeftWidth = pieces[0]; } else if (len === 2) { this.borderTopWidth = pieces[0]; this.borderRightWidth = pieces[1]; this.borderBottomWidth = pieces[0]; this.borderLeftWidth = pieces[1]; } else if (len === 3) { this.borderTopWidth = pieces[0]; this.borderRightWidth = pieces[1]; this.borderBottomWidth = pieces[2]; this.borderLeftWidth = pieces[1]; } else { this.borderTopWidth = pieces[0]; this.borderRightWidth = pieces[1]; this.borderBottomWidth = pieces[2]; this.borderLeftWidth = pieces[3]; } return this.borderWidth; } }); /** * The top border style of the element * * @type String * @default 'none' **/ elementProto.borderTopStyle = 'none'; /** * The right border style of the element * * @type String * @default 'none' **/ elementProto.borderRightStyle = 'none'; /** * The bottom border style of the element * * @type String * @default 'none' **/ elementProto.borderBottomStyle = 'none'; /** * The left border style of the element * * @type String * @default 'none' **/ elementProto.borderLeftStyle = 'none'; Object.defineProperty(elementProto, 'borderStyle', { /** * The style of the element's border * * @name Element#borderStyle * @type String **/ get: function() { return this.borderTopStyle + ' ' + this.borderRightStyle + ' ' + this.borderBottomStyle + ' ' + this.borderLeftStyle; }, set: function(borderStyle) { var pieces = borderStyle.split(' ') , len = pieces.length; if (len === 1) { this.borderTopStyle = pieces[0]; this.borderRightStyle = pieces[0]; this.borderBottomStyle = pieces[0]; this.borderLeftStyle = pieces[0]; } else if (len === 2) { this.borderTopStyle = pieces[0]; this.borderRightStyle = pieces[1]; this.borderBottomStyle = pieces[0]; this.borderLeftStyle = pieces[1]; } else if (len === 3) { this.borderTopStyle = pieces[0]; this.borderRightStyle = pieces[1]; this.borderBottomStyle = pieces[2]; this.borderLeftStyle = pieces[1]; } else { this.borderTopStyle = pieces[0]; this.borderRightStyle = pieces[1]; this.borderBottomStyle = pieces[2]; this.borderLeftStyle = pieces[3]; } return this.borderStyle; } }); /** * The top border color of the element * * @type String * @default 'none' **/ elementProto.borderTopColor = 'none'; /** * The right border color of the element * * @type String * @default 'none' **/ elementProto.borderRightColor = 'none'; /** * The bottom border color of the element * * @type String * @default 'none' **/ elementProto.borderBottomColor = 'none'; /** * The left border color of the element * * @type String * @default 'none' **/ elementProto.borderLeftColor = 'none'; Object.defineProperty(elementProto, 'borderColor', { /** * The color of the element's border * * @name Element#borderColor * @type String **/ get: function() { return this.borderTopColor + ' ' + this.borderRightColor + ' ' + this.borderBottomColor + ' ' + this.borderLeftColor; }, set: function(borderColor) { var pieces = borderColor.split(' ') , len = pieces.length; if (len === 1) { this.borderTopColor = pieces[0]; this.borderRightColor = pieces[0]; this.borderBottomColor = pieces[0]; this.borderLeftColor = pieces[0]; } else if (len === 2) { this.borderTopColor = pieces[0]; this.borderRightColor = pieces[1]; this.borderBottomColor = pieces[0]; this.borderLeftColor = pieces[1]; } else if (len === 3) { this.borderTopColor = pieces[0]; this.borderRightColor = pieces[1]; this.borderBottomColor = pieces[2]; this.borderLeftColor = pieces[1]; } else { this.borderTopColor = pieces[0]; this.borderRightColor = pieces[1]; this.borderBottomColor = pieces[2]; this.borderLeftColor = pieces[3]; } return this.borderColor; } }); /** * Allows the element to be moved using the mouse * * @type Boolean * @default false **/ elementProto.draggable = false; /** * Registers a "mousemove" event listener on the element * * @param {String|Function} callback * @returns {Element} this **/ elementProto.mousemove = function(callback) { if (isString(callback)) callback = parseMethod(callback); if (isFunction(callback)) this.addEventListener('mousemove', callback); return this; }; /** * Registers a "mouseenter" event listener on the element * * @param {String|Function} callback * @returns {Element} this **/ elementProto.mouseenter = function(callback) { if (isString(callback)) callback = parseMethod(callback); if (isFunction(callback)) this.addEventListener('mouseenter', callback); return this; }; /** * Registers a "mouseleave" event listener on the element * * @param {String|Function} callback * @returns {Element} this **/ elementProto.mouseleave = function(callback) { if (isString(callback)) callback = parseMethod(callback); if (isFunction(callback)) this.addEventListener('mouseleave', callback); return this; }; /** * Registers a "mousedown" event listener on the element * * @param {String|Function} callback * @returns {Element} this **/ elementProto.mousedown = function(callback) { if (isString(callback)) callback = parseMethod(callback); if (isFunction(callback)) this.addEventListener('mousedown', callback); return this; }; /** * Registers a "mouseup" event listener on the element * * @param {String|Function} callback * @returns {Element} this **/ elementProto.mouseup = function(callback) { if (isString(callback)) callback = parseMethod(callback); if (isFunction(callback)) this.addEventListener('mouseup', callback); return this; }; /** * Edits the element * * @param {Object} source * @returns {Element} this **/ elementProto.edit = function(source) { return use(this, source); }; /** * Returns the element's scene or null * * @returns {?Scene} * @todo (?)Check Layer contains Element and Scene contains Layer **/ elementProto.getScene = function() { var layer = this.parentLayer; return is(layer, Layer) && is(layer.root, Scene) ? layer.root : null; }; /** * Determines if the element is child of a container * * @param {ContainerElement} container * @returns {Boolean} **/ elementProto.isChildOf = function(container) { var current = container; do { if (this.parentElement === current) return true; current = current.parentElement; } while (is(current, ContainerElement)); return false; }; /** * Scales the element * * @param {int} widthRatio * @param {int} heightRatio * @returns {Element} this **/ elementProto.scale = function(widthRatio, heightRatio) { this.scaleX = widthRatio; this.scaleY = heightRatio; return this; }; /** * Adds a class to the element's classList * * @param {String} item * @param {int} [orderID] * @returns {Element} this * @see ClassList#add **/ elementProto.addClass = function(item, orderID) { this.classList.add(item, orderID); return this; }; /** * Toggles a class * * @param {String} item * @param {int} [orderID] * @returns {Element} this * @see ClassList#toggle **/ elementProto.toggleClass = function(item, orderID) { this.classList.toggle(item, orderID); return this; }; /** * Removes a class from the element's classList * * @param {String} item * @returns {Element} this * @see OrderedList#remove **/ elementProto.removeClass = function(item) { this.classList.remove(item); return this; }; /** * Toggles a boolean property of the element * * @param {String} propertyKey * @returns {Element} this **/ elementProto.toggle = function(propertyKey) { if (isBoolean(this[propertyKey])) { this[propertyKey] = !this[propertyKey]; } return this; }; /** * Applies transformation to the rendering context * * @param {CanvasRenderingContext2D} ctx * @returns {Element} this **/ elementProto.applyTransform = function(ctx) { var r = isNumber(this.angle) ? deg2rad(this.angle % 360) : 0 , scaleX = isNumber(this.scaleX) ? this.scaleX : 1 , scaleY = isNumber(this.scaleY) ? this.scaleY : 1 , tx, ty; if (this.flipX === true) scaleX *= -1; if (this.flipY === true) scaleY *= -1; if (r !== 0 || scaleX !== 1 || scaleY !== 1) { tx = this.screenX + this.renderWidth / 2; ty = this.screenY + this.renderHeight / 2; ctx.translate(tx, ty); if (r !== 0) ctx.rotate(r); if (scaleX !== 1 || scaleY !== 1) ctx.scale(scaleX, scaleY); ctx.translate(-tx, -ty); } return this; }; /** * Applies a mask to the rendering context * * @param {CanvasRenderingContext2D} ctx * @returns {Element} this **/ elementProto.applyMask = function(ctx) { var mask = $masks.get(this.mask); if (!isNull(mask)) { ctx.beginPath(); mask(ctx, this); ctx.clip(); } return this; }; /** * Draws background and border if necessary * * @param {CanvasRenderingContext2D} ctx * @returns {Element} this * @todo Implement lineDash **/ elementProto.drawBox = function(ctx) { var x = this.screenX , y = this.screenY , w = this.renderWidth , h = this.renderHeight; if (this.background !== '') { ctx.fillStyle = this.background; ctx.fillRect(x, y, w, h); } if (this.borderTopWidth > 0) { ctx.beginPath(); ctx.lineWidth = this.borderTopWidth; ctx.strokeStyle = this.borderTopColor; // ctx.setLineDash(); ctx.moveTo(x, y); ctx.lineTo(x + w, y); ctx.stroke(); } if (this.borderRightWidth > 0) { ctx.beginPath(); ctx.lineWidth = this.borderRightWidth; ctx.strokeStyle = this.borderRightColor; // ctx.setLineDash(); ctx.moveTo(x + w, y); ctx.lineTo(x + w, y + h); ctx.stroke(); } if (this.borderBottomWidth > 0) { ctx.beginPath(); ctx.lineWidth = this.borderBottomWidth; ctx.strokeStyle = this.borderBottomColor; // ctx.setLineDash(); ctx.moveTo(x + w, y + h); ctx.lineTo(x, y + h); ctx.stroke(); } if (this.borderLeftWidth > 0) { ctx.beginPath(); ctx.lineWidth = this.borderLeftWidth; ctx.strokeStyle = this.borderLeftColor; // ctx.setLineDash(); ctx.moveTo(x, y + h); ctx.lineTo(x, y); ctx.stroke(); } return this; }; /** * Updates the element (move by it's velocity) * * @returns {Element} this **/ elementProto.update = function() { if (isNumber(this.x) && isNumber(this.vX)) { this.x += this.vX; if (isNumber(this.minX) && this.x < this.minX) this.x = this.minX; if (isNumber(this.maxX) && this.x > this.maxX) this.x = this.maxX; } if (isNumber(this.y) && isNumber(this.vY)) { this.y += this.vY; if (isNumber(this.minY) && this.y < this.minY) this.y = this.minY; if (isNumber(this.maxY) && this.y > this.maxY) this.y = this.maxY; } return this; }; /** * Creates an animation task * * @param {Object} animData * @param {int} duration * @param {int} [delay] * @returns {Task} * @todo Handle colors and non-numeric values **/ elementProto.animation = function(animData, duration, delay) { var initial = getProps(this, keys(animData)) , fn = function(tick, elapsed) { var percent = range(0, 1, elapsed / (duration || 0)); forIn(initial, function(propKey) { this[propKey] = initial[propKey] + (animData[propKey] - initial[propKey]) * percent; }, this); return percent === 1; }; return new Task(fn, delay, this); }; /** * If the element is in a scene, adds an animation task to the scene's queue * * @param {Object} animData * @param {int} duration * @param {int} [delay] * @returns {?Task} **/ elementProto.animate = function(animData, duration, delay) { var scene = this.getScene() , task = null; if (is(scene, Scene)) { task = this.animation(animData, duration, delay); scene.queue.add(task, true); } return task; }; /** * Returns a clone of the element * * @returns {Element} **/ elementProto.clone = function() { var constructor = $elements.getInstantiatable(this.elementName) , element = null , elementUse, properties; if (!isNull(constructor)) { elementUse = stdClass(); properties = this.getProps(); forEach(properties, function(prop) { if (prop.value !== 'inherit') elementUse[prop.key] = prop.value; }); element = new constructor(elementUse); } return element; }; /** * Returns the string value of the element * * @returns {String} **/ elementProto.toString = function() { return 'Chill Element[' + this.elementType + ']'; }; var elementClass = $classes.fromPrototype( elementProto, [ // ignored properties 'elementType', 'elementName', 'top', 'right', 'bottom', 'left', 'screenX', 'screenY', 'parentX', 'parentY', 'renderWidth', 'renderHeight', 'onFocus', 'dragState' ] ); $elements.addType(elementProto.elementName, Element, false, true); $classes.set(elementProto.elementType, elementClass);
bokodi/chillJS
src/core/Element.js
JavaScript
mit
33,138
/** * Default Panels for Pattern Lab plus Panel related events * * note: config is coming from the default viewer and is passed through from PL's config */ import { PrismLanguages as Prism } from './prism-languages'; import { Dispatcher } from '../utils'; export const Panels = { panels: [], count() { return this.panels.length; }, get() { return JSON.parse(JSON.stringify(Panels.panels)); }, add(panel) { // if ID already exists in panels array ignore the add() for (let i = 0; i < this.panels.length; ++i) { if (panel.id === this.panels[i].id) { return; } } // it wasn't found so push the tab onto the tabs this.panels.push(panel); }, remove(id) { const panels = this.panels; for (let i = panels.length - 1; i >= 0; i--) { if (panels[i].id === id) { const panelToRemove = panels[i]; panels.splice(i, 1); //if removed panel was default, set first panel as new default, if exists if (panelToRemove.default && panels.length) { panels[0].default = true; } return; //should be no more panels with the same id } } }, }; function init(event) { // does the origin sending the message match the current host? if not dev/null the request const fileSuffixPattern = window.config.outputFileSuffixes !== undefined && window.config.outputFileSuffixes.rawTemplate !== undefined ? window.config.outputFileSuffixes.rawTemplate : ''; const fileSuffixMarkup = window.config.outputFileSuffixes !== undefined && window.config.outputFileSuffixes.markupOnly !== undefined ? window.config.outputFileSuffixes.markupOnly : '.markup-only'; // add the default panels // Panels.add({ 'id': 'pl-panel-info', 'name': 'info', 'default': true, 'templateID': 'pl-panel-template-info', 'httpRequest': false, 'prismHighlight': false, 'keyCombo': '' }); const languages = Object.keys(Prism.languages); // TODO: sort out pl-panel-html Panels.add({ id: 'pl-panel-pattern', name: window.config.patternExtension.toUpperCase(), default: true, templateID: 'pl-panel-template-code', httpRequest: true, httpRequestReplace: fileSuffixPattern, httpRequestCompleted: false, prismHighlight: true, language: languages[window.config.patternExtension], keyCombo: 'ctrl+shift+u', }); Panels.add({ id: 'pl-panel-html', name: 'HTML', default: false, templateID: 'pl-panel-template-code', httpRequest: true, httpRequestReplace: fileSuffixMarkup + '.html', httpRequestCompleted: false, prismHighlight: true, language: 'markup', keyCombo: 'ctrl+shift+y', }); } // gather panels from plugins Dispatcher.trigger('setupPanels'); init();
bolt-design-system/bolt
packages/uikit-workshop/src/scripts/components/panels.js
JavaScript
mit
2,943
version https://git-lfs.github.com/spec/v1 oid sha256:4683f5e177392cb502f8c856a4aa32000b062d0aea820991c42454318f0d66da size 1635
yogeshsaroya/new-cdnjs
ajax/libs/codemirror/4.3.0/mode/z80/z80.min.js
JavaScript
mit
129
using UnityEngine; using UnityEditor; using System.Collections; namespace UForms.Controls.Fields { /// <summary> /// /// </summary> public class CurveField : AbstractField< AnimationCurve > { /// <summary> /// /// </summary> public Color CurveColor { get; set; } /// <summary> /// /// </summary> public Rect CurveRect { get; set; } /// <summary> /// /// </summary> protected override Vector2 DefaultSize { get { return new Vector2( 200.0f, 16.0f ); } } /// <summary> /// /// </summary> protected override bool UseBackingFieldChangeDetection { get { return false; } } /// <summary> /// /// </summary> /// <param name="curveColor"></param> /// <param name="curveRect"></param> /// <param name="value"></param> /// <param name="label"></param> public CurveField( Color curveColor = default(Color), Rect curveRect = default(Rect), AnimationCurve value = default(AnimationCurve), string label = "" ) : base( value, label ) { CurveColor = curveColor; CurveRect = curveRect; if ( value == null ) { m_cachedValue = AnimationCurve.Linear( 0f, 0f, 1f, 1f ); } } /// <summary> /// /// </summary> /// <param name="position"></param> /// <param name="size"></param> /// <param name="curveColor"></param> /// <param name="curveRect"></param> /// <param name="value"></param> /// <param name="label"></param> public CurveField( Vector2 position, Vector2 size, Color curveColor = default(Color), Rect curveRect = default(Rect), AnimationCurve value = default(AnimationCurve), string label = "" ) : base( position, size, value, label ) { CurveColor = curveColor; CurveRect = curveRect; if ( value == null ) { m_cachedValue = AnimationCurve.Linear( 0f, 0f, 1f, 1f ); } } /// <summary> /// Apparently EditorGUI.CurveField is tightnly related to the inspector GUI and will throw an expection if the curve editor is opened without an inspector panel available. /// To bypass this issue, we will disable the control's interactivity if no selection is available. /// TODO :: probably need to find a more elegant solution as the current behavior limits the usefulness of this control. /// </summary> /// <returns></returns> protected override AnimationCurve DrawAndUpdateValue() { bool isActive = ( Selection.objects.Length > 0 ); AnimationCurve temp = m_cachedValue; if ( isActive ) { temp = EditorGUI.CurveField( ScreenRect, Label, m_cachedValue, CurveColor, CurveRect ); } else { EditorGUI.BeginDisabledGroup( true ); EditorGUI.CurveField( ScreenRect, Label, m_cachedValue, CurveColor, CurveRect ); EditorGUI.EndDisabledGroup(); } return temp; } /// <summary> /// /// </summary> /// <param name="oldval"></param> /// <param name="newval"></param> /// <returns></returns> protected override bool TestValueEquality( AnimationCurve oldval, AnimationCurve newval ) { if ( oldval == null || newval == null ) { if ( oldval == null && newval == null ) { return true; } return false; } return oldval.Equals( newval ); } } }
kilguril/UForms
Assets/UForms/Runtime/Editor/Controls/Fields/CurveField.cs
C#
mit
3,930
import itertools as it from conference_scheduler.resources import Shape, Constraint from conference_scheduler.lp_problem import utils as lpu def _schedule_all_events(events, slots, X, summation_type=None, **kwargs): shape = Shape(len(events), len(slots)) summation = lpu.summation_functions[summation_type] label = 'Event either not scheduled or scheduled multiple times' for event in range(shape.events): yield Constraint( f'{label} - event: {event}', summation(X[event, slot] for slot in range(shape.slots)) == 1 ) def _max_one_event_per_slot(events, slots, X, summation_type=None, **kwargs): shape = Shape(len(events), len(slots)) summation = lpu.summation_functions[summation_type] label = 'Slot with multiple events scheduled' for slot in range(shape.slots): yield Constraint( f'{label} - slot: {slot}', summation(X[(event, slot)] for event in range(shape.events)) <= 1 ) def _events_available_in_scheduled_slot(events, slots, X, **kwargs): """ Constraint that ensures that an event is scheduled in slots for which it is available """ slot_availability_array = lpu.slot_availability_array(slots=slots, events=events) label = 'Event scheduled when not available' for row, event in enumerate(slot_availability_array): for col, availability in enumerate(event): if availability == 0: yield Constraint( f'{label} - event: {row}, slot: {col}', X[row, col] <= availability ) def _events_available_during_other_events( events, slots, X, summation_type=None, **kwargs ): """ Constraint that ensures that an event is not scheduled at the same time as another event for which it is unavailable. Unavailability of events is either because it is explicitly defined or because they share a tag. """ summation = lpu.summation_functions[summation_type] event_availability_array = lpu.event_availability_array(events) label = 'Event clashes with another event' for slot1, slot2 in lpu.concurrent_slots(slots): for row, event in enumerate(event_availability_array): if events[row].unavailability: for col, availability in enumerate(event): if availability == 0: yield Constraint( f'{label} - event: {row} and event: {col}', summation( (X[row, slot1], X[col, slot2]) ) <= 1 + availability ) def _upper_bound_on_event_overflow( events, slots, X, beta, summation_type=None, **kwargs ): """ This is an artificial constraint that is used by the objective function aiming to minimise the maximum overflow in a slot. """ label = 'Artificial upper bound constraint' for row, event in enumerate(events): for col, slot in enumerate(slots): yield Constraint( f'{label} - slot: {col} and event: {row}', event.demand * X[row, col] - slot.capacity <= beta) def all_constraints(events, slots, X, beta=None, summation_type=None): kwargs = { 'events': events, 'slots': slots, 'X': X, 'beta': beta, 'summation_type': summation_type } generators = [ _schedule_all_events, _max_one_event_per_slot, _events_available_in_scheduled_slot, _events_available_during_other_events, ] if beta is not None: generators.append(_upper_bound_on_event_overflow) for generator in generators: for constraint in generator(**kwargs): yield constraint
PyconUK/ConferenceScheduler
src/conference_scheduler/lp_problem/constraints.py
Python
mit
3,874
package com.arellomobile.android.push.utils.notification; import android.app.Notification; /** * Date: 30.10.12 * Time: 18:14 * * @author MiG35 */ public interface NotificationFactory { void generateNotification(); void addSoundAndVibrate(); void addCancel(); Notification getNotification(); }
laurion/wabbit-client
Hackathon/YoeroBasePush/src/com/arellomobile/android/push/utils/notification/NotificationFactory.java
Java
mit
330
#region Using namespaces... using System; using System.Diagnostics; using System.IO; using Ninject; using NLog; using NLog.Config; using NLog.Targets; #endregion namespace Expanse.Services.Logger { internal sealed class LoggerService : Core.Services.Logger.LoggerService { #region Private Fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly NLog.Logger _log; #endregion #region Constructor [Inject, DebuggerStepThrough] public LoggerService() { //TODO move this to configuration var pathToLog = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments), @"Expances\Log\"); if (!Directory.Exists(pathToLog)) { Directory.CreateDirectory(pathToLog); } var config = new LoggingConfiguration(); var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); fileTarget.FileName = $"{pathToLog}/{"${shortdate}.log"}"; fileTarget.Layout = "${level}|${date}|${machinename}|${windows-identity} ${message}"; var consoleTarget = new ConsoleTarget { Name = "String", Layout = "${message}" }; config.AddTarget(consoleTarget); #if DEBUG config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, fileTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, consoleTarget)); #else config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget)); config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget)); #endif LogManager.Configuration = config; _log = LogManager.GetCurrentClassLogger(); //Info("Current directory: {0}", Environment.CurrentDirectory); } #endregion #region Public Methods [DebuggerStepThrough] public override void Trace(string message, params object[] args) => _log.Trace(message, args); [DebuggerStepThrough] public override void Debug(string message, params object[] args) => _log.Debug(message, args); [DebuggerStepThrough] public override void Info(string message, params object[] args) => _log.Info(message, args); [DebuggerStepThrough] public override void Warn(string message, params object[] args) => _log.Warn(message, args); [DebuggerStepThrough] public override void Error(string message, params object[] args) => _log.Error(message, args); [DebuggerStepThrough] public override void Fatal(string message, params object[] args) => _log.Fatal(message, args); #endregion } }
DaniilMonin/Expanse.js
Expanse/Expanse.Services/Logger/LoggerService.cs
C#
mit
2,840
#ifndef STACK_HPP #define STACK_HPP #include "Deque.hpp" namespace tour { template <class T> class Stack{ private: Deque<T> _deque; public: Stack(); //construtor ~Stack (); //metodo destruidor bool push(T); //insere elemento no inicio da pilha, usa pushFront do deque void pop (); //remove ultimo elemento, usa popBack do deque T& top(); //mostra o primeiro elemento da pilha, usa o front do deque bool empty(); //retorna verdadeiro se pilha estiver vazio, falso caso contrario, usa o empty do deque }; template <class T> tour::Stack<T>::Stack() { } template <class T> tour::Stack<T>::~Stack() { } template <class T> void tour::Stack<T>::pop() { _deque.popFront(); } template <class T> bool tour::Stack<T>::push (T element){ return _deque.pushFront(element); } template <class T> T& tour::Stack<T>::top(){ return _deque.front(); } template <class T> bool tour::Stack<T>::empty() { return _deque.empty(); } } #endif
falcaopetri/ufscar-summer-tour
include/Stack.hpp
C++
mit
1,069
import java.util.*; public class Sort { private List<String> names = Arrays.asList("Peter", "Ali", "Moe", "Eli"); // This 4 comparators have same functionality. private Comparator<String> myComp1 = new Comparator<String>(){ @Override public int compare(String a, String b) { return a.compareTo(b); } }; private Comparator<String> myComp2 = (String a, String b) -> { return a.compareTo(b); }; private Comparator<String> myComp3 = (String a, String b) -> a.compareTo(b); private Comparator<String> myComp4 = (a, b) -> a.compareTo(b); public Sort() {} private void sortMe() { Collections.sort(names, myComp4); } private void printCollection() { System.out.println(names); } public static void main(String[] args) { System.out.println("Hello Sort!"); Sort s = new Sort(); s.sortMe(); s.printCollection(); } }
nejads/java8-examples
Sort.java
Java
mit
1,003
module MatrixDdLppT16 class Fraccion #Módulo Comparable include Comparable attr_reader :num, :dem def initialize(num,dem) @num, @dem = num, dem mcm = gcd(num, dem) @num = num/mcm @dem = dem/mcm end #Calculo del minimo comun multiplo def gcd(u, v) u, v = u.abs, v.abs while v != 0 u, v = v, u % v end u end #Convierte a string def to_s "#{@num}/#{@dem}" end def coerce(other) [other, self] end #Convierte a flotante def to_f() @num.to_f/@dem.to_f end #Suma de fracciones def +(other) return Fraccion.new((other.dem * @num) + (@dem * other.num), @dem * other.dem) end #Multiplicacion de fracciones def *(other) return Fraccion.new(@num * other.num, @dem * other.dem) end end end
alu0100498820/prct11
lib/matrix_dd_lpp_t16/fraccion.rb
Ruby
mit
878
package net.robig.stlab; import net.robig.logging.Logger; import net.robig.stlab.util.config.AbstractValue; import net.robig.stlab.util.config.BoolValue; import net.robig.stlab.util.config.DoubleValue; import net.robig.stlab.util.config.IValueChangeListener; import net.robig.stlab.util.config.IntValue; import net.robig.stlab.util.config.LongValue; import net.robig.stlab.util.config.MapValue; import net.robig.stlab.util.config.StringValue; import net.robig.stlab.util.config.ObjectConfig; import net.robig.stlab.util.config.SystemPropertyValueChangeListener; /** * Easy type save access to all used config parameters * * @author robegroe * */ public class StLabConfig extends ObjectConfig { static final Logger log = new Logger(StLabConfig.class); static String environment = null; public static String getEnvironment() { if(environment==null) environment=getStringValue("environment", "production").getValue(); if(environment.equals("")) environment="production"; return environment; } public static String getEnvironmentString() { String env=getEnvironment(); if(env.equals("production")) return ""; return " ("+env+")"; } public static String getWebUrl(){ if(getEnvironment().equals("DIT")) return "http://robig.net/stlab-dit/"; if(getEnvironment().equals("UAT")) return "http://robig.net/stlab-uat/"; return "http://stlab.robig.net/"; } public static String getTaCUrl(){ return "http://robig.net/redmine/projects/stlab/wiki/StlabWebTaC"; } public static String getFeedbackUrl(){ return "http://sourceforge.net/apps/phpbb/stlab/"; } public static String getAboutUrl(){ return "http://robig.net/wiki/?wiki=EnStLab"; } // System.getProperties().put( "proxySet", "true" ); // System.getProperties().put( "proxyHost", "192.168.100.2" ); // System.getProperties().put( "proxyPort", "8080" ); public static StringValue getWebProxyUsername(){ StringValue v=getStringValue("web.proxy.user", ""); IValueChangeListener l = new SystemPropertyValueChangeListener("proxyUsername"); l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static StringValue getWebProxyPassword(){ StringValue v=getStringValue("web.proxy.pass", ""); IValueChangeListener l = new SystemPropertyValueChangeListener("proxyPassword"); l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static StringValue getWebProxyHost(){ StringValue v=getStringValue("web.proxy.host", ""); IValueChangeListener l = new SystemPropertyValueChangeListener("proxyHost"); l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static IntValue getWebProxyPort() { IntValue v=getIntValue("web.proxy.port", 8080); IValueChangeListener l = new SystemPropertyValueChangeListener("proxyPort"); l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static BoolValue isWebProxyEnabled(){ final BoolValue v=getBoolValue("web.proxy.enabled", false); IValueChangeListener l = new IValueChangeListener() { @Override public void valueChanged(AbstractValue av) { boolean e=v.getSimpleValue(); log.info((e?"Enabled":"Disabled")+" proxy"); System.getProperties().put( "proxySet", (e?"true":"false") ); if(!e){ System.getProperties().remove( "proxyPort" ); System.getProperties().remove( "proxyHost" ); } } }; l.valueChanged(v); //hack to initialize proxy on startup v.addChangeListener(l); return v; } public static boolean isUpdateCheckEnabled() { return getCheckForUpdates().getValue(); } public static BoolValue getCheckForUpdates() { return getBoolValue("startup.checkforupdates", true); } public static IntValue getMouseSensitivity() { return getIntValue("knobs.mouse.sensitivity",150); } public static void setMouseSensitivity(int value) { setIntValue("knobs.mouse.sensitivity",value); } public static DoubleValue getMouseWheelSensitivity() { return getDoubleValue("knobs.mousewheel.sensitivity",1.0); } public static void setMouseWheelSensitivity(double value) { setDoubleValue("knobs.mousewheel.sensitivity",value); } public static MapValue getAuthorInfo() { return (MapValue) getAbstractValue("preset.author", new MapValue("preset.author")); } public static StringValue getAuthor(){ return getStringValue("preset.author.name", System.getProperty("user.name")); } public static BoolValue getPresetListWindowVisible() { return getBoolValue("presetlist.visible", false); } public static IntValue getPresetListWindowWidth(){ return getIntValue("presetlist.width", 650); } public static IntValue getPresetListWindowHeight(){ return getIntValue("presetlist.height", 450); } public static IntValue getPresetListWindowX(){ return getIntValue("presetlist.x", 0); } public static IntValue getPresetListWindowY(){ return getIntValue("presetlist.y", 0); } public static IntValue getLiveWindowX(){ return getIntValue("livewindow.x", 0); } public static IntValue getLiveWindowY(){ return getIntValue("livewindow.y", 0); } /** Get last Directory */ public static StringValue getPresetsDirectory() { return getStringValue("directory.presets", ""); } /** Should the selected preset transfered directly to the device? */ public static BoolValue getOpenDialogActivatePresetOnSelection(){ return getBoolValue("opendialog.activate.presets", true); } public static StringValue getWebUsername() { return getStringValue("stlab-web.username", ""); } public static BoolValue isSpaceSwitchesPresetListEnabled(){ return getBoolValue("presetlist.space.switch", true); } }
robig/stlab
src/net/robig/stlab/StLabConfig.java
Java
mit
5,762
using System; using System.Diagnostics.Contracts; using System.Windows; using starshipxac.Windows.Devices.Interop; using starshipxac.Windows.Interop; namespace starshipxac.Windows.Devices { /// <summary> /// スクリーン情報を保持します。 /// </summary> public class Screen : IEquatable<Screen> { /// <summary> /// モニターハンドルを指定して、 /// <see cref="Screen" />クラスの新しいインスタンスを初期化します。 /// </summary> /// <param name="hMonitor">モニターハンドル。</param> internal Screen(IntPtr hMonitor) { Contract.Requires<ArgumentNullException>(hMonitor != IntPtr.Zero); this.Handle = hMonitor; } internal static Screen Create(IntPtr hMonitor) { var monitorInfo = MONITORINFOEX.Create(); var success = MultiMonitorNativeMethods.GetMonitorInfo(hMonitor, ref monitorInfo); if (!success) { return null; } var dpi = Dpi.Create(hMonitor); return new Screen(hMonitor) { DeviceName = monitorInfo.szDevice, IsPrimary = monitorInfo.dwFlags == MultiMonitorNativeMethods.MONITORINFOF_PRIMARY, Dpi = dpi, Bounds = CreateRect(monitorInfo.rcMonitor, dpi), WorkingArea = CreateRect(monitorInfo.rcWork, dpi) }; } /// <summary> /// モニターハンドルを取得します。 /// </summary> internal IntPtr Handle { get; } /// <summary> /// デバイス名を取得します。 /// </summary> public string DeviceName { get; private set; } /// <summary> /// 第一スクリーンかどうかを判定する値を取得します。 /// </summary> public bool IsPrimary { get; private set; } /// <summary> /// スクリーンの DPIを取得します。 /// </summary> public Dpi Dpi { get; private set; } /// <summary> /// スクリーンのサイズを取得します。 /// </summary> public Rect Bounds { get; private set; } /// <summary> /// スクリーン内のアプリケーション動作領域のサイズを取得します。 /// </summary> public Rect WorkingArea { get; private set; } public bool Equals(Screen other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return this.Handle.Equals(other.Handle); } private static Rect CreateRect(RECT rect, Dpi dpi) { var factorX = dpi.X/(double)Dpi.Default.X; var factorY = dpi.Y/(double)Dpi.Default.Y; var left = rect.Left/factorX; var top = rect.Top/factorY; var width = rect.Width/factorX; var height = rect.Height/factorY; return new Rect(left, top, width, height); } public static bool operator ==(Screen x, Screen y) { return Equals(x, y); } public static bool operator !=(Screen x, Screen y) { return !Equals(x, y); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } if (ReferenceEquals(this, obj)) { return true; } return Equals((Screen)obj); } public override int GetHashCode() { return this.Handle.GetHashCode(); } public override string ToString() { return $"{{DeviceName: {this.DeviceName}}}"; } } }
starshipxac/starshipxac.ShellLibrary
Source/starshipxac.Windows/Devices/Screen.cs
C#
mit
4,288
package lists import ( "reflect" "testing" ) type TestPairStringSlice struct { In StringSlice Out interface{} } type TestPairStringSlice2Out struct { In StringSlice Out1 interface{} Out2 interface{} } type TestPairGenericSlice struct { In []interface{} Out interface{} } type TestPairIntSlice struct { In []int Out interface{} } // P01 (*) Find the last element of a list. // Example: // ?- my_last(X,[a,b,c,d]). // X = d var TestPairsLastElement = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, "d"}, {StringSlice{"a", "b", "c"}, "c"}, {StringSlice{"a", "b", "c", "d", "e"}, "e"}, {StringSlice{"a", "b"}, "b"}, {StringSlice{"a"}, "a"}, {StringSlice{}, ""}, } var TestPairsLastElementButOne = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, "c"}, {StringSlice{"a", "b", "c"}, "b"}, {StringSlice{"a", "b", "c", "d", "e"}, "d"}, {StringSlice{"a", "b"}, "a"}, {StringSlice{"a"}, ""}, {StringSlice{}, ""}, } var TestPairsNthElement = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, "c"}, {StringSlice{"a", "b", "c"}, "c"}, {StringSlice{"a", "b", "c", "d", "e"}, "c"}, {StringSlice{"a", "b"}, ""}, {StringSlice{"a"}, ""}, {StringSlice{}, ""}, } var TestPairsLength = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, 4}, {StringSlice{"a", "b", "c"}, 3}, {StringSlice{"a", "b", "c", "d", "e"}, 5}, {StringSlice{"a", "b"}, 2}, {StringSlice{"a"}, 1}, {StringSlice{}, 0}, } var TestPairsReverse = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"h", "g", "f", "e", "d", "c", "b", "a"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g"}, StringSlice{"g", "f", "e", "d", "c", "b", "a"}}, {StringSlice{"a", "b", "c", "d", "e", "f"}, StringSlice{"f", "e", "d", "c", "b", "a"}}, {StringSlice{"a", "b", "c", "d", "e"}, StringSlice{"e", "d", "c", "b", "a"}}, {StringSlice{"a", "b", "c", "d"}, StringSlice{"d", "c", "b", "a"}}, {StringSlice{"a", "b", "c"}, StringSlice{"c", "b", "a"}}, {StringSlice{"a", "b"}, StringSlice{"b", "a"}}, } var TestPairsPalindrome = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "d", "c", "b", "a"}, true}, {StringSlice{"a", "b", "a", "b", "b", "a", "b", "a"}, true}, {StringSlice{"a", "b", "c", "d", "c", "b", "a"}, true}, {StringSlice{"a"}, true}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, false}, {StringSlice{"a", "b", "c", "d", "e", "f", "g"}, false}, {StringSlice{"a", "b"}, false}, } var TestPairsFlatten = []TestPairGenericSlice{ {[]interface{}{[]interface{}{"a", []interface{}{"b", []interface{}{"c", "d"}, "e"}}}, StringSlice{"a", "b", "c", "d", "e"}}, } var TestPairsCompress = []TestPairStringSlice{ {StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}, StringSlice{"a", "b", "c", "a", "d", "e"}}, {StringSlice{"a", "a", "a", "a"}, StringSlice{"a"}}, {StringSlice{"a", "a", "a", "a", "b", "c", "c", "c", "c"}, StringSlice{"a", "b", "c"}}, {StringSlice{"a", "a", "a", "a", "b", "b", "b"}, StringSlice{"a", "b"}}, } var TestPairsPack = []TestPairStringSlice{ {StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}, []StringSlice{{"a", "a", "a", "a"}, {"b"}, {"c", "c"}, {"a", "a"}, {"d"}, {"e", "e", "e", "e"}}}, } var TestPairsEncode = []TestPairStringSlice{ {StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}, []EncodedPair{{4, "a"}, {1, "b"}, {2, "c"}, {2, "a"}, {1, "d"}, {4, "e"}}}, } var TestPairsEncodeModified = []TestPairStringSlice{ {StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}, []interface{}{EncodedPair{4, "a"}, "b", EncodedPair{2, "c"}, EncodedPair{2, "a"}, "d", EncodedPair{4, "e"}}}, } var TestPairsDecode = []TestPairGenericSlice{ {[]interface{}{EncodedPair{4, "a"}, "b", EncodedPair{2, "c"}, EncodedPair{2, "a"}, "d", EncodedPair{4, "e"}}, StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}}, } var TestPairsEncodeDirect = []TestPairStringSlice{ {StringSlice{"a", "a", "a", "a", "b", "c", "c", "a", "a", "d", "e", "e", "e", "e"}, []interface{}{EncodedPair{4, "a"}, "b", EncodedPair{2, "c"}, EncodedPair{2, "a"}, "d", EncodedPair{4, "e"}}}, } var TestPairsDuplicate = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "c", "d"}, StringSlice{"a", "a", "b", "b", "c", "c", "c", "c", "d", "d"}}, } var TestPairsDuplicateN = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "c", "d"}, StringSlice{"a", "a", "a", "b", "b", "b", "c", "c", "c", "c", "c", "c", "d", "d", "d"}}, } var TestPairsDropEveryN = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h", "i", "k"}, StringSlice{"a", "b", "d", "e", "g", "h"}}, } var TestPairsSplitN = []TestPairStringSlice2Out{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h", "i", "k"}, StringSlice{"a", "b", "c"}, StringSlice{"d", "e", "f", "g", "h", "i", "k"}}, } var TestPairsSlice = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h", "i", "k"}, StringSlice{"c", "d", "e", "f", "g"}}, } var TestPairsRotate = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"b", "c", "d", "e", "f", "g", "h", "a"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"c", "d", "e", "f", "g", "h", "a", "b"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"d", "e", "f", "g", "h", "a", "b", "c"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"e", "f", "g", "h", "a", "b", "c", "d"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"f", "g", "h", "a", "b", "c", "d", "e"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"g", "h", "a", "b", "c", "d", "e", "f"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"h", "a", "b", "c", "d", "e", "f", "g"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"b", "c", "d", "e", "f", "g", "h", "a"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"c", "d", "e", "f", "g", "h", "a", "b"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"d", "e", "f", "g", "h", "a", "b", "c"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"e", "f", "g", "h", "a", "b", "c", "d"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"f", "g", "h", "a", "b", "c", "d", "e"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"g", "h", "a", "b", "c", "d", "e", "f"}}, {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, StringSlice{"h", "a", "b", "c", "d", "e", "f", "g"}}, } var TestPairsRemoveAt = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, StringSlice{"a", "c", "d"}}, } var TestPairsInsertAt = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d"}, StringSlice{"a", "alfa", "b", "c", "d"}}, } var TestPairsRange = []TestPairIntSlice{ {[]int{4, 9}, []int{4, 5, 6, 7, 8, 9}}, } var TestPairsRndSelect = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f", "g", "h"}, 3}, } var TestPairsLotto = []TestPairIntSlice{ {[]int{6, 49}, 6}, } var TestPairsRndPermu = []TestPairStringSlice{ {StringSlice{"a", "b", "c", "d", "e", "f"}, 6}, } func TestLastElement(t *testing.T) { for _, pair := range TestPairsLastElement { result, _ := pair.In.LastElement() if result != pair.Out { t.Errorf("Expected %v but got %v", pair.Out, result) } } } func TestLastElementThrowsError(t *testing.T) { _, err := TestPairsLastElement[5].In.LastElement() if err == nil { t.Errorf("Expected to throw error: ", err) } } func BenchmarkLastElement(b *testing.B) { for n := 0; n < b.N; n++ { TestPairsLastElement[0].In.LastElement() } } // P02 (*) Find the last but one element of a list. // (zweitletztes Element, l'avant-dernier élément) func TestLastElementButOne(t *testing.T) { for _, pair := range TestPairsLastElementButOne { result, _ := pair.In.LastElementButOne() if result != pair.Out { t.Errorf("Expected %v but got %v", pair.Out, result) } } } func TestLastElementButOneThrowsError(t *testing.T) { _, err := TestPairsLastElementButOne[5].In.LastElementButOne() if err == nil { t.Errorf("Expected to throw error: ", err) } } func BenchmarkLastElementButOne(b *testing.B) { for n := 0; n < b.N; n++ { TestPairsLastElementButOne[0].In.LastElementButOne() } } // P03 (*) Find the K'th element of a list. // The first element in the list is number 1. // Example: // ?- element_at(X,[a,b,c,d,e],3). // X = c func TestNthElement(t *testing.T) { for _, pair := range TestPairsNthElement { result, _ := pair.In.NthElement(3) if result != pair.Out { t.Errorf("Expected %v but got %v", pair.Out, result) } } } func TestNthElementThrowsError(t *testing.T) { _, err := TestPairsNthElement[5].In.NthElement(3) if err == nil { t.Errorf("Expected to throw error: ", err) } } func BenchmarkNthElement(b *testing.B) { for n := 0; n < b.N; n++ { TestPairsNthElement[0].In.NthElement(4) } } // P04 (*) Find the number of elements of a list. func TestLength(t *testing.T) { for _, pair := range TestPairsLength { result := pair.In.Length() if result != pair.Out { t.Errorf("Expected %v but got %v", pair.Out, result) } } } func BenchmarkLength(b *testing.B) { for n := 0; n < b.N; n++ { TestPairsLength[0].In.Length() } } // P05 (*) Reverse a list. func TestReverse(t *testing.T) { for _, pair := range TestPairsReverse { result := pair.In.Reverse() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkReverse(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsReverse[0].In.Reverse() } } // P06 (*) Find out whether a list is a palindrome. // A palindrome can be read forward or backward; e.g. [x,a,m,a,x]. func TestIsPalindrome(t *testing.T) { for _, pair := range TestPairsPalindrome { if pair.In.IsPalindrome() != pair.Out.(bool) { t.Errorf("Expected %v to be %v", pair.In, pair.Out.(bool)) } } } func BenchmarkIsPalindrome(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsPalindrome[0].In.IsPalindrome() } } // P07 (**) Flatten a nested list structure. // Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively). // Example: // ?- my_flatten([a, [b, [c, d], e]], X). // X = [a, b, c, d, e] // Hint: Use the predefined predicates is_list/1 and append/3 func TestFlatten(t *testing.T) { for _, pair := range TestPairsFlatten { result := Flatten(pair.In) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkFlatten(b *testing.B) { for i := 0; i < b.N; i++ { Flatten(TestPairsFlatten[0].In) } } // P08 (**) Eliminate consecutive duplicates of list elements. // If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed. // Example: // ?- compress([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). // X = [a,b,c,a,d,e] func TestCompress(t *testing.T) { for _, pair := range TestPairsCompress { result := pair.In.Compress() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkCompress(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsCompress[0].In.Compress() } } // P09 (**) Pack consecutive duplicates of list elements into sublists. // If a list contains repeated elements they should be placed in separate sublists. // Example: // ?- pack([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). // X = [[a,a,a,a],[b],[c,c],[a,a],[d],[e,e,e,e]] func TestPack(t *testing.T) { for _, pair := range TestPairsPack { result := pair.In.Pack() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkPack(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsCompress[0].In.Pack() } } // P10 (*) Run-length encoding of a list. // Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as terms [N,E] where N is the number of duplicates of the element E. // Example: // ?- encode([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). // X = [[4,a],[1,b],[2,c],[2,a],[1,d][4,e]] func TestEncode(t *testing.T) { for _, pair := range TestPairsEncode { result := pair.In.Encode() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkEncode(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsEncode[0].In.Encode() } } // P11 (*) Modified run-length encoding. // Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as [N,E] terms. // Example: // ?- encode_modified([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). // X = [[4,a],b,[2,c],[2,a],d,[4,e]] func TestEncodeModified(t *testing.T) { for _, pair := range TestPairsEncodeModified { result := pair.In.EncodeModified() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkEncodeModified(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsEncode[0].In.EncodeModified() } } // P12 (**) Decode a run-length encoded list. // Given a run-length code list generated as specified in problem P11. Construct its uncompressed version. func TestDecode(t *testing.T) { for _, pair := range TestPairsDecode { result := Decode(pair.In) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkDecode(b *testing.B) { for i := 0; i < b.N; i++ { Decode(TestPairsDecode[0].In) } } // P13 (**) Run-length encoding of a list (direct solution). // Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem P09, but only count them. As in problem P11, simplify the result list by replacing the singleton terms [1,X] by X. // "Direct" means to not use Pack() or Compress() // Example: // ?- encode_direct([a,a,a,a,b,c,c,a,a,d,e,e,e,e],X). // X = [[4,a],b,[2,c],[2,a],d,[4,e]] func TestEncodeDirect(t *testing.T) { for _, pair := range TestPairsEncodeDirect { result := pair.In.EncodeDirect() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkEncodeDirect(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsEncode[0].In.Encode() } } // P14 (*) Duplicate the elements of a list. // Example: // ?- dupli([a,b,c,c,d],X). // X = [a,a,b,b,c,c,c,c,d,d] func TestDuplicate(t *testing.T) { for _, pair := range TestPairsDuplicate { result := pair.In.Duplicate() if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkDuplicate(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsDuplicate[0].In.Duplicate() } } // P15 (**) Duplicate the elements of a list a given number of times. // Example: // ?- dupli([a,b,c],3,X). // X = [a,a,a,b,b,b,c,c,c] // What are the results of the goal: // ?- dupli(X,3,Y). func TestDuplicateN(t *testing.T) { for _, pair := range TestPairsDuplicateN { result := pair.In.DuplicateN(3) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkDuplicateN(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsDuplicateN[0].In.DuplicateN(3) } } // P16 (**) Drop every N'th element from a list. // Example: // ?- drop([a,b,c,d,e,f,g,h,i,k],3,X). // X = [a,b,d,e,g,h,k] func TestDropEveryN(t *testing.T) { for _, pair := range TestPairsDropEveryN { result := pair.In.DropEveryN(3) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkDropEveryN(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsDropEveryN[0].In.DropEveryN(3) } } // P17 (*) Split a list into two parts; the length of the first part is given. // Do not use any predefined predicates. // Example: // ?- split([a,b,c,d,e,f,g,h,i,k],3,L1,L2). // L1 = [a,b,c] // L2 = [d,e,f,g,h,i,k] func TestSplitN(t *testing.T) { for _, pair := range TestPairsSplitN { result1, result2 := pair.In.SplitN(3) if !reflect.DeepEqual(result1, pair.Out1) { t.Errorf("Expected %v to be %v", result1, pair.Out1) } if !reflect.DeepEqual(result2, pair.Out2) { t.Errorf("Expected %v to be %v", result2, pair.Out2) } } } func BenchmarkSplitN(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsSplitN[0].In.SplitN(3) } } // P18 (**) Extract a slice from a list. // Given two indices, I and K, the slice is the list containing the elements between the I'th and K'th element of the original list (both limits included). Start counting the elements with 1. // Example: // ?- slice([a,b,c,d,e,f,g,h,i,k],3,7,L). // X = [c,d,e,f,g] func TestSlice(t *testing.T) { for _, pair := range TestPairsSlice { result := pair.In.Slice(3, 7) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkSlice(b *testing.B) { TestPairsSlice[0].In.Slice(3, 7) } // P19 (**) Rotate a list N places to the left. // Examples: // ?- rotate([a,b,c,d,e,f,g,h],3,X). // X = [d,e,f,g,h,a,b,c] // ?- rotate([a,b,c,d,e,f,g,h],-2,X). // X = [g,h,a,b,c,d,e,f] // Hint: Use the predefined predicates length/2 and append/3, as well as the result of problem P17. // http://www.cs.bell-labs.com/cm/cs/pearls/rotate.c // Programming Pearls 2.3 func TestRotate(t *testing.T) { var dist = -7 for _, pair := range TestPairsRotate { result := pair.In.Rotate(dist, len(pair.In)) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected Rotate(%v) to be %v but got %v", dist, pair.Out, result) } dist++ } } func BenchmarkRotate(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsRotate[0].In.Rotate(3, TestPairsRotate[0].In.Length()) } } // P20 (*) Remove the K'th element from a list. // Example: // ?- remove_at(X,[a,b,c,d],2,R). // X = b // R = [a,c,d] func TestRemoveAt(t *testing.T) { for _, pair := range TestPairsRemoveAt { result := pair.In.RemoveAt(2) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } func BenchmarkRemoveAt(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsRemoveAt[0].In.RemoveAt(2) } } // P21 (*) Insert an element at a given position into a list. // Example: // ?- insert_at(alfa,[a,b,c,d],2,L). // L = [a,alfa,b,c,d] func TestInsertAt(t *testing.T) { for _, pair := range TestPairsInsertAt { result := pair.In.InsertAt(2, "alfa") if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } // P22 (*) Create a list containing all integers within a given range. // Example: // ?- range(4,9,L). // L = [4,5,6,7,8,9] func TestRange(t *testing.T) { for _, pair := range TestPairsRange { result := Range(pair.In[0], pair.In[1]) if !reflect.DeepEqual(result, pair.Out) { t.Errorf("Expected %v to be %v", result, pair.Out) } } } // P23 (**) Extract a given number of randomly selected elements from a list. // The selected items shall be put into a result list. // Example: // ?- rnd_select([a,b,c,d,e,f,g,h],3,L). // L = [e,d,a] // Hint: Use the built-in random number generator random/2 and the result of problem P20. func TestRndSelect(t *testing.T) { for _, pair := range TestPairsRndSelect { result := pair.In.RndSelect(3) if len(result) != pair.Out { t.Errorf("Expected %v to be len of %v", result, pair.Out) } } } func BenchmarkRndSelect(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsRndSelect[0].In.RndSelect(3) } } // P24 (*) Lotto: Draw N different random numbers from the set 1..M. // The selected numbers shall be put into a result list. // Example: // ?- rnd_select(6,49,L). // L = [23,1,17,33,21,37] func TestLotto(t *testing.T) { for _, pair := range TestPairsLotto { result := Lotto(pair.In[0], pair.In[1]) if len(result) != pair.Out { t.Errorf("Expected %v to be len of %v", result, pair.Out) } } } func BenchmarkLotto(b *testing.B) { for i := 0; i < b.N; i++ { Lotto(TestPairsLotto[0].In[0], TestPairsLotto[0].In[1]) } } // Hint: Combine the solutions of problems P22 and P23. // P25 (*) Generate a random permutation of the elements of a list. // Example: // ?- rnd_permu([a,b,c,d,e,f],L). // L = [b,a,d,c,e,f] // Hint: Use the solution of problem P23. func TestRndPermu(t *testing.T) { for _, pair := range TestPairsRndPermu { result := pair.In.RndPermu() if len(result) != pair.Out { t.Errorf("Expected %v to be len of %v", result, pair.Out) } } } func BenchmarkRndPermu(b *testing.B) { for i := 0; i < b.N; i++ { TestPairsRndPermu[0].In.RndPermu() } } // P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list // In how many ways can a committee of 3 be chosen from a group of 12 people? We all know that there are C(12,3) = 220 possibilities (C(N,K) denotes the well-known binomial coefficients). For pure mathematicians, this result may be great. But we want to really generate all the possibilities (via backtracking). // Example: // ?- combination(3,[a,b,c,d,e,f],L). // L = [a,b,c] ; // L = [a,b,d] ; // L = [a,b,e] ; // ... var TestPairsCombination = []struct { s StringSlice m int }{ {StringSlice{"a", "b", "c", "d", "e"}, 3}, } func TestCombination(t *testing.T) { for _, pair := range TestPairsCombination { pair.s.Combination(pair.m) } } // P27 (**) Group the elements of a set into disjoint subsets. // a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a predicate that generates all the possibilities via backtracking. // Example: // ?- group3([aldo,beat,carla,david,evi,flip,gary,hugo,ida],G1,G2,G3). // G1 = [aldo,beat], G2 = [carla,david,evi], G3 = [flip,gary,hugo,ida] // ... // b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. // Example: // ?- group([aldo,beat,carla,david,evi,flip,gary,hugo,ida],[2,2,5],Gs). // Gs = [[aldo,beat],[carla,david],[evi,flip,gary,hugo,ida]] // ... // Note that we do not want permutations of the group members; i.e. [[aldo,beat],...] is the same solution as [[beat,aldo],...]. However, we make a difference between [[aldo,beat],[carla,david],...] and [[carla,david],[aldo,beat],...]. // You may find more about this combinatorial problem in a good book on discrete mathematics under the term "multinomial coefficients". // P28 (**) Sorting a list of lists according to length of sublists // a) We suppose that a list (InList) contains elements that are lists themselves. The objective is to sort the elements of InList according to their length. E.g. short lists first, longer lists later, or vice versa. // Example: // ?- lsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L). // L = [[o], [d, e], [d, e], [m, n], [a, b, c], [f, g, h], [i, j, k, l]] // b) Again, we suppose that a list (InList) contains elements that are lists themselves. But this time the objective is to sort the elements of InList according to their length frequency; i.e. in the default, where sorting is done ascendingly, lists with rare lengths are placed first, others with a more frequent length come later. // Example: // ?- lfsort([[a,b,c],[d,e],[f,g,h],[d,e],[i,j,k,l],[m,n],[o]],L). // L = [[i, j, k, l], [o], [a, b, c], [f, g, h], [d, e], [d, e], [m, n]] // Note that in the above example, the first two lists in the result L have length 4 and 1, both lengths appear just once. The third and forth list have length 3 which appears, there are two list of this length. And finally, the last three lists have length 2. This is the most frequent length.
heynickc/ninety_nine_prolog
lists/lists_test.go
GO
mit
24,126
package presenters
open-gtd/server
tags/presentation/presenters/dummy_test.go
GO
mit
19
class Solution { public: static bool cmp(string a, string b){ if(a.length()!=b.length()) return a.length()>b.length(); if(a.compare(b)<0) return true; return false; } string findLongestWord(string s, vector<string>& d) { sort(d.begin(),d.end(),cmp); map<char,vector<int>> ind; for(int i=0;i<s.length();i++){ ind[s[i]].push_back(i); } for(int i=0;i<d.size();i++){ if(ind[d[i][0]].size()==0) continue; int prev=ind[d[i][0]].front(); bool work=true; for(int j=1;j<d[i].length();j++){ if(ind[d[i][j]].size()==0){ work=false; break; } bool found=false; for(int k=0;k<ind[d[i][j]].size();k++){ if(ind[d[i][j]][k]>prev){ prev=ind[d[i][j]][k]; found=true; break; } } if(!found){ work=false; break; } } if(work) return d[i]; } return ""; } };
zfang399/LeetCode-Problems
524.cpp
C++
mit
1,218
import sinon from 'sinon'; import unexpected from 'unexpected'; import unexpectedSinon from 'unexpected-sinon'; import unexpectedKnex from 'unexpected-knex'; import { Knorm } from '../src/Knorm'; import { Virtual } from '../src/Virtual'; import { knex } from '../util/knex'; import { postgresPlugin } from '../util/postgresPlugin'; const expect = unexpected.clone().use(unexpectedSinon).use(unexpectedKnex); describe('Model', () => { let Model; let Query; let Field; before(() => { ({ Model, Query, Field } = new Knorm()); }); describe('constructor', () => { describe('when the model has virtuals', () => { it("adds virtual's getters on the instance", () => { class Foo extends Model {} Foo.virtuals = { foo: { get() { return 'foo'; }, }, }; const foo = new Foo(); expect(foo.foo, 'to be', 'foo'); }); it('adds the getters with the correct scope', () => { class Foo extends Model {} Foo.virtuals = { foo: { get() { return this.theValue; }, }, }; const foo = new Foo(); foo.theValue = 'bar'; expect(foo.foo, 'to be', 'bar'); }); it("adds virtual's setters on the instance with the correct scope", () => { class Foo extends Model {} Foo.virtuals = { foo: { set(value) { this.theValue = value; }, }, }; const foo = new Foo(); foo.foo = 'bar'; expect(foo.theValue, 'to be', 'bar'); }); }); describe('with data provided', () => { it('calls Model.prototype.setData to populate the instance with the data', () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', }, }; const spy = sinon.spy(Foo.prototype, 'setData'); // eslint-disable-next-line no-unused-vars const field = new Foo({ id: 1 }); expect(spy, 'to have calls satisfying', () => { spy({ id: 1, }); }); spy.restore(); }); }); }); describe('Model.prototype.getField', () => { it('returns the field requested', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, }; const foo = new Foo(); expect(foo.getField('foo'), 'to equal', Foo.fields.foo); }); }); describe('Model.prototype.getFields', () => { it("returns all the model's fields if called with no arguments", () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, }; const foo = new Foo(); expect(foo.getFields(), 'to equal', [Foo.fields.foo]); }); it('returns an array of `Field` instances', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, }; const foo = new Foo(); expect(foo.getFields(['foo']), 'to satisfy', [ expect.it('to be a', Field), ]); }); it('returns the correct fields', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, bar: { type: 'string', }, }; const foo = new Foo(); expect(foo.getFields(['bar', 'foo']), 'to satisfy', [ Foo.fields.bar, Foo.fields.foo, ]); }); it('returns the same fields if passed an array of field instances', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, bar: { type: 'string', }, }; const foo = new Foo(); expect(foo.getFields([Foo.fields.bar, Foo.fields.foo]), 'to satisfy', [ Foo.fields.bar, Foo.fields.foo, ]); }); }); describe('Model.prototype.setData', () => { it('populates the instance with the data with the passed object', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', }, bar: { type: 'integer', }, }; const foo = new Foo(); expect(foo.foo, 'to be undefined'); expect(foo.bar, 'to be undefined'); foo.setData({ foo: 'foo', bar: 1, }); expect(foo.foo, 'to equal', 'foo'); expect(foo.bar, 'to equal', 1); }); it('populates virtuals if provided in the object', () => { class Foo extends Model {} Foo.virtuals = { bar: { get() { return this.setVirtualBarValue; }, set(value) { this.setVirtualBarValue = value; }, }, }; const foo = new Foo(); expect(foo.bar, 'to be undefined'); foo.setData({ bar: 1, }); expect(foo.bar, 'to equal', 1); }); it("calls the virtual's setter with this set to the model instance", () => { class Foo extends Model {} const spy = sinon.spy(); Foo.virtuals = { bar: { set: spy, }, }; const foo = new Foo(); foo.setData({ bar: 1 }); expect(spy, 'was called once').and('was called on', foo); }); it('returns the model instance to allow chaining', () => { class Foo extends Model {} Foo.fields = { foo: { required: true, type: 'string', }, }; const foo = new Foo(); expect(foo.setData({ foo: 'foo' }), 'to satisfy', foo); }); // https://github.com/knorm/knorm/issues/239 it('ignores virtuals in the object that have no setters', () => { class Foo extends Model {} Foo.virtuals = { bar: { get() { return 'bar'; }, }, }; const foo = new Foo(); expect(foo.bar, 'to be', 'bar'); foo.setData({ bar: 1 }); expect(foo.bar, 'to be', 'bar'); }); it('filters out `undefined` values from the data', () => { class Foo extends Model {} Foo.virtuals = { foo: { set(value) { if (value === undefined) { throw new Error('wat'); } }, }, }; const foo = new Foo(); expect(() => foo.setData({ foo: undefined }), 'not to throw'); }); }); describe('Model.prototype.setDefaults', () => { it('populates all configured fields with the configured default value', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', default: 'foo', }, bar: { type: 'string', default: 'bar', }, }; const foo = new Foo(); expect(foo.foo, 'to be undefined'); expect(foo.bar, 'to be undefined'); foo.setDefaults(); expect(foo.foo, 'to equal', 'foo'); expect(foo.bar, 'to equal', 'bar'); }); it('accepts a list of fields to populate with the configured default value', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', default: 'foo', }, bar: { type: 'string', default: 'bar', }, }; const foo = new Foo(); expect(foo.foo, 'to be undefined'); expect(foo.bar, 'to be undefined'); foo.setDefaults({ fields: ['bar'] }); expect(foo.foo, 'to be undefined'); expect(foo.bar, 'to equal', 'bar'); }); it("doesn't overwrite values that have already been set", () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', default: 'foo', }, }; const foo = new Foo(); foo.foo = 'dont change me'; expect(foo.foo, 'to be', 'dont change me'); foo.setDefaults(); expect(foo.foo, 'to be', 'dont change me'); }); describe("when a field's default value is a function", () => { it('calls the function and populates the field with the return value', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', default() { return 'foo'; }, }, }; const foo = new Foo(); expect(foo.foo, 'to be undefined'); foo.setDefaults(); expect(foo.foo, 'to be', 'foo'); }); it('calls the function with the model instance as a parameter', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', required: true, }, bar: { type: 'string', required: true, }, computed: { type: 'string', default(model) { return model.foo + model.bar; }, }, }; const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; expect(foo.computed, 'to be undefined'); foo.setDefaults(); expect(foo.computed, 'to be', 'foobar'); }); }); it('returns the model instance to allow chaining', () => { class Foo extends Model {} Foo.fields = { foo: { type: 'string', default: true, }, }; const foo = new Foo(); expect(foo.setDefaults(), 'to satisfy', foo); }); }); describe('Model.prototype.getFieldData', () => { let Foo; before(() => { Foo = class extends Model {}; Foo.fields = { foo: 'string', bar: 'string' }; }); it('returns an object mapping fields to their values', () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = null; expect(foo.getFieldData(), 'to equal', { foo: 'foo', bar: null, }); }); it('does not include fields whose value has not been set', () => { const foo = new Foo(); foo.foo = 'foo'; expect(foo.getFieldData(), 'to equal', { foo: 'foo', bar: undefined, }); }); it('does not include properties set on the model that are not fields', () => { const foo = new Foo(); foo.foo = 'foo'; foo.quux = 'quux'; expect(foo.getFieldData(), 'to equal', { foo: 'foo', quux: undefined, }); }); describe('with a `fields` option', () => { it('only returns data for the requested fields', () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; expect(foo.getFieldData({ fields: ['bar'] }), 'to equal', { bar: 'bar', }); }); it('does not include a field without a value even if it has been requested', () => { const foo = new Foo(); foo.foo = 'foo'; expect(foo.getFieldData({ fields: ['bar'] }), 'to equal', {}); }); }); }); describe('Model.prototype.getVirtualData', () => { it('resolves with an object with virtuals and their data', async () => { class Foo extends Model {} Foo.virtuals = { bar() { return 'bar'; }, }; const foo = new Foo(); await expect( foo.getVirtualData(), 'to be fulfilled with value exhaustively satisfying', { bar: 'bar' } ); }); it('resolves with data from async virtuals (that return a Promise)', async () => { class Foo extends Model {} Foo.virtuals = { bar() { return Promise.resolve('bar'); }, }; const foo = new Foo(); await expect( foo.getVirtualData(), 'to be fulfilled with value exhaustively satisfying', { bar: 'bar' } ); }); it('skips virtuals that have no getters', async () => { class Foo extends Model {} Foo.virtuals = { quux: { set() {}, }, }; const foo = new Foo(); await expect( foo.getVirtualData(), 'to be fulfilled with value exhaustively satisfying', { quux: undefined } ); }); it("calls the virtuals' getters with this set to the model instance", async () => { class Foo extends Model {} const spy = sinon.spy(); Foo.virtuals = { bar: { get: spy } }; const foo = new Foo(); await foo.getVirtualData(); await expect(spy, 'was called once').and('was called on', foo); }); }); describe('with a `virtuals` option', () => { it('only includes the requested virtuals', async () => { class Foo extends Model {} Foo.virtuals = { bar: { get() { return 'bar'; }, }, quux: { get() { return 'quux'; }, }, }; const foo = new Foo(); await expect( foo.getVirtualData({ virtuals: ['bar'] }), 'to be fulfilled with value exhaustively satisfying', { bar: 'bar' } ); }); it('rejects with an error if a requested virtual has no getter', async () => { class Foo extends Model {} Foo.virtuals = { bar: { set() {}, }, }; const foo = new Foo(); await expect( foo.getVirtualData({ virtuals: ['bar'] }), 'to be rejected with', new Error("Virtual 'Foo.bar' has no getter") ); }); }); describe('Model.prototype.getVirtualDataSync', () => { let Foo; before(() => { Foo = class extends Model {}; Foo.virtuals = { foo() { return 'foo'; }, async bar() { return 'bar'; }, }; }); it('returns virtual data without async virtuals', () => { const foo = new Foo(); expect(foo.getVirtualDataSync(), 'to equal', { foo: 'foo' }); }); describe('with a `virtuals` option', () => { it('does not include async virtuals even if requested', async () => { const foo = new Foo(); expect(foo.getVirtualDataSync({ virtuals: ['bar'] }), 'to equal', {}); }); }); }); describe('Model.prototype.getData', () => { let Foo; before(() => { Foo = class extends Model {}; Foo.fields = { foo: 'string', bar: 'string' }; Foo.virtuals = { baz() { return 'baz'; }, async quux() { return 'quux'; }, }; }); it('resolves with an object with field and virtual field data', async () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; await expect( foo.getData(), 'to be fulfilled with value exhaustively satisfying', { foo: 'foo', bar: 'bar', baz: 'baz', quux: 'quux' } ); }); describe('with a `fields` option', () => { it('only includes the requested fields', async () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; await expect( foo.getData({ fields: ['bar'] }), 'to be fulfilled with value exhaustively satisfying', { bar: 'bar', baz: 'baz', quux: 'quux' } ); }); }); describe('with a `virtuals` option', () => { it('only includes the requested virtuals', async () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; await expect( foo.getData({ virtuals: ['baz'] }), 'to be fulfilled with value exhaustively satisfying', { foo: 'foo', bar: 'bar', baz: 'baz' } ); }); }); }); describe('Model.prototype.getDataSync', () => { let Foo; before(() => { Foo = class extends Model {}; Foo.fields = { foo: 'string', bar: 'string' }; Foo.virtuals = { baz() { return 'baz'; }, async quux() { return 'quux'; }, }; }); it('returns an object with field and only sync virtual field data', () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; expect(foo.getDataSync(), 'to equal', { foo: 'foo', bar: 'bar', baz: 'baz', }); }); describe('with a `fields` option', () => { it('only includes the requested fields', () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; expect(foo.getDataSync({ fields: ['bar'] }), 'to equal', { bar: 'bar', baz: 'baz', }); }); }); describe('with a `virtuals` option', () => { it('only includes the requested sync virtuals', () => { const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; expect(foo.getDataSync({ virtuals: ['baz'] }), 'to equal', { foo: 'foo', bar: 'bar', baz: 'baz', }); }); }); }); describe('Model.prototype.validate', () => { it('validates all the fields by default', async () => { class Foo extends Model {} Foo.fields = { foo: { required: true, type: 'string', }, bar: { required: true, type: 'string', }, }; const fooValidationSpy = sinon.spy(Foo.fields.foo, 'validate'); const barValidationSpy = sinon.spy(Foo.fields.bar, 'validate'); const foo = new Foo(); await expect(foo.validate(), 'to be rejected with', { name: 'ValidationError', type: 'RequiredError', }); await expect(fooValidationSpy, 'was called once'); await expect(barValidationSpy, 'was called once'); fooValidationSpy.restore(); barValidationSpy.restore(); }); describe("with a 'fields' option", () => { it('validates only the fields passed', async () => { class Foo extends Model {} Foo.fields = { foo: { required: true, type: 'string', }, bar: { required: true, type: 'string', }, }; const fooValidationSpy = sinon.spy(Foo.fields.foo, 'validate'); const barValidationSpy = sinon.spy(Foo.fields.bar, 'validate'); const foo = new Foo(); await expect(foo.validate({ fields: ['bar'] }), 'to be rejected with', { name: 'ValidationError', type: 'RequiredError', }); await expect(fooValidationSpy, 'was not called'); await expect(barValidationSpy, 'was called once'); fooValidationSpy.restore(); barValidationSpy.restore(); }); it('accepts a list of field objects', async () => { class Foo extends Model {} Foo.fields = { foo: { required: true, type: 'string', }, bar: { required: true, type: 'string', }, }; const fooValidationSpy = sinon.spy(Foo.fields.foo, 'validate'); const barValidationSpy = sinon.spy(Foo.fields.bar, 'validate'); const foo = new Foo(); await expect( foo.validate({ fields: [Foo.fields.bar] }), 'to be rejected with', { name: 'ValidationError', type: 'RequiredError', } ); await expect(fooValidationSpy, 'was not called'); await expect(barValidationSpy, 'was called once'); fooValidationSpy.restore(); barValidationSpy.restore(); }); }); it('calls the validator with the set value and the model instance', async () => { class Foo extends Model {} Foo.fields = { bar: { type: 'string', }, }; const barValidationSpy = sinon.spy(Foo.fields.bar, 'validate'); const foo = new Foo(); foo.bar = 'bar'; await foo.validate({ fields: ['bar'] }); await expect(barValidationSpy, 'to have calls satisfying', () => { barValidationSpy('bar', foo); }); barValidationSpy.restore(); }); it('rejects with the error from Field.prototype.validate', async () => { class Foo extends Model {} Foo.fields = { bar: { type: 'string', }, }; const barValidationStub = sinon.stub(Foo.fields.bar, 'validate'); barValidationStub.returns(Promise.reject(new Error('foo happens'))); const foo = new Foo(); await expect( foo.validate({ fields: ['bar'] }), 'to be rejected with', new Error('foo happens') ); barValidationStub.restore(); }); it('resolves with the model instance to allow chaining', async () => { class Foo extends Model {} Foo.fields = { bar: { default: true, type: 'string', }, }; const foo = new Foo(); await expect( foo.validate({ fields: ['bar'] }), 'to be fulfilled with', foo ); }); }); describe('Model.prototype.cast', () => { it('casts all the fields that have cast functions and a value set', async () => { class Foo extends Model {} const fooSaveCast = sinon.spy(); Foo.fields = { foo: { required: true, type: 'string', cast: { forSave: fooSaveCast, }, }, bar: { required: true, type: 'string', }, }; const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; foo.cast({ forSave: true }); await expect(fooSaveCast, 'was called once'); }); describe("with a 'fields' option", () => { it('casts only the fields passed', async () => { class Foo extends Model {} const fooSaveCast = sinon.spy(); const barSaveCast = sinon.spy(); Foo.fields = { foo: { required: true, type: 'string', cast: { forSave: fooSaveCast, }, }, bar: { required: true, type: 'string', cast: { forSave: barSaveCast, }, }, }; const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; foo.cast({ fields: ['bar'], forSave: true }); await expect(fooSaveCast, 'was not called'); await expect(barSaveCast, 'was called once'); }); it('accepts a list of field objects', async () => { class Foo extends Model {} const fooSaveCast = sinon.spy(); const barSaveCast = sinon.spy(); Foo.fields = { foo: { required: true, type: 'string', cast: { forSave: fooSaveCast, }, }, bar: { required: true, type: 'string', cast: { forSave: barSaveCast, }, }, }; const foo = new Foo(); foo.foo = 'foo'; foo.bar = 'bar'; foo.cast({ fields: [Foo.fields.foo, Foo.fields.bar], forSave: true }); await expect(fooSaveCast, 'was called once'); await expect(barSaveCast, 'was called once'); }); }); it('calls Field.prototype.cast with the set value, the model instance and options passed', () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() {}, }, }, }; const barCastSpy = sinon.spy(Foo.fields.bar, 'cast'); const foo = new Foo(); foo.bar = 'bar'; foo.cast({ fields: ['bar'], forSave: true }); expect(barCastSpy, 'to have calls satisfying', () => { barCastSpy('bar', foo, { forSave: true, forFetch: undefined }); }); barCastSpy.restore(); }); it('does not call Field.prototype.cast if the field has no value set', () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() {}, }, }, }; const barCastSpy = sinon.spy(Foo.fields.bar, 'cast'); const foo = new Foo(); foo.cast({ fields: ['bar'], forSave: true }); expect(barCastSpy, 'was not called'); barCastSpy.restore(); }); it("calls Field.prototype.cast if the field's value is `null`", () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() {}, }, }, }; const barCastSpy = sinon.spy(Foo.fields.bar, 'cast'); const foo = new Foo(); foo.bar = null; foo.cast({ fields: ['bar'], forSave: true }); expect(barCastSpy, 'was called once'); barCastSpy.restore(); }); it('updates the set value with the value from the cast function', () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() { return 'new value'; }, }, }, }; const foo = new Foo(); foo.bar = 'bar'; foo.cast({ fields: ['bar'], forSave: true }); expect(foo.bar, 'to be', 'new value'); }); it('does not update the set value if the cast function returns `undefined`', () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() {}, }, }, }; const foo = new Foo(); foo.bar = 'bar'; foo.cast({ fields: ['bar'], forSave: true }); expect(foo.bar, 'to be', 'bar'); }); it('updates the set value if the cast function returns `null`', () => { class Foo extends Model {} Foo.fields = { bar: { required: true, type: 'string', cast: { forSave() { return null; }, }, }, }; const foo = new Foo(); foo.bar = 'bar'; foo.cast({ fields: ['bar'], forSave: true }); expect(foo.bar, 'to be', null); }); it('returns the model instance to allow chaining', () => { class Foo extends Model {} Foo.fields = { bar: { default: true, type: 'string', cast: { forSave() {}, }, }, }; const foo = new Foo(); expect(foo.cast({ fields: ['bar'] }, { forSave: true }), 'to be', foo); }); }); describe('Model.prototype.getQuery', () => { let Query; let Model; let Foo; before(() => { ({ Model, Query } = new Knorm()); Foo = class extends Model {}; Foo.table = 'foo'; Foo.fields = { id: { type: 'integer', primary: true, }, name: { type: 'string', }, }; }); it('passes any options passed to Query.prototype.setOptions', () => { const setOptions = sinon .stub(Query.prototype, 'setOptions') .returnsThis(); new Foo({ id: 1 }).getQuery({ returning: 'name' }); expect(setOptions, 'to have calls satisfying', () => setOptions({ returning: 'name' }) ); setOptions.restore(); }); it('sets `first` to `true`', () => { const first = sinon.stub(Query.prototype, 'first').returnsThis(); new Foo({ id: 1 }).getQuery(); expect(first, 'to have calls satisfying', () => first(true)); first.restore(); }); it('sets `require` to `true` by default', () => { const require = sinon.stub(Query.prototype, 'require').returnsThis(); new Foo({ id: 1 }).getQuery(); expect(require, 'to have calls satisfying', () => require(true)); require.restore(); }); it('allows overriding the `require` option to `false`', () => { const require = sinon.stub(Query.prototype, 'require').returnsThis(); new Foo({ id: 1 }).getQuery({ require: false }); expect(require, 'to have calls satisfying', () => require(false)); require.restore(); }); it('passes the primary field set on the model to Query.prototype.where', () => { const where = sinon.stub(Query.prototype, 'where').returnsThis(); new Foo({ id: 1 }).getQuery(); expect(where, 'to have calls satisfying', () => where({ id: 1 })); where.restore(); }); it('throws if the primary field is not set', () => { expect( () => new Foo({}).getQuery(), 'to throw', new Error('Foo: primary field (`id`) is not set') ); }); it('appends the `where` clause if a `where` option is passed', () => { const where = sinon.stub(Query.prototype, 'where').returnsThis(); new Foo({ id: 1 }).getQuery({ where: { name: 'foo' } }); expect(where, 'to have calls satisfying', () => { where({ name: 'foo' }); where({ id: 1 }); }); where.restore(); }); describe('with unique fields configured', () => { let Foo; let whereStub; before(() => { Foo = class extends Model {}; Foo.table = 'foo'; Foo.fields = { id: { type: 'integer', primary: true, }, name: { type: 'string', unique: true, }, number: { type: 'integer', unique: true, }, }; whereStub = sinon.stub(Query.prototype, 'where').returnsThis(); }); beforeEach(() => { whereStub.resetHistory(); }); after(() => { whereStub.restore(); }); it('uses the unique fields in a where clause if the primary field is not set', () => { new Foo({ name: 'foo' }).getQuery(); expect(whereStub, 'to have calls satisfying', () => whereStub({ name: 'foo' }) ); }); it('uses the primary field if both unique and primary fields are set', () => { new Foo({ id: 1, name: 'foo' }).getQuery(); expect(whereStub, 'to have calls satisfying', () => whereStub({ id: 1 }) ); }); it('uses only one of the primary fields if more than one are set', () => { new Foo({ name: 'foo', number: 1 }).getQuery(); expect(whereStub, 'to have calls satisfying', () => whereStub({ name: 'foo' }) ); }); it('throws if neither the primary field nor unique fields are set', () => { expect( () => new Foo({}).getQuery(), 'to throw', new Error('Foo: primary field (`id`) is not set') ); }); }); describe('for inserts', () => { it('does not throw if the primary field is not set', () => { expect( () => new Foo({}).getQuery({}, { forInsert: true }), 'not to throw' ); }); it('does not construct a `where` clause', () => { const where = sinon.stub(Query.prototype, 'where').returnsThis(); new Foo({ id: 1 }).getQuery({}, { forInsert: true }); expect(where, 'was not called'); where.restore(); }); }); }); describe('Model.config', () => { describe('as a setter', () => { it("adds the model to the Knorm instances' models", () => { const knorm = new Knorm(); class Foo extends knorm.Model {} expect(knorm.models.Foo, 'to be undefined'); Foo.config = {}; expect(knorm.models.Foo, 'to be', Foo); }); }); describe('when a model is subclassed', () => { it("adds the subclassed model to the Knorm instances' models", () => { const knorm = new Knorm(); class Foo extends knorm.Model {} Foo.config = {}; expect(knorm.models.Foo, 'to be', Foo); class Bar extends Foo {} Bar.config = {}; expect(knorm.models.Foo, 'to be', Foo); expect(knorm.models.Bar, 'to be', Bar); }); }); }); describe('Model.schema', () => { describe('as a setter', () => { it("sets the model's schema", () => { class Foo extends Model {} Foo.schema = 'foo'; expect(Foo.config.schema, 'to be', 'foo'); }); }); describe('when a model is subclassed', () => { it("inherits the parent's schema", () => { class Foo extends Model {} Foo.schema = 'foo'; class Bar extends Foo {} expect(Foo.schema, 'to be', 'foo'); expect(Bar.schema, 'to be', 'foo'); }); it("inherits the parent's schema when other configs are set", function () { class Foo extends Model {} Foo.schema = 'foo'; class Bar extends Foo {} Bar.table = 'bar'; expect(Foo.schema, 'to be', 'foo'); expect(Bar.schema, 'to be', 'foo'); }); it("allows overwriting the parent's schema", () => { class Foo extends Model {} Foo.schema = 'foo'; class Bar extends Foo {} Bar.schema = 'bar'; expect(Foo.schema, 'to be', 'foo'); expect(Bar.schema, 'to be', 'bar'); }); }); }); describe('Model.table', () => { describe('as a setter', () => { it("sets the model's table", () => { class Foo extends Model {} Foo.table = 'foo'; expect(Foo.config.table, 'to be', 'foo'); }); }); describe('when a model is subclassed', () => { it("inherits the parent's table", () => { class Foo extends Model {} Foo.table = 'foo'; class Bar extends Foo {} expect(Foo.table, 'to be', 'foo'); expect(Bar.table, 'to be', 'foo'); }); it("inherits the parent's table when other configs are set", function () { class Foo extends Model {} Foo.table = 'foo'; class Bar extends Foo {} Bar.fields = { bar: 'string' }; expect(Foo.table, 'to be', 'foo'); expect(Bar.table, 'to be', 'foo'); }); it("allows overwriting the parent's table", () => { class Foo extends Model {} class Bar extends Foo {} Foo.table = 'foo'; Bar.table = 'bar'; expect(Foo.table, 'to be', 'foo'); expect(Bar.table, 'to be', 'bar'); }); }); }); describe('Model.fields', () => { describe('as a getter', () => { it('returns added fields', () => { class User extends Model {} User.fields = { firstName: { type: 'string', }, }; expect(User.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); }); }); describe('as a setter', () => { it("adds the passed fields to the model's fields", () => { class User extends Model {} User.fields = { firstName: { type: 'string', }, }; expect(User.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); }); it("allows adding fields via the `fieldName: 'type'` shorthand", () => { class User extends Model {} User.fields = { firstName: 'string' }; expect(User.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); }); it('throws if the field-name is already assigned to an instance property', () => { class Foo extends Model { bar() {} } expect( () => (Foo.fields = { bar: { type: 'string', }, }), 'to throw', new Error( 'Foo: cannot add field `bar` (`Foo.prototype.bar` is already assigned)' ) ); }); it('throws if the field-name is already added as a virtual', () => { class Foo extends Model {} Foo.virtuals = { bar: { get() {}, }, }; expect( () => (Foo.fields = { bar: { type: 'string', }, }), 'to throw', new Error('Foo: cannot add field `bar` (`bar` is a virtual)') ); }); describe('when a model is subclassed', () => { it('allows overwriting fields defined in the parent', () => { class User extends Model {} User.fields = { id: { type: 'string', }, }; expect(User.fields, 'to exhaustively satisfy', { id: new Field({ name: 'id', model: User, type: 'string', }), }); class OtherUser extends User {} OtherUser.fields = { id: { type: 'text', }, }; expect(OtherUser.fields, 'to exhaustively satisfy', { id: new Field({ name: 'id', model: OtherUser, type: 'text', }), }); }); it('does not duplicate fieldNames when a field is overwritten', () => { class User extends Model {} User.fields = { id: { type: 'string', }, }; expect(User.config.fieldNames, 'to equal', ['id']); class OtherUser extends User {} OtherUser.fields = { id: { type: 'text', }, }; expect(User.config.fieldNames, 'to equal', ['id']); expect(OtherUser.config.fieldNames, 'to equal', ['id']); }); it("updates the child's fields' model class", () => { class User extends Model {} User.fields = { firstName: { type: 'string', }, }; expect(User.fields, 'to satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); class Student extends User {} Student.fields = { studentId: { type: 'integer', }, }; expect(Student.fields, 'to satisfy', { firstName: new Field({ name: 'firstName', model: Student, type: 'string', }), }); }); it("doesn't interfere with the parent's fields", () => { class User extends Model {} User.fields = { id: { type: 'integer', required: true, }, }; expect(User.fields, 'to exhaustively satisfy', { id: new Field({ name: 'id', model: User, required: true, type: 'integer', }), }); class OtherUser extends User {} OtherUser.fields = { firstName: { type: 'string', }, }; expect(User.fields, 'to exhaustively satisfy', { id: new Field({ name: 'id', model: User, required: true, type: 'integer', }), }); expect(OtherUser.fields, 'to exhaustively satisfy', { id: new Field({ name: 'id', model: OtherUser, required: true, type: 'integer', }), firstName: new Field({ name: 'firstName', model: OtherUser, type: 'string', }), }); }); }); describe('with `methods` configured on a field', () => { it('adds `ByField` methods', () => { class User extends Model {} User.fields = { id: { type: 'string', methods: true, }, }; expect(User.fetchById, 'to be a function'); expect(User.updateById, 'to be a function'); expect(User.deleteById, 'to be a function'); }); it('adds the correct names for camelCased field names', () => { class User extends Model {} User.fields = { someFieldName: { type: 'string', unique: true, methods: true, }, }; expect(User.fetchBySomeFieldName, 'to be a function'); expect(User.updateBySomeFieldName, 'to be a function'); expect(User.deleteBySomeFieldName, 'to be a function'); }); it('inherits `ByField` methods', () => { class User extends Model {} class OtherUser extends User {} User.fields = { id: { type: 'string', primary: true, methods: true, }, }; expect(OtherUser.fetchById, 'to be a function'); expect(OtherUser.updateById, 'to be a function'); expect(OtherUser.deleteById, 'to be a function'); }); }); }); describe('with a getter function', () => { let User; before(() => { User = class extends Model { static get fields() { this.config = { fields: { firstName: { type: 'string' } } }; return this.config.fields; } }; }); it('returns fields added via the `Model.config` setter', () => { expect(User.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); }); it('supports field inheritance', () => { class Student extends User { static get fields() { this.config = { fields: { studentId: { type: 'integer' } } }; return this.config.fields; } } expect(User.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: User, type: 'string', }), }); expect(Student.fields, 'to exhaustively satisfy', { firstName: new Field({ name: 'firstName', model: Student, type: 'string', }), studentId: new Field({ name: 'studentId', model: Student, type: 'integer', }), }); }); }); }); describe('Model.virtuals', () => { describe('as a setter', () => { it("adds the virtuals to the model's virtuals", () => { class User extends Model {} User.virtuals = { firstName: { get() {}, set() {}, }, }; expect(User.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), set: expect.it('to be a function'), }, }), }); }); it('throws if the virtual-name is already assigned to an instance property', () => { class Foo extends Model { bar() {} } expect( () => (Foo.virtuals = { bar: { get() {}, }, }), 'to throw', new Error( 'Foo: cannot add virtual `bar` (`Foo.prototype.bar` is already assigned)' ) ); }); it('throws if the virtual-name is already added as a field', () => { class Foo extends Model {} Foo.fields = { bar: { type: 'string', }, }; expect( () => (Foo.virtuals = { bar: { get() {}, }, }), 'to throw', new Error('Foo: cannot add virtual `bar` (`bar` is a field)') ); }); describe('when a model is subclassed', () => { it('allows overwriting the virtuals defined in the parent', () => { class User extends Model {} User.virtuals = { firstName: { get() { return 'foo'; }, }, }; expect(User.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), }, }), }); class OtherUser extends User {} OtherUser.virtuals = { firstName: { get() { return 'bar'; }, }, }; expect(OtherUser.virtuals, 'to satisfy', { firstName: new Virtual({ name: 'firstName', model: OtherUser, descriptor: { get: expect.it('to be a function'), }, }), }); }); it("updates the child's virtuals' model class", () => { class User extends Model {} User.virtuals = { firstName: { get() { return 'foo'; }, }, }; expect(User.virtuals, 'to satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), }, }), }); class Student extends User {} Student.virtuals = { lastName: { get() { return 'bar'; }, }, }; expect(Student.virtuals, 'to satisfy', { firstName: new Virtual({ name: 'firstName', model: Student, descriptor: { get: expect.it('to be a function'), }, }), }); }); it("doesn't interfere with the parent's virtuals", () => { class User extends Model {} User.virtuals = { firstName: { get() { return 'foo'; }, }, }; expect(User.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), }, }), }); class OtherUser extends User {} OtherUser.virtuals = { lastName: { get() { return 'bar'; }, }, }; expect(User.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), }, }), }); expect(OtherUser.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: OtherUser, descriptor: { get: expect.it('to be a function'), }, }), lastName: new Virtual({ name: 'lastName', model: OtherUser, descriptor: { get: expect.it('to be a function'), }, }), }); }); }); }); describe('as a getter', () => { it('returns the virtuals added to the model', () => { class User extends Model {} User.virtuals = { firstName: { get() { return 'foo'; }, }, }; expect(User.virtuals, 'to exhaustively satisfy', { firstName: new Virtual({ name: 'firstName', model: User, descriptor: { get: expect.it('to be a function'), }, }), }); }); }); }); describe('Model.options', () => { describe('as a getter', () => { it('returns added options', () => { class User extends Model {} User.options = { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }); }); }); describe('as a setter', () => { it("adds the passed options to the model's options", () => { class User extends Model {} User.options = { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }); }); describe('when a model is subclassed', () => { it("merges the child's options into the parent's options", () => { class User extends Model {} User.options = { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: 'id' } }, }); class OtherUser extends User {} OtherUser.options = { query: { fields: ['id'] }, plugins: { timestamps: { createdAt: true } }, }; expect(OtherUser.options, 'to exhaustively satisfy', { query: { where: { id: 1 }, fields: ['id'] }, plugins: { toJSON: { exclude: 'id' }, timestamps: { createdAt: true }, }, }); }); it('allows overwriting options defined in the parent', () => { class User extends Model {} User.options = { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: ['id'] } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: ['id'] } }, }); class OtherUser extends User {} OtherUser.options = { query: { where: { id: 2 } }, plugins: { toJSON: { exclude: ['name'] } }, }; expect(OtherUser.options, 'to exhaustively satisfy', { query: { where: { id: 2 } }, plugins: { toJSON: { exclude: ['name'] } }, }); }); it("doesn't interfere with the parent's options", () => { class User extends Model {} User.options = { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: ['id'] } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: ['id'] } }, }); class OtherUser extends User {} OtherUser.options = { query: { where: { id: 2 } }, plugins: { toJSON: { exclude: 'name' } }, }; expect(User.options, 'to exhaustively satisfy', { query: { where: { id: 1 } }, plugins: { toJSON: { exclude: ['id'] } }, }); expect(OtherUser.options, 'to exhaustively satisfy', { query: { where: { id: 2 } }, plugins: { toJSON: { exclude: 'name' } }, }); }); }); }); }); describe('Model.config.primary', () => { describe('as a getter', () => { it('throws an error of the model has no primary field', () => { class Foo extends Model {} Foo.fields = { foo: 'string' }; expect( () => Foo.config.primary, 'to throw', new Error('`Foo` has no primary field') ); }); it("returns the field-name of the model's primary field", () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', primary: true } }; expect(Foo.config.primary, 'to equal', 'id'); }); describe('when a model is subclassed', () => { it("inherits the parent's primary field", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', primary: true } }; expect(Foo.config.primary, 'to equal', 'id'); expect(Bar.config.primary, 'to equal', 'id'); }); it("allows overwriting the parent's primary field", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', primary: true } }; Bar.fields = { uuid: { type: 'uuid', primary: true } }; expect(Foo.config.primary, 'to equal', 'id'); expect(Bar.config.primary, 'to equal', 'uuid'); }); it("allows unsetting the parent's primary field", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', primary: true } }; Bar.fields = { id: { type: 'uuid', primary: false } }; expect(Foo.config.primary, 'to equal', 'id'); expect( () => Bar.config.primary, 'to throw', new Error('`Bar` has no primary field') ); }); }); }); }); describe('Model.config.notUpdated', () => { describe('as a getter', () => { it('returns field-names that should not be updated', () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', updated: false } }; expect(Foo.config.notUpdated, 'to equal', ['id']); }); describe('when a model is subclassed', () => { it("inherits the parent's notUpdated fields", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', updated: false } }; expect(Foo.config.notUpdated, 'to equal', ['id']); expect(Bar.config.notUpdated, 'to equal', ['id']); }); it("allows overwriting the parent's notUpdated fields", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', updated: false } }; Bar.fields = { id: { type: 'integer', updated: true } }; expect(Foo.config.notUpdated, 'to equal', ['id']); expect(Bar.config.notUpdated, 'to equal', []); }); }); }); }); describe('Model.config.unique', () => { describe('as a getter', () => { it('returns field-names of unique fields', () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', unique: true } }; expect(Foo.config.unique, 'to equal', ['id']); }); describe('when a model is subclassed', () => { it("inherits the parent's unique fields", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', unique: true } }; expect(Foo.config.unique, 'to equal', ['id']); expect(Bar.config.unique, 'to equal', ['id']); }); it("allows overwriting the parent's unique fields", () => { class Foo extends Model {} class Bar extends Foo {} Foo.fields = { id: { type: 'integer', unique: true } }; Bar.fields = { id: { type: 'integer', unique: false } }; expect(Foo.config.unique, 'to equal', ['id']); expect(Bar.config.unique, 'to equal', []); }); }); }); }); describe('Model.removeField', () => { it('removes a field', () => { class Foo extends Model {} Foo.fields = { id: 'integer' }; expect(Foo.config.fields, 'to have key', 'id'); Foo.removeField(Foo.fields.id); expect(Foo.config.fields, 'to equal', {}); }); it("removes a field's field-column mappings", () => { class Foo extends Model {} Foo.fields = { id: 'integer' }; expect(Foo.config.fieldsToColumns, 'to have key', 'id'); Foo.removeField(Foo.fields.id); expect(Foo.config.fieldsToColumns, 'to equal', {}); }); it("removes the field from the model's field names", () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer' } }; expect(Foo.config.fieldNames, 'to contain', 'id'); Foo.removeField(Foo.fields.id); expect(Foo.config.fieldNames, 'to equal', []); }); it("removes the field from the model's not-updated fields", () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', updated: false } }; expect(Foo.config.notUpdated, 'to contain', 'id'); Foo.removeField(Foo.fields.id); expect(Foo.config.notUpdated, 'to equal', []); }); it("removes the field from the model's unique fields", () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', unique: true } }; expect(Foo.config.unique, 'to contain', 'id'); Foo.removeField(Foo.fields.id); expect(Foo.config.unique, 'to equal', []); }); it("removes the field from the model's primary field", () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', primary: true } }; expect(Foo.config.primary, 'to be', 'id'); Foo.removeField(Foo.fields.id); expect(() => Foo.config.primary, 'to throw'); }); it('removes *ByField methods from the model', () => { class Foo extends Model {} Foo.fields = { id: { type: 'integer', primary: true, methods: true } }; expect(Foo.updateById, 'to be a function'); Foo.removeField(Foo.fields.id); expect(Foo.updateById, 'to be undefined'); }); }); describe('Model.query', () => { let User; before(() => { User = class extends Model {}; User.table = 'foo'; User.fields = { id: { type: 'integer', primary: true } }; User.options = { query: { fields: ['id'], where: { id: 1 } } }; }); describe('as a getter', () => { it('returns a Query instance', () => { expect(User.query, 'to be a', Query); }); it('configures the Query instance with the model', () => { const spy = sinon.spy(User, 'Query'); // eslint-disable-next-line no-unused-expressions User.query; expect(User.Query, 'to have calls satisfying', () => { // eslint-disable-next-line no-new new User.Query(User); }); spy.restore(); }); it('sets configured default query options on the instance', () => { expect(User.query, 'to satisfy', { options: { fields: { id: 'id' }, where: [[{ id: 1 }]] }, }); }); }); }); describe('Model.where', () => { let User; before(() => { User = class extends Model {}; }); it('returns a `Query.Where` instance', () => { expect(User.where, 'to be a', Query.Where); }); }); describe('for db operations', () => { let Model; let Query; let User; before(() => { ({ Model, Query } = new Knorm().use(postgresPlugin)); User = class extends Model {}; User.table = 'user'; User.fields = { id: { type: 'integer', required: true, primary: true, methods: true, }, name: { type: 'string', required: true, }, }; }); before(async () => knex.schema.dropTableIfExists(User.table)); before(async () => knex.schema.createTable(User.table, (table) => { table.increments(); table.string('name').notNullable(); }) ); after(async () => knex.schema.dropTable(User.table)); afterEach(async () => knex(User.table).truncate()); describe('Model.prototype.save', () => { it('inserts a model if its primary field is not set', async () => { const user = new User({ name: 'John Doe' }); await expect( user.save(), 'to be fulfilled with value satisfying', new User({ id: 1, name: 'John Doe' }) ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'John Doe' }] ); }); it('updates a model if its primary field is set', async () => { const user = await new User({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; await expect( user.save(), 'to be fulfilled with value satisfying', new User({ id: 1, name: 'Jane Doe' }) ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'Jane Doe' }] ); }); it('passes options along', async () => { const insert = sinon .stub(Query.prototype, 'query') .returns(Promise.resolve([])); const user = new User({ name: 'John Doe' }); await expect( user.save({ require: false }), 'to be fulfilled with value satisfying', null ); insert.restore(); }); }); describe('Model.prototype.insert', () => { it('inserts a model', async () => { const user = new User({ name: 'John Doe' }); await expect( user.insert(), 'to be fulfilled with value exhaustively satisfying', new User({ id: 1, name: 'John Doe' }) ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'John Doe' }] ); }); it('passes options along', async () => { const insert = sinon .stub(Query.prototype, 'query') .returns(Promise.resolve([])); const user = new User({ name: 'John Doe' }); await expect( user.insert({ require: false }), 'to be fulfilled with value satisfying', null ); insert.restore(); }); it('resolves with the same instance that was passed', async () => { const user = await new User({ name: 'John Doe' }); user.name = 'Jane Doe'; user.leaveMeIntact = 'okay'; await expect( user.insert(), 'to be fulfilled with value satisfying', expect.it('to be', user).and('to satisfy', { leaveMeIntact: 'okay' }) ); }); it('casts fields with `forFetch` cast functions', async () => { class OtherUser extends User {} OtherUser.fields = { name: { type: 'string', cast: { forFetch() { return 'cast name'; }, }, }, }; await expect( new OtherUser({ name: 'John Doe' }).insert(), 'to be fulfilled with value satisfying', new OtherUser({ name: 'cast name' }) ); }); }); describe('Model.prototype.update', () => { it('updates a model', async () => { const user = await new User({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; await expect( user.update(), 'to be fulfilled with value exhaustively satisfying', new User({ id: 1, name: 'Jane Doe' }) ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'Jane Doe' }] ); }); it('passes options along', async () => { const user = await new User({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; await expect( user.update({ require: false, where: { name: 'foo' } }), 'to be fulfilled with value exhaustively satisfying', null ); }); it('resolves with the same instance that was passed', async () => { const user = await new User({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; user.leaveMeIntact = 'okay'; await expect( user.update(), 'to be fulfilled with value satisfying', expect.it('to be', user).and('to satisfy', { leaveMeIntact: 'okay' }) ); }); it('casts fields with `forFetch` cast functions', async () => { class OtherUser extends User {} OtherUser.fields = { name: { type: 'string', cast: { forFetch() { return 'cast name'; }, }, }, }; const user = await new OtherUser({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; await expect( user.update(), 'to be fulfilled with value satisfying', new OtherUser({ name: 'cast name' }) ); }); }); describe('Model.prototype.fetch', () => { it('fetches a model', async () => { await new User({ id: 1, name: 'John Doe' }).insert(); const user = new User({ id: 1 }); await expect( user.fetch(), 'to be fulfilled with value exhaustively satisfying', new User({ id: 1, name: 'John Doe' }) ); }); it('passes options along', async () => { const user = await new User({ name: 'John Doe' }).insert(); user.name = 'Jane Doe'; await expect( user.fetch({ require: false, where: { name: 'foo' } }), 'to be fulfilled with value exhaustively satisfying', null ); }); it('casts fields with `forFetch` cast functions', async () => { class OtherUser extends User {} OtherUser.fields = { name: { type: 'string', cast: { forFetch() { return 'cast name'; }, }, }, }; const user = await new OtherUser({ name: 'John Doe' }).insert(); await expect( user.fetch(), 'to be fulfilled with value satisfying', new OtherUser({ name: 'cast name' }) ); }); }); describe('Model.prototype.delete', () => { it('deletes a model', async () => { await new User({ id: 1, name: 'John Doe' }).insert(); const user = new User({ id: 1 }); await expect( user.delete(), 'to be fulfilled with value exhaustively satisfying', new User({ id: 1, name: 'John Doe' }) ); await expect(knex, 'with table', User.table, 'to be empty'); }); it('passes options along', async () => { const user = await new User({ name: 'John Doe' }).insert(); await expect( user.delete({ require: false, where: { name: 'foo' } }), 'to be fulfilled with value exhaustively satisfying', null ); }); it('casts fields with `forFetch` cast functions', async () => { class OtherUser extends User {} OtherUser.fields = { name: { type: 'string', cast: { forFetch() { return 'cast name'; }, }, }, }; const user = await new OtherUser({ name: 'John Doe' }).insert(); await expect( user.delete(), 'to be fulfilled with value satisfying', new OtherUser({ name: 'cast name' }) ); }); }); describe('Model.save', () => { it('inserts models', async () => { await expect( User.save({ name: 'John Doe' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1, name: 'John Doe' })] ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'John Doe' }] ); }); it('updates models', async () => { await User.insert({ name: 'John Doe' }); await expect( User.save({ id: 1, name: 'Jane Doe' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1, name: 'Jane Doe' })] ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'Jane Doe' }] ); }); it('passes options along', async () => { await User.save({ name: 'John Doe' }); await expect( User.save({ id: 1, name: 'Jane Doe' }, { returning: 'id' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1 })] ); }); }); describe('Model.insert', () => { it('inserts models', async () => { await expect( User.insert({ id: 1, name: 'John Doe' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1, name: 'John Doe' })] ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'John Doe' }] ); }); it('passes options along', async () => { await expect( User.insert({ name: 'John Doe' }, { returning: 'id' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1 })] ); }); }); describe('Model.update', () => { it('updates models', async () => { await new User({ name: 'John Doe' }).insert(); await expect( User.update({ name: 'Jane Doe' }), 'to be fulfilled with value satisfying', [new User({ id: 1, name: 'Jane Doe' })] ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'Jane Doe' }] ); }); it('passes options along', async () => { await new User({ name: 'John Doe' }).insert(); await expect( User.update({ id: 1, name: 'Jane Doe' }, { returning: 'id' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1 })] ); }); }); describe('Model.fetch', () => { it('fetches models', async () => { await User.save({ name: 'John Doe' }); await expect( User.fetch(), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1, name: 'John Doe' })] ); }); it('passes options along', async () => { await User.save({ name: 'John Doe' }); await expect( User.fetch({ returning: 'id' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1 })] ); }); }); describe('Model.delete', () => { it('deletes models', async () => { await User.save({ name: 'John Doe' }); await expect( User.delete(), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1, name: 'John Doe' })] ); }); it('passes options along', async () => { await User.save({ name: 'John Doe' }); await expect( User.delete({ returning: 'id' }), 'to be fulfilled with value exhaustively satisfying', [new User({ id: 1 })] ); }); }); describe('with `methods` configured', () => { beforeEach(async () => new User({ id: 1, name: 'John Doe' }).insert()); describe('Model.fetchByField', () => { it('fetches a model using the field', async () => { await expect( User.fetchById(1), 'to be fulfilled with value satisfying', new User({ id: 1, name: 'John Doe' }) ); }); it('passes options along', async () => { await expect( User.fetchById(1, { where: { name: 'foo' } }), 'to be rejected with error satisfying', { name: 'NoRowsFetchedError' } ); }); }); describe('Model.deleteByField', () => { it('deletes a model using its primary field value', async () => { await expect( User.deleteById(1), 'to be fulfilled with value satisfying', new User({ id: 1, name: 'John Doe' }) ); await expect(knex, 'with table', User.table, 'to be empty'); }); it('passes options along', async () => { await expect( User.deleteById(1, { where: { name: 'foo' } }), 'to be rejected with error satisfying', { name: 'NoRowsDeletedError' } ); }); }); describe('Model.updateByField', () => { it('updates a model using its primary field value', async () => { await expect( User.updateById(1, { name: 'Jane Doe' }), 'to be fulfilled with value satisfying', new User({ id: 1, name: 'Jane Doe' }) ); await expect( knex, 'with table', User.table, 'to have rows satisfying', [{ id: 1, name: 'Jane Doe' }] ); }); it('passes options along', async () => { await expect( User.updateById( 1, { name: 'Jane Doe' }, { where: { name: 'foo' } } ), 'to be rejected with error satisfying', { name: 'NoRowsUpdatedError' } ); }); }); }); }); });
joelmukuthu/knorm
packages/knorm/test/Model.spec.js
JavaScript
mit
74,813
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Migration_Add_course_kml extends CI_Migration { function up(){ echo "Adding col: course_kml<br>"; $this->dbforge->add_column('course', array( 'course_kml' => array('type'=>'VARCHAR', 'constraint'=>512) )); echo "Remove col: course_map_embed, course_bikely_url"; $this->dbforge->drop_column('course', 'course_map_embed'); $this->dbforge->drop_column('course', 'course_bikely_url'); mkdir(FCPATH .'tmp/course/'); } function down(){ echo "would like to restore map embed and bikely url, but not going to do it!"; } }
iufer/race
public/system/race/migrations/012_Add_course_kml.php
PHP
mit
624
namespace DotNet.HighStock.Options { /// <summary> /// Properties for each single point /// </summary> public class PlotOptionsBoxplotPoint { /// <summary> /// Events for each single point /// </summary> public PlotOptionsBoxplotPointEvents Events { get; set; } } }
lisa3907/dotnet.highstock
DotNet.HighStock/Options/PlotOptionsBoxplotPoint.cs
C#
mit
349
const printMessage = require('..'); printMessage([ 'This message will be without border', 'But you still can set marginTop and marginBottom' ], { border: false, marginTop: 3, marginBottom: 3 });
ghaiklor/node-print-message
examples/withoutBorder.js
JavaScript
mit
206
using UnityEngine; using System.Collections; public class AnalogueStick : MonoBehaviour { // Public vars public Texture Tex; public Texture InnerTex; public Vector2 Position = Vector2.zero; public float Radius; public float Sensitivity = 1; public static Vector3 Val = Vector3.zero; // Private vars private int touchId = -1; // Use this for initialization void Start () { } // Update is called once per frame void Update () { // If we are on pc //#if UNITY_EDITOR // Check for a button press if (Input.GetMouseButtonDown(0)) { // Change the position of the pad to here. Vector3 mousePos = Input.mousePosition; Position = new Vector2(mousePos.x, Screen.height - mousePos.y); } // Check for mouse presses. if (Input.GetMouseButton(0)) { Vector3 mouse = Input.mousePosition; mouse.y = Screen.height - mouse.y; mouse.z = mouse.y; mouse.y = 0; // Get the distance from the stick. Vector3 diff = mouse - new Vector3(Position.x, 100, Position.y); diff.z *= -1; float distance = diff.magnitude; float val = (distance / Radius) * Sensitivity; Val = diff.normalized * val; } else { Val = Vector3.zero; } //#else // // Touch screen controls. // // Check for touches. // if (Input.touchCount > 0) { // // // Loop through events // for (int i = 0; i < Input.touchCount; ++i) { // Touch touch = Input.GetTouch(i); // // if (touchId == -1 && touch.phase == TouchPhase.Began) { // // Set the id. // touchId = touch.fingerId; // // // Change the position of the pad to here. // Vector3 mousePos = touch.position; // Position = new Vector2(mousePos.x, Screen.height - mousePos.y); // } // // // Check for mouse presses. // if (touch.fingerId == touchId) { // if (touch.phase == TouchPhase.Moved) { // Vector3 mouse = touch.position; // mouse.y = Screen.height - mouse.y; // mouse.z = mouse.y; // mouse.y = 0; // // // Get the distance from the stick. // Vector3 diff = mouse - new Vector3(Position.x, 100, Position.y); // diff.z *= -1; // float distance = diff.magnitude; // float val = (distance / Radius) * Sensitivity; // Val = diff.normalized * val; // } else if (touch.phase == TouchPhase.Canceled || touch.phase == TouchPhase.Ended) { // Val = Vector2.zero; // touchId = -1; // } // } // } // } //#endif // Make sure Val is within limits. Vector2 limits = new Vector2(Val.x, Val.z); if (limits.magnitude >= 1) { limits.Normalize(); Val = new Vector3(limits.x, Val.y, limits.y); } } // Draw void OnGUI() { // If the player is dead then don't draw. GameObject player = GameObject.FindGameObjectWithTag("Player"); if (player == null) return; if (player.GetComponent<PlayerDie>().IsDead) return; if (Input.GetMouseButton(0)) { // Draw the radius. GUI.DrawTexture(new Rect(Position.x - (Tex.width/2), Position.y - (Tex.height/2), Tex.width, Tex.height), Tex); // Draw a circle indicating in which direction the analogue stick is. GUI.DrawTexture(new Rect((Position.x + Val.x * Tex.width * 0.5f) - (InnerTex.width/2), (Position.y - Val.z * Tex.height * 0.5f) - (InnerTex.height/2), InnerTex.width, InnerTex.height), InnerTex); } } }
bombpersons/RocketDodger
Assets/Resources/Scripts/Utils/GUI/AnalogueStick.cs
C#
mit
3,318
package itchio import ( "encoding/json" "testing" "time" "github.com/mitchellh/mapstructure" "github.com/stretchr/testify/assert" ) func Test_GameHook(t *testing.T) { ref := Game{ ID: 123, InPressSystem: true, Platforms: Platforms{ Linux: ArchitecturesAll, Windows: ArchitecturesAll, }, } marshalledTraits := []byte(`{ "id": 123, "traits": ["in_press_system", "p_linux", "p_windows"] }`) marshalledSane := []byte(`{ "id": 123, "inPressSystem": true, "platforms": {"linux": "all", "windows": "all"} }`) { intermediateTraits := make(map[string]interface{}) err := json.Unmarshal(marshalledTraits, &intermediateTraits) assert.NoError(t, err) var decodedTraits Game dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ TagName: "json", DecodeHook: GameHookFunc, WeaklyTypedInput: true, Result: &decodedTraits, }) assert.NoError(t, err) err = dec.Decode(intermediateTraits) assert.NoError(t, err) assert.EqualValues(t, ref, decodedTraits) } { intermediateSane := make(map[string]interface{}) err := json.Unmarshal(marshalledSane, &intermediateSane) assert.NoError(t, err) var decodedSane Game dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ TagName: "json", DecodeHook: GameHookFunc, WeaklyTypedInput: true, Result: &decodedSane, }) assert.NoError(t, err) err = dec.Decode(intermediateSane) assert.NoError(t, err) assert.EqualValues(t, ref, decodedSane) } // ------------- bs, err := json.Marshal(ref) assert.NoError(t, err) var unmarshalled Game err = json.Unmarshal(bs, &unmarshalled) assert.NoError(t, err) assert.EqualValues(t, ref, unmarshalled) // ------------ } func Test_GameHookNested(t *testing.T) { type Res struct { Games []*Game `json:"games"` } marshalledSane := []byte(`{"games": [{ "id": 123, "inPressSystem": true, "platforms": {"linux": "all", "windows": "all"} }]}`) intermediate := make(map[string]interface{}) err := json.Unmarshal(marshalledSane, &intermediate) tmust(t, err) var res Res dec, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Result: &res, DecodeHook: mapstructure.ComposeDecodeHookFunc( mapstructure.StringToTimeHookFunc(time.RFC3339Nano), GameHookFunc, ), WeaklyTypedInput: true, }) tmust(t, err) err = dec.Decode(intermediate) tmust(t, err) assert.EqualValues(t, Res{ Games: []*Game{ &Game{ ID: 123, InPressSystem: true, Platforms: Platforms{ Linux: "all", Windows: "all", }, }, }, }, res) } // tmust shows a complete error stack and fails a test immediately // if err is non-nil func tmust(t *testing.T, err error) { if err != nil { t.Helper() t.Errorf("%+v", err) t.FailNow() } }
itchio/go-itchio
hook_game_test.go
GO
mit
2,858
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(5) braces fieldsfirst noctor nonlb space lnc package weka.classifiers.bayes.net; import java.awt.event.ActionEvent; import javax.swing.Action; import javax.swing.JLabel; // Referenced classes of package weka.classifiers.bayes.net: // GUI, EditableBayesNet class extends { private static final long serialVersionUID = 0xfff8c1b3bdcebe61L; final GUI this$0; public void actionPerformed(ActionEvent actionevent) { copy(); m_BayesNet.deleteSelection(m_Selection.elected()); m_jStatusBar.setText(m_BayesNet.lastActionMsg()); m_Selection.r(); a_undo.setEnabled(true); a_redo.setEnabled(false); repaint(); } public () { this$0 = GUI.this; super(GUI.this, "Cut", "Cut Nodes", "cut", "ctrl X"); } }
Prisjacke/Sismos
Source/net/GUI$ActionCutNode.java
Java
mit
996
<div class="box"> <div class="box-table"> <?php echo show_alert_message($this->session->flashdata('message'), '<div class="alert alert-auto-close alert-dismissible alert-info"><button type="button" class="close alertclose" >&times;</button>', '</div>'); echo show_alert_message($this->session->flashdata('dangermessage'), '<div class="alert alert-auto-close alert-dismissible alert-danger"><button type="button" class="close alertclose" >&times;</button>', '</div>'); $attributes = array('class' => 'form-inline', 'name' => 'flist', 'id' => 'flist'); echo form_open(current_full_url(), $attributes); ?> <div class="box-table-header"> <div class="btn-group btn-group-sm" role="group"> <a href="<?php echo admin_url('deposit/depositlist'); ?>" class="btn btn-sm <?php echo ( ! $this->input->get('dep_from_type') && ! $this->input->get('dep_to_type')) ? 'btn-success' : 'btn-default';?>">전체내역</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit" class="btn btn-sm <?php echo ($this->input->get('dep_to_type') === 'deposit') ? 'btn-success' : 'btn-default';?>">충전내역</a> <?php if ($this->input->get('dep_to_type') === 'deposit') { ?> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=bank" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'bank') ? 'btn-info' : 'btn-default';?>">무통장</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=card" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'card') ? 'btn-info' : 'btn-default';?>">카드</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=realtime" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'realtime') ? 'btn-info' : 'btn-default';?>">실시간</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=vbank" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'vbank') ? 'btn-info' : 'btn-default';?>">가상계좌</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=phone" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'phone') ? 'btn-info' : 'btn-default';?>">핸드폰</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=service" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'service') ? 'btn-info' : 'btn-default';?>">서비스</a> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_to_type=deposit&amp;dep_pay_type=point" class="btn btn-sm <?php echo ($this->input->get('dep_pay_type') === 'point') ? 'btn-info' : 'btn-default';?>">포인트결제</a> <?php } ?> <a href="<?php echo admin_url('deposit/depositlist'); ?>?dep_from_type=deposit" class="btn btn-sm <?php echo ($this->input->get('dep_from_type') === 'deposit') ? 'btn-success' : 'btn-default';?>">사용내역</a> </div> <?php ob_start(); ?> <div class="btn-group pull-right" role="group" aria-label="..."> <a href="<?php echo element('listall_url', $view); ?>" class="btn btn-outline btn-default btn-sm">전체목록</a> <a href="<?php echo element('write_url', $view); ?>" class="btn btn-outline btn-danger btn-sm"><?php echo $this->depositconfig->item('deposit_name'); ?> 변동내역추가</a> </div> <?php $buttons = ob_get_contents(); ob_end_flush(); ?> </div> <div class="row">전체 : <?php echo element('total_rows', element('data', $view), 0); ?>건</div> <div class="table-responsive"> <table class="table table-hover table-striped table-bordered"> <thead> <tr> <th><a href="<?php echo element('dep_id', element('sort', $view)); ?>">번호</a></th> <th>회원아이디</th> <th>회원명</th> <th>구분</th> <th>일시</th> <th>결제</th> <th>내용</th> <th><?php echo $this->depositconfig->item('deposit_name'); ?> 변동</th> <th>현금/카드 변동</th> <th>포인트 변동</th> <th><?php echo $this->depositconfig->item('deposit_name'); ?> 잔액</th> <th>수정</th> </tr> </thead> <tbody> <?php if (element('list', element('data', $view))) { foreach (element('list', element('data', $view)) as $result) { ?> <tr> <td><?php echo number_format(element('num', $result)); ?></td> <td><a href="?sfield=deposit.mem_id&amp;skeyword=<?php echo element('mem_id', $result); ?>"><?php echo html_escape(element('mem_userid', $result)); ?></a></td> <td><?php echo element('display_name', $result); ?></td> <td> <?php if (element('dep_deposit', $result) >= 0) { ?> <button type="button" class="btn btn-xs btn-primary" >충전</button> <?php } else { ?> <button type="button" class="btn btn-xs btn-danger" >사용</button> <?php } ?> <?php echo element('dep_type_display', $result); ?> </td> <td><?php echo display_datetime(element('dep_datetime', $result), 'full'); ?></td> <td><?php echo element('dep_pay_type', $result) ? $this->depositlib->paymethodtype[element('dep_pay_type', $result)] : ''; ?></td> <td><?php echo nl2br(html_escape(element('dep_content', $result))); ?></td> <td class="text-right"><?php echo number_format(element('dep_deposit', $result)); ?><?php echo $this->depositconfig->item('deposit_unit'); ?></td> <td class="text-right"><?php echo number_format(element('dep_cash', $result)) . '원'; ?></td> <td class="text-right"><?php echo number_format(element('dep_point', $result)); ?></td> <td class="text-right"><?php echo number_format(element('dep_deposit_sum', $result)); ?><?php echo $this->depositconfig->item('deposit_unit'); ?></td> <td><a href="<?php echo admin_url($this->pagedir); ?>/write/<?php echo element(element('primary_key', $view), $result); ?>?<?php echo $this->input->server('QUERY_STRING', null, ''); ?>" class="btn btn-outline btn-default btn-xs">수정</a></td> </tr> <?php } } if ( ! element('list', element('data', $view))) { ?> <tr> <td colspan="12" class="nopost">자료가 없습니다</td> </tr> <?php } ?> </tbody> </table> </div> <div class="box-info"> <?php echo element('paging', $view); ?> <div class="pull-left ml20"><?php echo admin_listnum_selectbox();?></div> <?php echo $buttons; ?> </div> <?php echo form_close(); ?> </div> <form name="fsearch" id="fsearch" action="<?php echo current_full_url(); ?>" method="get"> <div class="box-search"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <select class="form-control" name="sfield" > <?php echo element('search_option', $view); ?> </select> <div class="input-group"> <input type="text" class="form-control" name="skeyword" value="<?php echo html_escape(element('skeyword', $view)); ?>" placeholder="Search for..." /> <span class="input-group-btn"> <button class="btn btn-default btn-sm" name="search_submit" type="submit">검색!</button> </span> </div> </div> </div> </div> </form> </div>
cigiko/brdnc.cafe24.com
cb/views/admin/basic/deposit/depositlist/index.php
PHP
mit
9,561
<?php namespace AppBundle\Infrastructure\Market; use Domain\Order\Order; interface ClientOrderInterface { /** * @param Order $order * @return bool */ public function createOrder(Order $order); /** * @param Order $order * @param string $message * @return string Response content * @throws \Exception */ public function cancelOrder(Order $order, $message); /** * @param Order $order * @param $message * @return string Response content * @throws \Exception */ public function shipOrder(Order $order, $message); /** * @param Order $order * @param string $message * @return string Response content * @throws \Exception */ public function deliverOrder(Order $order, $message); }
pvgomes/symfony2biso
src/AppBundle/Infrastructure/Market/ClientOrderInterface.php
PHP
mit
801
const babelRule = require('./rule-babel') const lessRule = require('./rule-less') const rules = [babelRule, lessRule] module.exports = rules
Acgsior/Innovation
build/rules/index.js
JavaScript
mit
143
package types // PaymentRequest request to make payment type PaymentRequest struct { ClientID string `json:"clientID"` ClientToken string `json:"clientToken"` PaymentReferenceID string `json:"paymentReferenceID"` }
WPTechInnovation/worldpay-within-sdk
sdkcore/wpwithin/types/paymentrequest.go
GO
mit
236
class Hash def compact select do |_, v| !v.nil? end end def except(*keys) dup.except!(*keys) end def except!(*keys) keys.each { |key| delete(key) } self end def only!(*ks) except!(*(keys - ks)) end def only(*ks) dup.only!(*ks) end end
abdulsattar/rottendesk
lib/rottendesk/helpers/hash.rb
Ruby
mit
294
<?php namespace Mm\RecycleBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class BatterypackControllerTest extends WebTestCase { private $inputValues = array( array( 'batterypack[type]' => 'AA', 'batterypack[count]' => 4 ), array( 'batterypack[type]' => 'AAA', 'batterypack[count]' => 3 ), array( 'batterypack[type]' => 'AA', 'batterypack[count]' => 1 ) ); public function testStatistic() { $client = static::createClient(); $crawler = $client->request('GET', '/batterypack/add'); $btn = $crawler->selectButton('batterypack_save'); foreach($this->inputValues as $val) { $form = $btn->form($val); $client->submit($form); } $crawler = $client->request('GET', '/'); $this->assertCount(2, $crawler->filter('table.battery-stats tbody tr')); $this->assertCount(1, $crawler->filterXPath( "//tr[td[normalize-space(text())='AA'] and td[normalize-space(text())='5']]")); $this->assertCount(1, $crawler->filterXPath( "//tr[td[normalize-space(text())='AAA'] and td[normalize-space(text())='3']]")); } }
arkadiych/recycle
src/Mm/RecycleBundle/Tests/Controller/BatterypackControllerTest.php
PHP
mit
1,288
using System.IO; namespace NClap.ConsoleInput { /// <summary> /// Abstract interface for managing console history. /// </summary> public interface IConsoleHistory { /// <summary> /// The count of entries in the history. /// </summary> int EntryCount { get; } /// <summary> /// If the cursor is valid, the current entry in the history; null /// otherwise. /// </summary> string CurrentEntry { get; } /// <summary> /// Add a new entry to the end of the history, and reset the history's /// cursor to that new entry. /// </summary> /// <param name="entry">Entry to add.</param> void Add(string entry); /// <summary> /// Move the current history cursor by the specified offset. /// </summary> /// <param name="origin">Reference for movement.</param> /// <param name="offset">Positive or negative offset to apply to the /// specified origin.</param> /// <returns>True on success; false if the move could not be made. /// </returns> bool MoveCursor(SeekOrigin origin, int offset); } }
reubeno/NClap
src/NClap/ConsoleInput/IConsoleHistory.cs
C#
mit
1,201
jQuery(document).ready(function($){ // Хук начала инициализации javascript-составляющих шаблона ls.hook.run('ls_template_init_start',[],window); $('html').removeClass('no-js'); // Определение браузера if ($.browser.opera) { $('body').addClass('opera opera' + parseInt($.browser.version)); } if ($.browser.mozilla) { $('body').addClass('mozilla mozilla' + parseInt($.browser.version)); } if ($.browser.webkit) { $('body').addClass('webkit webkit' + parseInt($.browser.version)); } if ($.browser.msie) { $('body').addClass('ie'); if (parseInt($.browser.version) > 8) { $('body').addClass('ie' + parseInt($.browser.version)); } } // Всплывающие окна $('#window_login_form').jqm(); $('#blog_delete_form').jqm({trigger: '#blog_delete_show'}); $('#add_friend_form').jqm({trigger: '#add_friend_show'}); $('#window_upload_img').jqm(); $('#userfield_form').jqm(); $('#favourite-form-tags').jqm(); $('div#modal_write').jqm({trigger: '#modal_write_show'}); $('#foto-resize').jqm({modal: true}); $('#avatar-resize').jqm({modal: true}); $('#userfield_form').jqm({toTop: true}); $('#photoset-upload-form').jqm({trigger: '#photoset-start-upload'}); $('.js-registration-form-show').click(function(){ if (ls.blocks.switchTab('registration','popup-login')) { $('#window_login_form').jqmShow(); } else { window.location=aRouter.registration; } return false; }); $('.js-login-form-show').click(function(){ if (ls.blocks.switchTab('login','popup-login')) { $('#window_login_form').jqmShow(); } else { window.location=aRouter.login; } return false; }); // Datepicker /** * TODO: навесить языки на datepicker */ $('.date-picker').datepicker({ dateFormat: 'dd.mm.yy', dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'], monthNames: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'], firstDay: 1 }); // Поиск по тегам $('.js-tag-search-form').submit(function(){ window.location = aRouter['tag']+encodeURIComponent($(this).find('.js-tag-search').val())+'/'; return false; }); // Автокомплит ls.autocomplete.add($(".autocomplete-tags-sep"), aRouter['ajax']+'autocompleter/tag/', true); ls.autocomplete.add($(".autocomplete-tags"), aRouter['ajax']+'autocompleter/tag/', false); ls.autocomplete.add($(".autocomplete-users-sep"), aRouter['ajax']+'autocompleter/user/', true); ls.autocomplete.add($(".autocomplete-users"), aRouter['ajax']+'autocompleter/user/', false); // Скролл $(window)._scrollable(); // Тул-бар топиков ls.toolbar.topic.init(); // Кнопка "UP" ls.toolbar.up.init(); toolbarPos(); $(window).resize(function(){ toolbarPos(); }); $(window).scroll(function(){ if ($(document).width() <= 1100) { toolbarPos(); } }); // Всплывающие сообщения if (ls.registry.get('block_stream_show_tip')) { $('.js-title-comment, .js-title-topic').poshytip({ className: 'infobox-yellow', alignTo: 'target', alignX: 'left', alignY: 'center', offsetX: 10, liveEvents: true, showTimeout: 1000 }); } $('.js-title-talk').poshytip({ className: 'infobox-yellow', alignTo: 'target', alignX: 'left', alignY: 'center', offsetX: 10, liveEvents: true, showTimeout: 500 }); $('.js-infobox-vote-topic').poshytip({ content: function() { var id = $(this).attr('id').replace('vote_total_topic_','vote-info-topic-'); return $('#'+id).html(); }, className: 'infobox-standart', alignTo: 'target', alignX: 'center', alignY: 'top', offsetX: 2, liveEvents: true, showTimeout: 100 }); $('.js-tip-help').poshytip({ className: 'infobox-standart', alignTo: 'target', alignX: 'right', alignY: 'center', offsetX: 5, liveEvents: true, showTimeout: 500 }); $('.js-infobox').poshytip({ className: 'infobox-standart', liveEvents: true, showTimeout: 300 }); // подсветка кода prettyPrint(); // эмуляция border-sizing в IE var inputs = $('input.input-text, textarea'); ls.ie.bordersizing(inputs); // эмуляция placeholder'ов в IE inputs.placeholder(); // инизиализация блоков ls.blocks.init('stream',{group_items: true, group_min: 3}); ls.blocks.init('blogs'); ls.blocks.initSwitch('tags'); ls.blocks.initSwitch('upload-img'); ls.blocks.initSwitch('favourite-topic-tags'); ls.blocks.initSwitch('popup-login'); // комментарии ls.comments.options.folding = false; ls.comments.init(); // избранное ls.hook.add('ls_favourite_toggle_after',function(idTarget,objFavourite,type,params,result){ $('#fav_count_'+type+'_'+idTarget).text((result.iCount>0) ? result.iCount : ''); }); /**************** * TALK */ // Добавляем или удаляем друга из списка получателей $('#friends input:checkbox').change(function(){ ls.talk.toggleRecipient($('#'+$(this).attr('id')+'_label').text(), $(this).attr('checked')); }); // Добавляем всех друзей в список получателей $('#friend_check_all').click(function(){ $('#friends input:checkbox').each(function(index, item){ ls.talk.toggleRecipient($('#'+$(item).attr('id')+'_label').text(), true); $(item).attr('checked', true); }); return false; }); // Удаляем всех друзей из списка получателей $('#friend_uncheck_all').click(function(){ $('#friends input:checkbox').each(function(index, item){ ls.talk.toggleRecipient($('#'+$(item).attr('id')+'_label').text(), false); $(item).attr('checked', false); }); return false; }); // Удаляем пользователя из черного списка $("#black_list_block").delegate("a.delete", "click", function(){ ls.talk.removeFromBlackList(this); return false; }); // Удаляем пользователя из переписки $("#speaker_list_block").delegate("a.delete", "click", function(){ ls.talk.removeFromTalk(this, $('#talk_id').val()); return false; }); // Help-tags link $('.js-tags-help-link').click(function(){ var target=ls.registry.get('tags-help-target-id'); if (!target || !$('#'+target).length) { return false; } target=$('#'+target); if ($(this).data('insert')) { var s=$(this).data('insert'); } else { var s=$(this).text(); } $.markItUp({target: target, replaceWith: s}); return false; }); // Фикс бага с z-index у встроенных видео $("iframe").each(function(){ var ifr_source = $(this).attr('src'); if(ifr_source) { var wmode = "wmode=opaque"; if (ifr_source.indexOf('?') != -1) $(this).attr('src',ifr_source+'&'+wmode); else $(this).attr('src',ifr_source+'?'+wmode); } }); function toolbarPos() { var $=jQuery; if ($('#toolbar section').length) { if ($(document).width() <= 1000) { if (!$('#container').hasClass('no-resize')) { $('#container').addClass('toolbar-margin'); } $('#toolbar').css({'position': 'absolute', 'left': $('#wrapper').offset().left + $('#wrapper').outerWidth() + 7, 'top' : $(document).scrollTop() + 188, 'display': 'block'}); } else { $('#container').removeClass('toolbar-margin'); $('#toolbar').css({'position': 'fixed', 'left': $('#wrapper').offset().left + $('#wrapper').outerWidth() + 7, 'top': 188, 'display': 'block'}); } } }; $('.block.banner a.banner') .mouseover(function(){ //alert ('Это баннер'); $(this).animate({'background-image': 'url(livestreet/uploads/images/flas.png)'}, 1000); }); $(".slideBox").hover(function(){ $(this).find("img").stop().animate({ top:-350 }, 500); }, function(){ $(this).find("img").stop().animate({ top:0 }, 500); }); // Хук конца инициализации javascript-составляющих шаблона ls.hook.run('ls_template_init_end',[],window); });
ViktorZharina/auto-alto-971-cms
plugins/njournal/js/template.js
JavaScript
mit
8,464
# # Author:: Matheus Francisco Barra Mina (<mfbmina@gmail.com>) # © Copyright IBM Corporation 2015. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # module Fog module Softlayer class Account class Mock # Get all accounts who are owned by brand. # @param [Integer] identifier # @return [Excon::Response] def get_brand_owned_accounts(identifier) response = Excon::Response.new if @brands.select {|brand| brand[:id] == identifier.to_i }.empty? response.status = 404 response.body = { "error" => "Unable to find object with id of '#{identifier}'.", "code"=>"SoftLayer_Exception_ObjectNotFound" } else response.status = 200 response.body = mocked_accounts end response end end class Real def get_brand_owned_accounts(identifier) request(:brand, "#{identifier}/getOwnedAccounts") end end end end end module Fog module Softlayer class Account class Mock def mocked_accounts [ { "accountManagedResourcesFlag"=>false, "accountStatusId"=>1001, "address1"=>"R 1", "allowedPptpVpnQuantity"=>1, "brandId"=>23456, "city"=>"Itajuba", "claimedTaxExemptTxFlag"=>false, "companyName"=>"teste", "country"=>"BR", "createDate"=>"2015-06-10T17:06:27-03:00", "email"=>"a@gmail.com", "firstName"=>"Matheus2", "id"=>23456, "isReseller"=>0, "lastName"=>"Mina2", "lateFeeProtectionFlag"=>nil, "modifyDate"=>"2015-06-10T17:06:31-03:00", "postalCode"=>"37500-050", "state"=>"OT", "statusDate"=>nil, "brand"=> { "catalogId"=>14, "id"=>12345, "keyName"=>"ALS", "longName"=>"als", "name"=>"als", "ownedAccounts"=> [ { "accountManagedResourcesFlag"=>false, "accountStatusId"=>1001, "address1"=>"Av, 1303 Sl 10", "address2"=>"Sl 11", "allowedPptpVpnQuantity"=>2, "brandId"=>44443, "city"=>"Itajuba", "claimedTaxExemptTxFlag"=>false, "companyName"=>"Tecnologias LTDA", "country"=>"BR", "createDate"=>"2010-10-06T11:32:30-03:00", "email"=>"sysadmin@example.com.br", "firstName"=>"Xe", "id"=>12345, "isReseller"=>1, "lastName"=>"Silva", "lateFeeProtectionFlag"=>true, "modifyDate"=>"2011-02-14T17:40:23-02:00", "officePhone"=>"+55 35 3629-1616", "postalCode"=>"37500-903", "state"=>"OT", "statusDate"=>nil, "brand"=>nil }, nil ] } } ] end end end end end
fog/fog-softlayer
lib/fog/softlayer/requests/account/get_brand_owned_accounts.rb
Ruby
mit
3,546
/* Copyright (c) 2006, NAKAMURA Satoru All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the NAKAMURA Satoru nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * DateFormatter * * @website http://clonedoppelganger.net/ * @version 0.0.1 * * Example: * var now = new Date(); * alert(DateFormatter.format(now, "Y/m/d H:i:s")); */ var DateFormatter = { /** * format * @param {Date} target date object * {String} pattern * Y : A full numeric representation of a year, 4 digits * y : A two digit representation of a year * m : Numeric representation of a month, with leading zeros * n : Numeric representation of a month, without leading zeros * F : A full textual representation of a month, such as January or March * M : A short textual representation of a month, three letters * O : Japanese old month name * d : Day of the month, 2 digits with leading zeros * j : Day of the month without leading zeros * w : Numeric representation of the day of the week * l : A full textual representation of the day of the week * D : A textual representation of a day, three letters * N : ISO-8601 numeric representation of the day of the week * J : A Japanese textual representation of the day of the week * g : 12-hour format of an hour without leading zeros * G : 24-hour format of an hour without leading zeros * h : 12-hour format of an hour with leading zeros * H : 24-hour format of an hour with leading zeros * i : Minutes with leading zeros * s : Seconds, with leading zeros * a : Lowercase Ante meridiem and Post meridiem (am or pm) * A : Uppercase Ante meridiem and Post meridiem (AM or PM) * S : English ordinal suffix for the day of the month, 2 characters * z : The day of the year (starting from 0) * t : Number of days in the given month * L : Whether it's a leap year * Escape character is #. Example: DateFormatter.format(new Date(), "#Y#m#d #i#s Ymd"); * @return {String} formatted date */ format: function(d, pattern) { if (typeof pattern != "string") return; var dYear = d.getFullYear(); var dMonth = d.getMonth(); var dDate = d.getDate(); var dDay = d.getDay(); var dHours = d.getHours(); var dMinutes = d.getMinutes(); var dSeconds = d.getSeconds(); var res = ""; for (var i = 0, len = pattern.length; i < len; i++) { var c = pattern.charAt(i); switch (c) { case "#": if (i == len - 1) break; res += pattern.charAt(++i); break; case "Y": res += dYear; break; case "y": res += dYear.toString().substr(2, 2); break; case "m": res += this.preZero(dMonth + 1); break; case "n": res += dMonth + 1; break; case "d": res += this.preZero(dDate); break; case "j": res += dDate; break; case "w": res += dDay; break; case "N": res += this.isoDay(dDay); break case "l": res += this.weekFullEn[dDay]; break; case "D": res += this.weekFullEn[dDay].substr(0, 3); break; case "J": res += this.weekJp[dDay]; break; case "F": res += this.monthFullEn[dMonth]; break; case "M": res += this.monthFullEn[dMonth].substr(0, 3); break; case "O": res += this.monthOldJp[dMonth]; break; case "a": res += this.ampm(dHours); break; case "A": res += this.ampm(dHours).toUpperCase(); break; case "H": res += this.preZero(dHours); break; case "h": res += this.preZero(this.from24to12(dHours)); break; case "g": res += this.from24to12(dHours); break; case "G": res += dHours; break; case "i": res += this.preZero(dMinutes); break; case "s": res += this.preZero(dSeconds); break; case "t": res += this.lastDayOfMonth(d); break; case "L": res += this.isLeapYear(dYear); break; case "z": res += this.dateCount(dYear, dMonth, dDate); break; case "S": res += this.dateSuffix[dDate - 1]; break; default : res += c; break; } } return res; }, weekFullEn: ["Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday"], weekJp: ["日","月","火","水","木","金","土"], monthFullEn: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthOldJp: ["睦月", "如月", "弥生", "卯月", "皐月", "水無月", "文月", "葉月", "長月", "神無月", "霜月", "師走"], dateSuffix: [ "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"], preZero: function(value) { return (parseInt(value) < 10) ? "0" + value : value; }, from24to12: function(hours) { return (hours > 12) ? hours - 12 : hours; }, ampm: function(hours) { return (hours < 12) ? "am" : "pm"; }, isoDay: function(day) { return (day == 0) ? "7" : day; }, lastDayOfMonth: function(dateObj) { var tmp = new Date(dateObj.getFullYear(), dateObj.getMonth() + 1, 1); tmp.setTime(tmp.getTime() - 1); return tmp.getDate(); }, isLeapYear: function(year) { var tmp = new Date(year, 0, 1); var sum = 0; for (var i = 0; i < 12; i++) { tmp.setMonth(i); sum += this.lastDayOfMonth(tmp); } return (sum == 365) ? "0" : "1"; }, dateCount: function(year, month, date) { var tmp = new Date(year, 0, 1); var sum = -1; for (var i = 0; i < month; i++) { tmp.setMonth(i); sum += this.lastDayOfMonth(tmp); } return sum + date; } }
robert-kurcina/generator
common/js/lib/DateFormatter.js
JavaScript
mit
7,258
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core; import java.io.IOException; import java.io.OutputStream; import java.util.Arrays; import ch.qos.logback.core.joran.spi.ConsoleTarget; import ch.qos.logback.core.status.Status; import ch.qos.logback.core.status.WarnStatus; import ch.qos.logback.core.util.DynamicClassLoadingException; import ch.qos.logback.core.util.EnvUtil; import ch.qos.logback.core.util.IncompatibleClassException; import ch.qos.logback.core.util.OptionHelper; import org.fusesource.jansi.WindowsAnsiOutputStream; /** * ConsoleAppender appends log events to <code>System.out</code> or * <code>System.err</code> using a layout specified by the user. The default * target is <code>System.out</code>. * <p/> * For more information about this appender, please refer to the online manual * at http://logback.qos.ch/manual/appenders.html#ConsoleAppender * * @author Ceki G&uuml;lc&uuml; * @author Tom SH Liu * @author Ruediger Dohna */ public class ConsoleAppender<E> extends OutputStreamAppender<E> { protected ConsoleTarget target = ConsoleTarget.SystemOut; protected boolean withJansi = false; private final static String WindowsAnsiOutputStream_CLASS_NAME = "org.fusesource.jansi.WindowsAnsiOutputStream"; /** * Sets the value of the <b>Target</b> option. Recognized values are * "System.out" and "System.err". Any other value will be ignored. */ public void setTarget(String value) { ConsoleTarget t = ConsoleTarget.findByName(value.trim()); if (t == null) { targetWarn(value); } else { target = t; } } /** * Returns the current value of the <b>target</b> property. The default value * of the option is "System.out". * <p/> * See also {@link #setTarget}. */ public String getTarget() { return target.getName(); } private void targetWarn(String val) { Status status = new WarnStatus("[" + val + "] should be one of " + Arrays.toString(ConsoleTarget.values()), this); status.add(new WarnStatus( "Using previously set target, System.out by default.", this)); addStatus(status); } @Override public void start() { OutputStream targetStream = target.getStream(); // enable jansi only on Windows and only if withJansi set to true if (EnvUtil.isWindows() && withJansi) { targetStream = getTargetStreamForWindows(targetStream); } setOutputStream(targetStream); super.start(); } private OutputStream getTargetStreamForWindows(OutputStream targetStream) { try { addInfo("Enabling JANSI WindowsAnsiOutputStream for the console."); Object windowsAnsiOutputStream = OptionHelper.instantiateByClassNameAndParameter(WindowsAnsiOutputStream_CLASS_NAME, Object.class, context, OutputStream.class, targetStream); return (OutputStream) windowsAnsiOutputStream; } catch (Exception e) { addWarn("Failed to create WindowsAnsiOutputStream. Falling back on the default stream.", e); } return targetStream; } /** * @return */ public boolean isWithJansi() { return withJansi; } /** * If true, this appender will output to a stream which * * @param withJansi * @since 1.0.5 */ public void setWithJansi(boolean withJansi) { this.withJansi = withJansi; } }
cscfa/bartleby
library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/ConsoleAppender.java
Java
mit
3,892
package de.silveryard.car.gradleplugin; import java.io.File; /** * Created by silveryard on 23.05.17. */ public class InstallBluetoothPlayerTask extends InstallAppTask { @Override protected File getAPFFile() { return getProject().file("BluetoothPlayer/build/apf/de_silveryard_car_BluetoothPlayer_1_0-SNAPSHOT.apf"); } }
Silveryard/CarLauncher
GradlePlugin/src/main/java/de/silveryard/car/gradleplugin/InstallBluetoothPlayerTask.java
Java
mit
344
import './src/styles/theme.css'
siddharthkp/siddharthkp.github.io
gatsby-browser.js
JavaScript
mit
32
package main import ( "github.com/codegangsta/martini" "github.com/dustin/go-humanize" "github.com/tanner/isgtwifidown.com/gtwifi" "html/template" "log" "net/http" "time" ) type PageData struct { Green bool Yellow bool Red bool Reason string LastUpdated string } type LastData struct { Status int Reason string TimeRetrieved time.Time } var lastData LastData func main() { m := martini.Classic() template := template.Must(template.ParseFiles("index.tmpl")) schedule(checkData, 10*time.Minute) checkData() m.Get("/", func(res http.ResponseWriter, req *http.Request) { data := PageData{} data.Green = lastData.Status == gtwifi.GREEN data.Yellow = lastData.Status == gtwifi.YELLOW data.Red = lastData.Status == gtwifi.RED data.Reason = lastData.Reason data.LastUpdated = humanize.Time(lastData.TimeRetrieved) template.Execute(res, data) }) m.Run() } func checkData() { log.Println("Retrieving new data...") status, err := gtwifi.GetStatus() if err != nil { log.Println(err) return } log.Println("New data retrieved!") lastData = LastData{status.Status, status.Reason, time.Now()} } func schedule(caller func(), delay time.Duration) chan bool { ticker := time.NewTicker(delay) stop := make(chan bool) go func() { for { select { case <-ticker.C: caller() case <-stop: ticker.Stop() return } } }() return stop }
Tanner/isgtwifidown.com
main.go
GO
mit
1,441
if( !String.prototype.trim ){ String.prototype.trim = function () { return this.replace(/^\s*/, "").replace(/\s*$/, ""); } } if( !String.prototype.ltrim ){ String.prototype.ltrim=function(){return this.replace(/^\s+/,'');}; } if( !String.prototype.rtrim ){ String.prototype.rtrim=function(){return this.replace(/\s+$/,'');}; } String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');}; if( !String.prototype.camelize ) String.prototype.camelize = function(){ return this.replace(/_+(.)?/g, function(match, chr) { return chr ? chr.toUpperCase() : ''; }); } if( !String.prototype.seperate ) String.prototype.seperate = function(){ return this.replace(/_+(.)?/g, function(match, chr) { return chr ? ' ' + chr.toUpperCase() : ''; }); } if( !String.prototype.capitalize ) String.prototype.capitalize = function(){ return this.charAt(0).toUpperCase() + this.substring(1); } if( !String.prototype.endInSlash ) String.prototype.endInSlash = function(){ var sStr = this; if( /\/$/.test(this) == false ){ sStr = this + '/'; } return sStr; } if( !String.prototype.endInBSlash ) String.prototype.endInBSlash = function(){ var sStr = this; if( /\$/.test(this) == false ){ /*sStr = this + '\\';*/ } return sStr; } if( !String.prototype.escapeCSV ) String.prototype.escapeCSV = function(){ var sStr = this; sStr = sStr.replace(/"/g,'\\"').replace(/\n/g,""); return sStr; } if( !String.prototype.htmlEscape ) String.prototype.htmlEscape = function(){ return String(this) .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } if( !String.prototype.htmlUnescape ) String.prototype.htmlUnescape = function(){ return String(this) .replace(/&quot;/g, '"') .replace(/&#39;/g, "'") .replace(/&lt;/g, '<') .replace(/&gt;/g, '>') .replace(/&amp;/g, '&'); } if( !String.prototype.toElementId ) String.prototype.toElementId = function(){ return String(this).replace(/[!@$%&*()-=+~^.#' \n\t\f\r`"]+/g, '_');//this makes the id less unique, need a better way //Before html5 id's not supposed to start with a number? Might want to check for that. //jQuery has issues with . and : might want to replace that. //May also want to check on CSS restrictions } if( !String.prototype.toElementIdForjQuery ) String.prototype.toElementIdForjQuery = function(){ return String(this).replace(/[~!@$%&*()-=+^#' \n\t\f\r:.`"]+/g, '_'); //See notes from toElementID } if( !String.prototype.supplant ) String.prototype.supplant = function(o){ return this.replace(/{([^{}]*)}/g,function(a,b){ var r = o[b]; return typeof r === 'string' ? r:a; }); }; if( !String.prototype.mustache ) String.prototype.mustache = function(o){ return this.replace(/{{([^{}]*)}}/g,function(a,b){ var r = o[b]; return typeof r === 'string' ? r:a; }); };
scirelli/multifileuploader
js/extras-string.js
JavaScript
mit
3,405
# 倒序排 a = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True) print(a) # 按成绩从高到低排序: L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)] def by_score(t): return t[1] L2 = sorted(L, key=by_score) print(L2) # [('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)]
longze/my-cellar
web/articles/python/demo/09-sort.py
Python
mit
322
from util import * @responses.activate def test_getters(client, dummy_data): assert client.host() == dummy_data.host assert client.api_host() == dummy_data.api_host @responses.activate def test_setters(client, dummy_data): try: client.host('host.nexmo.com') client.api_host('host.nexmo.com') assert client.host() != dummy_data.host assert client.api_host() != dummy_data.api_host except: assert False @responses.activate def test_fail_setter_url_format(client, dummy_data): try: client.host('1000.1000') assert False except: assert True
Nexmo/nexmo-python
tests/test_getters_setters.py
Python
mit
627
DGVocabulary = function () { }; DGVocabulary._MSG = {}; DGVocabulary._MSG["alert_select_row"] = "你必须选择一个或多个行进行此操作!"; DGVocabulary._MSG["alert_perform_operation"] = "您是否确定要进行这项行动?"; DGVocabulary._MSG["alert_perform_operation_delete"] = "您是否确定要进行删除操作?"; DGVocabulary._MSG["alert_perform_operation_clone"] = "您是否确定要进行克隆操作?"; DGVocabulary._MSG["alert_blocked_in_demo"] = "此操作被阻止在演示版!"; DGVocabulary._MSG["cookies_required"] = "此操作要求您的浏览器接受Cookie的!请接受Cookie转机。"; DGVocabulary._MSG["extension_not_allowed"] = "选定扩展名的文件是不允许的。"; DGVocabulary._MSG["need_upload_file"] = "更新之前,您必须上载文件或图像!请点击上传链接。"; DGVocabulary._MSG["please_reenter"] = "请重新输入!"; DGVocabulary._MSG["upload_file_size_alert"] = "您尝试上传文件大于允许的最大大小:";
jessadayim/findtheroom
web/datagrid-backend/datagrid/languages/js/dg-ch.js
JavaScript
mit
1,001
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tracking', '0007_auto_20160313_1725'), ] operations = [ migrations.AddField( model_name='organization', name='creation_time', field=models.DateTimeField(blank=True, verbose_name='Creation Timestamp', null=True), ), migrations.AddField( model_name='organization', name='modification_time', field=models.DateTimeField(blank=True, verbose_name='Modification Timestamp', null=True), ), migrations.AddField( model_name='patientvisit', name='creation_time', field=models.DateTimeField(blank=True, verbose_name='Creation Timestamp', null=True), ), migrations.AddField( model_name='patientvisit', name='modification_time', field=models.DateTimeField(blank=True, verbose_name='Modification Timestamp', null=True), ), migrations.AddField( model_name='referringentity', name='creation_time', field=models.DateTimeField(blank=True, verbose_name='Creation Timestamp', null=True), ), migrations.AddField( model_name='referringentity', name='modification_time', field=models.DateTimeField(blank=True, verbose_name='Modification Timestamp', null=True), ), migrations.AddField( model_name='treatingprovider', name='creation_time', field=models.DateTimeField(blank=True, verbose_name='Creation Timestamp', null=True), ), migrations.AddField( model_name='treatingprovider', name='modification_time', field=models.DateTimeField(blank=True, verbose_name='Modification Timestamp', null=True), ), ]
Heteroskedastic/Dr-referral-tracker
tracking/migrations/0008_adding_creation_modification_time.py
Python
mit
1,984
/* VerbDestroyStructure.cpp (c)2000 Palestar Inc, Richard Lyle */ #include "Debug/Assert.h" #include "SceneryEffect.h" #include "VerbDestroyStructure.h" #include "GameContext.h" //------------------------------------------------------------------------------- IMPLEMENT_FACTORY( VerbDestroyStructure, Verb ); BEGIN_PROPERTY_LIST( VerbDestroyStructure, Verb ) ADD_TRANSMIT_PROPERTY( m_pKiller ); END_PROPERTY_LIST(); VerbDestroyStructure::VerbDestroyStructure() {} VerbDestroyStructure::VerbDestroyStructure( NounStructure * pStructure, Noun * pKiller ) : m_pKiller( pKiller ) { attachVerb( pStructure ); } //---------------------------------------------------------------------------- Verb::Priority VerbDestroyStructure::priority() const { return MEDIUM; } Verb::Scope VerbDestroyStructure::scope() const { return LOCAL; } bool VerbDestroyStructure::client() const { return false; } bool VerbDestroyStructure::canAttach( Noun * pNoun ) { return WidgetCast<NounStructure>( pNoun ) != NULL; } void VerbDestroyStructure::onExecute() { NounStructure * pStructure = WidgetCast<NounStructure>( target() ); if ( validate( pStructure ) ) pStructure->destroy( m_pKiller ); } //---------------------------------------------------------------------------- //EOF
palestar/darkspace
DarkSpace/VerbDestroyStructure.cpp
C++
mit
1,280
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Jmp.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
virtuallysmart/jmp
source/Jmp.Web/Global.asax.cs
C#
mit
589
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using OpenRealEstate.Core.Models; using OpenRealEstate.Core.Models.Land; using OpenRealEstate.Core.Models.Rental; using OpenRealEstate.Core.Models.Residential; using OpenRealEstate.Core.Models.Rural; using CategoryTypeHelpers = OpenRealEstate.Core.Models.Land.CategoryTypeHelpers; namespace OpenRealEstate.Services.RealEstateComAu { public class ReaXmlTransmorgrifier : ITransmorgrifier { private static readonly IList<string> ValidRootNodes = new List<string> { "propertyList", "residential", "rental", "rural", "land" }; private CultureInfo _defaultCultureInfo; /// <summary> /// Converts some given data into a listing instance. /// </summary> /// <param name="data">some data source, like Xml data or json data.</param> /// <param name="areBadCharactersRemoved">Help clean up the data.</param> /// <param name="isClearAllIsModified">After the data is loaded, do we clear all IsModified fields so it looks like the listing(s) are all ready to be used and/or compared against other listings.</param> /// /// <returns>List of listings and any unhandled data.</returns> public ConvertToResult ConvertTo(string data, bool areBadCharactersRemoved = false, bool isClearAllIsModified = false) { Guard.AgainstNullOrWhiteSpace(data); // Remove any BOM if one exists. // REF: http://stackoverflow.com/questions/5098757/how-to-tell-asciiencoding-class-not-to-decode-the-byte-order-mark data = RemoveByteOrderMark(data); var validationErrorMessage = ValidateXmlString(data); if (!string.IsNullOrWhiteSpace(validationErrorMessage)) { if (!areBadCharactersRemoved) { return new ConvertToResult { Errors = new List<ParsedError> { new ParsedError(validationErrorMessage, "The entire data source.")} }; } // Some bad data occurs, so lets clean any bad data out. data = RemoveInvalidXmlChars(data); } // Now split it up into the known listing types. SplitElementResult elements; try { elements = SplitReaXmlIntoElements(data); } catch (Exception exception) { return new ConvertToResult { Errors = new List<ParsedError> { new ParsedError(exception.Message, "Failed to parse the provided xml data because it contains some invalid data. Pro Tip: This is usually because a character is not encoded. Like an ampersand.") } }; } if (!elements.KnownXmlData.Any() && !elements.UnknownXmlData.Any()) { return null; } // Finally, we convert each segment into a listing. var successfullyParsedListings = new ConcurrentBag<ListingResult>(); var invalidData = new ConcurrentBag<ParsedError>(); Parallel.ForEach(elements.KnownXmlData, element => { try { successfullyParsedListings.Add(new ListingResult { Listing = ConvertFromReaXml(element, DefaultCultureInfo, AddressDelimeter, DefaultSalePriceTextIfMissing, DefaultSoldPriceTextIfMissing, isClearAllIsModified), SourceData = element.ToString() }); } catch (ParsingException exception) { var error = new ParsedError(exception.Message, element.ToString()) { AgencyId = exception.AgencyId, ListingId = exception.ListingId }; invalidData.Add(error); } catch (Exception exception) { invalidData.Add(new ParsedError(exception.Message, element.ToString())); } }); return new ConvertToResult { Listings = successfullyParsedListings.Any() ? successfullyParsedListings.ToList() : null, UnhandledData = elements.UnknownXmlData != null && elements.UnknownXmlData.Any() ? elements.UnknownXmlData.Select(x => x.ToString()).ToList() : null, Errors = invalidData.Any() ? invalidData.ToList() : null }; } public CultureInfo DefaultCultureInfo { get { return _defaultCultureInfo ?? new CultureInfo("en-au"); } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _defaultCultureInfo = value; } } public string AddressDelimeter { get; set; } = "/"; public string DefaultSalePriceTextIfMissing { get; set; } = "Contact Agent"; public string DefaultSoldPriceTextIfMissing { get; set; } = "Contact Agent"; private static string RemoveByteOrderMark(string text) { var byteOrderMark = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()).ToCharArray(); var startOfTextChars = text.Substring(0, byteOrderMark.Length).ToCharArray(); for (int i = byteOrderMark.Length - 1; i >= 0; i--) { if (startOfTextChars[i] == byteOrderMark[i]) { text = text.Remove(i, 1); } } return text; } private static string ValidateXmlString(string text) { Guard.AgainstNullOrWhiteSpace(text); try { XmlConvert.VerifyXmlChars(text); return null; } catch (XmlException exception) { return string.Format( "The REA Xml data provided contains some invalid characters. Line: {0}, Position: {1}. Error: {2} Suggested Solution: Either set the 'areBadCharactersRemoved' parameter to 'true' so invalid characters are removed automatically OR manually remove the errors from the file OR manually handle the error (eg. notify the people who sent you this data, that it contains bad data and they should clean it up.)", exception.LineNumber, exception.LinePosition, exception.Message); } catch (Exception exception) { return string.Format("Failed to valid the xml string provided. Unknown error: {0}.", exception.Message); } } private static string RemoveInvalidXmlChars(string text) { Guard.AgainstNullOrWhiteSpace(text); var validXmlChars = text.Where(XmlConvert.IsXmlChar).ToArray(); return new string(validXmlChars); } private static void EnsureXmlHasRootNode(ref XDocument document) { Guard.AgainstNull(document); var rootNode = document.Root == null ? null : document.Root.Name.LocalName; if (string.IsNullOrWhiteSpace(rootNode) || !ValidRootNodes.Contains(document.Root.Name.LocalName)) { var errorMessage = string.Format( "Unable to parse the xml data provided. Currently, only a <propertyList/> or listing segments <residential/> / <rental/> / <land/> / <rural/>. Root node found: '{0}'.", document.Root == null ? "-no root node" : document.Root.Name.LocalName); throw new Exception(errorMessage); } // Lets make sure our document has a propertyList root node. if (rootNode != "propertyList") { document = new XDocument(new XElement("propertyList", document.Root)); } } private static SplitElementResult SplitReaXmlIntoElements(string xml) { Guard.AgainstNullOrWhiteSpace(xml); // If there are bad elements in the XML, then this throw an exception. // Eg. & (ampersands) in video links that are not properly encoded, etc. var document = XDocument.Parse(xml); // Prepare the xml data we're given. EnsureXmlHasRootNode(ref document); var knownNodes = new[] { "residential", "rental", "land", "rural" }; return document.Root == null ? null : new SplitElementResult { KnownXmlData = document.Root.Elements() .Where( x => knownNodes.Any( node => string.Compare(node, x.Name.LocalName, true, CultureInfo.InvariantCulture) == 0)) .ToList(), UnknownXmlData = document.Root.Elements() .Where( x => knownNodes.All( node => string.Compare(node, x.Name.LocalName, true, CultureInfo.InvariantCulture) != 0)) .ToList() }; } private static Listing ConvertFromReaXml(XElement document, CultureInfo cultureInfo, string addressDelimeter, string defaultSalePriceTextIfMissing, string defaultSoldPriceTextIfMissing, bool isClearAllIsModified) { Guard.AgainstNull(document); // Determine the category, so we know why type of listing we need to create. var categoryType = document.Name.ToCategoryType(); // We can only handle a subset of all the category types. var listing = CreateListing(categoryType); if (listing == null) { // TODO: Add logging message. return null; } try { // Extract common data. ExtractCommonData(listing, document, addressDelimeter); // Extract specific data. if (listing is ResidentialListing) { ExtractResidentialData(listing as ResidentialListing, document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); } if (listing is RentalListing) { ExtractRentalData(listing as RentalListing, document, cultureInfo); } if (listing is LandListing) { ExtractLandData(listing as LandListing, document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); } if (listing is RuralListing) { ExtractRuralData(listing as RuralListing, document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); } } catch (Exception exception) { throw new ParsingException(exception.Message, listing.AgencyId, listing.Id, exception); } if (isClearAllIsModified) { listing.ClearAllIsModified(); } return listing; } private static Listing CreateListing(CategoryType categoryType) { Listing listing; switch (categoryType) { case CategoryType.Sale: listing = new ResidentialListing(); break; case CategoryType.Rent: listing = new RentalListing(); break; case CategoryType.Land: listing = new LandListing(); break; case CategoryType.Rural: listing = new RuralListing(); break; default: // Not sure if we should do some logging here? listing = null; break; } return listing; } private static DateTime ToDateTime(string reaDateTime) { Guard.AgainstNullOrWhiteSpace(reaDateTime); // REFERENCE: http://reaxml.realestate.com.au/docs/reaxml1-xml-format.html#datetime /* YYYY-MM-DD YYYY-MM-DD-hh:mm YYYY-MM-DD-hh:mm:ss YYYY-MM-DDThh:mm YYYY-MM-DDThh:mm:ss YYYYMMDD YYYYMMDD-hhmm YYYYMMDD-hhmmss YYYYMMDDThhmm YYYYMMDDThhmmss // FFS REA!!!! URGH!!!!!!!! :( // Stick to fricking ISO8061 with yyyy-MM-ddTHH:mm:ss // ONE FORMAT TO RULE THEM ALL. // (not that hard, peeps). */ var formats = new[] { "yyyy-MM-dd", "yyyy-MM-dd-HH:mm", "yyyy-MM-ddTHH:mm", "yyyy-MM-dd-HH:mm:", "yyyy-MM-dd-HH:mm:ss", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTH:mm:ss", // 2016-05-21T9:33:49 (Notice the single 'hour' that is not 24 hour format?) "yyyy-MM-dd-H:mm:ss", // 2016-05-26-9:41:29 (Another back hack from people. Single hour. GRR!) "yyyy-MM-dd-HH:mm:ss", // 2016-05-26-16:41:29 (Another back hack from people. 24 hour. GRR!) "yyyy-MM-dd-HH:mm:sstt", // 2015-12-15-01:18:52PM "yyyy-MM-dd-h:mm:ss", // Urgh :( 2016-10-05-0:00:00 (Notice the single 'hour' that is not 24 hour format?) "yyyyMMdd-HHmmss", "yyyyMMDD-HHmmss", "yyyyMMddTHHmmss", "yyyyMMDDTHHmm", "yyyyMMdd-HHmm", "yyyyMMddTHHmm", "yyyyMMdd", "o", "s" }; var trimmedValue = reaDateTime.Trim(); DateTime result; if (DateTime.TryParseExact(trimmedValue, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result)) { return result; } if (DateTime.TryParse(trimmedValue, out result)) { return result; } throw new Exception($"Invalid date/time trying to be parsed. Attempted the value: '{reaDateTime}' but that format is invalid."); } #region Common listing methods private static void ExtractCommonData(Listing listing, XElement document, string addressDelimeter) { Guard.AgainstNull(listing); Guard.AgainstNull(document); listing.UpdatedOn = ToDateTime(document.AttributeValue("modTime")); // We have no idea if this was created before this date, but we need to set a date // so we'll default it to this. listing.CreatedOn = listing.UpdatedOn; listing.AgencyId = document.ValueOrDefault("agentID"); listing.Id = document.ValueOrDefault("uniqueID"); var status = document.AttributeValueOrDefault("status"); if (!string.IsNullOrWhiteSpace(status)) { var statusType = StatusTypeHelpers.ToStatusType(status); if (statusType == StatusType.Unknown) { throw new Exception($"An invalid StatusType '{status}' was provided."); } listing.StatusType = statusType; } listing.Title = document.ValueOrDefault("headline"); listing.Description = document.ValueOrDefault("description"); listing.Address = ExtractAddress(document, addressDelimeter); var agents = ExtractAgent(document); if (agents != null && agents.Any()) { listing.AddAgents(agents); } var inspections = ExtractInspectionTimes(document); if (inspections != null && inspections.Any()) { listing.AddInspections(inspections); } var images = ExtractImages(document); if (images != null && images.Any()) { listing.AddImages(images); } var floorPlans = ExtractFloorPlans(document); if (floorPlans != null && floorPlans.Any()) { listing.AddFloorPlans(floorPlans); } var videos = ExtractVideos(document); if (videos != null && videos.Any()) { listing.AddVideos(videos); } var documents = ExtractDocuments(document); if (documents != null && documents.Any()) { listing.AddDocuments(documents); } listing.Features = ExtractFeatures(document); listing.LandDetails = ExtractLandDetails(document); var links = ExtractExternalLinks(document); if (links != null && links.Any()) { listing.AddLinks(links); } } private static Address ExtractAddress(XElement document, string addressDelimeter) { Guard.AgainstNull(document); var addressElement = document.Element("address"); if (addressElement == null) { return null; } var address = new Address(); // Land and CommericalLand should only provide lot numbers. var lotNumber = addressElement.ValueOrDefault("lotNumber"); var subNumber = addressElement.ValueOrDefault("subNumber"); var streetNumber = addressElement.ValueOrDefault("streetNumber"); // LOGIC: // So, we're trying to create a streetnumber value that contains the rea values // Sub Number // Lot Number // Street Number // into a single value. URGH. // This is because REA have over fricking complicated shiz (again). So lets just // keep this simple, eh? :) // FORMAT: subnumber lotnumber streetnumber // eg. 23a/135 smith street // 6/23a 135 smith street // 23a lot 33 smith street // 23a lot 33/135 smith street // Lot number logic: If the value contains the word LOT in it, then we don't // need to do anything. Otherwise, we should have a value the starts with 'LOT'. // eg. LOT 123abc var lotNumberResult = string.IsNullOrWhiteSpace(lotNumber) ? string.Empty : lotNumber.IndexOf("lot", StringComparison.InvariantCultureIgnoreCase) > 0 ? lotNumber : string.Format("LOT {0}", lotNumber); // Sub number and Street number logic: A sub number can exist -before- the street number. // A street number might NOT exist, so a sub number is all by itself. // When we want to show a sub number, we probably want to show it, like this: // 'subNumber`delimeter`streetNumber` // eg. 12a/432 // But .. sometimes, the sub number -already- contains a delimeter! so then we want this: // eg. 45f/231 15 // So we don't put a delimeter in there, but a space. Urgh! confusing, so sowwy. var subNumberLotNumber = string.Format("{0} {1}", subNumber, lotNumberResult).Trim(); // We only have a delimeter if we have a sub-or-lot number **and** // a street number. // Also, we use the default delimeter if we don't have one already in the // sub-or-lot number. var delimeter = string.IsNullOrWhiteSpace(subNumberLotNumber) ? string.Empty : subNumberLotNumber.IndexOfAny(new[] {'/', '\\', '-'}) > 0 ? " " : string.IsNullOrWhiteSpace(streetNumber) ? string.Empty : addressDelimeter; address.StreetNumber = string.Format("{0}{1}{2}", subNumberLotNumber, delimeter, streetNumber).Trim(); address.Street = addressElement.ValueOrDefault("street"); address.Suburb = addressElement.ValueOrDefault("suburb"); address.State = addressElement.ValueOrDefault("state"); // REA Xml Rule: Country is ommited == default to Australia. // Reference: http://reaxml.realestate.com.au/docs/reaxml1-xml-format.html#country var country = addressElement.ValueOrDefault("country"); address.CountryIsoCode = !string.IsNullOrEmpty(country) ? ConvertCountryToIsoCode(country) : "AU"; address.Postcode = addressElement.ValueOrDefault("postcode"); var isStreetDisplayedText = addressElement.AttributeValueOrDefault("display"); if (!string.IsNullOrWhiteSpace(isStreetDisplayedText)) { // We have a value - so lets try and set it. // Because this is a bool we might not set this field to MODIFIED because default value // might equal the text-value, which doesn't set the bool field :/ (i.e. nothing changes :( ) // So lets force the field to be 'updated'. address.IsStreetDisplayed = true; // Now lets set the real value. // NOTE: The default bool value is FALSE. If the text-value is false, then the field // is false = false, which does nothing and doesn't suggest that this value should be changed. address.IsStreetDisplayed = string.IsNullOrWhiteSpace(isStreetDisplayedText) || addressElement.AttributeBoolValueOrDefault("display"); } // Technically, the <municipality/> element is not a child of the <address/> element. // But I feel that it's sensible to still parse for it, in here. address.Municipality = document.ValueOrDefault("municipality"); // Finally - Lat/Longs. These are -not- part of the REA XML standard. // ~BUT~ some multi-loaders are sticking this data into some xml! ExtractLatitudeLongitudes(document, address); return address; } private static void ExtractLatitudeLongitudes(XElement document, Address address) { Guard.AgainstNull(document); Guard.AgainstNull(address); var latitudeElement = document.Descendants("Latitude").FirstOrDefault() ?? document.Descendants("latitude").FirstOrDefault(); if (latitudeElement != null) { address.Latitude = latitudeElement.DecimalValueOrDefault(); } var longitudeElement = document.Descendants("Longitude").FirstOrDefault() ?? document.Descendants("longitude").FirstOrDefault(); if (latitudeElement != null) { address.Longitude = longitudeElement.DecimalValueOrDefault(); } } private static IList<ListingAgent> ExtractAgent(XElement document) { Guard.AgainstNull(document); var agentElements = document.Elements("listingAgent").ToArray(); if (!agentElements.Any()) { return null; } var agents = new List<ListingAgent>(); foreach (var agentElement in agentElements) { var name = agentElement.ValueOrDefault("name"); if (string.IsNullOrWhiteSpace(name)) { // We need a name of the agent at the very least. // Some listings have this element but no data provided. :( // So we don't add 'emtpy' agents. continue; } var agent = new ListingAgent { Name = name }; var orderValue = agentElement.AttributeValueOrDefault("id"); int order = 0; if (!string.IsNullOrWhiteSpace(orderValue) && int.TryParse(orderValue, out order)) { agent.Order = order; } var communications = new List<Communication>(); var email = agentElement.ValueOrDefault("email"); if (!string.IsNullOrWhiteSpace(email)) { communications.Add(new Communication { CommunicationType = CommunicationType.Email, Details = email }); } var phoneMobile = agentElement.ValueOrDefault("telephone", "type", "mobile"); if (!string.IsNullOrWhiteSpace(phoneMobile)) { communications.Add(new Communication { CommunicationType = CommunicationType.Mobile, Details = phoneMobile }); } var phoneOffice = agentElement.ValueOrDefault("telephone", "type", "BH"); if (!string.IsNullOrWhiteSpace(phoneOffice)) { communications.Add(new Communication { CommunicationType = CommunicationType.Landline, Details = phoneOffice }); } if (communications.Any()) { agent.AddCommunications(communications); } // Don't add this agent, if the name already exists in the list. if (!agents.Any(x => x.Name.Equals(agent.Name, StringComparison.InvariantCultureIgnoreCase))) { // This agent doesn't exists - so we're good to add them! agents.Add(agent); } } var counter = 0; if (agents.Any()) { var orderedAgents = new List<ListingAgent>(); foreach (var agent in agents.OrderBy(x => x.Order)) { var orderedAgent = new ListingAgent { Name = agent.Name, Order = ++counter }; if (agent.Communications.Any()) { orderedAgent.AddCommunications(agent.Communications); } orderedAgents.Add(orderedAgent); } return orderedAgents; } return null; } private static Features ExtractFeatures(XContainer document) { Guard.AgainstNull(document); var featuresElement = document.Element("features"); if (featuresElement == null) { return null; } var tags = new HashSet<string>(StringComparer.OrdinalIgnoreCase); // NOTE: Bedrooms can be a number -or- the value 'STUDIO'. // YES - where a number is the logical value, they can now have a string. :cry: // So, if the value is a string, like STUDIO (or anything else), then the // value will be returned as ZERO. // If it's a STUDIO, we'll add that to the feature's tag hash set. var bedroomsValue = featuresElement.ValueOrDefault("bedrooms"); byte bedrooms = 0; if (!string.IsNullOrWhiteSpace(bedroomsValue)) { if (bedroomsValue.Equals("studio", StringComparison.OrdinalIgnoreCase)) { // *epic le sigh - yes, we have a text value for (what looks like) a number value. tags.Add("bedroom-studio"); } else { bedrooms = featuresElement.ByteValueOrDefault("bedrooms"); } } ExtractFeatureWithTextValues(featuresElement, "heating", new[] {"gas", "electric", "GDH", "solid", "other"}, tags); ExtractFeatureWithTextValues(featuresElement, "hotWaterService", new[] {"gas", "electric", "solar"}, tags); ExtractFeatureWithTextValues(featuresElement, "pool", new[] { "inground", "aboveground" }, tags, null); ExtractFeatureWithTextValues(featuresElement, "spa", new[] { "inground", "aboveground" }, tags, null); ExtractOtherFeatures(featuresElement, tags); // Now for the final, tricky part - extracting all the boolean stuff into tags. foreach (var feature in new[] {"features", "allowances", "ecoFriendly"} .Select(node => document.Element(node)) .Where(element => element != null).Select(ExtractBooleanFeatures) .Where(features => features.Any()).SelectMany(features => features)) { tags.Add(feature); } var finalFeatures = new Features { Bedrooms = bedrooms, Bathrooms = featuresElement.ByteValueOrDefault("bathrooms"), CarParking = new CarParking { Garages = featuresElement.BoolOrByteValueOrDefault("garages"), Carports = featuresElement.BoolOrByteValueOrDefault("carports"), OpenSpaces = featuresElement.BoolOrByteValueOrDefault("openSpaces") }, Ensuites = featuresElement.BoolOrByteValueOrDefault("ensuite"), Toilets = featuresElement.BoolOrByteValueOrDefault("toilets"), LivingAreas = featuresElement.BoolOrByteValueOrDefault("livingAreas"), }; if (tags.Any()) { finalFeatures.AddTags(tags); } return finalFeatures; } private static void ExtractFeatureWithTextValues(XElement document, string elementName, string[] validValues, ISet<string> tags, string delimeter = "-") { Guard.AgainstNull(document); Guard.AgainstNullOrWhiteSpace(elementName); Guard.AgainstNull(validValues); Guard.AgainstNull(tags); var type = document.ValueOrDefault(elementName, ("type")); if (string.IsNullOrWhiteSpace(type)) { return; } if (validValues.Contains(type, StringComparer.InvariantCultureIgnoreCase)) { tags.Add(string.Format("{0}{1}{2}", elementName, string.IsNullOrWhiteSpace(delimeter) ? string.Empty : delimeter, type)); } } private static void ExtractOtherFeatures(XElement document, ISet<string> tags) { Guard.AgainstNull(document); Guard.AgainstNull(tags); var value = document.ValueOrDefault("otherFeatures"); if (string.IsNullOrWhiteSpace(value)) { return; } // Split the value up into comma delimeted parts. var parts = value.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); foreach (var part in parts) { tags.Add(part.Trim()); } } private static ISet<string> ExtractBooleanFeatures(XElement document) { var suppliedFeatures = new ConcurrentBag<string>(); Parallel.ForEach(XmlFeatureHelpers.OtherFeatureNames, possibleFeature => { if (document.BoolValueOrDefault(possibleFeature)) { suppliedFeatures.Add(possibleFeature); } }); return new HashSet<string>(suppliedFeatures); } private static IList<Inspection> ExtractInspectionTimes(XElement document) { Guard.AgainstNull(document); var inspectionTimes = document.Element("inspectionTimes"); if (inspectionTimes == null) { return null; } var inspectionElements = inspectionTimes.Elements("inspection").ToList(); if (!inspectionElements.Any()) { return null; } var inspections = new List<Inspection>(); foreach (var inspectionElement in inspectionElements) { // -Some- xml data only contains empty inspects. (eg. RentalExpress). if (inspectionElement == null || inspectionElement.IsEmpty || string.IsNullOrWhiteSpace(inspectionElement.Value)) { continue; } // Only the following format is accepted as valid: DD-MON-YYYY hh:mm[am|pm] to hh:mm[am|pm] // REF: http://reaxml.realestate.com.au/docs/reaxml1-xml-format.html#inspection var data = inspectionElement.Value.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries); if (data.Length < 4) { throw new Exception("Inspection element has an invald Date/Time value. Element: " + inspectionElement); } DateTime inspectionStartsOn, inspectionEndsOn; DateTime.TryParse(string.Format("{0} {1}", data[0], data[1]), out inspectionStartsOn); DateTime.TryParse(string.Format("{0} {1}", data[0], data[3]), out inspectionEndsOn); if (inspectionStartsOn == DateTime.MinValue || inspectionEndsOn == DateTime.MinValue) { throw new Exception("Inspection element has an invalid Date/Time value. Element: " + inspectionElement); } var newInspection = new Inspection { OpensOn = inspectionStartsOn, ClosesOn = inspectionEndsOn == inspectionStartsOn ? (DateTime?) null : inspectionEndsOn }; // Just to be safe, lets make sure do get dupes. if (!inspections.Contains(newInspection)) { inspections.Add(newInspection); } } return inspections.Any() ? inspections.OrderBy(x => x.OpensOn).ToList() : null; } private static IList<Media> ExtractImages(XElement document) { Guard.AgainstNull(document); // Images can go in either <images> or <objects>. Only idiots are putting them in <objects> // Generally, <objects> is reservered for floorplans. :/ var imageElement = document.Element("images") ?? document.Element("objects"); if (imageElement == null) { return null; } var imagesElements = imageElement.Elements("img").ToArray(); if (!imagesElements.Any()) { return null; } return ConvertMediaXmlDataToMedia(imagesElements, ConvertImageOrderToNumber); } private static IList<Media> ExtractFloorPlans(XElement document) { Guard.AgainstNull(document); // NOTE: The idea is that <images> will contain images while <objects> will only be for floorplans. // Yes, some listings put their images in <objects>, but this is handled elsewhere. var objectElement = document.Element("objects"); if (objectElement == null) { return null; } var floorPlanElements = objectElement.Elements("floorplan").ToArray(); if (!floorPlanElements.Any()) { return null; } return ConvertMediaXmlDataToMedia(floorPlanElements, Convert.ToInt32); } private static IList<Media> ConvertMediaXmlDataToMedia(IEnumerable<XElement> mediaElements, Func<string, int> orderConverstionFunction) { // Note 1: Image 'urls' can either be via a Uri (yay!) or // a file name because the xml was provided in a zip file with // the images (booooo! hiss!!!) // Note 2: Not all image's might have a last mod time. var media = (from x in mediaElements let url = x.AttributeValueOrDefault("url") let file = x.AttributeValueOrDefault("file") let order = x.AttributeValueOrDefault("id") let createdOn = x.AttributeValueOrDefault("modTime") let contentType = x.AttributeValueOrDefault("format") where (!string.IsNullOrWhiteSpace(url) || !string.IsNullOrWhiteSpace(file)) && !string.IsNullOrWhiteSpace(order) select new Media { CreatedOn = string.IsNullOrWhiteSpace(createdOn) ? (DateTime?) null : ToDateTime(createdOn), Url = string.IsNullOrWhiteSpace(url) ? string.IsNullOrWhiteSpace(file) ? null : file : url, Order = orderConverstionFunction(order), ContentType = contentType }).ToList(); return media.Any() ? media : null; } private static IList<Media> ExtractVideos(XElement document) { Guard.AgainstNull(document); var videoUrl = document.ValueOrDefault("videoLink", "href"); return string.IsNullOrWhiteSpace(videoUrl) ? null : new List<Media> { new Media { CreatedOn = DateTime.UtcNow, Order = 1, Url = videoUrl } }; } private static IList<Media> ExtractDocuments(XElement document) { { Guard.AgainstNull(document); var mediaElement = document.Element("media"); if (mediaElement == null) { return null; } var attachmentElements = mediaElement.Elements("attachment") .Select((e, order) => new Media { Id = e.AttributeValueOrDefault("id"), CreatedOn = DateTime.UtcNow, Tag = e.AttributeValueOrDefault("usage"), Url = e.AttributeValueOrDefault("url"), ContentType = e.AttributeValueOrDefault("contentType"), Order = ++order }); return attachmentElements.ToArray(); } } private static PropertyType ExtractResidentialAndRentalPropertyType(XElement document) { var propertyType = PropertyType.Unknown; var category = document.ValueOrDefault("category", "name"); if (!string.IsNullOrWhiteSpace(category)) { propertyType = PropertyTypeHelpers.ToPropertyType(category); } return propertyType; } private static SalePricing ExtractSalePricing(XElement document, string defaultSalePriceTextIfMissing, string defaultSoldPriceTextIfMissing, CultureInfo cultureInfo) { Guard.AgainstNull(document); var salePricing = new SalePricing(); ExtractSalePrice(document, salePricing, defaultSalePriceTextIfMissing, cultureInfo); ExtractSoldDetails(document, defaultSoldPriceTextIfMissing, salePricing); return salePricing; } private static string CalculatePriceText(decimal price, string priceText, bool isDisplay, string defaultPriceTextIfNoneProvided) { /* *** Display: yes/no determins if _any_ info should be shown. * if no, ignore price AND priceText. * Missing display field == a Yes value. * display: yes, text: hi; result: hi. * display: yes, text: null, SP: 100,000; result: $100000 * display: no, dSPT: Contact Agent; result: ContactAgent * display: no, dSPT: null; result: null * */ if (isDisplay) { return !string.IsNullOrWhiteSpace(priceText) ? priceText : price.ToString("C0"); } // Display == No. So never display any price/priceText info. // We only display the default text if one is provided. return !string.IsNullOrWhiteSpace(defaultPriceTextIfNoneProvided) ? defaultPriceTextIfNoneProvided : null; } /* Eg xml. <residential ... <price display="yes">500000</price> <priceView>Between $400,000 and $600,000</priceView> /> */ private static void ExtractSalePrice(XElement document, SalePricing salePricing, string defaultPriceTextIfNoneProvided, CultureInfo cultureInfo) { Guard.AgainstNull(document); Guard.AgainstNull(salePricing); if (document.Element("price") == null) { // No sale price element, so don't do anything. return; } salePricing.SalePrice = document.MoneyValueOrDefault(cultureInfo, "price"); // This forces this property to be 'modified'. Otherwise, if we are asked to hide/not-display // the sale price, then setting null over null means the property is not changed, so that null value will // never be used/set _outside_ of this instance. // ie. a consumer will not think this value has changed and ignore it. BAD. salePricing.SalePriceText = string.Empty; var salePriceText = document.ValueOrDefault("priceView"); var displayAttributeValue = document.ValueOrDefault("price", "display"); var isDisplay = string.IsNullOrWhiteSpace(displayAttributeValue) || displayAttributeValue.ParseOneYesZeroNoToBool(); // NOTE 1: If Display="no" then we do not display anything for the price, regardless // of any other data provided. Otherwise, make a decision. // NOTE 2: If -NO- saleprice is provided (eg. this is _very_ common when we get // an SOLD or LEASED, etc) then we should leave the sale price text alone. // So only do the sale-price-text checks if we have a value set AND // it's ok to display a value. // NOTE 3: display='no' means NO price is displayed, even if there's a priceText. salePricing.SalePriceText = CalculatePriceText(salePricing.SalePrice, salePriceText, isDisplay, defaultPriceTextIfNoneProvided); var isUnderOffer = document.ValueOrDefault("underOffer", "value"); salePricing.IsUnderOffer = !string.IsNullOrWhiteSpace(isUnderOffer) && isUnderOffer.ParseOneYesZeroNoToBool(); } /* Eg xml. <residential ... <soldDetails> <price display="yes">580000</price> <date>2009-01-10-12:30:00</date> </soldDetails> /> */ private static void ExtractSoldDetails(XContainer document, string defaultSoldPriceTextIfMissing, SalePricing salePricing) { Guard.AgainstNull(document); Guard.AgainstNull(salePricing); var soldDetails = document.Element("soldDetails"); if (soldDetails != null) { // SoldPrice could be price or soldPrice. Thanks REA for such a great schema. var soldPrice = soldDetails.Element("price") ?? soldDetails.Element("soldPrice"); if (soldPrice != null) { ExtractSoldPrice(soldPrice, defaultSoldPriceTextIfMissing, salePricing); } var soldDate = soldDetails.Element("date") ?? soldDetails.Element("soldDate"); if (soldDate != null) { ExtractSoldOn(soldDate, salePricing); } } } // Eg xml: <price display="yes">580000</price> private static void ExtractSoldPrice(XElement document, string defaultSoldPriceTextIfMissing, SalePricing salePricing) { Guard.AgainstNull(document); Guard.AgainstNull(salePricing); salePricing.SoldPrice = document.DecimalValueOrDefault(); // This forces this property to be 'modified'. Otherwise, if we are asked to hide/not-display // the sale price, then setting null over null means the property is not changed, so that null value will // never be used/set _outside_ of this instance. // ie. a consumer will not think this value has changed and ignore it. BAD. salePricing.SoldPriceText = string.Empty; // NOTE 1: no/missing display price assumes a 'YES' and that the price -is- to be displayed. // NOTE 2: A _display attribute_ value of 'range' can only valid for commerical properties ... // and .. we don't handle commerical. So it will end up throwing an exception // which is legit in this case. // NOTE 3: display='no' means NO price is displayed, even if there's a priceText. var soldPriceText = document.ValueOrDefault("priceView"); var soldDisplayAttribute = document.ValueOrDefault(null, "display"); var isDisplay = string.IsNullOrWhiteSpace(soldDisplayAttribute) || soldDisplayAttribute.ParseOneYesZeroNoToBool(); salePricing.SoldPriceText = CalculatePriceText(salePricing.SoldPrice.Value, soldPriceText, isDisplay, defaultSoldPriceTextIfMissing); } // Eg xml: <date>2009-01-10-12:30:00</date> private static void ExtractSoldOn(XElement document, SalePricing salePricing) { Guard.AgainstNull(document); // SoldOn could be date or soldData. Thanks REA for such a great schema. var soldOnText = document.ValueOrDefault(); if (!string.IsNullOrWhiteSpace(soldOnText)) { salePricing.SoldOn = ToDateTime(soldOnText); } } private static DateTime? ExtractAuction(XElement document) { Guard.AgainstNull(document); var auction = document.ValueOrDefault("auction"); // NOTE: The REA documentation is vague as to the 100% specification on this. // So i'm going to assume the following (in order) // 1. <auction>date-time-in-here</auction> // 2. <auction date="date-time-in-here"></auction> // ** YET ANOTHER FRICKING EXAMPLE OF WHY THIS SCHEMA AND XML ARE F'ING CRAP ** if (string.IsNullOrWhiteSpace(auction)) { auction = document.ValueOrDefault("auction", "date"); } return (!string.IsNullOrWhiteSpace(auction)) ? (DateTime?)ToDateTime(auction) : null; } private static BuildingDetails ExtractBuildingDetails(XElement document) { Guard.AgainstNull(document); var buildingDetailsElement = document.Element("buildingDetails"); if (buildingDetailsElement == null) { return null; } var energyRating = buildingDetailsElement.DecimalValueOrDefault("energyRating"); return new BuildingDetails { Area = buildingDetailsElement.UnitOfMeasureOrDefault("area", "unit"), EnergyRating = energyRating <= 0 ? (decimal?) null : energyRating, }; } private static LandDetails ExtractLandDetails(XElement document) { Guard.AgainstNull(document); var landDetailsElement = document.Element("landDetails"); if (landDetailsElement == null) { return null; } var details = new LandDetails { Area = landDetailsElement.UnitOfMeasureOrDefault("area", "unit"), Frontage = landDetailsElement.UnitOfMeasureOrDefault("frontage", "unit"), CrossOver = landDetailsElement.ValueOrDefault("crossOver", "value") }; var depthElements = landDetailsElement.Elements("depth").ToArray(); if (depthElements.Any()) { foreach (var depthElement in depthElements) { var depthValue = depthElement.DecimalValueOrDefault(); var depthType = depthElement.AttributeValueOrDefault("unit"); var depthSide = depthElement.AttributeValueOrDefault("side"); if (depthValue > 0) { var depth = new Depth { Value = depthValue, Type = string.IsNullOrWhiteSpace(depthType) ? "Total" : depthType, Side = depthSide }; details.AddDepths(new[] {depth}); } } } return details; } private static IList<string> ExtractExternalLinks(XElement document) { Guard.AgainstNull(document); var elements = document.Elements("externalLink").ToArray(); if (!elements.Any()) { return null; } return (from e in elements let externalLink = e.AttributeValueOrDefault("href") where !string.IsNullOrWhiteSpace(externalLink) select Uri.UnescapeDataString(externalLink.Trim())) .ToList(); } ///// <summary> ///// REA Specific DateTime parsing. ///// </summary> //private static DateTime ParseReaDateTime(string someDateTime) //{ // Guard.AgainstNullOrWhiteSpace(someDateTime); // // FFS REA!!!! URGH!!!!!!!! :( // // Stick to fricking ISO8061 with yyyy-MM-ddTHH:mm:ss // // ONE FORMAT TO RULE THEM ALL. // // (not that hard, peeps). // var reaDateTimeFormats = new[] // { // "yyyy-MM-dd", // "yyyy-MM-dd-HH:mm", // "yyyy-MM-dd-HH:mm:ss", // "yyyy-MM-dd-hh:mm:sstt", // 2015-12-15-01:18:52PM // "yyyy-MM-ddTHH:mm", // "yyyy-MM-ddTHH:mm:ss", // "yyyyMMdd", // "yyyyMMdd-HHmm", // "yyyyMMDD-HHmmss", // "yyyyMMDDTHHmm", // "yyyyMMddTHHmmss" // }; // DateTime resultDateTime; // if (!DateTime.TryParse(someDateTime, out resultDateTime)) // { // DateTime.TryParseExact(someDateTime.Trim(), reaDateTimeFormats, CultureInfo.InvariantCulture, // DateTimeStyles.None, out resultDateTime); // } // return resultDateTime; //} //private static DateTime? ParseReaDateTimeNullable(string someDateTime) //{ // Guard.AgainstNullOrWhiteSpace(someDateTime); // var result = ParseReaDateTime(someDateTime); // return result == DateTime.MinValue // ? (DateTime?)null // : result; //} private static string ConvertCountryToIsoCode(string country) { Guard.AgainstNullOrWhiteSpace(country); switch (country.ToUpperInvariant()) { case "AU": case "AUS": case "AUSTRALIA": return "AU"; case "NZ": case "NEW ZEALAND": return "NZ"; default: throw new ArgumentOutOfRangeException("country", string.Format("Country '{0}' is unhandled - not sure of the ISO Code to use.", country)); } } private static int ConvertImageOrderToNumber(string imageOrder) { var character = imageOrder.ToUpperInvariant().First(); // 65 == 'A'. But we need 'm' to be 1, so we have to do some funky shit. // A == 65 - 63 == 2 // B == 66 - 63 == 3 return character == 'M' ? 1 : character - 63; } #endregion #region Residential Listing methods private static void ExtractResidentialData(ResidentialListing residentialListing, XElement document, string defaultSalePriceTextIfMissing, string defaultSoldPriceTextIfMissing, CultureInfo cultureInfo) { Guard.AgainstNull(residentialListing); Guard.AgainstNull(document); residentialListing.PropertyType = ExtractResidentialAndRentalPropertyType(document); residentialListing.Pricing = ExtractSalePricing(document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); residentialListing.AuctionOn = ExtractAuction(document); residentialListing.BuildingDetails = ExtractBuildingDetails(document); residentialListing.CouncilRates = document.ValueOrDefault("councilRates"); ExtractHomeAndLandPackage(document, residentialListing); ExtractResidentialNewConstruction(document, residentialListing); } private static void ExtractHomeAndLandPackage(XElement document, ResidentialListing residentialListing) { Guard.AgainstNull(document); Guard.AgainstNull(residentialListing); var homeAndLandPackageElement = document.Element("isHomeLandPackage"); if (homeAndLandPackageElement == null) { return; } if (homeAndLandPackageElement.AttributeBoolValueOrDefault("value")) { if (residentialListing.Features == null) { residentialListing.Features = new Features(); } residentialListing.Features.AddTags(new[] {"houseAndLandPackage"}); }; } private static void ExtractResidentialNewConstruction(XElement document, ResidentialListing listing) { Guard.AgainstNull(document); Guard.AgainstNull(listing); if (!document.BoolValueOrDefault("newConstruction")) { return; } if (listing.Features == null) { listing.Features= new Features(); } listing.Features.AddTags(new[] {"isANewConstruction"}); } #endregion #region Rental Listing Methods private static void ExtractRentalData(RentalListing rentalListing, XElement document, CultureInfo cultureInfo) { Guard.AgainstNull(rentalListing); Guard.AgainstNull(document); var dateAvailble = document.ValueOrDefault("dateAvailable"); if (!string.IsNullOrWhiteSpace(dateAvailble)) { rentalListing.AvailableOn = ToDateTime(dateAvailble); } rentalListing.PropertyType = ExtractResidentialAndRentalPropertyType(document); rentalListing.Pricing = ExtractRentalPricing(document, cultureInfo); rentalListing.Features = ExtractFeatures(document); rentalListing.BuildingDetails = ExtractBuildingDetails(document); ExtractRentalNewConstruction(document, rentalListing); } // REF: http://reaxml.realestate.com.au/docs/reaxml1-xml-format.html#rent private static RentalPricing ExtractRentalPricing(XElement xElement, CultureInfo cultureInfo) { Guard.AgainstNull(xElement); // Quote: There can be multiple rent elements if you wish to specify a price for both monthly and weekly. // However, at least one of the rent elements must be for a weekly period. // Result: FML :( var rentElements = xElement.Elements("rent").ToArray(); if (!rentElements.Any()) { return null; } // We will only use the WEEKLY one. var rentalPricing = new RentalPricing(); foreach (var rentElement in rentElements) { // Have to have a period. var frequency = rentElement.AttributeValueOrDefault("period"); if (string.IsNullOrWhiteSpace(frequency)) { continue; } if (frequency.Equals("week", StringComparison.InvariantCultureIgnoreCase) || frequency.Equals("weekly", StringComparison.InvariantCultureIgnoreCase)) { rentalPricing.PaymentFrequencyType = PaymentFrequencyType.Weekly; } else if (frequency.Equals("month", StringComparison.InvariantCultureIgnoreCase) || frequency.Equals("monthly", StringComparison.InvariantCultureIgnoreCase)) { rentalPricing.PaymentFrequencyType = PaymentFrequencyType.Monthly; } rentalPricing.RentalPrice = rentElement.MoneyValueOrDefault(cultureInfo); var displayAttributeValue = rentElement.AttributeValueOrDefault("display"); var isDisplay = string.IsNullOrWhiteSpace(displayAttributeValue) || displayAttributeValue.ParseOneYesZeroNoToBool(); rentalPricing.RentalPriceText = isDisplay ? rentalPricing.RentalPrice.ToString("C0") : null; // NOTE: We only parse the first one. You have more than one? Pffftttt!!! Die! break; } // NOTE: Even though we have set the rental price text to be the last // rental period's value ... this can now be overwritten by // whatever value they might have in here ... if they have a value. var priceView = xElement.ValueOrDefault("priceView"); if (!string.IsNullOrWhiteSpace(priceView)) { rentalPricing.RentalPriceText = priceView; } rentalPricing.Bond = xElement.NullableMoneyValueOrDefault(cultureInfo, "bond"); return rentalPricing; } private static void ExtractRentalNewConstruction(XElement document, RentalListing listing) { Guard.AgainstNull(document); Guard.AgainstNull(listing); if (!document.BoolValueOrDefault("newConstruction")) { return; } if (listing.Features == null) { listing.Features = new Features(); } listing.Features.AddTags(new[] {"isANewConstruction"}); } #endregion #region Land Listing Methods private static void ExtractLandData(LandListing landListing, XElement document, string defaultSalePriceTextIfMissing, string defaultSoldPriceTextIfMissing, CultureInfo cultureInfo) { Guard.AgainstNull(landListing); Guard.AgainstNull(document); landListing.CategoryType = ExtractLandCategoryType(document); landListing.Pricing = ExtractSalePricing(document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); landListing.AuctionOn = ExtractAuction(document); landListing.Estate = ExtractLandEstate(document); landListing.AuctionOn = ExtractAuction(document); landListing.CouncilRates = document.ValueOrDefault("councilRates"); } private static Core.Models.Land.CategoryType ExtractLandCategoryType(XElement xElement) { var category = xElement.ValueOrDefault("landCategory", "name"); return string.IsNullOrWhiteSpace(category) ? Core.Models.Land.CategoryType.Unknown : CategoryTypeHelpers.ToCategoryType(category); } private static LandEstate ExtractLandEstate(XElement xElement) { Guard.AgainstNull(xElement); var estateElement = xElement.Element("estate"); if (estateElement == null) { return null; } return new LandEstate { Name = estateElement.ValueOrDefault("name"), Stage = estateElement.ValueOrDefault("stage") }; } #endregion #region Rural Listing Methods private static void ExtractRuralData(RuralListing ruralListing, XElement document, string defaultSalePriceTextIfMissing, string defaultSoldPriceTextIfMissing, CultureInfo cultureInfo) { Guard.AgainstNull(document); ruralListing.CategoryType = ExtractRuralCategoryType(document); ruralListing.Pricing = ExtractSalePricing(document, defaultSalePriceTextIfMissing, defaultSoldPriceTextIfMissing, cultureInfo); ruralListing.AuctionOn = ExtractAuction(document); ruralListing.RuralFeatures = ExtractRuralFeatures(document); ruralListing.CouncilRates = ExtractRuralCouncilRates(document); ruralListing.BuildingDetails = ExtractBuildingDetails(document); ExtractRuralNewConstruction(document, ruralListing); } private static Core.Models.Rural.CategoryType ExtractRuralCategoryType(XElement document) { Guard.AgainstNull(document); var categoryElement = document.Element("ruralCategory"); if (categoryElement == null) { return Core.Models.Rural.CategoryType.Unknown; } var categoryValue = categoryElement.AttributeValueOrDefault("name"); return string.IsNullOrWhiteSpace(categoryValue) ? Core.Models.Rural.CategoryType.Unknown : Core.Models.Rural.CategoryTypeHelpers.ToCategoryType(categoryValue); } private static RuralFeatures ExtractRuralFeatures(XElement document) { Guard.AgainstNull(document); var ruralFeaturesElement = document.Element("ruralFeatures"); if (ruralFeaturesElement == null) { return null; } return new RuralFeatures { AnnualRainfall = ruralFeaturesElement.ValueOrDefault("annualRainfall"), CarryingCapacity = ruralFeaturesElement.ValueOrDefault("carryingCapacity"), Fencing = ruralFeaturesElement.ValueOrDefault("fencing"), Improvements = ruralFeaturesElement.ValueOrDefault("improvements"), Irrigation = ruralFeaturesElement.ValueOrDefault("irrigation"), Services = ruralFeaturesElement.ValueOrDefault("services"), SoilTypes = ruralFeaturesElement.ValueOrDefault("soilTypes") }; } private static string ExtractRuralCouncilRates(XElement document) { Guard.AgainstNull(document); var ruralFeaturesElement = document.Element("ruralFeatures"); return ruralFeaturesElement == null ? null : ruralFeaturesElement.ValueOrDefault("councilRates"); } private static void ExtractRuralNewConstruction(XElement document, RuralListing listing) { Guard.AgainstNull(document); Guard.AgainstNull(listing); if (!document.BoolValueOrDefault("newConstruction")) { return; } if (listing.Features == null) { listing.Features = new Features(); } listing.Features.AddTags(new[] {"isANewConstruction"}); } #endregion private class SplitElementResult { public IList<XElement> KnownXmlData { get; set; } public IList<XElement> UnknownXmlData { get; set; } } } }
OpenRealEstate/OpenRealEstate.NET
Code/OpenRealEstate.Services/RealEstateComAu/ReaXmlTransmorgrifier.cs
C#
mit
70,646
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; /// <summary> /// Filter to correct the joint locations and joint orientations to constraint to range of viable human motion. /// </summary> public class BoneOrientationsConstraint { public enum ConstraintAxis { X = 0, Y = 1, Z = 2 } // The Joint Constraints. private readonly List<BoneOrientationConstraint> jointConstraints = new List<BoneOrientationConstraint>(); //private GameObject debugText; /// Initializes a new instance of the BoneOrientationConstraints class. public BoneOrientationsConstraint() { //debugText = GameObject.Find("CalibrationText"); } // find the bone constraint structure for given joint // returns the structure index in the list, or -1 if the bone structure is not found private int FindBoneOrientationConstraint(int joint) { for(int i = 0; i < jointConstraints.Count; i++) { if(jointConstraints[i].joint == joint) return i; } // not found return -1; } // AddJointConstraint - Adds a joint constraint to the system. public void AddBoneOrientationConstraint(int joint, ConstraintAxis axis, float angleMin, float angleMax) { int index = FindBoneOrientationConstraint(joint); BoneOrientationConstraint jc = index >= 0 ? jointConstraints[index] : new BoneOrientationConstraint(joint); if(index < 0) { index = jointConstraints.Count; jointConstraints.Add(jc); } AxisOrientationConstraint constraint = new AxisOrientationConstraint(axis, angleMin, angleMax); jc.axisConstrainrs.Add(constraint); jointConstraints[index] = jc; } // AddDefaultConstraints - Adds a set of default joint constraints for normal human poses. // This is a reasonable set of constraints for plausible human bio-mechanics. public void AddDefaultConstraints() { // // Spine // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.X, -10f, 45f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.Y, -10f, 30f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.Z, -10f, 30f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.X, -90f, 95f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.Y, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.Spine, ConstraintAxis.Z, -90f, 90f); // ShoulderCenter AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter, ConstraintAxis.X, -30f, 10f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter, ConstraintAxis.Y, -20f, 20f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter, ConstraintAxis.Z, -20f, 20f); // ShoulderLeft, ShoulderRight AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft, ConstraintAxis.X, 0f, 30f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight, ConstraintAxis.X, 0f, 30f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft, ConstraintAxis.Y, -60f, 60f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight, ConstraintAxis.Y, -30f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderLeft, ConstraintAxis.Z, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderRight, ConstraintAxis.Z, -90f, 90f); // // ElbowLeft, ElbowRight // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.X, 300f, 360f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.X, 300f, 360f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.Y, 210f, 340f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.Y, 0f, 120f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.Z, -90f, 30f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.Z, 0f, 120f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.X, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.X, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.Y, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.Y, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowLeft, ConstraintAxis.Z, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.ElbowRight, ConstraintAxis.Z, -90f, 90f); // WristLeft, WristRight AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristLeft, ConstraintAxis.X, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristRight, ConstraintAxis.X, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristLeft, ConstraintAxis.Y, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristRight, ConstraintAxis.Y, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristLeft, ConstraintAxis.Z, -90f, 90f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.WristRight, ConstraintAxis.Z, -90f, 90f); // // HipLeft, HipRight // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft, ConstraintAxis.X, 0f, 90f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipRight, ConstraintAxis.X, 0f, 90f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft, ConstraintAxis.Y, 0f, 0f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipRight, ConstraintAxis.Y, 0f, 0f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipLeft, ConstraintAxis.Z, 270f, 360f); // AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.HipRight, ConstraintAxis.Z, 0f, 90f); // KneeLeft, KneeRight AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeLeft, ConstraintAxis.X, 270f, 360f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeRight, ConstraintAxis.X, 270f, 360f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeLeft, ConstraintAxis.Y, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeRight, ConstraintAxis.Y, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeLeft, ConstraintAxis.Z, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.KneeRight, ConstraintAxis.Z, 0f, 0f); // AnkleLeft, AnkleRight AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft, ConstraintAxis.X, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight, ConstraintAxis.X, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft, ConstraintAxis.Y, -40f, 40f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight, ConstraintAxis.Y, -40f, 40f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft, ConstraintAxis.Z, 0f, 0f); AddBoneOrientationConstraint((int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight, ConstraintAxis.Z, 0f, 0f); } // ApplyBoneOrientationConstraints and constrain rotations. public void Constrain(ref Matrix4x4[] jointOrientations, ref bool[] jointTracked) { // Constraints are defined as a vector with respect to the parent bone vector, and a constraint angle, // which is the maximum angle with respect to the constraint axis that the bone can move through. // Calculate constraint values. 0.0-1.0 means the bone is within the constraint cone. Greater than 1.0 means // it lies outside the constraint cone. for (int i = 0; i < this.jointConstraints.Count; i++) { BoneOrientationConstraint jc = this.jointConstraints[i]; if (!jointTracked[i] || jc.joint == (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter) { // End joint is not tracked or Hip Center has no parent to perform this calculation with. continue; } // If the joint has a parent, constrain the bone direction to be within the constraint cone int parentIdx = KinectWrapper.GetSkeletonJointParent(jc.joint); // Local bone orientation relative to parent Matrix4x4 localOrientationMatrix = jointOrientations[parentIdx].inverse * jointOrientations[jc.joint]; Vector3 localOrientationZ = (Vector3)localOrientationMatrix.GetColumn(2); Vector3 localOrientationY = (Vector3)localOrientationMatrix.GetColumn(1); if(localOrientationZ == Vector3.zero || localOrientationY == Vector3.zero) continue; Quaternion localRotation = Quaternion.LookRotation(localOrientationZ, localOrientationY); Vector3 eulerAngles = localRotation.eulerAngles; bool isConstrained = false; //Matrix4x4 globalOrientationMatrix = jointOrientations[jc.joint]; //Quaternion globalRotation = Quaternion.LookRotation(globalOrientationMatrix.GetColumn(2), globalOrientationMatrix.GetColumn(1)); for(int a = 0; a < jc.axisConstrainrs.Count; a++) { AxisOrientationConstraint ac = jc.axisConstrainrs[a]; Quaternion axisRotation = Quaternion.AngleAxis(localRotation.eulerAngles[ac.axis], ac.rotateAround); //Quaternion axisRotation = Quaternion.AngleAxis(globalRotation.eulerAngles[ac.axis], ac.rotateAround); float angleFromMin = Quaternion.Angle(axisRotation, ac.minQuaternion); float angleFromMax = Quaternion.Angle(axisRotation, ac.maxQuaternion); if(!(angleFromMin <= ac.angleRange && angleFromMax <= ac.angleRange)) { // Keep the current rotations around other axes and only // correct the axis that has fallen out of range. //Vector3 euler = globalRotation.eulerAngles; if(angleFromMin > angleFromMax) { eulerAngles[ac.axis] = ac.angleMax; } else { eulerAngles[ac.axis] = ac.angleMin; } isConstrained = true; } } if(isConstrained) { Quaternion constrainedRotation = Quaternion.Euler(eulerAngles); // Put it back into the bone orientations localOrientationMatrix.SetTRS(Vector3.zero, constrainedRotation, Vector3.one); jointOrientations[jc.joint] = jointOrientations[parentIdx] * localOrientationMatrix; //globalOrientationMatrix.SetTRS(Vector3.zero, constrainedRotation, Vector3.one); //jointOrientations[jc.joint] = globalOrientationMatrix; switch(jc.joint) { case (int)KinectWrapper.NuiSkeletonPositionIndex.ShoulderCenter: jointOrientations[(int)KinectWrapper.NuiSkeletonPositionIndex.Head] = jointOrientations[jc.joint]; break; case (int)KinectWrapper.NuiSkeletonPositionIndex.WristLeft: jointOrientations[(int)KinectWrapper.NuiSkeletonPositionIndex.HandLeft] = jointOrientations[jc.joint]; break; case (int)KinectWrapper.NuiSkeletonPositionIndex.WristRight: jointOrientations[(int)KinectWrapper.NuiSkeletonPositionIndex.HandRight] = jointOrientations[jc.joint]; break; case (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft: jointOrientations[(int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft] = jointOrientations[jc.joint]; break; case (int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight: jointOrientations[(int)KinectWrapper.NuiSkeletonPositionIndex.FootRight] = jointOrientations[jc.joint]; break; } } // globalRotation = Quaternion.LookRotation(globalOrientationMatrix.GetColumn(2), globalOrientationMatrix.GetColumn(1)); // string stringToDebug = string.Format("{0}, {2}", (KinectWrapper.NuiSkeletonPositionIndex)jc.joint, // globalRotation.eulerAngles, localRotation.eulerAngles); // Debug.Log(stringToDebug); // // if(debugText != null) // debugText.guiText.text = stringToDebug; } } // Joint Constraint structure to hold the constraint axis, angle and cone direction and associated joint. private struct BoneOrientationConstraint { // skeleton joint public int joint; // the list of axis constraints for this bone public List<AxisOrientationConstraint> axisConstrainrs; public BoneOrientationConstraint(int joint) { this.joint = joint; axisConstrainrs = new List<AxisOrientationConstraint>(); } } private struct AxisOrientationConstraint { // the axis to rotate around public int axis; public Vector3 rotateAround; // min, max and range of allowed angle public float angleMin; public float angleMax; public Quaternion minQuaternion; public Quaternion maxQuaternion; public float angleRange; public AxisOrientationConstraint(ConstraintAxis axis, float angleMin, float angleMax) { // Set the axis that we will rotate around this.axis = (int)axis; switch(axis) { case ConstraintAxis.X: this.rotateAround = Vector3.right; break; case ConstraintAxis.Y: this.rotateAround = Vector3.up; break; case ConstraintAxis.Z: this.rotateAround = Vector3.forward; break; default: this.rotateAround = Vector3.zero; break; } // Set the min and max rotations in degrees this.angleMin = angleMin; this.angleMax = angleMax; // Set the min and max rotations in quaternion space this.minQuaternion = Quaternion.AngleAxis(angleMin, this.rotateAround); this.maxQuaternion = Quaternion.AngleAxis(angleMax, this.rotateAround); this.angleRange = angleMax - angleMin; } } }
webrokeit/DTU
02515 - Healthcare Technology/Jump Squat/Example/Assets/KinectScripts/Filters/BoneOrientationsConstraint.cs
C#
mit
14,866
<?php $email_to = "benwaymichael@gmail.com"; $email_subject = "MB Designs"; $nameCompany = $_POST['NameCompany']; // required $phone = $_POST['Phone']; // required $email = $_POST['Email']; // required $message = $_POST['Message']; // not required $budget = $_POST['Budget']; // required // These are for testing if it is broken in the app //$nameCompany = "test"; // required //$phone = "test"; // required //$email = "test"; // required //$message = "test"; // not required //$budget = "Message test"; // required $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type", "bcc:", "to:", "cc:", "href"); return str_replace($bad, "", $string); } $email_message .= "Name/Company: " . $nameCompany . "\n"; $email_message .= "Phone: " . $phone . "\n"; $email_message .= "Email: " . $email . "\n"; $email_message .= "Message: " . $message . "\n"; $email_message .= "Budget: " . $budget . "\n"; // create email headers $headers = 'From: ' . $email . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); // Below is the redirect line that needs to be enabled for live //header('Location: http://dev.michaelbenway.com'); // remove everything below when going to the live minimized file ?> <!DOCTYPE html> <html lang="en"> <body> <?php print '<code class="block"><pre>sent to: ' . $email_to . '</pre></code>'; print '<code class="block"><pre>subject: ' . $email_subject . '</pre></code>'; print '<code class="block"><pre>' . $nameCompany . '</pre></code>'; print '<code class="block"><pre>result: ' . $phone . '</pre></code>'; print '<code class="block"><pre>result: ' . $email . '</pre></code>'; print '<code class="block"><pre>result: ' . $message . '</pre></code>'; print '<code class="block"><pre>result: ' . $budget . '</pre></code>'; ?> </body> </html>
mbenway1/portfoilo
app/submit-test.php
PHP
mit
1,904
// Copyright 2012 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "version.h" // These macros define the version number for the current version. // NOTE these macros are used by some of the tool scripts and the build // system so their names cannot be changed without changing the scripts. #define MAJOR_VERSION 3 #define MINOR_VERSION 23 #define BUILD_NUMBER 0 #define PATCH_LEVEL 0 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) #define IS_CANDIDATE_VERSION 1 // Define SONAME to have the build system put a specific SONAME into the // shared library instead the generic SONAME generated from the V8 version // number. This define is mainly used by the build system script. #define SONAME "" #if IS_CANDIDATE_VERSION #define CANDIDATE_STRING " (candidate)" #else #define CANDIDATE_STRING "" #endif #define SX(x) #x #define S(x) SX(x) #if PATCH_LEVEL > 0 #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \ S(PATCH_LEVEL) CANDIDATE_STRING #else #define VERSION_STRING \ S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \ CANDIDATE_STRING #endif namespace v8 { namespace internal { int Version::major_ = MAJOR_VERSION; int Version::minor_ = MINOR_VERSION; int Version::build_ = BUILD_NUMBER; int Version::patch_ = PATCH_LEVEL; bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0); const char* Version::soname_ = SONAME; const char* Version::version_string_ = VERSION_STRING; // Calculate the V8 version string. void Version::GetString(Vector<char> str) { const char* candidate = IsCandidate() ? " (candidate)" : ""; #ifdef USE_SIMULATOR const char* is_simulator = " SIMULATOR"; #else const char* is_simulator = ""; #endif // USE_SIMULATOR if (GetPatch() > 0) { OS::SNPrintF(str, "%d.%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate, is_simulator); } else { OS::SNPrintF(str, "%d.%d.%d%s%s", GetMajor(), GetMinor(), GetBuild(), candidate, is_simulator); } } // Calculate the SONAME for the V8 shared library. void Version::GetSONAME(Vector<char> str) { if (soname_ == NULL || *soname_ == '\0') { // Generate generic SONAME if no specific SONAME is defined. const char* candidate = IsCandidate() ? "-candidate" : ""; if (GetPatch() > 0) { OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate); } else { OS::SNPrintF(str, "libv8-%d.%d.%d%s.so", GetMajor(), GetMinor(), GetBuild(), candidate); } } else { // Use specific SONAME. OS::SNPrintF(str, "%s", soname_); } } } } // namespace v8::internal
h0x91b/redis-v8
redis/deps/v8/src/version.cc
C++
mit
4,513
require 'volt/server/rack/source_map_server' # There is currently a weird issue with therubyracer # https://github.com/rails/execjs/issues/15 # https://github.com/middleman/middleman/issues/1367 # # To get around this, we just force Node for the time being ENV['EXECJS_RUNTIME'] = 'Node' # Sets up the maps for the opal assets, and source maps if enabled. module Volt class OpalFiles attr_reader :environment def initialize(builder, app_path, component_paths) Opal::Processor.source_map_enabled = Volt.source_maps? Opal::Processor.const_missing_enabled = true # Setup Opal paths # Add the lib directory to the load path Opal.append_path(Volt.root + '/app') Opal.append_path(Volt.root + '/lib') Gem.loaded_specs.values.select {|gem| gem.name =~ /^(volt|ejson_ext)/ } .each do |gem| ['app', 'lib'].each do |folder| path = gem.full_gem_path + "/#{folder}" Opal.append_path(path) if Dir.exist?(path) end end # Don't run arity checks in production # Opal::Processor.arity_check_enabled = !Volt.env.production? # Opal::Processor.dynamic_require_severity = :raise server = Opal::Server.new(prefix: '/') @component_paths = component_paths # @environment = Opal::Environment.new @environment = server.sprockets # Since the scope changes in builder blocks, we need to capture # environment in closure environment = @environment environment.cache = Sprockets::Cache::FileStore.new('./tmp') # Compress in production if Volt.config.compress_javascript require 'uglifier' environment.js_compressor = Sprockets::UglifierCompressor end if Volt.config.compress_css # Use csso for css compression by default. require 'volt/utils/csso_patch' require 'csso' Csso.install(environment) end server.append_path(app_path) volt_gem_lib_path = File.expand_path(File.join(File.dirname(__FILE__), '../../..')) server.append_path(volt_gem_lib_path) add_asset_folders(server) builder.map '/assets' do run server end # map server.source_maps.prefix do # run server.source_maps # end # if Volt.source_maps? # source_maps = SourceMapServer.new(environment) # # builder.map(source_maps.prefix) do # run source_maps # end # end end def add_asset_folders(environment) @component_paths.asset_folders do |asset_folder| environment.append_path(asset_folder) end end end end
merongivian/volt
lib/volt/server/rack/opal_files.rb
Ruby
mit
2,735
var fs = require('fs') var yaml = require('yamljs') // Usage: node lib/roundup-helper.js <RoundupMonth> <PostMonth> <Year> // Returns: Markdown table rows to be copy and pasted into blog post // Example for August roundup: node lib/roundup-helper.js August September 2016 // Example post: http://electron.atom.io/blog/2016/09/06/august-2016-roundup // Note: A current month comment must be added to _data/apps.yml before using var args = process.argv.slice(2) if (!args[3]) args.push(new Date().getFullYear()) var yamlString = fs.readFileSync('_data/apps.yml').toString() var roundupMonth = yamlString.split(`# ${args[0]} ${args[2]}`)[1].split(`# ${args[1]} ${args[2]}`)[0] var apps = yaml.parse(roundupMonth) var rows = '' apps.forEach(function (app) { app.description = app.description.replace('.', '').replace('!', '') return rows += `| <img src='/images/apps/${app.icon}' width='50'> | [${app.name}](${app.website || app.repository}) | ${app.description} |\n` }) console.log(rows)
noomatv/noomatv.github.io
lib/roundup-helper.js
JavaScript
mit
994
// compare version of current installation with the one on github // inform the user of any update if github version is different // $(document).ready(function() { var current = $.get("./version/version-info.json"), github = $.get("http://raw.githubusercontent.com/kodejuice/localGoogoo/master/version/version-info.json"); current.then(function(curr) { github.then(function(repo) { if (typeof curr == "string") curr = JSON.parse(curr); if (typeof repo == "string") repo = JSON.parse(repo); if (repo.version_number > curr.version_number) { // theres been an update, inform user // display changes repo.changes.forEach(function(v) { $('.alert-info.version .update-list').append("<li>" + v + "</li>"); }); // display the alert $('.alert-info.version').show(); } }); }); });
kodejuice/localGoogle
version/version-tracker.js
JavaScript
mit
939
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.10.1-rc2-master-7bbfd1f */ goog.provide('ng.material.components.list'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.list * @description * List module */ angular.module('material.components.list', [ 'material.core' ]) .controller('MdListController', MdListController) .directive('mdList', mdListDirective) .directive('mdListItem', mdListItemDirective); /** * @ngdoc directive * @name mdList * @module material.components.list * * @restrict E * * @description * The `<md-list>` directive is a list container for 1..n `<md-list-item>` tags. * * @usage * <hljs lang="html"> * <md-list> * <md-list-item class="md-2-line" ng-repeat="item in todos"> * <md-checkbox ng-model="item.done"></md-checkbox> * <div class="md-list-item-text"> * <h3>{{item.title}}</h3> * <p>{{item.description}}</p> * </div> * </md-list-item> * </md-list> * </hljs> */ function mdListDirective($mdTheming) { return { restrict: 'E', compile: function(tEl) { tEl[0].setAttribute('role', 'list'); return $mdTheming; } }; } mdListDirective.$inject = ["$mdTheming"]; /** * @ngdoc directive * @name mdListItem * @module material.components.list * * @restrict E * * @description * The `<md-list-item>` directive is a container intended for row items in a `<md-list>` container. * * @usage * <hljs lang="html"> * <md-list> * <md-list-item> * Item content in list * </md-list-item> * </md-list> * </hljs> * */ function mdListItemDirective($mdAria, $mdConstant, $timeout) { var proxiedTypes = ['md-checkbox', 'md-switch']; return { restrict: 'E', controller: 'MdListController', compile: function(tEl, tAttrs) { // Check for proxy controls (no ng-click on parent, and a control inside) var secondaryItem = tEl[0].querySelector('.md-secondary'); var hasProxiedElement; var proxyElement; tEl[0].setAttribute('role', 'listitem'); if (!tAttrs.ngClick) { for (var i = 0, type; type = proxiedTypes[i]; ++i) { if (proxyElement = tEl[0].querySelector(type)) { hasProxiedElement = true; break; } } if (hasProxiedElement) { wrapIn('div'); } else if (!tEl[0].querySelector('md-button')) { tEl.addClass('md-no-proxy'); } } else { wrapIn('button'); } setupToggleAria(); function setupToggleAria() { var toggleTypes = ['md-switch', 'md-checkbox']; var toggle; for (var i = 0, toggleType; toggleType = toggleTypes[i]; ++i) { if (toggle = tEl.find(toggleType)[0]) { if (!toggle.hasAttribute('aria-label')) { var p = tEl.find('p')[0]; if (!p) return; toggle.setAttribute('aria-label', 'Toggle ' + p.textContent); } } } } function wrapIn(type) { var container; if (type == 'div') { container = angular.element('<div class="md-no-style md-list-item-inner">'); container.append(tEl.contents()); tEl.addClass('md-proxy-focus'); } else { container = angular.element('<md-button class="md-no-style"><div class="md-list-item-inner"></div></md-button>'); var copiedAttrs = ['ng-click', 'aria-label', 'ng-disabled']; angular.forEach(copiedAttrs, function(attr) { if (tEl[0].hasAttribute(attr)) { container[0].setAttribute(attr, tEl[0].getAttribute(attr)); tEl[0].removeAttribute(attr); } }); container.children().eq(0).append(tEl.contents()); } tEl[0].setAttribute('tabindex', '-1'); tEl.append(container); if (secondaryItem && secondaryItem.hasAttribute('ng-click')) { $mdAria.expect(secondaryItem, 'aria-label'); var buttonWrapper = angular.element('<md-button class="md-secondary-container md-icon-button">'); buttonWrapper.attr('ng-click', secondaryItem.getAttribute('ng-click')); secondaryItem.removeAttribute('ng-click'); secondaryItem.setAttribute('tabindex', '-1'); secondaryItem.classList.remove('md-secondary'); buttonWrapper.append(secondaryItem); secondaryItem = buttonWrapper[0]; } // Check for a secondary item and move it outside if ( secondaryItem && ( secondaryItem.hasAttribute('ng-click') || ( tAttrs.ngClick && isProxiedElement(secondaryItem) ) )) { tEl.addClass('md-with-secondary'); tEl.append(secondaryItem); } } function isProxiedElement(el) { return proxiedTypes.indexOf(el.nodeName.toLowerCase()) != -1; } return postLink; function postLink($scope, $element, $attr, ctrl) { var proxies = [], firstChild = $element[0].firstElementChild, hasClick = firstChild && firstChild.hasAttribute('ng-click'); computeProxies(); computeClickable(); if ($element.hasClass('md-proxy-focus') && proxies.length) { angular.forEach(proxies, function(proxy) { proxy = angular.element(proxy); $scope.mouseActive = false; proxy.on('mousedown', function() { $scope.mouseActive = true; $timeout(function(){ $scope.mouseActive = false; }, 100); }) .on('focus', function() { if ($scope.mouseActive === false) { $element.addClass('md-focused'); } proxy.on('blur', function proxyOnBlur() { $element.removeClass('md-focused'); proxy.off('blur', proxyOnBlur); }); }); }); } function computeProxies() { var children = $element.children(); if (children.length && !children[0].hasAttribute('ng-click')) { angular.forEach(proxiedTypes, function(type) { angular.forEach(firstChild.querySelectorAll(type), function(child) { proxies.push(child); }); }); } } function computeClickable() { if (proxies.length || hasClick) { $element.addClass('md-clickable'); ctrl.attachRipple($scope, angular.element($element[0].querySelector('.md-no-style'))); } } if (!hasClick && !proxies.length) { firstChild && firstChild.addEventListener('keypress', function(e) { if (e.target.nodeName != 'INPUT' && e.target.nodeName != 'TEXTAREA') { var keyCode = e.which || e.keyCode; if (keyCode == $mdConstant.KEY_CODE.SPACE) { if (firstChild) { firstChild.click(); e.preventDefault(); e.stopPropagation(); } } } }); } $element.off('click'); $element.off('keypress'); if (proxies.length && firstChild) { $element.children().eq(0).on('click', function(e) { if (firstChild.contains(e.target)) { angular.forEach(proxies, function(proxy) { if (e.target !== proxy && !proxy.contains(e.target)) { angular.element(proxy).triggerHandler('click'); } }); } }); } } } }; } mdListItemDirective.$inject = ["$mdAria", "$mdConstant", "$timeout"]; /* * @private * @ngdoc controller * @name MdListController * @module material.components.list * */ function MdListController($scope, $element, $mdListInkRipple) { var ctrl = this; ctrl.attachRipple = attachRipple; function attachRipple (scope, element) { var options = {}; $mdListInkRipple.attach(scope, element, options); } } MdListController.$inject = ["$scope", "$element", "$mdListInkRipple"]; ng.material.components.list = angular.module("material.components.list");
CirceThanis/bower-material
modules/closure/list/list.js
JavaScript
mit
8,249
package hudson.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Adds more to commons-io. * * @author Kohsuke Kawaguchi * @since 1.337 */ public class IOUtils extends org.apache.commons.io.IOUtils { public static void copy(File src, OutputStream out) throws IOException { FileInputStream in = new FileInputStream(src); try { copy(in,out); } finally { closeQuietly(in); } } public static void copy(InputStream in, File out) throws IOException { FileOutputStream fos = new FileOutputStream(out); try { copy(in,fos); } finally { closeQuietly(fos); } } /** * Ensures that the given directory exists (if not, it's created, including all the parent directories.) * * @return * This method returns the 'dir' parameter so that the method call flows better. */ public static File mkdirs(File dir) throws IOException { if(dir.mkdirs() || dir.exists()) return dir; // following Ant <mkdir> task to avoid possible race condition. try { Thread.sleep(10); } catch (InterruptedException e) { // ignore } if (dir.mkdirs() || dir.exists()) return dir; throw new IOException("Failed to create a directory at "+dir); } /** * Fully skips the specified size from the given input stream * @since 1.349 */ public static InputStream skip(InputStream in, long size) throws IOException { while (size>0) size -= in.skip(size); return in; } }
vivek/hudson
core/src/main/java/hudson/util/IOUtils.java
Java
mit
1,790
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About stripecoin</source> <translation>Info su stripecoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;stripecoin&lt;/b&gt; version</source> <translation>Versione di &lt;b&gt;stripecoin&lt;/b&gt;</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> Questo è un software sperimentale. Distribuito sotto la licenza software MIT/X11, vedi il file COPYING incluso oppure su http://www.opensource.org/licenses/mit-license.php. Questo prodotto include software sviluppato dal progetto OpenSSL per l&apos;uso del Toolkit OpenSSL (http://www.openssl.org/), software crittografico scritto da Eric Young (eay@cryptsoft.com) e software UPnP scritto da Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The stripecoin developers</source> <translation>Sviluppatori di stripecoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Rubrica</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Fai doppio click per modificare o cancellare l&apos;etichetta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Crea un nuovo indirizzo</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copia l&apos;indirizzo attualmente selezionato nella clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Nuovo indirizzo</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your stripecoin 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>Questi sono i tuoi indirizzi stripecoin per ricevere pagamenti. Potrai darne uno diverso ad ognuno per tenere così traccia di chi ti sta pagando.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copia l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostra il codice &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a stripecoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma il &amp;messaggio</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Cancella l&apos;indirizzo attualmente selezionato dalla lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Esporta...</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified stripecoin address</source> <translation>Verifica un messaggio per accertarsi che sia firmato con un indirizzo stripecoin specifico</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Cancella</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your stripecoin 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 &amp;Label</source> <translation>Copia &amp;l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Modifica</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Invia &amp;stripecoin</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Esporta gli indirizzi della rubrica</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nessuna etichetta)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Finestra passphrase</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Inserisci la passphrase</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nuova passphrase</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Ripeti la passphrase</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Inserisci la passphrase per il portamonete.&lt;br/&gt;Per piacere usare unapassphrase di &lt;b&gt;10 o più caratteri casuali&lt;/b&gt;, o &lt;b&gt;otto o più parole&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Cifra il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Sblocca il portamonete</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Quest&apos;operazione necessita della passphrase per decifrare il portamonete,</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decifra il portamonete</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Cambia la passphrase</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Inserisci la vecchia e la nuova passphrase per il portamonete.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Conferma la cifratura del portamonete</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Attenzione: se si cifra il portamonete e si perde la frase d&apos;ordine, &lt;b&gt;SI PERDERANNO TUTTI I PROPRI stripecoin&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Si è sicuri di voler cifrare il portamonete?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: qualsiasi backup del portafoglio effettuato precedentemente dovrebbe essere sostituito con il file del portafoglio criptato appena generato. Per ragioni di sicurezza, i backup precedenti del file del portafoglio non criptato diventeranno inservibili non appena si inizi ad usare il nuovo portafoglio criptato.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Attenzione: tasto Blocco maiuscole attivo.</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portamonete cifrato</translation> </message> <message> <location line="-56"/> <source>stripecoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your litecoins from being stolen by malware infecting your computer.</source> <translation>stripecoin verrà ora chiuso per finire il processo di crittazione. Ricorda che criptare il tuo portamonete non può fornire una protezione totale contro furti causati da malware che dovessero infettare il tuo computer.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Cifratura del portamonete fallita</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Cifratura del portamonete fallita a causa di un errore interno. Il portamonete non è stato cifrato.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Le passphrase inserite non corrispondono.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Sblocco del portamonete fallito</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>La passphrase inserita per la decifrazione del portamonete è errata.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decifrazione del portamonete fallita</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Passphrase del portamonete modificata con successo.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Firma il &amp;messaggio...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sto sincronizzando con la rete...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Sintesi</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostra lo stato generale del portamonete</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transazioni</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Cerca nelle transazioni</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Modifica la lista degli indirizzi salvati e delle etichette</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostra la lista di indirizzi su cui ricevere pagamenti</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Esci</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Chiudi applicazione</translation> </message> <message> <location line="+4"/> <source>Show information about stripecoin</source> <translation>Mostra informazioni su stripecoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Informazioni su &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostra informazioni su Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opzioni...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Cifra il portamonete...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup Portamonete...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Cambia la passphrase...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importa blocchi dal disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Re-indicizzazione blocchi su disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a stripecoin address</source> <translation>Invia monete ad un indirizzo stripecoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for stripecoin</source> <translation>Modifica configurazione opzioni per stripecoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Backup portamonete in un&apos;altra locazione</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Cambia la passphrase per la cifratura del portamonete</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Finestra &amp;Debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Apri la console di degugging e diagnostica</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verifica messaggio...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>stripecoin</source> <translation>stripecoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Spedisci</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Ricevi</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>&amp;Indirizzi</translation> </message> <message> <location line="+22"/> <source>&amp;About stripecoin</source> <translation>&amp;Info su stripecoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Mostra/Nascondi</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostra o nascondi la Finestra principale</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Crittografa le chiavi private che appartengono al tuo portafoglio</translation> </message> <message> <location line="+7"/> <source>Sign messages with your stripecoin addresses to prove you own them</source> <translation>Firma i messaggi con il tuo indirizzo stripecoin per dimostrare di possederli</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified stripecoin addresses</source> <translation>Verifica i messaggi per accertarsi che siano stati firmati con gli indirizzi stripecoin specificati</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;File</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Impostazioni</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Aiuto</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra degli strumenti &quot;Tabs&quot;</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="+47"/> <source>stripecoin client</source> <translation>stripecoin client</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to stripecoin network</source> <translation><numerusform>%n connessione attiva alla rete stripecoin</numerusform><numerusform>%n connessioni attive alla rete stripecoin</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>Processati %1 di %2 (circa) blocchi della cronologia transazioni.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processati %1 blocchi della cronologia transazioni.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n ora</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n giorno</numerusform><numerusform>%n giorni</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n settimana</numerusform><numerusform>%n settimane</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>L&apos;ultimo blocco ricevuto è stato generato %1 fa.</translation> </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>Errore</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informazione</translation> </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>Questa transazione è superiore al limite di dimensione. È comunque possibile inviarla con una commissione di %1, che va ai nodi che processano la tua transazione e contribuisce a sostenere la rete. Vuoi pagare la commissione?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Aggiornato</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>In aggiornamento...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Conferma compenso transazione</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transazione inviata</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transazione ricevuta</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantità: %2 Tipo: %3 Indirizzo: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Gestione URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid stripecoin address or malformed URI parameters.</source> <translation>Impossibile interpretare l&apos;URI! Ciò può essere causato da un indirizzo stripecoin invalido o da parametri URI non corretti.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;sbloccato&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Il portamonete è &lt;b&gt;cifrato&lt;/b&gt; e attualmente &lt;b&gt;bloccato&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. stripecoin can no longer continue safely and will quit.</source> <translation>Riscontrato un errore irreversibile. stripecoin non può più continuare in sicurezza e verrà terminato.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Avviso di rete</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Modifica l&apos;indirizzo</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>L&apos;etichetta associata a questo indirizzo nella rubrica</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Indirizzo</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>L&apos;indirizzo associato a questa voce della rubrica. Si può modificare solo negli indirizzi di spedizione.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Nuovo indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Nuovo indirizzo d&apos;invio</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Modifica indirizzo di ricezione</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Modifica indirizzo d&apos;invio</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; è già in rubrica.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid stripecoin address.</source> <translation>L&apos;indirizzo inserito &quot;%1&quot; non è un indirizzo stripecoin valido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossibile sbloccare il portamonete.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Generazione della nuova chiave non riuscita.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>stripecoin-Qt</source> <translation>stripecoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versione</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opzioni</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Imposta lingua, ad esempio &quot;it_IT&quot; (predefinita: lingua di sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Parti in icona </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostra finestra di presentazione all&apos;avvio (default: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opzioni</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principale</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.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Paga la &amp;commissione</translation> </message> <message> <location line="+31"/> <source>Automatically start stripecoin after logging in to the system.</source> <translation>Avvia automaticamente stripecoin all&apos;accensione del computer</translation> </message> <message> <location line="+3"/> <source>&amp;Start stripecoin on system login</source> <translation>&amp;Fai partire stripecoin all&apos;avvio del sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Ripristina tutte le opzioni del client alle predefinite.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Ripristina Opzioni</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>Rete</translation> </message> <message> <location line="+6"/> <source>Automatically open the stripecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Apri automaticamente la porta del client stripecoin sul router. Questo funziona solo se il router supporta UPnP ed è abilitato.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mappa le porte tramite l&apos;&amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the stripecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Connettiti alla rete Bitcon attraverso un proxy SOCKS (ad esempio quando ci si collega via Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Collegati tramite SOCKS proxy:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP del proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Indirizzo IP del proxy (ad esempio 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta del proxy (es. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Version:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versione SOCKS del proxy (es. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Finestra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Mostra solo un&apos;icona nel tray quando si minimizza la finestra</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizza sul tray invece che sulla barra delle applicazioni</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Riduci ad icona, invece di uscire dall&apos;applicazione quando la finestra viene chiusa. Quando questa opzione è attivata, l&apos;applicazione verrà chiusa solo dopo aver selezionato Esci nel menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizza alla chiusura</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Lingua Interfaccia Utente:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting stripecoin.</source> <translation>La lingua dell&apos;interfaccia utente può essere impostata qui. L&apos;impostazione avrà effetto dopo il riavvio di stripecoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unità di misura degli importi in:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Scegli l&apos;unità di suddivisione di default per l&apos;interfaccia e per l&apos;invio di monete</translation> </message> <message> <location line="+9"/> <source>Whether to show stripecoin addresses in the transaction list or not.</source> <translation>Se mostrare l&apos;indirizzo stripecoin nella transazione o meno.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Mostra gli indirizzi nella lista delle transazioni</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancella</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Applica</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>default</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Conferma ripristino opzioni</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Alcune modifiche necessitano del riavvio del programma per essere salvate.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Vuoi procedere?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting stripecoin.</source> <translation>L&apos;impostazione avrà effetto dopo il riavvio di stripecoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>L&apos;indirizzo proxy che hai fornito è invalido.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the stripecoin network after a connection is established, but this process has not completed yet.</source> <translation>Le informazioni visualizzate sono datate. Il tuo partafogli verrà sincronizzato automaticamente con il network stripecoin dopo che la connessione è stabilita, ma questo processo non può essere completato ora.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Non confermato:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portamonete</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Immaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Importo scavato che non è ancora maturato</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transazioni recenti&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Saldo attuale</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>Totale delle transazioni in corso di conferma, che non sono ancora incluse nel saldo attuale</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fuori sincrono</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start stripecoin: 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>Codice QR di dialogo</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Richiedi pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Importo:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etichetta:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Messaggio:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salva come...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Errore nella codifica URI nel codice QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>L&apos;importo specificato non è valido, prego verificare.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>L&apos;URI risulta troppo lungo, prova a ridurre il testo nell&apos;etichetta / messaggio.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salva codice QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Immagini PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome del client</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="+339"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versione client</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informazione</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Versione OpenSSL in uso</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo di avvio</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rete</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numero connessioni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Nel testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Block chain</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numero attuale di blocchi</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Numero totale stimato di blocchi</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ora dell blocco piu recente</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Apri</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>opzioni riga di comando</translation> </message> <message> <location line="+7"/> <source>Show the stripecoin-Qt help message to get a list with possible stripecoin command-line options.</source> <translation>Mostra il messaggio di aiuto di stripecoin-QT per avere la lista di tutte le opzioni della riga di comando di stripecoin.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Mostra</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Console</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data di creazione</translation> </message> <message> <location line="-104"/> <source>stripecoin - Debug window</source> <translation>stripecoin - Finestra debug</translation> </message> <message> <location line="+25"/> <source>stripecoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>File log del Debug</translation> </message> <message> <location line="+7"/> <source>Open the stripecoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Apri il file di log del debug di stripecoin dalla cartella attuale. Può richiedere alcuni secondi per file di log grandi.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Svuota console</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the stripecoin RPC console.</source> <translation>Benvenuto nella console RPC di stripecoin</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Usa le frecce direzionali per navigare la cronologia, and &lt;b&gt;Ctrl-L&lt;/b&gt; per cancellarla.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrivi &lt;b&gt;help&lt;/b&gt; per un riassunto dei comandi disponibili</translation> </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>Spedisci stripecoin</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Spedisci a diversi beneficiari in una volta sola</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Aggiungi beneficiario</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Rimuovi tutti i campi della transazione</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</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>Conferma la spedizione</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Spedisci</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Conferma la spedizione di stripecoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Si è sicuri di voler spedire %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> e </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>L&apos;indirizzo del beneficiario non è valido, per cortesia controlla.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>L&apos;importo da pagare dev&apos;essere maggiore di 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>L&apos;importo è superiore al saldo attuale</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Il totale è superiore al saldo attuale includendo la commissione %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Trovato un indirizzo doppio, si può spedire solo una volta a ciascun indirizzo in una singola operazione.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Errore: Creazione transazione fallita!</translation> </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>Errore: la transazione è stata rifiutata. Ciò accade se alcuni stripecoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i stripecoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Modulo</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>&amp;Importo:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Paga &amp;a:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>L&apos;indirizzo del beneficiario a cui inviare il pagamento (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </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>Inserisci un&apos;etichetta per questo indirizzo, per aggiungerlo nella rubrica</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;Etichetta</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</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>Incollare l&apos;indirizzo dagli appunti</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>Rimuovere questo beneficiario</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a stripecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Firme - Firma / Verifica un messaggio</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Firma il messaggio</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>Puoi firmare messeggi con i tuoi indirizzi per dimostrare che sono tuoi. Fai attenzione a non firmare niente di vago, visto che gli attacchi di phishing potrebbero cercare di spingerti a mettere la tua firma su di loro. Firma solo dichiarazioni completamente dettagliate con cui sei d&apos;accordo.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Scegli l&apos;indirizzo dalla rubrica</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>Incollare l&apos;indirizzo dagli appunti</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>Inserisci qui il messaggio che vuoi firmare</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Firma</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copia la firma corrente nella clipboard</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this stripecoin address</source> <translation>Firma un messaggio per dimostrare di possedere questo indirizzo</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Firma &amp;messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Reimposta tutti i campi della firma</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Cancella &amp;tutto</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verifica Messaggio</translation> </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>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified stripecoin address</source> <translation>Verifica il messaggio per assicurarsi che sia stato firmato con l&apos;indirizzo stripecoin specificato</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>&amp;Verifica Messaggio</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Reimposta tutti i campi della verifica messaggio</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a stripecoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Inserisci un indirizzo stripecoin (ad esempio Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clicca &quot;Firma il messaggio&quot; per ottenere la firma</translation> </message> <message> <location line="+3"/> <source>Enter stripecoin signature</source> <translation>Inserisci firma stripecoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>L&apos;indirizzo inserito non è valido.</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>Per favore controlla l&apos;indirizzo e prova ancora</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>L&apos;indirizzo stripecoin inserito non è associato a nessuna chiave.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Sblocco del portafoglio annullato.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>La chiave privata per l&apos;indirizzo inserito non è disponibile.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Firma messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Messaggio firmato.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Non è stato possibile decodificare la firma.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Per favore controlla la firma e prova ancora.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>La firma non corrisponde al sunto del messaggio.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verifica messaggio fallita.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Messaggio verificato.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The stripecoin developers</source> <translation>Sviluppatori di stripecoin</translation> </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>Aperto fino a %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/offline</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/non confermato</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 conferme</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stato</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, trasmesso attraverso %n nodo</numerusform><numerusform>, trasmesso attraverso %n nodi</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sorgente</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generato</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Da</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>A</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>proprio indirizzo</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetta</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura in %n ulteriore blocco</numerusform><numerusform>matura in altri %n blocchi</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>non accettate</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Tranzakciós díj</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Importo netto</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Messaggio</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Commento</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID della transazione</translation> </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 &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Bisogna attendere 120 blocchi prima di spendere I stripecoin generati. Quando è stato generato questo blocco, è stato trasmesso alla rete per aggiungerlo alla catena di blocchi. Se non riesce a entrare nella catena, verrà modificato in &quot;non accettato&quot; e non sarà spendibile. Questo può accadere a volte, se un altro nodo genera un blocco entro pochi secondi del tuo.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informazione di debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transazione</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Input</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>vero</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, non è stato ancora trasmesso con successo</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>sconosciuto</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Dettagli sulla transazione</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Questo pannello mostra una descrizione dettagliata della transazione</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Importo</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aperto per %n altro blocco</numerusform><numerusform>Aperto per altri %n blocchi</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aperto fino a %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 conferme)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Non confermati (%1 su %2 conferme)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confermato (%1 conferme)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Il saldo generato sarà disponibile quando maturerà in %n altro blocco</numerusform><numerusform>Il saldo generato sarà disponibile quando maturerà in altri %n blocchi</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>Questo blocco non è stato ricevuto da altri nodi e probabilmente non sarà accettato!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generati, ma non accettati</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Ricevuto da</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento a te stesso</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(N / a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Stato della transazione. Passare con il mouse su questo campo per vedere il numero di conferme.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e ora in cui la transazione è stata ricevuta.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo di transazione.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Indirizzo di destinazione della transazione.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Importo rimosso o aggiunto al saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Tutti</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Oggi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Questa settimana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Questo mese</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Il mese scorso</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Quest&apos;anno</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervallo...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Ricevuto tramite</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Spedito a</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>A te</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Ottenuto dal mining</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altro</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Inserisci un indirizzo o un&apos;etichetta da cercare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Importo minimo</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copia l&apos;indirizzo</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copia l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copia l&apos;importo</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Modifica l&apos;etichetta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostra i dettagli della transazione</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Esporta i dati della transazione</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Testo CSV (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confermato</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetta</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Indirizzo</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Importo</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Errore nell&apos;esportazione</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossibile scrivere sul file %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Intervallo:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>a</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Spedisci stripecoin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Esporta i dati nella tabella corrente su un file</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>Backup fallito</translation> </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>Backup eseguito con successo</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Il portafoglio è stato correttamente salvato nella nuova cartella.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>stripecoin version</source> <translation>Versione di stripecoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilizzo:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or stripecoind</source> <translation>Manda il comando a -server o stripecoind </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Lista comandi </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Aiuto su un comando </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opzioni: </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: stripecoin.conf)</source> <translation>Specifica il file di configurazione (di default: stripecoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: stripecoind.pid)</source> <translation>Specifica il file pid (default: stripecoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica la cartella dati </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Imposta la dimensione cache del database in megabyte (default: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 33615 or testnet: 19333)</source> <translation>Ascolta le connessioni JSON-RPC su &lt;porta&gt; (default: 33615 o testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Mantieni al massimo &lt;n&gt; connessioni ai peer (default: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Connessione ad un nodo per ricevere l&apos;indirizzo del peer, e disconnessione</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Specifica il tuo indirizzo pubblico</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Soglia di disconnessione dei peer di cattiva qualità (default: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numero di secondi di sospensione che i peer di cattiva qualità devono trascorrere prima di riconnettersi (default: 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>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 33616 or testnet: 19332)</source> <translation>Attendi le connessioni JSON-RPC su &lt;porta&gt; (default: 33616 or testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Accetta da linea di comando e da comandi JSON-RPC </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Esegui in background come demone e accetta i comandi </translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizza la rete di prova </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accetta connessioni dall&apos;esterno (default: 1 se no -proxy o -connect)</translation> </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=litecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;stripecoin Alert&quot; 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>Errore riscontrato durante l&apos;impostazione della porta RPC %u per l&apos;ascolto su IPv6, tornando su IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Collega all&apos;indirizzo indicato e resta sempre in ascolto su questo. Usa la notazione [host]:porta per l&apos;IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. stripecoin is probably already running.</source> <translation>Non è possibile ottenere i dati sulla cartella %s. Probabilmente stripecoin è già in esecuzione.</translation> </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>Errore: la transazione è stata rifiutata. Ciò accade se alcuni stripecoin nel portamonete sono stati già spesi, ad esempio se è stata usata una copia del file wallet.dat e i stripecoin sono stati spesi dalla copia ma non segnati come spesi qui.</translation> </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>Errore: questa transazione necessita di una commissione di almeno %s a causa del suo ammontare, della sua complessità, o dell&apos;uso di fondi recentemente ricevuti!</translation> </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>Esegui comando quando una transazione del portafoglio cambia (%s in cmd è sostituito da TxID)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Imposta dimensione massima delle transazioni ad alta priorità/bassa-tassa in bytes (predefinito: 27000)</translation> </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>Questa versione è una compilazione pre-rilascio - usala a tuo rischio - non utilizzarla per la generazione o per applicazioni di commercio</translation> </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>Attenzione: -paytxfee è molto alta. Questa è la commissione che si paga quando si invia una transazione.</translation> </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>Attenzione: le transazioni mostrate potrebbero essere sbagliate! Potresti aver bisogno di aggiornare, o altri nodi ne hanno bisogno.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong stripecoin will not work properly.</source> <translation>Attenzione: si prega di controllare che la data del computer e l&apos;ora siano corrette. Se il vostro orologio è sbagliato stripecoin non funziona correttamente.</translation> </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>Attenzione: errore di lettura di wallet.dat! Tutte le chiave lette correttamente, ma i dati delle transazioni o le voci in rubrica potrebbero mancare o non essere corretti.</translation> </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>Attenzione: wallet.dat corrotto, dati salvati! Il wallet.dat originale salvato come wallet.{timestamp}.bak in %s; se il tuo bilancio o le transazioni non sono corrette dovresti ripristinare da un backup.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tenta di recuperare le chiavi private da un wallet.dat corrotto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opzioni creazione blocco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Connetti solo al nodo specificato</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Rilevato database blocchi corrotto</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Scopri proprio indirizzo IP (default: 1 se in ascolto e no -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Vuoi ricostruire ora il database dei blocchi?</translation> </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>Errore caricamento database blocchi</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Errore caricamento database blocchi</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Errore: la spazio libero sul disco è poco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Errore: portafoglio bloccato, impossibile creare la transazione!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Errore: errore di sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Impossibile mettersi in ascolto su una porta. Usa -listen=0 se vuoi usare questa opzione.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Lettura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Lettura blocco fallita</translation> </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>Scrittura informazioni blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Scrittura blocco fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Scrittura informazioni file fallita</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Scrittura nel database dei stripecoin fallita</translation> </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>Trova peer utilizzando la ricerca DNS (predefinito: 1 finché utilizzato -connect)</translation> </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>Quanti blocchi da controllare all&apos;avvio (predefinito: 288, 0 = tutti)</translation> </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>Verifica blocchi...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verifica portafoglio...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importa blocchi da un file blk000??.dat esterno</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informazione</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Indirizzo -tor non valido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</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, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Buffer di ricezione massimo per connessione, &lt;n&gt;*1000 byte (default: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Buffer di invio massimo per connessione, &lt;n&gt;*1000 byte (default: 1000)</translation> </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 &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Connetti solo a nodi nella rete &lt;net&gt; (IPv4, IPv6 o Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produci informazioni extra utili al debug. Implies all other -debug* options</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Genera informazioni extra utili al debug della rete</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Anteponi all&apos;output di debug una marca temporale</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the stripecoin Wiki for SSL setup instructions)</source> <translation>Opzioni SSL: (vedi il wiki di stripecoin per le istruzioni di configurazione SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selezionare la versione del proxy socks da usare (4-5, default: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Invia le informazioni di trace/debug alla console invece che al file debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Invia le informazioni di trace/debug al debugger</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Imposta dimensione massima del blocco in bytes (predefinito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Imposta dimensione minima del blocco in bytes (predefinito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Riduci il file debug.log all&apos;avvio del client (predefinito: 1 se non impostato -debug)</translation> </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>Specifica il timeout di connessione in millisecondi (default: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Errore di sistema:</translation> </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>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Usa un proxy per raggiungere servizi nascosti di tor (predefinito: uguale a -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome utente per connessioni JSON-RPC </translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Attenzione</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Attenzione: questa versione è obsoleta, aggiornamento necessario!</translation> </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>wallet.dat corrotto, salvataggio fallito</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Password per connessioni JSON-RPC </translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Consenti connessioni JSON-RPC dall&apos;indirizzo IP specificato </translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Inviare comandi al nodo in esecuzione su &lt;ip&gt; (default: 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>Esegui il comando quando il miglior block cambia(%s nel cmd è sostituito dall&apos;hash del blocco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Aggiorna il wallet all&apos;ultimo formato</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Impostare la quantità di chiavi di riserva a &lt;n&gt; (default: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ripeti analisi della catena dei blocchi per cercare le transazioni mancanti dal portamonete </translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Utilizzare OpenSSL (https) per le connessioni JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>File certificato del server (default: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chiave privata del server (default: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifrari accettabili (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Questo messaggio di aiuto </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Impossibile collegarsi alla %s su questo computer (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Connessione tramite socks proxy</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Consenti ricerche DNS per aggiungere nodi e collegare </translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Caricamento indirizzi...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Errore caricamento wallet.dat: Wallet corrotto</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of stripecoin</source> <translation>Errore caricamento wallet.dat: il wallet richiede una versione nuova di stripecoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart stripecoin to complete</source> <translation>Il portamonete deve essere riscritto: riavviare stripecoin per completare</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Errore caricamento wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Indirizzo -proxy non valido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rete sconosciuta specificata in -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versione -socks proxy sconosciuta richiesta: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Impossibile risolvere -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Impossibile risolvere indirizzo -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Importo non valido per -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Importo non valido</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fondi insufficienti</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Caricamento dell&apos;indice del blocco...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. stripecoin is probably already running.</source> <translation>Impossibile collegarsi alla %s su questo computer. Probabilmente stripecoin è già in esecuzione.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Commissione per KB da aggiungere alle transazioni in uscita</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Caricamento portamonete...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Non è possibile retrocedere il wallet</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Non è possibile scrivere l&apos;indirizzo di default</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Ripetere la scansione...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Caricamento completato</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Per usare la opzione %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Errore</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Devi settare rpcpassword=&lt;password&gt; nel file di configurazione: %s Se il file non esiste, crealo con i permessi di amministratore</translation> </message> </context> </TS>
stripecoin/stripecoin
src/qt/locale/bitcoin_it.ts
TypeScript
mit
116,607
#include <iostream> #include <stddef.h> #include <fitsio.h> #include <fitsio2.h> #include <longnam.h> #include "leastsq.h" #include <cmath> /* */ using namespace std; // error handling void printerror( int status) { /*****************************************************/ /* Print out cfitsio error messages and exit program */ /*****************************************************/ if (status) { fits_report_error(stderr, status); /* print error report */ exit( status ); /* terminate the program, returning error status */ } return; } int main( int argc, char** argv ) { if( argc!=3 && argc!=4 ) { std::cerr <<"Usage: " << argv[0] << " <inputfile> <outputfile> (verboseflag)"<< std::endl; std::cerr <<"Input image must be image with background pixels set to -1, objects > 0."<<std::endl; ::exit(1); } int v =0; if(argc==4) v =1; char* filename = argv[1]; char* outfilename = argv[2]; /* Most of the code to load the fits file, I have brazenly stolen from the cfitsio manual examples*/ if(v) cout<<"Start reading FITS file"<<endl; fitsfile *fptr; /* FITS file pointer, defined in fitsio.h */ int status = 0; /* CFITSIO status value MUST be initialized to zero! */ int bitpix; // not important int naxis;// number of axes. Better be 2. int ii;// iterator long naxes[2] = {1,1};// number of pixels in axis{x,y} long fpixel[2] = {1,1};// effectively an iterator int NaxisX=0; int NaxisY=0; int Npixels=0; int max = 0; //minimum val int min = 99999; double average=0; double total=0; int open_file_flag=0,img_param_flag=0; // Open FITS file: open_file_flag = fits_open_file(&fptr, filename, READONLY, &status); if(open_file_flag) { printf("Error: Cannot open file\n"); return 0;} if(v) cout<<"FileOpen"<<endl; // Get Parameters: NaxisX & NaxisY from header img_param_flag = fits_get_img_param(fptr, 2, &bitpix, &naxis, naxes, &status); if (img_param_flag ) {printf("Error: Cannot find image dimensions\n");return 0; } NaxisX = naxes[0]; NaxisY = naxes[1]; Npixels = NaxisX * NaxisY; if(v) cout<<"Nx = "<< NaxisX<<"; Ny = "<< NaxisY<<endl; if (naxis > 2 || naxis == 0) { printf("Error: only 1D or 2D images are supported\n"); return 0; } // Define Masks double **imagearray = new double*[NaxisX]; // the input image double **maskarray = new double*[NaxisX]; // intermediate mask. for(int iter = 0; iter < NaxisX ; iter++){ imagearray[iter] = new double [NaxisY]; maskarray [iter] = new double [NaxisY]; } /* get memory for 1 row */ double *pixels = new double[NaxisX]; if(v) cout<<"Starting Reading File"<<endl; /* loop over all the rows in the image, top to bottom */ for (fpixel[1] = naxes[1]; fpixel[1] >= 1; fpixel[1]--) { /* read row of pixels */ if (fits_read_pix(fptr, TDOUBLE, fpixel, naxes[0], NULL, pixels, NULL, &status) ) { break;} /* jump out of loop on error */ for (ii = 0; ii < naxes[0]; ii++) { imagearray[ii][fpixel[1]-1] = pixels[ii]; // Fill array } } free(pixels); /* Close the file*/ fits_close_file(fptr, &status); if(v) cout<<"Closed infile"<<endl; if (status) fits_report_error(stderr, status); /* print any error message */ //mask arrays are for(int i=0; i<NaxisX; i++) { for(int j=0; j<NaxisY; j++) { maskarray[i][j]=0; } } for(int jcol = 0; jcol<NaxisX; jcol++) { for(int jrow = 0; jrow<NaxisY; jrow++) { float val = imagearray[jcol][jrow]; if(val < 0.5) continue; // Nothin doin else { for(int localx = jcol-1; localx <= jcol+1; localx++) { for(int localy = jrow-1; localy <= jrow+1; localy++) { // Make sure we're still on the image! if(!(localx<0 || localx>=NaxisX || localy<0 || localy>=NaxisY)) { maskarray[localx][localy] = 1; } } } } } } /******************************************************/ /* Create a FITS primary array containing a 2-D image */ /* ... Again, stolen from the cfitsio doc */ /******************************************************/ fitsfile *fptrout; /* pointer to the FITS file, defined in fitsio.h */ int statusout; long fpixelout, nelements; unsigned short *array[NaxisY]; /* initialize FITS image parameters */ bitpix = -32; /* 16-bit unsigned short pixel values */ /* allocate memory for the whole image */ array[0] = (unsigned short *)malloc( naxes[0] * naxes[1] * sizeof( unsigned short ) ); /* initialize pointers to the start of each row of the image */ for( ii=1; ii<naxes[1]; ii++ ) { array[ii] = array[ii-1] + naxes[0]; } remove(outfilename); /* Delete old file if it already exists */ statusout = 0; /* initialize statusout before calling fitsio routines */ if (fits_create_file(&fptrout, outfilename, &statusout)) /* create new FITS file */ printerror( statusout ); /* call printerror if error occurs */ if ( fits_create_img(fptrout, bitpix, naxis, naxes, &statusout) ) printerror( statusout ); /* set the values in the image with the mask values */ for (int jj = 0; jj < naxes[1]; jj++) { for (ii = 0; ii < naxes[0]; ii++) { array[jj][ii] = maskarray[ii][jj]; } } fpixelout = 1; /* first pixel to write */ nelements = naxes[0] * naxes[1]; /* number of pixels to write */ if ( fits_write_img(fptrout, TUSHORT, fpixelout, nelements, array[0], &statusout) ) printerror( statusout ); free( array[0] ); /* free previously allocated memory */ if ( fits_close_file(fptrout, &statusout) ) /* close the file */ printerror( statusout ); if(v) cout<<"Done."<<endl; return 0; }
deapplegate/wtgpipeline
sfdir/expand_cosmics_mask.cc
C++
mit
6,037
package com.lanceolata.leetcode; public class Question_0082_Remove_Duplicates_from_Sorted_List_II { // Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode node = new ListNode(0); node.next = head; ListNode pre = node; while (pre.next != null) { ListNode cur = pre.next; while (cur.next != null && cur.val == cur.next.val) { cur = cur.next; } if (pre.next != cur) { pre.next = cur.next; } else { pre = pre.next; } } return node.next; } }
Lanceolata/code-problems
java/src/main/java/com/lanceolata/leetcode/Question_0082_Remove_Duplicates_from_Sorted_List_II.java
Java
mit
901
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { Directive, EmbeddedViewRef, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[sqxTemplateWrapper]', }) export class TemplateWrapperDirective implements OnDestroy, OnInit, OnChanges { @Input() public item: any; @Input() public index = 0; @Input() public context: any; @Input('sqxTemplateWrapper') public templateRef!: TemplateRef<any>; public view?: EmbeddedViewRef<any>; public constructor( private readonly viewContainer: ViewContainerRef, ) { } public ngOnDestroy() { if (this.view) { this.view.destroy(); } } public ngOnInit() { const { index, context } = this; const data = { $implicit: this.item, index, context, }; this.view = this.viewContainer.createEmbeddedView(this.templateRef, data); } public ngOnChanges(changes: SimpleChanges) { if (this.view) { if (changes.item) { this.view.context.$implicit = this.item; } if (changes.index) { this.view.context.index = this.index; } if (changes.context) { this.view.context.context = this.context; } } } }
Squidex/squidex
frontend/src/app/framework/angular/template-wrapper.directive.ts
TypeScript
mit
1,495
using System.Collections.Generic; using System.Threading.Tasks; using Majorsilence.MediaService.Dto; namespace Majorsilence.MediaService.RepoInterfaces { public interface IMediaFileInfoRepo { Task<IEnumerable<MediaFileInfo>> SearchAsync(long id); } }
majorsilence/MediaService
Majorsilence.MediaService.RepoInterfaces/IMediaFileInfoRepo.cs
C#
mit
284
namespace CoreFtp.Tests.Integration.FtpClientTests.Files { using System; using System.Linq; using System.Threading.Tasks; using Enum; using FluentAssertions; using Helpers; using Microsoft.Extensions.Logging; using Xunit; using Xunit.Abstractions; public class When_deleting_a_file : TestBase { public When_deleting_a_file( ITestOutputHelper outputHelper ) : base( outputHelper ) {} [ Theory ] [ InlineData( FtpEncryption.None ) ] [ InlineData( FtpEncryption.Explicit ) ] [ InlineData( FtpEncryption.Implicit ) ] public async Task Should_delete_file( FtpEncryption encryption ) { using ( var sut = new FtpClient( new FtpClientConfiguration { Host = Program.FtpConfiguration.Host, Username = Program.FtpConfiguration.Username, Password = Program.FtpConfiguration.Password, Port = encryption == FtpEncryption.Implicit ? 990 : Program.FtpConfiguration.Port, EncryptionType = encryption, IgnoreCertificateErrors = true } ) ) { sut.Logger = Logger; string randomFileName = $"{Guid.NewGuid()}.jpg"; await sut.LoginAsync(); var fileinfo = ResourceHelpers.GetResourceFileInfo( "penguin.jpg" ); Logger.LogDebug( "Writing the file" ); using ( var writeStream = await sut.OpenFileWriteStreamAsync( randomFileName ) ) { var fileReadStream = fileinfo.OpenRead(); await fileReadStream.CopyToAsync( writeStream ); } Logger.LogDebug( "Listing the directory" ); ( await sut.ListFilesAsync() ).Any( x => x.Name == randomFileName ).Should().BeTrue(); Logger.LogDebug( "Deleting the file" ); await sut.DeleteFileAsync( randomFileName ); Logger.LogDebug( "Listing the firector" ); ( await sut.ListFilesAsync() ).Any( x => x.Name == randomFileName ).Should().BeFalse(); } } } }
sparkeh9/CoreFTP
tests/CoreFtp.Tests.Integration/FtpClientTests/Files/When_deleting_a_file.cs
C#
mit
2,233
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace DDZProj { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } } }
flysnoopy1984/DDZ_Live
DDZProj/Program.cs
C#
mit
477
<?php namespace Vicus\Controller; /** * Description of ErrorContorller * * @author Michael Koert <mkoert at bluebikeproductions.com> */ use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\FlattenException; class ErrorController { public function indexAction(FlattenException $exception) { // $msg = 'Something went wrong! ('.$exception->getMessage().')'; // // return new Response($msg, $exception->getStatusCode()); $msg = 'Something went wrong!'; return new Response($msg, $exception->getStatusCode()); } public function exceptionAction(FlattenException $exception) { // $msg = 'Something went wrong! ('.$exception->getMessage().')'; // // return new Response($msg, $exception->getStatusCode()); $msg = 'Something went wrong!'; return new Response($msg, $exception->getStatusCode()); } }
opensourcerefinery/vicus
src/Controller/ErrorController.php
PHP
mit
915
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using BackEnd; namespace Assignment5 { //types aliasing using S = BackEnd.Student<long>; using P = BackEnd.Paper<long>; using E = BackEnd.Enrollment<long>; public partial class MainForm : Form { /// <summary> /// fields /// </summary> private BackEnd.University _Uni; private DetailForm _Detail; /// <summary> /// Ctor /// </summary> public MainForm() { this.InitializeComponent(); _Uni = new BackEnd.University(); _Detail = new DetailForm(); this.SetupColumnsFittingPapers(_GridPapers); this.SetupColumnsFittingStudents(_GridStudents); this.SetAlternatingRowStyles(Color.White, Color.Azure); } /// <summary> /// event handler for right click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RightClickOnGrid(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { _ContextMenuStrip.Show(MousePosition); (_GridPapers.Focused ? _GridStudents : _GridPapers).ClearSelection(); } } /// <summary> /// import students event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _StudentsToolStripMenuItemClick(object sender, EventArgs e) { if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportStudents(_OpenFileDialog.FileName); this.UpdateGrids(); MessageBox.Show(count + " students loaded."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for papers item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _PapersToolStripMenuItemClick(object sender, EventArgs e) { if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportPapers(_OpenFileDialog.FileName); this.UpdateGrids(); MessageBox.Show(count + " papers loaded."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for enroll item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _EnrollmentsToolStripMenuItemClick(object sender, EventArgs e) { if (_Uni.Papers.Count == 0 || _Uni.Students.Count == 0) { MessageBox.Show("Please import students and papers first."); return; } if (_OpenFileDialog.ShowDialog() == DialogResult.OK) { try { var count = _Uni.ImportEnrollments(_OpenFileDialog.FileName); MessageBox.Show(count + " pieces of enrollments info loaed."); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for export item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void exportToolStripMenuItemClick(object sender, EventArgs e) { var fdb = new FolderBrowserDialog(); if (fdb.ShowDialog() == DialogResult.OK) { try { MessageBox.Show(_Uni.ExportAllData(fdb.SelectedPath) ? "Done" : "Failed"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } /// <summary> /// event handler for detail item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _DetailToolStripMenuItemClick(object sender, EventArgs e) { if (_GridPapers.Focused) { if (_GridPapers.CurrentRow == null || _GridPapers.CurrentRow.Cells["Code"].Value == null) { MessageBox.Show("No valid cell specified"); return; } long code; if (Int64.TryParse(_GridPapers.CurrentRow.Cells["Code"].Value.ToString(), out code)) this.PopulateEnrolledStudents(_Detail._Grid, code); _Detail.Text = "Students enrolled for Paper " + code; _Detail.ShowDialog(); } if(_GridStudents.Focused) { if (_GridStudents.CurrentRow == null || _GridStudents.CurrentRow.Cells["Id"].Value == null) { MessageBox.Show("No valid cell specified"); return; } long id; if (Int64.TryParse(_GridStudents.CurrentRow.Cells["Id"].Value.ToString(), out id)) this.PopulateEnrolledPapers(_Detail._Grid, id); _Detail.Text = "Student " + id + " have enrolled in "; _Detail.ShowDialog(); } } /// <summary> /// event handler for OnRowValidating /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CheckAndSaveOnRowValidating(object sender, DataGridViewCellCancelEventArgs e) { var grid = sender as DataGridView; if (e.RowIndex == grid.RowCount - 1) return; var cells = grid.Rows[e.RowIndex].Cells; //check if any cell is empty if (cells.Cast<DataGridViewCell>().Any(c => c.Value == null)) { e.Cancel = true; MessageBox.Show("Empty cell"); return; } //check paper code or student id long codeOrId = 0; if (!Int64.TryParse(cells[0].Value.ToString(), out codeOrId)) { e.Cancel = true; MessageBox.Show("Invalid input for number"); grid.ClearSelection(); cells[0].Selected = true; return; } if(grid == _GridPapers) { long code = codeOrId; string name = cells["Name"].Value.ToString(); string coordinator = cells["Coordinator"].Value.ToString(); _Uni.Add(new P(code, name, coordinator)); } if(grid == _GridStudents) { DateTime birth; if (!DateTime.TryParse(cells["Birth"].Value.ToString(), out birth)) { e.Cancel = true; MessageBox.Show("Invalid Date"); grid.ClearSelection(); cells["Birth"].Selected = true; return; } long id = codeOrId; string name = cells["Name"].Value.ToString(); string address = cells["Address"].Value.ToString(); _Uni.Add(new S(id, name, birth, address)); } } /// <summary> /// event handler for enrol item /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _EnrollToolStripMenuItemClick(object sender, EventArgs e) { var grid = _GridPapers.Focused ? _GridPapers : _GridStudents; if (grid.CurrentRow == null || grid.CurrentRow.Cells[0].Value == null) { MessageBox.Show("Incompleted row"); return; } var cells = grid.CurrentRow.Cells; long codeOrId = 0; if (!Int64.TryParse(cells[0].Value.ToString(), out codeOrId)) { MessageBox.Show("Bad number"); return; } if(grid == _GridPapers) { long code = codeOrId; _Detail.Text = "Students to choose"; if (0 == this.PopulateAvailableStudents(_Detail._Grid, code)) { MessageBox.Show("No availabe students"); return; } if(_Detail.ShowDialog(this) == DialogResult.Cancel) { long id = Convert.ToInt64(_Detail._Grid.CurrentRow.Cells["Id"].Value.ToString()); bool result = _Uni.Enrol(code, id); MessageBox.Show(result ? "Enrolled" : "Failed"); } } if(grid == _GridStudents) { long id = codeOrId; _Detail.Text = "Papers to choose"; if (0 == this.PopulateAvailablePapers(_Detail._Grid, id)) { MessageBox.Show("No availabe papers"); return; } if (_Detail.ShowDialog(this) == DialogResult.Cancel) { long code = Convert.ToInt64(_Detail._Grid.CurrentRow.Cells["Code"].Value.ToString()); bool result = _Uni.Enrol(code, id); MessageBox.Show(result ? "Enrolled" : "Failed"); } } } } }
Mooophy/158212
Assignment5/Assignment5/MainForm.cs
C#
mit
10,271
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace LinqToTwitter { public partial class TwitterContext { /// <summary> /// Adds a user subscription to specified webhook /// </summary> /// <param name="webhookID">ID of webhook user is subscribing to.</param> /// <returns>Account Activity data.</returns> /// <exception cref="TwitterQueryException"> /// Throws TwitterQueryException when an AddAccountActivitySubscriptionAsync fails. /// </exception> public async Task<AccountActivity> AddAccountActivitySubscriptionAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}/subscriptions.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Post.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Subscriptions); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Adds a new webhook to account /// </summary> /// <param name="url">Url of webhook.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> AddAccountActivityWebhookAsync(string url, CancellationToken cancelToken = default(CancellationToken)) { if (string.IsNullOrWhiteSpace(url)) throw new ArgumentException($"{nameof(url)} must be set.", nameof(url)); var newUrl = BaseUrl + $"account_activity/webhooks.json"; RawResult = await TwitterExecutor.PostFormUrlEncodedToTwitterAsync<AccountActivity>( HttpMethod.Post.ToString(), newUrl, new Dictionary<string, string> { { "url", url } }, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.Url = url; return accAct; } /// <summary> /// Sends a CRC check to a webhook for testing /// </summary> /// <param name="webhookID">ID of webhook to send CRC to.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> SendAccountActivityCrcAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Put.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Deletes a user subscription to specified webhook /// </summary> /// <param name="webhookID">ID of webhook user is subscribing to.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> DeleteAccountActivitySubscriptionAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}/subscriptions.json"; var accActValue = new AccountActivityValue(); RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Delete.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Subscriptions); accAct.WebhookID = webhookID; return accAct; } /// <summary> /// Deletes a new webhook to account /// </summary> /// <param name="webhookID">Url of webhook.</param> /// <returns>Account Activity data.</returns> public async Task<AccountActivity> DeleteAccountActivityWebhookAsync(ulong webhookID, CancellationToken cancelToken = default(CancellationToken)) { if (webhookID == default(ulong)) throw new ArgumentException($"{nameof(webhookID)} must be set.", nameof(webhookID)); var newUrl = BaseUrl + $"account_activity/webhooks/{webhookID}.json"; var accActValue = new AccountActivity { WebhookID = webhookID }; RawResult = await TwitterExecutor.SendJsonToTwitterAsync( HttpMethod.Delete.ToString(), newUrl, new Dictionary<string, string>(), accActValue, cancelToken) .ConfigureAwait(false); var reqProc = new AccountActivityRequestProcessor<AccountActivity>(); AccountActivity accAct = reqProc.ProcessActionResult(RawResult, AccountActivityType.Webhooks); accAct.WebhookID = webhookID; return accAct; } } }
JoeMayo/LinqToTwitter
src/LinqToTwitter5/LinqToTwitter.Shared/AccountActivity/TwitterContextAccountActivityCommands.cs
C#
mit
6,813
<?php namespace Acme\BookBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class AuthorControllerTest extends WebTestCase { /* public function testCompleteScenario() { // Create a new client to browse the application $client = static::createClient(); // Create a new entry in the database $crawler = $client->request('GET', '/author/'); $this->assertTrue(200 === $client->getResponse()->getStatusCode()); $crawler = $client->click($crawler->selectLink('Create a new entry')->link()); // Fill in the form and submit it $form = $crawler->selectButton('Create')->form(array( 'acme_bookbundle_authortype[field_name]' => 'Test', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check data in the show view $this->assertTrue($crawler->filter('td:contains("Test")')->count() > 0); // Edit the entity $crawler = $client->click($crawler->selectLink('Edit')->link()); $form = $crawler->selectButton('Edit')->form(array( 'acme_bookbundle_authortype[field_name]' => 'Foo', // ... other fields to fill )); $client->submit($form); $crawler = $client->followRedirect(); // Check the element contains an attribute with value equals "Foo" $this->assertTrue($crawler->filter('[value="Foo"]')->count() > 0); // Delete the entity $client->submit($crawler->selectButton('Delete')->form()); $crawler = $client->followRedirect(); // Check the entity has been delete on the list $this->assertNotRegExp('/Foo/', $client->getResponse()->getContent()); } */ }
okovalov/alexbookstore
src/Acme/BookBundle/Tests/Controller/AuthorControllerTest.php
PHP
mit
1,800
from matplotlib import pyplot as plt import seaborn as sns import pandas as pd from ..ml.linear_algebra import distmat def scatter_2d(orig_df: pd.DataFrame, colx, coly, label_col, xmin=None, xmax=None, ymin=None, ymax=None): """ Return scatter plot of 2 columns in a DataFrame, taking labels as colours. """ plt.scatter(orig_df[colx], orig_df[coly], c=orig_df[label_col].values, cmap='viridis') plt.colorbar() plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) plt.show() def visualise_dist(fframe=None, metric='euclidean'): """ Plot a distance matrix from a DataFrame containing only feature columns. The plot is a heatmap, and the distance metric is specified with `metric` """ plt.figure(figsize=(14, 10)) # ax = plt.gca() sns.heatmap(distmat(fframe, metric=metric)) plt.show()
Seiji-Armstrong/seipy
seipy/plots_/base.py
Python
mit
875
package ita8 // Constants var ( ClipboardPath = "clipboard" OpenPath = "open" )
yushi/ita8
ita8.go
GO
mit
88
module PettanrPublicDomainV01Licenses VERSION = "0.1.11" end
yasushiito/pettanr_pd_v01_licenses
lib/pettanr_public_domain_v01_licenses/version.rb
Ruby
mit
63
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace ContosoUniversity.WebApi.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
ChauThan/WebApi101
src/ContosoUniversity.WebApi/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
C#
mit
6,488
module ActiveRecord # = Active Record Autosave Association # # AutosaveAssociation is a module that takes care of automatically saving # associated records when their parent is saved. In addition to saving, it # also destroys any associated records that were marked for destruction. # (See #mark_for_destruction and #marked_for_destruction?). # # Saving of the parent, its associations, and the destruction of marked # associations, all happen inside a transaction. This should never leave the # database in an inconsistent state. # # If validations for any of the associations fail, their error messages will # be applied to the parent. # # Note that it also means that associations marked for destruction won't # be destroyed directly. They will however still be marked for destruction. # # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>. # When the <tt>:autosave</tt> option is not present then new association records are # saved but the updated association records are not saved. # # == Validation # # Child records are validated unless <tt>:validate</tt> is +false+. # # == Callbacks # # Association with autosave option defines several callbacks on your # model (before_save, after_create, after_update). Please note that # callbacks are executed in the order they were defined in # model. You should avoid modifying the association content, before # autosave callbacks are executed. Placing your callbacks after # associations is usually a good practice. # # === One-to-one Example # # class Post < ActiveRecord::Base # has_one :author, autosave: true # end # # Saving changes to the parent and its associated model can now be performed # automatically _and_ atomically: # # post = Post.find(1) # post.title # => "The current global position of migrating ducks" # post.author.name # => "alloy" # # post.title = "On the migration of ducks" # post.author.name = "Eloy Duran" # # post.save # post.reload # post.title # => "On the migration of ducks" # post.author.name # => "Eloy Duran" # # Destroying an associated model, as part of the parent's save action, is as # simple as marking it for destruction: # # post.author.mark_for_destruction # post.author.marked_for_destruction? # => true # # Note that the model is _not_ yet removed from the database: # # id = post.author.id # Author.find_by(id: id).nil? # => false # # post.save # post.reload.author # => nil # # Now it _is_ removed from the database: # # Author.find_by(id: id).nil? # => true # # === One-to-many Example # # When <tt>:autosave</tt> is not declared new children are saved when their parent is saved: # # class Post < ActiveRecord::Base # has_many :comments # :autosave option is not declared # end # # post = Post.new(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # post.comments.build(body: 'hello world') # post.save # => saves both post and comment # # post = Post.create(title: 'ruby rocks') # post.comments.create(body: 'hello world') # post.save # => saves both post and comment # # When <tt>:autosave</tt> is true all children are saved, no matter whether they # are new records or not: # # class Post < ActiveRecord::Base # has_many :comments, autosave: true # end # # post = Post.create(title: 'ruby rocks') # post.comments.create(body: 'hello world') # post.comments[0].body = 'hi everyone' # post.comments.build(body: "good morning.") # post.title += "!" # post.save # => saves both post and comments. # # Destroying one of the associated models as part of the parent's save action # is as simple as marking it for destruction: # # post.comments # => [#<Comment id: 1, ...>, #<Comment id: 2, ...]> # post.comments[1].mark_for_destruction # post.comments[1].marked_for_destruction? # => true # post.comments.length # => 2 # # Note that the model is _not_ yet removed from the database: # # id = post.comments.last.id # Comment.find_by(id: id).nil? # => false # # post.save # post.reload.comments.length # => 1 # # Now it _is_ removed from the database: # # Comment.find_by(id: id).nil? # => true module AutosaveAssociation extend ActiveSupport::Concern module AssociationBuilderExtension #:nodoc: def self.build(model, reflection) model.send(:add_autosave_association_callbacks, reflection) end def self.valid_options [ :autosave ] end end included do Associations::Builder::Association.extensions << AssociationBuilderExtension mattr_accessor :index_nested_attribute_errors, instance_writer: false self.index_nested_attribute_errors = false end module ClassMethods # :nodoc: private def define_non_cyclic_method(name, &block) return if method_defined?(name) define_method(name) do |*args| result = true; @_already_called ||= {} # Loop prevention for validation of associations unless @_already_called[name] begin @_already_called[name] = true result = instance_eval(&block) ensure @_already_called[name] = false end end result end end # Adds validation and save callbacks for the association as specified by # the +reflection+. # # For performance reasons, we don't check whether to validate at runtime. # However the validation and callback methods are lazy and those methods # get created when they are invoked for the very first time. However, # this can change, for instance, when using nested attributes, which is # called _after_ the association has been defined. Since we don't want # the callbacks to get defined multiple times, there are guards that # check if the save or validation methods have already been defined # before actually defining them. def add_autosave_association_callbacks(reflection) save_method = :"autosave_associated_records_for_#{reflection.name}" if reflection.collection? before_save :before_save_collection_association define_non_cyclic_method(save_method) { save_collection_association(reflection) } # Doesn't use after_save as that would save associations added in after_create/after_update twice after_create save_method after_update save_method elsif reflection.has_one? define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method) # Configures two callbacks instead of a single after_save so that # the model may rely on their execution order relative to its # own callbacks. # # For example, given that after_creates run before after_saves, if # we configured instead an after_save there would be no way to fire # a custom after_create callback after the child association gets # created. after_create save_method after_update save_method else define_non_cyclic_method(save_method) { throw(:abort) if save_belongs_to_association(reflection) == false } before_save save_method end define_autosave_validation_callbacks(reflection) end def define_autosave_validation_callbacks(reflection) validation_method = :"validate_associated_records_for_#{reflection.name}" if reflection.validate? && !method_defined?(validation_method) if reflection.collection? method = :validate_collection_association else method = :validate_single_association end define_non_cyclic_method(validation_method) do send(method, reflection) # TODO: remove the following line as soon as the return value of # callbacks is ignored, that is, returning `false` does not # display a deprecation warning or halts the callback chain. true end validate validation_method after_validation :_ensure_no_duplicate_errors end end end # Reloads the attributes of the object as usual and clears <tt>marked_for_destruction</tt> flag. def reload(options = nil) @marked_for_destruction = false @destroyed_by_association = nil super end # Marks this record to be destroyed as part of the parent's save transaction. # This does _not_ actually destroy the record instantly, rather child record will be destroyed # when <tt>parent.save</tt> is called. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def mark_for_destruction @marked_for_destruction = true end # Returns whether or not this record will be destroyed as part of the parent's save transaction. # # Only useful if the <tt>:autosave</tt> option on the parent is enabled for this associated model. def marked_for_destruction? @marked_for_destruction end # Records the association that is being destroyed and destroying this # record in the process. def destroyed_by_association=(reflection) @destroyed_by_association = reflection end # Returns the association for the parent being destroyed. # # Used to avoid updating the counter cache unnecessarily. def destroyed_by_association @destroyed_by_association end # Returns whether or not this record has been changed in any way (including whether # any of its nested autosave associations are likewise changed) def changed_for_autosave? new_record? || has_changes_to_save? || marked_for_destruction? || nested_records_changed_for_autosave? end private # Returns the record for an association collection that should be validated # or saved. If +autosave+ is +false+ only new records will be returned, # unless the parent is/was a new record itself. def associated_records_to_validate_or_save(association, new_record, autosave) if new_record || autosave association && association.target else association.target.find_all(&:new_record?) end end # go through nested autosave associations that are loaded in memory (without loading # any new ones), and return true if is changed for autosave def nested_records_changed_for_autosave? @_nested_records_changed_for_autosave_already_called ||= false return false if @_nested_records_changed_for_autosave_already_called begin @_nested_records_changed_for_autosave_already_called = true self.class._reflections.values.any? do |reflection| if reflection.options[:autosave] association = association_instance_get(reflection.name) association && Array.wrap(association.target).any?(&:changed_for_autosave?) end end ensure @_nested_records_changed_for_autosave_already_called = false end end # Validate the association if <tt>:validate</tt> or <tt>:autosave</tt> is # turned on for the association. def validate_single_association(reflection) association = association_instance_get(reflection.name) record = association && association.reader association_valid?(reflection, record) if record end # Validate the associated records if <tt>:validate</tt> or # <tt>:autosave</tt> is turned on for the association specified by # +reflection+. def validate_collection_association(reflection) if association = association_instance_get(reflection.name) if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) records.each_with_index { |record, index| association_valid?(reflection, record, index) } end end end # Returns whether or not the association is valid and applies any errors to # the parent, <tt>self</tt>, if it wasn't. Skips any <tt>:autosave</tt> # enabled records if they're marked_for_destruction? or destroyed. def association_valid?(reflection, record, index = nil) return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?) validation_context = self.validation_context unless [:create, :update].include?(self.validation_context) unless valid = record.valid?(validation_context) if reflection.options[:autosave] indexed_attribute = !index.nil? && (reflection.options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors) record.errors.each do |attribute, message| attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) errors[attribute] << message errors[attribute].uniq! end record.errors.details.each_key do |attribute| reflection_attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute).to_sym record.errors.details[attribute].each do |error| errors.details[reflection_attribute] << error errors.details[reflection_attribute].uniq! end end else errors.add(reflection.name) end end valid end def normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) if indexed_attribute "#{reflection.name}[#{index}].#{attribute}" else "#{reflection.name}.#{attribute}" end end # Is used as a before_save callback to check while saving a collection # association whether or not the parent was a new record before saving. def before_save_collection_association @new_record_before_save = new_record? true end # Saves any new associated records, or all loaded autosave associations if # <tt>:autosave</tt> is enabled on the association. # # In addition, it destroys all children that were marked for destruction # with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_collection_association(reflection) if association = association_instance_get(reflection.name) autosave = reflection.options[:autosave] # reconstruct the scope now that we know the owner's id association.reset_scope if association.respond_to?(:reset_scope) if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) if autosave records_to_destroy = records.select(&:marked_for_destruction?) records_to_destroy.each { |record| association.destroy(record) } records -= records_to_destroy end records.each do |record| next if record.destroyed? saved = true if autosave != false && (@new_record_before_save || record.new_record?) if autosave saved = association.insert_record(record, false) else association.insert_record(record) unless reflection.nested? end elsif autosave saved = record.save(validate: false) end raise ActiveRecord::Rollback unless saved end end end end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled # on the association. # # In addition, it will destroy the association if it was marked for # destruction with #mark_for_destruction. # # This all happens inside a transaction, _if_ the Transactions module is included into # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. def save_has_one_association(reflection) association = association_instance_get(reflection.name) record = association && association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? record.destroy elsif autosave != false key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key) unless reflection.through_reflection record[reflection.foreign_key] = key end saved = record.save(validate: !autosave) raise ActiveRecord::Rollback if !saved && autosave saved end end end end # If the record is new or it has changed, returns true. def record_changed?(reflection, record, key) record.new_record? || (record.has_attribute?(reflection.foreign_key) && record[reflection.foreign_key] != key) || record.will_save_change_to_attribute?(reflection.foreign_key) end # Saves the associated record if it's new or <tt>:autosave</tt> is enabled. # # In addition, it will destroy the association if it was marked for destruction. def save_belongs_to_association(reflection) association = association_instance_get(reflection.name) return unless association && association.loaded? && !association.stale_target? record = association.load_target if record && !record.destroyed? autosave = reflection.options[:autosave] if autosave && record.marked_for_destruction? self[reflection.foreign_key] = nil record.destroy elsif autosave != false saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) if association.updated? association_id = record.send(reflection.options[:primary_key] || :id) self[reflection.foreign_key] = association_id association.loaded! end saved if autosave end end end def _ensure_no_duplicate_errors errors.messages.each_key do |attribute| errors[attribute].uniq! end end end end
tijwelch/rails
activerecord/lib/active_record/autosave_association.rb
Ruby
mit
19,240
/** * clientCacheProvider **/ angular.module('providers') .provider('clientCacheProvider', function ClientCacheProvider($state, clientCacheService) { console.log(clientCacheService) console.log(clientCacheService.logout()); var forceLogin = false; this.forceLogin = function(clientCacheService) { forceLogin = clientCacheService.logout(); $state.go('/login'); } });
evoila/cf-spring-web-management-console
frontend/app/js/providers/general/clientCacheProvider.js
JavaScript
mit
407
<!-- Main Header --> <header class="main-header"> <!-- Logo --> <a href="/admin" class="logo"> <!-- mini logo for sidebar mini 50x50 pixels --> <span class="logo-mini"><b>C</b>MS</span> <!-- logo for regular state and mobile devices --> <span class="logo-lg"><b>The</b>CMS</span> </a> <!-- Header Navbar --> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle navigation</span> </a> <!-- Navbar Right Menu --> <div class="navbar-custom-menu"> <ul class="nav navbar-nav"> <!-- Messages: style can be found in dropdown.less--> <? if($tcadmin_config['has_feedbacks']):?> <li class="dropdown messages-menu"> <!-- Menu toggle button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-envelope-o"></i> <span class="label label-success"><?= $unread_feedback_count; ?></span> </a> <ul class="dropdown-menu"> <li class="header">У вас <?= $unread_feedback_count; ?> не прочитанных отзыва</li> <? if(count($unread_feedbacks) > 0): ?> <li> <ul class="menu"> <? foreach($unread_feedbacks as $model): ?> <li><!-- start message --> <a href="/admin/feedback/view/<?= $model->id; ?>"> <h4> <?= $model->user_name;?> <small><i class="fa fa-clock-o"></i> <?= Date::forge($model->created_at)->format("%d/%m/%Y %H:%M"); ?></small> </h4> <!-- The message --> <p><?= Fuel\Core\Str::truncate($model->text, 50, '...'); ?></p> </a> </li><!-- end message --> <? endforeach; ?> </ul><!-- /.menu --> </li> <li class="footer"><a href="/admin/feedback/index">Смотреть все</a></li> <? endif; ?> </ul> </li><!-- /.messages-menu --> <? endif; ?> <!-- Notifications Menu --> <!--<li class="dropdown notifications-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <span class="label label-warning">10</span> </a> <ul class="dropdown-menu"> <li class="header">You have 10 notifications</li> <li> <ul class="menu"> <li> <a href="#"> <i class="fa fa-users text-aqua"></i> 5 new members joined today </a> </li> </ul> </li> <li class="footer"><a href="#">View all</a></li> </ul> </li> <li class="dropdown tasks-menu"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-flag-o"></i> <span class="label label-danger">9</span> </a> <ul class="dropdown-menu"> <li class="header">You have 9 tasks</li> <li> <ul class="menu"> <li> <a href="#"> <h3> Design some buttons <small class="pull-right">20%</small> </h3> <div class="progress xs"> <div class="progress-bar progress-bar-aqua" style="width: 20%" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"> <span class="sr-only">20% Complete</span> </div> </div> </a> </li> </ul> </li> <li class="footer"> <a href="#">View all tasks</a> </li> </ul> </li>--> <!-- User Account Menu --> <li class="dropdown user user-menu"> <!-- Menu Toggle Button --> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <!-- The user image in the navbar--> <img src="/assets/img/aninimus.jpg" class="user-image" alt="User Image"> <!-- hidden-xs hides the username on small devices so only the image appears. --> <span class="hidden-xs"><?= Auth::get('username'); ?></span> </a> <ul class="dropdown-menu"> <!-- The user image in the menu --> <li class="user-header"> <img src="/assets/img/aninimus.jpg" class="img-circle" alt="User Image"> <p> <?= Auth::get('username'); ?> - Administrator <small>Member since <?= Date::forge(Auth::get('created_at'))->format("%d/%m/%Y"); ?></small> </p> </li> <!-- Menu Body --> <!--<li class="user-body"> <div class="col-xs-4 text-center"> <a href="#">Followers</a> </div> <div class="col-xs-4 text-center"> <a href="#">Sales</a> </div> <div class="col-xs-4 text-center"> <a href="#">Friends</a> </div> </li>--> <!-- Menu Footer--> <li class="user-footer"> <div class="pull-left"> <!--<a href="#" class="btn btn-default btn-flat">Profile</a>--> </div> <div class="pull-right"> <a href="/admin/auth/logout" class="btn btn-default btn-flat">Sign out</a> </div> </li> </ul> </li> <!-- Control Sidebar Toggle Button --> <!-- <li> <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a> </li>--> </ul> </div> </nav> </header>
SergeyOlifir/The-CMS-2.0
fuel/app/views/admin/main/header.php
PHP
mit
6,499
/* tslint:disable */ /* eslint-disable */ // @ts-nocheck import { ReaderFragment } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type ArtworkFilterArtworkGrid_filtered_artworks = { readonly id: string; readonly pageInfo: { readonly hasNextPage: boolean; readonly endCursor: string | null; }; readonly pageCursors: { readonly " $fragmentRefs": FragmentRefs<"Pagination_pageCursors">; }; readonly edges: ReadonlyArray<{ readonly node: { readonly id: string; } | null; } | null> | null; readonly " $fragmentRefs": FragmentRefs<"ArtworkGrid_artworks">; readonly " $refType": "ArtworkFilterArtworkGrid_filtered_artworks"; }; export type ArtworkFilterArtworkGrid_filtered_artworks$data = ArtworkFilterArtworkGrid_filtered_artworks; export type ArtworkFilterArtworkGrid_filtered_artworks$key = { readonly " $data"?: ArtworkFilterArtworkGrid_filtered_artworks$data; readonly " $fragmentRefs": FragmentRefs<"ArtworkFilterArtworkGrid_filtered_artworks">; }; const node: ReaderFragment = (function(){ var v0 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "ArtworkFilterArtworkGrid_filtered_artworks", "selections": [ (v0/*: any*/), { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "PageCursors", "kind": "LinkedField", "name": "pageCursors", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "Pagination_pageCursors" } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "FilterArtworksEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v0/*: any*/) ], "storageKey": null } ], "storageKey": null }, { "args": null, "kind": "FragmentSpread", "name": "ArtworkGrid_artworks" } ], "type": "FilterArtworksConnection", "abstractKey": null }; })(); (node as any).hash = '04cd49aefae4484840f678821ea905e1'; export default node;
artsy/force
src/v2/__generated__/ArtworkFilterArtworkGrid_filtered_artworks.graphql.ts
TypeScript
mit
3,068
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::CDN::Mgmt::V2020_09_01 module Models # # Result of the request to list endpoints. It contains a list of endpoint # objects and a URL link to get the next set of results. # class AFDEndpointListResult include MsRestAzure include MsRest::JSONable # @return [Array<AFDEndpoint>] List of AzureFrontDoor endpoints within a # profile attr_accessor :value # @return [String] URL to get the next set of endpoint objects if there # is any. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<AFDEndpoint>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [AFDEndpointListResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for AFDEndpointListResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'AFDEndpointListResult', type: { name: 'Composite', class_name: 'AFDEndpointListResult', model_properties: { value: { client_side_validation: true, required: false, read_only: true, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'AFDEndpointElementType', type: { name: 'Composite', class_name: 'AFDEndpoint' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_cdn/lib/2020-09-01/generated/azure_mgmt_cdn/models/afdendpoint_list_result.rb
Ruby
mit
2,932
/* eslint react/no-multi-comp:0, no-console:0 */ import { createForm } from 'rc-form'; import React, { PropTypes } from 'react'; import ReactDOM from 'react-dom'; import { regionStyle, errorStyle } from './styles'; let Form = React.createClass({ propTypes: { form: PropTypes.object, }, setEmail() { this.props.form.setFieldsValue({ email: 'yiminghe@gmail.com', }); }, render() { const { getFieldProps, getFieldError } = this.props.form; const errors = getFieldError('email'); return (<div style={ regionStyle }> <div>email:</div> <div> <input {...getFieldProps('email', { rules: [{ type: 'email', }], })} /> </div> <div style={errorStyle}> {(errors) ? errors.join(',') : null} </div> <button onClick={this.setEmail}>set</button> </div>); }, }); Form = createForm()(Form); class App extends React.Component { render() { return (<div> <h2>setFieldsValue</h2> <Form /> </div>); } } ReactDOM.render(<App />, document.getElementById('__react-content'));
setState/form
examples/setFieldsValue.js
JavaScript
mit
1,127
const commander = require('../'); // These are tests of the Help class, not of the Command help. // There is some overlap with the higher level Command tests (which predate Help). describe('sortOptions', () => { test('when unsorted then options in order added', () => { const program = new commander.Command(); program .option('--zzz', 'desc') .option('--aaa', 'desc') .option('--bbb', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(option => option.name()); expect(visibleOptionNames).toEqual(['zzz', 'aaa', 'bbb', 'help']); }); test('when sortOptions:true then options sorted alphabetically', () => { const program = new commander.Command(); program .configureHelp({ sortOptions: true }) .option('--zzz', 'desc') .option('--aaa', 'desc') .option('--bbb', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name()); expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'help', 'zzz']); }); test('when both short and long flags then sort on short flag', () => { const program = new commander.Command(); program .configureHelp({ sortOptions: true }) .option('-m,--zzz', 'desc') .option('-n,--aaa', 'desc') .option('-o,--bbb', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name()); expect(visibleOptionNames).toEqual(['help', 'zzz', 'aaa', 'bbb']); }); test('when lone short and long flags then sort on lone flag', () => { const program = new commander.Command(); program .configureHelp({ sortOptions: true }) .option('--zzz', 'desc') .option('--aaa', 'desc') .option('-b', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name()); expect(visibleOptionNames).toEqual(['aaa', 'b', 'help', 'zzz']); }); test('when mixed case flags then sort is case insensitive', () => { const program = new commander.Command(); program .configureHelp({ sortOptions: true }) .option('-B', 'desc') .option('-a', 'desc') .option('-c', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name()); expect(visibleOptionNames).toEqual(['a', 'B', 'c', 'help']); }); test('when negated option then sort negated option separately', () => { const program = new commander.Command(); program .configureHelp({ sortOptions: true }) .option('--bbb', 'desc') .option('--ccc', 'desc') .option('--no-bbb', 'desc') .option('--aaa', 'desc'); const helper = program.createHelp(); const visibleOptionNames = helper.visibleOptions(program).map(cmd => cmd.name()); expect(visibleOptionNames).toEqual(['aaa', 'bbb', 'ccc', 'help', 'no-bbb']); }); });
tj/commander.js
tests/help.sortOptions.test.js
JavaScript
mit
3,036
package de.hawhamburg.vs.wise15.superteam.client.worker; import de.hawhamburg.vs.wise15.superteam.client.PlayerServiceFacade; import de.hawhamburg.vs.wise15.superteam.client.callback.CallbackA; import de.hawhamburg.vs.wise15.superteam.client.model.Command; import javax.swing.*; import java.io.IOException; import java.util.List; import java.util.Map; /** * Created by florian on 09.01.16. */ public class CommandListener implements Runnable { private final PlayerServiceFacade facade; private final Map<String, List<CallbackA<String>>> listenerMap; public CommandListener(PlayerServiceFacade facade, Map<String, List<CallbackA<String>>> ListenerMap) { this.facade = facade; listenerMap = ListenerMap; } @Override public void run() { while (facade.isConnected()) { Command command = null; try { command = facade.getCommand(); } catch (IOException e) { e.printStackTrace(); } if (listenerMap.containsKey(command.getCommand())) { for (CallbackA<String> callback : listenerMap.get(command.getCommand())) { final Command finalCommand = command; SwingUtilities.invokeLater(() -> callback.callback(finalCommand.getContent())); } } } } }
flbaue/vs-wise15
client/src/main/java/de/hawhamburg/vs/wise15/superteam/client/worker/CommandListener.java
Java
mit
1,377
''' Created on Jan 30, 2011 @author: snail ''' import logging import logging.handlers import os import sys from os.path import join from os import getcwd from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL from pickle import dumps LogPath = "Logs" #ensure the logging path exists. try: from os import mkdir mkdir(join(getcwd(), LogPath)) del mkdir except: pass def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except: return sys.exc_info()[2].tb_frame.f_back def CreateLogger(name, level=None): l = logging.getLogger(name) l.setLevel(DEBUG) if level != None: l.setLevel(level) handler = logging.handlers.RotatingFileHandler(join( LogPath, "%s.log" % name), maxBytes=10240, backupCount=10) formatter = logging.Formatter("%(asctime)s|%(thread)d|%(levelno)s|%(module)s:%(funcName)s:%(lineno)d|%(message)s") handler.setFormatter(formatter) l.addHandler(handler) return l class LogFile: def __init__(self, output, minLevel=WARNING): self.minLevel = minLevel self._log = CreateLogger(output) self._log.findCaller = self.findCaller def findCaller(self): """ Find the stack frame of the caller so that we can note the source file name, line number and function name. """ f = currentframe() if f is not None: f = f.f_back rv = "(unknown file)", 0, "(unknown function)" i = 5 while hasattr(f, "f_code") and i > 0: i = i - 1 co = f.f_code rv = (co.co_filename, f.f_lineno, co.co_name) f = f.f_back return rv def debug(self, *vals, **kws): self.log(DEBUG, *vals, **kws) def note(self, *vals, **kws): self.log(INFO, *vals, **kws) def info(self, *vals, **kws): self.log(INFO, *vals, **kws) def warning(self, *vals, **kws): self.log(WARNING, *vals, **kws) def error(self, *vals, **kws): self.log(ERROR, *vals, **kws) def critical(self, *vals, **kws): self.log(CRITICAL, *vals, **kws) def dict(self, d, *vals): if d: lines = map(lambda (x, y): str(x) + " => " + str(y), d.items()) else: lines = ["None"] lines+=vals self.log(DEBUG, *lines) def exception(self, *vals): lines = list(vals) import sys import traceback tb = sys.exc_info() tbLines = (traceback.format_exception(*tb)) for l in tbLines: lines += l[:-1].split("\n") self.log(ERROR,*lines) global ExceptionLog ExceptionLog.log(ERROR,*lines) def log(self, level, *vals, **kws): self._log.log(level, "\t".join(map(str, vals))) ExceptionLog = LogFile("Exceptions") if __name__ == "__main__": import threading import time import random class Worker(threading.Thread): log = None def run(self): for i in range(20): time.sleep(random.random() * .1) if self.log: self.foo() self.log.debug("Exception time!") try: self.bar() except: self.log.exception("Exception while doing math!") def bar(self): i = 1 / 0 def foo(self): self.log.warning(i, "abc", "123") logger = LogFile("test") for i in range(20): w = Worker() w.log = logger w.start() logger.dict({"a":"a","foo":"bar",1:[1]})
theepicsnail/SuperBot2
Logging.py
Python
mit
3,658
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./quickInput'; import { Component } from 'vs/workbench/common/component'; import { IQuickInputService, IQuickPickItem, IPickOptions, IInputOptions, IQuickNavigateConfiguration, IQuickPick, IQuickInput, IQuickInputButton, IInputBox, IQuickPickItemButtonEvent, QuickPickInput, IQuickPickSeparator, IKeyMods } from 'vs/platform/quickinput/common/quickInput'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import * as dom from 'vs/base/browser/dom'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { contrastBorder, widgetShadow } from 'vs/platform/theme/common/colorRegistry'; import { SIDE_BAR_BACKGROUND, SIDE_BAR_FOREGROUND } from 'vs/workbench/common/theme'; import { IQuickOpenService } from 'vs/platform/quickOpen/common/quickOpen'; import { CancellationToken } from 'vs/base/common/cancellation'; import { QuickInputList } from './quickInputList'; import { QuickInputBox } from './quickInputBox'; import { KeyCode } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { localize } from 'vs/nls'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { CLOSE_ON_FOCUS_LOST_CONFIG } from 'vs/workbench/browser/quickopen'; import { CountBadge } from 'vs/base/browser/ui/countBadge/countBadge'; import { attachBadgeStyler, attachProgressBarStyler, attachButtonStyler } from 'vs/platform/theme/common/styler'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { ProgressBar } from 'vs/base/browser/ui/progressbar/progressbar'; import { debounceEvent, Emitter, Event } from 'vs/base/common/event'; import { Button } from 'vs/base/browser/ui/button/button'; import { dispose, IDisposable } from 'vs/base/common/lifecycle'; import Severity from 'vs/base/common/severity'; import { IEditorGroupsService } from 'vs/workbench/services/group/common/editorGroupsService'; import { IContextKeyService, RawContextKey, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { ICommandAndKeybindingRule, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { inQuickOpenContext } from 'vs/workbench/browser/parts/quickopen/quickopen'; import { ActionBar, ActionItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { Action } from 'vs/base/common/actions'; import { URI } from 'vs/base/common/uri'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { equals } from 'vs/base/common/arrays'; import { TimeoutTimer } from 'vs/base/common/async'; import { getIconClass } from 'vs/workbench/browser/parts/quickinput/quickInputUtils'; import { AccessibilitySupport } from 'vs/base/common/platform'; import * as browser from 'vs/base/browser/browser'; import { IEditorOptions } from 'vs/editor/common/config/editorOptions'; import { IStorageService } from 'vs/platform/storage/common/storage'; const $ = dom.$; type Writeable<T> = { -readonly [P in keyof T]: T[P] }; const backButton = { iconPath: { dark: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/dark/arrow-left.svg')), light: URI.parse(require.toUrl('vs/workbench/browser/parts/quickinput/media/light/arrow-left.svg')) }, tooltip: localize('quickInput.back', "Back"), handle: -1 // TODO }; interface QuickInputUI { container: HTMLElement; leftActionBar: ActionBar; title: HTMLElement; rightActionBar: ActionBar; checkAll: HTMLInputElement; inputBox: QuickInputBox; visibleCount: CountBadge; count: CountBadge; message: HTMLElement; progressBar: ProgressBar; list: QuickInputList; onDidAccept: Event<void>; onDidTriggerButton: Event<IQuickInputButton>; ignoreFocusOut: boolean; keyMods: Writeable<IKeyMods>; isScreenReaderOptimized(): boolean; show(controller: QuickInput): void; setVisibilities(visibilities: Visibilities): void; setComboboxAccessibility(enabled: boolean): void; setEnabled(enabled: boolean): void; setContextKey(contextKey?: string): void; hide(): void; } type Visibilities = { title?: boolean; checkAll?: boolean; inputBox?: boolean; visibleCount?: boolean; count?: boolean; message?: boolean; list?: boolean; ok?: boolean; }; class QuickInput implements IQuickInput { private _title: string; private _steps: number; private _totalSteps: number; protected visible = false; private _enabled = true; private _contextKey: string; private _busy = false; private _ignoreFocusOut = false; private _buttons: IQuickInputButton[] = []; private buttonsUpdated = false; private onDidTriggerButtonEmitter = new Emitter<IQuickInputButton>(); private onDidHideEmitter = new Emitter<void>(); protected visibleDisposables: IDisposable[] = []; protected disposables: IDisposable[] = [ this.onDidTriggerButtonEmitter, this.onDidHideEmitter, ]; private busyDelay: TimeoutTimer; constructor(protected ui: QuickInputUI) { } get title() { return this._title; } set title(title: string) { this._title = title; this.update(); } get step() { return this._steps; } set step(step: number) { this._steps = step; this.update(); } get totalSteps() { return this._totalSteps; } set totalSteps(totalSteps: number) { this._totalSteps = totalSteps; this.update(); } get enabled() { return this._enabled; } set enabled(enabled: boolean) { this._enabled = enabled; this.update(); } get contextKey() { return this._contextKey; } set contextKey(contextKey: string) { this._contextKey = contextKey; this.update(); } get busy() { return this._busy; } set busy(busy: boolean) { this._busy = busy; this.update(); } get ignoreFocusOut() { return this._ignoreFocusOut; } set ignoreFocusOut(ignoreFocusOut: boolean) { this._ignoreFocusOut = ignoreFocusOut; this.update(); } get buttons() { return this._buttons; } set buttons(buttons: IQuickInputButton[]) { this._buttons = buttons; this.buttonsUpdated = true; this.update(); } onDidTriggerButton = this.onDidTriggerButtonEmitter.event; show(): void { if (this.visible) { return; } this.visibleDisposables.push( this.ui.onDidTriggerButton(button => { if (this.buttons.indexOf(button) !== -1) { this.onDidTriggerButtonEmitter.fire(button); } }), ); this.ui.show(this); this.visible = true; this.update(); } hide(): void { if (!this.visible) { return; } this.ui.hide(); } didHide(): void { this.visible = false; this.visibleDisposables = dispose(this.visibleDisposables); this.onDidHideEmitter.fire(); } onDidHide = this.onDidHideEmitter.event; protected update() { if (!this.visible) { return; } const title = this.getTitle(); if (this.ui.title.textContent !== title) { this.ui.title.textContent = title; } if (this.busy && !this.busyDelay) { this.busyDelay = new TimeoutTimer(); this.busyDelay.setIfNotSet(() => { if (this.visible) { this.ui.progressBar.infinite(); } }, 800); } if (!this.busy && this.busyDelay) { this.ui.progressBar.stop(); this.busyDelay.cancel(); this.busyDelay = null; } if (this.buttonsUpdated) { this.buttonsUpdated = false; this.ui.leftActionBar.clear(); const leftButtons = this.buttons.filter(button => button === backButton); this.ui.leftActionBar.push(leftButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => this.onDidTriggerButtonEmitter.fire(button)); action.tooltip = button.tooltip; return action; }), { icon: true, label: false }); this.ui.rightActionBar.clear(); const rightButtons = this.buttons.filter(button => button !== backButton); this.ui.rightActionBar.push(rightButtons.map((button, index) => { const action = new Action(`id-${index}`, '', button.iconClass || getIconClass(button.iconPath), true, () => this.onDidTriggerButtonEmitter.fire(button)); action.tooltip = button.tooltip; return action; }), { icon: true, label: false }); } this.ui.ignoreFocusOut = this.ignoreFocusOut; this.ui.setEnabled(this.enabled); this.ui.setContextKey(this.contextKey); } private getTitle() { if (this.title && this.step) { return `${this.title} (${this.getSteps()})`; } if (this.title) { return this.title; } if (this.step) { return this.getSteps(); } return ''; } private getSteps() { if (this.step && this.totalSteps) { return localize('quickInput.steps', "{0}/{1}", this.step, this.totalSteps); } if (this.step) { return String(this.step); } return ''; } public dispose(): void { this.hide(); this.disposables = dispose(this.disposables); } } class QuickPick<T extends IQuickPickItem> extends QuickInput implements IQuickPick<T> { private static INPUT_BOX_ARIA_LABEL = localize('quickInputBox.ariaLabel', "Type to narrow down results."); private _value = ''; private _placeholder; private onDidChangeValueEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<string>(); private _items: (T | IQuickPickSeparator)[] = []; private itemsUpdated = false; private _canSelectMany = false; private _matchOnDescription = false; private _matchOnDetail = false; private _activeItems: T[] = []; private activeItemsUpdated = false; private activeItemsToConfirm: T[] = []; private onDidChangeActiveEmitter = new Emitter<T[]>(); private _selectedItems: T[] = []; private selectedItemsUpdated = false; private selectedItemsToConfirm: T[] = []; private onDidChangeSelectionEmitter = new Emitter<T[]>(); private onDidTriggerItemButtonEmitter = new Emitter<IQuickPickItemButtonEvent<T>>(); quickNavigate: IQuickNavigateConfiguration; constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidChangeValueEmitter, this.onDidAcceptEmitter, this.onDidChangeActiveEmitter, this.onDidChangeSelectionEmitter, this.onDidTriggerItemButtonEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } onDidChangeValue = this.onDidChangeValueEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; get items() { return this._items; } set items(items: (T | IQuickPickSeparator)[]) { this._items = items; this.itemsUpdated = true; this.update(); } get canSelectMany() { return this._canSelectMany; } set canSelectMany(canSelectMany: boolean) { this._canSelectMany = canSelectMany; this.update(); } get matchOnDescription() { return this._matchOnDescription; } set matchOnDescription(matchOnDescription: boolean) { this._matchOnDescription = matchOnDescription; this.update(); } get matchOnDetail() { return this._matchOnDetail; } set matchOnDetail(matchOnDetail: boolean) { this._matchOnDetail = matchOnDetail; this.update(); } get activeItems() { return this._activeItems; } set activeItems(activeItems: T[]) { this._activeItems = activeItems; this.activeItemsUpdated = true; this.update(); } onDidChangeActive = this.onDidChangeActiveEmitter.event; get selectedItems() { return this._selectedItems; } set selectedItems(selectedItems: T[]) { this._selectedItems = selectedItems; this.selectedItemsUpdated = true; this.update(); } get keyMods() { return this.ui.keyMods; } onDidChangeSelection = this.onDidChangeSelectionEmitter.event; onDidTriggerItemButton = this.onDidTriggerItemButtonEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.ui.list.filter(this.ui.inputBox.value); if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } this.onDidChangeValueEmitter.fire(value); }), this.ui.inputBox.onKeyDown(event => { switch (event.keyCode) { case KeyCode.DownArrow: this.ui.list.focus('Next'); if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.UpArrow: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('Previous'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageDown: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('NextPage'); } else { this.ui.list.focus('First'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; case KeyCode.PageUp: if (this.ui.list.getFocusedElements().length) { this.ui.list.focus('PreviousPage'); } else { this.ui.list.focus('Last'); } if (this.canSelectMany) { this.ui.list.domFocus(); } break; } }), this.ui.onDidAccept(() => { if (!this.canSelectMany && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); } this.onDidAcceptEmitter.fire(); }), this.ui.list.onDidChangeFocus(focusedItems => { if (this.activeItemsUpdated) { return; // Expect another event. } if (this.activeItemsToConfirm !== this._activeItems && equals(focusedItems, this._activeItems, (a, b) => a === b)) { return; } this._activeItems = focusedItems as T[]; this.onDidChangeActiveEmitter.fire(focusedItems as T[]); }), this.ui.list.onDidChangeSelection(selectedItems => { if (this.canSelectMany) { if (selectedItems.length) { this.ui.list.setSelectedElements([]); } return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(selectedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = selectedItems as T[]; this.onDidChangeSelectionEmitter.fire(selectedItems as T[]); if (selectedItems.length) { this.onDidAcceptEmitter.fire(); } }), this.ui.list.onChangedCheckedElements(checkedItems => { if (!this.canSelectMany) { return; } if (this.selectedItemsToConfirm !== this._selectedItems && equals(checkedItems, this._selectedItems, (a, b) => a === b)) { return; } this._selectedItems = checkedItems as T[]; this.onDidChangeSelectionEmitter.fire(checkedItems as T[]); }), this.ui.list.onButtonTriggered(event => this.onDidTriggerItemButtonEmitter.fire(event as IQuickPickItemButtonEvent<T>)), this.registerQuickNavigation() ); } super.show(); // TODO: Why have show() bubble up while update() trickles down? (Could move setComboboxAccessibility() here.) } private registerQuickNavigation() { return dom.addDisposableListener(this.ui.container, dom.EventType.KEY_UP, (e: KeyboardEvent) => { if (this.canSelectMany || !this.quickNavigate) { return; } const keyboardEvent: StandardKeyboardEvent = new StandardKeyboardEvent(e as KeyboardEvent); const keyCode = keyboardEvent.keyCode; // Select element when keys are pressed that signal it const quickNavKeys = this.quickNavigate.keybindings; const wasTriggerKeyPressed = keyCode === KeyCode.Enter || quickNavKeys.some(k => { const [firstPart, chordPart] = k.getParts(); if (chordPart) { return false; } if (firstPart.shiftKey && keyCode === KeyCode.Shift) { if (keyboardEvent.ctrlKey || keyboardEvent.altKey || keyboardEvent.metaKey) { return false; // this is an optimistic check for the shift key being used to navigate back in quick open } return true; } if (firstPart.altKey && keyCode === KeyCode.Alt) { return true; } if (firstPart.ctrlKey && keyCode === KeyCode.Ctrl) { return true; } if (firstPart.metaKey && keyCode === KeyCode.Meta) { return true; } return false; }); if (wasTriggerKeyPressed && this.activeItems[0]) { this._selectedItems = [this.activeItems[0]]; this.onDidChangeSelectionEmitter.fire(this.selectedItems); this.onDidAcceptEmitter.fire(); } }); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.itemsUpdated) { this.itemsUpdated = false; this.ui.list.setElements(this.items); this.ui.list.filter(this.ui.inputBox.value); this.ui.checkAll.checked = this.ui.list.getAllVisibleChecked(); this.ui.visibleCount.setCount(this.ui.list.getVisibleCount()); this.ui.count.setCount(this.ui.list.getCheckedCount()); if (!this.ui.isScreenReaderOptimized() && !this.canSelectMany) { this.ui.list.focus('First'); } } if (this.ui.container.classList.contains('show-checkboxes') !== !!this.canSelectMany) { if (this.canSelectMany) { this.ui.list.clearFocus(); } else if (!this.ui.isScreenReaderOptimized()) { this.ui.list.focus('First'); } } if (this.activeItemsUpdated) { this.activeItemsUpdated = false; this.activeItemsToConfirm = this._activeItems; this.ui.list.setFocusedElements(this.activeItems); if (this.activeItemsToConfirm === this._activeItems) { this.activeItemsToConfirm = null; } } if (this.selectedItemsUpdated) { this.selectedItemsUpdated = false; this.selectedItemsToConfirm = this._selectedItems; if (this.canSelectMany) { this.ui.list.setCheckedElements(this.selectedItems); } else { this.ui.list.setSelectedElements(this.selectedItems); } if (this.selectedItemsToConfirm === this._selectedItems) { this.selectedItemsToConfirm = null; } } this.ui.list.matchOnDescription = this.matchOnDescription; this.ui.list.matchOnDetail = this.matchOnDetail; this.ui.setComboboxAccessibility(true); this.ui.inputBox.setAttribute('aria-label', QuickPick.INPUT_BOX_ARIA_LABEL); this.ui.setVisibilities(this.canSelectMany ? { title: !!this.title || !!this.step, checkAll: true, inputBox: true, visibleCount: true, count: true, ok: true, list: true } : { title: !!this.title || !!this.step, inputBox: true, visibleCount: true, list: true }); } } class InputBox extends QuickInput implements IInputBox { private static noPromptMessage = localize('inputModeEntry', "Press 'Enter' to confirm your input or 'Escape' to cancel"); private _value = ''; private _valueSelection: Readonly<[number, number]>; private valueSelectionUpdated = true; private _placeholder: string; private _password = false; private _prompt: string; private noValidationMessage = InputBox.noPromptMessage; private _validationMessage: string; private onDidValueChangeEmitter = new Emitter<string>(); private onDidAcceptEmitter = new Emitter<string>(); constructor(ui: QuickInputUI) { super(ui); this.disposables.push( this.onDidValueChangeEmitter, this.onDidAcceptEmitter, ); } get value() { return this._value; } set value(value: string) { this._value = value || ''; this.update(); } set valueSelection(valueSelection: Readonly<[number, number]>) { this._valueSelection = valueSelection; this.valueSelectionUpdated = true; this.update(); } get placeholder() { return this._placeholder; } set placeholder(placeholder: string) { this._placeholder = placeholder; this.update(); } get password() { return this._password; } set password(password: boolean) { this._password = password; this.update(); } get prompt() { return this._prompt; } set prompt(prompt: string) { this._prompt = prompt; this.noValidationMessage = prompt ? localize('inputModeEntryDescription', "{0} (Press 'Enter' to confirm or 'Escape' to cancel)", prompt) : InputBox.noPromptMessage; this.update(); } get validationMessage() { return this._validationMessage; } set validationMessage(validationMessage: string) { this._validationMessage = validationMessage; this.update(); } onDidChangeValue = this.onDidValueChangeEmitter.event; onDidAccept = this.onDidAcceptEmitter.event; show() { if (!this.visible) { this.visibleDisposables.push( this.ui.inputBox.onDidChange(value => { if (value === this.value) { return; } this._value = value; this.onDidValueChangeEmitter.fire(value); }), this.ui.onDidAccept(() => this.onDidAcceptEmitter.fire()), ); this.valueSelectionUpdated = true; } super.show(); } protected update() { super.update(); if (!this.visible) { return; } if (this.ui.inputBox.value !== this.value) { this.ui.inputBox.value = this.value; } if (this.valueSelectionUpdated) { this.valueSelectionUpdated = false; this.ui.inputBox.select(this._valueSelection && { start: this._valueSelection[0], end: this._valueSelection[1] }); } if (this.ui.inputBox.placeholder !== (this.placeholder || '')) { this.ui.inputBox.placeholder = (this.placeholder || ''); } if (this.ui.inputBox.password !== this.password) { this.ui.inputBox.password = this.password; } if (!this.validationMessage && this.ui.message.textContent !== this.noValidationMessage) { this.ui.message.textContent = this.noValidationMessage; this.ui.inputBox.showDecoration(Severity.Ignore); } if (this.validationMessage && this.ui.message.textContent !== this.validationMessage) { this.ui.message.textContent = this.validationMessage; this.ui.inputBox.showDecoration(Severity.Error); } this.ui.setVisibilities({ title: !!this.title || !!this.step, inputBox: true, message: true }); } } export class QuickInputService extends Component implements IQuickInputService { public _serviceBrand: any; private static readonly ID = 'workbench.component.quickinput'; private static readonly MAX_WIDTH = 600; // Max total width of quick open widget private idPrefix = 'quickInput_'; // Constant since there is still only one. private layoutDimensions: dom.Dimension; private titleBar: HTMLElement; private filterContainer: HTMLElement; private visibleCountContainer: HTMLElement; private countContainer: HTMLElement; private okContainer: HTMLElement; private ok: Button; private ui: QuickInputUI; private comboboxAccessibility = false; private enabled = true; private inQuickOpenWidgets: Record<string, boolean> = {}; private inQuickOpenContext: IContextKey<boolean>; private contexts: { [id: string]: IContextKey<boolean>; } = Object.create(null); private onDidAcceptEmitter = this._register(new Emitter<void>()); private onDidTriggerButtonEmitter = this._register(new Emitter<IQuickInputButton>()); private keyMods: Writeable<IKeyMods> = { ctrlCmd: false, alt: false }; private controller: QuickInput; constructor( @IEnvironmentService private environmentService: IEnvironmentService, @IConfigurationService private configurationService: IConfigurationService, @IInstantiationService private instantiationService: IInstantiationService, @IPartService private partService: IPartService, @IQuickOpenService private quickOpenService: IQuickOpenService, @IEditorGroupsService private editorGroupService: IEditorGroupsService, @IKeybindingService private keybindingService: IKeybindingService, @IContextKeyService private contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService ) { super(QuickInputService.ID, themeService, storageService); this.inQuickOpenContext = new RawContextKey<boolean>('inQuickOpen', false).bindTo(contextKeyService); this._register(this.quickOpenService.onShow(() => this.inQuickOpen('quickOpen', true))); this._register(this.quickOpenService.onHide(() => this.inQuickOpen('quickOpen', false))); this.registerKeyModsListeners(); } private inQuickOpen(widget: 'quickInput' | 'quickOpen', open: boolean) { if (open) { this.inQuickOpenWidgets[widget] = true; } else { delete this.inQuickOpenWidgets[widget]; } if (Object.keys(this.inQuickOpenWidgets).length) { if (!this.inQuickOpenContext.get()) { this.inQuickOpenContext.set(true); } } else { if (this.inQuickOpenContext.get()) { this.inQuickOpenContext.reset(); } } } private setContextKey(id?: string) { let key: IContextKey<boolean>; if (id) { key = this.contexts[id]; if (!key) { key = new RawContextKey<boolean>(id, false) .bindTo(this.contextKeyService); this.contexts[id] = key; } } if (key && key.get()) { return; // already active context } this.resetContextKeys(); if (key) { key.set(true); } } private resetContextKeys() { for (const key in this.contexts) { if (this.contexts[key].get()) { this.contexts[key].reset(); } } } private registerKeyModsListeners() { const workbench = this.partService.getWorkbenchElement(); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = true; break; case KeyCode.Alt: this.keyMods.alt = true; break; } })); this._register(dom.addDisposableListener(workbench, dom.EventType.KEY_UP, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Ctrl: case KeyCode.Meta: this.keyMods.ctrlCmd = false; break; case KeyCode.Alt: this.keyMods.alt = false; break; } })); } private create() { if (this.ui) { return; } const workbench = this.partService.getWorkbenchElement(); const container = dom.append(workbench, $('.quick-input-widget.show-file-icons')); container.tabIndex = -1; container.style.display = 'none'; this.titleBar = dom.append(container, $('.quick-input-titlebar')); const leftActionBar = this._register(new ActionBar(this.titleBar)); leftActionBar.domNode.classList.add('quick-input-left-action-bar'); const title = dom.append(this.titleBar, $('.quick-input-title')); const rightActionBar = this._register(new ActionBar(this.titleBar)); rightActionBar.domNode.classList.add('quick-input-right-action-bar'); const headerContainer = dom.append(container, $('.quick-input-header')); const checkAll = <HTMLInputElement>dom.append(headerContainer, $('input.quick-input-check-all')); checkAll.type = 'checkbox'; this._register(dom.addStandardDisposableListener(checkAll, dom.EventType.CHANGE, e => { const checked = checkAll.checked; list.setAllVisibleChecked(checked); })); this._register(dom.addDisposableListener(checkAll, dom.EventType.CLICK, e => { if (e.x || e.y) { // Avoid 'click' triggered by 'space'... inputBox.setFocus(); } })); this.filterContainer = dom.append(headerContainer, $('.quick-input-filter')); const inputBox = this._register(new QuickInputBox(this.filterContainer)); inputBox.setAttribute('aria-describedby', `${this.idPrefix}message`); this.visibleCountContainer = dom.append(this.filterContainer, $('.quick-input-visible-count')); this.visibleCountContainer.setAttribute('aria-live', 'polite'); this.visibleCountContainer.setAttribute('aria-atomic', 'true'); const visibleCount = new CountBadge(this.visibleCountContainer, { countFormat: localize({ key: 'quickInput.visibleCount', comment: ['This tells the user how many items are shown in a list of items to select from. The items can be anything. Currently not visible, but read by screen readers.'] }, "{0} Results") }); this.countContainer = dom.append(this.filterContainer, $('.quick-input-count')); this.countContainer.setAttribute('aria-live', 'polite'); const count = new CountBadge(this.countContainer, { countFormat: localize({ key: 'quickInput.countSelected', comment: ['This tells the user how many items are selected in a list of items to select from. The items can be anything.'] }, "{0} Selected") }); this._register(attachBadgeStyler(count, this.themeService)); this.okContainer = dom.append(headerContainer, $('.quick-input-action')); this.ok = new Button(this.okContainer); attachButtonStyler(this.ok, this.themeService); this.ok.label = localize('ok', "OK"); this._register(this.ok.onDidClick(e => { this.onDidAcceptEmitter.fire(); })); const message = dom.append(container, $(`#${this.idPrefix}message.quick-input-message`)); const progressBar = new ProgressBar(container); dom.addClass(progressBar.getContainer(), 'quick-input-progress'); this._register(attachProgressBarStyler(progressBar, this.themeService)); const list = this._register(this.instantiationService.createInstance(QuickInputList, container, this.idPrefix + 'list')); this._register(list.onChangedAllVisibleChecked(checked => { checkAll.checked = checked; })); this._register(list.onChangedVisibleCount(c => { visibleCount.setCount(c); })); this._register(list.onChangedCheckedCount(c => { count.setCount(c); })); this._register(list.onLeave(() => { // Defer to avoid the input field reacting to the triggering key. setTimeout(() => { inputBox.setFocus(); if (this.controller instanceof QuickPick && this.controller.canSelectMany) { list.clearFocus(); } }, 0); })); this._register(list.onDidChangeFocus(() => { if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant()); } })); const focusTracker = dom.trackFocus(container); this._register(focusTracker); this._register(focusTracker.onDidBlur(() => { if (!this.ui.ignoreFocusOut && !this.environmentService.args['sticky-quickopen'] && this.configurationService.getValue(CLOSE_ON_FOCUS_LOST_CONFIG)) { this.hide(true); } })); this._register(dom.addDisposableListener(container, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => { const event = new StandardKeyboardEvent(e); switch (event.keyCode) { case KeyCode.Enter: dom.EventHelper.stop(e, true); this.onDidAcceptEmitter.fire(); break; case KeyCode.Escape: dom.EventHelper.stop(e, true); this.hide(); break; case KeyCode.Tab: if (!event.altKey && !event.ctrlKey && !event.metaKey) { const selectors = ['.action-label.icon']; if (container.classList.contains('show-checkboxes')) { selectors.push('input'); } else { selectors.push('input[type=text]'); } if (this.ui.list.isDisplayed()) { selectors.push('.monaco-list'); } const stops = container.querySelectorAll<HTMLElement>(selectors.join(', ')); if (event.shiftKey && event.target === stops[0]) { dom.EventHelper.stop(e, true); stops[stops.length - 1].focus(); } else if (!event.shiftKey && event.target === stops[stops.length - 1]) { dom.EventHelper.stop(e, true); stops[0].focus(); } } break; } })); this._register(this.quickOpenService.onShow(() => this.hide(true))); this.ui = { container, leftActionBar, title, rightActionBar, checkAll, inputBox, visibleCount, count, message, progressBar, list, onDidAccept: this.onDidAcceptEmitter.event, onDidTriggerButton: this.onDidTriggerButtonEmitter.event, ignoreFocusOut: false, keyMods: this.keyMods, isScreenReaderOptimized: () => this.isScreenReaderOptimized(), show: controller => this.show(controller), hide: () => this.hide(), setVisibilities: visibilities => this.setVisibilities(visibilities), setComboboxAccessibility: enabled => this.setComboboxAccessibility(enabled), setEnabled: enabled => this.setEnabled(enabled), setContextKey: contextKey => this.setContextKey(contextKey), }; this.updateStyles(); } pick<T extends IQuickPickItem, O extends IPickOptions<T>>(picks: Promise<QuickPickInput<T>[]> | QuickPickInput<T>[], options: O = <O>{}, token: CancellationToken = CancellationToken.None): Promise<O extends { canPickMany: true } ? T[] : T> { return new Promise<O extends { canPickMany: true } ? T[] : T>((doResolve, reject) => { let resolve = (result: any) => { resolve = doResolve; if (options.onKeyMods) { options.onKeyMods(input.keyMods); } doResolve(result); }; if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createQuickPick<T>(); let activeItem: T; const disposables = [ input, input.onDidAccept(() => { if (input.canSelectMany) { resolve(<any>input.selectedItems.slice()); input.hide(); } else { const result = input.activeItems[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidChangeActive(items => { const focused = items[0]; if (focused && options.onDidFocus) { options.onDidFocus(focused); } }), input.onDidChangeSelection(items => { if (!input.canSelectMany) { const result = items[0]; if (result) { resolve(<any>result); input.hide(); } } }), input.onDidTriggerItemButton(event => options.onDidTriggerItemButton && options.onDidTriggerItemButton({ ...event, removeItem: () => { const index = input.items.indexOf(event.item); if (index !== -1) { const items = input.items.slice(); items.splice(index, 1); input.items = items; } } })), input.onDidChangeValue(value => { if (activeItem && !value && (input.activeItems.length !== 1 || input.activeItems[0] !== activeItem)) { input.activeItems = [activeItem]; } }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.canSelectMany = options.canPickMany; input.placeholder = options.placeHolder; input.ignoreFocusOut = options.ignoreFocusLost; input.matchOnDescription = options.matchOnDescription; input.matchOnDetail = options.matchOnDetail; input.quickNavigate = options.quickNavigate; input.contextKey = options.contextKey; input.busy = true; Promise.all([picks, options.activeItem]) .then(([items, _activeItem]) => { activeItem = _activeItem; input.busy = false; input.items = items; if (input.canSelectMany) { input.selectedItems = items.filter(item => item.type !== 'separator' && item.picked) as T[]; } if (activeItem) { input.activeItems = [activeItem]; } }); input.show(); Promise.resolve(picks).then(null, err => { reject(err); input.hide(); }); }); } input(options: IInputOptions = {}, token: CancellationToken = CancellationToken.None): Promise<string> { return new Promise<string>((resolve, reject) => { if (token.isCancellationRequested) { resolve(undefined); return; } const input = this.createInputBox(); const validateInput = options.validateInput || (() => <Thenable<undefined>>Promise.resolve(undefined)); const onDidValueChange = debounceEvent(input.onDidChangeValue, (last, cur) => cur, 100); let validationValue = options.value || ''; let validation = Promise.resolve(validateInput(validationValue)); const disposables = [ input, onDidValueChange(value => { if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (value === validationValue) { input.validationMessage = result; } }); }), input.onDidAccept(() => { const value = input.value; if (value !== validationValue) { validation = Promise.resolve(validateInput(value)); validationValue = value; } validation.then(result => { if (!result) { resolve(value); input.hide(); } else if (value === validationValue) { input.validationMessage = result; } }); }), token.onCancellationRequested(() => { input.hide(); }), input.onDidHide(() => { dispose(disposables); resolve(undefined); }), ]; input.value = options.value; input.valueSelection = options.valueSelection; input.prompt = options.prompt; input.placeholder = options.placeHolder; input.password = options.password; input.ignoreFocusOut = options.ignoreFocusLost; input.show(); }); } backButton = backButton; createQuickPick<T extends IQuickPickItem>(): IQuickPick<T> { this.create(); return new QuickPick<T>(this.ui); } createInputBox(): IInputBox { this.create(); return new InputBox(this.ui); } private show(controller: QuickInput) { this.create(); this.quickOpenService.close(); const oldController = this.controller; this.controller = controller; if (oldController) { oldController.didHide(); } this.setEnabled(true); this.ui.leftActionBar.clear(); this.ui.title.textContent = ''; this.ui.rightActionBar.clear(); this.ui.checkAll.checked = false; // this.ui.inputBox.value = ''; Avoid triggering an event. this.ui.inputBox.placeholder = ''; this.ui.inputBox.password = false; this.ui.inputBox.showDecoration(Severity.Ignore); this.ui.visibleCount.setCount(0); this.ui.count.setCount(0); this.ui.message.textContent = ''; this.ui.progressBar.stop(); this.ui.list.setElements([]); this.ui.list.matchOnDescription = false; this.ui.list.matchOnDetail = false; this.ui.ignoreFocusOut = false; this.setComboboxAccessibility(false); this.ui.inputBox.removeAttribute('aria-label'); const keybinding = this.keybindingService.lookupKeybinding(BackAction.ID); backButton.tooltip = keybinding ? localize('quickInput.backWithKeybinding', "Back ({0})", keybinding.getLabel()) : localize('quickInput.back', "Back"); this.inQuickOpen('quickInput', true); this.resetContextKeys(); this.ui.container.style.display = ''; this.updateLayout(); this.ui.inputBox.setFocus(); } private setVisibilities(visibilities: Visibilities) { this.ui.title.style.display = visibilities.title ? '' : 'none'; this.ui.checkAll.style.display = visibilities.checkAll ? '' : 'none'; this.filterContainer.style.display = visibilities.inputBox ? '' : 'none'; this.visibleCountContainer.style.display = visibilities.visibleCount ? '' : 'none'; this.countContainer.style.display = visibilities.count ? '' : 'none'; this.okContainer.style.display = visibilities.ok ? '' : 'none'; this.ui.message.style.display = visibilities.message ? '' : 'none'; this.ui.list.display(visibilities.list); this.ui.container.classList[visibilities.checkAll ? 'add' : 'remove']('show-checkboxes'); this.updateLayout(); // TODO } private setComboboxAccessibility(enabled: boolean) { if (enabled !== this.comboboxAccessibility) { this.comboboxAccessibility = enabled; if (this.comboboxAccessibility) { this.ui.inputBox.setAttribute('role', 'combobox'); this.ui.inputBox.setAttribute('aria-haspopup', 'true'); this.ui.inputBox.setAttribute('aria-autocomplete', 'list'); this.ui.inputBox.setAttribute('aria-activedescendant', this.ui.list.getActiveDescendant()); } else { this.ui.inputBox.removeAttribute('role'); this.ui.inputBox.removeAttribute('aria-haspopup'); this.ui.inputBox.removeAttribute('aria-autocomplete'); this.ui.inputBox.removeAttribute('aria-activedescendant'); } } } private isScreenReaderOptimized() { const detected = browser.getAccessibilitySupport() === AccessibilitySupport.Enabled; const config = this.configurationService.getValue<IEditorOptions>('editor').accessibilitySupport; return config === 'on' || (config === 'auto' && detected); } private setEnabled(enabled: boolean) { if (enabled !== this.enabled) { this.enabled = enabled; for (const item of this.ui.leftActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } for (const item of this.ui.rightActionBar.items) { (item as ActionItem).getAction().enabled = enabled; } this.ui.checkAll.disabled = !enabled; // this.ui.inputBox.enabled = enabled; Avoid loosing focus. this.ok.enabled = enabled; this.ui.list.enabled = enabled; } } private hide(focusLost?: boolean) { const controller = this.controller; if (controller) { this.controller = null; this.inQuickOpen('quickInput', false); this.resetContextKeys(); this.ui.container.style.display = 'none'; if (!focusLost) { this.editorGroupService.activeGroup.focus(); } controller.didHide(); } } focus() { if (this.isDisplayed()) { this.ui.inputBox.setFocus(); } } toggle() { if (this.isDisplayed() && this.controller instanceof QuickPick && this.controller.canSelectMany) { this.ui.list.toggleCheckbox(); } } navigate(next: boolean, quickNavigate?: IQuickNavigateConfiguration) { if (this.isDisplayed() && this.ui.list.isDisplayed()) { this.ui.list.focus(next ? 'Next' : 'Previous'); if (quickNavigate && this.controller instanceof QuickPick) { this.controller.quickNavigate = quickNavigate; } } } accept() { this.onDidAcceptEmitter.fire(); return Promise.resolve(undefined); } back() { this.onDidTriggerButtonEmitter.fire(this.backButton); return Promise.resolve(undefined); } cancel() { this.hide(); return Promise.resolve(undefined); } layout(dimension: dom.Dimension): void { this.layoutDimensions = dimension; this.updateLayout(); } private updateLayout() { if (this.layoutDimensions && this.ui) { const titlebarOffset = this.partService.getTitleBarOffset(); this.ui.container.style.top = `${titlebarOffset}px`; const style = this.ui.container.style; const width = Math.min(this.layoutDimensions.width * 0.62 /* golden cut */, QuickInputService.MAX_WIDTH); style.width = width + 'px'; style.marginLeft = '-' + (width / 2) + 'px'; this.ui.inputBox.layout(); this.ui.list.layout(); } } protected updateStyles() { const theme = this.themeService.getTheme(); if (this.ui) { // TODO const titleColor = { dark: 'rgba(255, 255, 255, 0.105)', light: 'rgba(0,0,0,.06)', hc: 'black' }[theme.type]; this.titleBar.style.backgroundColor = titleColor ? titleColor.toString() : null; this.ui.inputBox.style(theme); const sideBarBackground = theme.getColor(SIDE_BAR_BACKGROUND); this.ui.container.style.backgroundColor = sideBarBackground ? sideBarBackground.toString() : null; const sideBarForeground = theme.getColor(SIDE_BAR_FOREGROUND); this.ui.container.style.color = sideBarForeground ? sideBarForeground.toString() : null; const contrastBorderColor = theme.getColor(contrastBorder); this.ui.container.style.border = contrastBorderColor ? `1px solid ${contrastBorderColor}` : null; const widgetShadowColor = theme.getColor(widgetShadow); this.ui.container.style.boxShadow = widgetShadowColor ? `0 5px 8px ${widgetShadowColor}` : null; } } private isDisplayed() { return this.ui && this.ui.container.style.display !== 'none'; } } export const QuickPickManyToggle: ICommandAndKeybindingRule = { id: 'workbench.action.quickPickManyToggle', weight: KeybindingWeight.WorkbenchContrib, when: inQuickOpenContext, primary: undefined, handler: accessor => { const quickInputService = accessor.get(IQuickInputService); quickInputService.toggle(); } }; export class BackAction extends Action { public static readonly ID = 'workbench.action.quickInputBack'; public static readonly LABEL = localize('back', "Back"); constructor(id: string, label: string, @IQuickInputService private quickInputService: IQuickInputService) { super(id, label); } public run(): Promise<any> { this.quickInputService.back(); return Promise.resolve(null); } }
DustinCampbell/vscode
src/vs/workbench/browser/parts/quickinput/quickInput.ts
TypeScript
mit
44,636
/** * @summary Race timing system * @author Guillaume Deconinck & Wojciech Grynczel */ 'use strict'; // time-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. const mongoose = require('mongoose'); const Schema = mongoose.Schema; const timeSchema = new Schema({ checkpoint_id: { type: Number, required: true }, tag: { type: Schema.Types.Mixed, required: true }, timestamp: { type: Date, required: true } }); const timeModel = mongoose.model('times', timeSchema); module.exports = timeModel;
osrts/osrts-backend
src/services/times/time-model.js
JavaScript
mit
568
<?php /* FOSUserBundle:Group:edit.html.twig */ class __TwigTemplate_ef57f06f37b4b105df31eabec2d1cd20acba6f1995ab286ffcc795254ca469ef extends Sonata\CacheBundle\Twig\TwigTemplate14 { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 try { $this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig"); } catch (Twig_Error_Loader $e) { $e->setTemplateFile($this->getTemplateName()); $e->setTemplateLine(1); throw $e; } $this->blocks = array( 'fos_user_content' => array($this, 'block_fos_user_content'), ); } protected function doGetParent(array $context) { return "FOSUserBundle::layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $this->parent->display($context, array_merge($this->blocks, $blocks)); } // line 3 public function block_fos_user_content($context, array $blocks = array()) { // line 4 $this->env->loadTemplate("FOSUserBundle:Group:edit_content.html.twig")->display($context); } public function getTemplateName() { return "FOSUserBundle:Group:edit.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 39 => 4, 36 => 3, 11 => 1,); } }
wieloming/GPI
1/ef/57/f06f37b4b105df31eabec2d1cd20acba6f1995ab286ffcc795254ca469ef.php
PHP
mit
1,473
/* global elmApp Elm */ // Brunch automatically concatenates all files in your // watched paths. Those paths can be configured at // config.paths.watched in "brunch-config.js". // // However, those files will only be executed if // explicitly imported. The only exception are files // in vendor, which are never wrapped in imports and // therefore are always executed. // Import dependencies // // If you no longer want to use a dependency, remember // to also remove its path from "config.paths.watched". import 'phoenix_html' // Import local files // // Local files can be imported directly using relative // paths "./socket" or full ones "web/static/js/socket". import socket from "./socket" let channel = socket.channel("tests:runner", {}) channel.join() .receive("ok", resp => { console.log("Joined successfully", resp) }) .receive("error", resp => { console.log("Unable to join", resp) }) channel.on('set_tests', data => { elmApp.ports.testLists.send(data.tests) }) var elmDiv = document.getElementById('elm-main') var initialState = { testLists: [] } var elmApp = Elm.embed(Elm.TestRunner, elmDiv, initialState)
chasm/trelm
web/static/js/app.js
JavaScript
mit
1,133
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateRoleUserTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('role_user', function (Blueprint $table) { // $table->integer('role_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->foreign('role_id') ->references('id') ->on('roles') ->onDelete('cascade'); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->primary('role_id', 'user_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('role_user'); } }
Khairulrabbi/htmis
database/migrations/2016_04_21_052356_create_role_user_table.php
PHP
mit
968
module Garages class ToggleStatusController < ApplicationController before_action :set_garage, only: :update after_action :verify_authorized def update authorize @garage @garage.toggle_status respond_to do |format| format.html { redirect_to garages_url } end end private def set_garage @garage = Garage.find(secure_id) end def garage_params params.permit(:id) end def secure_id garage_params[:id].to_i end end end
jonnyjava/ewoks
app/controllers/garages/toggle_status_controller.rb
Ruby
mit
534
#!/usr/bin/env python import sys, json from confusionmatrix import ConfusionMatrix as CM def main(): for line in sys.stdin: cm = json.loads(line) print CM(cm["TP"], cm["FP"], cm["FN"], cm["TN"]) if __name__ == '__main__': main()
yatmingyatming/LogisticRegressionSGDMapReduce
display_stats.py
Python
mit
264
/* * @(#)ByteBufferAs-X-Buffer.java 1.18 05/11/17 * * Copyright 2006 Sun Microsystems, Inc. All rights reserved. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ // -- This file was mechanically generated: Do not edit! -- // package java.nio; class ByteBufferAsDoubleBufferB // package-private extends DoubleBuffer { protected final ByteBuffer bb; protected final int offset; ByteBufferAsDoubleBufferB(ByteBuffer bb) { // package-private super(-1, 0, bb.remaining() >> 3, bb.remaining() >> 3); this.bb = bb; // enforce limit == capacity int cap = this.capacity(); this.limit(cap); int pos = this.position(); assert (pos <= cap); offset = pos; } ByteBufferAsDoubleBufferB(ByteBuffer bb, int mark, int pos, int lim, int cap, int off) { super(mark, pos, lim, cap); this.bb = bb; offset = off; } public DoubleBuffer slice() { int pos = this.position(); int lim = this.limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); int off = (pos << 3) + offset; assert (off >= 0); return new ByteBufferAsDoubleBufferB(bb, -1, 0, rem, rem, off); } public DoubleBuffer duplicate() { return new ByteBufferAsDoubleBufferB(bb, this.markValue(), this.position(), this.limit(), this.capacity(), offset); } public DoubleBuffer asReadOnlyBuffer() { return new ByteBufferAsDoubleBufferRB(bb, this.markValue(), this.position(), this.limit(), this.capacity(), offset); } protected int ix(int i) { return (i << 3) + offset; } public double get() { return Bits.getDoubleB(bb, ix(nextGetIndex())); } public double get(int i) { return Bits.getDoubleB(bb, ix(checkIndex(i))); } public DoubleBuffer put(double x) { Bits.putDoubleB(bb, ix(nextPutIndex()), x); return this; } public DoubleBuffer put(int i, double x) { Bits.putDoubleB(bb, ix(checkIndex(i)), x); return this; } public DoubleBuffer compact() { int pos = position(); int lim = limit(); assert (pos <= lim); int rem = (pos <= lim ? lim - pos : 0); ByteBuffer db = bb.duplicate(); db.limit(ix(lim)); db.position(ix(0)); ByteBuffer sb = db.slice(); sb.position(pos << 3); sb.compact(); position(rem); limit(capacity()); return this; } public boolean isDirect() { return bb.isDirect(); } public boolean isReadOnly() { return false; } public ByteOrder order() { return ByteOrder.BIG_ENDIAN; } }
jgaltidor/VarJ
analyzed_libs/jdk1.6.0_06_src/java/nio/ByteBufferAsDoubleBufferB.java
Java
mit
2,856
import { Injectable } from 'angular2/core'; @Injectable() export class Config { SERVER_URL:string = "http://128.199.158.79:9000/"; }
alexsalesdev/fiori-blossoms-ui-web-angular-2
public/app/service/config.ts
TypeScript
mit
138
class GeometryTests < PostgreSQLExtensionsTestCase def test_create_geometry Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_spatial Mig.create_table(:foo) do |t| t.spatial :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_spatial_and_spatial_column_type Mig.create_table(:foo) do |t| t.spatial :the_geom, :srid => 4326, :spatial_column_type => :geography end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geography, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geography Mig.create_table(:foo) do |t| t.geography :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geography, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_schema Mig.create_table('shabba.foo') do |t| t.geometry :the_geom, :srid => 4326 end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "shabba"."foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'shabba' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'shabba', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON "shabba"."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_not_null Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :null => false end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry NOT NULL, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_create_geometry_with_null_and_type Mig.create_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :geometry_type => :polygon end expected = [] expected << strip_heredoc(<<-SQL) CREATE TABLE "foo" ( "id" serial primary key, "the_geom" geometry, CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326)), CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2), CONSTRAINT "enforce_geotype_the_geom" CHECK (geometrytype("the_geom") = 'POLYGON'::text OR "the_geom" IS NULL) ); SQL expected << strip_heredoc(<<-SQL) DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom'; SQL expected << strip_heredoc(<<-SQL) INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'POLYGON'); SQL expected << strip_heredoc(<<-SQL) CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom"); SQL assert_equal(expected, statements) end def test_change_table_add_geometry Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_add_geometry_with_spatial Mig.change_table(:foo) do |t| t.spatial :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_spatial_and_spatial_column_type Mig.change_table(:foo) do |t| t.spatial :the_geom, :srid => 4326, :spatial_column_type => :geography end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geography}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geography Mig.change_table(:foo) do |t| t.geography :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geography}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_force_constraints Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :force_constraints => true end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_schema Mig.change_table('shabba.foo') do |t| t.geometry :the_geom, :srid => 4326 end expected = [ %{ALTER TABLE "shabba"."foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "shabba"."foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "shabba"."foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'shabba' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'shabba', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON "shabba"."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_not_null Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :null => false end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry NOT NULL}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'GEOMETRY');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end def test_change_table_geometry_with_null_and_type Mig.change_table(:foo) do |t| t.geometry :the_geom, :srid => 4326, :geometry_type => :polygon end expected = [ %{ALTER TABLE "foo" ADD COLUMN "the_geom" geometry}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_srid_the_geom" CHECK (ST_srid("the_geom") = (4326));}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_dims_the_geom" CHECK (ST_ndims("the_geom") = 2);}, %{ALTER TABLE "foo" ADD CONSTRAINT "enforce_geotype_the_geom" CHECK (geometrytype("the_geom") = 'POLYGON'::text OR "the_geom" IS NULL);}, %{DELETE FROM "geometry_columns" WHERE f_table_catalog = '' AND f_table_schema = 'public' AND f_table_name = 'foo' AND f_geometry_column = 'the_geom';}, %{INSERT INTO "geometry_columns" VALUES ('', 'public', 'foo', 'the_geom', 2, 4326, 'POLYGON');}, %{CREATE INDEX "foo_the_geom_gist_index" ON PUBLIC."foo" USING "gist"("the_geom");} ] assert_equal(expected, statements) end end
zoocasa/activerecord-postgresql-extensions
test/geometry_tests_legacy_postgis.rb
Ruby
mit
12,763
module FrankAfcProxy VERSION = "0.0.1" end
suzumura-ss/frank_afc_proxy
lib/frank_afc_proxy/version.rb
Ruby
mit
45
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" /> /// <reference path="../model/event.js" /> (function () { var initAppBarGlobalCommands = function () { var eventsButton = document.getElementById("navigate-onClick-to-events"); eventsButton.addEventListener("click", function () { WinJS.Navigation.navigate("/js/view/events/events.html"); }); } var initAppBarrEventsCommands = function () { var eventsButton = document.getElementById("call-form-for-event"); eventsButton.addEventListener("click", function () { var eventCreationFormHolder = document.getElementById("event-form-creation-form").winControl; eventCreationFormHolder.show(eventCreationFormHolder, "right", "center"); }); } var initNewEventCreateBtn = function () { var createEventBtn = document.getElementById("create-event-btn"); createEventBtn.addEventListener("click", function () { var eventDTO = Models.Event.eventDTO; var title = document.getElementById("new-event-title").value; var description = document.getElementById("new-event-description").innerHTML; eventDTO.title = title; eventDTO.description = description; var localFolder = Windows.Storage.ApplicationData.current.localFolder; localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists).then(function (file) { var content = JSON.stringify(eventDTO); Windows.Storage.FileIO.readTextAsync(file).then(function (oldContent) { oldContent = oldContent.replace("[", ""); oldContent = oldContent.replace("]", ""); content = content + ',' + oldContent; Windows.Storage.FileIO.writeTextAsync(file, "[" + content + "]"); }); }); }); } var readEventsFromLocalFolder = function () { var localFolder = Windows.Storage.ApplicationData.current.localFolder; return localFolder.createFileAsync("events", Windows.Storage.CreationCollisionOption.openIfExists); } WinJS.Namespace.define("Commands", { initAppBarCommands: initAppBarGlobalCommands, initAppBarrEventsCommands: initAppBarrEventsCommands, initNewEventCreateBtn: initNewEventCreateBtn, readEventsFromLocalFolder: readEventsFromLocalFolder, }); })();
vaster/RestReminder
RestReminderApp/RestReminderApp/js/commands/command.js
JavaScript
mit
2,545
<?php if (count($brands) > 0): ?> <?php if ($sf_request->hasParameter('is_search')): ?> <?php $action = '@product_search' ?> <?php else: ?> <?php $action = '@product_list' ?> <?php endif; ?> <?php if ($sf_request->hasParameter('path')): ?> <?php $path = '?path=' . $sf_request->getParameter('path') ?> <?php else: ?> <?php $path = '' ?> <?php endif; ?> <b><?php echo __('Filter by brand') ?>:</b> <?php $link = link_to( __('All'), url_for($action . $path, true) . '?filters[brand_id]=all&filter=filter', array('post' => true) ) ?> <?php if (!isset($filter['brand_id'])): ?> <b><?php echo $link ?></b> <?php else: ?> <?php echo $link ?> <?php endif; ?> <?php foreach ($brands as $brand): ?> <?php $link = link_to( $brand->getTitle(), url_for($action . $path, true) . '?filters[brand_id]=' . $brand->getId() . '&filter=filter', array('post' => true) ) ?> <?php if (isset($filter['brand_id']) && $brand->getId() == $filter['brand_id']): ?> <b><?php echo $link ?></b> <?php else: ?> <?php echo $link ?> <?php endif; ?> <?php endforeach; ?> <?php endif; ?>
alecslupu/sfshop
plugins/sfsProductPlugin/modules/brand/templates/_filterList.php
PHP
mit
1,333
package tile; import java.net.URL; public class Box extends Tile { public Box(URL url, char key) { // TODO Auto-generated constructor stub super(url, key); this.canMove = false; } }
Sy4z/The-Excellent-Adventure
src/tile/Box.java
Java
mit
193
// Generated by CoffeeScript 1.7.1 (function() { var pf, pfr; pf = function(n) { return pfr(n, 2, []); }; pfr = function(n, d, f) { if (n < 2) { return f; } if (n % d === 0) { return [d].concat(pfr(n / d, d, f)); } return pfr(n, d + 1, f); }; module.exports = pf; }).call(this);
dlwire/coffeescript-barebones
javascripts/pf.js
JavaScript
mit
331
var plan = require('./index'); module.exports = plan; var HOST = 'brainbug.local'; plan.target('single', function(done) { setTimeout(function() { done([ { host: HOST + 'lol', username: 'pstadler', agent: process.env.SSH_AUTH_SOCK, failsafe: true }, { host: HOST, username: 'pstadler', agent: process.env.SSH_AUTH_SOCK, } ]); }, 1000); }, { sudoUser: 'bar' }); plan.target('multi', [ { host: HOST, username: 'pstadler', privateKey: '/Users/pstadler/.ssh/id_rsa', passphrase: '' //agent: process.env.SSH_AUTH_SOCK }, { host: HOST, username: 'pstadler', privateKey: '/Users/pstadler/.ssh/id_rsa', passphrase: '' //agent: process.env.SSH_AUTH_SOCK } ]); plan.remote(function(remote) { remote.ls(); }); plan.local(function(local) { console.log(plan.runtime.options); var foo = local.prompt('Hello?'); console.log(foo); local.failsafe(); local.ls('-al', {exec: { cwd: '/'}}); local.transfer('lib/', '/tmp'); }); plan.remote(function(remote) { //remote.exec('read', {exec: {pty: true}}); //remote.exec('tail -f /tmp/foo/index.js'); // remote.silent(); // remote.ls('-al'); // remote.verbose(); remote.ls('-al'); // remote.exec('ls -al', { exec: { pty: true } }); // remote.sudo('ls -al', { user: 'node' }); }); plan.local(function(local) { local.ls('-al foooo', {failsafe: true}); //plan.abort(); }); plan.remote(function(remote) { remote.ls('-al'); }); // plan.local(function(local) { // local.with('cd /tmp', { failsafe: true }, function() { // local.ls('-al bar'); // local.with('echo hello world', { failsafe: false }, function() { // local.ls('-al bar', { failsafe: true }); // }); // }); // var files = local.ls({ silent: true }); // local.transfer(files, '/tmp/foo'); // local.prompt('Do you really want to foo?', {hidden: true}); // }); // plan.local(function(local) { // local.log('this is a user message'); // local.echo('hello world'); // //plan.abort(); // //local.prompt('foo', {hidden: true}); // }); // plan.local('default', function(local) { // local.exec('ls -al'); // local.exec('ls foo', { failsafe: true }); // try { // local.exec('ls foo'); // } catch(e) { // console.log(e); // } // local.with('cd /tmp', { silent: true }, function() { // local.ls(); // }) // }); // plan.remote(function(remote) { // remote.silent(); // remote.ls('-al'); // remote.ls('foo', { failsafe: true }) // remote.ls('foo'); // remote.sudo('echo foo', { user: 'node' }); // remote.verbose(); // remote.with('cd /tmp', function() { // remote.sudo('ls -al', { user: 'node' }); // }); // }); // plan.remote(function(remote) { // remote.ls('-al /tmp/foo'); // console.log(remote.target); // console.log(plan.runtime); // }); //plan.run('default', 'multi', { debug: true });
thundernixon/thundernixon2015wp-sage
node_modules/flightplan/flightplan.js
JavaScript
mit
2,931
<?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class SecurityController extends Controller { public function loginAction(Request $request) { $authUtils = $this->get('security.authentication_utils'); $error = $authUtils->getLastAuthenticationError(); $lastUsername = $authUtils->getLastUsername(); return $this->render('security/login.html.twig', [ 'error' => $error, 'last_username' => $lastUsername ]); } }
marko126/symfony-nastava
src/AppBundle/Controller/SecurityController.php
PHP
mit
612
require File.dirname(__FILE__) + '/spec_helper' module SDP describe "Dokken iteration 3" do before(:all) do @iteration = Iteration.new(3, "Dokken", Date.parse('01/21/2008'), Date.parse('01/25/2008')) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=632%2C754%2C2025%2C3370%2C3600%2C3708%2C3921%2C4017%2C4030%2C4161%2C4200%2C4461%2C4544%2C4571%2C4809%2C5008%2C5026%2C5382%2C5428%2C5496%2C5609%2C5774%2C6198%2C6206%2C6247%2C6248%2C6253%2C6294%2C6322%2C6324%2C6325%2C6329%2C6337%2C6356%2C6371%2C6427%2C6459%2C6471%2C6472%2C6486%2C6515%2C6519%2C6524%2C6525%2C6537%2C6640%2C6642%2C6652%2C6671%2C6676%2C6677%2C6678%2C6680%2C6681%2C6684%2C6685%2C6686%2C6688%2C6699%2C6705%2C6706%2C6707%2C6708%2C6709%2C6710%2C6711%2C6712%2C6713%2C6714%2C6715%2C6717%2C6726%2C6736%2C6788%2C6797%2C6804%2C6805%2C6806%2C6807%2C6808%2C6810%2C6811%2C6812%2C6813%2C6815%2C6816%2C6817%2C6818%2C6819%2C6820%2C6821%2C6822%2C6823%2C6824%2C6825%2C6826%2C6827%2C6828%2C6829%2C6830%2C6831%2C6834%2C6838%2C6839%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6859%2C6860%2C6861%2C6862%2C6863%2C6864%2C6865%2C6866%2C6867%2C6868%2C6904%2C6905 EOQ @iteration.remaining_at_start = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=2025%2C3370%2C3600%2C3921%2C4017%2C4030%2C4161%2C4200%2C4461%2C4544%2C4571%2C4809%2C4845%2C5008%2C5026%2C5382%2C5428%2C5496%2C5609%2C5774%2C5981%2C6198%2C6206%2C6247%2C6253%2C6316%2C6322%2C6324%2C6325%2C6337%2C6346%2C6356%2C6371%2C6427%2C6459%2C6471%2C6472%2C6486%2C6490%2C6515%2C6519%2C6537%2C6640%2C6642%2C6652%2C6671%2C6676%2C6677%2C6680%2C6684%2C6685%2C6688%2C6699%2C6705%2C6706%2C6707%2C6708%2C6709%2C6710%2C6711%2C6712%2C6713%2C6714%2C6715%2C6717%2C6726%2C6736%2C6788%2C6796%2C6797%2C6804%2C6807%2C6808%2C6810%2C6811%2C6812%2C6813%2C6815%2C6816%2C6817%2C6818%2C6819%2C6820%2C6821%2C6822%2C6823%2C6824%2C6825%2C6826%2C6827%2C6828%2C6829%2C6830%2C6831%2C6834%2C6838%2C6839%2C6860%2C6862%2C6863%2C6864%2C6865%2C6866%2C6867%2C6868%2C6904%2C6905%2C6912%2C6922%2C6933%2C6937%2C6949%2C6952%2C6953%2C6954%2C6955%2C6963%2C6989%2C6993%2C7005%2C7006%2C7008%2C7009 EOQ @iteration.remaining_at_end = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=754%2C6329%2C6607%2C6681%2C6693%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6248%2C6524%2C6525%2C6678%2C6805%2C6806%2C6859%2C6923%2C632%2C3708%2C6686%2C6861 EOQ @iteration.completed = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=2244%2C4017%2C4030%2C4461%2C4809%2C5611%2C6248%2C6346%2C6371%2C6708%2C6713%2C6714%2C6715%2C6807%2C6808%2C6810%2C6811%2C6860%2C6862%2C6863%2C6865%2C6866%2C6905%2C6933%2C6963%2C6989%2C6864 EOQ @iteration.carry_over = View.from_query(Query.from_s(s)) s = <<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=754%2C3708%2C4017%2C4030%2C4461%2C6329%2C6371%2C6678%2C6681%2C6686%2C6708%2C6713%2C6714%2C6715%2C6805%2C6810%2C6841%2C6853%2C6854%2C6856%2C6857%2C6858%2C6859%2C6860%2C6861%2C6862%2C6866 EOQ @iteration.planned = View.from_query(Query.from_s(s)) end it "should have length" do @iteration.length.should == 4 end it "should have expected items remaining at start" do @iteration.remaining_at_start.size.should == 122 end it "should have expected cost remaining at start" do begin @iteration.remaining_at_start.total_cost.should == 200 rescue View::CostMissingException => e puts e.view end end it "should have expected items planned" do @iteration.planned.size.should == 27 end it "should have expected cost planned" do begin @iteration.planned.total_cost.should == 45 rescue View::CostMissingException => e puts e.view end end it "should have expected items remaining at end" do @iteration.remaining_at_end.size.should == 123 end it "should have expected cost remaining at end" do begin @iteration.remaining_at_end.total_cost.should == 192 rescue View::CostMissingException => e puts e.view end end it "should have expected items carried over" do @iteration.carry_over.size.should == 27 end it "should have expected cost for carried over" do @iteration.carry_over.total_cost.should == 47 end it "should have expected items completed" do @iteration.completed.size.should == 23 end it "should have expected cost for completed" do @iteration.completed.total_cost.should == 39 end it "should have expected velocity" do @iteration.velocity.should == 9.75 end it "should compute changed" do q =<<EOQ http://bugzilla.songbirdnest.com/buglist.cgi?quicksearch=6607%2C6693%2C4845%2C6923%2C5981%2C6316%2C6294%2C6346%2C6490%2C6796%2C6912%2C6922%2C6933%2C6937%2C6949%2C6952%2C6953%2C6954%2C6955%2C6963%2C6989%2C6993%2C7005%2C7006%2C7008%2C7009 EOQ @iteration.changed.should == View.from_query(Query.from_s(q)) end it "should have expected items that changed" do @iteration.changed.size.should == 26 end it "should compute net intake cost" do @iteration.changed_net_cost.should == 31 end end end
skelliam/sdpbot
spec/dokken_iteration_3_spec.rb
Ruby
mit
5,352
using System; using Edsoft.Hypermedia.Serializers; using Newtonsoft.Json.Linq; using NUnit.Framework; using Ploeh.AutoFixture; using Rhino.Mocks; namespace Edsoft.Hypermedia.Tests.Serializers { public class JsonSerializerTests : TestWithFixture { private JsonSerializer sut; private Func<IRepresentationBuilder> builderFactoryMethod; [SetUp] public void Init() { sut = new JsonSerializer(); Fixture = GetFixture(); builderFactoryMethod = () => MockRepository.GenerateMock<IRepresentationBuilder>(); } [Test] public void HasCorrectContentType() { Assert.AreEqual("application/json", sut.ContentType); } [Test] public void Serialize_WorksWithEmptyRepresentor() { var representor = new HypermediaRepresentation(); sut.Serialize(representor); } [Test] public void Serialize_EmptyAttributes() { var representor = Fixture.Create<HypermediaRepresentation>(); representor.Attributes = new JObject(); var result = sut.Serialize(representor); Assert.AreEqual("{}", result); } [Test] public void Serialize_AddsAttributesToRootForEachAttributeInRepresentor() { var representor = Fixture.Create<HypermediaRepresentation>(); var dataJobject = JObject.FromObject(Fixture.Create<ExampleDataObject>()); representor.Attributes = dataJobject; var result = JObject.Parse(sut.Serialize(representor)); foreach (var property in dataJobject.Properties()) { Assert.AreEqual(dataJobject.GetValue(property.Name), result.GetValue(property.Name)); } } [Test] public void Serialize_AddsNestedAttributeToRootInRepresentor() { var representor = Fixture.Create<HypermediaRepresentation>(); var json = @" { ""data"": { ""self"": { ""not-href"": ""blah"" } } }"; var dataJobject = JObject.Parse(json); representor.Attributes = dataJobject; var result = sut.Serialize(representor); Assert.AreEqual(dataJobject.ToString(), result); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void Serialize_SetsRepresentorWithNull() { sut.Serialize(null); } [Test] public void DeserializeToNewBuilder_SetsEmptyDocument() { var href = Fixture.Create<string>(); var json = "{}"; var builder = sut.DeserializeToNewBuilder(json, builderFactoryMethod); builder.AssertWasCalled(b => b.SetAttributes(Arg<JObject>.Matches(j => j.Count == 0))); } [Test] public void DeserializeToNewBuilder_SetsAttributes() { var id = Fixture.Create<string>(); var intId = Fixture.Create<int>(); var json = @" {{ ""id"" : ""{0}"", ""int_id"" : {1} }}"; json = String.Format(json, id, intId); var builder = sut.DeserializeToNewBuilder(json, builderFactoryMethod); builder.AssertWasCalled(b => b.SetAttributes(Arg<JObject>.Matches(j => j["id"].Value<string>() == id && j["int_id"].Value<int>() == intId))); } [Test] public void DeserializeToNewBuilder_SetsNestedAttribute() { var href = Fixture.Create<string>(); var json = @" { ""data"": { ""self"": { ""not-href"": ""blah"" } } }"; var dataJobject = JObject.Parse(json); var builder = sut.DeserializeToNewBuilder(json, builderFactoryMethod); builder.AssertWasCalled(b => b.SetAttributes(Arg<JObject>.Matches(j => j.ToString() == dataJobject.ToString()))); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeserializeToNewBuilder_SetsMessageWithNull() { sut.DeserializeToNewBuilder(null, builderFactoryMethod); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void DeserializeToNewBuilder_SetsMethodWithNull() { var href = Fixture.Create<string>(); var json = @" {{ ""data"": {{ ""self"": {{ ""href"": ""{0}"" }} }} }}"; var builder = sut.DeserializeToNewBuilder(json, null); } } }
edandersen/Edsoft.Hypermedia
tests/Edsoft.Hypermedia.Tests/Serializers/JsonSerializerTests.cs
C#
mit
4,991
class TweetsController < ApplicationController def create # Planned on rendering json for line 6 to Ajax a new post back onto the page # But this single-app feature wouldn't grab new tweets. Having it live update # through streaming would take care of this, otherwise, just refresh page client.update(params[:tweet]) redirect_to root_path end end
heycait/twitter
app/controllers/tweets_controller.rb
Ruby
mit
371
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array('database'); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in the system/libraries folder | or in your application/libraries folder. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('session','database'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in the system/libraries folder or in your | application/libraries folder within their own subdirectory. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array('Cdn_model' => 'cdn');
opengbu/gbuonline
application/config/autoload.php
PHP
mit
3,814
#include <iostream> #include <seqan/file.h> #include <seqan/sequence.h> #include <seqan/score.h> template <typename TText, typename TPattern> int computeLocalScore(TText const &subText, TPattern const &pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) if (subText[i] == pattern[i]) ++localScore; return localScore; } template <typename TText> int computeLocalScore(TText const & subText, seqan::String<seqan::AminoAcid> const & pattern) { int localScore = 0; for (unsigned i = 0; i < seqan::length(pattern); ++i) localScore += seqan::score(seqan::Blosum62(), subText[i], pattern[i]); return localScore; } template <typename TText, typename TPattern> seqan::String<int> computeScore(TText const &text, TPattern const &pattern) { seqan::String<int> score; seqan::resize(score, seqan::length(text), 0); for (unsigned i = 0; i < seqan::length(text) - seqan::length(pattern) + 1; ++i) score[i] = computeLocalScore(infix(text, i, i + seqan::length(pattern)), pattern); return score; } template <typename Ty> void print(Ty const &score) { for (unsigned i = 0; i < seqan::length(score); ++i) {std::cout << score[i] << " ";} std::cout << std::endl; } template <> void print(seqan::String<int> const &score) { for (unsigned i = 0; i < seqan::length(score); ++i) {std::cout << score[i] << " ";} std::cout << std::endl; } int main() { seqan::String<char> text = "This is an awesome tutorial to get to now SeqAn!"; seqan::String<char> pattern = "tutorial"; seqan::String<int> score = computeScore(text, pattern); print(score); return 0; }
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/caivjx2geotu92t0/2013-04-09T16-09-03.492+0200/sandbox/my_sandbox/apps/firstSteps1/firstSteps1.cpp
C++
mit
1,740
package denvlib import ( "encoding/json" "io/ioutil" "os" git "github.com/buckhx/gitlib" "github.com/buckhx/pathutil" ) /* DenvInfo is a mechanism for handling state of the denv environment. It flushed it's contents to disk and reads from a given location */ type DenvInfo struct { Current *Denv Path string Repository *git.Repository } var Info DenvInfo func (d *DenvInfo) Clear() { d.Current = nil } func (d *DenvInfo) Flush() { content := []byte(d.ToString()) err := ioutil.WriteFile(d.Path, content, 0644) check(err) } func (d *DenvInfo) IsActive() bool { return d.Current != nil } func (d *DenvInfo) Load() { //TODO make sure that this is an available file content, err := ioutil.ReadFile(d.Path) check(err) err = json.Unmarshal(content, &d) check(err) } func (d *DenvInfo) ToString() string { content, err := json.Marshal(d) check(err) return string(content) } func bootstrap() error { //TODO: maybe this should live somewhere else // Create DENVHOME if !pathutil.Exists(Settings.DenvHome) { err := os.MkdirAll(Settings.DenvHome, 0744) if err != nil { return err } } if !git.IsRepository(Settings.DenvHome) { repo, err := git.NewRepository(Settings.DenvHome) check(err) repo.Init() repo.Exclude("/.*") // exclude hidden root files } return nil } func init() { bootstrap() path := Settings.InfoFile Info.Path = path repo, err := git.NewRepository(Settings.DenvHome) check(err) Info.Repository = repo if !pathutil.Exists(path) { Info.Flush() } Info.Load() }
buckhx/denv
denvlib/info.go
GO
mit
1,538