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 |
|---|---|---|---|---|---|
# cs.???? = currentstate, any variable on the status tab in the planner can be used.
# Script = options are
# Script.Sleep(ms)
# Script.ChangeParam(name,value)
# Script.GetParam(name)
# Script.ChangeMode(mode) - same as displayed in mode setup screen 'AUTO'
# Script.WaitFor(string,timeout)
# Script.SendRC(channel,pwm,sendnow)
#
print 'Start Script'
for chan in range(1,9):
Script.SendRC(chan,1500,False)
Script.SendRC(3,Script.GetParam('RC3_MIN'),True)
Script.Sleep(5000)
while cs.lat == 0:
print 'Waiting for GPS'
Script.Sleep(1000)
print 'Got GPS'
jo = 10 * 13
print jo
Script.SendRC(3,1000,False)
Script.SendRC(4,2000,True)
cs.messages.Clear()
Script.WaitFor('ARMING MOTORS',30000)
Script.SendRC(4,1500,True)
print 'Motors Armed!'
Script.SendRC(3,1700,True)
while cs.alt < 50:
Script.Sleep(50)
Script.SendRC(5,2000,True) # acro
Script.SendRC(1,2000,False) # roll
Script.SendRC(3,1370,True) # throttle
while cs.roll > -45: # top hald 0 - 180
Script.Sleep(5)
while cs.roll < -45: # -180 - -45
Script.Sleep(5)
Script.SendRC(5,1500,False) # stabalise
Script.SendRC(1,1500,True) # level roll
Script.Sleep(2000) # 2 sec to stabalise
Script.SendRC(3,1300,True) # throttle back to land
thro = 1350 # will decend
while cs.alt > 0.1:
Script.Sleep(300)
Script.SendRC(3,1000,False)
Script.SendRC(4,1000,True)
Script.WaitFor('DISARMING MOTORS',30000)
Script.SendRC(4,1500,True)
print 'Roll complete' | vizual54/MissionPlanner | Scripts/example1.py | Python | gpl-3.0 | 1,491 |
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package edu.amc.sakai.user;
import com.novell.ldap.LDAPConnection;
/**
* Pluggable strategy for verifying {@link LDAPConnection}
* "liveness". Typically injected into a
* {@link PooledLDAPConnectionFactory}.
*
* @author dmccallum@unicon.net
*
*/
public interface LdapConnectionLivenessValidator {
public boolean isConnectionAlive(LDAPConnection connectionToTest);
}
| marktriggs/nyu-sakai-10.4 | providers/jldap/src/java/edu/amc/sakai/user/LdapConnectionLivenessValidator.java | Java | apache-2.0 | 1,307 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
cr.define('cr.ui', function() {
// require cr.ui.define
// require cr.ui.limitInputWidth
/**
* The number of pixels to indent per level.
* @type {number}
* @const
*/
var INDENT = 20;
/**
* Returns the computed style for an element.
* @param {!Element} el The element to get the computed style for.
* @return {!CSSStyleDeclaration} The computed style.
*/
function getComputedStyle(el) {
return el.ownerDocument.defaultView.getComputedStyle(el);
}
/**
* Helper function that finds the first ancestor tree item.
* @param {!Element} el The element to start searching from.
* @return {cr.ui.TreeItem} The found tree item or null if not found.
*/
function findTreeItem(el) {
while (el && !(el instanceof TreeItem)) {
el = el.parentNode;
}
return el;
}
/**
* Creates a new tree element.
* @param {Object=} opt_propertyBag Optional properties.
* @constructor
* @extends {HTMLElement}
*/
var Tree = cr.ui.define('tree');
Tree.prototype = {
__proto__: HTMLElement.prototype,
/**
* Initializes the element.
*/
decorate: function() {
// Make list focusable
if (!this.hasAttribute('tabindex'))
this.tabIndex = 0;
this.addEventListener('click', this.handleClick);
this.addEventListener('mousedown', this.handleMouseDown);
this.addEventListener('dblclick', this.handleDblClick);
this.addEventListener('keydown', this.handleKeyDown);
},
/**
* Returns the tree item that are children of this tree.
*/
get items() {
return this.children;
},
/**
* Adds a tree item to the tree.
* @param {!cr.ui.TreeItem} treeItem The item to add.
*/
add: function(treeItem) {
this.addAt(treeItem, 0xffffffff);
},
/**
* Adds a tree item at the given index.
* @param {!cr.ui.TreeItem} treeItem The item to add.
* @param {number} index The index where we want to add the item.
*/
addAt: function(treeItem, index) {
this.insertBefore(treeItem, this.children[index]);
treeItem.setDepth_(this.depth + 1);
},
/**
* Removes a tree item child.
* @param {!cr.ui.TreeItem} treeItem The tree item to remove.
*/
remove: function(treeItem) {
this.removeChild(treeItem);
},
/**
* The depth of the node. This is 0 for the tree itself.
* @type {number}
*/
get depth() {
return 0;
},
/**
* Handles click events on the tree and forwards the event to the relevant
* tree items as necesary.
* @param {Event} e The click event object.
*/
handleClick: function(e) {
var treeItem = findTreeItem(e.target);
if (treeItem)
treeItem.handleClick(e);
},
handleMouseDown: function(e) {
if (e.button == 2) // right
this.handleClick(e);
},
/**
* Handles double click events on the tree.
* @param {Event} e The dblclick event object.
*/
handleDblClick: function(e) {
var treeItem = findTreeItem(e.target);
if (treeItem)
treeItem.expanded = !treeItem.expanded;
},
/**
* Handles keydown events on the tree and updates selection and exanding
* of tree items.
* @param {Event} e The click event object.
*/
handleKeyDown: function(e) {
var itemToSelect;
if (e.ctrlKey)
return;
var item = this.selectedItem;
if (!item)
return;
var rtl = getComputedStyle(item).direction == 'rtl';
switch (e.keyIdentifier) {
case 'Up':
itemToSelect = item ? getPrevious(item) :
this.items[this.items.length - 1];
break;
case 'Down':
itemToSelect = item ? getNext(item) :
this.items[0];
break;
case 'Left':
case 'Right':
// Don't let back/forward keyboard shortcuts be used.
if (!cr.isMac && e.altKey || cr.isMac && e.metaKey)
break;
if (e.keyIdentifier == 'Left' && !rtl ||
e.keyIdentifier == 'Right' && rtl) {
if (item.expanded)
item.expanded = false;
else
itemToSelect = findTreeItem(item.parentNode);
} else {
if (!item.expanded)
item.expanded = true;
else
itemToSelect = item.items[0];
}
break;
case 'Home':
itemToSelect = this.items[0];
break;
case 'End':
itemToSelect = this.items[this.items.length - 1];
break;
}
if (itemToSelect) {
itemToSelect.selected = true;
e.preventDefault();
}
},
/**
* The selected tree item or null if none.
* @type {cr.ui.TreeItem}
*/
get selectedItem() {
return this.selectedItem_ || null;
},
set selectedItem(item) {
var oldSelectedItem = this.selectedItem_;
if (oldSelectedItem != item) {
// Set the selectedItem_ before deselecting the old item since we only
// want one change when moving between items.
this.selectedItem_ = item;
if (oldSelectedItem)
oldSelectedItem.selected = false;
if (item)
item.selected = true;
cr.dispatchSimpleEvent(this, 'change');
}
},
/**
* @return {!ClientRect} The rect to use for the context menu.
*/
getRectForContextMenu: function() {
// TODO(arv): Add trait support so we can share more code between trees
// and lists.
if (this.selectedItem)
return this.selectedItem.rowElement.getBoundingClientRect();
return this.getBoundingClientRect();
}
};
/**
* Determines the visibility of icons next to the treeItem labels. If set to
* 'hidden', no space is reserved for icons and no icons are displayed next
* to treeItem labels. If set to 'parent', folder icons will be displayed
* next to expandable parent nodes. If set to 'all' folder icons will be
* displayed next to all nodes. Icons can be set using the treeItem's icon
* property.
*/
cr.defineProperty(Tree, 'iconVisibility', cr.PropertyKind.ATTR);
/**
* This is used as a blueprint for new tree item elements.
* @type {!HTMLElement}
*/
var treeItemProto = (function() {
var treeItem = cr.doc.createElement('div');
treeItem.className = 'tree-item';
treeItem.innerHTML = '<div class=tree-row>' +
'<span class=expand-icon></span>' +
'<span class=tree-label></span>' +
'</div>' +
'<div class=tree-children></div>';
treeItem.setAttribute('role', 'treeitem');
return treeItem;
})();
/**
* Creates a new tree item.
* @param {Object=} opt_propertyBag Optional properties.
* @constructor
* @extends {HTMLElement}
*/
var TreeItem = cr.ui.define(function() {
return treeItemProto.cloneNode(true);
});
TreeItem.prototype = {
__proto__: HTMLElement.prototype,
/**
* Initializes the element.
*/
decorate: function() {
},
/**
* The tree items children.
*/
get items() {
return this.lastElementChild.children;
},
/**
* The depth of the tree item.
* @type {number}
*/
depth_: 0,
get depth() {
return this.depth_;
},
/**
* Sets the depth.
* @param {number} depth The new depth.
* @private
*/
setDepth_: function(depth) {
if (depth != this.depth_) {
this.rowElement.style.WebkitPaddingStart = Math.max(0, depth - 1) *
INDENT + 'px';
this.depth_ = depth;
var items = this.items;
for (var i = 0, item; item = items[i]; i++) {
item.setDepth_(depth + 1);
}
}
},
/**
* Adds a tree item as a child.
* @param {!cr.ui.TreeItem} child The child to add.
*/
add: function(child) {
this.addAt(child, 0xffffffff);
},
/**
* Adds a tree item as a child at a given index.
* @param {!cr.ui.TreeItem} child The child to add.
* @param {number} index The index where to add the child.
*/
addAt: function(child, index) {
this.lastElementChild.insertBefore(child, this.items[index]);
if (this.items.length == 1)
this.hasChildren = true;
child.setDepth_(this.depth + 1);
},
/**
* Removes a child.
* @param {!cr.ui.TreeItem} child The tree item child to remove.
*/
remove: function(child) {
// If we removed the selected item we should become selected.
var tree = this.tree;
var selectedItem = tree.selectedItem;
if (selectedItem && child.contains(selectedItem))
this.selected = true;
this.lastElementChild.removeChild(child);
if (this.items.length == 0)
this.hasChildren = false;
},
/**
* The parent tree item.
* @type {!cr.ui.Tree|cr.ui.TreeItem}
*/
get parentItem() {
var p = this.parentNode;
while (p && !(p instanceof TreeItem) && !(p instanceof Tree)) {
p = p.parentNode;
}
return p;
},
/**
* The tree that the tree item belongs to or null of no added to a tree.
* @type {cr.ui.Tree}
*/
get tree() {
var t = this.parentItem;
while (t && !(t instanceof Tree)) {
t = t.parentItem;
}
return t;
},
/**
* Whether the tree item is expanded or not.
* @type {boolean}
*/
get expanded() {
return this.hasAttribute('expanded');
},
set expanded(b) {
if (this.expanded == b)
return;
var treeChildren = this.lastElementChild;
if (b) {
if (this.mayHaveChildren_) {
this.setAttribute('expanded', '');
treeChildren.setAttribute('expanded', '');
cr.dispatchSimpleEvent(this, 'expand', true);
this.scrollIntoViewIfNeeded(false);
}
} else {
var tree = this.tree;
if (tree && !this.selected) {
var oldSelected = tree.selectedItem;
if (oldSelected && this.contains(oldSelected))
this.selected = true;
}
this.removeAttribute('expanded');
treeChildren.removeAttribute('expanded');
cr.dispatchSimpleEvent(this, 'collapse', true);
}
},
/**
* Expands all parent items.
*/
reveal: function() {
var pi = this.parentItem;
while (pi && !(pi instanceof Tree)) {
pi.expanded = true;
pi = pi.parentItem;
}
},
/**
* The element representing the row that gets highlighted.
* @type {!HTMLElement}
*/
get rowElement() {
return this.firstElementChild;
},
/**
* The element containing the label text and the icon.
* @type {!HTMLElement}
*/
get labelElement() {
return this.firstElementChild.lastElementChild;
},
/**
* The label text.
* @type {string}
*/
get label() {
return this.labelElement.textContent;
},
set label(s) {
this.labelElement.textContent = s;
},
/**
* The URL for the icon.
* @type {string}
*/
get icon() {
return getComputedStyle(this.labelElement).backgroundImage.slice(4, -1);
},
set icon(icon) {
return this.labelElement.style.backgroundImage = url(icon);
},
/**
* Whether the tree item is selected or not.
* @type {boolean}
*/
get selected() {
return this.hasAttribute('selected');
},
set selected(b) {
if (this.selected == b)
return;
var rowItem = this.firstElementChild;
var tree = this.tree;
if (b) {
this.setAttribute('selected', '');
rowItem.setAttribute('selected', '');
this.reveal();
this.labelElement.scrollIntoViewIfNeeded(false);
if (tree)
tree.selectedItem = this;
} else {
this.removeAttribute('selected');
rowItem.removeAttribute('selected');
if (tree && tree.selectedItem == this)
tree.selectedItem = null;
}
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
get mayHaveChildren_() {
return this.hasAttribute('may-have-children');
},
set mayHaveChildren_(b) {
var rowItem = this.firstElementChild;
if (b) {
this.setAttribute('may-have-children', '');
rowItem.setAttribute('may-have-children', '');
} else {
this.removeAttribute('may-have-children');
rowItem.removeAttribute('may-have-children');
}
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
get hasChildren() {
return !!this.items[0];
},
/**
* Whether the tree item has children.
* @type {boolean}
*/
set hasChildren(b) {
var rowItem = this.firstElementChild;
this.setAttribute('has-children', b);
rowItem.setAttribute('has-children', b);
if (b)
this.mayHaveChildren_ = true;
},
/**
* Called when the user clicks on a tree item. This is forwarded from the
* cr.ui.Tree.
* @param {Event} e The click event.
*/
handleClick: function(e) {
if (e.target.className == 'expand-icon')
this.expanded = !this.expanded;
else
this.selected = true;
},
/**
* Makes the tree item user editable. If the user renamed the item a
* bubbling {@code rename} event is fired.
* @type {boolean}
*/
set editing(editing) {
var oldEditing = this.editing;
if (editing == oldEditing)
return;
var self = this;
var labelEl = this.labelElement;
var text = this.label;
var input;
// Handles enter and escape which trigger reset and commit respectively.
function handleKeydown(e) {
// Make sure that the tree does not handle the key.
e.stopPropagation();
// Calling tree.focus blurs the input which will make the tree item
// non editable.
switch (e.keyIdentifier) {
case 'U+001B': // Esc
input.value = text;
// fall through
case 'Enter':
self.tree.focus();
}
}
function stopPropagation(e) {
e.stopPropagation();
}
if (editing) {
this.selected = true;
this.setAttribute('editing', '');
this.draggable = false;
// We create an input[type=text] and copy over the label value. When
// the input loses focus we set editing to false again.
input = this.ownerDocument.createElement('input');
input.value = text;
if (labelEl.firstChild)
labelEl.replaceChild(input, labelEl.firstChild);
else
labelEl.appendChild(input);
input.addEventListener('keydown', handleKeydown);
input.addEventListener('blur', (function() {
this.editing = false;
}).bind(this));
// Make sure that double clicks do not expand and collapse the tree
// item.
var eventsToStop = ['mousedown', 'mouseup', 'contextmenu', 'dblclick'];
eventsToStop.forEach(function(type) {
input.addEventListener(type, stopPropagation);
});
// Wait for the input element to recieve focus before sizing it.
var rowElement = this.rowElement;
function onFocus() {
input.removeEventListener('focus', onFocus);
// 20 = the padding and border of the tree-row
cr.ui.limitInputWidth(input, rowElement, 100);
}
input.addEventListener('focus', onFocus);
input.focus();
input.select();
this.oldLabel_ = text;
} else {
this.removeAttribute('editing');
this.draggable = true;
input = labelEl.firstChild;
var value = input.value;
if (/^\s*$/.test(value)) {
labelEl.textContent = this.oldLabel_;
} else {
labelEl.textContent = value;
if (value != this.oldLabel_) {
cr.dispatchSimpleEvent(this, 'rename', true);
}
}
delete this.oldLabel_;
}
},
get editing() {
return this.hasAttribute('editing');
}
};
/**
* Helper function that returns the next visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getNext(item) {
if (item.expanded) {
var firstChild = item.items[0];
if (firstChild) {
return firstChild;
}
}
return getNextHelper(item);
}
/**
* Another helper function that returns the next visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getNextHelper(item) {
if (!item)
return null;
var nextSibling = item.nextElementSibling;
if (nextSibling) {
return nextSibling;
}
return getNextHelper(item.parentItem);
}
/**
* Helper function that returns the previous visible tree item.
* @param {cr.ui.TreeItem} item The tree item.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getPrevious(item) {
var previousSibling = item.previousElementSibling;
return previousSibling ? getLastHelper(previousSibling) : item.parentItem;
}
/**
* Helper function that returns the last visible tree item in the subtree.
* @param {cr.ui.TreeItem} item The item to find the last visible item for.
* @return {cr.ui.TreeItem} The found item or null.
*/
function getLastHelper(item) {
if (!item)
return null;
if (item.expanded && item.hasChildren) {
var lastChild = item.items[item.items.length - 1];
return getLastHelper(lastChild);
}
return item;
}
// Export
return {
Tree: Tree,
TreeItem: TreeItem
};
});
| aospx-kitkat/platform_external_chromium_org | ui/webui/resources/js/cr/ui/tree.js | JavaScript | bsd-3-clause | 18,164 |
/**
* @license Highcharts JS v4.2.2 (2016-02-04)
*
* (c) 2014 Highsoft AS
* Authors: Jon Arild Nygard / Oystein Moseng
*
* License: www.highcharts.com/license
*/
(function (factory) {
if (typeof module === 'object' && module.exports) {
module.exports = factory;
} else {
factory(Highcharts);
}
}(function (H) {
var seriesTypes = H.seriesTypes,
map = H.map,
merge = H.merge,
extend = H.extend,
extendClass = H.extendClass,
defaultOptions = H.getOptions(),
plotOptions = defaultOptions.plotOptions,
noop = function () {
},
each = H.each,
grep = H.grep,
pick = H.pick,
Series = H.Series,
stableSort = H.stableSort,
Color = H.Color,
eachObject = function (list, func, context) {
var key;
context = context || this;
for (key in list) {
if (list.hasOwnProperty(key)) {
func.call(context, list[key], key, list);
}
}
},
reduce = function (arr, func, previous, context) {
context = context || this;
arr = arr || []; // @note should each be able to handle empty values automatically?
each(arr, function (current, i) {
previous = func.call(context, previous, current, i, arr);
});
return previous;
},
// @todo find correct name for this function.
recursive = function (item, func, context) {
var next;
context = context || this;
next = func.call(context, item);
if (next !== false) {
recursive(next, func, context);
}
};
// Define default options
plotOptions.treemap = merge(plotOptions.scatter, {
showInLegend: false,
marker: false,
borderColor: '#E0E0E0',
borderWidth: 1,
dataLabels: {
enabled: true,
defer: false,
verticalAlign: 'middle',
formatter: function () { // #2945
return this.point.name || this.point.id;
},
inside: true
},
tooltip: {
headerFormat: '',
pointFormat: '<b>{point.name}</b>: {point.node.val}</b><br/>'
},
layoutAlgorithm: 'sliceAndDice',
layoutStartingDirection: 'vertical',
alternateStartingDirection: false,
levelIsConstant: true,
states: {
hover: {
borderColor: '#A0A0A0',
brightness: seriesTypes.heatmap ? 0 : 0.1,
shadow: false
}
},
drillUpButton: {
position: {
align: 'right',
x: -10,
y: 10
}
}
});
// Stolen from heatmap
var colorSeriesMixin = {
// mapping between SVG attributes and the corresponding options
pointAttrToOptions: {},
pointArrayMap: ['value'],
axisTypes: seriesTypes.heatmap ? ['xAxis', 'yAxis', 'colorAxis'] : ['xAxis', 'yAxis'],
optionalAxis: 'colorAxis',
getSymbol: noop,
parallelArrays: ['x', 'y', 'value', 'colorValue'],
colorKey: 'colorValue', // Point color option key
translateColors: seriesTypes.heatmap && seriesTypes.heatmap.prototype.translateColors
};
// The Treemap series type
seriesTypes.treemap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'treemap',
trackerGroups: ['group', 'dataLabelsGroup'],
pointClass: extendClass(H.Point, {
setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible
}),
/**
* Creates an object map from parent id to childrens index.
* @param {Array} data List of points set in options.
* @param {string} data[].parent Parent id of point.
* @param {Array} ids List of all point ids.
* @return {Object} Map from parent id to children index in data.
*/
getListOfParents: function (data, ids) {
var listOfParents = reduce(data, function (prev, curr, i) {
var parent = pick(curr.parent, '');
if (prev[parent] === undefined) {
prev[parent] = [];
}
prev[parent].push(i);
return prev;
}, {});
// If parent does not exist, hoist parent to root of tree.
eachObject(listOfParents, function (children, parent, list) {
if ((parent !== '') && (H.inArray(parent, ids) === -1)) {
each(children, function (child) {
list[''].push(child);
});
delete list[parent];
}
});
return listOfParents;
},
/**
* Creates a tree structured object from the series points
*/
getTree: function () {
var tree,
series = this,
allIds = map(this.data, function (d) {
return d.id;
}),
parentList = series.getListOfParents(this.data, allIds);
series.nodeMap = [];
tree = series.buildNode('', -1, 0, parentList, null);
recursive(this.nodeMap[this.rootNode], function (node) {
var next = false,
p = node.parent;
node.visible = true;
if (p || p === '') {
next = series.nodeMap[p];
}
return next;
});
recursive(this.nodeMap[this.rootNode].children, function (children) {
var next = false;
each(children, function (child) {
child.visible = true;
if (child.children.length) {
next = (next || []).concat(child.children);
}
});
return next;
});
this.setTreeValues(tree);
return tree;
},
init: function (chart, options) {
var series = this;
Series.prototype.init.call(series, chart, options);
if (series.options.allowDrillToNode) {
series.drillTo();
}
},
buildNode: function (id, i, level, list, parent) {
var series = this,
children = [],
point = series.points[i],
node,
child;
// Actions
each((list[id] || []), function (i) {
child = series.buildNode(series.points[i].id, i, (level + 1), list, id);
children.push(child);
});
node = {
id: id,
i: i,
children: children,
level: level,
parent: parent,
visible: false // @todo move this to better location
};
series.nodeMap[node.id] = node;
if (point) {
point.node = node;
}
return node;
},
setTreeValues: function (tree) {
var series = this,
options = series.options,
childrenTotal = 0,
children = [],
val,
point = series.points[tree.i];
// First give the children some values
each(tree.children, function (child) {
child = series.setTreeValues(child);
children.push(child);
if (!child.ignore) {
childrenTotal += child.val;
} else {
// @todo Add predicate to avoid looping already ignored children
recursive(child.children, function (children) {
var next = false;
each(children, function (node) {
extend(node, {
ignore: true,
isLeaf: false,
visible: false
});
if (node.children.length) {
next = (next || []).concat(node.children);
}
});
return next;
});
}
});
// Sort the children
stableSort(children, function (a, b) {
return a.sortIndex - b.sortIndex;
});
// Set the values
val = pick(point && point.value, childrenTotal);
extend(tree, {
children: children,
childrenTotal: childrenTotal,
// Ignore this node if point is not visible
ignore: !(pick(point && point.visible, true) && (val > 0)),
isLeaf: tree.visible && !childrenTotal,
levelDynamic: (options.levelIsConstant ? tree.level : (tree.level - series.nodeMap[series.rootNode].level)),
name: pick(point && point.name, ''),
sortIndex: pick(point && point.sortIndex, -val),
val: val
});
return tree;
},
/**
* Recursive function which calculates the area for all children of a node.
* @param {Object} node The node which is parent to the children.
* @param {Object} area The rectangular area of the parent.
*/
calculateChildrenAreas: function (parent, area) {
var series = this,
options = series.options,
level = this.levelMap[parent.levelDynamic + 1],
algorithm = pick((series[level && level.layoutAlgorithm] && level.layoutAlgorithm), options.layoutAlgorithm),
alternate = options.alternateStartingDirection,
childrenValues = [],
children;
// Collect all children which should be included
children = grep(parent.children, function (n) {
return !n.ignore;
});
if (level && level.layoutStartingDirection) {
area.direction = level.layoutStartingDirection === 'vertical' ? 0 : 1;
}
childrenValues = series[algorithm](area, children);
each(children, function (child, index) {
var values = childrenValues[index];
child.values = merge(values, {
val: child.childrenTotal,
direction: (alternate ? 1 - area.direction : area.direction)
});
child.pointValues = merge(values, {
x: (values.x / series.axisRatio),
width: (values.width / series.axisRatio)
});
// If node has children, then call method recursively
if (child.children.length) {
series.calculateChildrenAreas(child, child.values);
}
});
},
setPointValues: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis;
each(series.points, function (point) {
var node = point.node,
values = node.pointValues,
x1,
x2,
y1,
y2;
// Points which is ignored, have no values.
if (values) {
x1 = Math.round(xAxis.translate(values.x, 0, 0, 0, 1));
x2 = Math.round(xAxis.translate(values.x + values.width, 0, 0, 0, 1));
y1 = Math.round(yAxis.translate(values.y, 0, 0, 0, 1));
y2 = Math.round(yAxis.translate(values.y + values.height, 0, 0, 0, 1));
// Set point values
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2);
point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2);
} else {
// Reset visibility
delete point.plotX;
delete point.plotY;
}
});
},
setColorRecursive: function (node, color) {
var series = this,
point,
level;
if (node) {
point = series.points[node.i];
level = series.levelMap[node.levelDynamic];
// Select either point color, level color or inherited color.
color = pick(point && point.options.color, level && level.color, color);
if (point) {
point.color = color;
}
// Do it all again with the children
if (node.children.length) {
each(node.children, function (child) {
series.setColorRecursive(child, color);
});
}
}
},
algorithmGroup: function (h, w, d, p) {
this.height = h;
this.width = w;
this.plot = p;
this.direction = d;
this.startDirection = d;
this.total = 0;
this.nW = 0;
this.lW = 0;
this.nH = 0;
this.lH = 0;
this.elArr = [];
this.lP = {
total: 0,
lH: 0,
nH: 0,
lW: 0,
nW: 0,
nR: 0,
lR: 0,
aspectRatio: function (w, h) {
return Math.max((w / h), (h / w));
}
};
this.addElement = function (el) {
this.lP.total = this.elArr[this.elArr.length - 1];
this.total = this.total + el;
if (this.direction === 0) {
// Calculate last point old aspect ratio
this.lW = this.nW;
this.lP.lH = this.lP.total / this.lW;
this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH);
// Calculate last point new aspect ratio
this.nW = this.total / this.height;
this.lP.nH = this.lP.total / this.nW;
this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH);
} else {
// Calculate last point old aspect ratio
this.lH = this.nH;
this.lP.lW = this.lP.total / this.lH;
this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH);
// Calculate last point new aspect ratio
this.nH = this.total / this.width;
this.lP.nW = this.lP.total / this.nH;
this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH);
}
this.elArr.push(el);
};
this.reset = function () {
this.nW = 0;
this.lW = 0;
this.elArr = [];
this.total = 0;
};
},
algorithmCalcPoints: function (directionChange, last, group, childrenArea) {
var pX,
pY,
pW,
pH,
gW = group.lW,
gH = group.lH,
plot = group.plot,
keep,
i = 0,
end = group.elArr.length - 1;
if (last) {
gW = group.nW;
gH = group.nH;
} else {
keep = group.elArr[group.elArr.length - 1];
}
each(group.elArr, function (p) {
if (last || (i < end)) {
if (group.direction === 0) {
pX = plot.x;
pY = plot.y;
pW = gW;
pH = p / pW;
} else {
pX = plot.x;
pY = plot.y;
pH = gH;
pW = p / pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (group.direction === 0) {
plot.y = plot.y + pH;
} else {
plot.x = plot.x + pW;
}
}
i = i + 1;
});
// Reset variables
group.reset();
if (group.direction === 0) {
group.width = group.width - gW;
} else {
group.height = group.height - gH;
}
plot.y = plot.parent.y + (plot.parent.height - group.height);
plot.x = plot.parent.x + (plot.parent.width - group.width);
if (directionChange) {
group.direction = 1 - group.direction;
}
// If not last, then add uncalculated element
if (!last) {
group.addElement(keep);
}
},
algorithmLowAspectRatio: function (directionChange, parent, children) {
var childrenArea = [],
series = this,
pTot,
plot = {
x: parent.x,
y: parent.y,
parent: parent
},
direction = parent.direction,
i = 0,
end = children.length - 1,
group = new this.algorithmGroup(parent.height, parent.width, direction, plot);
// Loop through and calculate all areas
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
group.addElement(pTot);
if (group.lP.nR > group.lP.lR) {
series.algorithmCalcPoints(directionChange, false, group, childrenArea, plot);
}
// If last child, then calculate all remaining areas
if (i === end) {
series.algorithmCalcPoints(directionChange, true, group, childrenArea, plot);
}
i = i + 1;
});
return childrenArea;
},
algorithmFill: function (directionChange, parent, children) {
var childrenArea = [],
pTot,
direction = parent.direction,
x = parent.x,
y = parent.y,
width = parent.width,
height = parent.height,
pX,
pY,
pW,
pH;
each(children, function (child) {
pTot = (parent.width * parent.height) * (child.val / parent.val);
pX = x;
pY = y;
if (direction === 0) {
pH = height;
pW = pTot / pH;
width = width - pW;
x = x + pW;
} else {
pW = width;
pH = pTot / pW;
height = height - pH;
y = y + pH;
}
childrenArea.push({
x: pX,
y: pY,
width: pW,
height: pH
});
if (directionChange) {
direction = 1 - direction;
}
});
return childrenArea;
},
strip: function (parent, children) {
return this.algorithmLowAspectRatio(false, parent, children);
},
squarified: function (parent, children) {
return this.algorithmLowAspectRatio(true, parent, children);
},
sliceAndDice: function (parent, children) {
return this.algorithmFill(true, parent, children);
},
stripes: function (parent, children) {
return this.algorithmFill(false, parent, children);
},
translate: function () {
var pointValues,
seriesArea,
tree,
val;
// Call prototype function
Series.prototype.translate.call(this);
// Assign variables
this.rootNode = pick(this.options.rootId, '');
// Create a object map from level to options
this.levelMap = reduce(this.options.levels, function (arr, item) {
arr[item.level] = item;
return arr;
}, {});
tree = this.tree = this.getTree(); // @todo Only if series.isDirtyData is true
// Calculate plotting values.
this.axisRatio = (this.xAxis.len / this.yAxis.len);
this.nodeMap[''].pointValues = pointValues = { x: 0, y: 0, width: 100, height: 100 };
this.nodeMap[''].values = seriesArea = merge(pointValues, {
width: (pointValues.width * this.axisRatio),
direction: (this.options.layoutStartingDirection === 'vertical' ? 0 : 1),
val: tree.val
});
this.calculateChildrenAreas(tree, seriesArea);
// Logic for point colors
if (this.colorAxis) {
this.translateColors();
} else if (!this.options.colorByPoint) {
this.setColorRecursive(this.tree, undefined);
}
// Update axis extremes according to the root node.
val = this.nodeMap[this.rootNode].pointValues;
this.xAxis.setExtremes(val.x, val.x + val.width, false);
this.yAxis.setExtremes(val.y, val.y + val.height, false);
this.xAxis.setScale();
this.yAxis.setScale();
// Assign values to points.
this.setPointValues();
},
/**
* Extend drawDataLabels with logic to handle custom options related to the treemap series:
* - Points which is not a leaf node, has dataLabels disabled by default.
* - Options set on series.levels is merged in.
* - Width of the dataLabel is set to match the width of the point shape.
*/
drawDataLabels: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
}),
options,
level;
each(points, function (point) {
level = series.levelMap[point.node.levelDynamic];
// Set options to new object to avoid problems with scope
options = { style: {} };
// If not a leaf, then label should be disabled as default
if (!point.node.isLeaf) {
options.enabled = false;
}
// If options for level exists, include them as well
if (level && level.dataLabels) {
options = merge(options, level.dataLabels);
series._hasPointLabels = true;
}
// Set dataLabel width to the width of the point shape.
if (point.shapeArgs) {
options.style.width = point.shapeArgs.width;
}
// Merge custom options with point options
point.dlOptions = merge(options, point.options.dataLabels);
});
Series.prototype.drawDataLabels.call(this);
},
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
/**
* Get presentational attributes
*/
pointAttribs: function (point, state) {
var level = this.levelMap[point.node.levelDynamic] || {},
options = this.options,
attr,
stateOptions = (state && options.states[state]) || {};
// Set attributes by precedence. Point trumps level trumps series. Stroke width uses pick
// because it can be 0.
attr = {
'stroke': point.borderColor || level.borderColor || stateOptions.borderColor || options.borderColor,
'stroke-width': pick(point.borderWidth, level.borderWidth, stateOptions.borderWidth, options.borderWidth),
'dashstyle': point.borderDashStyle || level.borderDashStyle || stateOptions.borderDashStyle || options.borderDashStyle,
'fill': point.color || this.color,
'zIndex': state === 'hover' ? 1 : 0
};
if (point.node.level <= this.nodeMap[this.rootNode].level) {
// Hide levels above the current view
attr.fill = 'none';
attr['stroke-width'] = 0;
} else if (!point.node.isLeaf) {
// If not a leaf, then remove fill
// @todo let users set the opacity
attr.fill = pick(options.interactByLeaf, !options.allowDrillToNode) ? 'none' : Color(attr.fill).setOpacity(state === 'hover' ? 0.75 : 0.15).get();
} else if (state) {
// Brighten and hoist the hover nodes
attr.fill = Color(attr.fill).brighten(stateOptions.brightness).get();
}
return attr;
},
/**
* Extending ColumnSeries drawPoints
*/
drawPoints: function () {
var series = this,
points = grep(series.points, function (n) {
return n.node.visible;
});
each(points, function (point) {
var groupKey = 'levelGroup-' + point.node.levelDynamic;
if (!series[groupKey]) {
series[groupKey] = series.chart.renderer.g(groupKey)
.attr({
zIndex: 1000 - point.node.levelDynamic // @todo Set the zIndex based upon the number of levels, instead of using 1000
})
.add(series.group);
}
point.group = series[groupKey];
// Preliminary code in prepraration for HC5 that uses pointAttribs for all series
point.pointAttr = {
'': series.pointAttribs(point),
'hover': series.pointAttribs(point, 'hover'),
'select': {}
};
});
// Call standard drawPoints
seriesTypes.column.prototype.drawPoints.call(this);
// If drillToNode is allowed, set a point cursor on clickables & add drillId to point
if (series.options.allowDrillToNode) {
each(points, function (point) {
var cursor,
drillId;
if (point.graphic) {
drillId = point.drillId = series.options.interactByLeaf ? series.drillToByLeaf(point) : series.drillToByGroup(point);
cursor = drillId ? 'pointer' : 'default';
point.graphic.css({ cursor: cursor });
}
});
}
},
/**
* Add drilling on the suitable points
*/
drillTo: function () {
var series = this;
H.addEvent(series, 'click', function (event) {
var point = event.point,
drillId = point.drillId,
drillName;
// If a drill id is returned, add click event and cursor.
if (drillId) {
drillName = series.nodeMap[series.rootNode].name || series.rootNode;
point.setState(''); // Remove hover
series.drillToNode(drillId);
series.showDrillUpButton(drillName);
}
});
},
/**
* Finds the drill id for a parent node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByGroup: function (point) {
var series = this,
drillId = false;
if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.node.isLeaf) {
drillId = point.id;
}
return drillId;
},
/**
* Finds the drill id for a leaf node.
* Returns false if point should not have a click event
* @param {Object} point
* @return {string || boolean} Drill to id or false when point should not have a click event
*/
drillToByLeaf: function (point) {
var series = this,
drillId = false,
nodeParent;
if ((point.node.parent !== series.rootNode) && (point.node.isLeaf)) {
nodeParent = point.node;
while (!drillId) {
nodeParent = series.nodeMap[nodeParent.parent];
if (nodeParent.parent === series.rootNode) {
drillId = nodeParent.id;
}
}
}
return drillId;
},
drillUp: function () {
var drillPoint = null,
node,
parent;
if (this.rootNode) {
node = this.nodeMap[this.rootNode];
if (node.parent !== null) {
drillPoint = this.nodeMap[node.parent];
} else {
drillPoint = this.nodeMap[''];
}
}
if (drillPoint !== null) {
this.drillToNode(drillPoint.id);
if (drillPoint.id === '') {
this.drillUpButton = this.drillUpButton.destroy();
} else {
parent = this.nodeMap[drillPoint.parent];
this.showDrillUpButton((parent.name || parent.id));
}
}
},
drillToNode: function (id) {
this.options.rootId = id;
this.isDirty = true; // Force redraw
this.chart.redraw();
},
showDrillUpButton: function (name) {
var series = this,
backText = (name || '< Back'),
buttonOptions = series.options.drillUpButton,
attr,
states;
if (buttonOptions.text) {
backText = buttonOptions.text;
}
if (!this.drillUpButton) {
attr = buttonOptions.theme;
states = attr && attr.states;
this.drillUpButton = this.chart.renderer.button(
backText,
null,
null,
function () {
series.drillUp();
},
attr,
states && states.hover,
states && states.select
)
.attr({
align: buttonOptions.position.align,
zIndex: 9
})
.add()
.align(buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox');
} else {
this.drillUpButton.attr({
text: backText
})
.align();
}
},
buildKDTree: noop,
drawLegendSymbol: H.LegendSymbolMixin.drawRectangle,
getExtremes: function () {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.colorValueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
},
getExtremesFromAll: true,
bindAxes: function () {
var treeAxis = {
endOnTick: false,
gridLineWidth: 0,
lineWidth: 0,
min: 0,
dataMin: 0,
minPadding: 0,
max: 100,
dataMax: 100,
maxPadding: 0,
startOnTick: false,
title: null,
tickPositions: []
};
Series.prototype.bindAxes.call(this);
H.extend(this.yAxis.options, treeAxis);
H.extend(this.xAxis.options, treeAxis);
}
}));
}));
| morsaken/webim-cms | views/backend/default/layouts/js/plugins/highcharts/modules/treemap.src.js | JavaScript | mit | 24,507 |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.stresstest.indexing;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import java.util.concurrent.ThreadLocalRandom;
/**
*/
public class BulkIndexingStressTest {
public static void main(String[] args) {
final int NUMBER_OF_NODES = 4;
final int NUMBER_OF_INDICES = 600;
final int BATCH = 300;
final Settings nodeSettings = ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2).build();
// ESLogger logger = Loggers.getLogger("org.elasticsearch");
// logger.setLevel("DEBUG");
Node[] nodes = new Node[NUMBER_OF_NODES];
for (int i = 0; i < nodes.length; i++) {
nodes[i] = NodeBuilder.nodeBuilder().settings(nodeSettings).node();
}
Client client = nodes.length == 1 ? nodes[0].client() : nodes[1].client();
while (true) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (int i = 0; i < BATCH; i++) {
bulkRequest.add(Requests.indexRequest("test" + ThreadLocalRandom.current().nextInt(NUMBER_OF_INDICES)).type("type").source("field", "value"));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
for (BulkItemResponse item : bulkResponse) {
if (item.isFailed()) {
System.out.println("failed response:" + item.getFailureMessage());
}
}
throw new RuntimeException("Failed responses");
}
;
}
}
}
| corochoone/elasticsearch | src/test/java/org/elasticsearch/stresstest/indexing/BulkIndexingStressTest.java | Java | apache-2.0 | 2,807 |
/*!
* inferno-router v0.7.14
* (c) 2016 Dominic Gannaway
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoRouter = factory());
}(this, function () { 'use strict';
var NO_RENDER = 'NO_RENDER';
// Runs only once in applications lifetime
var isBrowser = typeof window !== 'undefined' && window.document;
function isArray(obj) {
return obj instanceof Array;
}
function isNullOrUndefined(obj) {
return isUndefined(obj) || isNull(obj);
}
function isNull(obj) {
return obj === null;
}
function isUndefined(obj) {
return obj === undefined;
}
function VNode(blueprint) {
this.bp = blueprint;
this.dom = null;
this.instance = null;
this.tag = null;
this.children = null;
this.style = null;
this.className = null;
this.attrs = null;
this.events = null;
this.hooks = null;
this.key = null;
this.clipData = null;
}
VNode.prototype = {
setAttrs: function setAttrs(attrs) {
this.attrs = attrs;
return this;
},
setTag: function setTag(tag) {
this.tag = tag;
return this;
},
setStyle: function setStyle(style) {
this.style = style;
return this;
},
setClassName: function setClassName(className) {
this.className = className;
return this;
},
setChildren: function setChildren(children) {
this.children = children;
return this;
},
setHooks: function setHooks(hooks) {
this.hooks = hooks;
return this;
},
setEvents: function setEvents(events) {
this.events = events;
return this;
},
setKey: function setKey(key) {
this.key = key;
return this;
}
};
function createVNode(bp) {
return new VNode(bp);
}
function VPlaceholder() {
this.placeholder = true;
this.dom = null;
}
function createVPlaceholder() {
return new VPlaceholder();
}
function constructDefaults(string, object, value) {
/* eslint no-return-assign: 0 */
string.split(',').forEach(function (i) { return object[i] = value; });
}
var xlinkNS = 'http://www.w3.org/1999/xlink';
var xmlNS = 'http://www.w3.org/XML/1998/namespace';
var strictProps = {};
var booleanProps = {};
var namespaces = {};
var isUnitlessNumber = {};
constructDefaults('xlink:href,xlink:arcrole,xlink:actuate,xlink:role,xlink:titlef,xlink:type', namespaces, xlinkNS);
constructDefaults('xml:base,xml:lang,xml:space', namespaces, xmlNS);
constructDefaults('volume,value', strictProps, true);
constructDefaults('muted,scoped,loop,open,checked,default,capture,disabled,selected,readonly,multiple,required,autoplay,controls,seamless,reversed,allowfullscreen,novalidate', booleanProps, true);
constructDefaults('animationIterationCount,borderImageOutset,borderImageSlice,borderImageWidth,boxFlex,boxFlexGroup,boxOrdinalGroup,columnCount,flex,flexGrow,flexPositive,flexShrink,flexNegative,flexOrder,gridRow,gridColumn,fontWeight,lineClamp,lineHeight,opacity,order,orphans,tabSize,widows,zIndex,zoom,fillOpacity,floodOpacity,stopOpacity,strokeDasharray,strokeDashoffset,strokeMiterlimit,strokeOpacity,strokeWidth,', isUnitlessNumber, true);
var screenWidth = isBrowser && window.screen.width;
var screenHeight = isBrowser && window.screen.height;
var scrollX = 0;
var scrollY = 0;
var lastScrollTime = 0;
if (isBrowser) {
window.onscroll = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
lastScrollTime = performance.now();
};
window.resize = function () {
scrollX = window.scrollX;
scrollY = window.scrollY;
screenWidth = window.screen.width;
screenHeight = window.screen.height;
lastScrollTime = performance.now();
};
}
function Lifecycle() {
this._listeners = [];
this.scrollX = null;
this.scrollY = null;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
}
Lifecycle.prototype = {
refresh: function refresh() {
this.scrollX = isBrowser && window.scrollX;
this.scrollY = isBrowser && window.scrollY;
},
addListener: function addListener(callback) {
this._listeners.push(callback);
},
trigger: function trigger() {
var this$1 = this;
for (var i = 0; i < this._listeners.length; i++) {
this$1._listeners[i]();
}
}
};
var noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.';
// Copy of the util from dom/util, otherwise it makes massive bundles
function getActiveNode() {
return document.activeElement;
}
// Copy of the util from dom/util, otherwise it makes massive bundles
function resetActiveNode(activeNode) {
if (activeNode !== document.body && document.activeElement !== activeNode) {
activeNode.focus(); // TODO: verify are we doing new focus event, if user has focus listener this might trigger it
}
}
function queueStateChanges(component, newState, callback) {
for (var stateKey in newState) {
component._pendingState[stateKey] = newState[stateKey];
}
if (!component._pendingSetState) {
component._pendingSetState = true;
applyState(component, false, callback);
} else {
var pendingState = component._pendingState;
var oldState = component.state;
component.state = Object.assign({}, oldState, pendingState);
component._pendingState = {};
}
}
function applyState(component, force, callback) {
if (!component._deferSetState || force) {
component._pendingSetState = false;
var pendingState = component._pendingState;
var oldState = component.state;
var nextState = Object.assign({}, oldState, pendingState);
component._pendingState = {};
var nextNode = component._updateComponent(oldState, nextState, component.props, component.props, force);
if (nextNode === NO_RENDER) {
nextNode = component._lastNode;
} else if (isNullOrUndefined(nextNode)) {
nextNode = createVPlaceholder();
}
var lastNode = component._lastNode;
var parentDom = lastNode.dom.parentNode;
var activeNode = getActiveNode();
var subLifecycle = new Lifecycle();
component._patch(lastNode, nextNode, parentDom, subLifecycle, component.context, component, null);
component._lastNode = nextNode;
component._componentToDOMNodeMap.set(component, nextNode.dom);
component._parentNode.dom = nextNode.dom;
subLifecycle.trigger();
if (!isNullOrUndefined(callback)) {
callback();
}
resetActiveNode(activeNode);
}
}
var Component = function Component(props) {
/** @type {object} */
this.props = props || {};
/** @type {object} */
this.state = {};
/** @type {object} */
this.refs = {};
this._blockSetState = false;
this._deferSetState = false;
this._pendingSetState = false;
this._pendingState = {};
this._parentNode = null;
this._lastNode = null;
this._unmounted = true;
this.context = {};
this._patch = null;
this._parentComponent = null;
this._componentToDOMNodeMap = null;
};
Component.prototype.render = function render () {
};
Component.prototype.forceUpdate = function forceUpdate (callback) {
if (this._unmounted) {
throw Error(noOp);
}
applyState(this, true, callback);
};
Component.prototype.setState = function setState (newState, callback) {
if (this._unmounted) {
throw Error(noOp);
}
if (this._blockSetState === false) {
queueStateChanges(this, newState, callback);
} else {
throw Error('Inferno Warning: Cannot update state via setState() in componentWillUpdate()');
}
};
Component.prototype.componentDidMount = function componentDidMount () {
};
Component.prototype.componentWillMount = function componentWillMount () {
};
Component.prototype.componentWillUnmount = function componentWillUnmount () {
};
Component.prototype.componentDidUpdate = function componentDidUpdate () {
};
Component.prototype.shouldComponentUpdate = function shouldComponentUpdate () {
return true;
};
Component.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
};
Component.prototype.componentWillUpdate = function componentWillUpdate () {
};
Component.prototype.getChildContext = function getChildContext () {
};
Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, force) {
if (this._unmounted === true) {
this._unmounted = false;
return false;
}
if (!isNullOrUndefined(nextProps) && isNullOrUndefined(nextProps.children)) {
nextProps.children = prevProps.children;
}
if (prevProps !== nextProps || prevState !== nextState || force) {
if (prevProps !== nextProps) {
this._blockSetState = true;
this.componentWillReceiveProps(nextProps);
this._blockSetState = false;
}
var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState);
if (shouldUpdate !== false) {
this._blockSetState = true;
this.componentWillUpdate(nextProps, nextState);
this._blockSetState = false;
this.props = nextProps;
this.state = nextState;
var node = this.render();
this.componentDidUpdate(prevProps, prevState);
return node;
}
}
return NO_RENDER;
};
var ASYNC_STATUS = {
pending: 'pending',
fulfilled: 'fulfilled',
rejected: 'rejected'
};
var Route = (function (Component) {
function Route(props) {
Component.call(this, props);
this.state = {
async: null
};
}
if ( Component ) Route.__proto__ = Component;
Route.prototype = Object.create( Component && Component.prototype );
Route.prototype.constructor = Route;
Route.prototype.async = function async () {
var this$1 = this;
var async = this.props.async;
if (async) {
this.setState({
async: { status: ASYNC_STATUS.pending }
});
async(this.props.params).then(function (value) {
this$1.setState({
async: {
status: ASYNC_STATUS.fulfilled,
value: value
}
});
}, this.reject).catch(this.reject);
}
};
Route.prototype.reject = function reject (value) {
this.setState({
async: {
status: ASYNC_STATUS.rejected,
value: value
}
});
};
Route.prototype.componentWillReceiveProps = function componentWillReceiveProps () {
this.async();
};
Route.prototype.componentWillMount = function componentWillMount () {
this.async();
};
Route.prototype.render = function render () {
var ref = this.props;
var component = ref.component;
var params = ref.params;
return createVNode().setTag(component).setAttrs({ params: params, async: this.state.async });
};
return Route;
}(Component));
var EMPTY$1 = {};
function segmentize(url) {
return strip(url).split('/');
}
function strip(url) {
return url.replace(/(^\/+|\/+$)/g, '');
}
function convertToHashbang(url) {
if (url.indexOf('#') === -1) {
url = '/';
} else {
var splitHashUrl = url.split('#!');
splitHashUrl.shift();
url = splitHashUrl.join('');
}
return url;
}
// Thanks goes to Preact for this function: https://github.com/developit/preact-router/blob/master/src/util.js#L4
function exec(url, route, opts) {
if ( opts === void 0 ) opts = EMPTY$1;
var reg = /(?:\?([^#]*))?(#.*)?$/,
c = url.match(reg),
matches = {},
ret;
if (c && c[1]) {
var p = c[1].split('&');
for (var i = 0; i < p.length; i++) {
var r = p[i].split('=');
matches[decodeURIComponent(r[0])] = decodeURIComponent(r.slice(1).join('='));
}
}
url = segmentize(url.replace(reg, ''));
route = segmentize(route || '');
var max = Math.max(url.length, route.length);
var hasWildcard = false;
for (var i$1 = 0; i$1 < max; i$1++) {
if (route[i$1] && route[i$1].charAt(0) === ':') {
var param = route[i$1].replace(/(^\:|[+*?]+$)/g, ''),
flags = (route[i$1].match(/[+*?]+$/) || EMPTY$1)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = url[i$1] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = url.slice(i$1).map(decodeURIComponent).join('/');
break;
}
}
else if (route[i$1] !== url[i$1] && !hasWildcard) {
if (route[i$1] === '*' && route.length === i$1 + 1) {
hasWildcard = true;
} else {
ret = false;
break;
}
}
}
if (opts.default !== true && ret === false) {
return false;
}
return matches;
}
function pathRankSort(a, b) {
var aAttr = a.attrs || EMPTY$1,
bAttr = b.attrs || EMPTY$1;
var diff = rank(bAttr.path) - rank(aAttr.path);
return diff || (bAttr.path.length - aAttr.path.length);
}
function rank(url) {
return (strip(url).match(/\/+/g) || '').length;
}
var Router = (function (Component) {
function Router(props) {
Component.call(this, props);
if (!props.history) {
throw new Error('Inferno Error: "inferno-router" Router components require a "history" prop passed.');
}
this._didRoute = false;
this.state = {
url: props.url || props.history.getCurrentUrl()
};
}
if ( Component ) Router.__proto__ = Component;
Router.prototype = Object.create( Component && Component.prototype );
Router.prototype.constructor = Router;
Router.prototype.getChildContext = function getChildContext () {
return {
history: this.props.history,
hashbang: this.props.hashbang
};
};
Router.prototype.componentWillMount = function componentWillMount () {
this.props.history.addRouter(this);
};
Router.prototype.componentWillUnmount = function componentWillUnmount () {
this.props.history.removeRouter(this);
};
Router.prototype.routeTo = function routeTo (url) {
this._didRoute = false;
this.setState({ url: url });
return this._didRoute;
};
Router.prototype.render = function render () {
var children = toArray(this.props.children);
var url = this.props.url || this.state.url;
var wrapperComponent = this.props.component;
var hashbang = this.props.hashbang;
return handleRoutes(children, url, hashbang, wrapperComponent, '');
};
return Router;
}(Component));
function toArray(children) {
return isArray(children) ? children : (children ? [children] : children);
}
function handleRoutes(routes, url, hashbang, wrapperComponent, lastPath) {
routes.sort(pathRankSort);
for (var i = 0; i < routes.length; i++) {
var route = routes[i];
var ref = route.attrs;
var path = ref.path;
var fullPath = lastPath + path;
var params = exec(hashbang ? convertToHashbang(url) : url, fullPath);
var children = toArray(route.children);
if (children) {
var subRoute = handleRoutes(children, url, hashbang, wrapperComponent, fullPath);
if (!isNull(subRoute)) {
return subRoute;
}
}
if (params) {
if (wrapperComponent) {
return createVNode().setTag(wrapperComponent).setChildren(route).setAttrs({
params: params
});
}
return route.setAttrs(Object.assign({}, { params: params }, route.attrs));
}
}
return !lastPath && wrapperComponent ? createVNode().setTag(wrapperComponent) : null;
}
function Link(ref, ref$1) {
var to = ref.to;
var children = ref.children;
var hashbang = ref$1.hashbang;
var history = ref$1.history;
return (createVNode().setAttrs({
href: hashbang ? history.getHashbangRoot() + convertToHashbang('#!' + to) : to
}).setTag('a').setChildren(children));
}
var routers = [];
function getCurrentUrl() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.pathname || '') + (url.search || '') + (url.hash || ''));
}
function getHashbangRoot() {
var url = typeof location !== 'undefined' ? location : EMPTY;
return ("" + (url.protocol + '//' || '') + (url.host || '') + (url.pathname || '') + (url.search || '') + "#!");
}
function routeTo(url) {
var didRoute = false;
for (var i = 0; i < routers.length; i++) {
if (routers[i].routeTo(url) === true) {
didRoute = true;
}
}
return didRoute;
}
if (isBrowser) {
window.addEventListener('popstate', function () { return routeTo(getCurrentUrl()); });
}
var browserHistory = {
addRouter: function addRouter(router) {
routers.push(router);
},
removeRouter: function removeRouter(router) {
routers.splice(routers.indexOf(router), 1);
},
getCurrentUrl: getCurrentUrl,
getHashbangRoot: getHashbangRoot
};
var index = {
Route: Route,
Router: Router,
Link: Link,
browserHistory: browserHistory
};
return index;
})); | dlueth/cdnjs | ajax/libs/inferno/0.7.14/inferno-router.js | JavaScript | mit | 18,182 |
# Requiring test environment file
require 'spec_helper'
# Requiring test subject file
require_relative File.join(APP_CONTROLLERS, "static")
# Test cases
describe 'Routing for root' do
it "has ok response when get '/' is called." do
get '/'
expect(last_response).to be_ok
end
end | hollowaykeanho/airbnb-accessment | spec/static_spec.rb | Ruby | mit | 286 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/clusters/utils.h"
#include "third_party/eigen3/Eigen/Core"
#if GOOGLE_CUDA
#include "cuda/include/cuda.h"
#include "cuda/include/cuda_runtime_api.h"
#include "cuda/include/cudnn.h"
#endif
#ifdef EIGEN_USE_LIBXSMM
#include "include/libxsmm.h"
#endif
#include "tensorflow/core/lib/strings/numbers.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/cpu_info.h"
namespace tensorflow {
namespace grappler {
DeviceProperties GetLocalCPUInfo() {
DeviceProperties device;
device.set_type("CPU");
device.set_vendor(port::CPUVendorIDString());
// Combine cpu family and model into the model string.
device.set_model(
strings::StrCat((port::CPUFamily() << 4) + port::CPUModelNum()));
device.set_frequency(port::NominalCPUFrequency() * 1e-6);
device.set_num_cores(port::NumSchedulableCPUs());
device.set_l1_cache_size(Eigen::l1CacheSize());
device.set_l2_cache_size(Eigen::l2CacheSize());
device.set_l3_cache_size(Eigen::l3CacheSize());
(*device.mutable_environment())["cpu_instruction_set"] =
Eigen::SimdInstructionSetsInUse();
(*device.mutable_environment())["eigen"] = strings::StrCat(
EIGEN_WORLD_VERSION, ".", EIGEN_MAJOR_VERSION, ".", EIGEN_MINOR_VERSION);
#ifdef EIGEN_USE_LIBXSMM
(*device.mutable_environment())["libxsmm"] = LIBXSMM_VERSION;
#endif
return device;
}
DeviceProperties GetLocalGPUInfo(int gpu_id) {
DeviceProperties device;
device.set_type("GPU");
#if GOOGLE_CUDA
cudaDeviceProp properties;
cudaError_t error = cudaGetDeviceProperties(&properties, gpu_id);
if (error == cudaSuccess) {
device.set_vendor("NVidia");
device.set_model(properties.name);
device.set_frequency(properties.clockRate * 1e-3);
device.set_num_cores(properties.multiProcessorCount);
device.set_num_registers(properties.regsPerMultiprocessor);
// For compute capability less than 5, l1 cache size is configurable to
// either 16 KB or 48 KB. We use the initial configuration 16 KB here. For
// compute capability larger or equal to 5, l1 cache (unified with texture
// cache) size is 24 KB. This number may need to be updated for future
// compute capabilities.
device.set_l1_cache_size((properties.major < 5) ? 16 * 1024 : 24 * 1024);
device.set_l2_cache_size(properties.l2CacheSize);
device.set_l3_cache_size(0);
device.set_shared_memory_size_per_multiprocessor(
properties.sharedMemPerMultiprocessor);
device.set_memory_size(properties.totalGlobalMem);
// 8 is the number of bits per byte. 2 is accounted for
// double data rate (DDR).
device.set_bandwidth(properties.memoryBusWidth / 8 *
properties.memoryClockRate * 2);
}
(*device.mutable_environment())["architecture"] =
strings::StrCat(properties.major, ".", properties.minor);
(*device.mutable_environment())["cuda"] = strings::StrCat(CUDA_VERSION);
(*device.mutable_environment())["cudnn"] = strings::StrCat(CUDNN_VERSION);
#endif
return device;
}
DeviceProperties GetDeviceInfo(const DeviceNameUtils::ParsedName& device) {
if (device.type == "CPU") {
return GetLocalCPUInfo();
} else if (device.type == "GPU") {
if (device.has_id) {
return GetLocalGPUInfo(device.id);
} else {
return GetLocalGPUInfo(0);
}
}
DeviceProperties result;
result.set_type("UNKNOWN");
return result;
}
} // end namespace grappler
} // end namespace tensorflow
| npuichigo/ttsflow | third_party/tensorflow/tensorflow/core/grappler/clusters/utils.cc | C++ | apache-2.0 | 4,151 |
<?php
/**
* @file
* Contains \Drupal\filter\FilterProcessResult.
*/
namespace Drupal\filter;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Core\Template\Attribute;
/**
* Used to return values from a text filter plugin's processing method.
*
* The typical use case for a text filter plugin's processing method is to just
* apply some filtering to the given text, but for more advanced use cases,
* it may be necessary to also:
* - Declare asset libraries to be loaded.
* - Declare cache tags that the filtered text depends upon, so when either of
* those cache tags is invalidated, the filtered text should also be
* invalidated.
* - Declare cache context to vary by, e.g. 'language' to do language-specific
* filtering.
* - Declare a maximum age for the filtered text.
* - Apply uncacheable filtering, for example because it differs per user.
*
* In case a filter needs one or more of these advanced use cases, it can use
* the additional methods available.
*
* The typical use case:
* @code
* public function process($text, $langcode) {
* // Modify $text.
*
* return new FilterProcess($text);
* }
* @endcode
*
* The advanced use cases:
* @code
* public function process($text, $langcode) {
* // Modify $text.
*
* $result = new FilterProcess($text);
*
* // Associate assets to be attached.
* $result->setAttachments(array(
* 'library' => array(
* 'filter/caption',
* ),
* ));
*
* // Associate cache contexts to vary by.
* $result->setCacheContexts(['language']);
*
* // Associate cache tags to be invalidated by.
* $result->setCacheTags($node->getCacheTags());
*
* // Associate a maximum age.
* $result->setCacheMaxAge(300); // 5 minutes.
*
* return $result;
* }
* @endcode
*/
class FilterProcessResult extends BubbleableMetadata {
/**
* The processed text.
*
* @see \Drupal\filter\Plugin\FilterInterface::process()
*
* @var string
*/
protected $processedText;
/**
* Constructs a FilterProcessResult object.
*
* @param string $processed_text
* The text as processed by a text filter.
*/
public function __construct($processed_text) {
$this->processedText = $processed_text;
}
/**
* Gets the processed text.
*
* @return string
*/
public function getProcessedText() {
return $this->processedText;
}
/**
* Gets the processed text.
*
* @return string
*/
public function __toString() {
return $this->getProcessedText();
}
/**
* Sets the processed text.
*
* @param string $processed_text
* The text as processed by a text filter.
*
* @return $this
*/
public function setProcessedText($processed_text) {
$this->processedText = $processed_text;
return $this;
}
/**
* Creates a placeholder.
*
* This generates its own placeholder markup for one major reason: to not have
* FilterProcessResult depend on the Renderer service, because this is a value
* object. As a side-effect and added benefit, this makes it easier to
* distinguish placeholders for filtered text versus generic render system
* placeholders.
*
* @param string $callback
* The #lazy_builder callback that will replace the placeholder with its
* eventual markup.
* @param array $args
* The arguments for the #lazy_builder callback.
*
* @return string
* The placeholder markup.
*/
public function createPlaceholder($callback, array $args) {
// Generate placeholder markup.
// @see \Drupal\Core\Render\Renderer::createPlaceholder()
$attributes = new Attribute();
$attributes['callback'] = $callback;
$attributes['arguments'] = UrlHelper::buildQuery($args);
$attributes['token'] = hash('sha1', serialize([$callback, $args]));
$placeholder_markup = Html::normalize('<drupal-filter-placeholder' . $attributes . '></drupal-filter-placeholder>');
// Add the placeholder attachment.
$this->addAttachments([
'placeholders' => [
$placeholder_markup => [
'#lazy_builder' => [$callback, $args],
]
],
]);
// Return the placeholder markup, so that the filter wanting to use a
// placeholder can actually insert the placeholder markup where it needs the
// placeholder to be replaced.
return $placeholder_markup;
}
}
| komejo/d8demo-dev | web/core/modules/filter/src/FilterProcessResult.php | PHP | mit | 4,448 |
/**
* React Starter Kit (http://www.reactstarterkit.com/)
*
* Copyright © 2014-2015 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import path from 'path';
import cp from 'child_process';
/**
* Launches Node.js/Express web server in a separate (forked) process.
*/
export default () => new Promise((resolve, reject) => {
console.log('serve');
const server = cp.fork(path.join(__dirname, '../build/server.js'), {
env: Object.assign({NODE_ENV: 'development'}, process.env)
});
server.once('message', message => {
if (message.match(/^online$/)) {
resolve();
}
});
server.once('error', err => reject(error));
process.on('exit', () => server.kill('SIGTERM'));
});
| SFDevLabs/react-starter-kit | tools/serve.js | JavaScript | mit | 825 |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.maps.android;
import static java.lang.Math.*;
/**
* Utility functions that are used my both PolyUtil and SphericalUtil.
*/
class MathUtil {
/**
* The earth's radius, in meters.
* Mean radius as defined by IUGG.
*/
static final double EARTH_RADIUS = 6371009;
/**
* Restrict x to the range [low, high].
*/
static double clamp(double x, double low, double high) {
return x < low ? low : (x > high ? high : x);
}
/**
* Wraps the given value into the inclusive-exclusive interval between min and max.
* @param n The value to wrap.
* @param min The minimum.
* @param max The maximum.
*/
static double wrap(double n, double min, double max) {
return (n >= min && n < max) ? n : (mod(n - min, max - min) + min);
}
/**
* Returns the non-negative remainder of x / m.
* @param x The operand.
* @param m The modulus.
*/
static double mod(double x, double m) {
return ((x % m) + m) % m;
}
/**
* Returns mercator Y corresponding to latitude.
* See http://en.wikipedia.org/wiki/Mercator_projection .
*/
static double mercator(double lat) {
return log(tan(lat * 0.5 + PI/4));
}
/**
* Returns latitude from mercator Y.
*/
static double inverseMercator(double y) {
return 2 * atan(exp(y)) - PI / 2;
}
/**
* Returns haversine(angle-in-radians).
* hav(x) == (1 - cos(x)) / 2 == sin(x / 2)^2.
*/
static double hav(double x) {
double sinHalf = sin(x * 0.5);
return sinHalf * sinHalf;
}
/**
* Computes inverse haversine. Has good numerical stability around 0.
* arcHav(x) == acos(1 - 2 * x) == 2 * asin(sqrt(x)).
* The argument must be in [0, 1], and the result is positive.
*/
static double arcHav(double x) {
return 2 * asin(sqrt(x));
}
// Given h==hav(x), returns sin(abs(x)).
static double sinFromHav(double h) {
return 2 * sqrt(h * (1 - h));
}
// Returns hav(asin(x)).
static double havFromSin(double x) {
double x2 = x * x;
return x2 / (1 + sqrt(1 - x2)) * .5;
}
// Returns sin(arcHav(x) + arcHav(y)).
static double sinSumFromHav(double x, double y) {
double a = sqrt(x * (1 - x));
double b = sqrt(y * (1 - y));
return 2 * (a + b - 2 * (a * y + b * x));
}
/**
* Returns hav() of distance from (lat1, lng1) to (lat2, lng2) on the unit sphere.
*/
static double havDistance(double lat1, double lat2, double dLng) {
return hav(lat1 - lat2) + hav(dLng) * cos(lat1) * cos(lat2);
}
}
| davidmrtz/TrackingApp | myMapa/library/src/com/google/maps/android/MathUtil.java | Java | apache-2.0 | 3,305 |
/**
* Copyright (c) 2010-2015, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.maxcube.internal.exceptions;
/**
* Will be thrown when there is an attempt to put a new message line into the message processor,
* but the processor is currently processing an other message type.
*
* @author Christian Rockrohr <christian@rockrohr.de>
*/
public class IncorrectMultilineIndexException extends Exception {
private static final long serialVersionUID = -2261755876987011907L;
}
| cyclingengineer/UpnpHomeAutomationBridge | src/org/openhab/binding/maxcube/internal/exceptions/IncorrectMultilineIndexException.java | Java | epl-1.0 | 737 |
// Copyright John Maddock 2007.
// Copyright Paul A. Bristow 2010.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Note that this file contains quickbook mark-up as well as code
// and comments, don't change any of the special comment mark-ups!
//[policy_ref_snip7
#include <boost/math/distributions/negative_binomial.hpp>
using boost::math::negative_binomial_distribution;
using namespace boost::math::policies;
typedef negative_binomial_distribution<
double,
policy<discrete_quantile<integer_round_inwards> >
> dist_type;
// Lower quantile rounded up:
double x = quantile(dist_type(20, 0.3), 0.05); // 28 rounded up from 27.3898
// Upper quantile rounded down:
double y = quantile(complement(dist_type(20, 0.3), 0.05)); // 68 rounded down from 68.1584
//] //[/policy_ref_snip7]
#include <iostream>
using std::cout; using std::endl;
int main()
{
cout << "using policy<discrete_quantile<integer_round_inwards> > " << endl
<< "quantile(dist_type(20, 0.3), 0.05) = " << x << endl
<< "quantile(complement(dist_type(20, 0.3), 0.05)) = " << y << endl;
}
/*
Output:
using policy<discrete_quantile<integer_round_inwards> >
quantile(dist_type(20, 0.3), 0.05) = 28
quantile(complement(dist_type(20, 0.3), 0.05)) = 68
*/
| NixaSoftware/CVis | venv/bin/libs/math/example/policy_ref_snip7.cpp | C++ | apache-2.0 | 1,412 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import java.io.IOException;
/**
* For sharing between the local and remote block reader implementations.
*/
class BlockReaderUtil {
/* See {@link BlockReader#readAll(byte[], int, int)} */
public static int readAll(BlockReader reader,
byte[] buf, int offset, int len) throws IOException {
int n = 0;
for (;;) {
int nread = reader.read(buf, offset + n, len - n);
if (nread <= 0)
return (n == 0) ? nread : n;
n += nread;
if (n >= len)
return n;
}
}
/* See {@link BlockReader#readFully(byte[], int, int)} */
public static void readFully(BlockReader reader,
byte[] buf, int off, int len) throws IOException {
int toRead = len;
while (toRead > 0) {
int ret = reader.read(buf, off, toRead);
if (ret < 0) {
throw new IOException("Premature EOF from inputStream");
}
toRead -= ret;
off += ret;
}
}
} | tseen/Federated-HDFS | tseenliu/FedHDFS-hadoop-src/hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/BlockReaderUtil.java | Java | apache-2.0 | 1,761 |
require File.expand_path('../../../spec_helper', __FILE__)
require 'bigdecimal'
describe "BigDecimal#remainder" do
before(:each) do
@zero = BigDecimal("0")
@one = BigDecimal("0")
@mixed = BigDecimal("1.23456789")
@pos_int = BigDecimal("2E5555")
@neg_int = BigDecimal("-2E5555")
@pos_frac = BigDecimal("2E-9999")
@neg_frac = BigDecimal("-2E-9999")
@nan = BigDecimal("NaN")
@infinity = BigDecimal("Infinity")
@infinity_minus = BigDecimal("-Infinity")
@one_minus = BigDecimal("-1")
@frac_1 = BigDecimal("1E-99999")
@frac_2 = BigDecimal("0.9E-99999")
end
it "it equals modulo, if both values are of same sign" do
BigDecimal('1234567890123456789012345679').remainder(BigDecimal('1')).should == @zero
BigDecimal('123456789').remainder(BigDecimal('333333333333333333333333333E-50')).should == BigDecimal('0.12233333333333333333345679E-24')
@mixed.remainder(@pos_frac).should == @mixed % @pos_frac
@pos_int.remainder(@pos_frac).should == @pos_int % @pos_frac
@neg_frac.remainder(@neg_int).should == @neg_frac % @neg_int
@neg_int.remainder(@neg_frac).should == @neg_int % @neg_frac
end
it "means self-arg*(self/arg).truncate" do
@mixed.remainder(@neg_frac).should == @mixed - @neg_frac * (@mixed / @neg_frac).truncate
@pos_int.remainder(@neg_frac).should == @pos_int - @neg_frac * (@pos_int / @neg_frac).truncate
@neg_frac.remainder(@pos_int).should == @neg_frac - @pos_int * (@neg_frac / @pos_int).truncate
@neg_int.remainder(@pos_frac).should == @neg_int - @pos_frac * (@neg_int / @pos_frac).truncate
end
it "returns NaN used with zero" do
@mixed.remainder(@zero).nan?.should == true
@zero.remainder(@zero).nan?.should == true
end
it "returns zero if used on zero" do
@zero.remainder(@mixed).should == @zero
end
it "returns NaN if NaN is involved" do
@nan.remainder(@nan).nan?.should == true
@nan.remainder(@one).nan?.should == true
@one.remainder(@nan).nan?.should == true
@infinity.remainder(@nan).nan?.should == true
@nan.remainder(@infinity).nan?.should == true
end
it "returns NaN if Infinity is involved" do
@infinity.remainder(@infinity).nan?.should == true
@infinity.remainder(@one).nan?.should == true
@infinity.remainder(@mixed).nan?.should == true
@infinity.remainder(@one_minus).nan?.should == true
@infinity.remainder(@frac_1).nan?.should == true
@one.remainder(@infinity).nan?.should == true
@infinity_minus.remainder(@infinity_minus).nan?.should == true
@infinity_minus.remainder(@one).nan?.should == true
@one.remainder(@infinity_minus).nan?.should == true
@frac_2.remainder(@infinity_minus).nan?.should == true
@infinity.remainder(@infinity_minus).nan?.should == true
@infinity_minus.remainder(@infinity).nan?.should == true
end
it "coerces arguments to BigDecimal if possible" do
@one.remainder(2).should == @one
end
it "raises TypeError if the argument cannot be coerced to BigDecimal" do
lambda {
@one.remainder('2')
}.should raise_error(TypeError)
end
end
| takano32/rubinius | spec/ruby/library/bigdecimal/remainder_spec.rb | Ruby | bsd-3-clause | 3,111 |
/*
Project: angular-gantt v1.2.8 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
/* global ResizeSensor: false */
/* global ElementQueries: false */
'use strict';
angular.module('gantt.resizeSensor', ['gantt']).directive('ganttResizeSensor', [function() {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
// Load options from global options attribute.
if (scope.options && typeof(scope.options.progress) === 'object') {
for (var option in scope.options.progress) {
scope[option] = scope.options[option];
}
}
if (scope.enabled === undefined) {
scope.enabled = true;
}
function buildSensor() {
var ganttElement = element.parent().parent().parent()[0].querySelectorAll('div.gantt')[0];
return new ResizeSensor(ganttElement, function() {
ganttCtrl.gantt.$scope.ganttElementWidth = ganttElement.clientWidth;
ganttCtrl.gantt.$scope.$apply();
});
}
var rendered = false;
api.core.on.rendered(scope, function() {
rendered = true;
if (sensor !== undefined) {
sensor.detach();
}
if (scope.enabled) {
ElementQueries.update();
sensor = buildSensor();
}
});
var sensor;
scope.$watch('enabled', function(newValue) {
if (rendered) {
if (newValue && sensor === undefined) {
ElementQueries.update();
sensor = buildSensor();
} else if (!newValue && sensor !== undefined) {
sensor.detach();
sensor = undefined;
}
}
});
}
};
}]);
}());
angular.module('gantt.resizeSensor.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-resizeSensor-plugin.js.map | GuilhouT/angular-gantt | dist/angular-gantt-resizeSensor-plugin.js | JavaScript | mit | 2,694 |
/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Represents module nodes in the project tree.
*/
public final class CModuleNode extends CProjectTreeNode<INaviModule> {
/**
* Used for serialization.
*/
private static final long serialVersionUID = -5643276356053733957L;
/**
* Icon used for loaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));
/**
* Icon used for unloaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_GRAY =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));
/**
* Icon used for incomplete modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_BROKEN =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));
/**
* Icon used for not yet converted modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_UNCONVERTED =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));
/**
* The module described by the node.
*/
private final INaviModule m_module;
/**
* Context in which views of the represented module are opened.
*/
private final IViewContainer m_contextContainer;
/**
* Updates the node on important changes in the represented module.
*/
private final InternalModuleListener m_listener;
/**
* Constructor for modules inside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param addressSpace The address space the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree,
final DefaultMutableTreeNode parentNode,
final IDatabase database,
final INaviAddressSpace addressSpace,
final INaviModule module,
final CProjectContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, addressSpace, module,
contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
addressSpace,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Constructor for modules outside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
null,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01970: Database can't be null");
m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Creates the child nodes of the module node. One node is added for the native Call graph of the
* module, another node is added that contains all native Flow graph views of the module.
*/
@Override
protected void createChildren() {}
@Override
public void dispose() {
super.dispose();
m_contextContainer.dispose();
m_module.removeListener(m_listener);
deleteChildren();
}
@Override
public void doubleClicked() {
if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
}
}
@Override
public CModuleNodeComponent getComponent() {
return (CModuleNodeComponent) super.getComponent();
}
@Override
public Icon getIcon() {
if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
} else if (m_module.getConfiguration().getRawModule().isComplete()
&& !m_module.isInitialized()) {
return ICON_MODULE_UNCONVERTED;
} else {
return ICON_MODULE_BROKEN;
}
}
@Override
public String toString() {
return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
+ m_module.getCustomViewCount() + ")";
}
/**
* Updates the node on important changes in the represented module.
*/
private class InternalModuleListener extends CModuleListenerAdapter {
@Override
public void addedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void changedName(final INaviModule module, final String name) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void deletedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
/**
* When the module is loaded, create the child nodes.
*/
@Override
public void loadedModule(final INaviModule module) {
new SwingInvoker() {
@Override
protected void operation() {
createChildren();
getTreeModel().nodeStructureChanged(CModuleNode.this);
}
}.invokeAndWait();
}
}
}
| dgrif/binnavi | src/main/java/com/google/security/zynamics/binnavi/Gui/MainWindow/ProjectTree/Nodes/Module/CModuleNode.java | Java | apache-2.0 | 8,652 |
package daemon
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
"github.com/docker/docker/builder"
"github.com/docker/docker/container"
"github.com/docker/docker/pkg/archive"
"github.com/docker/docker/pkg/chrootarchive"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/ioutils"
"github.com/docker/docker/pkg/system"
"github.com/docker/engine-api/types"
)
// ErrExtractPointNotDirectory is used to convey that the operation to extract
// a tar archive to a directory in a container has failed because the specified
// path does not refer to a directory.
var ErrExtractPointNotDirectory = errors.New("extraction point is not a directory")
// ContainerCopy performs a deprecated operation of archiving the resource at
// the specified path in the container identified by the given name.
func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, err
}
if res[0] == '/' || res[0] == '\\' {
res = res[1:]
}
return daemon.containerCopy(container, res)
}
// ContainerStatPath stats the filesystem resource at the specified path in the
// container identified by the given name.
func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, err
}
return daemon.containerStatPath(container, path)
}
// ContainerArchivePath creates an archive of the filesystem resource at the
// specified path in the container identified by the given name. Returns a
// tar archive of the resource and whether it was a directory or a single file.
func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
container, err := daemon.GetContainer(name)
if err != nil {
return nil, nil, err
}
return daemon.containerArchivePath(container, path)
}
// ContainerExtractToDir extracts the given archive to the specified location
// in the filesystem of the container identified by the given name. The given
// path must be of a directory in the container. If it is not, the error will
// be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will
// be an error if unpacking the given content would cause an existing directory
// to be replaced with a non-directory and vice versa.
func (daemon *Daemon) ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error {
container, err := daemon.GetContainer(name)
if err != nil {
return err
}
return daemon.containerExtractToDir(container, path, noOverwriteDirNonDir, content)
}
// containerStatPath stats the filesystem resource at the specified path in this
// container. Returns stat info about the resource.
func (daemon *Daemon) containerStatPath(container *container.Container, path string) (stat *types.ContainerPathStat, err error) {
container.Lock()
defer container.Unlock()
if err = daemon.Mount(container); err != nil {
return nil, err
}
defer daemon.Unmount(container)
err = daemon.mountVolumes(container)
defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
if err != nil {
return nil, err
}
resolvedPath, absPath, err := container.ResolvePath(path)
if err != nil {
return nil, err
}
return container.StatPath(resolvedPath, absPath)
}
// containerArchivePath creates an archive of the filesystem resource at the specified
// path in this container. Returns a tar archive of the resource and stat info
// about the resource.
func (daemon *Daemon) containerArchivePath(container *container.Container, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) {
container.Lock()
defer func() {
if err != nil {
// Wait to unlock the container until the archive is fully read
// (see the ReadCloseWrapper func below) or if there is an error
// before that occurs.
container.Unlock()
}
}()
if err = daemon.Mount(container); err != nil {
return nil, nil, err
}
defer func() {
if err != nil {
// unmount any volumes
container.UnmountVolumes(true, daemon.LogVolumeEvent)
// unmount the container's rootfs
daemon.Unmount(container)
}
}()
if err = daemon.mountVolumes(container); err != nil {
return nil, nil, err
}
resolvedPath, absPath, err := container.ResolvePath(path)
if err != nil {
return nil, nil, err
}
stat, err = container.StatPath(resolvedPath, absPath)
if err != nil {
return nil, nil, err
}
// We need to rebase the archive entries if the last element of the
// resolved path was a symlink that was evaluated and is now different
// than the requested path. For example, if the given path was "/foo/bar/",
// but it resolved to "/var/lib/docker/containers/{id}/foo/baz/", we want
// to ensure that the archive entries start with "bar" and not "baz". This
// also catches the case when the root directory of the container is
// requested: we want the archive entries to start with "/" and not the
// container ID.
data, err := archive.TarResourceRebase(resolvedPath, filepath.Base(absPath))
if err != nil {
return nil, nil, err
}
content = ioutils.NewReadCloserWrapper(data, func() error {
err := data.Close()
container.UnmountVolumes(true, daemon.LogVolumeEvent)
daemon.Unmount(container)
container.Unlock()
return err
})
daemon.LogContainerEvent(container, "archive-path")
return content, stat, nil
}
// containerExtractToDir extracts the given tar archive to the specified location in the
// filesystem of this container. The given path must be of a directory in the
// container. If it is not, the error will be ErrExtractPointNotDirectory. If
// noOverwriteDirNonDir is true then it will be an error if unpacking the
// given content would cause an existing directory to be replaced with a non-
// directory and vice versa.
func (daemon *Daemon) containerExtractToDir(container *container.Container, path string, noOverwriteDirNonDir bool, content io.Reader) (err error) {
container.Lock()
defer container.Unlock()
if err = daemon.Mount(container); err != nil {
return err
}
defer daemon.Unmount(container)
err = daemon.mountVolumes(container)
defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
if err != nil {
return err
}
// Check if a drive letter supplied, it must be the system drive. No-op except on Windows
path, err = system.CheckSystemDriveAndRemoveDriveLetter(path)
if err != nil {
return err
}
// The destination path needs to be resolved to a host path, with all
// symbolic links followed in the scope of the container's rootfs. Note
// that we do not use `container.ResolvePath(path)` here because we need
// to also evaluate the last path element if it is a symlink. This is so
// that you can extract an archive to a symlink that points to a directory.
// Consider the given path as an absolute path in the container.
absPath := archive.PreserveTrailingDotOrSeparator(filepath.Join(string(filepath.Separator), path), path)
// This will evaluate the last path element if it is a symlink.
resolvedPath, err := container.GetResourcePath(absPath)
if err != nil {
return err
}
stat, err := os.Lstat(resolvedPath)
if err != nil {
return err
}
if !stat.IsDir() {
return ErrExtractPointNotDirectory
}
// Need to check if the path is in a volume. If it is, it cannot be in a
// read-only volume. If it is not in a volume, the container cannot be
// configured with a read-only rootfs.
// Use the resolved path relative to the container rootfs as the new
// absPath. This way we fully follow any symlinks in a volume that may
// lead back outside the volume.
//
// The Windows implementation of filepath.Rel in golang 1.4 does not
// support volume style file path semantics. On Windows when using the
// filter driver, we are guaranteed that the path will always be
// a volume file path.
var baseRel string
if strings.HasPrefix(resolvedPath, `\\?\Volume{`) {
if strings.HasPrefix(resolvedPath, container.BaseFS) {
baseRel = resolvedPath[len(container.BaseFS):]
if baseRel[:1] == `\` {
baseRel = baseRel[1:]
}
}
} else {
baseRel, err = filepath.Rel(container.BaseFS, resolvedPath)
}
if err != nil {
return err
}
// Make it an absolute path.
absPath = filepath.Join(string(filepath.Separator), baseRel)
toVolume, err := checkIfPathIsInAVolume(container, absPath)
if err != nil {
return err
}
if !toVolume && container.HostConfig.ReadonlyRootfs {
return ErrRootFSReadOnly
}
uid, gid := daemon.GetRemappedUIDGID()
options := &archive.TarOptions{
NoOverwriteDirNonDir: noOverwriteDirNonDir,
ChownOpts: &archive.TarChownOptions{
UID: uid, GID: gid, // TODO: should all ownership be set to root (either real or remapped)?
},
}
if err := chrootarchive.Untar(content, resolvedPath, options); err != nil {
return err
}
daemon.LogContainerEvent(container, "extract-to-dir")
return nil
}
func (daemon *Daemon) containerCopy(container *container.Container, resource string) (rc io.ReadCloser, err error) {
container.Lock()
defer func() {
if err != nil {
// Wait to unlock the container until the archive is fully read
// (see the ReadCloseWrapper func below) or if there is an error
// before that occurs.
container.Unlock()
}
}()
if err := daemon.Mount(container); err != nil {
return nil, err
}
defer func() {
if err != nil {
// unmount any volumes
container.UnmountVolumes(true, daemon.LogVolumeEvent)
// unmount the container's rootfs
daemon.Unmount(container)
}
}()
if err := daemon.mountVolumes(container); err != nil {
return nil, err
}
basePath, err := container.GetResourcePath(resource)
if err != nil {
return nil, err
}
stat, err := os.Stat(basePath)
if err != nil {
return nil, err
}
var filter []string
if !stat.IsDir() {
d, f := filepath.Split(basePath)
basePath = d
filter = []string{f}
} else {
filter = []string{filepath.Base(basePath)}
basePath = filepath.Dir(basePath)
}
archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{
Compression: archive.Uncompressed,
IncludeFiles: filter,
})
if err != nil {
return nil, err
}
reader := ioutils.NewReadCloserWrapper(archive, func() error {
err := archive.Close()
container.UnmountVolumes(true, daemon.LogVolumeEvent)
daemon.Unmount(container)
container.Unlock()
return err
})
daemon.LogContainerEvent(container, "copy")
return reader, nil
}
// CopyOnBuild copies/extracts a source FileInfo to a destination path inside a container
// specified by a container object.
// TODO: make sure callers don't unnecessarily convert destPath with filepath.FromSlash (Copy does it already).
// CopyOnBuild should take in abstract paths (with slashes) and the implementation should convert it to OS-specific paths.
func (daemon *Daemon) CopyOnBuild(cID string, destPath string, src builder.FileInfo, decompress bool) error {
srcPath := src.Path()
destExists := true
destDir := false
rootUID, rootGID := daemon.GetRemappedUIDGID()
// Work in daemon-local OS specific file paths
destPath = filepath.FromSlash(destPath)
c, err := daemon.GetContainer(cID)
if err != nil {
return err
}
err = daemon.Mount(c)
if err != nil {
return err
}
defer daemon.Unmount(c)
dest, err := c.GetResourcePath(destPath)
if err != nil {
return err
}
// Preserve the trailing slash
// TODO: why are we appending another path separator if there was already one?
if strings.HasSuffix(destPath, string(os.PathSeparator)) || destPath == "." {
destDir = true
dest += string(os.PathSeparator)
}
destPath = dest
destStat, err := os.Stat(destPath)
if err != nil {
if !os.IsNotExist(err) {
//logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err)
return err
}
destExists = false
}
uidMaps, gidMaps := daemon.GetUIDGIDMaps()
archiver := &archive.Archiver{
Untar: chrootarchive.Untar,
UIDMaps: uidMaps,
GIDMaps: gidMaps,
}
if src.IsDir() {
// copy as directory
if err := archiver.CopyWithTar(srcPath, destPath); err != nil {
return err
}
return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
}
if decompress && archive.IsArchivePath(srcPath) {
// Only try to untar if it is a file and that we've been told to decompress (when ADD-ing a remote file)
// First try to unpack the source as an archive
// to support the untar feature we need to clean up the path a little bit
// because tar is very forgiving. First we need to strip off the archive's
// filename from the path but this is only added if it does not end in slash
tarDest := destPath
if strings.HasSuffix(tarDest, string(os.PathSeparator)) {
tarDest = filepath.Dir(destPath)
}
// try to successfully untar the orig
err := archiver.UntarPath(srcPath, tarDest)
/*
if err != nil {
logrus.Errorf("Couldn't untar to %s: %v", tarDest, err)
}
*/
return err
}
// only needed for fixPermissions, but might as well put it before CopyFileWithTar
if destDir || (destExists && destStat.IsDir()) {
destPath = filepath.Join(destPath, src.Name())
}
if err := idtools.MkdirAllNewAs(filepath.Dir(destPath), 0755, rootUID, rootGID); err != nil {
return err
}
if err := archiver.CopyFileWithTar(srcPath, destPath); err != nil {
return err
}
return fixPermissions(srcPath, destPath, rootUID, rootGID, destExists)
}
| albamc/gorb | vendor/github.com/docker/docker/daemon/archive.go | GO | lgpl-3.0 | 13,485 |
cask 'dsp-radio' do
version '1.4.1'
sha256 'b04ff63d41a47923455499340e32706df83a184c54c590d70191072b8fdbbbc9'
url "https://dl2sdr.homepage.t-online.de/files/DSP_Radio_#{version.delete('.')}.zip"
name 'DSP Radio'
homepage 'https://dl2sdr.homepage.t-online.de/'
license :gratis
app "DSP Radio #{version}.app"
end
| JosephViolago/homebrew-cask | Casks/dsp-radio.rb | Ruby | bsd-2-clause | 327 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.mock;
import com.intellij.lang.FileASTNode;
import com.intellij.lang.Language;
import com.intellij.navigation.ItemPresentation;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.FileContextUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiElementProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.LocalTimeCounter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class MockPsiFile extends MockPsiElement implements PsiFile {
private final long myModStamp = LocalTimeCounter.currentTime();
private VirtualFile myVirtualFile = null;
public boolean valid = true;
public String text = "";
private final FileViewProvider myFileViewProvider;
private final PsiManager myPsiManager;
public MockPsiFile(@NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), new LightVirtualFile("noname", getFileType(), ""));
}
public MockPsiFile(@NotNull VirtualFile virtualFile, @NotNull PsiManager psiManager) {
super(psiManager.getProject());
myPsiManager = psiManager;
myVirtualFile = virtualFile;
myFileViewProvider = new SingleRootFileViewProvider(getManager(), virtualFile);
}
@Override
public VirtualFile getVirtualFile() {
return myVirtualFile;
}
@Override
public boolean processChildren(final PsiElementProcessor<PsiFileSystemItem> processor) {
return true;
}
@Override
@NotNull
public String getName() {
return "mock.file";
}
@Override
@Nullable
public ItemPresentation getPresentation() {
return null;
}
@Override
public PsiElement setName(@NotNull String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public void checkSetName(String name) throws IncorrectOperationException {
throw new IncorrectOperationException("Not implemented");
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public PsiDirectory getContainingDirectory() {
return null;
}
@Nullable
public PsiDirectory getParentDirectory() {
throw new UnsupportedOperationException("Method getParentDirectory is not yet implemented in " + getClass().getName());
}
@Override
public long getModificationStamp() {
return myModStamp;
}
@Override
@NotNull
public PsiFile getOriginalFile() {
return this;
}
@Override
@NotNull
public FileType getFileType() {
return StdFileTypes.JAVA;
}
@Override
@NotNull
public Language getLanguage() {
return StdFileTypes.JAVA.getLanguage();
}
@Override
@NotNull
public PsiFile[] getPsiRoots() {
return new PsiFile[]{this};
}
@Override
@NotNull
public FileViewProvider getViewProvider() {
return myFileViewProvider;
}
@Override
public PsiManager getManager() {
return myPsiManager;
}
@Override
@NotNull
public PsiElement[] getChildren() {
return PsiElement.EMPTY_ARRAY;
}
@Override
public PsiDirectory getParent() {
return null;
}
@Override
public PsiElement getFirstChild() {
return null;
}
@Override
public PsiElement getLastChild() {
return null;
}
@Override
public void acceptChildren(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement getNextSibling() {
return null;
}
@Override
public PsiElement getPrevSibling() {
return null;
}
@Override
public PsiFile getContainingFile() {
return null;
}
@Override
public TextRange getTextRange() {
return null;
}
@Override
public int getStartOffsetInParent() {
return 0;
}
@Override
public int getTextLength() {
return 0;
}
@Override
public PsiElement findElementAt(int offset) {
return null;
}
@Override
public PsiReference findReferenceAt(int offset) {
return null;
}
@Override
public int getTextOffset() {
return 0;
}
@Override
public String getText() {
return text;
}
@Override
@NotNull
public char[] textToCharArray() {
return ArrayUtil.EMPTY_CHAR_ARRAY;
}
@Override
public boolean textMatches(@NotNull CharSequence text) {
return false;
}
@Override
public boolean textMatches(@NotNull PsiElement element) {
return false;
}
@Override
public boolean textContains(char c) {
return false;
}
@Override
public void accept(@NotNull PsiElementVisitor visitor) {
}
@Override
public PsiElement copy() {
return null;
}
@Override
public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException {
return null;
}
@Override
public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException {
}
@Override
public PsiElement addRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeBefore(@NotNull PsiElement first, @NotNull PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public PsiElement addRangeAfter(PsiElement first, PsiElement last, PsiElement anchor)
throws IncorrectOperationException {
return null;
}
@Override
public void delete() throws IncorrectOperationException {
}
@Override
public void checkDelete() throws IncorrectOperationException {
}
@Override
public void deleteChildRange(PsiElement first, PsiElement last) throws IncorrectOperationException {
}
@Override
public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException {
return null;
}
@Override
public boolean isValid() {
return valid;
}
@Override
public boolean isWritable() {
return false;
}
@Override
public PsiReference getReference() {
return null;
}
@Override
@NotNull
public PsiReference[] getReferences() {
return PsiReference.EMPTY_ARRAY;
}
@Override
public <T> T getCopyableUserData(@NotNull Key<T> key) {
return null;
}
@Override
public <T> void putCopyableUserData(@NotNull Key<T> key, T value) {
}
@Override
@NotNull
public Project getProject() {
final PsiManager manager = getManager();
if (manager == null) throw new PsiInvalidElementAccessException(this);
return manager.getProject();
}
@Override
public boolean isPhysical() {
return true;
}
@Override
public PsiElement getNavigationElement() {
return this;
}
@Override
public PsiElement getOriginalElement() {
return this;
}
@Override
@NotNull
public GlobalSearchScope getResolveScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
@NotNull
public SearchScope getUseScope() {
return GlobalSearchScope.EMPTY_SCOPE;
}
@Override
public FileASTNode getNode() {
return null;
}
@Override
public void subtreeChanged() {
}
@Override
public void navigate(boolean requestFocus) {
}
@Override
public boolean canNavigate() {
return false;
}
@Override
public boolean canNavigateToSource() {
return false;
}
@Override
public PsiElement getContext() {
return FileContextUtil.getFileContext(this);
}
}
| idea4bsd/idea4bsd | platform/testFramework/src/com/intellij/mock/MockPsiFile.java | Java | apache-2.0 | 8,673 |
// Type definitions for lodash-webpack-plugin 0.11
// Project: https://github.com/lodash/lodash-webpack-plugin#readme
// Definitions by: Benjamin Lim <https://github.com/bumbleblym>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import { Plugin } from 'webpack';
export = LodashModuleReplacementPlugin;
declare class LodashModuleReplacementPlugin extends Plugin {
constructor(options?: LodashModuleReplacementPlugin.Options);
}
declare namespace LodashModuleReplacementPlugin {
interface Options {
caching?: boolean;
chaining?: boolean;
cloning?: boolean;
coercions?: boolean;
collections?: boolean;
currying?: boolean;
deburring?: boolean;
exotics?: boolean;
flattening?: boolean;
guards?: boolean;
memoizing?: boolean;
metadata?: boolean;
paths?: boolean;
placeholders?: boolean;
shorthands?: boolean;
unicode?: boolean;
}
}
| borisyankov/DefinitelyTyped | types/lodash-webpack-plugin/index.d.ts | TypeScript | mit | 913 |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.source.xml;
import com.intellij.psi.impl.meta.MetaRegistry;
import com.intellij.psi.meta.PsiMetaData;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.psi.xml.XmlMarkupDecl;
/**
* @author Mike
*/
public class XmlMarkupDeclImpl extends XmlElementImpl implements XmlMarkupDecl {
public XmlMarkupDeclImpl() {
super(XmlElementType.XML_MARKUP_DECL);
}
@Override
public PsiMetaData getMetaData(){
return MetaRegistry.getMeta(this);
}
}
| asedunov/intellij-community | xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlMarkupDeclImpl.java | Java | apache-2.0 | 1,100 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.zookeeper.operations;
import java.util.List;
import static java.lang.String.format;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Stat;
/**
* <code>CreateOperation</code> is a basic Zookeeper operation used to create
* and set the data contained in a given node
*/
public class CreateOperation extends ZooKeeperOperation<String> {
private static final List<ACL> DEFAULT_PERMISSIONS = Ids.OPEN_ACL_UNSAFE;
private static final CreateMode DEFAULT_MODE = CreateMode.EPHEMERAL;
private byte[] data;
private List<ACL> permissions = DEFAULT_PERMISSIONS;
private CreateMode createMode = DEFAULT_MODE;
public CreateOperation(ZooKeeper connection, String node) {
super(connection, node);
}
@Override
public OperationResult<String> getResult() {
try {
String created = connection.create(node, data, permissions, createMode);
if (LOG.isDebugEnabled()) {
LOG.debug(format("Created node '%s' using mode '%s'", created, createMode));
}
// for consistency with other operations return an empty stats set.
return new OperationResult<String>(created, new Stat());
} catch (Exception e) {
return new OperationResult<String>(e);
}
}
public void setData(byte[] data) {
this.data = data;
}
public void setPermissions(List<ACL> permissions) {
this.permissions = permissions;
}
public void setCreateMode(CreateMode createMode) {
this.createMode = createMode;
}
}
| YMartsynkevych/camel | components/camel-zookeeper/src/main/java/org/apache/camel/component/zookeeper/operations/CreateOperation.java | Java | apache-2.0 | 2,550 |
/*
* Copyright 2005 Sascha Weinreuter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.lang.xpath;
import com.intellij.lang.Commenter;
import com.intellij.lang.Language;
import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import org.jetbrains.annotations.NotNull;
public final class XPath2Language extends Language {
public static final String ID = "XPath2";
XPath2Language() {
super(Language.findLanguageByID(XPathLanguage.ID), ID);
}
@Override
public XPathFileType getAssociatedFileType() {
return XPathFileType.XPATH2;
}
public static class XPathSyntaxHighlighterFactory extends SingleLazyInstanceSyntaxHighlighterFactory {
@NotNull
protected SyntaxHighlighter createHighlighter() {
return new XPathHighlighter(true);
}
}
public static class XPath2Commenter implements Commenter {
@Override
public String getLineCommentPrefix() {
return null;
}
@Override
public String getBlockCommentPrefix() {
return "(:";
}
@Override
public String getBlockCommentSuffix() {
return ":)";
}
@Override
public String getCommentedBlockCommentPrefix() {
return getBlockCommentPrefix();
}
@Override
public String getCommentedBlockCommentSuffix() {
return getBlockCommentSuffix();
}
}
}
| clumsy/intellij-community | plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPath2Language.java | Java | apache-2.0 | 1,943 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tools/json_schema_compiler/test/simple_api.h"
#include "testing/gtest/include/gtest/gtest.h"
using namespace test::api::simple_api;
namespace {
static scoped_ptr<base::DictionaryValue> CreateTestTypeDictionary() {
scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
value->SetWithoutPathExpansion("number", new base::FundamentalValue(1.1));
value->SetWithoutPathExpansion("integer", new base::FundamentalValue(4));
value->SetWithoutPathExpansion("string", new base::StringValue("bling"));
value->SetWithoutPathExpansion("boolean", new base::FundamentalValue(true));
return value.Pass();
}
} // namespace
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerResultCreate) {
scoped_ptr<base::ListValue> results = IncrementInteger::Results::Create(5);
base::ListValue expected;
expected.Append(new base::FundamentalValue(5));
EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, IncrementIntegerParamsCreate) {
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::FundamentalValue(6));
scoped_ptr<IncrementInteger::Params> params(
IncrementInteger::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_EQ(6, params->num);
}
TEST(JsonSchemaCompilerSimpleTest, NumberOfParams) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::StringValue("text"));
params_value->Append(new base::StringValue("text"));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
scoped_ptr<IncrementInteger::Params> params(
IncrementInteger::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalStringParamsCreate) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->str.get());
}
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::StringValue("asdf"));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_TRUE(params->str.get());
EXPECT_EQ("asdf", *params->str);
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalParamsTakingNull) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(base::Value::CreateNullValue());
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->str.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalStringParamsWrongType) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(new base::FundamentalValue(5));
scoped_ptr<OptionalString::Params> params(
OptionalString::Params::Create(*params_value));
EXPECT_FALSE(params.get());
}
}
TEST(JsonSchemaCompilerSimpleTest, OptionalBeforeRequired) {
{
scoped_ptr<base::ListValue> params_value(new base::ListValue());
params_value->Append(base::Value::CreateNullValue());
params_value->Append(new base::StringValue("asdf"));
scoped_ptr<OptionalBeforeRequired::Params> params(
OptionalBeforeRequired::Params::Create(*params_value));
EXPECT_TRUE(params.get());
EXPECT_FALSE(params->first.get());
EXPECT_EQ("asdf", params->second);
}
}
TEST(JsonSchemaCompilerSimpleTest, NoParamsResultCreate) {
scoped_ptr<base::ListValue> results = OptionalString::Results::Create();
base::ListValue expected;
EXPECT_TRUE(results->Equals(&expected));
}
TEST(JsonSchemaCompilerSimpleTest, TestTypePopulate) {
{
scoped_ptr<TestType> test_type(new TestType());
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
EXPECT_EQ("bling", test_type->string);
EXPECT_EQ(1.1, test_type->number);
EXPECT_EQ(4, test_type->integer);
EXPECT_EQ(true, test_type->boolean);
EXPECT_TRUE(value->Equals(test_type->ToValue().get()));
}
{
scoped_ptr<TestType> test_type(new TestType());
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
value->Remove("number", NULL);
EXPECT_FALSE(TestType::Populate(*value, test_type.get()));
}
}
TEST(JsonSchemaCompilerSimpleTest, GetTestType) {
{
scoped_ptr<base::DictionaryValue> value = CreateTestTypeDictionary();
scoped_ptr<TestType> test_type(new TestType());
EXPECT_TRUE(TestType::Populate(*value, test_type.get()));
scoped_ptr<base::ListValue> results =
GetTestType::Results::Create(*test_type);
base::DictionaryValue* result = NULL;
results->GetDictionary(0, &result);
EXPECT_TRUE(result->Equals(value.get()));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnIntegerFiredCreate) {
{
scoped_ptr<base::ListValue> results(OnIntegerFired::Create(5));
base::ListValue expected;
expected.Append(new base::FundamentalValue(5));
EXPECT_TRUE(results->Equals(&expected));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnStringFiredCreate) {
{
scoped_ptr<base::ListValue> results(OnStringFired::Create("yo dawg"));
base::ListValue expected;
expected.Append(new base::StringValue("yo dawg"));
EXPECT_TRUE(results->Equals(&expected));
}
}
TEST(JsonSchemaCompilerSimpleTest, OnTestTypeFiredCreate) {
{
TestType some_test_type;
scoped_ptr<base::DictionaryValue> expected = CreateTestTypeDictionary();
ASSERT_TRUE(expected->GetDouble("number", &some_test_type.number));
ASSERT_TRUE(expected->GetString("string", &some_test_type.string));
ASSERT_TRUE(expected->GetInteger("integer", &some_test_type.integer));
ASSERT_TRUE(expected->GetBoolean("boolean", &some_test_type.boolean));
scoped_ptr<base::ListValue> results(
OnTestTypeFired::Create(some_test_type));
base::DictionaryValue* result = NULL;
results->GetDictionary(0, &result);
EXPECT_TRUE(result->Equals(expected.get()));
}
}
| CTSRD-SOAAP/chromium-42.0.2311.135 | tools/json_schema_compiler/test/simple_api_unittest.cc | C++ | bsd-3-clause | 6,511 |
// Copyright 2014 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package internal
// This file implements a network dialer that limits the number of concurrent connections.
// It is only used for API calls.
import (
"log"
"net"
"runtime"
"sync"
"time"
)
var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable.
func limitRelease() {
// non-blocking
select {
case <-limitSem:
default:
// This should not normally happen.
log.Print("appengine: unbalanced limitSem release!")
}
}
func limitDial(network, addr string) (net.Conn, error) {
limitSem <- 1
// Dial with a timeout in case the API host is MIA.
// The connection should normally be very fast.
conn, err := net.DialTimeout(network, addr, 500*time.Millisecond)
if err != nil {
limitRelease()
return nil, err
}
lc := &limitConn{Conn: conn}
runtime.SetFinalizer(lc, (*limitConn).Close) // shouldn't usually be required
return lc, nil
}
type limitConn struct {
close sync.Once
net.Conn
}
func (lc *limitConn) Close() error {
defer lc.close.Do(func() {
limitRelease()
runtime.SetFinalizer(lc, nil)
})
return lc.Conn.Close()
}
| ae6rt/decap | web/vendor/google.golang.org/appengine/internal/net.go | GO | mit | 1,236 |
/// <reference path="denodeify.d.ts" />
/// <reference path="../node/node.d.ts" />
import denodeify = require("denodeify");
import fs = require('fs');
import cp = require('child_process');
const readFile = denodeify<string,string,string>(fs.readFile);
const exec = denodeify<string,string>(cp.exec, (err, stdout, stderr) => [err, stdout]);
| Pro/DefinitelyTyped | denodeify/denodeify-tests.ts | TypeScript | mit | 342 |
package graph
import (
"strings"
"github.com/docker/docker/engine"
"github.com/docker/docker/image"
)
func (s *TagStore) CmdViz(job *engine.Job) engine.Status {
images, _ := s.graph.Map()
if images == nil {
return engine.StatusOK
}
job.Stdout.Write([]byte("digraph docker {\n"))
var (
parentImage *image.Image
err error
)
for _, image := range images {
parentImage, err = image.GetParent()
if err != nil {
return job.Errorf("Error while getting parent image: %v", err)
}
if parentImage != nil {
job.Stdout.Write([]byte(" \"" + parentImage.ID + "\" -> \"" + image.ID + "\"\n"))
} else {
job.Stdout.Write([]byte(" base -> \"" + image.ID + "\" [style=invis]\n"))
}
}
for id, repos := range s.GetRepoRefs() {
job.Stdout.Write([]byte(" \"" + id + "\" [label=\"" + id + "\\n" + strings.Join(repos, "\\n") + "\",shape=box,fillcolor=\"paleturquoise\",style=\"filled,rounded\"];\n"))
}
job.Stdout.Write([]byte(" base [style=invisible]\n}\n"))
return engine.StatusOK
}
| openshift/dockerexec | vendor/src/github.com/docker/docker/graph/viz.go | GO | apache-2.0 | 1,016 |
import * as angular from 'angular';
angular
.module('app', ['ngDesktopNotification'])
.config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => {
desktopNotificationProvider.config({
autoClose: true,
duration: 5,
showOnPageHidden: false,
});
}])
.controller('AppController', ['desktopNotification', (desktopNotification: angular.desktopNotification.IDesktopNotificationService) => {
// Check support and permission
const isNotificationSupported = desktopNotification.isSupported();
const currentNotificationPermission = desktopNotification.currentPermission();
if (currentNotificationPermission === desktopNotification.permissions.granted) {
// Permission granted
}
// Request permission
desktopNotification.requestPermission().then(
// Permission granted
(permission) => {
// Show notification
desktopNotification.show(
"Notification title",
{
tag: "tag",
body: "Notification body",
icon: "https://www.iconurl.com/icon-name.icon-extension",
onClick: () => {
// Notification clicked
}
});
},
() => {
// No permission granted
});
}]);
| borisyankov/DefinitelyTyped | types/angular-desktop-notification/angular-desktop-notification-tests.ts | TypeScript | mit | 1,560 |
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
// Author: petar@google.com (Petar Petrov)
#include <Python.h>
#include <string>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/pyext/descriptor.h>
#include <google/protobuf/pyext/scoped_pyobject_ptr.h>
#define C(str) const_cast<char*>(str)
#if PY_MAJOR_VERSION >= 3
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
#define PyInt_FromLong PyLong_FromLong
#if PY_VERSION_HEX < 0x03030000
#error "Python 3.0 - 3.2 are not supported."
#else
#define PyString_AsString(ob) \
(PyUnicode_Check(ob)? PyUnicode_AsUTF8(ob): PyBytes_AS_STRING(ob))
#endif
#endif
namespace google {
namespace protobuf {
namespace python {
#ifndef PyVarObject_HEAD_INIT
#define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
#endif
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
static google::protobuf::DescriptorPool* g_descriptor_pool = NULL;
namespace cfield_descriptor {
static void Dealloc(CFieldDescriptor* self) {
Py_CLEAR(self->descriptor_field);
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
static PyObject* GetFullName(CFieldDescriptor* self, void *closure) {
return PyString_FromStringAndSize(
self->descriptor->full_name().c_str(),
self->descriptor->full_name().size());
}
static PyObject* GetName(CFieldDescriptor *self, void *closure) {
return PyString_FromStringAndSize(
self->descriptor->name().c_str(),
self->descriptor->name().size());
}
static PyObject* GetCppType(CFieldDescriptor *self, void *closure) {
return PyInt_FromLong(self->descriptor->cpp_type());
}
static PyObject* GetLabel(CFieldDescriptor *self, void *closure) {
return PyInt_FromLong(self->descriptor->label());
}
static PyObject* GetID(CFieldDescriptor *self, void *closure) {
return PyLong_FromVoidPtr(self);
}
static PyGetSetDef Getters[] = {
{ C("full_name"), (getter)GetFullName, NULL, "Full name", NULL},
{ C("name"), (getter)GetName, NULL, "last name", NULL},
{ C("cpp_type"), (getter)GetCppType, NULL, "C++ Type", NULL},
{ C("label"), (getter)GetLabel, NULL, "Label", NULL},
{ C("id"), (getter)GetID, NULL, "ID", NULL},
{NULL}
};
} // namespace cfield_descriptor
PyTypeObject CFieldDescriptor_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
C("google.protobuf.internal."
"_net_proto2___python."
"CFieldDescriptor"), // tp_name
sizeof(CFieldDescriptor), // tp_basicsize
0, // tp_itemsize
(destructor)cfield_descriptor::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
C("A Field Descriptor"), // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
cfield_descriptor::Getters, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyType_GenericAlloc, // tp_alloc
PyType_GenericNew, // tp_new
PyObject_Del, // tp_free
};
namespace cdescriptor_pool {
static void Dealloc(CDescriptorPool* self) {
Py_TYPE(self)->tp_free(reinterpret_cast<PyObject*>(self));
}
static PyObject* NewCDescriptor(
const google::protobuf::FieldDescriptor* field_descriptor) {
CFieldDescriptor* cfield_descriptor = PyObject_New(
CFieldDescriptor, &CFieldDescriptor_Type);
if (cfield_descriptor == NULL) {
return NULL;
}
cfield_descriptor->descriptor = field_descriptor;
cfield_descriptor->descriptor_field = NULL;
return reinterpret_cast<PyObject*>(cfield_descriptor);
}
PyObject* FindFieldByName(CDescriptorPool* self, PyObject* name) {
const char* full_field_name = PyString_AsString(name);
if (full_field_name == NULL) {
return NULL;
}
const google::protobuf::FieldDescriptor* field_descriptor = NULL;
field_descriptor = self->pool->FindFieldByName(full_field_name);
if (field_descriptor == NULL) {
PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s",
full_field_name);
return NULL;
}
return NewCDescriptor(field_descriptor);
}
PyObject* FindExtensionByName(CDescriptorPool* self, PyObject* arg) {
const char* full_field_name = PyString_AsString(arg);
if (full_field_name == NULL) {
return NULL;
}
const google::protobuf::FieldDescriptor* field_descriptor =
self->pool->FindExtensionByName(full_field_name);
if (field_descriptor == NULL) {
PyErr_Format(PyExc_TypeError, "Couldn't find field %.200s",
full_field_name);
return NULL;
}
return NewCDescriptor(field_descriptor);
}
static PyMethodDef Methods[] = {
{ C("FindFieldByName"),
(PyCFunction)FindFieldByName,
METH_O,
C("Searches for a field descriptor by full name.") },
{ C("FindExtensionByName"),
(PyCFunction)FindExtensionByName,
METH_O,
C("Searches for extension descriptor by full name.") },
{NULL}
};
} // namespace cdescriptor_pool
PyTypeObject CDescriptorPool_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
C("google.protobuf.internal."
"_net_proto2___python."
"CFieldDescriptor"), // tp_name
sizeof(CDescriptorPool), // tp_basicsize
0, // tp_itemsize
(destructor)cdescriptor_pool::Dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_compare
0, // tp_repr
0, // tp_as_number
0, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT, // tp_flags
C("A Descriptor Pool"), // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
cdescriptor_pool::Methods, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
0, // tp_init
PyType_GenericAlloc, // tp_alloc
PyType_GenericNew, // tp_new
PyObject_Del, // tp_free
};
google::protobuf::DescriptorPool* GetDescriptorPool() {
if (g_descriptor_pool == NULL) {
g_descriptor_pool = new google::protobuf::DescriptorPool(
google::protobuf::DescriptorPool::generated_pool());
}
return g_descriptor_pool;
}
PyObject* Python_NewCDescriptorPool(PyObject* ignored, PyObject* args) {
CDescriptorPool* cdescriptor_pool = PyObject_New(
CDescriptorPool, &CDescriptorPool_Type);
if (cdescriptor_pool == NULL) {
return NULL;
}
cdescriptor_pool->pool = GetDescriptorPool();
return reinterpret_cast<PyObject*>(cdescriptor_pool);
}
// Collects errors that occur during proto file building to allow them to be
// propagated in the python exception instead of only living in ERROR logs.
class BuildFileErrorCollector : public google::protobuf::DescriptorPool::ErrorCollector {
public:
BuildFileErrorCollector() : error_message(""), had_errors(false) {}
void AddError(const string& filename, const string& element_name,
const Message* descriptor, ErrorLocation location,
const string& message) {
// Replicates the logging behavior that happens in the C++ implementation
// when an error collector is not passed in.
if (!had_errors) {
error_message +=
("Invalid proto descriptor for file \"" + filename + "\":\n");
}
// As this only happens on failure and will result in the program not
// running at all, no effort is made to optimize this string manipulation.
error_message += (" " + element_name + ": " + message + "\n");
}
string error_message;
bool had_errors;
};
PyObject* Python_BuildFile(PyObject* ignored, PyObject* arg) {
char* message_type;
Py_ssize_t message_len;
if (PyBytes_AsStringAndSize(arg, &message_type, &message_len) < 0) {
return NULL;
}
google::protobuf::FileDescriptorProto file_proto;
if (!file_proto.ParseFromArray(message_type, message_len)) {
PyErr_SetString(PyExc_TypeError, "Couldn't parse file content!");
return NULL;
}
if (google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
file_proto.name()) != NULL) {
Py_RETURN_NONE;
}
BuildFileErrorCollector error_collector;
const google::protobuf::FileDescriptor* descriptor =
GetDescriptorPool()->BuildFileCollectingErrors(file_proto,
&error_collector);
if (descriptor == NULL) {
PyErr_Format(PyExc_TypeError,
"Couldn't build proto file into descriptor pool!\n%s",
error_collector.error_message.c_str());
return NULL;
}
Py_RETURN_NONE;
}
bool InitDescriptor() {
CFieldDescriptor_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&CFieldDescriptor_Type) < 0)
return false;
CDescriptorPool_Type.tp_new = PyType_GenericNew;
if (PyType_Ready(&CDescriptorPool_Type) < 0)
return false;
return true;
}
} // namespace python
} // namespace protobuf
} // namespace google
| cherrishes/weilai | xingxing/protobuf/python/lib/Python3.4/google/protobuf/pyext/descriptor.cc | C++ | apache-2.0 | 13,106 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Shell;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* This class tests reliability of the framework in the face of failures of
* both tasks and tasktrackers. Steps:
* 1) Get the cluster status
* 2) Get the number of slots in the cluster
* 3) Spawn a sleepjob that occupies the entire cluster (with two waves of maps)
* 4) Get the list of running attempts for the job
* 5) Fail a few of them
* 6) Now fail a few trackers (ssh)
* 7) Job should run to completion
* 8) The above is repeated for the Sort suite of job (randomwriter, sort,
* validator). All jobs must complete, and finally, the sort validation
* should succeed.
* To run the test:
* ./bin/hadoop --config <config> jar
* build/hadoop-<version>-test.jar MRReliabilityTest -libjars
* build/hadoop-<version>-examples.jar [-scratchdir <dir>]"
*
* The scratchdir is optional and by default the current directory on the client
* will be used as the scratch space. Note that password-less SSH must be set up
* between the client machine from where the test is submitted, and the cluster
* nodes where the test runs.
*
* The test should be run on a <b>free</b> cluster where there is no other parallel
* job submission going on. Submission of other jobs while the test runs can cause
* the tests/jobs submitted to fail.
*/
public class ReliabilityTest extends Configured implements Tool {
private String dir;
private static final Log LOG = LogFactory.getLog(ReliabilityTest.class);
private void displayUsage() {
LOG.info("This must be run in only the distributed mode " +
"(LocalJobRunner not supported).\n\tUsage: MRReliabilityTest " +
"-libjars <path to hadoop-examples.jar> [-scratchdir <dir>]" +
"\n[-scratchdir] points to a scratch space on this host where temp" +
" files for this test will be created. Defaults to current working" +
" dir. \nPasswordless SSH must be set up between this host and the" +
" nodes which the test is going to use.\n"+
"The test should be run on a free cluster with no parallel job submission" +
" going on, as the test requires to restart TaskTrackers and kill tasks" +
" any job submission while the tests are running can cause jobs/tests to fail");
System.exit(-1);
}
public int run(String[] args) throws Exception {
Configuration conf = getConf();
if ("local".equals(conf.get("mapred.job.tracker", "local"))) {
displayUsage();
}
String[] otherArgs =
new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length == 2) {
if (otherArgs[0].equals("-scratchdir")) {
dir = otherArgs[1];
} else {
displayUsage();
}
}
else if (otherArgs.length == 0) {
dir = System.getProperty("user.dir");
} else {
displayUsage();
}
//to protect against the case of jobs failing even when multiple attempts
//fail, set some high values for the max attempts
conf.setInt("mapred.map.max.attempts", 10);
conf.setInt("mapred.reduce.max.attempts", 10);
runSleepJobTest(new JobClient(new JobConf(conf)), conf);
runSortJobTests(new JobClient(new JobConf(conf)), conf);
return 0;
}
private void runSleepJobTest(final JobClient jc, final Configuration conf)
throws Exception {
ClusterStatus c = jc.getClusterStatus();
int maxMaps = c.getMaxMapTasks() * 2;
int maxReduces = maxMaps;
int mapSleepTime = (int)c.getTTExpiryInterval();
int reduceSleepTime = mapSleepTime;
String[] sleepJobArgs = new String[] {
"-m", Integer.toString(maxMaps),
"-r", Integer.toString(maxReduces),
"-mt", Integer.toString(mapSleepTime),
"-rt", Integer.toString(reduceSleepTime)};
runTest(jc, conf, "org.apache.hadoop.examples.SleepJob", sleepJobArgs,
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.4f, false, 1));
LOG.info("SleepJob done");
}
private void runSortJobTests(final JobClient jc, final Configuration conf)
throws Exception {
String inputPath = "my_reliability_test_input";
String outputPath = "my_reliability_test_output";
FileSystem fs = jc.getFs();
fs.delete(new Path(inputPath), true);
fs.delete(new Path(outputPath), true);
runRandomWriterTest(jc, conf, inputPath);
runSortTest(jc, conf, inputPath, outputPath);
runSortValidatorTest(jc, conf, inputPath, outputPath);
}
private void runRandomWriterTest(final JobClient jc,
final Configuration conf, final String inputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.RandomWriter",
new String[]{inputPath},
null, new KillTrackerThread(jc, 0, 0.4f, false, 1));
LOG.info("RandomWriter job done");
}
private void runSortTest(final JobClient jc, final Configuration conf,
final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.examples.Sort",
new String[]{inputPath, outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 2),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("Sort job done");
}
private void runSortValidatorTest(final JobClient jc,
final Configuration conf, final String inputPath, final String outputPath)
throws Exception {
runTest(jc, conf, "org.apache.hadoop.mapred.SortValidator", new String[] {
"-sortInput", inputPath, "-sortOutput", outputPath},
new KillTaskThread(jc, 2, 0.2f, false, 1),
new KillTrackerThread(jc, 2, 0.8f, false, 1));
LOG.info("SortValidator job done");
}
private String normalizeCommandPath(String command) {
final String hadoopHome;
if ((hadoopHome = System.getenv("HADOOP_HOME")) != null) {
command = hadoopHome + "/" + command;
}
return command;
}
private void checkJobExitStatus(int status, String jobName) {
if (status != 0) {
LOG.info(jobName + " job failed with status: " + status);
System.exit(status);
} else {
LOG.info(jobName + " done.");
}
}
//Starts the job in a thread. It also starts the taskKill/tasktrackerKill
//threads.
private void runTest(final JobClient jc, final Configuration conf,
final String jobClass, final String[] args, KillTaskThread killTaskThread,
KillTrackerThread killTrackerThread) throws Exception {
Thread t = new Thread("Job Test") {
public void run() {
try {
Class<?> jobClassObj = conf.getClassByName(jobClass);
int status = ToolRunner.run(conf, (Tool)(jobClassObj.newInstance()),
args);
checkJobExitStatus(status, jobClass);
} catch (Exception e) {
LOG.fatal("JOB " + jobClass + " failed to run");
System.exit(-1);
}
}
};
t.setDaemon(true);
t.start();
JobStatus[] jobs;
//get the job ID. This is the job that we just submitted
while ((jobs = jc.jobsToComplete()).length == 0) {
LOG.info("Waiting for the job " + jobClass +" to start");
Thread.sleep(1000);
}
JobID jobId = jobs[jobs.length - 1].getJobID();
RunningJob rJob = jc.getJob(jobId);
if(rJob.isComplete()) {
LOG.error("The last job returned by the querying JobTracker is complete :" +
rJob.getJobID() + " .Exiting the test");
System.exit(-1);
}
while (rJob.getJobState() == JobStatus.PREP) {
LOG.info("JobID : " + jobId + " not started RUNNING yet");
Thread.sleep(1000);
rJob = jc.getJob(jobId);
}
if (killTaskThread != null) {
killTaskThread.setRunningJob(rJob);
killTaskThread.start();
killTaskThread.join();
LOG.info("DONE WITH THE TASK KILL/FAIL TESTS");
}
if (killTrackerThread != null) {
killTrackerThread.setRunningJob(rJob);
killTrackerThread.start();
killTrackerThread.join();
LOG.info("DONE WITH THE TESTS TO DO WITH LOST TASKTRACKERS");
}
t.join();
}
private class KillTrackerThread extends Thread {
private volatile boolean killed = false;
private JobClient jc;
private RunningJob rJob;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
final private String slavesFile = dir + "/_reliability_test_slaves_file_";
final String shellCommand = normalizeCommandPath("bin/slaves.sh");
final private String STOP_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s STOP";
final private String RESUME_COMMAND = "ps uwwx | grep java | grep " +
"org.apache.hadoop.mapred.TaskTracker"+ " |" +
" grep -v grep | tr -s ' ' | cut -d ' ' -f2 | xargs kill -s CONT";
//Only one instance must be active at any point
public KillTrackerThread(JobClient jc, int threshaldMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = threshaldMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
stopStartTrackers(true);
if (!onlyMapsProgress) {
stopStartTrackers(false);
}
}
private void stopStartTrackers(boolean considerMaps) {
if (considerMaps) {
LOG.info("Will STOP/RESUME tasktrackers based on Maps'" +
" progress");
} else {
LOG.info("Will STOP/RESUME tasktrackers based on " +
"Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
ClusterStatus c;
stopTaskTrackers((c = jc.getClusterStatus(true)));
Thread.sleep((int)Math.ceil(1.5 * c.getTTExpiryInterval()));
startTaskTrackers();
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
return;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
private void stopTaskTrackers(ClusterStatus c) throws Exception {
Collection <String> trackerNames = c.getActiveTrackerNames();
ArrayList<String> trackerNamesList = new ArrayList<String>(trackerNames);
Collections.shuffle(trackerNamesList);
int count = 0;
FileOutputStream fos = new FileOutputStream(new File(slavesFile));
LOG.info(new Date() + " Stopping a few trackers");
for (String tracker : trackerNamesList) {
String host = convertTrackerNameToHostName(tracker);
LOG.info(new Date() + " Marking tracker on host: " + host);
fos.write((host + "\n").getBytes());
if (count++ >= trackerNamesList.size()/2) {
break;
}
}
fos.close();
runOperationOnTT("suspend");
}
private void startTaskTrackers() throws Exception {
LOG.info(new Date() + " Resuming the stopped trackers");
runOperationOnTT("resume");
new File(slavesFile).delete();
}
private void runOperationOnTT(String operation) throws IOException {
Map<String,String> hMap = new HashMap<String,String>();
hMap.put("HADOOP_SLAVES", slavesFile);
StringTokenizer strToken;
if (operation.equals("suspend")) {
strToken = new StringTokenizer(STOP_COMMAND, " ");
} else {
strToken = new StringTokenizer(RESUME_COMMAND, " ");
}
String commandArgs[] = new String[strToken.countTokens() + 1];
int i = 0;
commandArgs[i++] = shellCommand;
while (strToken.hasMoreTokens()) {
commandArgs[i++] = strToken.nextToken();
}
String output = Shell.execCommand(hMap, commandArgs);
if (output != null && !output.equals("")) {
LOG.info(output);
}
}
private String convertTrackerNameToHostName(String trackerName) {
// Convert the trackerName to it's host name
int indexOfColon = trackerName.indexOf(":");
String trackerHostName = (indexOfColon == -1) ?
trackerName :
trackerName.substring(0, indexOfColon);
return trackerHostName.substring("tracker_".length());
}
}
private class KillTaskThread extends Thread {
private volatile boolean killed = false;
private RunningJob rJob;
private JobClient jc;
final private int thresholdMultiplier;
private float threshold = 0.2f;
private boolean onlyMapsProgress;
private int numIterations;
public KillTaskThread(JobClient jc, int thresholdMultiplier,
float threshold, boolean onlyMapsProgress, int numIterations) {
this.jc = jc;
this.thresholdMultiplier = thresholdMultiplier;
this.threshold = threshold;
this.onlyMapsProgress = onlyMapsProgress;
this.numIterations = numIterations;
setDaemon(true);
}
public void setRunningJob(RunningJob rJob) {
this.rJob = rJob;
}
public void kill() {
killed = true;
}
public void run() {
killBasedOnProgress(true);
if (!onlyMapsProgress) {
killBasedOnProgress(false);
}
}
private void killBasedOnProgress(boolean considerMaps) {
boolean fail = false;
if (considerMaps) {
LOG.info("Will kill tasks based on Maps' progress");
} else {
LOG.info("Will kill tasks based on Reduces' progress");
}
LOG.info("Initial progress threshold: " + threshold +
". Threshold Multiplier: " + thresholdMultiplier +
". Number of iterations: " + numIterations);
float thresholdVal = threshold;
int numIterationsDone = 0;
while (!killed) {
try {
float progress;
if (jc.getJob(rJob.getID()).isComplete() ||
numIterationsDone == numIterations) {
break;
}
if (considerMaps) {
progress = jc.getJob(rJob.getID()).mapProgress();
} else {
progress = jc.getJob(rJob.getID()).reduceProgress();
}
if (progress >= thresholdVal) {
numIterationsDone++;
if (numIterationsDone > 0 && numIterationsDone % 2 == 0) {
fail = true; //fail tasks instead of kill
}
ClusterStatus c = jc.getClusterStatus();
LOG.info(new Date() + " Killing a few tasks");
Collection<TaskAttemptID> runningTasks =
new ArrayList<TaskAttemptID>();
TaskReport mapReports[] = jc.getMapTaskReports(rJob.getID());
for (TaskReport mapReport : mapReports) {
if (mapReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(mapReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
runningTasks.clear();
TaskReport reduceReports[] = jc.getReduceTaskReports(rJob.getID());
for (TaskReport reduceReport : reduceReports) {
if (reduceReport.getCurrentStatus() == TIPStatus.RUNNING) {
runningTasks.addAll(reduceReport.getRunningTaskAttempts());
}
}
if (runningTasks.size() > c.getTaskTrackers()/2) {
int count = 0;
for (TaskAttemptID t : runningTasks) {
LOG.info(new Date() + " Killed task : " + t);
rJob.killTask(t, fail);
if (count++ > runningTasks.size()/2) { //kill 50%
break;
}
}
}
thresholdVal = thresholdVal * thresholdMultiplier;
}
Thread.sleep(5000);
} catch (InterruptedException ie) {
killed = true;
} catch (Exception e) {
LOG.fatal(StringUtils.stringifyException(e));
}
}
}
}
public static void main(String args[]) throws Exception {
int res = ToolRunner.run(new Configuration(), new ReliabilityTest(), args);
System.exit(res);
}
} | shakamunyi/hadoop-20 | src/test/org/apache/hadoop/mapred/ReliabilityTest.java | Java | apache-2.0 | 18,910 |
a enum; | Jazzling/jazzle-parser | test/test-esprima/fixtures/invalid-syntax/migrated_0115.js | JavaScript | mit | 7 |
<?php
// This file is part of Moodle - https://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <https://www.gnu.org/licenses/>.
/**
* Automatically generated strings for Moodle installer
*
* Do not edit this file manually! It contains just a subset of strings
* needed during the very first steps of installation. This file was
* generated automatically by export-installer.php (which is part of AMOS
* {@link http://docs.moodle.org/dev/Languages/AMOS}) using the
* list of strings defined in /install/stringnames.txt.
*
* @package installer
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['cannotcreatelangdir'] = 'Hindi makalikha ng lang bgsk.';
$string['cannotcreatetempdir'] = 'Hindi makalikha ng temp bgsk.';
$string['cannotdownloadcomponents'] = 'Hindi mai-download ang mga sangkap';
$string['cannotdownloadzipfile'] = 'Hindi mai-download ang ZIP file.';
$string['cannotfindcomponent'] = 'Hindi makita ang component.';
$string['cannotsavemd5file'] = 'Hindi mai-save ang file na md5.';
$string['cannotsavezipfile'] = 'Hindi mai-save ang file na ZIP.';
$string['cannotunzipfile'] = 'Hindi mai-unzip ang file.';
$string['componentisuptodate'] = 'Up-to-date ang component.';
$string['downloadedfilecheckfailed'] = 'Bigo ang pagsusuri sa idinownload na file.';
$string['invalidmd5'] = 'Mali ang check variable - paki-ulit';
$string['missingrequiredfield'] = 'May ilang nawawalang field na kailangan';
$string['wrongdestpath'] = 'Mali ang patutunguhang landas';
$string['wrongsourcebase'] = 'Mali ang URL base ng source.';
$string['wrongzipfilename'] = 'Mali ang pangalan ng ZIP file';
| michael-milette/moodle | install/lang/tl/error.php | PHP | gpl-3.0 | 2,237 |
package butterknife;
import android.view.View;
import butterknife.internal.ListenerClass;
import butterknife.internal.ListenerMethod;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static android.widget.AdapterView.OnItemSelectedListener;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.CLASS;
/**
* Bind a method to an {@link OnItemSelectedListener OnItemSelectedListener} on the view for each
* ID specified.
* <pre><code>
* {@literal @}OnItemSelected(R.id.example_list) void onItemSelected(int position) {
* Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
* Any number of parameters from
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View, int,
* long) onItemSelected} may be used on the method.
* <p>
* To bind to methods other than {@code onItemSelected}, specify a different {@code callback}.
* <pre><code>
* {@literal @}OnItemSelected(value = R.id.example_list, callback = NOTHING_SELECTED)
* void onNothingSelected() {
* Toast.makeText(this, "Nothing selected!", Toast.LENGTH_SHORT).show();
* }
* </code></pre>
*
* @see OnItemSelectedListener
*/
@Target(METHOD)
@Retention(CLASS)
@ListenerClass(
targetType = "android.widget.AdapterView<?>",
setter = "setOnItemSelectedListener",
type = "android.widget.AdapterView.OnItemSelectedListener",
callbacks = OnItemSelected.Callback.class
)
public @interface OnItemSelected {
/** View IDs to which the method will be bound. */
int[] value() default { View.NO_ID };
/** Listener callback to which the method will be bound. */
Callback callback() default Callback.ITEM_SELECTED;
/** {@link OnItemSelectedListener} callback methods. */
enum Callback {
/**
* {@link OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View,
* int, long)}
*/
@ListenerMethod(
name = "onItemSelected",
parameters = {
"android.widget.AdapterView<?>",
"android.view.View",
"int",
"long"
}
)
ITEM_SELECTED,
/** {@link OnItemSelectedListener#onNothingSelected(android.widget.AdapterView)} */
@ListenerMethod(
name = "onNothingSelected",
parameters = "android.widget.AdapterView<?>"
)
NOTHING_SELECTED
}
}
| carollynn2253/butterknife | butterknife/src/main/java/butterknife/OnItemSelected.java | Java | apache-2.0 | 2,447 |
topojson = (function() {
function merge(topology, arcs) {
var arcsByEnd = {},
fragmentByStart = {},
fragmentByEnd = {};
arcs.forEach(function(i) {
var e = ends(i);
(arcsByEnd[e[0]] || (arcsByEnd[e[0]] = [])).push(i);
(arcsByEnd[e[1]] || (arcsByEnd[e[1]] = [])).push(~i);
});
arcs.forEach(function(i) {
var e = ends(i),
start = e[0],
end = e[1],
f, g;
if (f = fragmentByEnd[start]) {
delete fragmentByEnd[f.end];
f.push(i);
f.end = end;
if (g = fragmentByStart[end]) {
delete fragmentByStart[g.start];
var fg = g === f ? f : f.concat(g);
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
} else if (g = fragmentByEnd[end]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByStart[end]) {
delete fragmentByStart[f.start];
f.unshift(i);
f.start = start;
if (g = fragmentByEnd[start]) {
delete fragmentByEnd[g.end];
var gf = g === f ? f : g.concat(f);
fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
} else if (g = fragmentByStart[start]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByStart[start]) {
delete fragmentByStart[f.start];
f.unshift(~i);
f.start = end;
if (g = fragmentByEnd[end]) {
delete fragmentByEnd[g.end];
var gf = g === f ? f : g.concat(f);
fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
} else if (g = fragmentByStart[end]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var gf = g.map(function(i) { return ~i; }).reverse().concat(f);
fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else if (f = fragmentByEnd[end]) {
delete fragmentByEnd[f.end];
f.push(~i);
f.end = start;
if (g = fragmentByEnd[start]) {
delete fragmentByStart[g.start];
var fg = g === f ? f : f.concat(g);
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
} else if (g = fragmentByStart[start]) {
delete fragmentByStart[g.start];
delete fragmentByEnd[g.end];
var fg = f.concat(g.map(function(i) { return ~i; }).reverse());
fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg;
} else {
fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
}
} else {
f = [i];
fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
}
});
function ends(i) {
var arc = topology.arcs[i], p0 = arc[0], p1 = [0, 0];
arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
return [p0, p1];
}
var fragments = [];
for (var k in fragmentByEnd) fragments.push(fragmentByEnd[k]);
return fragments;
}
function mesh(topology, o, filter) {
var arcs = [];
if (arguments.length > 1) {
var geomsByArc = [],
geom;
function arc(i) {
if (i < 0) i = ~i;
(geomsByArc[i] || (geomsByArc[i] = [])).push(geom);
}
function line(arcs) {
arcs.forEach(arc);
}
function polygon(arcs) {
arcs.forEach(line);
}
function geometry(o) {
if (o.type === "GeometryCollection") o.geometries.forEach(geometry);
else if (o.type in geometryType) {
geom = o;
geometryType[o.type](o.arcs);
}
}
var geometryType = {
LineString: line,
MultiLineString: polygon,
Polygon: polygon,
MultiPolygon: function(arcs) { arcs.forEach(polygon); }
};
geometry(o);
geomsByArc.forEach(arguments.length < 3
? function(geoms, i) { arcs.push([i]); }
: function(geoms, i) { if (filter(geoms[0], geoms[geoms.length - 1])) arcs.push([i]); });
} else {
for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push([i]);
}
return object(topology, {type: "MultiLineString", arcs: merge(topology, arcs)});
}
function object(topology, o) {
var tf = topology.transform,
kx = tf.scale[0],
ky = tf.scale[1],
dx = tf.translate[0],
dy = tf.translate[1],
arcs = topology.arcs;
function arc(i, points) {
if (points.length) points.pop();
for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, x = 0, y = 0, p; k < n; ++k) points.push([
(x += (p = a[k])[0]) * kx + dx,
(y += p[1]) * ky + dy
]);
if (i < 0) reverse(points, n);
}
function point(coordinates) {
return [coordinates[0] * kx + dx, coordinates[1] * ky + dy];
}
function line(arcs) {
var points = [];
for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
if (points.length < 2) points.push(points[0]);
return points;
}
function ring(arcs) {
var points = line(arcs);
while (points.length < 4) points.push(points[0]);
return points;
}
function polygon(arcs) {
return arcs.map(ring);
}
function geometry(o) {
var t = o.type, g = t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
: t in geometryType ? {type: t, coordinates: geometryType[t](o)}
: {type: null};
if ("id" in o) g.id = o.id;
if ("properties" in o) g.properties = o.properties;
return g;
}
var geometryType = {
Point: function(o) { return point(o.coordinates); },
MultiPoint: function(o) { return o.coordinates.map(point); },
LineString: function(o) { return line(o.arcs); },
MultiLineString: function(o) { return o.arcs.map(line); },
Polygon: function(o) { return polygon(o.arcs); },
MultiPolygon: function(o) { return o.arcs.map(polygon); }
};
return geometry(o);
}
function reverse(array, n) {
var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
}
function bisect(a, x) {
var lo = 0, hi = a.length;
while (lo < hi) {
var mid = lo + hi >>> 1;
if (a[mid] < x) lo = mid + 1;
else hi = mid;
}
return lo;
}
function neighbors(objects) {
var objectsByArc = [],
neighbors = objects.map(function() { return []; });
function line(arcs, i) {
arcs.forEach(function(a) {
if (a < 0) a = ~a;
var o = objectsByArc[a] || (objectsByArc[a] = []);
if (!o[i]) o.forEach(function(j) {
var n, k;
k = bisect(n = neighbors[i], j); if (n[k] !== j) n.splice(k, 0, j);
k = bisect(n = neighbors[j], i); if (n[k] !== i) n.splice(k, 0, i);
}), o[i] = i;
});
}
function polygon(arcs, i) {
arcs.forEach(function(arc) { line(arc, i); });
}
function geometry(o, i) {
if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
}
var geometryType = {
LineString: line,
MultiLineString: polygon,
Polygon: polygon,
MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
};
objects.forEach(geometry);
return neighbors;
}
return {
version: "0.0.28",
mesh: mesh,
object: object,
neighbors: neighbors
};
})();
| pzp1997/cdnjs | ajax/libs/topojson/0.0.28/topojson.js | JavaScript | mit | 8,261 |
#--
# Copyright (c) 2006-2013 Philip Ross
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#++
module TZInfo
# Represents an offset defined in a Timezone data file.
#
# @private
class TimezoneOffsetInfo #:nodoc:
# The base offset of the timezone from UTC in seconds.
attr_reader :utc_offset
# The offset from standard time for the zone in seconds (i.e. non-zero if
# daylight savings is being observed).
attr_reader :std_offset
# The total offset of this observance from UTC in seconds
# (utc_offset + std_offset).
attr_reader :utc_total_offset
# The abbreviation that identifies this observance, e.g. "GMT"
# (Greenwich Mean Time) or "BST" (British Summer Time) for "Europe/London". The returned identifier is a
# symbol.
attr_reader :abbreviation
# Constructs a new TimezoneOffsetInfo. utc_offset and std_offset are
# specified in seconds.
def initialize(utc_offset, std_offset, abbreviation)
@utc_offset = utc_offset
@std_offset = std_offset
@abbreviation = abbreviation
@utc_total_offset = @utc_offset + @std_offset
end
# True if std_offset is non-zero.
def dst?
@std_offset != 0
end
# Converts a UTC DateTime to local time based on the offset of this period.
def to_local(utc)
TimeOrDateTime.wrap(utc) {|wrapped|
wrapped + @utc_total_offset
}
end
# Converts a local DateTime to UTC based on the offset of this period.
def to_utc(local)
TimeOrDateTime.wrap(local) {|wrapped|
wrapped - @utc_total_offset
}
end
# Returns true if and only if toi has the same utc_offset, std_offset
# and abbreviation as this TimezoneOffsetInfo.
def ==(toi)
toi.kind_of?(TimezoneOffsetInfo) &&
utc_offset == toi.utc_offset && std_offset == toi.std_offset && abbreviation == toi.abbreviation
end
# Returns true if and only if toi has the same utc_offset, std_offset
# and abbreviation as this TimezoneOffsetInfo.
def eql?(toi)
self == toi
end
# Returns a hash of this TimezoneOffsetInfo.
def hash
utc_offset.hash ^ std_offset.hash ^ abbreviation.hash
end
# Returns internal object state as a programmer-readable string.
def inspect
"#<#{self.class}: #@utc_offset,#@std_offset,#@abbreviation>"
end
end
end
| apcomplete/devise_security_questions | vendor/ruby/gems/tzinfo-0.3.39/lib/tzinfo/timezone_offset_info.rb | Ruby | mit | 3,439 |
define(
"dijit/form/nls/ca/validate", ({
invalidMessage: "El valor introduït no és vàlid",
missingMessage: "Aquest valor és necessari",
rangeMessage: "Aquest valor és fora de l'interval"
})
);
| Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dijit/form/nls/ca/validate.js.uncompressed.js | JavaScript | apache-2.0 | 201 |
/*
Copyright © 2002, The KPD-Team
All rights reserved.
http://www.mentalis.org/
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.
- Neither the name of the KPD-Team, 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.
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Org.Mentalis.Network.ProxySocket.Authentication {
/// <summary>
/// This class implements the 'username/password authentication' scheme.
/// </summary>
internal sealed class AuthUserPass : AuthMethod {
/// <summary>
/// Initializes a new AuthUserPass instance.
/// </summary>
/// <param name="server">The socket connection with the proxy server.</param>
/// <param name="user">The username to use.</param>
/// <param name="pass">The password to use.</param>
/// <exception cref="ArgumentNullException"><c>user</c> -or- <c>pass</c> is null.</exception>
public AuthUserPass(Socket server, string user, string pass) : base(server) {
Username = user;
Password = pass;
}
/// <summary>
/// Creates an array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.
/// </summary>
/// <returns>An array of bytes that has to be sent if the user wants to authenticate with the username/password authentication scheme.</returns>
private byte[] GetAuthenticationBytes() {
byte[] buffer = new byte[3 + Username.Length + Password.Length];
buffer[0] = 1;
buffer[1] = (byte)Username.Length;
Array.Copy(Encoding.ASCII.GetBytes(Username), 0, buffer, 2, Username.Length);
buffer[Username.Length + 2] = (byte)Password.Length;
Array.Copy(Encoding.ASCII.GetBytes(Password), 0, buffer, Username.Length + 3, Password.Length);
return buffer;
}
/// <summary>
/// Starts the authentication process.
/// </summary>
public override void Authenticate() {
Server.Send(GetAuthenticationBytes());
byte[] buffer = new byte[2];
int received = 0;
while (received != 2) {
received += Server.Receive(buffer, received, 2 - received, SocketFlags.None);
}
if (buffer[1] != 0) {
Server.Close();
throw new ProxyException("Username/password combination rejected.");
}
return;
}
/// <summary>
/// Starts the asynchronous authentication process.
/// </summary>
/// <param name="callback">The method to call when the authentication is complete.</param>
public override void BeginAuthenticate(HandShakeComplete callback) {
CallBack = callback;
Server.BeginSend(GetAuthenticationBytes(), 0, 3 + Username.Length + Password.Length, SocketFlags.None, new AsyncCallback(this.OnSent), Server);
return;
}
/// <summary>
/// Called when the authentication bytes have been sent.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnSent(IAsyncResult ar) {
try {
Server.EndSend(ar);
Buffer = new byte[2];
Server.BeginReceive(Buffer, 0, 2, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
CallBack(e);
}
}
/// <summary>
/// Called when the socket received an authentication reply.
/// </summary>
/// <param name="ar">Stores state information for this asynchronous operation as well as any user-defined data.</param>
private void OnReceive(IAsyncResult ar) {
try {
Received += Server.EndReceive(ar);
if (Received == Buffer.Length)
if (Buffer[1] == 0)
CallBack(null);
else
throw new ProxyException("Username/password combination not accepted.");
else
Server.BeginReceive(Buffer, Received, Buffer.Length - Received, SocketFlags.None, new AsyncCallback(this.OnReceive), Server);
} catch (Exception e) {
CallBack(e);
}
}
/// <summary>
/// Gets or sets the username to use when authenticating with the proxy server.
/// </summary>
/// <value>The username to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Username {
get {
return m_Username;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Username = value;
}
}
/// <summary>
/// Gets or sets the password to use when authenticating with the proxy server.
/// </summary>
/// <value>The password to use when authenticating with the proxy server.</value>
/// <exception cref="ArgumentNullException">The specified value is null.</exception>
private string Password {
get {
return m_Password;
}
set {
if (value == null)
throw new ArgumentNullException();
m_Password = value;
}
}
// private variables
/// <summary>Holds the value of the Username property.</summary>
private string m_Username;
/// <summary>Holds the value of the Password property.</summary>
private string m_Password;
}
} | kolrabi/DesktopBooru | Sources/Network/ProxySocket/AuthUserPass.cs | C# | gpl-3.0 | 6,063 |
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package glacier provides the client and types for making API
// requests to Amazon Glacier.
//
// Amazon Glacier is a storage solution for "cold data."
//
// Amazon Glacier is an extremely low-cost storage service that provides secure,
// durable, and easy-to-use storage for data backup and archival. With Amazon
// Glacier, customers can store their data cost effectively for months, years,
// or decades. Amazon Glacier also enables customers to offload the administrative
// burdens of operating and scaling storage to AWS, so they don't have to worry
// about capacity planning, hardware provisioning, data replication, hardware
// failure and recovery, or time-consuming hardware migrations.
//
// Amazon Glacier is a great storage choice when low storage cost is paramount,
// your data is rarely retrieved, and retrieval latency of several hours is
// acceptable. If your application requires fast or frequent access to your
// data, consider using Amazon S3. For more information, see Amazon Simple Storage
// Service (Amazon S3) (http://aws.amazon.com/s3/).
//
// You can store any kind of data in any format. There is no maximum limit on
// the total amount of data you can store in Amazon Glacier.
//
// If you are a first-time user of Amazon Glacier, we recommend that you begin
// by reading the following sections in the Amazon Glacier Developer Guide:
//
// * What is Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/introduction.html)
// - This section of the Developer Guide describes the underlying data model,
// the operations it supports, and the AWS SDKs that you can use to interact
// with the service.
//
// * Getting Started with Amazon Glacier (http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-getting-started.html)
// - The Getting Started section walks you through the process of creating
// a vault, uploading archives, creating jobs to download archives, retrieving
// the job output, and deleting archives.
//
// See glacier package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/
//
// Using the Client
//
// To Amazon Glacier with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the Amazon Glacier client Glacier for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/glacier/#New
package glacier
| crobby/oshinko-cli | vendor/github.com/openshift/origin/cmd/cluster-capacity/go/src/github.com/kubernetes-incubator/cluster-capacity/vendor/github.com/aws/aws-sdk-go/service/glacier/doc.go | GO | apache-2.0 | 2,876 |
<?php
/**
* Order details table shown in emails.
*
* This template can be overridden by copying it to yourtheme/woocommerce/emails/plain/email-order-details.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* @see https://docs.woocommerce.com/document/template-structure/
* @author WooThemes
* @package WooCommerce/Templates/Emails
* @version 2.5.0
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
do_action( 'woocommerce_email_before_order_table', $order, $sent_to_admin, $plain_text, $email );
echo strtoupper( sprintf( __( 'Order number: %s', 'woocommerce' ), $order->get_order_number() ) ) . "\n";
echo date_i18n( __( 'jS F Y', 'woocommerce' ), strtotime( $order->order_date ) ) . "\n";
echo "\n" . $order->email_order_items_table( array(
'show_sku' => $sent_to_admin,
'show_image' => false,
'image_size' => array( 32, 32 ),
'plain_text' => true
) );
echo "==========\n\n";
if ( $totals = $order->get_order_item_totals() ) {
foreach ( $totals as $total ) {
echo $total['label'] . "\t " . $total['value'] . "\n";
}
}
if ( $sent_to_admin ) {
echo "\n" . sprintf( __( 'View order: %s', 'woocommerce'), admin_url( 'post.php?post=' . $order->id . '&action=edit' ) ) . "\n";
}
do_action( 'woocommerce_email_after_order_table', $order, $sent_to_admin, $plain_text, $email );
| befair/soulShape | wp/soulshape.earth/wp-content/plugins/woocommerce/templates/emails/plain/email-order-details.php | PHP | agpl-3.0 | 1,630 |
<?php
/*!
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2012, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Providers_MySpace provider adapter based on OAuth1 protocol
*
* http://hybridauth.sourceforge.net/userguide/IDProvider_info_MySpace.html
*/
class Hybrid_Providers_MySpace extends Hybrid_Provider_Model_OAuth1
{
/**
* IDp wrappers initializer
*/
function initialize()
{
parent::initialize();
// Provider api end-points
$this->api->api_endpoint_url = "http://api.myspace.com/v1/";
$this->api->authorize_url = "http://api.myspace.com/authorize";
$this->api->request_token_url = "http://api.myspace.com/request_token";
$this->api->access_token_url = "http://api.myspace.com/access_token";
}
/**
* get the connected uid from myspace api
*/
public function getCurrentUserId()
{
$response = $this->api->get( 'http://api.myspace.com/v1/user.json' );
if ( ! isset( $response->userId ) ){
throw new Exception( "User id request failed! {$this->providerId} returned an invalid response." );
}
return $response->userId;
}
/**
* load the user profile from the IDp api client
*/
function getUserProfile()
{
$userId = $this->getCurrentUserId();
$data = $this->api->get( 'http://api.myspace.com/v1/users/' . $userId . '/profile.json' );
if ( ! is_object( $data ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
}
$this->user->profile->identifier = $userId;
$this->user->profile->displayName = $data->basicprofile->name;
$this->user->profile->description = $data->aboutme;
$this->user->profile->gender = $data->basicprofile->gender;
$this->user->profile->photoURL = $data->basicprofile->image;
$this->user->profile->profileURL = $data->basicprofile->webUri;
$this->user->profile->age = $data->age;
$this->user->profile->country = $data->country;
$this->user->profile->region = $data->region;
$this->user->profile->city = $data->city;
$this->user->profile->zip = $data->postalcode;
return $this->user->profile;
}
/**
* load the user contacts
*/
function getUserContacts()
{
$userId = $this->getCurrentUserId();
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/friends.json" );
if ( ! is_object( $response ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
}
$contacts = ARRAY();
foreach( $response->Friends as $item ){
$uc = new Hybrid_User_Contact();
$uc->identifier = $item->userId;
$uc->displayName = $item->name;
$uc->profileURL = $item->webUri;
$uc->photoURL = $item->image;
$uc->description = $item->status;
$contacts[] = $uc;
}
return $contacts;
}
/**
* update user status
*/
function setUserStatus( $status )
{
// crappy myspace... gonna see this asaic
$userId = $this->getCurrentUserId();
$parameters = array( 'status' => $status );
$response = $this->api->api( "http://api.myspace.com/v1/users/" . $userId . "/status", 'PUT', $parameters );
// check the last HTTP status code returned
if ( $this->api->http_code != 200 )
{
throw new Exception( "Update user status failed! {$this->providerId} returned an error. " . $this->errorMessageByStatus( $this->api->http_code ) );
}
}
/**
* load the user latest activity
* - timeline : all the stream
* - me : the user activity only
*/
function getUserActivity( $stream )
{
$userId = $this->getCurrentUserId();
if( $stream == "me" ){
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/status.json" );
}
else{
$response = $this->api->get( "http://api.myspace.com/v1/users/" . $userId . "/friends/status.json" );
}
if ( ! is_object( $response ) ){
throw new Exception( "User profile request failed! {$this->providerId} returned an invalid response.", 6 );
}
$activities = ARRAY();
if( $stream == "me" ){
// todo
}
else{
foreach( $response->FriendsStatus as $item ){
$ua = new Hybrid_User_Activity();
$ua->id = $item->statusId;
$ua->date = NULL; // to find out!!
$ua->text = $item->status;
$ua->user->identifier = $item->user->userId;
$ua->user->displayName = $item->user->name;
$ua->user->profileURL = $item->user->uri;
$ua->user->photoURL = $item->user->image;
$activities[] = $ua;
}
}
return $activities;
}
}
| tiltfactor/mg-game | www/protected/extensions/HybridAuth/hybridauth-2.1.2/hybridauth/Providers/MySpace.php | PHP | agpl-3.0 | 4,857 |
<?php
namespace Gedmo\Uploadable\Stub;
use Gedmo\Uploadable\FileInfo\FileInfoArray;
class FileInfoStub extends FileInfoArray
{
}
| bantudevelopment/smis | vendor/gedmo1/doctrine-extensions/tests/Gedmo/Uploadable/Stub/FileInfoStub.php | PHP | bsd-3-clause | 132 |
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/disk_cache/blockfile/bitmap.h"
#include <algorithm>
#include "base/logging.h"
namespace {
// Returns the number of trailing zeros.
int FindLSBSetNonZero(uint32 word) {
// Get the LSB, put it on the exponent of a 32 bit float and remove the
// mantisa and the bias. This code requires IEEE 32 bit float compliance.
float f = static_cast<float>(word & -static_cast<int>(word));
// We use a union to go around strict-aliasing complains.
union {
float ieee_float;
uint32 as_uint;
} x;
x.ieee_float = f;
return (x.as_uint >> 23) - 0x7f;
}
// Returns the index of the first bit set to |value| from |word|. This code
// assumes that we'll be able to find that bit.
int FindLSBNonEmpty(uint32 word, bool value) {
// If we are looking for 0, negate |word| and look for 1.
if (!value)
word = ~word;
return FindLSBSetNonZero(word);
}
} // namespace
namespace disk_cache {
Bitmap::Bitmap(int num_bits, bool clear_bits)
: num_bits_(num_bits),
array_size_(RequiredArraySize(num_bits)),
alloc_(true) {
map_ = new uint32[array_size_];
// Initialize all of the bits.
if (clear_bits)
Clear();
}
Bitmap::Bitmap(uint32* map, int num_bits, int num_words)
: map_(map),
num_bits_(num_bits),
// If size is larger than necessary, trim because array_size_ is used
// as a bound by various methods.
array_size_(std::min(RequiredArraySize(num_bits), num_words)),
alloc_(false) {
}
Bitmap::~Bitmap() {
if (alloc_)
delete [] map_;
}
void Bitmap::Resize(int num_bits, bool clear_bits) {
DCHECK(alloc_ || !map_);
const int old_maxsize = num_bits_;
const int old_array_size = array_size_;
array_size_ = RequiredArraySize(num_bits);
if (array_size_ != old_array_size) {
uint32* new_map = new uint32[array_size_];
// Always clear the unused bits in the last word.
new_map[array_size_ - 1] = 0;
memcpy(new_map, map_,
sizeof(*map_) * std::min(array_size_, old_array_size));
if (alloc_)
delete[] map_; // No need to check for NULL.
map_ = new_map;
alloc_ = true;
}
num_bits_ = num_bits;
if (old_maxsize < num_bits_ && clear_bits) {
SetRange(old_maxsize, num_bits_, false);
}
}
void Bitmap::Set(int index, bool value) {
DCHECK_LT(index, num_bits_);
DCHECK_GE(index, 0);
const int i = index & (kIntBits - 1);
const int j = index / kIntBits;
if (value)
map_[j] |= (1 << i);
else
map_[j] &= ~(1 << i);
}
bool Bitmap::Get(int index) const {
DCHECK_LT(index, num_bits_);
DCHECK_GE(index, 0);
const int i = index & (kIntBits-1);
const int j = index / kIntBits;
return ((map_[j] & (1 << i)) != 0);
}
void Bitmap::Toggle(int index) {
DCHECK_LT(index, num_bits_);
DCHECK_GE(index, 0);
const int i = index & (kIntBits - 1);
const int j = index / kIntBits;
map_[j] ^= (1 << i);
}
void Bitmap::SetMapElement(int array_index, uint32 value) {
DCHECK_LT(array_index, array_size_);
DCHECK_GE(array_index, 0);
map_[array_index] = value;
}
uint32 Bitmap::GetMapElement(int array_index) const {
DCHECK_LT(array_index, array_size_);
DCHECK_GE(array_index, 0);
return map_[array_index];
}
void Bitmap::SetMap(const uint32* map, int size) {
memcpy(map_, map, std::min(size, array_size_) * sizeof(*map_));
}
void Bitmap::SetRange(int begin, int end, bool value) {
DCHECK_LE(begin, end);
int start_offset = begin & (kIntBits - 1);
if (start_offset) {
// Set the bits in the first word.
int len = std::min(end - begin, kIntBits - start_offset);
SetWordBits(begin, len, value);
begin += len;
}
if (begin == end)
return;
// Now set the bits in the last word.
int end_offset = end & (kIntBits - 1);
end -= end_offset;
SetWordBits(end, end_offset, value);
// Set all the words in the middle.
memset(map_ + (begin / kIntBits), (value ? 0xFF : 0x00),
((end / kIntBits) - (begin / kIntBits)) * sizeof(*map_));
}
// Return true if any bit between begin inclusive and end exclusive
// is set. 0 <= begin <= end <= bits() is required.
bool Bitmap::TestRange(int begin, int end, bool value) const {
DCHECK_LT(begin, num_bits_);
DCHECK_LE(end, num_bits_);
DCHECK_LE(begin, end);
DCHECK_GE(begin, 0);
DCHECK_GE(end, 0);
// Return false immediately if the range is empty.
if (begin >= end || end <= 0)
return false;
// Calculate the indices of the words containing the first and last bits,
// along with the positions of the bits within those words.
int word = begin / kIntBits;
int offset = begin & (kIntBits - 1);
int last_word = (end - 1) / kIntBits;
int last_offset = (end - 1) & (kIntBits - 1);
// If we are looking for zeros, negate the data from the map.
uint32 this_word = map_[word];
if (!value)
this_word = ~this_word;
// If the range spans multiple words, discard the extraneous bits of the
// first word by shifting to the right, and then test the remaining bits.
if (word < last_word) {
if (this_word >> offset)
return true;
offset = 0;
word++;
// Test each of the "middle" words that lies completely within the range.
while (word < last_word) {
this_word = map_[word++];
if (!value)
this_word = ~this_word;
if (this_word)
return true;
}
}
// Test the portion of the last word that lies within the range. (This logic
// also handles the case where the entire range lies within a single word.)
const uint32 mask = ((2 << (last_offset - offset)) - 1) << offset;
this_word = map_[last_word];
if (!value)
this_word = ~this_word;
return (this_word & mask) != 0;
}
bool Bitmap::FindNextBit(int* index, int limit, bool value) const {
DCHECK_LT(*index, num_bits_);
DCHECK_LE(limit, num_bits_);
DCHECK_LE(*index, limit);
DCHECK_GE(*index, 0);
DCHECK_GE(limit, 0);
const int bit_index = *index;
if (bit_index >= limit || limit <= 0)
return false;
// From now on limit != 0, since if it was we would have returned false.
int word_index = bit_index >> kLogIntBits;
uint32 one_word = map_[word_index];
// Simple optimization where we can immediately return true if the first
// bit is set. This helps for cases where many bits are set, and doesn't
// hurt too much if not.
if (Get(bit_index) == value)
return true;
const int first_bit_offset = bit_index & (kIntBits - 1);
// First word is special - we need to mask off leading bits.
uint32 mask = 0xFFFFFFFF << first_bit_offset;
if (value) {
one_word &= mask;
} else {
one_word |= ~mask;
}
uint32 empty_value = value ? 0 : 0xFFFFFFFF;
// Loop through all but the last word. Note that 'limit' is one
// past the last bit we want to check, and we don't want to read
// past the end of "words". E.g. if num_bits_ == 32 only words[0] is
// valid, so we want to avoid reading words[1] when limit == 32.
const int last_word_index = (limit - 1) >> kLogIntBits;
while (word_index < last_word_index) {
if (one_word != empty_value) {
*index = (word_index << kLogIntBits) + FindLSBNonEmpty(one_word, value);
return true;
}
one_word = map_[++word_index];
}
// Last word is special - we may need to mask off trailing bits. Note that
// 'limit' is one past the last bit we want to check, and if limit is a
// multiple of 32 we want to check all bits in this word.
const int last_bit_offset = (limit - 1) & (kIntBits - 1);
mask = 0xFFFFFFFE << last_bit_offset;
if (value) {
one_word &= ~mask;
} else {
one_word |= mask;
}
if (one_word != empty_value) {
*index = (word_index << kLogIntBits) + FindLSBNonEmpty(one_word, value);
return true;
}
return false;
}
int Bitmap::FindBits(int* index, int limit, bool value) const {
DCHECK_LT(*index, num_bits_);
DCHECK_LE(limit, num_bits_);
DCHECK_LE(*index, limit);
DCHECK_GE(*index, 0);
DCHECK_GE(limit, 0);
if (!FindNextBit(index, limit, value))
return false;
// Now see how many bits have the same value.
int end = *index;
if (!FindNextBit(&end, limit, !value))
return limit - *index;
return end - *index;
}
void Bitmap::SetWordBits(int start, int len, bool value) {
DCHECK_LT(len, kIntBits);
DCHECK_GE(len, 0);
if (!len)
return;
int word = start / kIntBits;
int offset = start % kIntBits;
uint32 to_add = 0xffffffff << len;
to_add = (~to_add) << offset;
if (value) {
map_[word] |= to_add;
} else {
map_[word] &= ~to_add;
}
}
} // namespace disk_cache
| anirudhSK/chromium | net/disk_cache/blockfile/bitmap.cc | C++ | bsd-3-clause | 8,691 |
/*
* Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @bug 4959409
* @author Naoto Sato
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bug4959409 extends javax.swing.JApplet {
public void init() {
new TestFrame();
}
}
class TestFrame extends JFrame implements KeyListener {
JTextField text;
JLabel label;
TestFrame () {
text = new JTextField();
text.addKeyListener(this);
label = new JLabel(" ");
Container c = getContentPane();
BorderLayout borderLayout1 = new BorderLayout();
c.setLayout(borderLayout1);
c.add(text, BorderLayout.CENTER);
c.add(label, BorderLayout.SOUTH);
setSize(300, 200);
setVisible(true);
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
int mods = e.getModifiers();
if (code == '1' && mods == KeyEvent.SHIFT_MASK) {
label.setText("KEYPRESS received for Shift+1");
} else {
label.setText(" ");
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
| rokn/Count_Words_2015 | testing/openjdk2/jdk/test/java/awt/im/4959409/bug4959409.java | Java | mit | 2,168 |
/*
* Copyright (c) 2013-2015 by appPlant UG. All rights reserved.
*
* @APPPLANT_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apache License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://opensource.org/licenses/Apache-2.0/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPPLANT_LICENSE_HEADER_END@
*/
package de.appplant.cordova.plugin.localnotification;
import de.appplant.cordova.plugin.notification.Builder;
import de.appplant.cordova.plugin.notification.Notification;
import de.appplant.cordova.plugin.notification.TriggerReceiver;
/**
* The receiver activity is triggered when a notification is clicked by a user.
* The activity calls the background callback and brings the launch intent
* up to foreground.
*/
public class ClickActivity extends de.appplant.cordova.plugin.notification.ClickActivity {
/**
* Called when local notification was clicked by the user.
*
* @param notification
* Wrapper around the local notification
*/
@Override
public void onClick(Notification notification) {
LocalNotification.fireEvent("click", notification);
if (!notification.getOptions().isOngoing()) {
String event = notification.isRepeating() ? "clear" : "cancel";
LocalNotification.fireEvent(event, notification);
}
super.onClick(notification);
}
/**
* Build notification specified by options.
*
* @param builder
* Notification builder
*/
@Override
public Notification buildNotification (Builder builder) {
return builder
.setTriggerReceiver(TriggerReceiver.class)
.build();
}
}
| ElieSauveterre/cordova-plugin-local-notifications | src/android/ClickActivity.java | Java | apache-2.0 | 2,346 |
declare var a: number;
var b: typeof a = "...";
var c: typeof a = "...";
type T = number;
var x:T = "...";
// what about recursive unions?
| kidaa/kythe | third_party/flow/tests/reflection/type.js | JavaScript | apache-2.0 | 141 |
/**
* Italian translation for bootstrap-datepicker
* Enrico Rubboli <rubboli@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['it'] = {
days: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato", "Domenica"],
daysShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"],
daysMin: ["Do", "Lu", "Ma", "Me", "Gi", "Ve", "Sa", "Do"],
months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"],
monthsShort: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"],
today: "Oggi",
weekStart: 1,
format: "dd/mm/yyyy"
};
}(jQuery));
| zxinStar/footshop | zxAdmin/assets/js/uncompressed/date-time/locales/bootstrap-datepicker.it.js | JavaScript | agpl-3.0 | 694 |
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Extensions to the standard "os" package.
package osext // import "github.com/kardianos/osext"
import "path/filepath"
// Executable returns an absolute path that can be used to
// re-invoke the current program.
// It may not be valid after the current program exits.
func Executable() (string, error) {
p, err := executable()
return filepath.Clean(p), err
}
// Returns same path as Executable, returns just the folder
// path. Excludes the executable name.
func ExecutableFolder() (string, error) {
p, err := Executable()
if err != nil {
return "", err
}
folder, _ := filepath.Split(p)
return folder, nil
}
| sg00dwin/origin | vendor/github.com/kardianos/osext/osext.go | GO | apache-2.0 | 781 |
<?php
namespace PicoFeed\Scraper;
use DomDocument;
use DOMXPath;
use PicoFeed\Logging\Logger;
use PicoFeed\Parser\XmlParser;
/**
* Candidate Parser.
*
* @author Frederic Guillot
*/
class CandidateParser implements ParserInterface
{
private $dom;
private $xpath;
/**
* List of attributes to try to get the content, order is important, generic terms at the end.
*
* @var array
*/
private $candidatesAttributes = array(
'articleBody',
'articlebody',
'article-body',
'articleContent',
'articlecontent',
'article-content',
'articlePage',
'post-content',
'post_content',
'entry-content',
'entry-body',
'main-content',
'story_content',
'storycontent',
'entryBox',
'entrytext',
'comic',
'post',
'article',
'content',
'main',
);
/**
* List of attributes to strip.
*
* @var array
*/
private $stripAttributes = array(
'comment',
'share',
'links',
'toolbar',
'fb',
'footer',
'credit',
'bottom',
'nav',
'header',
'social',
'tag',
'metadata',
'entry-utility',
'related-posts',
'tweet',
'categories',
'post_title',
'by_line',
'byline',
'sponsors',
);
/**
* Tags to remove.
*
* @var array
*/
private $stripTags = array(
'nav',
'header',
'footer',
'aside',
'form',
);
/**
* Constructor.
*
* @param string $html
*/
public function __construct($html)
{
$this->dom = XmlParser::getHtmlDocument('<?xml version="1.0" encoding="UTF-8">'.$html);
$this->xpath = new DOMXPath($this->dom);
}
/**
* Get the relevant content with the list of potential attributes.
*
* @return string
*/
public function execute()
{
$content = $this->findContentWithCandidates();
if (strlen($content) < 200) {
$content = $this->findContentWithArticle();
}
if (strlen($content) < 50) {
$content = $this->findContentWithBody();
}
return $this->stripGarbage($content);
}
/**
* Find content based on the list of tag candidates.
*
* @return string
*/
public function findContentWithCandidates()
{
foreach ($this->candidatesAttributes as $candidate) {
Logger::setMessage(get_called_class().': Try this candidate: "'.$candidate.'"');
$nodes = $this->xpath->query('//*[(contains(@class, "'.$candidate.'") or @id="'.$candidate.'") and not (contains(@class, "nav") or contains(@class, "page"))]');
if ($nodes !== false && $nodes->length > 0) {
Logger::setMessage(get_called_class().': Find candidate "'.$candidate.'"');
return $this->dom->saveXML($nodes->item(0));
}
}
return '';
}
/**
* Find <article/> tag.
*
* @return string
*/
public function findContentWithArticle()
{
$nodes = $this->xpath->query('//article');
if ($nodes !== false && $nodes->length > 0) {
Logger::setMessage(get_called_class().': Find <article/> tag');
return $this->dom->saveXML($nodes->item(0));
}
return '';
}
/**
* Find <body/> tag.
*
* @return string
*/
public function findContentWithBody()
{
$nodes = $this->xpath->query('//body');
if ($nodes !== false && $nodes->length > 0) {
Logger::setMessage(get_called_class().' Find <body/>');
return $this->dom->saveXML($nodes->item(0));
}
return '';
}
/**
* Strip useless tags.
*
* @param string $content
*
* @return string
*/
public function stripGarbage($content)
{
$dom = XmlParser::getDomDocument($content);
if ($dom !== false) {
$xpath = new DOMXPath($dom);
$this->stripTags($xpath);
$this->stripAttributes($dom, $xpath);
$content = $dom->saveXML($dom->documentElement);
}
return $content;
}
/**
* Remove blacklisted tags.
*
* @param DOMXPath $xpath
*/
public function stripTags(DOMXPath $xpath)
{
foreach ($this->stripTags as $tag) {
$nodes = $xpath->query('//'.$tag);
if ($nodes !== false && $nodes->length > 0) {
Logger::setMessage(get_called_class().': Strip tag: "'.$tag.'"');
foreach ($nodes as $node) {
$node->parentNode->removeChild($node);
}
}
}
}
/**
* Remove blacklisted attributes.
*
* @param DomDocument $dom
* @param DOMXPath $xpath
*/
public function stripAttributes(DomDocument $dom, DOMXPath $xpath)
{
foreach ($this->stripAttributes as $attribute) {
$nodes = $xpath->query('//*[contains(@class, "'.$attribute.'") or contains(@id, "'.$attribute.'")]');
if ($nodes !== false && $nodes->length > 0) {
Logger::setMessage(get_called_class().': Strip attribute: "'.$attribute.'"');
foreach ($nodes as $node) {
if ($this->shouldRemove($dom, $node)) {
$node->parentNode->removeChild($node);
}
}
}
}
}
/**
* Return false if the node should not be removed.
*
* @param DomDocument $dom
* @param DomNode $node
*
* @return bool
*/
public function shouldRemove(DomDocument $dom, $node)
{
$document_length = strlen($dom->textContent);
$node_length = strlen($node->textContent);
if ($document_length === 0) {
return true;
}
$ratio = $node_length * 100 / $document_length;
if ($ratio >= 90) {
Logger::setMessage(get_called_class().': Should not remove this node ('.$node->nodeName.') ratio: '.$ratio.'%');
return false;
}
return true;
}
}
| bkostrowiecki/devnote | www/user/plugins/admin/vendor/fguillot/picofeed/lib/PicoFeed/Scraper/CandidateParser.php | PHP | gpl-3.0 | 6,365 |
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Displays the 'User groups' sub page under 'Users' page.
*
* @package PhpMyAdmin
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/server_users.lib.php';
require_once 'libraries/server_user_groups.lib.php';
PMA_getRelationsParam();
if (! $GLOBALS['cfgRelation']['menuswork']) {
exit;
}
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('server_user_groups.js');
/**
* Only allowed to superuser
*/
if (! $GLOBALS['is_superuser']) {
$response->addHTML(PMA_Message::error(__('No Privileges'))->getDisplay());
exit;
}
$response->addHTML('<div>');
$response->addHTML(PMA_getHtmlForSubMenusOnUsersPage('server_user_groups.php'));
/**
* Delete user group
*/
if (! empty($_REQUEST['deleteUserGroup'])) {
PMA_deleteUserGroup($_REQUEST['userGroup']);
}
/**
* Add a new user group
*/
if (! empty($_REQUEST['addUserGroupSubmit'])) {
PMA_editUserGroup($_REQUEST['userGroup'], true);
}
/**
* Update a user group
*/
if (! empty($_REQUEST['editUserGroupSubmit'])) {
PMA_editUserGroup($_REQUEST['userGroup']);
}
if (isset($_REQUEST['viewUsers'])) {
// Display users belonging to a user group
$response->addHTML(PMA_getHtmlForListingUsersofAGroup($_REQUEST['userGroup']));
}
if (isset($_REQUEST['addUserGroup'])) {
// Display add user group dialog
$response->addHTML(PMA_getHtmlToEditUserGroup());
} elseif (isset($_REQUEST['editUserGroup'])) {
// Display edit user group dialog
$response->addHTML(PMA_getHtmlToEditUserGroup($_REQUEST['userGroup']));
} else {
// Display user groups table
$response->addHTML(PMA_getHtmlForUserGroupsTable());
}
$response->addHTML('</div>');
| Dokaponteam/ITF_Project | xampp/phpMyAdmin/server_user_groups.php | PHP | mit | 1,786 |
# Copyright (c) 2007, Robert Coup <robert.coup@onetrackmind.co.nz>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. Neither the name of Distance 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.
#
"""
Distance and Area objects to allow for sensible and convenient calculation
and conversions.
Authors: Robert Coup, Justin Bronn, Riccardo Di Virgilio
Inspired by GeoPy (http://exogen.case.edu/projects/geopy/)
and Geoff Biggs' PhD work on dimensioned units for robotics.
"""
__all__ = ['A', 'Area', 'D', 'Distance']
from decimal import Decimal
from functools import total_ordering
from django.utils import six
NUMERIC_TYPES = six.integer_types + (float, Decimal)
AREA_PREFIX = "sq_"
def pretty_name(obj):
return obj.__name__ if obj.__class__ == type else obj.__class__.__name__
@total_ordering
class MeasureBase(object):
STANDARD_UNIT = None
ALIAS = {}
UNITS = {}
LALIAS = {}
def __init__(self, default_unit=None, **kwargs):
value, self._default_unit = self.default_units(kwargs)
setattr(self, self.STANDARD_UNIT, value)
if default_unit and isinstance(default_unit, six.string_types):
self._default_unit = default_unit
def _get_standard(self):
return getattr(self, self.STANDARD_UNIT)
def _set_standard(self, value):
setattr(self, self.STANDARD_UNIT, value)
standard = property(_get_standard, _set_standard)
def __getattr__(self, name):
if name in self.UNITS:
return self.standard / self.UNITS[name]
else:
raise AttributeError('Unknown unit type: %s' % name)
def __repr__(self):
return '%s(%s=%s)' % (pretty_name(self), self._default_unit,
getattr(self, self._default_unit))
def __str__(self):
return '%s %s' % (getattr(self, self._default_unit), self._default_unit)
# **** Comparison methods ****
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.standard == other.standard
else:
return NotImplemented
def __lt__(self, other):
if isinstance(other, self.__class__):
return self.standard < other.standard
else:
return NotImplemented
# **** Operators methods ****
def __add__(self, other):
if isinstance(other, self.__class__):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard + other.standard)})
else:
raise TypeError('%(class)s must be added with %(class)s' % {"class": pretty_name(self)})
def __iadd__(self, other):
if isinstance(other, self.__class__):
self.standard += other.standard
return self
else:
raise TypeError('%(class)s must be added with %(class)s' % {"class": pretty_name(self)})
def __sub__(self, other):
if isinstance(other, self.__class__):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard - other.standard)})
else:
raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
def __isub__(self, other):
if isinstance(other, self.__class__):
self.standard -= other.standard
return self
else:
raise TypeError('%(class)s must be subtracted from %(class)s' % {"class": pretty_name(self)})
def __mul__(self, other):
if isinstance(other, NUMERIC_TYPES):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard * other)})
else:
raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
def __imul__(self, other):
if isinstance(other, NUMERIC_TYPES):
self.standard *= float(other)
return self
else:
raise TypeError('%(class)s must be multiplied with number' % {"class": pretty_name(self)})
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if isinstance(other, self.__class__):
return self.standard / other.standard
if isinstance(other, NUMERIC_TYPES):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard / other)})
else:
raise TypeError('%(class)s must be divided with number or %(class)s' % {"class": pretty_name(self)})
def __div__(self, other): # Python 2 compatibility
return type(self).__truediv__(self, other)
def __itruediv__(self, other):
if isinstance(other, NUMERIC_TYPES):
self.standard /= float(other)
return self
else:
raise TypeError('%(class)s must be divided with number' % {"class": pretty_name(self)})
def __idiv__(self, other): # Python 2 compatibility
return type(self).__itruediv__(self, other)
def __bool__(self):
return bool(self.standard)
def __nonzero__(self): # Python 2 compatibility
return type(self).__bool__(self)
def default_units(self, kwargs):
"""
Return the unit value and the default units specified
from the given keyword arguments dictionary.
"""
val = 0.0
default_unit = self.STANDARD_UNIT
for unit, value in six.iteritems(kwargs):
if not isinstance(value, float):
value = float(value)
if unit in self.UNITS:
val += self.UNITS[unit] * value
default_unit = unit
elif unit in self.ALIAS:
u = self.ALIAS[unit]
val += self.UNITS[u] * value
default_unit = u
else:
lower = unit.lower()
if lower in self.UNITS:
val += self.UNITS[lower] * value
default_unit = lower
elif lower in self.LALIAS:
u = self.LALIAS[lower]
val += self.UNITS[u] * value
default_unit = u
else:
raise AttributeError('Unknown unit type: %s' % unit)
return val, default_unit
@classmethod
def unit_attname(cls, unit_str):
"""
Retrieves the unit attribute name for the given unit string.
For example, if the given unit string is 'metre', 'm' would be returned.
An exception is raised if an attribute cannot be found.
"""
lower = unit_str.lower()
if unit_str in cls.UNITS:
return unit_str
elif lower in cls.UNITS:
return lower
elif lower in cls.LALIAS:
return cls.LALIAS[lower]
else:
raise Exception('Could not find a unit keyword associated with "%s"' % unit_str)
class Distance(MeasureBase):
STANDARD_UNIT = "m"
UNITS = {
'chain': 20.1168,
'chain_benoit': 20.116782,
'chain_sears': 20.1167645,
'british_chain_benoit': 20.1167824944,
'british_chain_sears': 20.1167651216,
'british_chain_sears_truncated': 20.116756,
'cm': 0.01,
'british_ft': 0.304799471539,
'british_yd': 0.914398414616,
'clarke_ft': 0.3047972654,
'clarke_link': 0.201166195164,
'fathom': 1.8288,
'ft': 0.3048,
'german_m': 1.0000135965,
'gold_coast_ft': 0.304799710181508,
'indian_yd': 0.914398530744,
'inch': 0.0254,
'km': 1000.0,
'link': 0.201168,
'link_benoit': 0.20116782,
'link_sears': 0.20116765,
'm': 1.0,
'mi': 1609.344,
'mm': 0.001,
'nm': 1852.0,
'nm_uk': 1853.184,
'rod': 5.0292,
'sears_yd': 0.91439841,
'survey_ft': 0.304800609601,
'um': 0.000001,
'yd': 0.9144,
}
# Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
ALIAS = {
'centimeter': 'cm',
'foot': 'ft',
'inches': 'inch',
'kilometer': 'km',
'kilometre': 'km',
'meter': 'm',
'metre': 'm',
'micrometer': 'um',
'micrometre': 'um',
'millimeter': 'mm',
'millimetre': 'mm',
'mile': 'mi',
'yard': 'yd',
'British chain (Benoit 1895 B)': 'british_chain_benoit',
'British chain (Sears 1922)': 'british_chain_sears',
'British chain (Sears 1922 truncated)': 'british_chain_sears_truncated',
'British foot (Sears 1922)': 'british_ft',
'British foot': 'british_ft',
'British yard (Sears 1922)': 'british_yd',
'British yard': 'british_yd',
"Clarke's Foot": 'clarke_ft',
"Clarke's link": 'clarke_link',
'Chain (Benoit)': 'chain_benoit',
'Chain (Sears)': 'chain_sears',
'Foot (International)': 'ft',
'German legal metre': 'german_m',
'Gold Coast foot': 'gold_coast_ft',
'Indian yard': 'indian_yd',
'Link (Benoit)': 'link_benoit',
'Link (Sears)': 'link_sears',
'Nautical Mile': 'nm',
'Nautical Mile (UK)': 'nm_uk',
'US survey foot': 'survey_ft',
'U.S. Foot': 'survey_ft',
'Yard (Indian)': 'indian_yd',
'Yard (Sears)': 'sears_yd'
}
LALIAS = {k.lower(): v for k, v in ALIAS.items()}
def __mul__(self, other):
if isinstance(other, self.__class__):
return Area(default_unit=AREA_PREFIX + self._default_unit,
**{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)})
elif isinstance(other, NUMERIC_TYPES):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard * other)})
else:
raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
"distance": pretty_name(self.__class__),
})
class Area(MeasureBase):
STANDARD_UNIT = AREA_PREFIX + Distance.STANDARD_UNIT
# Getting the square units values and the alias dictionary.
UNITS = {'%s%s' % (AREA_PREFIX, k): v ** 2 for k, v in Distance.UNITS.items()}
ALIAS = {k: '%s%s' % (AREA_PREFIX, v) for k, v in Distance.ALIAS.items()}
LALIAS = {k.lower(): v for k, v in ALIAS.items()}
def __truediv__(self, other):
if isinstance(other, NUMERIC_TYPES):
return self.__class__(default_unit=self._default_unit,
**{self.STANDARD_UNIT: (self.standard / other)})
else:
raise TypeError('%(class)s must be divided by a number' % {"class": pretty_name(self)})
def __div__(self, other): # Python 2 compatibility
return type(self).__truediv__(self, other)
# Shortcuts
D = Distance
A = Area
| Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/Django-1.9-py2.7.egg/django/contrib/gis/measure.py | Python | artistic-2.0 | 12,272 |
<?php
/**
* @file
* Template file for Radix modal.
*/
?>
<!-- Button trigger modal -->
<?php print render($trigger_button); ?>
<!-- Modal -->
<div class="modal fade" id="<?php print $modal_id; ?>" tabindex="-1" role="dialog" aria-labelledby="<?php print $modal_id; ?>" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<?php if ($header): ?>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">
<?php print $header; ?>
</h4>
</div>
<?php endif; ?>
<?php if ($content): ?>
<div class="modal-body">
<?php print render($content); ?>
</div>
<?php endif; ?>
<?php if (count($buttons)): ?>
<div class="modal-footer">
<?php foreach ($buttons as $button): ?>
<?php print $button; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
| angrycactus/dkan | webroot/profiles/dkan/themes/contrib/radix/templates/radix/radix-modal.tpl.php | PHP | gpl-2.0 | 1,060 |
'use strict';
var $ = require('jquery');
require('./github-node-cfg.js');
var AddonHelper = require('js/addonHelper');
$(window.contextVars.githubSettingsSelector).on('submit', AddonHelper.onSubmitSettings);
| ticklemepierce/osf.io | website/addons/github/static/node-cfg.js | JavaScript | apache-2.0 | 210 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/event_client_impl.h"
#include "ash/session/session_state_delegate.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ui/aura/window.h"
#include "ui/keyboard/keyboard_util.h"
namespace ash {
EventClientImpl::EventClientImpl() {
}
EventClientImpl::~EventClientImpl() {
}
bool EventClientImpl::CanProcessEventsWithinSubtree(
const aura::Window* window) const {
const aura::Window* root_window = window ? window->GetRootWindow() : NULL;
if (!root_window ||
!Shell::GetInstance()->session_state_delegate()->IsUserSessionBlocked()) {
return true;
}
const aura::Window* lock_screen_containers = Shell::GetContainer(
root_window,
kShellWindowId_LockScreenContainersContainer);
const aura::Window* lock_background_containers = Shell::GetContainer(
root_window,
kShellWindowId_LockScreenBackgroundContainer);
const aura::Window* lock_screen_related_containers = Shell::GetContainer(
root_window,
kShellWindowId_LockScreenRelatedContainersContainer);
bool can_process_events = (window->Contains(lock_screen_containers) &&
window->Contains(lock_background_containers) &&
window->Contains(lock_screen_related_containers)) ||
lock_screen_containers->Contains(window) ||
lock_background_containers->Contains(window) ||
lock_screen_related_containers->Contains(window);
if (keyboard::IsKeyboardEnabled()) {
const aura::Window* virtual_keyboard_container = Shell::GetContainer(
root_window,
kShellWindowId_VirtualKeyboardContainer);
can_process_events |= (window->Contains(virtual_keyboard_container) ||
virtual_keyboard_container->Contains(window));
}
return can_process_events;
}
ui::EventTarget* EventClientImpl::GetToplevelEventTarget() {
return Shell::GetInstance();
}
} // namespace ash
| s20121035/rk3288_android5.1_repo | external/chromium_org/ash/wm/event_client_impl.cc | C++ | gpl-3.0 | 2,044 |
public enum A {
;
A(String s){}
} | asedunov/intellij-community | java/java-tests/testData/refactoring/moveMembers/enumConstant/before/A.java | Java | apache-2.0 | 37 |
class A {
public void f() {
Inner i = new Inner();
i.doStuff();
}
private class <caret>Inner {
public void doStuff() {
}
}
} | asedunov/intellij-community | java/java-tests/testData/refactoring/inlineToAnonymousClass/NoInlineMethodUsage.java | Java | apache-2.0 | 173 |
class MyException extends RuntimeException{}
class MyClass {
public void foo() throws MyException {
throw new MyException();<caret>
}
} | asedunov/intellij-community | java/java-tests/testData/codeInsight/completion/smartType/ExceptionTwice-out.java | Java | apache-2.0 | 139 |
/*!
* https://github.com/es-shims/es5-shim
* @license es5-shim Copyright 2009-2015 by contributors, MIT License
* see https://github.com/es-shims/es5-shim/blob/master/LICENSE
*/
// vim: ts=4 sts=4 sw=4 expandtab
// Add semicolon to prevent IIFE from being passed as argument to concatenated code.
;
// UMD (Universal Module Definition)
// see https://github.com/umdjs/umd/blob/master/returnExports.js
(function (root, factory) {
'use strict';
/* global define, exports, module */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(factory);
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.returnExports = factory();
}
}(this, function () {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally. This also holds a reference to known-good
// functions.
var $Array = Array;
var ArrayPrototype = $Array.prototype;
var $Object = Object;
var ObjectPrototype = $Object.prototype;
var FunctionPrototype = Function.prototype;
var $String = String;
var StringPrototype = $String.prototype;
var $Number = Number;
var NumberPrototype = $Number.prototype;
var array_slice = ArrayPrototype.slice;
var array_splice = ArrayPrototype.splice;
var array_push = ArrayPrototype.push;
var array_unshift = ArrayPrototype.unshift;
var array_concat = ArrayPrototype.concat;
var call = FunctionPrototype.call;
var max = Math.max;
var min = Math.min;
// Having a toString local variable name breaks in Opera so use to_string.
var to_string = ObjectPrototype.toString;
var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
var isCallable; /* inlined from https://npmjs.com/is-callable */ var fnToStr = Function.prototype.toString, tryFunctionObject = function tryFunctionObject(value) { try { fnToStr.call(value); return true; } catch (e) { return false; } }, fnClass = '[object Function]', genClass = '[object GeneratorFunction]'; isCallable = function isCallable(value) { if (typeof value !== 'function') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } var strClass = to_string.call(value); return strClass === fnClass || strClass === genClass; };
var isRegex; /* inlined from https://npmjs.com/is-regex */ var regexExec = RegExp.prototype.exec, tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }, regexClass = '[object RegExp]'; isRegex = function isRegex(value) { if (typeof value !== 'object') { return false; } return hasToStringTag ? tryRegexExec(value) : to_string.call(value) === regexClass; };
var isString; /* inlined from https://npmjs.com/is-string */ var strValue = String.prototype.valueOf, tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }, stringClass = '[object String]'; isString = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : to_string.call(value) === stringClass; };
/* inlined from http://npmjs.com/define-properties */
var defineProperties = (function (has) {
var supportsDescriptors = $Object.defineProperty && (function () {
try {
var obj = {};
$Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
for (var _ in obj) { return false; }
return obj.x === obj;
} catch (e) { /* this is ES3 */
return false;
}
}());
// Define configurable, writable and non-enumerable props
// if they don't exist.
var defineProperty;
if (supportsDescriptors) {
defineProperty = function (object, name, method, forceAssign) {
if (!forceAssign && (name in object)) { return; }
$Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
};
} else {
defineProperty = function (object, name, method, forceAssign) {
if (!forceAssign && (name in object)) { return; }
object[name] = method;
};
}
return function defineProperties(object, map, forceAssign) {
for (var name in map) {
if (has.call(map, name)) {
defineProperty(object, name, map[name], forceAssign);
}
}
};
}(ObjectPrototype.hasOwnProperty));
//
// Util
// ======
//
/* replaceable with https://npmjs.com/package/es-abstract /helpers/isPrimitive */
var isPrimitive = function isPrimitive(input) {
var type = typeof input;
return input === null || (type !== 'object' && type !== 'function');
};
var isActualNaN = $Number.isNaN || function (x) { return x !== x; };
var ES = {
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToInteger */
ToInteger: function ToInteger(num) {
var n = +num;
if (isActualNaN(n)) {
n = 0;
} else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
},
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToPrimitive */
ToPrimitive: function ToPrimitive(input) {
var val, valueOf, toStr;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (isCallable(valueOf)) {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toStr = input.toString;
if (isCallable(toStr)) {
val = toStr.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
},
// ES5 9.9
// http://es5.github.com/#x9.9
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToObject */
ToObject: function (o) {
/* jshint eqnull: true */
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert " + o + ' to object');
}
return $Object(o);
},
/* replaceable with https://npmjs.com/package/es-abstract ES5.ToUint32 */
ToUint32: function ToUint32(x) {
return x >>> 0;
}
};
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
var Empty = function Empty() {};
defineProperties(FunctionPrototype, {
bind: function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (!isCallable(target)) {
throw new TypeError('Function.prototype.bind called on incompatible ' + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = array_slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound;
var binder = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
array_concat.call(args, array_slice.call(arguments))
);
if ($Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
array_concat.call(args, array_slice.call(arguments))
);
}
};
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
var boundLength = max(0, target.length - args.length);
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
var boundArgs = [];
for (var i = 0; i < boundLength; i++) {
array_push.call(boundArgs, '$' + i);
}
// XXX Build a dynamic function with desired amount of arguments is the only
// way to set the length property of a function.
// In environments where Content Security Policies enabled (Chrome extensions,
// for ex.) all use of eval or Function costructor throws an exception.
// However in all of these environments Function.prototype.bind exists
// and so this code will never be executed.
bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this, arguments); }')(binder);
if (target.prototype) {
Empty.prototype = target.prototype;
bound.prototype = new Empty();
// Clean up dangling references.
Empty.prototype = null;
}
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
}
});
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var owns = call.bind(ObjectPrototype.hasOwnProperty);
var toStr = call.bind(ObjectPrototype.toString);
var strSlice = call.bind(StringPrototype.slice);
var strSplit = call.bind(StringPrototype.split);
var strIndexOf = call.bind(StringPrototype.indexOf);
//
// Array
// =====
//
var isArray = $Array.isArray || function isArray(obj) {
return toStr(obj) === '[object Array]';
};
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.13
// Return len+argCount.
// [bugfix, ielt8]
// IE < 8 bug: [].unshift(0) === undefined but should be "1"
var hasUnshiftReturnValueBug = [].unshift(0) !== 1;
defineProperties(ArrayPrototype, {
unshift: function () {
array_unshift.apply(this, arguments);
return this.length;
}
}, hasUnshiftReturnValueBug);
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
defineProperties($Array, { isArray: isArray });
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = $Object('a');
var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
var properlyBoxesContext = function properlyBoxed(method) {
// Check node 0.6.21 bug where third parameter is not boxed
var properlyBoxesNonStrict = true;
var properlyBoxesStrict = true;
if (method) {
method.call('foo', function (_, __, context) {
if (typeof context !== 'object') { properlyBoxesNonStrict = false; }
});
method.call([1], function () {
'use strict';
properlyBoxesStrict = typeof this === 'string';
}, 'x');
}
return !!method && properlyBoxesNonStrict && properlyBoxesStrict;
};
defineProperties(ArrayPrototype, {
forEach: function forEach(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var i = -1;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.forEach callback must be a function');
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
if (typeof T === 'undefined') {
callbackfn(self[i], i, object);
} else {
callbackfn.call(T, self[i], i, object);
}
}
}
}
}, !properlyBoxesContext(ArrayPrototype.forEach));
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
defineProperties(ArrayPrototype, {
map: function map(callbackfn/*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var result = $Array(length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.map callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
if (typeof T === 'undefined') {
result[i] = callbackfn(self[i], i, object);
} else {
result[i] = callbackfn.call(T, self[i], i, object);
}
}
}
return result;
}
}, !properlyBoxesContext(ArrayPrototype.map));
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
defineProperties(ArrayPrototype, {
filter: function filter(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var result = [];
var value;
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.filter callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (typeof T === 'undefined' ? callbackfn(value, i, object) : callbackfn.call(T, value, i, object)) {
array_push.call(result, value);
}
}
}
return result;
}
}, !properlyBoxesContext(ArrayPrototype.filter));
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
defineProperties(ArrayPrototype, {
every: function every(callbackfn /*, thisArg*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.every callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self && !(typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
return false;
}
}
return true;
}
}, !properlyBoxesContext(ArrayPrototype.every));
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
defineProperties(ArrayPrototype, {
some: function some(callbackfn/*, thisArg */) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
var T;
if (arguments.length > 1) {
T = arguments[1];
}
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.some callback must be a function');
}
for (var i = 0; i < length; i++) {
if (i in self && (typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
return true;
}
}
return false;
}
}, !properlyBoxesContext(ArrayPrototype.some));
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
var reduceCoercesToObject = false;
if (ArrayPrototype.reduce) {
reduceCoercesToObject = typeof ArrayPrototype.reduce.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
defineProperties(ArrayPrototype, {
reduce: function reduce(callbackfn /*, initialValue*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.reduce callback must be a function');
}
// no value to return if no initial value and an empty array
if (length === 0 && arguments.length === 1) {
throw new TypeError('reduce of empty array with no initial value');
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError('reduce of empty array with no initial value');
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = callbackfn(result, self[i], i, object);
}
}
return result;
}
}, !reduceCoercesToObject);
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
var reduceRightCoercesToObject = false;
if (ArrayPrototype.reduceRight) {
reduceRightCoercesToObject = typeof ArrayPrototype.reduceRight.call('es5', function (_, __, ___, list) { return list; }) === 'object';
}
defineProperties(ArrayPrototype, {
reduceRight: function reduceRight(callbackfn/*, initial*/) {
var object = ES.ToObject(this);
var self = splitString && isString(this) ? strSplit(this, '') : object;
var length = ES.ToUint32(self.length);
// If no callback function or if callback is not a callable function
if (!isCallable(callbackfn)) {
throw new TypeError('Array.prototype.reduceRight callback must be a function');
}
// no value to return if no initial value, empty array
if (length === 0 && arguments.length === 1) {
throw new TypeError('reduceRight of empty array with no initial value');
}
var result;
var i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError('reduceRight of empty array with no initial value');
}
} while (true);
}
if (i < 0) {
return result;
}
do {
if (i in self) {
result = callbackfn(result, self[i], i, object);
}
} while (i--);
return result;
}
}, !reduceRightCoercesToObject);
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
var hasFirefox2IndexOfBug = ArrayPrototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
defineProperties(ArrayPrototype, {
indexOf: function indexOf(searchElement /*, fromIndex */) {
var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
var length = ES.ToUint32(self.length);
if (length === 0) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = ES.ToInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === searchElement) {
return i;
}
}
return -1;
}
}, hasFirefox2IndexOfBug);
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
var hasFirefox2LastIndexOfBug = ArrayPrototype.lastIndexOf && [0, 1].lastIndexOf(0, -3) !== -1;
defineProperties(ArrayPrototype, {
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */) {
var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
var length = ES.ToUint32(self.length);
if (length === 0) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = min(i, ES.ToInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && searchElement === self[i]) {
return i;
}
}
return -1;
}
}, hasFirefox2LastIndexOfBug);
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.12
var spliceNoopReturnsEmptyArray = (function () {
var a = [1, 2];
var result = a.splice();
return a.length === 2 && isArray(result) && result.length === 0;
}());
defineProperties(ArrayPrototype, {
// Safari 5.0 bug where .splice() returns undefined
splice: function splice(start, deleteCount) {
if (arguments.length === 0) {
return [];
} else {
return array_splice.apply(this, arguments);
}
}
}, !spliceNoopReturnsEmptyArray);
var spliceWorksWithEmptyObject = (function () {
var obj = {};
ArrayPrototype.splice.call(obj, 0, 0, 1);
return obj.length === 1;
}());
defineProperties(ArrayPrototype, {
splice: function splice(start, deleteCount) {
if (arguments.length === 0) { return []; }
var args = arguments;
this.length = max(ES.ToInteger(this.length), 0);
if (arguments.length > 0 && typeof deleteCount !== 'number') {
args = array_slice.call(arguments);
if (args.length < 2) {
array_push.call(args, this.length - start);
} else {
args[1] = ES.ToInteger(deleteCount);
}
}
return array_splice.apply(this, args);
}
}, !spliceWorksWithEmptyObject);
var spliceWorksWithLargeSparseArrays = (function () {
// Per https://github.com/es-shims/es5-shim/issues/295
// Safari 7/8 breaks with sparse arrays of size 1e5 or greater
var arr = new $Array(1e5);
// note: the index MUST be 8 or larger or the test will false pass
arr[8] = 'x';
arr.splice(1, 1);
// note: this test must be defined *after* the indexOf shim
// per https://github.com/es-shims/es5-shim/issues/313
return arr.indexOf('x') === 7;
}());
var spliceWorksWithSmallSparseArrays = (function () {
// Per https://github.com/es-shims/es5-shim/issues/295
// Opera 12.15 breaks on this, no idea why.
var n = 256;
var arr = [];
arr[n] = 'a';
arr.splice(n + 1, 0, 'b');
return arr[n] === 'a';
}());
defineProperties(ArrayPrototype, {
splice: function splice(start, deleteCount) {
var O = ES.ToObject(this);
var A = [];
var len = ES.ToUint32(O.length);
var relativeStart = ES.ToInteger(start);
var actualStart = relativeStart < 0 ? max((len + relativeStart), 0) : min(relativeStart, len);
var actualDeleteCount = min(max(ES.ToInteger(deleteCount), 0), len - actualStart);
var k = 0;
var from;
while (k < actualDeleteCount) {
from = $String(actualStart + k);
if (owns(O, from)) {
A[k] = O[from];
}
k += 1;
}
var items = array_slice.call(arguments, 2);
var itemCount = items.length;
var to;
if (itemCount < actualDeleteCount) {
k = actualStart;
while (k < (len - actualDeleteCount)) {
from = $String(k + actualDeleteCount);
to = $String(k + itemCount);
if (owns(O, from)) {
O[to] = O[from];
} else {
delete O[to];
}
k += 1;
}
k = len;
while (k > (len - actualDeleteCount + itemCount)) {
delete O[k - 1];
k -= 1;
}
} else if (itemCount > actualDeleteCount) {
k = len - actualDeleteCount;
while (k > actualStart) {
from = $String(k + actualDeleteCount - 1);
to = $String(k + itemCount - 1);
if (owns(O, from)) {
O[to] = O[from];
} else {
delete O[to];
}
k -= 1;
}
}
k = actualStart;
for (var i = 0; i < items.length; ++i) {
O[k] = items[i];
k += 1;
}
O.length = len - actualDeleteCount + itemCount;
return A;
}
}, !spliceWorksWithLargeSparseArrays || !spliceWorksWithSmallSparseArrays);
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var hasStringEnumBug = !owns('x', '0');
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var blacklistedKeys = {
$window: true,
$console: true,
$parent: true,
$self: true,
$frame: true,
$frames: true,
$frameElement: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true
};
var hasAutomationEqualityBug = (function () {
/* globals window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
try {
if (!blacklistedKeys['$' + k] && owns(window, k) && window[k] !== null && typeof window[k] === 'object') {
equalsConstructorPrototype(window[k]);
}
} catch (e) {
return true;
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (object) {
if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(object); }
try {
return equalsConstructorPrototype(object);
} catch (e) {
return false;
}
};
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var dontEnumsLength = dontEnums.length;
// taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
// can be replaced with require('is-arguments') if we ever use a build process instead
var isStandardArguments = function isArguments(value) {
return toStr(value) === '[object Arguments]';
};
var isLegacyArguments = function isArguments(value) {
return value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
!isArray(value) &&
isCallable(value.callee);
};
var isArguments = isStandardArguments(arguments) ? isStandardArguments : isLegacyArguments;
defineProperties($Object, {
keys: function keys(object) {
var isFn = isCallable(object);
var isArgs = isArguments(object);
var isObject = object !== null && typeof object === 'object';
var isStr = isObject && isString(object);
if (!isObject && !isFn && !isArgs) {
throw new TypeError('Object.keys called on a non-object');
}
var theKeys = [];
var skipProto = hasProtoEnumBug && isFn;
if ((isStr && hasStringEnumBug) || isArgs) {
for (var i = 0; i < object.length; ++i) {
array_push.call(theKeys, $String(i));
}
}
if (!isArgs) {
for (var name in object) {
if (!(skipProto && name === 'prototype') && owns(object, name)) {
array_push.call(theKeys, $String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var j = 0; j < dontEnumsLength; j++) {
var dontEnum = dontEnums[j];
if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) {
array_push.call(theKeys, dontEnum);
}
}
}
return theKeys;
}
});
var keysWorksWithArguments = $Object.keys && (function () {
// Safari 5.0 bug
return $Object.keys(arguments).length === 2;
}(1, 2));
var keysHasArgumentsLengthBug = $Object.keys && (function () {
var argKeys = $Object.keys(arguments);
return arguments.length !== 1 || argKeys.length !== 1 || argKeys[0] !== 1;
}(1));
var originalKeys = $Object.keys;
defineProperties($Object, {
keys: function keys(object) {
if (isArguments(object)) {
return originalKeys(array_slice.call(object));
} else {
return originalKeys(object);
}
}
}, !keysWorksWithArguments || keysHasArgumentsLengthBug);
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
var negativeDate = -62198755200000;
var negativeYearString = '-000001';
var hasNegativeDateBug = Date.prototype.toISOString && new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1;
var hasSafari51DateBug = Date.prototype.toISOString && new Date(-1).toISOString() !== '1969-12-31T23:59:59.999Z';
defineProperties(Date.prototype, {
toISOString: function toISOString() {
var result, length, value, year, month;
if (!isFinite(this)) {
throw new RangeError('Date.prototype.toISOString called on non-finite value.');
}
year = this.getUTCFullYear();
month = this.getUTCMonth();
// see https://github.com/es-shims/es5-shim/issues/111
year += Math.floor(month / 12);
month = (month % 12 + 12) % 12;
// the date time string format is specified in 15.9.1.15.
result = [month + 1, this.getUTCDate(), this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = (
(year < 0 ? '-' : (year > 9999 ? '+' : '')) +
strSlice('00000' + Math.abs(year), (0 <= year && year <= 9999) ? -4 : -6)
);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two
// digits.
if (value < 10) {
result[length] = '0' + value;
}
}
// pad milliseconds to have three digits.
return (
year + '-' + array_slice.call(result, 0, 2).join('-') +
'T' + array_slice.call(result, 2).join(':') + '.' +
strSlice('000' + this.getUTCMilliseconds(), -3) + 'Z'
);
}
}, hasNegativeDateBug || hasSafari51DateBug);
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
var dateToJSONIsSupported = (function () {
try {
return Date.prototype.toJSON &&
new Date(NaN).toJSON() === null &&
new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
Date.prototype.toJSON.call({ // generic
toISOString: function () { return true; }
});
} catch (e) {
return false;
}
}());
if (!dateToJSONIsSupported) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ES.ToPrimitive(O, hint Number).
var O = $Object(this);
var tv = ES.ToPrimitive(O);
// 3. If tv is a Number and is not finite, return null.
if (typeof tv === 'number' && !isFinite(tv)) {
return null;
}
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
var toISO = O.toISOString;
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (!isCallable(toISO)) {
throw new TypeError('toISOString property is not callable');
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return toISO.call(O);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15;
var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')) || !isNaN(Date.parse('2012-12-31T23:59:60.000Z'));
var doesNotParseY2KNewYear = isNaN(Date.parse('2000-01-01T00:00:00.000Z'));
if (doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
/* global Date: true */
/* eslint-disable no-undef */
var maxSafeUnsigned32Bit = Math.pow(2, 31) - 1;
var secondsWithinMaxSafeUnsigned32Bit = Math.floor(maxSafeUnsigned32Bit / 1e3);
var hasSafariSignedIntBug = isActualNaN(new Date(1970, 0, 1, 0, 0, 0, maxSafeUnsigned32Bit + 1).getTime());
Date = (function (NativeDate) {
/* eslint-enable no-undef */
// Date.length === 7
var DateShim = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
var date;
if (this instanceof NativeDate) {
var seconds = s;
var millis = ms;
if (hasSafariSignedIntBug && length >= 7 && ms > maxSafeUnsigned32Bit) {
// work around a Safari 8/9 bug where it treats the seconds as signed
var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
var sToShift = Math.floor(msToShift / 1e3);
seconds += sToShift;
millis -= sToShift * 1e3;
}
date = length === 1 && $String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(DateShim.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, seconds, millis) :
length >= 6 ? new NativeDate(Y, M, D, h, m, seconds) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
} else {
date = NativeDate.apply(this, arguments);
}
if (!isPrimitive(date)) {
// Prevent mixups with unfixed Date object
defineProperties(date, { constructor: DateShim }, true);
}
return date;
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp('^' +
'(\\d{4}|[+-]\\d{6})' + // four-digit year capture or sign +
// 6-digit extended year
'(?:-(\\d{2})' + // optional month capture
'(?:-(\\d{2})' + // optional day capture
'(?:' + // capture hours:minutes:seconds.milliseconds
'T(\\d{2})' + // hours capture
':(\\d{2})' + // minutes capture
'(?:' + // optional :seconds.milliseconds
':(\\d{2})' + // seconds capture
'(?:(\\.\\d{1,}))?' + // milliseconds capture
')?' +
'(' + // capture UTC offset component
'Z|' + // UTC capture
'(?:' + // offset specifier +/-hours:minutes
'([-+])' + // sign capture
'(\\d{2})' + // hours offset capture
':(\\d{2})' + // minutes offset capture
')' +
')?)?)?)?' +
'$');
var months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
var dayFromMonth = function dayFromMonth(year, month) {
var t = month > 1 ? 1 : 0;
return (
months[month] +
Math.floor((year - 1969 + t) / 4) -
Math.floor((year - 1901 + t) / 100) +
Math.floor((year - 1601 + t) / 400) +
365 * (year - 1970)
);
};
var toUTC = function toUTC(t) {
var s = 0;
var ms = t;
if (hasSafariSignedIntBug && ms > maxSafeUnsigned32Bit) {
// work around a Safari 8/9 bug where it treats the seconds as signed
var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
var sToShift = Math.floor(msToShift / 1e3);
s += sToShift;
ms -= sToShift * 1e3;
}
return $Number(new NativeDate(1970, 0, 1, 0, 0, s, ms));
};
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
if (owns(NativeDate, key)) {
DateShim[key] = NativeDate[key];
}
}
// Copy "native" methods explicitly; they may be non-enumerable
defineProperties(DateShim, {
now: NativeDate.now,
UTC: NativeDate.UTC
}, true);
DateShim.prototype = NativeDate.prototype;
defineProperties(DateShim.prototype, {
constructor: DateShim
}, true);
// Upgrade Date.parse to handle simplified ISO 8601 strings
var parseShim = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = $Number(match[1]),
month = $Number(match[2] || 1) - 1,
day = $Number(match[3] || 1) - 1,
hour = $Number(match[4] || 0),
minute = $Number(match[5] || 0),
second = $Number(match[6] || 0),
millisecond = Math.floor($Number(match[7] || 0) * 1000),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
isLocalTime = Boolean(match[4] && !match[8]),
signOffset = match[9] === '-' ? 1 : -1,
hourOffset = $Number(match[10] || 0),
minuteOffset = $Number(match[11] || 0),
result;
var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
if (
hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond;
if (isLocalTime) {
result = toUTC(result);
}
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
};
defineProperties(DateShim, { parse: parseShim });
return DateShim;
}(Date));
/* global Date: false */
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
//
// Number
// ======
//
// ES5.1 15.7.4.5
// http://es5.github.com/#x15.7.4.5
var hasToFixedBugs = NumberPrototype.toFixed && (
(0.00008).toFixed(3) !== '0.000' ||
(0.9).toFixed(0) !== '1' ||
(1.255).toFixed(2) !== '1.25' ||
(1000000000000000128).toFixed(0) !== '1000000000000000128'
);
var toFixedHelpers = {
base: 1e7,
size: 6,
data: [0, 0, 0, 0, 0, 0],
multiply: function multiply(n, c) {
var i = -1;
var c2 = c;
while (++i < toFixedHelpers.size) {
c2 += n * toFixedHelpers.data[i];
toFixedHelpers.data[i] = c2 % toFixedHelpers.base;
c2 = Math.floor(c2 / toFixedHelpers.base);
}
},
divide: function divide(n) {
var i = toFixedHelpers.size, c = 0;
while (--i >= 0) {
c += toFixedHelpers.data[i];
toFixedHelpers.data[i] = Math.floor(c / n);
c = (c % n) * toFixedHelpers.base;
}
},
numToString: function numToString() {
var i = toFixedHelpers.size;
var s = '';
while (--i >= 0) {
if (s !== '' || i === 0 || toFixedHelpers.data[i] !== 0) {
var t = $String(toFixedHelpers.data[i]);
if (s === '') {
s = t;
} else {
s += strSlice('0000000', 0, 7 - t.length) + t;
}
}
}
return s;
},
pow: function pow(x, n, acc) {
return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc)));
},
log: function log(x) {
var n = 0;
var x2 = x;
while (x2 >= 4096) {
n += 12;
x2 /= 4096;
}
while (x2 >= 2) {
n += 1;
x2 /= 2;
}
return n;
}
};
defineProperties(NumberPrototype, {
toFixed: function toFixed(fractionDigits) {
var f, x, s, m, e, z, j, k;
// Test for NaN and round fractionDigits down
f = $Number(fractionDigits);
f = isActualNaN(f) ? 0 : Math.floor(f);
if (f < 0 || f > 20) {
throw new RangeError('Number.toFixed called with invalid number of decimals');
}
x = $Number(this);
if (isActualNaN(x)) {
return 'NaN';
}
// If it is too big or small, return the string value of the number
if (x <= -1e21 || x >= 1e21) {
return $String(x);
}
s = '';
if (x < 0) {
s = '-';
x = -x;
}
m = '0';
if (x > 1e-21) {
// 1e-21 < x < 1e21
// -70 < log2(x) < 70
e = toFixedHelpers.log(x * toFixedHelpers.pow(2, 69, 1)) - 69;
z = (e < 0 ? x * toFixedHelpers.pow(2, -e, 1) : x / toFixedHelpers.pow(2, e, 1));
z *= 0x10000000000000; // Math.pow(2, 52);
e = 52 - e;
// -18 < e < 122
// x = z / 2 ^ e
if (e > 0) {
toFixedHelpers.multiply(0, z);
j = f;
while (j >= 7) {
toFixedHelpers.multiply(1e7, 0);
j -= 7;
}
toFixedHelpers.multiply(toFixedHelpers.pow(10, j, 1), 0);
j = e - 1;
while (j >= 23) {
toFixedHelpers.divide(1 << 23);
j -= 23;
}
toFixedHelpers.divide(1 << j);
toFixedHelpers.multiply(1, 1);
toFixedHelpers.divide(2);
m = toFixedHelpers.numToString();
} else {
toFixedHelpers.multiply(0, z);
toFixedHelpers.multiply(1 << (-e), 0);
m = toFixedHelpers.numToString() + strSlice('0.00000000000000000000', 2, 2 + f);
}
}
if (f > 0) {
k = m.length;
if (k <= f) {
m = s + strSlice('0.0000000000000000000', 0, f - k + 2) + m;
} else {
m = s + strSlice(m, 0, k - f) + '.' + strSlice(m, k - f);
}
} else {
m = s + m;
}
return m;
}
}, hasToFixedBugs);
//
// String
// ======
//
// ES5 15.5.4.14
// http://es5.github.com/#x15.5.4.14
// [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
// Many browsers do not split properly with regular expressions or they
// do not perform the split correctly under obscure conditions.
// See http://blog.stevenlevithan.com/archives/cross-browser-split
// I've tested in many browsers and this seems to cover the deviant ones:
// 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
// '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
// 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
// [undefined, "t", undefined, "e", ...]
// ''.split(/.?/) should be [], not [""]
// '.'.split(/()()/) should be ["."], not ["", "", "."]
if (
'ab'.split(/(?:ab)*/).length !== 2 ||
'.'.split(/(.?)(.?)/).length !== 4 ||
'tesst'.split(/(s)*/)[1] === 't' ||
'test'.split(/(?:)/, -1).length !== 4 ||
''.split(/.?/).length ||
'.'.split(/()()/).length > 1
) {
(function () {
var compliantExecNpcg = typeof (/()??/).exec('')[1] === 'undefined'; // NPCG: nonparticipating capturing group
var maxSafe32BitInt = Math.pow(2, 32) - 1;
StringPrototype.split = function (separator, limit) {
var string = this;
if (typeof separator === 'undefined' && limit === 0) {
return [];
}
// If `separator` is not a regex, use native split
if (!isRegex(separator)) {
return strSplit(this, separator, limit);
}
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') + // in ES6
(separator.sticky ? 'y' : ''), // Firefox 3+ and ES6
lastLastIndex = 0,
// Make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
var separatorCopy = new RegExp(separator.source, flags + 'g');
string += ''; // Type-convert
if (!compliantExecNpcg) {
// Doesn't need flags gy, but they don't hurt
separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
}
/* Values for `limit`, per the spec:
* If undefined: 4294967295 // maxSafe32BitInt
* If 0, Infinity, or NaN: 0
* If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
* If negative number: 4294967296 - Math.floor(Math.abs(limit))
* If other: Type-convert, then use the above rules
*/
var splitLimit = typeof limit === 'undefined' ? maxSafe32BitInt : ES.ToUint32(limit);
match = separatorCopy.exec(string);
while (match) {
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0].length;
if (lastIndex > lastLastIndex) {
array_push.call(output, strSlice(string, lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1) {
/* eslint-disable no-loop-func */
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (typeof arguments[i] === 'undefined') {
match[i] = void 0;
}
}
});
/* eslint-enable no-loop-func */
}
if (match.length > 1 && match.index < string.length) {
array_push.apply(output, array_slice.call(match, 1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= splitLimit) {
break;
}
}
if (separatorCopy.lastIndex === match.index) {
separatorCopy.lastIndex++; // Avoid an infinite loop
}
match = separatorCopy.exec(string);
}
if (lastLastIndex === string.length) {
if (lastLength || !separatorCopy.test('')) {
array_push.call(output, '');
}
} else {
array_push.call(output, strSlice(string, lastLastIndex));
}
return output.length > splitLimit ? strSlice(output, 0, splitLimit) : output;
};
}());
// [bugfix, chrome]
// If separator is undefined, then the result array contains just one String,
// which is the this value (converted to a String). If limit is not undefined,
// then the output array is truncated so that it contains no more than limit
// elements.
// "0".split(undefined, 0) -> []
} else if ('0'.split(void 0, 0).length) {
StringPrototype.split = function split(separator, limit) {
if (typeof separator === 'undefined' && limit === 0) { return []; }
return strSplit(this, separator, limit);
};
}
var str_replace = StringPrototype.replace;
var replaceReportsGroupsCorrectly = (function () {
var groups = [];
'x'.replace(/x(.)?/g, function (match, group) {
array_push.call(groups, group);
});
return groups.length === 1 && typeof groups[0] === 'undefined';
}());
if (!replaceReportsGroupsCorrectly) {
StringPrototype.replace = function replace(searchValue, replaceValue) {
var isFn = isCallable(replaceValue);
var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source);
if (!isFn || !hasCapturingGroups) {
return str_replace.call(this, searchValue, replaceValue);
} else {
var wrappedReplaceValue = function (match) {
var length = arguments.length;
var originalLastIndex = searchValue.lastIndex;
searchValue.lastIndex = 0;
var args = searchValue.exec(match) || [];
searchValue.lastIndex = originalLastIndex;
array_push.call(args, arguments[length - 2], arguments[length - 1]);
return replaceValue.apply(this, args);
};
return str_replace.call(this, searchValue, wrappedReplaceValue);
}
};
}
// ECMA-262, 3rd B.2.3
// Not an ECMAScript standard, although ECMAScript 3rd Edition has a
// non-normative section suggesting uniform semantics and it should be
// normalized across all browsers
// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
var string_substr = StringPrototype.substr;
var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
defineProperties(StringPrototype, {
substr: function substr(start, length) {
var normalizedStart = start;
if (start < 0) {
normalizedStart = max(this.length + start, 0);
}
return string_substr.call(this, normalizedStart, length);
}
}, hasNegativeSubstrBug);
// ES5 15.5.4.20
// whitespace from: http://es5.github.io/#x15.5.4.20
var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' +
'\u2029\uFEFF';
var zeroWidth = '\u200b';
var wsRegexChars = '[' + ws + ']';
var trimBeginRegexp = new RegExp('^' + wsRegexChars + wsRegexChars + '*');
var trimEndRegexp = new RegExp(wsRegexChars + wsRegexChars + '*$');
var hasTrimWhitespaceBug = StringPrototype.trim && (ws.trim() || !zeroWidth.trim());
defineProperties(StringPrototype, {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
trim: function trim() {
if (typeof this === 'undefined' || this === null) {
throw new TypeError("can't convert " + this + ' to object');
}
return $String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
}
}, hasTrimWhitespaceBug);
var hasLastIndexBug = String.prototype.lastIndexOf && 'abcあい'.lastIndexOf('あい', 2) !== -1;
defineProperties(StringPrototype, {
lastIndexOf: function lastIndexOf(searchString) {
if (typeof this === 'undefined' || this === null) {
throw new TypeError("can't convert " + this + ' to object');
}
var S = $String(this);
var searchStr = $String(searchString);
var numPos = arguments.length > 1 ? $Number(arguments[1]) : NaN;
var pos = isActualNaN(numPos) ? Infinity : ES.ToInteger(numPos);
var start = min(max(pos, 0), S.length);
var searchLen = searchStr.length;
var k = start + searchLen;
while (k > 0) {
k = max(0, k - searchLen);
var index = strIndexOf(strSlice(S, k, start + searchLen), searchStr);
if (index !== -1) {
return k + index;
}
}
return -1;
}
}, hasLastIndexBug);
// ES-5 15.1.2.2
if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) {
/* global parseInt: true */
parseInt = (function (origParseInt) {
var hexRegex = /^0[xX]/;
return function parseInt(str, radix) {
var string = $String(str).trim();
var defaultedRadix = $Number(radix) || (hexRegex.test(string) ? 16 : 10);
return origParseInt(string, defaultedRadix);
};
}(parseInt));
}
}));
| staticmatrix/Triangle | refer/modules/es5-shim/4.2.0/es5-shim.js | JavaScript | mit | 61,950 |
<?php
namespace Drupal\views_ui\Form\Ajax;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\ViewExecutable;
use Drupal\views\ViewEntityInterface;
use Drupal\views\Views;
/**
* Provides a form for adding an item in the Views UI.
*/
class AddHandler extends ViewsFormBase {
/**
* Constructs a new AddHandler object.
*/
public function __construct($type = NULL) {
$this->setType($type);
}
/**
* {@inheritdoc}
*/
public function getFormKey() {
return 'add-handler';
}
/**
* {@inheritdoc}
*/
public function getForm(ViewEntityInterface $view, $display_id, $js, $type = NULL) {
$this->setType($type);
return parent::getForm($view, $display_id, $js);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'views_ui_add_handler_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$view = $form_state->get('view');
$display_id = $form_state->get('display_id');
$type = $form_state->get('type');
$form = array(
'options' => array(
'#theme_wrappers' => array('container'),
'#attributes' => array('class' => array('scroll'), 'data-drupal-views-scroll' => TRUE),
),
);
$executable = $view->getExecutable();
if (!$executable->setDisplay($display_id)) {
$form['markup'] = array('#markup' => $this->t('Invalid display id @display', array('@display' => $display_id)));
return $form;
}
$display = &$executable->displayHandlers->get($display_id);
$types = ViewExecutable::getHandlerTypes();
$ltitle = $types[$type]['ltitle'];
$section = $types[$type]['plural'];
if (!empty($types[$type]['type'])) {
$type = $types[$type]['type'];
}
$form['#title'] = $this->t('Add @type', array('@type' => $ltitle));
$form['#section'] = $display_id . 'add-handler';
// Add the display override dropdown.
views_ui_standard_display_dropdown($form, $form_state, $section);
// Figure out all the base tables allowed based upon what the relationships provide.
$base_tables = $executable->getBaseTables();
$options = Views::viewsDataHelper()->fetchFields(array_keys($base_tables), $type, $display->useGroupBy(), $form_state->get('type'));
if (!empty($options)) {
$form['override']['controls'] = array(
'#theme_wrappers' => array('container'),
'#id' => 'views-filterable-options-controls',
'#attributes' => ['class' => ['form--inline', 'views-filterable-options-controls']],
);
$form['override']['controls']['options_search'] = array(
'#type' => 'textfield',
'#title' => $this->t('Search'),
);
$groups = array('all' => $this->t('- All -'));
$form['override']['controls']['group'] = array(
'#type' => 'select',
'#title' => $this->t('Type'),
'#options' => array(),
);
$form['options']['name'] = array(
'#prefix' => '<div class="views-radio-box form-checkboxes views-filterable-options">',
'#suffix' => '</div>',
'#type' => 'tableselect',
'#header' => array(
'title' => $this->t('Title'),
'group' => $this->t('Category'),
'help' => $this->t('Description'),
),
'#js_select' => FALSE,
);
$grouped_options = array();
foreach ($options as $key => $option) {
$group = preg_replace('/[^a-z0-9]/', '-', strtolower($option['group']));
$groups[$group] = $option['group'];
$grouped_options[$group][$key] = $option;
if (!empty($option['aliases']) && is_array($option['aliases'])) {
foreach ($option['aliases'] as $id => $alias) {
if (empty($alias['base']) || !empty($base_tables[$alias['base']])) {
$copy = $option;
$copy['group'] = $alias['group'];
$copy['title'] = $alias['title'];
if (isset($alias['help'])) {
$copy['help'] = $alias['help'];
}
$group = preg_replace('/[^a-z0-9]/', '-', strtolower($copy['group']));
$groups[$group] = $copy['group'];
$grouped_options[$group][$key . '$' . $id] = $copy;
}
}
}
}
foreach ($grouped_options as $group => $group_options) {
foreach ($group_options as $key => $option) {
$form['options']['name']['#options'][$key] = array(
'#attributes' => array(
'class' => array('filterable-option', $group),
),
'title' => array(
'data' => array(
'#title' => $option['title'],
'#plain_text' => $option['title'],
),
'class' => array('title'),
),
'group' => $option['group'],
'help' => array(
'data' => $option['help'],
'class' => array('description'),
),
);
}
}
$form['override']['controls']['group']['#options'] = $groups;
}
else {
$form['options']['markup'] = array(
'#markup' => '<div class="js-form-item form-item">' . $this->t('There are no @types available to add.', array('@types' => $ltitle)) . '</div>',
);
}
// Add a div to show the selected items
$form['selected'] = array(
'#type' => 'item',
'#markup' => '<span class="views-ui-view-title">' . $this->t('Selected:') . '</span> ' . '<div class="views-selected-options"></div>',
'#theme_wrappers' => array('form_element', 'views_ui_container'),
'#attributes' => array(
'class' => array('container-inline', 'views-add-form-selected', 'views-offset-bottom'),
'data-drupal-views-offset' => 'bottom',
),
);
$view->getStandardButtons($form, $form_state, 'views_ui_add_handler_form', $this->t('Add and configure @types', array('@types' => $ltitle)));
// Remove the default submit function.
$form['actions']['submit']['#submit'] = array_filter($form['actions']['submit']['#submit'], function($var) {
return !(is_array($var) && isset($var[1]) && $var[1] == 'standardSubmit');
});
$form['actions']['submit']['#submit'][] = array($view, 'submitItemAdd');
return $form;
}
}
| ngbentley/d8_devshop | web/core/modules/views_ui/src/Form/Ajax/AddHandler.php | PHP | gpl-2.0 | 6,305 |
<?php
class meter
{
function __construct()
{
}
function makeSVG($tag, $type, $value, $max, $min, $optimum, $low, $high)
{
$svg = '';
if ($tag == 'meter') {
if ($type == '2') {
/////////////////////////////////////////////////////////////////////////////////////
///////// CUSTOM <meter type="2">
/////////////////////////////////////////////////////////////////////////////////////
$h = 10;
$w = 160;
$border_radius = 0.143; // Factor of Height
$svg = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g>
<defs>
<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(222, 222, 222)" />
<stop offset="20%" stop-color="rgb(232, 232, 232)" />
<stop offset="25%" stop-color="rgb(232, 232, 232)" />
<stop offset="100%" stop-color="rgb(182, 182, 182)" />
</linearGradient>
</defs>
';
$svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="#f4f4f4" stroke="none" />';
// LOW to HIGH region
//if ($low && $high && ($low != $min || $high != $max)) {
if ($low && $high) {
$barx = (($low - $min) / ($max - $min) ) * $w;
$barw = (($high - $low) / ($max - $min) ) * $w;
$svg .= '<rect x="' . $barx . '" y="0" width="' . $barw . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="#888888" stroke-width="0.5px" />';
}
// OPTIMUM Marker (? AVERAGE)
if ($optimum) {
$barx = (($optimum - $min) / ($max - $min) ) * $w;
$barw = $h / 2;
$barcol = '#888888';
$svg .= '<rect x="' . $barx . '" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />';
}
// VALUE Marker
if ($value) {
if ($min != $low && $value < $low) {
$col = 'orange';
} else if ($max != $high && $value > $high) {
$col = 'orange';
} else {
$col = '#008800';
}
$cx = (($value - $min) / ($max - $min) ) * $w;
$cy = $h / 2;
$rx = $h / 3.5;
$ry = $h / 2.2;
$svg .= '<ellipse fill="' . $col . '" stroke="#000000" stroke-width="0.5px" cx="' . $cx . '" cy="' . $cy . '" rx="' . $rx . '" ry="' . $ry . '"/>';
}
// BoRDER
$svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />';
$svg .= '</g></svg>';
} else if ($type == '3') {
/////////////////////////////////////////////////////////////////////////////////////
///////// CUSTOM <meter type="2">
/////////////////////////////////////////////////////////////////////////////////////
$h = 10;
$w = 100;
$border_radius = 0.143; // Factor of Height
$svg = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g>
<defs>
<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(222, 222, 222)" />
<stop offset="20%" stop-color="rgb(232, 232, 232)" />
<stop offset="25%" stop-color="rgb(232, 232, 232)" />
<stop offset="100%" stop-color="rgb(182, 182, 182)" />
</linearGradient>
</defs>
';
$svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="#f4f4f4" stroke="none" />';
// LOW to HIGH region
if ($low && $high && ($low != $min || $high != $max)) {
//if ($low && $high) {
$barx = (($low - $min) / ($max - $min) ) * $w;
$barw = (($high - $low) / ($max - $min) ) * $w;
$svg .= '<rect x="' . $barx . '" y="0" width="' . $barw . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="#888888" stroke-width="0.5px" />';
}
// OPTIMUM Marker (? AVERAGE)
if ($optimum) {
$barx = (($optimum - $min) / ($max - $min) ) * $w;
$barw = $h / 2;
$barcol = '#888888';
$svg .= '<rect x="' . $barx . '" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />';
}
// VALUE Marker
if ($value) {
if ($min != $low && $value < $low) {
$col = 'orange';
} else if ($max != $high && $value > $high) {
$col = 'orange';
} else {
$col = 'orange';
}
$cx = (($value - $min) / ($max - $min) ) * $w;
$cy = $h / 2;
$rx = $h / 2.2;
$ry = $h / 2.2;
$svg .= '<ellipse fill="' . $col . '" stroke="#000000" stroke-width="0.5px" cx="' . $cx . '" cy="' . $cy . '" rx="' . $rx . '" ry="' . $ry . '"/>';
}
// BoRDER
$svg .= '<rect x="0" y="0" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />';
$svg .= '</g></svg>';
} else {
/////////////////////////////////////////////////////////////////////////////////////
///////// DEFAULT <meter>
/////////////////////////////////////////////////////////////////////////////////////
$h = 10;
$w = 50;
$border_radius = 0.143; // Factor of Height
$svg = '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" ><g>
<defs>
<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(222, 222, 222)" />
<stop offset="20%" stop-color="rgb(232, 232, 232)" />
<stop offset="25%" stop-color="rgb(232, 232, 232)" />
<stop offset="100%" stop-color="rgb(182, 182, 182)" />
</linearGradient>
<linearGradient id="GrRED" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(255, 162, 162)" />
<stop offset="20%" stop-color="rgb(255, 218, 218)" />
<stop offset="25%" stop-color="rgb(255, 218, 218)" />
<stop offset="100%" stop-color="rgb(255, 0, 0)" />
</linearGradient>
<linearGradient id="GrGREEN" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(102, 230, 102)" />
<stop offset="20%" stop-color="rgb(218, 255, 218)" />
<stop offset="25%" stop-color="rgb(218, 255, 218)" />
<stop offset="100%" stop-color="rgb(0, 148, 0)" />
</linearGradient>
<linearGradient id="GrBLUE" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(102, 102, 230)" />
<stop offset="20%" stop-color="rgb(238, 238, 238)" />
<stop offset="25%" stop-color="rgb(238, 238, 238)" />
<stop offset="100%" stop-color="rgb(0, 0, 128)" />
</linearGradient>
<linearGradient id="GrORANGE" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(255, 186, 0)" />
<stop offset="20%" stop-color="rgb(255, 238, 168)" />
<stop offset="25%" stop-color="rgb(255, 238, 168)" />
<stop offset="100%" stop-color="rgb(255, 155, 0)" />
</linearGradient>
</defs>
<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="url(#GrGRAY)" stroke="none" />
';
if ($value) {
$barw = (($value - $min) / ($max - $min) ) * $w;
if ($optimum < $low) {
if ($value < $low) {
$barcol = 'url(#GrGREEN)';
} else if ($value > $high) {
$barcol = 'url(#GrRED)';
} else {
$barcol = 'url(#GrORANGE)';
}
} else if ($optimum > $high) {
if ($value < $low) {
$barcol = 'url(#GrRED)';
} else if ($value > $high) {
$barcol = 'url(#GrGREEN)';
} else {
$barcol = 'url(#GrORANGE)';
}
} else {
if ($value < $low) {
$barcol = 'url(#GrORANGE)';
} else if ($value > $high) {
$barcol = 'url(#GrORANGE)';
} else {
$barcol = 'url(#GrGREEN)';
}
}
$svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />';
}
// Borders
//$svg .= '<rect x="0" y="0" rx="'.($h*$border_radius).'px" ry="'.($h*$border_radius).'px" width="'.$w.'" height="'.$h.'" fill="none" stroke="#888888" stroke-width="0.5px" />';
if ($value) {
// $svg .= '<rect x="0" y="0" rx="'.($h*$border_radius).'px" ry="'.($h*$border_radius).'px" width="'.$barw.'" height="'.$h.'" fill="none" stroke="#888888" stroke-width="0.5px" />';
}
$svg .= '</g></svg>';
}
} else { // $tag == 'progress'
if ($type == '2') {
/////////////////////////////////////////////////////////////////////////////////////
///////// CUSTOM <progress type="2">
/////////////////////////////////////////////////////////////////////////////////////
} else {
/////////////////////////////////////////////////////////////////////////////////////
///////// DEFAULT <progress>
/////////////////////////////////////////////////////////////////////////////////////
$h = 10;
$w = 100;
$border_radius = 0.143; // Factor of Height
if ($value or $value === '0') {
$fill = 'url(#GrGRAY)';
} else {
$fill = '#f8f8f8';
}
$svg = '<svg width="' . $w . 'px" height="' . $h . 'px" viewBox="0 0 ' . $w . ' ' . $h . '"><g>
<defs>
<linearGradient id="GrGRAY" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(222, 222, 222)" />
<stop offset="20%" stop-color="rgb(232, 232, 232)" />
<stop offset="25%" stop-color="rgb(232, 232, 232)" />
<stop offset="100%" stop-color="rgb(182, 182, 182)" />
</linearGradient>
<linearGradient id="GrGREEN" x1="0" y1="0" x2="0" y2="1" gradientUnits="boundingBox">
<stop offset="0%" stop-color="rgb(102, 230, 102)" />
<stop offset="20%" stop-color="rgb(218, 255, 218)" />
<stop offset="25%" stop-color="rgb(218, 255, 218)" />
<stop offset="100%" stop-color="rgb(0, 148, 0)" />
</linearGradient>
</defs>
<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="' . $fill . '" stroke="none" />
';
if ($value) {
$barw = (($value - $min) / ($max - $min) ) * $w;
$barcol = 'url(#GrGREEN)';
$svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $barw . '" height="' . $h . '" fill="' . $barcol . '" stroke="none" />';
}
// Borders
$svg .= '<rect x="0" y="0" rx="' . ($h * $border_radius) . 'px" ry="' . ($h * $border_radius) . 'px" width="' . $w . '" height="' . $h . '" fill="none" stroke="#888888" stroke-width="0.5px" />';
if ($value) {
// $svg .= '<rect x="0" y="0" rx="'.($h*$border_radius).'px" ry="'.($h*$border_radius).'px" width="'.$barw.'" height="'.$h.'" fill="none" stroke="#888888" stroke-width="0.5px" />';
}
$svg .= '</g></svg>';
}
}
return $svg;
}
}
| wp-rio/wp-rio | wp-content/themes/wp-rio/inc/certificate/lib/mpdf/classes/meter.php | PHP | gpl-2.0 | 11,355 |
// -*- C++ -*-
// Copyright (C) 2005-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file cc_hash_table_map_/cmp_fn_imps.hpp
* Contains implementations of cc_ht_map_'s entire container comparison related
* functions.
*/
PB_DS_CLASS_T_DEC
template<typename Other_HT_Map_Type>
bool
PB_DS_CLASS_C_DEC::
operator==(const Other_HT_Map_Type& other) const
{ return cmp_with_other(other); }
PB_DS_CLASS_T_DEC
template<typename Other_Map_Type>
bool
PB_DS_CLASS_C_DEC::
cmp_with_other(const Other_Map_Type& other) const
{
if (size() != other.size())
return false;
for (typename Other_Map_Type::const_iterator it = other.begin();
it != other.end(); ++it)
{
key_const_reference r_key = key_const_reference(PB_DS_V2F(*it));
mapped_const_pointer p_mapped_value =
const_cast<PB_DS_CLASS_C_DEC& >(*this).
find_key_pointer(r_key, traits_base::m_store_extra_indicator);
if (p_mapped_value == 0)
return false;
#ifdef PB_DS_DATA_TRUE_INDICATOR
if (p_mapped_value->second != it->second)
return false;
#endif
}
return true;
}
PB_DS_CLASS_T_DEC
template<typename Other_HT_Map_Type>
bool
PB_DS_CLASS_C_DEC::
operator!=(const Other_HT_Map_Type& other) const
{ return !operator==(other); }
| ruibarreira/linuxtrail | usr/include/c++/4.9/ext/pb_ds/detail/cc_hash_table_map_/cmp_fn_imps.hpp | C++ | gpl-3.0 | 2,765 |
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the 2-clause BSD license.
* See license.txt in the OpenLayers distribution or repository for the
* full text of the license. */
/**
* @requires OpenLayers/BaseTypes/Class.js
*/
/**
* Class: OpenLayers.Protocol
* Abstract vector layer protocol class. Not to be instantiated directly. Use
* one of the protocol subclasses instead.
*/
OpenLayers.Protocol = OpenLayers.Class({
/**
* Property: format
* {<OpenLayers.Format>} The format used by this protocol.
*/
format: null,
/**
* Property: options
* {Object} Any options sent to the constructor.
*/
options: null,
/**
* Property: autoDestroy
* {Boolean} The creator of the protocol can set autoDestroy to false
* to fully control when the protocol is destroyed. Defaults to
* true.
*/
autoDestroy: true,
/**
* Property: defaultFilter
* {<OpenLayers.Filter>} Optional default filter to read requests
*/
defaultFilter: null,
/**
* Constructor: OpenLayers.Protocol
* Abstract class for vector protocols. Create instances of a subclass.
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*/
initialize: function(options) {
options = options || {};
OpenLayers.Util.extend(this, options);
this.options = options;
},
/**
* Method: mergeWithDefaultFilter
* Merge filter passed to the read method with the default one
*
* Parameters:
* filter - {<OpenLayers.Filter>}
*/
mergeWithDefaultFilter: function(filter) {
var merged;
if (filter && this.defaultFilter) {
merged = new OpenLayers.Filter.Logical({
type: OpenLayers.Filter.Logical.AND,
filters: [this.defaultFilter, filter]
});
} else {
merged = filter || this.defaultFilter || undefined;
}
return merged;
},
/**
* APIMethod: destroy
* Clean up the protocol.
*/
destroy: function() {
this.options = null;
this.format = null;
},
/**
* APIMethod: read
* Construct a request for reading new features.
*
* Parameters:
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
read: function(options) {
options = options || {};
options.filter = this.mergeWithDefaultFilter(options.filter);
},
/**
* APIMethod: create
* Construct a request for writing newly created features.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})} or
* {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
create: function() {
},
/**
* APIMethod: update
* Construct a request updating modified features.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})} or
* {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
update: function() {
},
/**
* APIMethod: delete
* Construct a request deleting a removed feature.
*
* Parameters:
* feature - {<OpenLayers.Feature.Vector>}
* options - {Object} Optional object for configuring the request.
*
* Returns:
* {<OpenLayers.Protocol.Response>} An <OpenLayers.Protocol.Response>
* object, the same object will be passed to the callback function passed
* if one exists in the options object.
*/
"delete": function() {
},
/**
* APIMethod: commit
* Go over the features and for each take action
* based on the feature state. Possible actions are create,
* update and delete.
*
* Parameters:
* features - {Array({<OpenLayers.Feature.Vector>})}
* options - {Object} Object whose possible keys are "create", "update",
* "delete", "callback" and "scope", the values referenced by the
* first three are objects as passed to the "create", "update", and
* "delete" methods, the value referenced by the "callback" key is
* a function which is called when the commit operation is complete
* using the scope referenced by the "scope" key.
*
* Returns:
* {Array({<OpenLayers.Protocol.Response>})} An array of
* <OpenLayers.Protocol.Response> objects.
*/
commit: function() {
},
/**
* Method: abort
* Abort an ongoing request.
*
* Parameters:
* response - {<OpenLayers.Protocol.Response>}
*/
abort: function(response) {
},
/**
* Method: createCallback
* Returns a function that applies the given public method with resp and
* options arguments.
*
* Parameters:
* method - {Function} The method to be applied by the callback.
* response - {<OpenLayers.Protocol.Response>} The protocol response object.
* options - {Object} Options sent to the protocol method
*/
createCallback: function(method, response, options) {
return OpenLayers.Function.bind(function() {
method.apply(this, [response, options]);
}, this);
},
CLASS_NAME: "OpenLayers.Protocol"
});
/**
* Class: OpenLayers.Protocol.Response
* Protocols return Response objects to their users.
*/
OpenLayers.Protocol.Response = OpenLayers.Class({
/**
* Property: code
* {Number} - OpenLayers.Protocol.Response.SUCCESS or
* OpenLayers.Protocol.Response.FAILURE
*/
code: null,
/**
* Property: requestType
* {String} The type of request this response corresponds to. Either
* "create", "read", "update" or "delete".
*/
requestType: null,
/**
* Property: last
* {Boolean} - true if this is the last response expected in a commit,
* false otherwise, defaults to true.
*/
last: true,
/**
* Property: features
* {Array({<OpenLayers.Feature.Vector>})} or {<OpenLayers.Feature.Vector>}
* The features returned in the response by the server. Depending on the
* protocol's read payload, either features or data will be populated.
*/
features: null,
/**
* Property: data
* {Object}
* The data returned in the response by the server. Depending on the
* protocol's read payload, either features or data will be populated.
*/
data: null,
/**
* Property: reqFeatures
* {Array({<OpenLayers.Feature.Vector>})} or {<OpenLayers.Feature.Vector>}
* The features provided by the user and placed in the request by the
* protocol.
*/
reqFeatures: null,
/**
* Property: priv
*/
priv: null,
/**
* Property: error
* {Object} The error object in case a service exception was encountered.
*/
error: null,
/**
* Constructor: OpenLayers.Protocol.Response
*
* Parameters:
* options - {Object} Optional object whose properties will be set on the
* instance.
*/
initialize: function(options) {
OpenLayers.Util.extend(this, options);
},
/**
* Method: success
*
* Returns:
* {Boolean} - true on success, false otherwise
*/
success: function() {
return this.code > 0;
},
CLASS_NAME: "OpenLayers.Protocol.Response"
});
OpenLayers.Protocol.Response.SUCCESS = 1;
OpenLayers.Protocol.Response.FAILURE = 0;
| savchukoleksii/beaversteward | www/settings/tools/mysql/js/openlayers/src/openlayers/lib/OpenLayers/Protocol.js | JavaScript | mit | 8,407 |
(function($){
if(webshims.support.texttrackapi && document.addEventListener){
var trackOptions = webshims.cfg.track;
var trackListener = function(e){
$(e.target).filter('track').each(changeApi);
};
var trackBugs = webshims.bugs.track;
var changeApi = function(){
if(trackBugs || (!trackOptions.override && $.prop(this, 'readyState') == 3)){
trackOptions.override = true;
webshims.reTest('track');
document.removeEventListener('error', trackListener, true);
if(this && $.nodeName(this, 'track')){
webshims.error("track support was overwritten. Please check your vtt including your vtt mime-type");
} else {
webshims.info("track support was overwritten. due to bad browser support");
}
return false;
}
};
var detectTrackError = function(){
document.addEventListener('error', trackListener, true);
if(trackBugs){
changeApi();
} else {
$('track').each(changeApi);
}
if(!trackBugs && !trackOptions.override){
webshims.defineProperty(TextTrack.prototype, 'shimActiveCues', {
get: function(){
return this._shimActiveCues || this.activeCues;
}
});
}
};
if(!trackOptions.override){
$(detectTrackError);
}
}
})(webshims.$);
webshims.register('track-ui', function($, webshims, window, document, undefined){
"use strict";
var options = webshims.cfg.track;
var support = webshims.support;
//descriptions are not really shown, but they are inserted into the dom
var showTracks = {subtitles: 1, captions: 1, descriptions: 1};
var mediaelement = webshims.mediaelement;
var usesNativeTrack = function(){
return !options.override && support.texttrackapi;
};
var trackDisplay = {
update: function(baseData, media){
if(!baseData.activeCues.length){
this.hide(baseData);
} else {
if(!compareArray(baseData.displayedActiveCues, baseData.activeCues)){
baseData.displayedActiveCues = baseData.activeCues;
if(!baseData.trackDisplay){
baseData.trackDisplay = $('<div class="cue-display '+webshims.shadowClass+'"><span class="description-cues" aria-live="assertive" /></div>').insertAfter(media);
this.addEvents(baseData, media);
webshims.docObserve();
}
if(baseData.hasDirtyTrackDisplay){
media.triggerHandler('forceupdatetrackdisplay');
}
this.showCues(baseData);
}
}
},
showCues: function(baseData){
var element = $('<span class="cue-wrapper" />');
$.each(baseData.displayedActiveCues, function(i, cue){
var id = (cue.id) ? 'id="cue-id-'+cue.id +'"' : '';
var cueHTML = $('<span class="cue-line"><span '+ id+ ' class="cue" /></span>').find('span').html(cue.getCueAsHTML()).end();
if(cue.track.kind == 'descriptions'){
setTimeout(function(){
$('span.description-cues', baseData.trackDisplay).html(cueHTML);
}, 0);
} else {
element.prepend(cueHTML);
}
});
$('span.cue-wrapper', baseData.trackDisplay).remove();
baseData.trackDisplay.append(element);
},
addEvents: function(baseData, media){
if(options.positionDisplay){
var timer;
var positionDisplay = function(_force){
if(baseData.displayedActiveCues.length || _force === true){
baseData.trackDisplay.css({display: 'none'});
var uiElement = media.getShadowElement();
var uiHeight = uiElement.innerHeight();
var uiWidth = uiElement.innerWidth();
var position = uiElement.position();
baseData.trackDisplay.css({
left: position.left,
width: uiWidth,
height: uiHeight - 45,
top: position.top,
display: 'block'
});
baseData.trackDisplay.css('fontSize', Math.max(Math.round(uiHeight / 30), 7));
baseData.hasDirtyTrackDisplay = false;
} else {
baseData.hasDirtyTrackDisplay = true;
}
};
var delayed = function(e){
clearTimeout(timer);
timer = setTimeout(positionDisplay, 0);
};
var forceUpdate = function(){
positionDisplay(true);
};
media.on('playerdimensionchange mediaelementapichange updatetrackdisplay updatemediaelementdimensions swfstageresize', delayed);
media.on('forceupdatetrackdisplay', forceUpdate).onWSOff('updateshadowdom', delayed);
forceUpdate();
}
},
hide: function(baseData){
if(baseData.trackDisplay && baseData.displayedActiveCues.length){
baseData.displayedActiveCues = [];
$('span.cue-wrapper', baseData.trackDisplay).remove();
$('span.description-cues', baseData.trackDisplay).empty();
}
}
};
function compareArray(a1, a2){
var ret = true;
var i = 0;
var len = a1.length;
if(len != a2.length){
ret = false;
} else {
for(; i < len; i++){
if(a1[i] != a2[i]){
ret = false;
break;
}
}
}
return ret;
}
mediaelement.trackDisplay = trackDisplay;
if(!mediaelement.createCueList){
var cueListProto = {
getCueById: function(id){
var cue = null;
for(var i = 0, len = this.length; i < len; i++){
if(this[i].id === id){
cue = this[i];
break;
}
}
return cue;
}
};
mediaelement.createCueList = function(){
return $.extend([], cueListProto);
};
}
mediaelement.getActiveCue = function(track, media, time, baseData){
if(!track._lastFoundCue){
track._lastFoundCue = {index: 0, time: 0};
}
if(support.texttrackapi && !options.override && !track._shimActiveCues){
track._shimActiveCues = mediaelement.createCueList();
}
var i = 0;
var len;
var cue;
for(; i < track.shimActiveCues.length; i++){
cue = track.shimActiveCues[i];
if(cue.startTime > time || cue.endTime < time){
track.shimActiveCues.splice(i, 1);
i--;
if(cue.pauseOnExit){
$(media).pause();
}
$(track).triggerHandler('cuechange');
$(cue).triggerHandler('exit');
} else if(track.mode == 'showing' && showTracks[track.kind] && $.inArray(cue, baseData.activeCues) == -1){
baseData.activeCues.push(cue);
}
}
len = track.cues.length;
i = track._lastFoundCue.time < time ? track._lastFoundCue.index : 0;
for(; i < len; i++){
cue = track.cues[i];
if(cue.startTime <= time && cue.endTime >= time && $.inArray(cue, track.shimActiveCues) == -1){
track.shimActiveCues.push(cue);
if(track.mode == 'showing' && showTracks[track.kind]){
baseData.activeCues.push(cue);
}
$(track).triggerHandler('cuechange');
$(cue).triggerHandler('enter');
track._lastFoundCue.time = time;
track._lastFoundCue.index = i;
}
if(cue.startTime > time){
break;
}
}
};
if(usesNativeTrack()){
(function(){
var block;
var triggerDisplayUpdate = function(elem){
block = true;
setTimeout(function(){
$(elem).triggerHandler('updatetrackdisplay');
block = false;
}, 9);
};
var createUpdateFn = function(nodeName, prop, type){
var superType = '_sup'+type;
var desc = {prop: {}};
var superDesc;
desc.prop[type] = function(){
if(!block && usesNativeTrack()){
triggerDisplayUpdate($(this).closest('audio, video'));
}
return superDesc.prop[superType].apply(this, arguments);
};
superDesc = webshims.defineNodeNameProperty(nodeName, prop, desc);
};
createUpdateFn('track', 'track', 'get');
['audio', 'video'].forEach(function(nodeName){
createUpdateFn(nodeName, 'textTracks', 'get');
createUpdateFn('nodeName', 'addTextTrack', 'value');
});
})();
$.propHooks.activeCues = {
get: function(obj){
return obj._shimActiveCues || obj.activeCues;
}
};
}
webshims.addReady(function(context, insertedElement){
$('video, audio', context)
.add(insertedElement.filter('video, audio'))
.filter(function(){
return webshims.implement(this, 'trackui');
})
.each(function(){
var baseData, trackList, updateTimer, updateTimer2;
var elem = $(this);
var getDisplayCues = function(e){
var track;
var time;
if(!trackList || !baseData){
trackList = elem.prop('textTracks');
baseData = webshims.data(elem[0], 'mediaelementBase') || webshims.data(elem[0], 'mediaelementBase', {});
if(!baseData.displayedActiveCues){
baseData.displayedActiveCues = [];
}
}
if (!trackList){return;}
time = elem.prop('currentTime');
if(!time && time !== 0){return;}
baseData.activeCues = [];
for(var i = 0, len = trackList.length; i < len; i++){
track = trackList[i];
if(track.mode != 'disabled' && track.cues && track.cues.length){
mediaelement.getActiveCue(track, elem, time, baseData);
}
}
trackDisplay.update(baseData, elem);
};
var onUpdate = function(e){
clearTimeout(updateTimer);
if(e){
if(e.type == 'timeupdate'){
getDisplayCues();
}
updateTimer2 = setTimeout(onUpdate, 90);
} else {
updateTimer = setTimeout(getDisplayCues, 9);
}
};
var addTrackView = function(){
if(!trackList) {
trackList = elem.prop('textTracks');
}
//as soon as change on trackList is implemented in all browsers we do not need to have 'updatetrackdisplay' anymore
$( [trackList] ).on('change', onUpdate);
elem
.off('.trackview')
.on('play.trackview timeupdate.trackview updatetrackdisplay.trackview', onUpdate)
;
};
elem.on('remove', function(e){
if(!e.originalEvent && baseData && baseData.trackDisplay){
setTimeout(function(){
baseData.trackDisplay.remove();
}, 4);
}
});
if(!usesNativeTrack()){
addTrackView();
} else {
if(elem.hasClass('nonnative-api-active')){
addTrackView();
}
elem
.on('mediaelementapichange trackapichange', function(){
if(!usesNativeTrack() || elem.hasClass('nonnative-api-active')){
addTrackView();
} else {
clearTimeout(updateTimer);
clearTimeout(updateTimer2);
trackList = elem.prop('textTracks');
baseData = webshims.data(elem[0], 'mediaelementBase') || webshims.data(elem[0], 'mediaelementBase', {});
$.each(trackList, function(i, track){
if(track._shimActiveCues){
delete track._shimActiveCues;
}
});
trackDisplay.hide(baseData);
elem.off('.trackview');
}
})
;
}
})
;
});
});
| ttitto/ttitto.github.io | js-webshim/dev/shims/track-ui.js | JavaScript | mit | 10,440 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2012 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# GuessIt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import unicode_literals
from guessit import Guess
from guessit.transfo import SingleNodeGuesser
from guessit.patterns import video_rexps, sep
import re
import logging
log = logging.getLogger(__name__)
def guess_video_rexps(string):
string = '-' + string + '-'
for rexp, confidence, span_adjust in video_rexps:
match = re.search(sep + rexp + sep, string, re.IGNORECASE)
if match:
metadata = match.groupdict()
# is this the better place to put it? (maybe, as it is at least
# the soonest that we can catch it)
if metadata.get('cdNumberTotal', -1) is None:
del metadata['cdNumberTotal']
span = (match.start() + span_adjust[0],
match.end() + span_adjust[1] - 2)
return (Guess(metadata, confidence=confidence, raw=string[span[0]:span[1]]),
span)
return None, None
def process(mtree):
SingleNodeGuesser(guess_video_rexps, None, log).process(mtree)
| loulich/Couchpotato | libs/guessit/transfo/guess_video_rexps.py | Python | gpl-3.0 | 1,837 |
//// [symbolDeclarationEmit8.ts]
var obj = {
[Symbol.isConcatSpreadable]: 0
}
//// [symbolDeclarationEmit8.js]
var obj = {
[Symbol.isConcatSpreadable]: 0
};
//// [symbolDeclarationEmit8.d.ts]
declare var obj: {
[Symbol.isConcatSpreadable]: number;
};
| shanexu/TypeScript | tests/baselines/reference/symbolDeclarationEmit8.js | JavaScript | apache-2.0 | 279 |
/*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"fmt"
"github.com/golang/glog"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/tools/cache"
)
// WaitForCacheSync is a wrapper around cache.WaitForCacheSync that generates log messages
// indicating that the controller identified by controllerName is waiting for syncs, followed by
// either a successful or failed sync.
func WaitForCacheSync(controllerName string, stopCh <-chan struct{}, cacheSyncs ...cache.InformerSynced) bool {
glog.Infof("Waiting for caches to sync for %s controller", controllerName)
if !cache.WaitForCacheSync(stopCh, cacheSyncs...) {
utilruntime.HandleError(fmt.Errorf("Unable to sync caches for %s controller", controllerName))
return false
}
glog.Infof("Caches are synced for %s controller", controllerName)
return true
}
| bparees/open-service-broker-sdk | vendor/k8s.io/kubernetes/staging/src/k8s.io/kube-aggregator/pkg/controllers/cache.go | GO | apache-2.0 | 1,390 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
namespace System.Data.Common
{
internal partial class DbConnectionOptions
{
protected DbConnectionOptions(string connectionString, Dictionary<string, string> synonyms)
: this (connectionString, new Hashtable(synonyms), false)
{
}
internal bool TryGetParsetableValue(string key, out string value)
{
if (_parsetable.ContainsKey(key))
{
value = (string)_parsetable[key];
return true;
}
value = null;
return false;
}
}
} | nbarbettini/corefx | src/System.Data.Common/src/System/Data/Common/DbConnectionOptions.Mono.cs | C# | mit | 843 |
<?php
/**
* Memcache storage engine for cache
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Cache.Engine
* @since CakePHP(tm) v 1.2.0.4933
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Memcache storage engine for cache. Memcache has some limitations in the amount of
* control you have over expire times far in the future. See MemcacheEngine::write() for
* more information.
*
* @package Cake.Cache.Engine
* @deprecated 3.0.0 You should use the Memcached adapter instead.
*/
class MemcacheEngine extends CacheEngine {
/**
* Contains the compiled group names
* (prefixed with the global configuration prefix)
*
* @var array
*/
protected $_compiledGroupNames = array();
/**
* Memcache wrapper.
*
* @var Memcache
*/
protected $_Memcache = null;
/**
* Settings
*
* - servers = string or array of memcache servers, default => 127.0.0.1. If an
* array MemcacheEngine will use them as a pool.
* - compress = boolean, default => false
*
* @var array
*/
public $settings = array();
/**
* Initialize the Cache Engine
*
* Called automatically by the cache frontend
* To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
*
* @param array $settings array of setting for the engine
* @return bool True if the engine has been successfully initialized, false if not
*/
public function init($settings = array()) {
if (!class_exists('Memcache')) {
return false;
}
if (!isset($settings['prefix'])) {
$settings['prefix'] = Inflector::slug(APP_DIR) . '_';
}
$settings += array(
'engine' => 'Memcache',
'servers' => array('127.0.0.1'),
'compress' => false,
'persistent' => true
);
parent::init($settings);
if ($this->settings['compress']) {
$this->settings['compress'] = MEMCACHE_COMPRESSED;
}
if (is_string($this->settings['servers'])) {
$this->settings['servers'] = array($this->settings['servers']);
}
if (!isset($this->_Memcache)) {
$return = false;
$this->_Memcache = new Memcache();
foreach ($this->settings['servers'] as $server) {
list($host, $port) = $this->_parseServerString($server);
if ($this->_Memcache->addServer($host, $port, $this->settings['persistent'])) {
$return = true;
}
}
return $return;
}
return true;
}
/**
* Parses the server address into the host/port. Handles both IPv6 and IPv4
* addresses and Unix sockets
*
* @param string $server The server address string.
* @return array Array containing host, port
*/
protected function _parseServerString($server) {
if ($server[0] === 'u') {
return array($server, 0);
}
if (substr($server, 0, 1) === '[') {
$position = strpos($server, ']:');
if ($position !== false) {
$position++;
}
} else {
$position = strpos($server, ':');
}
$port = 11211;
$host = $server;
if ($position !== false) {
$host = substr($server, 0, $position);
$port = substr($server, $position + 1);
}
return array($host, $port);
}
/**
* Write data for key into cache. When using memcache as your cache engine
* remember that the Memcache pecl extension does not support cache expiry times greater
* than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
*
* @param string $key Identifier for the data
* @param mixed $value Data to be cached
* @param int $duration How long to cache the data, in seconds
* @return bool True if the data was successfully cached, false on failure
* @see http://php.net/manual/en/memcache.set.php
*/
public function write($key, $value, $duration) {
if ($duration > 30 * DAY) {
$duration = 0;
}
return $this->_Memcache->set($key, $value, $this->settings['compress'], $duration);
}
/**
* Read a key from the cache
*
* @param string $key Identifier for the data
* @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
*/
public function read($key) {
return $this->_Memcache->get($key);
}
/**
* Increments the value of an integer cached key
*
* @param string $key Identifier for the data
* @param int $offset How much to increment
* @return New incremented value, false otherwise
* @throws CacheException when you try to increment with compress = true
*/
public function increment($key, $offset = 1) {
if ($this->settings['compress']) {
throw new CacheException(
__d('cake_dev', 'Method %s not implemented for compressed cache in %s', 'increment()', __CLASS__)
);
}
return $this->_Memcache->increment($key, $offset);
}
/**
* Decrements the value of an integer cached key
*
* @param string $key Identifier for the data
* @param int $offset How much to subtract
* @return New decremented value, false otherwise
* @throws CacheException when you try to decrement with compress = true
*/
public function decrement($key, $offset = 1) {
if ($this->settings['compress']) {
throw new CacheException(
__d('cake_dev', 'Method %s not implemented for compressed cache in %s', 'decrement()', __CLASS__)
);
}
return $this->_Memcache->decrement($key, $offset);
}
/**
* Delete a key from the cache
*
* @param string $key Identifier for the data
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
*/
public function delete($key) {
return $this->_Memcache->delete($key);
}
/**
* Delete all keys from the cache
*
* @param bool $check If true no deletes will occur and instead CakePHP will rely
* on key TTL values.
* @return bool True if the cache was successfully cleared, false otherwise
*/
public function clear($check) {
if ($check) {
return true;
}
foreach ($this->_Memcache->getExtendedStats('slabs', 0) as $slabs) {
foreach (array_keys($slabs) as $slabId) {
if (!is_numeric($slabId)) {
continue;
}
foreach ($this->_Memcache->getExtendedStats('cachedump', $slabId, 0) as $stats) {
if (!is_array($stats)) {
continue;
}
foreach (array_keys($stats) as $key) {
if (strpos($key, $this->settings['prefix']) === 0) {
$this->_Memcache->delete($key);
}
}
}
}
}
return true;
}
/**
* Connects to a server in connection pool
*
* @param string $host host ip address or name
* @param int $port Server port
* @return bool True if memcache server was connected
*/
public function connect($host, $port = 11211) {
if ($this->_Memcache->getServerStatus($host, $port) === 0) {
if ($this->_Memcache->connect($host, $port)) {
return true;
}
return false;
}
return true;
}
/**
* Returns the `group value` for each of the configured groups
* If the group initial value was not found, then it initializes
* the group accordingly.
*
* @return array
*/
public function groups() {
if (empty($this->_compiledGroupNames)) {
foreach ($this->settings['groups'] as $group) {
$this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
}
}
$groups = $this->_Memcache->get($this->_compiledGroupNames);
if (count($groups) !== count($this->settings['groups'])) {
foreach ($this->_compiledGroupNames as $group) {
if (!isset($groups[$group])) {
$this->_Memcache->set($group, 1, false, 0);
$groups[$group] = 1;
}
}
ksort($groups);
}
$result = array();
$groups = array_values($groups);
foreach ($this->settings['groups'] as $i => $group) {
$result[] = $group . $groups[$i];
}
return $result;
}
/**
* Increments the group value to simulate deletion of all keys under a group
* old values will remain in storage until they expire.
*
* @param string $group The group to clear.
* @return bool success
*/
public function clearGroup($group) {
return (bool)$this->_Memcache->increment($this->settings['prefix'] . $group);
}
}
| kcraam/rasp-fligthtime | webapp/lib/Cake/Cache/Engine/MemcacheEngine.php | PHP | bsd-3-clause | 8,310 |
class Nasm < Formula
desc "Netwide Assembler (NASM) is an 80x86 assembler"
homepage "http://www.nasm.us/"
revision 1
stable do
url "http://www.nasm.us/pub/nasm/releasebuilds/2.11.08/nasm-2.11.08.tar.xz"
sha256 "c99467c7072211c550d147640d8a1a0aa4d636d4d8cf849f3bf4317d900a1f7f"
# http://repo.or.cz/nasm.git/commit/4920a0324348716d6ab5106e65508496241dc7a2
# http://bugzilla.nasm.us/show_bug.cgi?id=3392306#c5
patch do
url "https://raw.githubusercontent.com/Homebrew/patches/7a329c65e/nasm/nasm_outmac64.patch"
sha256 "54bfb2a8e0941e0108efedb4a3bcdc6ce8dff0d31d3abdf2256410c0f93f5ad7"
end
end
bottle do
cellar :any_skip_relocation
sha256 "4023e31702e37163be8c0089550b50ccb06c5de78788271f3b72c17f235d0449" => :el_capitan
sha256 "3a3f2ead668f671710c08988ecd28d4ee778202b20fff12a4f7ffc397eda080d" => :yosemite
sha256 "ccbea16ab6ea7f786112531697b04b0abd2709ca72f4378b7f54db83f0d7364e" => :mavericks
end
devel do
url "http://www.nasm.us/pub/nasm/releasebuilds/2.11.09rc1/nasm-2.11.09rc1.tar.xz"
sha256 "8b76b7f40701a5bdc8ef29fc352edb0714a8e921b2383072283057d2b426a890"
end
option :universal
def install
ENV.universal_binary if build.universal?
system "./configure", "--prefix=#{prefix}"
system "make", "install", "install_rdf"
end
test do
(testpath/"foo.s").write <<-EOS
mov eax, 0
mov ebx, 0
int 0x80
EOS
system "#{bin}/nasm", "foo.s"
code = File.open("foo", "rb") { |f| f.read.unpack("C*") }
expected = [0x66, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x66, 0xbb,
0x00, 0x00, 0x00, 0x00, 0xcd, 0x80]
assert_equal expected, code
end
end
| rokn/Count_Words_2015 | fetched_code/ruby/nasm.rb | Ruby | mit | 1,684 |
/*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "system.h"
#if defined (HAVE_WAYLAND)
#include <boost/scoped_ptr.hpp>
#include "Application.h"
#include "xbmc/windowing/WindowingFactory.h"
#include "WinEventsWayland.h"
#include "wayland/EventListener.h"
#include "wayland/InputFactory.h"
#include "wayland/EventLoop.h"
namespace xwe = xbmc::wayland::events;
namespace
{
class XBMCListener :
public xbmc::IEventListener
{
public:
virtual void OnEvent(XBMC_Event &event);
virtual void OnFocused();
virtual void OnUnfocused();
};
XBMCListener g_listener;
boost::scoped_ptr <xbmc::InputFactory> g_inputInstance;
boost::scoped_ptr <xwe::Loop> g_eventLoop;
}
void XBMCListener::OnEvent(XBMC_Event &e)
{
g_application.OnEvent(e);
}
void XBMCListener::OnFocused()
{
g_application.m_AppFocused = true;
g_Windowing.NotifyAppFocusChange(g_application.m_AppFocused);
}
void XBMCListener::OnUnfocused()
{
g_application.m_AppFocused = false;
g_Windowing.NotifyAppFocusChange(g_application.m_AppFocused);
}
CWinEventsWayland::CWinEventsWayland()
{
}
void CWinEventsWayland::RefreshDevices()
{
}
bool CWinEventsWayland::IsRemoteLowBattery()
{
return false;
}
/* This function reads the display connection and dispatches
* any events through the specified object listeners */
bool CWinEventsWayland::MessagePump()
{
if (!g_eventLoop.get())
return false;
g_eventLoop->Dispatch();
return true;
}
size_t CWinEventsWayland::GetQueueSize()
{
/* We can't query the size of the queue */
return 0;
}
void CWinEventsWayland::SetEventQueueStrategy(xwe::IEventQueueStrategy &strategy)
{
g_eventLoop.reset(new xwe::Loop(g_listener, strategy));
}
void CWinEventsWayland::DestroyEventQueueStrategy()
{
g_eventLoop.reset();
}
/* Once we know about a wayland seat, we can just create our manager
* object to encapsulate all of that state. When the seat goes away
* we just unset the manager object and it is all cleaned up at that
* point */
void CWinEventsWayland::SetWaylandSeat(IDllWaylandClient &clientLibrary,
IDllXKBCommon &xkbCommonLibrary,
struct wl_seat *s)
{
if (!g_eventLoop.get())
throw std::logic_error("Must have a wl_display set before setting "
"the wl_seat in CWinEventsWayland ");
g_inputInstance.reset(new xbmc::InputFactory(clientLibrary,
xkbCommonLibrary,
s,
*g_eventLoop,
*g_eventLoop));
}
void CWinEventsWayland::DestroyWaylandSeat()
{
g_inputInstance.reset();
}
/* When a surface becomes available, this function should be called
* to register it as the current one for processing input events on.
*
* It is a precondition violation to call this function before
* a seat has been registered */
void CWinEventsWayland::SetXBMCSurface(struct wl_surface *s)
{
if (!g_inputInstance.get())
throw std::logic_error("Must have a wl_seat set before setting "
"the wl_surface in CWinEventsWayland");
g_inputInstance->SetXBMCSurface(s);
}
#endif
| TRex22/xbmc | xbmc/windowing/WinEventsWayland.cpp | C++ | gpl-2.0 | 3,936 |
/*
* Copyright (C) 2007 Esmertec AG.
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ws.com.google.android.mms.pdu;
import ws.com.google.android.mms.InvalidHeaderValueException;
public class ReadRecInd extends GenericPdu {
/**
* Constructor, used when composing a M-ReadRec.ind pdu.
*
* @param from the from value
* @param messageId the message ID value
* @param mmsVersion current viersion of mms
* @param readStatus the read status value
* @param to the to value
* @throws InvalidHeaderValueException if parameters are invalid.
* NullPointerException if messageId or to is null.
*/
public ReadRecInd(EncodedStringValue from,
byte[] messageId,
int mmsVersion,
int readStatus,
EncodedStringValue[] to) throws InvalidHeaderValueException {
super();
setMessageType(PduHeaders.MESSAGE_TYPE_READ_REC_IND);
setFrom(from);
setMessageId(messageId);
setMmsVersion(mmsVersion);
setTo(to);
setReadStatus(readStatus);
}
/**
* Constructor with given headers.
*
* @param headers Headers for this PDU.
*/
ReadRecInd(PduHeaders headers) {
super(headers);
}
/**
* Get Date value.
*
* @return the value
*/
public long getDate() {
return mPduHeaders.getLongInteger(PduHeaders.DATE);
}
/**
* Set Date value.
*
* @param value the value
*/
public void setDate(long value) {
mPduHeaders.setLongInteger(value, PduHeaders.DATE);
}
/**
* Get Message-ID value.
*
* @return the value
*/
public byte[] getMessageId() {
return mPduHeaders.getTextString(PduHeaders.MESSAGE_ID);
}
/**
* Set Message-ID value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setMessageId(byte[] value) {
mPduHeaders.setTextString(value, PduHeaders.MESSAGE_ID);
}
/**
* Get To value.
*
* @return the value
*/
public EncodedStringValue[] getTo() {
return mPduHeaders.getEncodedStringValues(PduHeaders.TO);
}
/**
* Set To value.
*
* @param value the value
* @throws NullPointerException if the value is null.
*/
public void setTo(EncodedStringValue[] value) {
mPduHeaders.setEncodedStringValues(value, PduHeaders.TO);
}
/**
* Get X-MMS-Read-status value.
*
* @return the value
*/
public int getReadStatus() {
return mPduHeaders.getOctet(PduHeaders.READ_STATUS);
}
/**
* Set X-MMS-Read-status value.
*
* @param value the value
* @throws InvalidHeaderValueException if the value is invalid.
*/
public void setReadStatus(int value) throws InvalidHeaderValueException {
mPduHeaders.setOctet(value, PduHeaders.READ_STATUS);
}
/*
* Optional, not supported header fields:
*
* public byte[] getApplicId() {return null;}
* public void setApplicId(byte[] value) {}
*
* public byte[] getAuxApplicId() {return null;}
* public void getAuxApplicId(byte[] value) {}
*
* public byte[] getReplyApplicId() {return 0x00;}
* public void setReplyApplicId(byte[] value) {}
*/
}
| jodson/TextSecure | src/ws/com/google/android/mms/pdu/ReadRecInd.java | Java | gpl-3.0 | 4,014 |
#include <string.h>
#include <node.h>
#include "macros.h"
#include "database.h"
#include "statement.h"
using namespace node_sqlite3;
Persistent<FunctionTemplate> Database::constructor_template;
void Database::Init(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew("Database"));
NODE_SET_PROTOTYPE_METHOD(t, "close", Close);
NODE_SET_PROTOTYPE_METHOD(t, "exec", Exec);
NODE_SET_PROTOTYPE_METHOD(t, "wait", Wait);
NODE_SET_PROTOTYPE_METHOD(t, "loadExtension", LoadExtension);
NODE_SET_PROTOTYPE_METHOD(t, "serialize", Serialize);
NODE_SET_PROTOTYPE_METHOD(t, "parallelize", Parallelize);
NODE_SET_PROTOTYPE_METHOD(t, "configure", Configure);
NODE_SET_GETTER(t, "open", OpenGetter);
NanAssignPersistent(constructor_template, t);
target->Set(NanNew("Database"),
t->GetFunction());
}
void Database::Process() {
NanScope();
if (!open && locked && !queue.empty()) {
EXCEPTION(NanNew<String>("Database handle is closed"), SQLITE_MISUSE, exception);
Local<Value> argv[] = { exception };
bool called = false;
// Call all callbacks with the error object.
while (!queue.empty()) {
Call* call = queue.front();
Local<Function> cb = NanNew(call->baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(this), cb, 1, argv);
called = true;
}
queue.pop();
// We don't call the actual callback, so we have to make sure that
// the baton gets destroyed.
delete call->baton;
delete call;
}
// When we couldn't call a callback function, emit an error on the
// Database object.
if (!called) {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(this), 2, args);
}
return;
}
while (open && (!locked || pending == 0) && !queue.empty()) {
Call* call = queue.front();
if (call->exclusive && pending > 0) {
break;
}
queue.pop();
locked = call->exclusive;
call->callback(call->baton);
delete call;
if (locked) break;
}
}
void Database::Schedule(Work_Callback callback, Baton* baton, bool exclusive) {
NanScope();
if (!open && locked) {
EXCEPTION(NanNew<String>("Database is closed"), SQLITE_MISUSE, exception);
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(this), cb, 1, argv);
}
else {
Local<Value> argv[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(this), 2, argv);
}
return;
}
if (!open || ((locked || exclusive || serialize) && pending > 0)) {
queue.push(new Call(callback, baton, exclusive || serialize));
}
else {
locked = exclusive;
callback(baton);
}
}
NAN_METHOD(Database::New) {
NanScope();
if (!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to create new Database objects");
}
REQUIRE_ARGUMENT_STRING(0, filename);
int pos = 1;
int mode;
if (args.Length() >= pos && args[pos]->IsInt32()) {
mode = args[pos++]->Int32Value();
} else {
mode = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX;
}
Local<Function> callback;
if (args.Length() >= pos && args[pos]->IsFunction()) {
callback = Local<Function>::Cast(args[pos++]);
}
Database* db = new Database();
db->Wrap(args.This());
args.This()->Set(NanNew("filename"), args[0]->ToString(), ReadOnly);
args.This()->Set(NanNew("mode"), NanNew<Integer>(mode), ReadOnly);
// Start opening the database.
OpenBaton* baton = new OpenBaton(db, callback, *filename, mode);
Work_BeginOpen(baton);
NanReturnValue(args.This());
}
void Database::Work_BeginOpen(Baton* baton) {
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Open, (uv_after_work_cb)Work_AfterOpen);
assert(status == 0);
}
void Database::Work_Open(uv_work_t* req) {
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_open_v2(
baton->filename.c_str(),
&db->_handle,
baton->mode,
NULL
);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->_handle));
sqlite3_close(db->_handle);
db->_handle = NULL;
}
else {
// Set default database handle values.
sqlite3_busy_timeout(db->_handle, 1000);
}
}
void Database::Work_AfterOpen(uv_work_t* req) {
NanScope();
OpenBaton* baton = static_cast<OpenBaton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = true;
argv[0] = NanNew(NanNull());
}
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else if (!db->open) {
Local<Value> args[] = { NanNew("error"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
if (db->open) {
Local<Value> args[] = { NanNew("open") };
EMIT_EVENT(NanObjectWrapHandle(db), 1, args);
db->Process();
}
delete baton;
}
NAN_GETTER(Database::OpenGetter) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
NanReturnValue(NanNew<Boolean>(db->open));
}
NAN_METHOD(Database::Close) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(Work_BeginClose, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginClose(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
baton->db->RemoveCallbacks();
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Close, (uv_after_work_cb)Work_AfterClose);
assert(status == 0);
}
void Database::Work_Close(uv_work_t* req) {
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
baton->status = sqlite3_close(db->_handle);
if (baton->status != SQLITE_OK) {
baton->message = std::string(sqlite3_errmsg(db->_handle));
}
else {
db->_handle = NULL;
}
}
void Database::Work_AfterClose(uv_work_t* req) {
NanScope();
Baton* baton = static_cast<Baton*>(req->data);
Database* db = baton->db;
Local<Value> argv[1];
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
argv[0] = exception;
}
else {
db->open = false;
// Leave db->locked to indicate that this db object has reached
// the end of its life.
argv[0] = NanNew(NanNull());
}
Local<Function> cb = NanNew(baton->callback);
// Fire callbacks.
if (!cb.IsEmpty() && cb->IsFunction()) {
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else if (db->open) {
Local<Value> args[] = { NanNew("error"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
if (!db->open) {
Local<Value> args[] = { NanNew("close"), argv[0] };
EMIT_EVENT(NanObjectWrapHandle(db), 1, args);
db->Process();
}
delete baton;
}
NAN_METHOD(Database::Serialize) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = true;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Parallelize) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
bool before = db->serialize;
db->serialize = false;
if (!callback.IsEmpty() && callback->IsFunction()) {
TRY_CATCH_CALL(args.This(), callback, 0, NULL);
db->serialize = before;
}
db->Process();
NanReturnValue(args.This());
}
NAN_METHOD(Database::Configure) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENTS(2);
if (args[0]->Equals(NanNew("trace"))) {
Local<Function> handle;
Baton* baton = new Baton(db, handle);
db->Schedule(RegisterTraceCallback, baton);
}
else if (args[0]->Equals(NanNew("profile"))) {
Local<Function> handle;
Baton* baton = new Baton(db, handle);
db->Schedule(RegisterProfileCallback, baton);
}
else if (args[0]->Equals(NanNew("busyTimeout"))) {
if (!args[1]->IsInt32()) {
return NanThrowTypeError("Value must be an integer");
}
Local<Function> handle;
Baton* baton = new Baton(db, handle);
baton->status = args[1]->Int32Value();
db->Schedule(SetBusyTimeout, baton);
}
else {
return NanThrowError(Exception::Error(String::Concat(
args[0]->ToString(),
NanNew<String>(" is not a valid configuration option")
)));
}
db->Process();
NanReturnValue(args.This());
}
void Database::SetBusyTimeout(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
// Abuse the status field for passing the timeout.
sqlite3_busy_timeout(baton->db->_handle, baton->status);
delete baton;
}
void Database::RegisterTraceCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->debug_trace == NULL) {
// Add it.
db->debug_trace = new AsyncTrace(db, TraceCallback);
sqlite3_trace(db->_handle, TraceCallback, db);
}
else {
// Remove it.
sqlite3_trace(db->_handle, NULL, NULL);
db->debug_trace->finish();
db->debug_trace = NULL;
}
delete baton;
}
void Database::TraceCallback(void* db, const char* sql) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
static_cast<Database*>(db)->debug_trace->send(new std::string(sql));
}
void Database::TraceCallback(Database* db, std::string* sql) {
// Note: This function is called in the main V8 thread.
NanScope();
Local<Value> argv[] = {
NanNew("trace"),
NanNew<String>(sql->c_str())
};
EMIT_EVENT(NanObjectWrapHandle(db), 2, argv);
delete sql;
}
void Database::RegisterProfileCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->debug_profile == NULL) {
// Add it.
db->debug_profile = new AsyncProfile(db, ProfileCallback);
sqlite3_profile(db->_handle, ProfileCallback, db);
}
else {
// Remove it.
sqlite3_profile(db->_handle, NULL, NULL);
db->debug_profile->finish();
db->debug_profile = NULL;
}
delete baton;
}
void Database::ProfileCallback(void* db, const char* sql, sqlite3_uint64 nsecs) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
ProfileInfo* info = new ProfileInfo();
info->sql = std::string(sql);
info->nsecs = nsecs;
static_cast<Database*>(db)->debug_profile->send(info);
}
void Database::ProfileCallback(Database *db, ProfileInfo* info) {
NanScope();
Local<Value> argv[] = {
NanNew("profile"),
NanNew<String>(info->sql.c_str()),
NanNew<Integer>((double)info->nsecs / 1000000.0)
};
EMIT_EVENT(NanObjectWrapHandle(db), 3, argv);
delete info;
}
void Database::RegisterUpdateCallback(Baton* baton) {
assert(baton->db->open);
assert(baton->db->_handle);
Database* db = baton->db;
if (db->update_event == NULL) {
// Add it.
db->update_event = new AsyncUpdate(db, UpdateCallback);
sqlite3_update_hook(db->_handle, UpdateCallback, db);
}
else {
// Remove it.
sqlite3_update_hook(db->_handle, NULL, NULL);
db->update_event->finish();
db->update_event = NULL;
}
delete baton;
}
void Database::UpdateCallback(void* db, int type, const char* database,
const char* table, sqlite3_int64 rowid) {
// Note: This function is called in the thread pool.
// Note: Some queries, such as "EXPLAIN" queries, are not sent through this.
UpdateInfo* info = new UpdateInfo();
info->type = type;
info->database = std::string(database);
info->table = std::string(table);
info->rowid = rowid;
static_cast<Database*>(db)->update_event->send(info);
}
void Database::UpdateCallback(Database *db, UpdateInfo* info) {
NanScope();
Local<Value> argv[] = {
NanNew(sqlite_authorizer_string(info->type)),
NanNew<String>(info->database.c_str()),
NanNew<String>(info->table.c_str()),
NanNew<Integer>(info->rowid),
};
EMIT_EVENT(NanObjectWrapHandle(db), 4, argv);
delete info;
}
NAN_METHOD(Database::Exec) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, sql);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new ExecBaton(db, callback, *sql);
db->Schedule(Work_BeginExec, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginExec(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_Exec, (uv_after_work_cb)Work_AfterExec);
assert(status == 0);
}
void Database::Work_Exec(uv_work_t* req) {
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
char* message = NULL;
baton->status = sqlite3_exec(
baton->db->_handle,
baton->sql.c_str(),
NULL,
NULL,
&message
);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
}
void Database::Work_AfterExec(uv_work_t* req) {
NanScope();
ExecBaton* baton = static_cast<ExecBaton*>(req->data);
Database* db = baton->db;
Local<Function> cb = NanNew(baton->callback);
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
}
else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
db->Process();
delete baton;
}
NAN_METHOD(Database::Wait) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
OPTIONAL_ARGUMENT_FUNCTION(0, callback);
Baton* baton = new Baton(db, callback);
db->Schedule(Work_Wait, baton, true);
NanReturnValue(args.This());
}
void Database::Work_Wait(Baton* baton) {
NanScope();
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
Local<Function> cb = NanNew(baton->callback);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(baton->db), cb, 1, argv);
}
baton->db->Process();
delete baton;
}
NAN_METHOD(Database::LoadExtension) {
NanScope();
Database* db = ObjectWrap::Unwrap<Database>(args.This());
REQUIRE_ARGUMENT_STRING(0, filename);
OPTIONAL_ARGUMENT_FUNCTION(1, callback);
Baton* baton = new LoadExtensionBaton(db, callback, *filename);
db->Schedule(Work_BeginLoadExtension, baton, true);
NanReturnValue(args.This());
}
void Database::Work_BeginLoadExtension(Baton* baton) {
assert(baton->db->locked);
assert(baton->db->open);
assert(baton->db->_handle);
assert(baton->db->pending == 0);
int status = uv_queue_work(uv_default_loop(),
&baton->request, Work_LoadExtension, (uv_after_work_cb)Work_AfterLoadExtension);
assert(status == 0);
}
void Database::Work_LoadExtension(uv_work_t* req) {
LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data);
sqlite3_enable_load_extension(baton->db->_handle, 1);
char* message = NULL;
baton->status = sqlite3_load_extension(
baton->db->_handle,
baton->filename.c_str(),
0,
&message
);
sqlite3_enable_load_extension(baton->db->_handle, 0);
if (baton->status != SQLITE_OK && message != NULL) {
baton->message = std::string(message);
sqlite3_free(message);
}
}
void Database::Work_AfterLoadExtension(uv_work_t* req) {
NanScope();
LoadExtensionBaton* baton = static_cast<LoadExtensionBaton*>(req->data);
Database* db = baton->db;
Local<Function> cb = NanNew(baton->callback);
if (baton->status != SQLITE_OK) {
EXCEPTION(NanNew<String>(baton->message.c_str()), baton->status, exception);
if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { exception };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
else {
Local<Value> args[] = { NanNew("error"), exception };
EMIT_EVENT(NanObjectWrapHandle(db), 2, args);
}
}
else if (!cb.IsEmpty() && cb->IsFunction()) {
Local<Value> argv[] = { NanNew(NanNull()) };
TRY_CATCH_CALL(NanObjectWrapHandle(db), cb, 1, argv);
}
db->Process();
delete baton;
}
void Database::RemoveCallbacks() {
if (debug_trace) {
debug_trace->finish();
debug_trace = NULL;
}
if (debug_profile) {
debug_profile->finish();
debug_profile = NULL;
}
}
| diagonalfish/reddit-post-scheduler | web/node_modules/sqlite3/src/database.cc | C++ | mit | 18,996 |
package networks
import (
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/pagination"
)
// List returns a Pager that allows you to iterate over a collection of Network.
func List(client *gophercloud.ServiceClient) pagination.Pager {
return pagination.NewPager(client, listURL(client), func(r pagination.PageResult) pagination.Page {
return NetworkPage{pagination.SinglePageBase(r)}
})
}
// Get returns data about a previously created Network.
func Get(client *gophercloud.ServiceClient, id string) (r GetResult) {
_, r.Err = client.Get(getURL(client, id), &r.Body, nil)
return
}
| ashetty1/kedge | vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/networks/requests.go | GO | apache-2.0 | 615 |
/*
Highcharts JS v5.0.13 (2017-07-27)
(c) 2009-2017 Highsoft AS
License: www.highcharts.com/license
*/
(function(a){"object"===typeof module&&module.exports?module.exports=a:a(Highcharts)})(function(a){a.theme={colors:["#FDD089","#FF7F79","#A0446E","#251535"],colorAxis:{maxColor:"#60042E",minColor:"#FDD089"},plotOptions:{map:{nullColor:"#fefefc"}},navigator:{series:{color:"#FF7F79",lineColor:"#A0446E"}}};a.setOptions(a.theme)});
| ChrisCioffi/ChrisCioffi.github.io | portfolio/Highcharts-5.0.13/code/themes/sunset.js | JavaScript | mit | 438 |
/**
@file PhysicsFrame.cpp
@maintainer Morgan McGuire, http://graphics.cs.williams.edu
@created 2002-07-09
@edited 2006-01-25
*/
#include "G3D/platform.h"
#include "G3D/PhysicsFrame.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
namespace G3D {
PhysicsFrame::PhysicsFrame() {
translation = Vector3::zero();
rotation = Quat();
}
PhysicsFrame::PhysicsFrame(
const CoordinateFrame& coordinateFrame) {
translation = coordinateFrame.translation;
rotation = Quat(coordinateFrame.rotation);
}
PhysicsFrame PhysicsFrame::operator*(const PhysicsFrame& other) const {
PhysicsFrame result;
result.rotation = rotation * other.rotation;
result.translation = translation + rotation.toRotationMatrix() * other.translation;
return result;
}
CoordinateFrame PhysicsFrame::toCoordinateFrame() const {
CoordinateFrame f;
f.translation = translation;
f.rotation = rotation.toRotationMatrix();
return f;
}
PhysicsFrame PhysicsFrame::lerp(
const PhysicsFrame& other,
float alpha) const {
PhysicsFrame result;
result.translation = translation.lerp(other.translation, alpha);
result.rotation = rotation.slerp(other.rotation, alpha);
return result;
}
void PhysicsFrame::deserialize(class BinaryInput& b) {
translation.deserialize(b);
rotation.deserialize(b);
}
void PhysicsFrame::serialize(class BinaryOutput& b) const {
translation.serialize(b);
rotation.serialize(b);
}
}; // namespace
| AsherBond/MondocosmOS | mangos/dep/src/g3dlite/PhysicsFrame.cpp | C++ | agpl-3.0 | 1,542 |
/*
HISTORY
02-Aug-10 L-05-28 $$1 pdeshmuk Created.
*/
function deleteItemsInSimpRep ()
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
/*--------------------------------------------------------------------*\
Get the current assembly
\*--------------------------------------------------------------------*/
var session = pfcGetProESession ();
var assembly = session.CurrentModel;
if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly");
/*--------------------------------------------------------------------*\
Get the current active simprep.
\*--------------------------------------------------------------------*/
var simp_rep = assembly.GetActiveSimpRep();
/*--------------------------------------------------------------------*\
Get the current number of items
\*--------------------------------------------------------------------*/
var simp_rep_instructions = simp_rep.GetInstructions();
var number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
/*--------------------------------------------------------------------*\
Deleting items
\*--------------------------------------------------------------------*/
var simp_rep_instructions_item = simp_rep_instructions.Items.Item(number_items-1);
simp_rep_instructions_item.Action = null;
simp_rep.SetInstructions(simp_rep_instructions);
number_items = simp_rep.GetInstructions().Items.Count;
document.getElementById("numItems").value = number_items;
return;
}
function addItemsInSimpRep ()
{
if (!pfcIsWindows())
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
/*--------------------------------------------------------------------*\
Get the current assembly
\*--------------------------------------------------------------------*/
var session = pfcGetProESession ();
var assembly = session.CurrentModel;
if (assembly.Type != pfcCreate ("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly");
/*--------------------------------------------------------------------*\
Get the current active simprep.
\*--------------------------------------------------------------------*/
var simp_rep = assembly.GetActiveSimpRep();
/*--------------------------------------------------------------------*\
Get the current number of items
\*--------------------------------------------------------------------*/
var simp_rep_instructions = simp_rep.GetInstructions();
var number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
/*--------------------------------------------------------------------*\
Add an item
\*--------------------------------------------------------------------*/
var item_path = pfcCreate ("intseq");
/*--------------------------------------------------------------------*\
Prompt for selection.
\*--------------------------------------------------------------------*/
selOptions = pfcCreate ("pfcSelectionOptions").Create ("feature");
selOptions.MaxNumSels = parseInt (1);
var selections = void null;
try {
selections = session.Select (selOptions, void null);
}
catch (err) {
/*--------------------------------------------------------------------*\
Handle the situation where the user didn't make selections, but picked
elsewhere instead.
\*--------------------------------------------------------------------*/
if (pfcGetExceptionType (err) == "pfcXToolkitUserAbort" ||
pfcGetExceptionType (err) == "pfcXToolkitPickAbove")
return (void null);
else
throw err;
}
if (selections.Count == 0)
return (void null);
var selection = selections.Item(0);
var componentpath = selection.Path;
var intseqIds = componentpath.ComponentIds;
item_path.Append(intseqIds.Item(0));
simp_rep_comp_item_path = pfcCreate("pfcSimpRepCompItemPath").Create(item_path);
simp_rep_item = pfcCreate("pfcSimpRepItem").Create(simp_rep_comp_item_path);
simp_rep_action = pfcCreate("pfcSimpRepExclude").Create();
simp_rep_item.Action = simp_rep_action;
simp_rep_instructions.Items.Append(simp_rep_item);
simp_rep.SetInstructions(simp_rep_instructions);
simp_rep_instructions = simp_rep.GetInstructions();
number_items = simp_rep_instructions.Items.Count;
document.getElementById("numItems").value = number_items;
return;
}
| 2014c2g12/c2g12 | wsgi/wsgi/static/weblink/examples/jscript/pfcSimpRepExamples.js | JavaScript | gpl-2.0 | 4,660 |
/**
* A date picker component which shows a Date Picker on the screen. This class extends from {@link Ext.picker.Picker}
* and {@link Ext.Sheet} so it is a popup.
*
* This component has no required configurations.
*
* ## Examples
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date');
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You may want to adjust the {@link #yearFrom} and {@link #yearTo} properties:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* yearFrom: 2000,
* yearTo : 2015
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* You can set the value of the {@link Ext.picker.Date} to the current date using `new Date()`:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* value: new Date()
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*
* And you can hide the titles from each of the slots by using the {@link #useTitles} configuration:
*
* @example miniphone preview
* var datePicker = Ext.create('Ext.picker.Date', {
* useTitles: false
* });
* Ext.Viewport.add(datePicker);
* datePicker.show();
*/
Ext.define('Ext.picker.Date', {
extend: 'Ext.picker.Picker',
xtype: 'datepicker',
alternateClassName: 'Ext.DatePicker',
requires: ['Ext.DateExtras', 'Ext.util.InputBlocker'],
/**
* @event change
* Fired when the value of this picker has changed and the done button is pressed.
* @param {Ext.picker.Date} this This Picker
* @param {Date} value The date value
*/
config: {
/**
* @cfg {Number} yearFrom
* The start year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearFrom: 1980,
/**
* @cfg {Number} [yearTo=new Date().getFullYear()]
* The last year for the date picker. If {@link #yearFrom} is greater than
* {@link #yearTo} then the order of years will be reversed.
* @accessor
*/
yearTo: new Date().getFullYear(),
/**
* @cfg {String} monthText
* The label to show for the month column.
* @accessor
*/
monthText: 'Month',
/**
* @cfg {String} dayText
* The label to show for the day column.
* @accessor
*/
dayText: 'Day',
/**
* @cfg {String} yearText
* The label to show for the year column.
* @accessor
*/
yearText: 'Year',
/**
* @cfg {Array} slotOrder
* An array of strings that specifies the order of the slots.
* @accessor
*/
slotOrder: ['month', 'day', 'year'],
/**
* @cfg {Object/Date} value
* Default value for the field and the internal {@link Ext.picker.Date} component. Accepts an object of 'year',
* 'month' and 'day' values, all of which should be numbers, or a {@link Date}.
*
* Examples:
*
* - `{year: 1989, day: 1, month: 5}` = 1st May 1989
* - `new Date()` = current date
* @accessor
*/
/**
* @cfg {Array} slots
* @hide
* @accessor
*/
/**
* @cfg {String/Mixed} doneButton
* Can be either:
*
* - A {String} text to be used on the Done button.
* - An {Object} as config for {@link Ext.Button}.
* - `false` or `null` to hide it.
* @accessor
*/
doneButton: true
},
platformConfig: [{
theme: ['Windows'],
doneButton: {
iconCls: 'check2',
ui: 'round',
text: ''
}
}],
initialize: function() {
this.callParent();
this.on({
scope: this,
delegate: '> slot',
slotpick: this.onSlotPick
});
this.on({
scope: this,
show: this.onSlotPick
});
},
setValue: function(value, animated) {
if (Ext.isDate(value)) {
value = {
day : value.getDate(),
month: value.getMonth() + 1,
year : value.getFullYear()
};
}
this.callParent([value, animated]);
this.onSlotPick();
},
getValue: function(useDom) {
var values = {},
items = this.getItems().items,
ln = items.length,
daysInMonth, day, month, year, item, i;
for (i = 0; i < ln; i++) {
item = items[i];
if (item instanceof Ext.picker.Slot) {
values[item.getName()] = item.getValue(useDom);
}
}
//if all the slots return null, we should not return a date
if (values.year === null && values.month === null && values.day === null) {
return null;
}
year = Ext.isNumber(values.year) ? values.year : 1;
month = Ext.isNumber(values.month) ? values.month : 1;
day = Ext.isNumber(values.day) ? values.day : 1;
if (month && year && month && day) {
daysInMonth = this.getDaysInMonth(month, year);
}
day = (daysInMonth) ? Math.min(day, daysInMonth): day;
return new Date(year, month - 1, day);
},
/**
* Updates the yearFrom configuration
*/
updateYearFrom: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the yearTo configuration
*/
updateYearTo: function() {
if (this.initialized) {
this.createSlots();
}
},
/**
* Updates the monthText configuration
*/
updateMonthText: function(newMonthText, oldMonthText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldMonthText) || (item.title.html == oldMonthText)) {
item.setTitle(newMonthText);
}
}
}
},
/**
* Updates the {@link #dayText} configuration.
*/
updateDayText: function(newDayText, oldDayText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if ((typeof item.title == "string" && item.title == oldDayText) || (item.title.html == oldDayText)) {
item.setTitle(newDayText);
}
}
}
},
/**
* Updates the yearText configuration
*/
updateYearText: function(yearText) {
var innerItems = this.getInnerItems,
ln = innerItems.length,
item, i;
//loop through each of the current items and set the title on the correct slice
if (this.initialized) {
for (i = 0; i < ln; i++) {
item = innerItems[i];
if (item.title == this.yearText) {
item.setTitle(yearText);
}
}
}
},
// @private
constructor: function() {
this.callParent(arguments);
this.createSlots();
},
/**
* Generates all slots for all years specified by this component, and then sets them on the component
* @private
*/
createSlots: function() {
var me = this,
slotOrder = me.getSlotOrder(),
yearsFrom = me.getYearFrom(),
yearsTo = me.getYearTo(),
years = [],
days = [],
months = [],
reverse = yearsFrom > yearsTo,
ln, i, daysInMonth;
while (yearsFrom) {
years.push({
text : yearsFrom,
value : yearsFrom
});
if (yearsFrom === yearsTo) {
break;
}
if (reverse) {
yearsFrom--;
} else {
yearsFrom++;
}
}
daysInMonth = me.getDaysInMonth(1, new Date().getFullYear());
for (i = 0; i < daysInMonth; i++) {
days.push({
text : i + 1,
value : i + 1
});
}
for (i = 0, ln = Ext.Date.monthNames.length; i < ln; i++) {
months.push({
text : Ext.Date.monthNames[i],
value : i + 1
});
}
var slots = [];
slotOrder.forEach(function (item) {
slots.push(me.createSlot(item, days, months, years));
});
me.setSlots(slots);
},
/**
* Returns a slot config for a specified date.
* @private
*/
createSlot: function(name, days, months, years) {
switch (name) {
case 'year':
return {
name: 'year',
align: 'center',
data: years,
title: this.getYearText(),
flex: 3
};
case 'month':
return {
name: name,
align: 'right',
data: months,
title: this.getMonthText(),
flex: 4
};
case 'day':
return {
name: 'day',
align: 'center',
data: days,
title: this.getDayText(),
flex: 2
};
}
},
onSlotPick: function() {
var value = this.getValue(true),
slot = this.getDaySlot(),
year = value.getFullYear(),
month = value.getMonth(),
days = [],
daysInMonth, i;
if (!value || !Ext.isDate(value) || !slot) {
return;
}
this.callParent(arguments);
//get the new days of the month for this new date
daysInMonth = this.getDaysInMonth(month + 1, year);
for (i = 0; i < daysInMonth; i++) {
days.push({
text: i + 1,
value: i + 1
});
}
// We don't need to update the slot days unless it has changed
if (slot.getStore().getCount() == days.length) {
return;
}
slot.getStore().setData(days);
// Now we have the correct amount of days for the day slot, lets update it
var store = slot.getStore(),
viewItems = slot.getViewItems(),
valueField = slot.getValueField(),
index, item;
index = store.find(valueField, value.getDate());
if (index == -1) {
return;
}
item = Ext.get(viewItems[index]);
slot.selectedIndex = index;
slot.scrollToItem(item);
slot.setValue(slot.getValue(true));
},
getDaySlot: function() {
var innerItems = this.getInnerItems(),
ln = innerItems.length,
i, slot;
if (this.daySlot) {
return this.daySlot;
}
for (i = 0; i < ln; i++) {
slot = innerItems[i];
if (slot.isSlot && slot.getName() == "day") {
this.daySlot = slot;
return slot;
}
}
return null;
},
// @private
getDaysInMonth: function(month, year) {
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return month == 2 && this.isLeapYear(year) ? 29 : daysInMonth[month-1];
},
// @private
isLeapYear: function(year) {
return !!((year & 3) === 0 && (year % 100 || (year % 400 === 0 && year)));
},
onDoneButtonTap: function() {
var oldValue = this._value,
newValue = this.getValue(true),
testValue = newValue;
if (Ext.isDate(newValue)) {
testValue = newValue.toDateString();
}
if (Ext.isDate(oldValue)) {
oldValue = oldValue.toDateString();
}
if (testValue != oldValue) {
this.fireEvent('change', this, newValue);
}
this.hide();
Ext.util.InputBlocker.unblockInputs();
}
}); | appcodechile/Rockola | webapp/touch/src/picker/Date.js | JavaScript | mit | 12,879 |
function acosh (arg) {
// http://kevin.vanzonneveld.net
// + original by: Onno Marsman
// * example 1: acosh(8723321.4);
// * returns 1: 16.674657798418625
return Math.log(arg + Math.sqrt(arg * arg - 1));
}
| montanaflynn/phpjs | functions/math/acosh.js | JavaScript | mit | 227 |
// @target: ES3
// @sourcemap: true
interface I {}
var x = 0; | progre/TypeScript | tests/cases/compiler/sourceMap-InterfacePrecedingVariableDeclaration1.ts | TypeScript | apache-2.0 | 66 |
/*
YUI 3.16.0 (build 76f0e08)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('router', function (Y, NAME) {
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
@module app
@submodule router
@since 3.4.0
**/
var HistoryHash = Y.HistoryHash,
QS = Y.QueryString,
YArray = Y.Array,
YLang = Y.Lang,
YObject = Y.Object,
win = Y.config.win,
// Holds all the active router instances. This supports the static
// `dispatch()` method which causes all routers to dispatch.
instances = [],
// We have to queue up pushState calls to avoid race conditions, since the
// popstate event doesn't actually provide any info on what URL it's
// associated with.
saveQueue = [],
/**
Fired when the router is ready to begin dispatching to route handlers.
You shouldn't need to wait for this event unless you plan to implement some
kind of custom dispatching logic. It's used internally in order to avoid
dispatching to an initial route if a browser history change occurs first.
@event ready
@param {Boolean} dispatched `true` if routes have already been dispatched
(most likely due to a history change).
@fireOnce
**/
EVT_READY = 'ready';
/**
Provides URL-based routing using HTML5 `pushState()` or the location hash.
This makes it easy to wire up route handlers for different application states
while providing full back/forward navigation support and bookmarkable, shareable
URLs.
@class Router
@param {Object} [config] Config properties.
@param {Boolean} [config.html5] Overrides the default capability detection
and forces this router to use (`true`) or not use (`false`) HTML5
history.
@param {String} [config.root=''] Root path from which all routes should be
evaluated.
@param {Array} [config.routes=[]] Array of route definition objects.
@constructor
@extends Base
@since 3.4.0
**/
function Router() {
Router.superclass.constructor.apply(this, arguments);
}
Y.Router = Y.extend(Router, Y.Base, {
// -- Protected Properties -------------------------------------------------
/**
Whether or not `_dispatch()` has been called since this router was
instantiated.
@property _dispatched
@type Boolean
@default undefined
@protected
**/
/**
Whether or not we're currently in the process of dispatching to routes.
@property _dispatching
@type Boolean
@default undefined
@protected
**/
/**
History event handle for the `history:change` or `hashchange` event
subscription.
@property _historyEvents
@type EventHandle
@protected
**/
/**
Cached copy of the `html5` attribute for internal use.
@property _html5
@type Boolean
@protected
**/
/**
Map which holds the registered param handlers in the form:
`name` -> RegExp | Function.
@property _params
@type Object
@protected
@since 3.12.0
**/
/**
Whether or not the `ready` event has fired yet.
@property _ready
@type Boolean
@default undefined
@protected
**/
/**
Regex used to break up a URL string around the URL's path.
Subpattern captures:
1. Origin, everything before the URL's path-part.
2. The URL's path-part.
3. The URL's query.
4. The URL's hash fragment.
@property _regexURL
@type RegExp
@protected
@since 3.5.0
**/
_regexURL: /^((?:[^\/#?:]+:\/\/|\/\/)[^\/]*)?([^?#]*)(\?[^#]*)?(#.*)?$/,
/**
Regex used to match parameter placeholders in route paths.
Subpattern captures:
1. Parameter prefix character. Either a `:` for subpath parameters that
should only match a single level of a path, or `*` for splat parameters
that should match any number of path levels.
2. Parameter name, if specified, otherwise it is a wildcard match.
@property _regexPathParam
@type RegExp
@protected
**/
_regexPathParam: /([:*])([\w\-]+)?/g,
/**
Regex that matches and captures the query portion of a URL, minus the
preceding `?` character, and discarding the hash portion of the URL if any.
@property _regexUrlQuery
@type RegExp
@protected
**/
_regexUrlQuery: /\?([^#]*).*$/,
/**
Regex that matches everything before the path portion of a URL (the origin).
This will be used to strip this part of the URL from a string when we
only want the path.
@property _regexUrlOrigin
@type RegExp
@protected
**/
_regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
/**
Collection of registered routes.
@property _routes
@type Array
@protected
**/
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
var self = this;
self._html5 = self.get('html5');
self._params = {};
self._routes = [];
self._url = self._getURL();
// Necessary because setters don't run on init.
self._setRoutes(config && config.routes ? config.routes :
self.get('routes'));
// Set up a history instance or hashchange listener.
if (self._html5) {
self._history = new Y.HistoryHTML5({force: true});
self._historyEvents =
Y.after('history:change', self._afterHistoryChange, self);
} else {
self._historyEvents =
Y.on('hashchange', self._afterHistoryChange, win, self);
}
// Fire a `ready` event once we're ready to route. We wait first for all
// subclass initializers to finish, then for window.onload, and then an
// additional 20ms to allow the browser to fire a useless initial
// `popstate` event if it wants to (and Chrome always wants to).
self.publish(EVT_READY, {
defaultFn : self._defReadyFn,
fireOnce : true,
preventable: false
});
self.once('initializedChange', function () {
Y.once('load', function () {
setTimeout(function () {
self.fire(EVT_READY, {dispatched: !!self._dispatched});
}, 20);
});
});
// Store this router in the collection of all active router instances.
instances.push(this);
},
destructor: function () {
var instanceIndex = YArray.indexOf(instances, this);
// Remove this router from the collection of active router instances.
if (instanceIndex > -1) {
instances.splice(instanceIndex, 1);
}
if (this._historyEvents) {
this._historyEvents.detach();
}
},
// -- Public Methods -------------------------------------------------------
/**
Dispatches to the first route handler that matches the current URL, if any.
If `dispatch()` is called before the `ready` event has fired, it will
automatically wait for the `ready` event before dispatching. Otherwise it
will dispatch immediately.
@method dispatch
@chainable
**/
dispatch: function () {
this.once(EVT_READY, function () {
var req, res;
this._ready = true;
if (!this.upgrade()) {
req = this._getRequest('dispatch');
res = this._getResponse(req);
this._dispatch(req, res);
}
});
return this;
},
/**
Gets the current route path.
@method getPath
@return {String} Current route path.
**/
getPath: function () {
return this._getPath();
},
/**
Returns `true` if this router has at least one route that matches the
specified URL, `false` otherwise. This also checks that any named `param`
handlers also accept app param values in the `url`.
This method enforces the same-origin security constraint on the specified
`url`; any URL which is not from the same origin as the current URL will
always return `false`.
@method hasRoute
@param {String} url URL to match.
@return {Boolean} `true` if there's at least one matching route, `false`
otherwise.
**/
hasRoute: function (url) {
var path, routePath, routes;
if (!this._hasSameOrigin(url)) {
return false;
}
if (!this._html5) {
url = this._upgradeURL(url);
}
// Get just the path portion of the specified `url`. The `match()`
// method does some special checking that the `path` is within the root.
path = this.removeQuery(url.replace(this._regexUrlOrigin, ''));
routes = this.match(path);
if (!routes.length) {
return false;
}
routePath = this.removeRoot(path);
// Check that there's at least one route whose param handlers also
// accept all the param values.
return !!YArray.filter(routes, function (route) {
// Get the param values for the route and path to see whether the
// param handlers accept or reject the param values. Include any
// route whose named param handlers accept *all* param values. This
// will return `false` if a param handler rejects a param value.
return this._getParamValues(route, routePath);
}, this).length;
},
/**
Returns an array of route objects that match the specified URL path.
If this router has a `root`, then the specified `path` _must_ be
semantically within the `root` path to match any routes.
This method is called internally to determine which routes match the current
path whenever the URL changes. You may override it if you want to customize
the route matching logic, although this usually shouldn't be necessary.
Each returned route object has the following properties:
* `callback`: A function or a string representing the name of a function
this router that should be executed when the route is triggered.
* `keys`: An array of strings representing the named parameters defined in
the route's path specification, if any.
* `path`: The route's path specification, which may be either a string or
a regex.
* `regex`: A regular expression version of the route's path specification.
This regex is used to determine whether the route matches a given path.
@example
router.route('/foo', function () {});
router.match('/foo');
// => [{callback: ..., keys: [], path: '/foo', regex: ...}]
@method match
@param {String} path URL path to match. This should be an absolute path that
starts with a slash: "/".
@return {Object[]} Array of route objects that match the specified path.
**/
match: function (path) {
var root = this.get('root');
if (root) {
// The `path` must be semantically within this router's `root` path
// or mount point, if it's not then no routes should be considered a
// match.
if (!this._pathHasRoot(root, path)) {
return [];
}
// Remove this router's `root` from the `path` before checking the
// routes for any matches.
path = this.removeRoot(path);
}
return YArray.filter(this._routes, function (route) {
return path.search(route.regex) > -1;
});
},
/**
Adds a handler for a route param specified by _name_.
Param handlers can be registered via this method and are used to
validate/format values of named params in routes before dispatching to the
route's handler functions. Using param handlers allows routes to defined
using string paths which allows for `req.params` to use named params, but
still applying extra validation or formatting to the param values parsed
from the URL.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped. All
other return values will be used in place of the original param value parsed
from the URL.
@example
router.param('postId', function (value) {
return parseInt(value, 10);
});
router.param('username', /^\w+$/);
router.route('/posts/:postId', function (req) {
});
router.route('/users/:username', function (req) {
// `req.params.username` is an array because the result of calling
// `exec()` on the regex is assigned as the param's value.
});
router.route('*', function () {
});
// URLs which match routes:
router.save('/posts/1'); // => "Post: 1"
router.save('/users/ericf'); // => "User: ericf"
// URLs which do not match routes because params fail validation:
router.save('/posts/a'); // => "Catch-all no routes matched!"
router.save('/users/ericf,rgrove'); // => "Catch-all no routes matched!"
@method param
@param {String} name Name of the param used in route paths.
@param {Function|RegExp} handler Function to invoke or regular expression to
`exec()` during route dispatching whose return value is used as the new
param value. Values of `false`, `null`, `undefined`, or `NaN` will cause
the current route to not match and be skipped. When a function is
specified, it will be invoked in the context of this instance with the
following parameters:
@param {String} handler.value The current param value parsed from the URL.
@param {String} handler.name The name of the param.
@chainable
@since 3.12.0
**/
param: function (name, handler) {
this._params[name] = handler;
return this;
},
/**
Removes the `root` URL from the front of _url_ (if it's there) and returns
the result. The returned path will always have a leading `/`.
@method removeRoot
@param {String} url URL.
@return {String} Rootless path.
**/
removeRoot: function (url) {
var root = this.get('root'),
path;
// Strip out the non-path part of the URL, if any (e.g.
// "http://foo.com"), so that we're left with just the path.
url = url.replace(this._regexUrlOrigin, '');
// Return the host-less URL if there's no `root` path to further remove.
if (!root) {
return url;
}
path = this.removeQuery(url);
// Remove the `root` from the `url` if it's the same or its path is
// semantically within the root path.
if (path === root || this._pathHasRoot(root, path)) {
url = url.substring(root.length);
}
return url.charAt(0) === '/' ? url : '/' + url;
},
/**
Removes a query string from the end of the _url_ (if one exists) and returns
the result.
@method removeQuery
@param {String} url URL.
@return {String} Queryless path.
**/
removeQuery: function (url) {
return url.replace(/\?.*$/, '');
},
/**
Replaces the current browser history entry with a new one, and dispatches to
the first matching route handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.replace('/path/');
// New URL: http://example.com/path/
router.replace('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.replace('/');
// New URL: http://example.com/
@method replace
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see save()
**/
replace: function (url) {
return this._queue(url, true);
},
/**
Adds a route handler for the specified `route`.
The `route` parameter may be a string or regular expression to represent a
URL path, or a route object. If it's a string (which is most common), it may
contain named parameters: `:param` will match any single part of a URL path
(not including `/` characters), and `*param` will match any number of parts
of a URL path (including `/` characters). These named parameters will be
made available as keys on the `req.params` object that's passed to route
handlers.
If the `route` parameter is a regex, all pattern matches will be made
available as numbered keys on `req.params`, starting with `0` for the full
match, then `1` for the first subpattern match, and so on.
Alternatively, an object can be provided to represent the route and it may
contain a `path` property which is a string or regular expression which
causes the route to be process as described above. If the route object
already contains a `regex` or `regexp` property, the route will be
considered fully-processed and will be associated with any `callacks`
specified on the object and those specified as parameters to this method.
**Note:** Any additional data contained on the route object will be
preserved.
Here's a set of sample routes along with URL paths that they match:
* Route: `/photos/:tag/:page`
* URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
* URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
* Route: `/file/*path`
* URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
* URL: `/file/foo`, params: `{path: 'foo'}`
**Middleware**: Routes also support an arbitrary number of callback
functions. This allows you to easily reuse parts of your route-handling code
with different route. This method is liberal in how it processes the
specified `callbacks`, you can specify them as separate arguments, or as
arrays, or both.
If multiple route match a given URL, they will be executed in the order they
were added. The first route that was added will be the first to be executed.
**Passing Control**: Invoking the `next()` function within a route callback
will pass control to the next callback function (if any) or route handler
(if any). If a value is passed to `next()`, it's assumed to be an error,
therefore stopping the dispatch chain, unless that value is: `"route"`,
which is special case and dispatching will skip to the next route handler.
This allows middleware to skip any remaining middleware for a particular
route.
@example
router.route('/photos/:tag/:page', function (req, res, next) {
});
// Using middleware.
router.findUser = function (req, res, next) {
req.user = this.get('users').findById(req.params.user);
next();
};
router.route('/users/:user', 'findUser', function (req, res, next) {
// The `findUser` middleware puts the `user` object on the `req`.
});
@method route
@param {String|RegExp|Object} route Route to match. May be a string or a
regular expression, or a route object.
@param {Array|Function|String} callbacks* Callback functions to call
whenever this route is triggered. These can be specified as separate
arguments, or in arrays, or both. If a callback is specified as a
string, the named function will be called on this router instance.
@param {Object} callbacks.req Request object containing information about
the request. It contains the following properties.
@param {Array|Object} callbacks.req.params Captured parameters matched
by the route path specification. If a string path was used and
contained named parameters, then this will be a key/value hash mapping
parameter names to their matched values. If a regex path was used,
this will be an array of subpattern matches starting at index 0 for
the full match, then 1 for the first subpattern match, and so on.
@param {String} callbacks.req.path The current URL path.
@param {Number} callbacks.req.pendingCallbacks Number of remaining
callbacks the route handler has after this one in the dispatch chain.
@param {Number} callbacks.req.pendingRoutes Number of matching routes
after this one in the dispatch chain.
@param {Object} callbacks.req.query Query hash representing the URL
query string, if any. Parameter names are keys, and are mapped to
parameter values.
@param {Object} callbacks.req.route Reference to the current route
object whose callbacks are being dispatched.
@param {Object} callbacks.req.router Reference to this router instance.
@param {String} callbacks.req.src What initiated the dispatch. In an
HTML5 browser, when the back/forward buttons are used, this property
will have a value of "popstate". When the `dispath()` method is
called, the `src` will be `"dispatch"`.
@param {String} callbacks.req.url The full URL.
@param {Object} callbacks.res Response object containing methods and
information that relate to responding to a request. It contains the
following properties.
@param {Object} callbacks.res.req Reference to the request object.
@param {Function} callbacks.next Function to pass control to the next
callback or the next matching route if no more callbacks (middleware)
exist for the current route handler. If you don't call this function,
then no further callbacks or route handlers will be executed, even if
there are more that match. If you do call this function, then the next
callback (if any) or matching route handler (if any) will be called.
All of these functions will receive the same `req` and `res` objects
that were passed to this route (so you can use these objects to pass
data along to subsequent callbacks and routes).
@param {String} [callbacks.next.err] Optional error which will stop the
dispatch chaining for this `req`, unless the value is `"route"`, which
is special cased to jump skip past any callbacks for the current route
and pass control the next route handler.
@chainable
**/
route: function (route, callbacks) {
// Grab callback functions from var-args.
callbacks = YArray(arguments, 1, true);
var keys, regex;
// Supports both the `route(path, callbacks)` and `route(config)` call
// signatures, allowing for fully-processed route configs to be passed.
if (typeof route === 'string' || YLang.isRegExp(route)) {
// Flatten `callbacks` into a single dimension array.
callbacks = YArray.flatten(callbacks);
keys = [];
regex = this._getRegex(route, keys);
route = {
callbacks: callbacks,
keys : keys,
path : route,
regex : regex
};
} else {
// Look for any configured `route.callbacks` and fallback to
// `route.callback` for back-compat, append var-arg `callbacks`,
// then flatten the entire collection to a single dimension array.
callbacks = YArray.flatten(
[route.callbacks || route.callback || []].concat(callbacks)
);
// Check for previously generated regex, also fallback to `regexp`
// for greater interop.
keys = route.keys;
regex = route.regex || route.regexp;
// Generates the route's regex if it doesn't already have one.
if (!regex) {
keys = [];
regex = this._getRegex(route.path, keys);
}
// Merge specified `route` config object with processed data.
route = Y.merge(route, {
callbacks: callbacks,
keys : keys,
path : route.path || regex,
regex : regex
});
}
this._routes.push(route);
return this;
},
/**
Saves a new browser history entry and dispatches to the first matching route
handler, if any.
Behind the scenes, this method uses HTML5 `pushState()` in browsers that
support it (or the location hash in older browsers and IE) to change the
URL and create a history entry.
The specified URL must share the same origin (i.e., protocol, host, and
port) as the current page, or an error will occur.
@example
// Starting URL: http://example.com/
router.save('/path/');
// New URL: http://example.com/path/
router.save('/path?foo=bar');
// New URL: http://example.com/path?foo=bar
router.save('/');
// New URL: http://example.com/
@method save
@param {String} [url] URL to set. This URL needs to be of the same origin as
the current URL. This can be a URL relative to the router's `root`
attribute. If no URL is specified, the page's current URL will be used.
@chainable
@see replace()
**/
save: function (url) {
return this._queue(url);
},
/**
Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
browsers, this method is a noop.
@method upgrade
@return {Boolean} `true` if the URL was upgraded, `false` otherwise.
**/
upgrade: function () {
if (!this._html5) {
return false;
}
// Get the resolve hash path.
var hashPath = this._getHashPath();
if (hashPath) {
// This is an HTML5 browser and we have a hash-based path in the
// URL, so we need to upgrade the URL to a non-hash URL. This
// will trigger a `history:change` event, which will in turn
// trigger a dispatch.
this.once(EVT_READY, function () {
this.replace(hashPath);
});
return true;
}
return false;
},
// -- Protected Methods ----------------------------------------------------
/**
Wrapper around `decodeURIComponent` that also converts `+` chars into
spaces.
@method _decode
@param {String} string String to decode.
@return {String} Decoded string.
@protected
**/
_decode: function (string) {
return decodeURIComponent(string.replace(/\+/g, ' '));
},
/**
Shifts the topmost `_save()` call off the queue and executes it. Does
nothing if the queue is empty.
@method _dequeue
@chainable
@see _queue
@protected
**/
_dequeue: function () {
var self = this,
fn;
// If window.onload hasn't yet fired, wait until it has before
// dequeueing. This will ensure that we don't call pushState() before an
// initial popstate event has fired.
if (!YUI.Env.windowLoaded) {
Y.once('load', function () {
self._dequeue();
});
return this;
}
fn = saveQueue.shift();
return fn ? fn() : this;
},
/**
Dispatches to the first route handler that matches the specified _path_.
If called before the `ready` event has fired, the dispatch will be aborted.
This ensures normalized behavior between Chrome (which fires a `popstate`
event on every pageview) and other browsers (which do not).
@method _dispatch
@param {object} req Request object.
@param {String} res Response object.
@chainable
@protected
**/
_dispatch: function (req, res) {
var self = this,
routes = self.match(req.path),
callbacks = [],
routePath, paramValues;
self._dispatching = self._dispatched = true;
if (!routes || !routes.length) {
self._dispatching = false;
return self;
}
routePath = self.removeRoot(req.path);
function next(err) {
var callback, name, route;
if (err) {
// Special case "route" to skip to the next route handler
// avoiding any additional callbacks for the current route.
if (err === 'route') {
callbacks = [];
next();
} else {
Y.error(err);
}
} else if ((callback = callbacks.shift())) {
if (typeof callback === 'string') {
name = callback;
callback = self[name];
if (!callback) {
Y.error('Router: Callback not found: ' + name, null, 'router');
}
}
// Allow access to the number of remaining callbacks for the
// route.
req.pendingCallbacks = callbacks.length;
callback.call(self, req, res, next);
} else if ((route = routes.shift())) {
paramValues = self._getParamValues(route, routePath);
if (!paramValues) {
// Skip this route because one of the param handlers
// rejected a param value in the `routePath`.
next('route');
return;
}
// Expose the processed param values.
req.params = paramValues;
// Allow access to current route and the number of remaining
// routes for this request.
req.route = route;
req.pendingRoutes = routes.length;
// Make a copy of this route's `callbacks` so the original array
// is preserved.
callbacks = route.callbacks.concat();
// Execute this route's `callbacks`.
next();
}
}
next();
self._dispatching = false;
return self._dequeue();
},
/**
Returns the resolved path from the hash fragment, or an empty string if the
hash is not path-like.
@method _getHashPath
@param {String} [hash] Hash fragment to resolve into a path. By default this
will be the hash from the current URL.
@return {String} Current hash path, or an empty string if the hash is empty.
@protected
**/
_getHashPath: function (hash) {
hash || (hash = HistoryHash.getHash());
// Make sure the `hash` is path-like.
if (hash && hash.charAt(0) === '/') {
return this._joinURL(hash);
}
return '';
},
/**
Gets the location origin (i.e., protocol, host, and port) as a URL.
@example
http://example.com
@method _getOrigin
@return {String} Location origin (i.e., protocol, host, and port).
@protected
**/
_getOrigin: function () {
var location = Y.getLocation();
return location.origin || (location.protocol + '//' + location.host);
},
/**
Getter for the `params` attribute.
@method _getParams
@return {Object} Mapping of param handlers: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_getParams: function () {
return Y.merge(this._params);
},
/**
Gets the param values for the specified `route` and `path`, suitable to use
form `req.params`.
**Note:** This method will return `false` if a named param handler rejects a
param value.
@method _getParamValues
@param {Object} route The route to get param values for.
@param {String} path The route path (root removed) that provides the param
values.
@return {Boolean|Array|Object} The collection of processed param values.
Either a hash of `name` -> `value` for named params processed by this
router's param handlers, or an array of matches for a route with unnamed
params. If a named param handler rejects a value, then `false` will be
returned.
@protected
@since 3.16.0
**/
_getParamValues: function (route, path) {
var matches, paramsMatch, paramValues;
// Decode each of the path params so that the any URL-encoded path
// segments are decoded in the `req.params` object.
matches = YArray.map(route.regex.exec(path) || [], function (match) {
// Decode matches, or coerce `undefined` matches to an empty
// string to match expectations of working with `req.params`
// in the context of route dispatching, and normalize
// browser differences in their handling of regex NPCGs:
// https://github.com/yui/yui3/issues/1076
return (match && this._decode(match)) || '';
}, this);
// Simply return the array of decoded values when the route does *not*
// use named parameters.
if (matches.length - 1 !== route.keys.length) {
return matches;
}
// Remove the first "match" from the param values, because it's just the
// `path` processed by the route's regex, and map the values to the keys
// to create the name params collection.
paramValues = YArray.hash(route.keys, matches.slice(1));
// Pass each named param value to its handler, if there is one, for
// validation/processing. If a param value is rejected by a handler,
// then the params don't match and a falsy value is returned.
paramsMatch = YArray.every(route.keys, function (name) {
var paramHandler = this._params[name],
value = paramValues[name];
if (paramHandler && value && typeof value === 'string') {
// Check if `paramHandler` is a RegExp, because this
// is true in Android 2.3 and other browsers!
// `typeof /.*/ === 'function'`
value = YLang.isRegExp(paramHandler) ?
paramHandler.exec(value) :
paramHandler.call(this, value, name);
if (value !== false && YLang.isValue(value)) {
// Update the named param to the value from the handler.
paramValues[name] = value;
return true;
}
// Consider the param value as rejected by the handler.
return false;
}
return true;
}, this);
if (paramsMatch) {
return paramValues;
}
// Signal that a param value was rejected by a named param handler.
return false;
},
/**
Gets the current route path.
@method _getPath
@return {String} Current route path.
@protected
**/
_getPath: function () {
var path = (!this._html5 && this._getHashPath()) ||
Y.getLocation().pathname;
return this.removeQuery(path);
},
/**
Returns the current path root after popping off the last path segment,
making it useful for resolving other URL paths against.
The path root will always begin and end with a '/'.
@method _getPathRoot
@return {String} The URL's path root.
@protected
@since 3.5.0
**/
_getPathRoot: function () {
var slash = '/',
path = Y.getLocation().pathname,
segments;
if (path.charAt(path.length - 1) === slash) {
return path;
}
segments = path.split(slash);
segments.pop();
return segments.join(slash) + slash;
},
/**
Gets the current route query string.
@method _getQuery
@return {String} Current route query string.
@protected
**/
_getQuery: function () {
var location = Y.getLocation(),
hash, matches;
if (this._html5) {
return location.search.substring(1);
}
hash = HistoryHash.getHash();
matches = hash.match(this._regexUrlQuery);
return hash && matches ? matches[1] : location.search.substring(1);
},
/**
Creates a regular expression from the given route specification. If _path_
is already a regex, it will be returned unmodified.
@method _getRegex
@param {String|RegExp} path Route path specification.
@param {Array} keys Array reference to which route parameter names will be
added.
@return {RegExp} Route regex.
@protected
**/
_getRegex: function (path, keys) {
if (YLang.isRegExp(path)) {
return path;
}
// Special case for catchall paths.
if (path === '*') {
return (/.*/);
}
path = path.replace(this._regexPathParam, function (match, operator, key) {
// Only `*` operators are supported for key-less matches to allowing
// in-path wildcards like: '/foo/*'.
if (!key) {
return operator === '*' ? '.*' : match;
}
keys.push(key);
return operator === '*' ? '(.*?)' : '([^/#?]+)';
});
return new RegExp('^' + path + '$');
},
/**
Gets a request object that can be passed to a route handler.
@method _getRequest
@param {String} src What initiated the URL change and need for the request.
@return {Object} Request object.
@protected
**/
_getRequest: function (src) {
return {
path : this._getPath(),
query : this._parseQuery(this._getQuery()),
url : this._getURL(),
router: this,
src : src
};
},
/**
Gets a response object that can be passed to a route handler.
@method _getResponse
@param {Object} req Request object.
@return {Object} Response Object.
@protected
**/
_getResponse: function (req) {
return {req: req};
},
/**
Getter for the `routes` attribute.
@method _getRoutes
@return {Object[]} Array of route objects.
@protected
**/
_getRoutes: function () {
return this._routes.concat();
},
/**
Gets the current full URL.
@method _getURL
@return {String} URL.
@protected
**/
_getURL: function () {
var url = Y.getLocation().toString();
if (!this._html5) {
url = this._upgradeURL(url);
}
return url;
},
/**
Returns `true` when the specified `url` is from the same origin as the
current URL; i.e., the protocol, host, and port of the URLs are the same.
All host or path relative URLs are of the same origin. A scheme-relative URL
is first prefixed with the current scheme before being evaluated.
@method _hasSameOrigin
@param {String} url URL to compare origin with the current URL.
@return {Boolean} Whether the URL has the same origin of the current URL.
@protected
**/
_hasSameOrigin: function (url) {
var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
// Prepend current scheme to scheme-relative URLs.
if (origin && origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return !origin || origin === this._getOrigin();
},
/**
Joins the `root` URL to the specified _url_, normalizing leading/trailing
`/` characters.
@example
router.set('root', '/foo');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
router.set('root', '/foo/');
router._joinURL('bar'); // => '/foo/bar'
router._joinURL('/bar'); // => '/foo/bar'
@method _joinURL
@param {String} url URL to append to the `root` URL.
@return {String} Joined URL.
@protected
**/
_joinURL: function (url) {
var root = this.get('root');
// Causes `url` to _always_ begin with a "/".
url = this.removeRoot(url);
if (url.charAt(0) === '/') {
url = url.substring(1);
}
return root && root.charAt(root.length - 1) === '/' ?
root + url :
root + '/' + url;
},
/**
Returns a normalized path, ridding it of any '..' segments and properly
handling leading and trailing slashes.
@method _normalizePath
@param {String} path URL path to normalize.
@return {String} Normalized path.
@protected
@since 3.5.0
**/
_normalizePath: function (path) {
var dots = '..',
slash = '/',
i, len, normalized, segments, segment, stack;
if (!path || path === slash) {
return slash;
}
segments = path.split(slash);
stack = [];
for (i = 0, len = segments.length; i < len; ++i) {
segment = segments[i];
if (segment === dots) {
stack.pop();
} else if (segment) {
stack.push(segment);
}
}
normalized = slash + stack.join(slash);
// Append trailing slash if necessary.
if (normalized !== slash && path.charAt(path.length - 1) === slash) {
normalized += slash;
}
return normalized;
},
/**
Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
available, this method will be an alias to that.
@method _parseQuery
@param {String} query Query string to parse.
@return {Object} Hash of key/value pairs for query parameters.
@protected
**/
_parseQuery: QS && QS.parse ? QS.parse : function (query) {
var decode = this._decode,
params = query.split('&'),
i = 0,
len = params.length,
result = {},
param;
for (; i < len; ++i) {
param = params[i].split('=');
if (param[0]) {
result[decode(param[0])] = decode(param[1] || '');
}
}
return result;
},
/**
Returns `true` when the specified `path` is semantically within the
specified `root` path.
If the `root` does not end with a trailing slash ("/"), one will be added
before the `path` is evaluated against the root path.
@example
this._pathHasRoot('/app', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/foo'); // => true
this._pathHasRoot('/app/', '/app/'); // => true
this._pathHasRoot('/app', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/foo/bar'); // => false
this._pathHasRoot('/app/', '/app'); // => false
this._pathHasRoot('/app', '/app'); // => false
@method _pathHasRoot
@param {String} root Root path used to evaluate whether the specificed
`path` is semantically within. A trailing slash ("/") will be added if
it does not already end with one.
@param {String} path Path to evaluate for containing the specified `root`.
@return {Boolean} Whether or not the `path` is semantically within the
`root` path.
@protected
@since 3.13.0
**/
_pathHasRoot: function (root, path) {
var rootPath = root.charAt(root.length - 1) === '/' ? root : root + '/';
return path.indexOf(rootPath) === 0;
},
/**
Queues up a `_save()` call to run after all previously-queued calls have
finished.
This is necessary because if we make multiple `_save()` calls before the
first call gets dispatched, then both calls will dispatch to the last call's
URL.
All arguments passed to `_queue()` will be passed on to `_save()` when the
queued function is executed.
@method _queue
@chainable
@see _dequeue
@protected
**/
_queue: function () {
var args = arguments,
self = this;
saveQueue.push(function () {
if (self._html5) {
if (Y.UA.ios && Y.UA.ios < 5) {
// iOS <5 has buggy HTML5 history support, and needs to be
// synchronous.
self._save.apply(self, args);
} else {
// Wrapped in a timeout to ensure that _save() calls are
// always processed asynchronously. This ensures consistency
// between HTML5- and hash-based history.
setTimeout(function () {
self._save.apply(self, args);
}, 1);
}
} else {
self._dispatching = true; // otherwise we'll dequeue too quickly
self._save.apply(self, args);
}
return self;
});
return !this._dispatching ? this._dequeue() : this;
},
/**
Returns the normalized result of resolving the `path` against the current
path. Falsy values for `path` will return just the current path.
@method _resolvePath
@param {String} path URL path to resolve.
@return {String} Resolved path.
@protected
@since 3.5.0
**/
_resolvePath: function (path) {
if (!path) {
return Y.getLocation().pathname;
}
if (path.charAt(0) !== '/') {
path = this._getPathRoot() + path;
}
return this._normalizePath(path);
},
/**
Resolves the specified URL against the current URL.
This method resolves URLs like a browser does and will always return an
absolute URL. When the specified URL is already absolute, it is assumed to
be fully resolved and is simply returned as is. Scheme-relative URLs are
prefixed with the current protocol. Relative URLs are giving the current
URL's origin and are resolved and normalized against the current path root.
@method _resolveURL
@param {String} url URL to resolve.
@return {String} Resolved URL.
@protected
@since 3.5.0
**/
_resolveURL: function (url) {
var parts = url && url.match(this._regexURL),
origin, path, query, hash, resolved;
if (!parts) {
return Y.getLocation().toString();
}
origin = parts[1];
path = parts[2];
query = parts[3];
hash = parts[4];
// Absolute and scheme-relative URLs are assumed to be fully-resolved.
if (origin) {
// Prepend the current scheme for scheme-relative URLs.
if (origin.indexOf('//') === 0) {
origin = Y.getLocation().protocol + origin;
}
return origin + (path || '/') + (query || '') + (hash || '');
}
// Will default to the current origin and current path.
resolved = this._getOrigin() + this._resolvePath(path);
// A path or query for the specified URL trumps the current URL's.
if (path || query) {
return resolved + (query || '') + (hash || '');
}
query = this._getQuery();
return resolved + (query ? ('?' + query) : '') + (hash || '');
},
/**
Saves a history entry using either `pushState()` or the location hash.
This method enforces the same-origin security constraint; attempting to save
a `url` that is not from the same origin as the current URL will result in
an error.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
**/
_save: function (url, replace) {
var urlIsString = typeof url === 'string',
currentPath, root, hash;
// Perform same-origin check on the specified URL.
if (urlIsString && !this._hasSameOrigin(url)) {
Y.error('Security error: The new URL must be of the same origin as the current URL.');
return this;
}
// Joins the `url` with the `root`.
if (urlIsString) {
url = this._joinURL(url);
}
// Force _ready to true to ensure that the history change is handled
// even if _save is called before the `ready` event fires.
this._ready = true;
if (this._html5) {
this._history[replace ? 'replace' : 'add'](null, {url: url});
} else {
currentPath = Y.getLocation().pathname;
root = this.get('root');
hash = HistoryHash.getHash();
if (!urlIsString) {
url = hash;
}
// Determine if the `root` already exists in the current location's
// `pathname`, and if it does then we can exclude it from the
// hash-based path. No need to duplicate the info in the URL.
if (root === currentPath || root === this._getPathRoot()) {
url = this.removeRoot(url);
}
// The `hashchange` event only fires when the new hash is actually
// different. This makes sure we'll always dequeue and dispatch
// _all_ router instances, mimicking the HTML5 behavior.
if (url === hash) {
Y.Router.dispatch();
} else {
HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
}
}
return this;
},
/**
Setter for the `params` attribute.
@method _setParams
@param {Object} params Map in the form: `name` -> RegExp | Function.
@return {Object} The map of params: `name` -> RegExp | Function.
@protected
@since 3.12.0
**/
_setParams: function (params) {
this._params = {};
YObject.each(params, function (regex, name) {
this.param(name, regex);
}, this);
return Y.merge(this._params);
},
/**
Setter for the `routes` attribute.
@method _setRoutes
@param {Object[]} routes Array of route objects.
@return {Object[]} Array of route objects.
@protected
**/
_setRoutes: function (routes) {
this._routes = [];
YArray.each(routes, function (route) {
this.route(route);
}, this);
return this._routes.concat();
},
/**
Upgrades a hash-based URL to a full-path URL, if necessary.
The specified `url` will be upgraded if its of the same origin as the
current URL and has a path-like hash. URLs that don't need upgrading will be
returned as-is.
@example
app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
@method _upgradeURL
@param {String} url The URL to upgrade from hash-based to full-path.
@return {String} The upgraded URL, or the specified URL untouched.
@protected
@since 3.5.0
**/
_upgradeURL: function (url) {
// We should not try to upgrade paths for external URLs.
if (!this._hasSameOrigin(url)) {
return url;
}
var hash = (url.match(/#(.*)$/) || [])[1] || '',
hashPrefix = Y.HistoryHash.hashPrefix,
hashPath;
// Strip any hash prefix, like hash-bangs.
if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
hash = hash.replace(hashPrefix, '');
}
// If the hash looks like a URL path, assume it is, and upgrade it!
if (hash) {
hashPath = this._getHashPath(hash);
if (hashPath) {
return this._resolveURL(hashPath);
}
}
return url;
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles `history:change` and `hashchange` events.
@method _afterHistoryChange
@param {EventFacade} e
@protected
**/
_afterHistoryChange: function (e) {
var self = this,
src = e.src,
prevURL = self._url,
currentURL = self._getURL(),
req, res;
self._url = currentURL;
// Handles the awkwardness that is the `popstate` event. HTML5 browsers
// fire `popstate` right before they fire `hashchange`, and Chrome fires
// `popstate` on page load. If this router is not ready or the previous
// and current URLs only differ by their hash, then we want to ignore
// this `popstate` event.
if (src === 'popstate' &&
(!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
return;
}
req = self._getRequest(src);
res = self._getResponse(req);
self._dispatch(req, res);
},
// -- Default Event Handlers -----------------------------------------------
/**
Default handler for the `ready` event.
@method _defReadyFn
@param {EventFacade} e
@protected
**/
_defReadyFn: function (e) {
this._ready = true;
}
}, {
// -- Static Properties ----------------------------------------------------
NAME: 'router',
ATTRS: {
/**
Whether or not this browser is capable of using HTML5 history.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
**/
html5: {
// Android versions lower than 3.0 are buggy and don't update
// window.location after a pushState() call, so we fall back to
// hash-based history for them.
//
// See http://code.google.com/p/android/issues/detail?id=17471
valueFn: function () { return Y.Router.html5; },
writeOnce: 'initOnly'
},
/**
Map of params handlers in the form: `name` -> RegExp | Function.
If a param handler regex or function returns a value of `false`, `null`,
`undefined`, or `NaN`, the current route will not match and be skipped.
All other return values will be used in place of the original param
value parsed from the URL.
This attribute is intended to be used to set params at init time, or to
completely reset all params after init. To add params after init without
resetting all existing params, use the `param()` method.
@attribute params
@type Object
@default `{}`
@see param
@since 3.12.0
**/
params: {
value : {},
getter: '_getParams',
setter: '_setParams'
},
/**
Absolute root path from which all routes should be evaluated.
For example, if your router is running on a page at
`http://example.com/myapp/` and you add a route with the path `/`, your
route will never execute, because the path will always be preceded by
`/myapp`. Setting `root` to `/myapp` would cause all routes to be
evaluated relative to that root URL, so the `/` route would then execute
when the user browses to `http://example.com/myapp/`.
@example
router.set('root', '/myapp');
router.route('/foo', function () { ... });
// Updates the URL to: "/myapp/foo"
router.save('/foo');
@attribute root
@type String
@default `''`
**/
root: {
value: ''
},
/**
Array of route objects.
Each item in the array must be an object with the following properties
in order to be processed by the router:
* `path`: String or regex representing the path to match. See the docs
for the `route()` method for more details.
* `callbacks`: Function or a string representing the name of a
function on this router instance that should be called when the
route is triggered. An array of functions and/or strings may also be
provided. See the docs for the `route()` method for more details.
If a route object contains a `regex` or `regexp` property, or if its
`path` is a regular express, then the route will be considered to be
fully-processed. Any fully-processed routes may contain the following
properties:
* `regex`: The regular expression representing the path to match, this
property may also be named `regexp` for greater compatibility.
* `keys`: Array of named path parameters used to populate `req.params`
objects when dispatching to route handlers.
Any additional data contained on these route objects will be retained.
This is useful to store extra metadata about a route; e.g., a `name` to
give routes logical names.
This attribute is intended to be used to set routes at init time, or to
completely reset all routes after init. To add routes after init without
resetting all existing routes, use the `route()` method.
@attribute routes
@type Object[]
@default `[]`
@see route
**/
routes: {
value : [],
getter: '_getRoutes',
setter: '_setRoutes'
}
},
// Used as the default value for the `html5` attribute, and for testing.
html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3),
// To make this testable.
_instances: instances,
/**
Dispatches to the first route handler that matches the specified `path` for
all active router instances.
This provides a mechanism to cause all active router instances to dispatch
to their route handlers without needing to change the URL or fire the
`history:change` or `hashchange` event.
@method dispatch
@static
@since 3.6.0
**/
dispatch: function () {
var i, len, router, req, res;
for (i = 0, len = instances.length; i < len; i += 1) {
router = instances[i];
if (router) {
req = router._getRequest('dispatch');
res = router._getResponse(req);
router._dispatch(req, res);
}
}
}
});
/**
The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
`Router` class. Use that class instead. This alias will be removed in a future
version of YUI.
@class Controller
@constructor
@extends Base
@deprecated Use `Router` instead.
@see Router
**/
Y.Controller = Y.Router;
}, '3.16.0', {"optional": ["querystring-parse"], "requires": ["array-extras", "base-build", "history"]});
| vousk/jsdelivr | files/yui/3.16.0/router/router.js | JavaScript | mit | 59,499 |
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
/**
* List compiled by mystix on the extjs.com forums.
* Thank you Mystix!
*/
/* Slovak Translation by Michal Thomka
* 14 April 2007
*/
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">Nahrávam...</div>';
if(Ext.View){
Ext.View.prototype.emptyText = "";
}
if(Ext.grid.GridPanel){
Ext.grid.GridPanel.prototype.ddText = "{0} označených riadkov";
}
if(Ext.TabPanelItem){
Ext.TabPanelItem.prototype.closeText = "Zavrieť túto záložku";
}
if(Ext.form.Field){
Ext.form.Field.prototype.invalidText = "Hodnota v tomto poli je nesprávna";
}
if(Ext.LoadMask){
Ext.LoadMask.prototype.msg = "Nahrávam...";
}
Date.monthNames = [
"Január",
"Február",
"Marec",
"Apríl",
"Máj",
"Jún",
"Júl",
"August",
"September",
"Október",
"November",
"December"
];
Date.dayNames = [
"Nedeľa",
"Pondelok",
"Utorok",
"Streda",
"Štvrtok",
"Piatok",
"Sobota"
];
if(Ext.MessageBox){
Ext.MessageBox.buttonText = {
ok : "OK",
cancel : "Zrušiť",
yes : "Áno",
no : "Nie"
};
}
if(Ext.util.Format){
Ext.util.Format.date = function(v, format){
if(!v) return "";
if(!(v instanceof Date)) v = new Date(Date.parse(v));
return v.dateFormat(format || "d.m.Y");
};
}
if(Ext.DatePicker){
Ext.apply(Ext.DatePicker.prototype, {
todayText : "Dnes",
minText : "Tento dátum je menší ako minimálny možný dátum",
maxText : "Tento dátum je väčší ako maximálny možný dátum",
disabledDaysText : "",
disabledDatesText : "",
monthNames : Date.monthNames,
dayNames : Date.dayNames,
nextText : 'Ďalší Mesiac (Control+Doprava)',
prevText : 'Predch. Mesiac (Control+Doľava)',
monthYearText : 'Vyberte Mesiac (Control+Hore/Dole pre posun rokov)',
todayTip : "{0} (Medzerník)",
format : "d.m.Y"
});
}
if(Ext.PagingToolbar){
Ext.apply(Ext.PagingToolbar.prototype, {
beforePageText : "Strana",
afterPageText : "z {0}",
firstText : "Prvá Strana",
prevText : "Predch. Strana",
nextText : "Ďalšia Strana",
lastText : "Posledná strana",
refreshText : "Obnoviť",
displayMsg : "Zobrazujem {0} - {1} z {2}",
emptyMsg : 'iadne dáta'
});
}
if(Ext.form.TextField){
Ext.apply(Ext.form.TextField.prototype, {
minLengthText : "Minimálna dĺžka pre toto pole je {0}",
maxLengthText : "Maximálna dĺžka pre toto pole je {0}",
blankText : "Toto pole je povinné",
regexText : "",
emptyText : null
});
}
if(Ext.form.NumberField){
Ext.apply(Ext.form.NumberField.prototype, {
minText : "Minimálna hodnota pre toto pole je {0}",
maxText : "Maximálna hodnota pre toto pole je {0}",
nanText : "{0} je nesprávne číslo"
});
}
if(Ext.form.DateField){
Ext.apply(Ext.form.DateField.prototype, {
disabledDaysText : "Zablokované",
disabledDatesText : "Zablokované",
minText : "Dátum v tomto poli musí byť až po {0}",
maxText : "Dátum v tomto poli musí byť pred {0}",
invalidText : "{0} nie je správny dátum - musí byť vo formáte {1}",
format : "d.m.Y"
});
}
if(Ext.form.ComboBox){
Ext.apply(Ext.form.ComboBox.prototype, {
loadingText : "Nahrávam...",
valueNotFoundText : undefined
});
}
if(Ext.form.VTypes){
Ext.apply(Ext.form.VTypes, {
emailText : 'Toto pole musí byť e-mailová adresa vo formáte "user@example.com"',
urlText : 'Toto pole musí byť URL vo formáte "http:/'+'/www.example.com"',
alphaText : 'Toto pole može obsahovať iba písmená a znak _',
alphanumText : 'Toto pole može obsahovať iba písmená, čísla a znak _'
});
}
if(Ext.grid.GridView){
Ext.apply(Ext.grid.GridView.prototype, {
sortAscText : "Zoradiť vzostupne",
sortDescText : "Zoradiť zostupne",
lockText : "Zamknúť stľpec",
unlockText : "Odomknúť stľpec",
columnsText : "Stľpce"
});
}
if(Ext.grid.PropertyColumnModel){
Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
nameText : "Názov",
valueText : "Hodnota",
dateFormat : "d.m.Y"
});
}
if(Ext.layout.BorderLayout && Ext.layout.BorderLayout.SplitRegion){
Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
splitTip : "Potiahnite pre zmenu rozmeru",
collapsibleSplitTip : "Potiahnite pre zmenu rozmeru. Dvojklikom schováte."
});
}
| dinubalti/FirstSymfony | web/public/js/lib/ext-3.4.1/src/locale/ext-lang-sk.js | JavaScript | mit | 5,418 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
public enum SmoothingMode
{
Invalid = QualityMode.Invalid,
Default = QualityMode.Default,
HighSpeed = QualityMode.Low,
HighQuality = QualityMode.High,
None,
AntiAlias
}
}
| rubo/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/SmoothingMode.cs | C# | mit | 472 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
public enum InterpolationMode
{
Invalid = QualityMode.Invalid,
Default = QualityMode.Default,
Low = QualityMode.Low,
High = QualityMode.High,
Bilinear,
Bicubic,
NearestNeighbor,
HighQualityBilinear,
HighQualityBicubic
}
}
| nbarbettini/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/InterpolationMode.cs | C# | mit | 547 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* An implementation of a userlist which has been filtered and approved.
*
* @package core_privacy
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace core_privacy\local\request;
defined('MOODLE_INTERNAL') || die();
/**
* An implementation of a userlist which has been filtered and approved.
*
* @copyright 2018 Andrew Nicols <andrew@nicols.co.uk>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class approved_userlist extends userlist_base {
/**
* Create a new approved userlist.
*
* @param \context $context The context.
* @param string $component the frankenstyle component name.
* @param \int[] $userids The list of userids present in this list.
*/
public function __construct(\context $context, string $component, array $userids) {
parent::__construct($context, $component);
$this->set_userids($userids);
}
/**
* Create an approved userlist from a userlist.
*
* @param userlist $userlist The source list
* @return approved_userlist The newly created approved userlist.
*/
public static function create_from_userlist(userlist $userlist) : approved_userlist {
$newlist = new static($userlist->get_context(), $userlist->get_component(), $userlist->get_userids());
return $newlist;
}
}
| reskit/moodle | privacy/classes/local/request/approved_userlist.php | PHP | gpl-3.0 | 2,170 |
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.View
* @since CakePHP(tm) v 0.2.9
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Router', 'Routing');
App::uses('Hash', 'Utility');
App::uses('Inflector', 'Utility');
/**
* Abstract base class for all other Helpers in CakePHP.
* Provides common methods and features.
*
* @package Cake.View
*/
class Helper extends Object {
/**
* Settings for this helper.
*
* @var array
*/
public $settings = array();
/**
* List of helpers used by this helper
*
* @var array
*/
public $helpers = array();
/**
* A helper lookup table used to lazy load helper objects.
*
* @var array
*/
protected $_helperMap = array();
/**
* The current theme name if any.
*
* @var string
*/
public $theme = null;
/**
* Request object
*
* @var CakeRequest
*/
public $request = null;
/**
* Plugin path
*
* @var string
*/
public $plugin = null;
/**
* Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
* primaryKey and validates array('field_name')
*
* @var array
*/
public $fieldset = array();
/**
* Holds tag templates.
*
* @var array
*/
public $tags = array();
/**
* Holds the content to be cleaned.
*
* @var mixed
*/
protected $_tainted = null;
/**
* Holds the cleaned content.
*
* @var mixed
*/
protected $_cleaned = null;
/**
* The View instance this helper is attached to
*
* @var View
*/
protected $_View;
/**
* A list of strings that should be treated as suffixes, or
* sub inputs for a parent input. This is used for date/time
* inputs primarily.
*
* @var array
*/
protected $_fieldSuffixes = array(
'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
);
/**
* The name of the current model entities are in scope of.
*
* @see Helper::setEntity()
* @var string
*/
protected $_modelScope;
/**
* The name of the current model association entities are in scope of.
*
* @see Helper::setEntity()
* @var string
*/
protected $_association;
/**
* The dot separated list of elements the current field entity is for.
*
* @see Helper::setEntity()
* @var string
*/
protected $_entityPath;
/**
* Minimized attributes
*
* @var array
*/
protected $_minimizedAttributes = array(
'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
);
/**
* Format to attribute
*
* @var string
*/
protected $_attributeFormat = '%s="%s"';
/**
* Format to attribute
*
* @var string
*/
protected $_minimizedAttributeFormat = '%s="%s"';
/**
* Default Constructor
*
* @param View $View The View this helper is being attached to.
* @param array $settings Configuration settings for the helper.
*/
public function __construct(View $View, $settings = array()) {
$this->_View = $View;
$this->request = $View->request;
if ($settings) {
$this->settings = Hash::merge($this->settings, $settings);
}
if (!empty($this->helpers)) {
$this->_helperMap = ObjectCollection::normalizeObjectArray($this->helpers);
}
}
/**
* Provide non fatal errors on missing method calls.
*
* @param string $method Method to invoke
* @param array $params Array of params for the method.
* @return void
*/
public function __call($method, $params) {
trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
}
/**
* Lazy loads helpers. Provides access to deprecated request properties as well.
*
* @param string $name Name of the property being accessed.
* @return mixed Helper or property found at $name
* @deprecated Accessing request properties through this method is deprecated and will be removed in 3.0.
*/
public function __get($name) {
if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
$settings = array('enabled' => false) + (array)$this->_helperMap[$name]['settings'];
$this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
}
if (isset($this->{$name})) {
return $this->{$name};
}
switch ($name) {
case 'base':
case 'here':
case 'webroot':
case 'data':
return $this->request->{$name};
case 'action':
return isset($this->request->params['action']) ? $this->request->params['action'] : '';
case 'params':
return $this->request;
}
}
/**
* Provides backwards compatibility access for setting values to the request object.
*
* @param string $name Name of the property being accessed.
* @param mixed $value Value to set.
* @return void
* @deprecated This method will be removed in 3.0
*/
public function __set($name, $value) {
switch ($name) {
case 'base':
case 'here':
case 'webroot':
case 'data':
$this->request->{$name} = $value;
return;
case 'action':
$this->request->params['action'] = $value;
return;
}
$this->{$name} = $value;
}
/**
* Finds URL for specified action.
*
* Returns a URL pointing at the provided parameters.
*
* @param string|array $url Either a relative string url like `/products/view/23` or
* an array of URL parameters. Using an array for URLs will allow you to leverage
* the reverse routing features of CakePHP.
* @param boolean $full If true, the full base URL will be prepended to the result
* @return string Full translated URL with base path.
* @link http://book.cakephp.org/2.0/en/views/helpers.html
*/
public function url($url = null, $full = false) {
return h(Router::url($url, $full));
}
/**
* Checks if a file exists when theme is used, if no file is found default location is returned
*
* @param string $file The file to create a webroot path to.
* @return string Web accessible path to file.
*/
public function webroot($file) {
$asset = explode('?', $file);
$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
$webPath = "{$this->request->webroot}" . $asset[0];
$file = $asset[0];
if (!empty($this->theme)) {
$file = trim($file, '/');
$theme = $this->theme . '/';
if (DS === '\\') {
$file = str_replace('/', '\\', $file);
}
if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
} else {
$themePath = App::themePath($this->theme);
$path = $themePath . 'webroot' . DS . $file;
if (file_exists($path)) {
$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
}
}
}
if (strpos($webPath, '//') !== false) {
return str_replace('//', '/', $webPath . $asset[1]);
}
return $webPath . $asset[1];
}
/**
* Generate URL for given asset file. Depending on options passed provides full URL with domain name.
* Also calls Helper::assetTimestamp() to add timestamp to local files
*
* @param string|array $path Path string or URL array
* @param array $options Options array. Possible keys:
* `fullBase` Return full URL with domain name
* `pathPrefix` Path prefix for relative URLs
* `ext` Asset extension to append
* `plugin` False value will prevent parsing path as a plugin
* @return string Generated URL
*/
public function assetUrl($path, $options = array()) {
if (is_array($path)) {
return $this->url($path, !empty($options['fullBase']));
}
if (strpos($path, '://') !== false) {
return $path;
}
if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
list($plugin, $path) = $this->_View->pluginSplit($path, false);
}
if (!empty($options['pathPrefix']) && $path[0] !== '/') {
$path = $options['pathPrefix'] . $path;
}
if (
!empty($options['ext']) &&
strpos($path, '?') === false &&
substr($path, -strlen($options['ext'])) !== $options['ext']
) {
$path .= $options['ext'];
}
if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
return $path;
}
if (isset($plugin)) {
$path = Inflector::underscore($plugin) . '/' . $path;
}
$path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
if (!empty($options['fullBase'])) {
$path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
}
return $path;
}
/**
* Encodes a URL for use in HTML attributes.
*
* @param string $url The URL to encode.
* @return string The URL encoded for both URL & HTML contexts.
*/
protected function _encodeUrl($url) {
$path = parse_url($url, PHP_URL_PATH);
$parts = array_map('rawurldecode', explode('/', $path));
$parts = array_map('rawurlencode', $parts);
$encoded = implode('/', $parts);
return h(str_replace($path, $encoded, $url));
}
/**
* Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
* Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force'
* a timestamp will be added.
*
* @param string $path The file path to timestamp, the path must be inside WWW_ROOT
* @return string Path with a timestamp added, or not.
*/
public function assetTimestamp($path) {
$stamp = Configure::read('Asset.timestamp');
$timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug') > 0);
if ($timestampEnabled && strpos($path, '?') === false) {
$filepath = preg_replace(
'/^' . preg_quote($this->request->webroot, '/') . '/',
'',
urldecode($path)
);
$webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
if (file_exists($webrootPath)) {
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($webrootPath);
//@codingStandardsIgnoreEnd
}
$segments = explode('/', ltrim($filepath, '/'));
if ($segments[0] === 'theme') {
$theme = $segments[1];
unset($segments[0], $segments[1]);
$themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($themePath);
//@codingStandardsIgnoreEnd
} else {
$plugin = Inflector::camelize($segments[0]);
if (CakePlugin::loaded($plugin)) {
unset($segments[0]);
$pluginPath = CakePlugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
//@codingStandardsIgnoreStart
return $path . '?' . @filemtime($pluginPath);
//@codingStandardsIgnoreEnd
}
}
}
return $path;
}
/**
* Used to remove harmful tags from content. Removes a number of well known XSS attacks
* from content. However, is not guaranteed to remove all possibilities. Escaping
* content is the best way to prevent all possible attacks.
*
* @param string|array $output Either an array of strings to clean or a single string to clean.
* @return string|array cleaned content for output
* @deprecated This method will be removed in 3.0
*/
public function clean($output) {
$this->_reset();
if (empty($output)) {
return null;
}
if (is_array($output)) {
foreach ($output as $key => $value) {
$return[$key] = $this->clean($value);
}
return $return;
}
$this->_tainted = $output;
$this->_clean();
return $this->_cleaned;
}
/**
* Returns a space-delimited string with items of the $options array. If a key
* of $options array happens to be one of those listed in `Helper::$_minimizedAttributes`
*
* And its value is one of:
*
* - '1' (string)
* - 1 (integer)
* - true (boolean)
* - 'true' (string)
*
* Then the value will be reset to be identical with key's name.
* If the value is not one of these 3, the parameter is not output.
*
* 'escape' is a special option in that it controls the conversion of
* attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
*
* If value for any option key is set to `null` or `false`, that option will be excluded from output.
*
* @param array $options Array of options.
* @param array $exclude Array of options to be excluded, the options here will not be part of the return.
* @param string $insertBefore String to be inserted before options.
* @param string $insertAfter String to be inserted after options.
* @return string Composed attributes.
* @deprecated This method will be moved to HtmlHelper in 3.0
*/
protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
if (!is_string($options)) {
$options = (array)$options + array('escape' => true);
if (!is_array($exclude)) {
$exclude = array();
}
$exclude = array('escape' => true) + array_flip($exclude);
$escape = $options['escape'];
$attributes = array();
foreach ($options as $key => $value) {
if (!isset($exclude[$key]) && $value !== false && $value !== null) {
$attributes[] = $this->_formatAttribute($key, $value, $escape);
}
}
$out = implode(' ', $attributes);
} else {
$out = $options;
}
return $out ? $insertBefore . $out . $insertAfter : '';
}
/**
* Formats an individual attribute, and returns the string value of the composed attribute.
* Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
*
* @param string $key The name of the attribute to create
* @param string $value The value of the attribute to create.
* @param boolean $escape Define if the value must be escaped
* @return string The composed attribute.
* @deprecated This method will be moved to HtmlHelper in 3.0
*/
protected function _formatAttribute($key, $value, $escape = true) {
if (is_array($value)) {
$value = implode(' ', $value);
}
if (is_numeric($key)) {
return sprintf($this->_minimizedAttributeFormat, $value, $value);
}
$truthy = array(1, '1', true, 'true', $key);
$isMinimized = in_array($key, $this->_minimizedAttributes);
if ($isMinimized && in_array($value, $truthy, true)) {
return sprintf($this->_minimizedAttributeFormat, $key, $key);
}
if ($isMinimized) {
return '';
}
return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
}
/**
* Returns a string to be used as onclick handler for confirm dialogs.
*
* @param string $message Message to be displayed
* @param string $okCode Code to be executed after user chose 'OK'
* @param string $cancelCode Code to be executed after user chose 'Cancel'
* @param array $options Array of options
* @return string onclick JS code
*/
protected function _confirm($message, $okCode, $cancelCode = '', $options = array()) {
$message = json_encode($message);
$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
if (isset($options['escape']) && $options['escape'] === false) {
$confirm = h($confirm);
}
return $confirm;
}
/**
* Sets this helper's model and field properties to the dot-separated value-pair in $entity.
*
* @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
* @param boolean $setScope Sets the view scope to the model specified in $tagValue
* @return void
*/
public function setEntity($entity, $setScope = false) {
if ($entity === null) {
$this->_modelScope = false;
}
if ($setScope === true) {
$this->_modelScope = $entity;
}
$parts = array_values(Hash::filter(explode('.', $entity)));
if (empty($parts)) {
return;
}
$count = count($parts);
$lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
// Either 'body' or 'date.month' type inputs.
if (
($count === 1 && $this->_modelScope && !$setScope) ||
(
$count === 2 &&
in_array($lastPart, $this->_fieldSuffixes) &&
$this->_modelScope &&
$parts[0] !== $this->_modelScope
)
) {
$entity = $this->_modelScope . '.' . $entity;
}
// 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
if (
$count >= 2 &&
is_numeric($parts[0]) &&
!is_numeric($parts[1]) &&
$this->_modelScope &&
strpos($entity, $this->_modelScope) === false
) {
$entity = $this->_modelScope . '.' . $entity;
}
$this->_association = null;
$isHabtm = (
isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
$this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
);
// habtm models are special
if ($count === 1 && $isHabtm) {
$this->_association = $parts[0];
$entity = $parts[0] . '.' . $parts[0];
} else {
// check for associated model.
$reversed = array_reverse($parts);
foreach ($reversed as $i => $part) {
if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
$this->_association = $part;
break;
}
}
}
$this->_entityPath = $entity;
}
/**
* Returns the entity reference of the current context as an array of identity parts
*
* @return array An array containing the identity elements of an entity
*/
public function entity() {
return explode('.', $this->_entityPath);
}
/**
* Gets the currently-used model of the rendering context.
*
* @return string
*/
public function model() {
if ($this->_association) {
return $this->_association;
}
return $this->_modelScope;
}
/**
* Gets the currently-used model field of the rendering context.
* Strips off field suffixes such as year, month, day, hour, min, meridian
* when the current entity is longer than 2 elements.
*
* @return string
*/
public function field() {
$entity = $this->entity();
$count = count($entity);
$last = $entity[$count - 1];
if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
$last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
}
return $last;
}
/**
* Generates a DOM ID for the selected element, if one is not set.
* Uses the current View::entity() settings to generate a CamelCased id attribute.
*
* @param array|string $options Either an array of html attributes to add $id into, or a string
* with a view entity path to get a domId for.
* @param string $id The name of the 'id' attribute.
* @return mixed If $options was an array, an array will be returned with $id set. If a string
* was supplied, a string will be returned.
*/
public function domId($options = null, $id = 'id') {
if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
unset($options[$id]);
return $options;
} elseif (!is_array($options) && $options !== null) {
$this->setEntity($options);
return $this->domId();
}
$entity = $this->entity();
$model = array_shift($entity);
$dom = $model . implode('', array_map(array('Inflector', 'camelize'), $entity));
if (is_array($options) && !array_key_exists($id, $options)) {
$options[$id] = $dom;
} elseif ($options === null) {
return $dom;
}
return $options;
}
/**
* Gets the input field name for the current tag. Creates input name attributes
* using CakePHP's data[Model][field] formatting.
*
* @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
* If a string or null, will be used as the View entity.
* @param string $field Field name.
* @param string $key The name of the attribute to be set, defaults to 'name'
* @return mixed If an array was given for $options, an array with $key set will be returned.
* If a string was supplied a string will be returned.
*/
protected function _name($options = array(), $field = null, $key = 'name') {
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (!empty($field)) {
$this->setEntity($field);
}
if (is_array($options) && array_key_exists($key, $options)) {
return $options;
}
switch ($field) {
case '_method':
$name = $field;
break;
default:
$name = 'data[' . implode('][', $this->entity()) . ']';
}
if (is_array($options)) {
$options[$key] = $name;
return $options;
}
return $name;
}
/**
* Gets the data for the current tag
*
* @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
* If a string or null, will be used as the View entity.
* @param string $field Field name.
* @param string $key The name of the attribute to be set, defaults to 'value'
* @return mixed If an array was given for $options, an array with $key set will be returned.
* If a string was supplied a string will be returned.
*/
public function value($options = array(), $field = null, $key = 'value') {
if ($options === null) {
$options = array();
} elseif (is_string($options)) {
$field = $options;
$options = 0;
}
if (is_array($options) && isset($options[$key])) {
return $options;
}
if (!empty($field)) {
$this->setEntity($field);
}
$result = null;
$data = $this->request->data;
$entity = $this->entity();
if (!empty($data) && is_array($data) && !empty($entity)) {
$result = Hash::get($data, implode('.', $entity));
}
$habtmKey = $this->field();
if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
$result = $data[$habtmKey][$habtmKey];
} elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
if (ClassRegistry::isKeySet($habtmKey)) {
$model = ClassRegistry::getObject($habtmKey);
$result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
}
}
if (is_array($options)) {
if ($result === null && isset($options['default'])) {
$result = $options['default'];
}
unset($options['default']);
}
if (is_array($options)) {
$options[$key] = $result;
return $options;
}
return $result;
}
/**
* Sets the defaults for an input tag. Will set the
* name, value, and id attributes for an array of html attributes.
*
* @param string $field The field name to initialize.
* @param array $options Array of options to use while initializing an input field.
* @return array Array options for the form input.
*/
protected function _initInputField($field, $options = array()) {
if ($field !== null) {
$this->setEntity($field);
}
$options = (array)$options;
$options = $this->_name($options);
$options = $this->value($options);
$options = $this->domId($options);
return $options;
}
/**
* Adds the given class to the element options
*
* @param array $options Array options/attributes to add a class to
* @param string $class The class name being added.
* @param string $key the key to use for class.
* @return array Array of options with $key set.
*/
public function addClass($options = array(), $class = null, $key = 'class') {
if (isset($options[$key]) && trim($options[$key])) {
$options[$key] .= ' ' . $class;
} else {
$options[$key] = $class;
}
return $options;
}
/**
* Returns a string generated by a helper method
*
* This method can be overridden in subclasses to do generalized output post-processing
*
* @param string $str String to be output.
* @return string
* @deprecated This method will be removed in future versions.
*/
public function output($str) {
return $str;
}
/**
* Before render callback. beforeRender is called before the view file is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that is going to be rendered
* @return void
*/
public function beforeRender($viewFile) {
}
/**
* After render callback. afterRender is called after the view file is rendered
* but before the layout has been rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The view file that was rendered.
* @return void
*/
public function afterRender($viewFile) {
}
/**
* Before layout callback. beforeLayout is called before the layout is rendered.
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout about to be rendered.
* @return void
*/
public function beforeLayout($layoutFile) {
}
/**
* After layout callback. afterLayout is called after the layout has rendered.
*
* Overridden in subclasses.
*
* @param string $layoutFile The layout file that was rendered.
* @return void
*/
public function afterLayout($layoutFile) {
}
/**
* Before render file callback.
* Called before any view fragment is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The file about to be rendered.
* @return void
*/
public function beforeRenderFile($viewFile) {
}
/**
* After render file callback.
* Called after any view fragment is rendered.
*
* Overridden in subclasses.
*
* @param string $viewFile The file just be rendered.
* @param string $content The content that was rendered.
* @return void
*/
public function afterRenderFile($viewFile, $content) {
}
/**
* Transforms a recordset from a hasAndBelongsToMany association to a list of selected
* options for a multiple select element
*
* @param string|array $data Data array or model name.
* @param string $key Field name.
* @return array
*/
protected function _selectedArray($data, $key = 'id') {
if (!is_array($data)) {
$model = $data;
if (!empty($this->request->data[$model][$model])) {
return $this->request->data[$model][$model];
}
if (!empty($this->request->data[$model])) {
$data = $this->request->data[$model];
}
}
$array = array();
if (!empty($data)) {
foreach ($data as $row) {
if (isset($row[$key])) {
$array[$row[$key]] = $row[$key];
}
}
}
return empty($array) ? null : $array;
}
/**
* Resets the vars used by Helper::clean() to null
*
* @return void
*/
protected function _reset() {
$this->_tainted = null;
$this->_cleaned = null;
}
/**
* Removes harmful content from output
*
* @return void
*/
protected function _clean() {
if (get_magic_quotes_gpc()) {
$this->_cleaned = stripslashes($this->_tainted);
} else {
$this->_cleaned = $this->_tainted;
}
$this->_cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->_cleaned);
$this->_cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->_cleaned);
$this->_cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->_cleaned);
$this->_cleaned = html_entity_decode($this->_cleaned, ENT_COMPAT, "UTF-8");
$this->_cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*)[\\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu', '$1=$2nomozbinding...', $this->_cleaned);
$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*>#iUu', "$1>", $this->_cleaned);
$this->_cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->_cleaned);
do {
$oldstring = $this->_cleaned;
$this->_cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->_cleaned);
} while ($oldstring !== $this->_cleaned);
$this->_cleaned = str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $this->_cleaned);
}
}
| jones139/hdms | lib/Cake/View/Helper.php | PHP | gpl-3.0 | 28,454 |
// (C) Copyright Edward Diener 2015
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#if !defined(BOOST_VMD_SEQ_TO_LIST_HPP)
#define BOOST_VMD_SEQ_TO_LIST_HPP
#include <boost/vmd/detail/setup.hpp>
#if BOOST_PP_VARIADICS
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/seq/to_list.hpp>
// #include <boost/vmd/identity.hpp>
#include <boost/vmd/is_empty.hpp>
/*
The succeeding comments in this file are in doxygen format.
*/
/** \file
*/
/** \def BOOST_VMD_SEQ_TO_LIST(seq)
\brief converts a seq to a list.
seq = seq to be converted.
If the seq is an empty seq it is converted to an empty list (BOOST_PP_NIL).
Otherwise the seq is converted to a list with the same number of elements as the seq.
*/
#if BOOST_VMD_MSVC
#define BOOST_VMD_SEQ_TO_LIST(seq) \
BOOST_PP_IIF \
( \
BOOST_VMD_IS_EMPTY(seq), \
BOOST_VMD_SEQ_TO_LIST_PE, \
BOOST_VMD_SEQ_TO_LIST_NPE \
) \
(seq) \
/**/
#define BOOST_VMD_SEQ_TO_LIST_PE(seq) BOOST_PP_NIL
/**/
#define BOOST_VMD_SEQ_TO_LIST_NPE(seq) BOOST_PP_SEQ_TO_LIST(seq)
/**/
#else
#define BOOST_VMD_SEQ_TO_LIST(seq) \
BOOST_PP_IIF \
( \
BOOST_VMD_IS_EMPTY(seq), \
BOOST_VMD_IDENTITY(BOOST_PP_NIL), \
BOOST_PP_SEQ_TO_LIST \
) \
(seq) \
/**/
#endif
#endif /* BOOST_PP_VARIADICS */
#endif /* BOOST_VMD_SEQ_TO_LIST_HPP */
| gwq5210/litlib | thirdparty/sources/boost_1_60_0/boost/vmd/seq/to_list.hpp | C++ | gpl-3.0 | 1,572 |
<?php
/**
* SimplePie
*
* A PHP-Based RSS and Atom Feed Framework.
* Takes the hard work out of managing a complete RSS/Atom solution.
*
* Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors
* 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 SimplePie Team 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 HOLDERS
* AND 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.
*
* @package SimplePie
* @version 1.3.1
* @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue
* @author Ryan Parman
* @author Geoffrey Sneddon
* @author Ryan McCue
* @link http://simplepie.org/ SimplePie
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
/**
* Used for data cleanup and post-processing
*
*
* This class can be overloaded with {@see SimplePie::set_sanitize_class()}
*
* @package SimplePie
* @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags
*/
class SimplePie_Sanitize
{
// Private vars
var $base;
// Options
var $remove_div = true;
var $image_handler = '';
var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style');
var $encode_instead_of_strip = false;
var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc');
var $strip_comments = false;
var $output_encoding = 'UTF-8';
var $enable_cache = true;
var $cache_location = './cache';
var $cache_name_function = 'md5';
var $timeout = 10;
var $useragent = '';
var $force_fsockopen = false;
var $replace_url_attributes = null;
public function __construct()
{
// Set defaults
$this->set_url_replacements(null);
}
public function remove_div($enable = true)
{
$this->remove_div = (bool) $enable;
}
public function set_image_handler($page = false)
{
if ($page)
{
$this->image_handler = (string) $page;
}
else
{
$this->image_handler = false;
}
}
public function set_registry(SimplePie_Registry $registry)
{
$this->registry = $registry;
}
public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache')
{
if (isset($enable_cache))
{
$this->enable_cache = (bool) $enable_cache;
}
if ($cache_location)
{
$this->cache_location = (string) $cache_location;
}
if ($cache_name_function)
{
$this->cache_name_function = (string) $cache_name_function;
}
}
public function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false)
{
if ($timeout)
{
$this->timeout = (string) $timeout;
}
if ($useragent)
{
$this->useragent = (string) $useragent;
}
if ($force_fsockopen)
{
$this->force_fsockopen = (string) $force_fsockopen;
}
}
public function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'))
{
if ($tags)
{
if (is_array($tags))
{
$this->strip_htmltags = $tags;
}
else
{
$this->strip_htmltags = explode(',', $tags);
}
}
else
{
$this->strip_htmltags = false;
}
}
public function encode_instead_of_strip($encode = false)
{
$this->encode_instead_of_strip = (bool) $encode;
}
public function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'))
{
if ($attribs)
{
if (is_array($attribs))
{
$this->strip_attributes = $attribs;
}
else
{
$this->strip_attributes = explode(',', $attribs);
}
}
else
{
$this->strip_attributes = false;
}
}
public function strip_comments($strip = false)
{
$this->strip_comments = (bool) $strip;
}
public function set_output_encoding($encoding = 'UTF-8')
{
$this->output_encoding = (string) $encoding;
}
/**
* Set element/attribute key/value pairs of HTML attributes
* containing URLs that need to be resolved relative to the feed
*
* Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite,
* |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite,
* |q|@cite
*
* @since 1.0
* @param array|null $element_attribute Element/attribute key/value pairs, null for default
*/
public function set_url_replacements($element_attribute = null)
{
if ($element_attribute === null)
{
$element_attribute = array(
'a' => 'href',
'area' => 'href',
'blockquote' => 'cite',
'del' => 'cite',
'form' => 'action',
'img' => array(
'longdesc',
'src'
),
'input' => 'src',
'ins' => 'cite',
'q' => 'cite'
);
}
$this->replace_url_attributes = (array) $element_attribute;
}
public function sanitize($data, $type, $base = '')
{
$data = trim($data);
if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI)
{
if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML)
{
if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data))
{
$type |= SIMPLEPIE_CONSTRUCT_HTML;
}
else
{
$type |= SIMPLEPIE_CONSTRUCT_TEXT;
}
}
if ($type & SIMPLEPIE_CONSTRUCT_BASE64)
{
$data = base64_decode($data);
}
if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML))
{
if (!class_exists('DOMDocument'))
{
$this->registry->call('Misc', 'error', array('DOMDocument not found, unable to use sanitizer', E_USER_WARNING, __FILE__, __LINE__));
return '';
}
$document = new DOMDocument();
$document->encoding = 'UTF-8';
$data = $this->preprocess($data, $type);
set_error_handler(array('SimplePie_Misc', 'silence_errors'));
$document->loadHTML($data);
restore_error_handler();
// Strip comments
if ($this->strip_comments)
{
$xpath = new DOMXPath($document);
$comments = $xpath->query('//comment()');
foreach ($comments as $comment)
{
$comment->parentNode->removeChild($comment);
}
}
// Strip out HTML tags and attributes that might cause various security problems.
// Based on recommendations by Mark Pilgrim at:
// http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely
if ($this->strip_htmltags)
{
foreach ($this->strip_htmltags as $tag)
{
$this->strip_tag($tag, $document, $type);
}
}
if ($this->strip_attributes)
{
foreach ($this->strip_attributes as $attrib)
{
$this->strip_attr($attrib, $document);
}
}
// Replace relative URLs
$this->base = $base;
foreach ($this->replace_url_attributes as $element => $attributes)
{
$this->replace_urls($document, $element, $attributes);
}
// If image handling (caching, etc.) is enabled, cache and rewrite all the image tags.
if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache)
{
$images = $document->getElementsByTagName('img');
foreach ($images as $img)
{
if ($img->hasAttribute('src'))
{
$image_url = call_user_func($this->cache_name_function, $img->getAttribute('src'));
$cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi'));
if ($cache->load())
{
$img->setAttribute('src', $this->image_handler . $image_url);
}
else
{
$file = $this->registry->create('File', array($img->getAttribute('src'), $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen));
$headers = $file->headers;
if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300)))
{
if ($cache->save(array('headers' => $file->headers, 'body' => $file->body)))
{
$img->setAttribute('src', $this->image_handler . $image_url);
}
else
{
trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
}
}
}
}
}
}
// Remove the DOCTYPE
// Seems to cause segfaulting if we don't do this
if ($document->firstChild instanceof DOMDocumentType)
{
$document->removeChild($document->firstChild);
}
// Move everything from the body to the root
$real_body = $document->getElementsByTagName('body')->item(0)->childNodes->item(0);
$document->replaceChild($real_body, $document->firstChild);
// Finally, convert to a HTML string
$data = trim($document->saveHTML());
if ($this->remove_div)
{
$data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data);
$data = preg_replace('/<\/div>$/', '', $data);
}
else
{
$data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data);
}
}
if ($type & SIMPLEPIE_CONSTRUCT_IRI)
{
$absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base));
if ($absolute !== false)
{
$data = $absolute;
}
}
if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI))
{
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
if ($this->output_encoding !== 'UTF-8')
{
$data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding));
}
}
return $data;
}
protected function preprocess($html, $type)
{
$ret = '';
if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML)
{
// Atom XHTML constructs are wrapped with a div by default
// Note: No protection if $html contains a stray </div>!
$html = '<div>' . $html . '</div>';
$ret .= '<!DOCTYPE html>';
$content_type = 'text/html';
}
else
{
$ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
$content_type = 'application/xhtml+xml';
}
$ret .= '<html><head>';
$ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />';
$ret .= '</head><body>' . $html . '</body></html>';
return $ret;
}
public function replace_urls($document, $tag, $attributes)
{
if (!is_array($attributes))
{
$attributes = array($attributes);
}
if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags))
{
$elements = $document->getElementsByTagName($tag);
foreach ($elements as $element)
{
foreach ($attributes as $attribute)
{
if ($element->hasAttribute($attribute))
{
$value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base));
if ($value !== false)
{
$element->setAttribute($attribute, $value);
}
}
}
}
}
}
public function do_strip_htmltags($match)
{
if ($this->encode_instead_of_strip)
{
if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
$match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8');
$match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8');
return "<$match[1]$match[2]>$match[3]</$match[1]>";
}
else
{
return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8');
}
}
elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style')))
{
return $match[4];
}
else
{
return '';
}
}
protected function strip_tag($tag, $document, $type)
{
$xpath = new DOMXPath($document);
$elements = $xpath->query('body//' . $tag);
if ($this->encode_instead_of_strip)
{
foreach ($elements as $element)
{
$fragment = $document->createDocumentFragment();
// For elements which aren't script or style, include the tag itself
if (!in_array($tag, array('script', 'style')))
{
$text = '<' . $tag;
if ($element->hasAttributes())
{
$attrs = array();
foreach ($element->attributes as $name => $attr)
{
$value = $attr->value;
// In XHTML, empty values should never exist, so we repeat the value
if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML))
{
$value = $name;
}
// For HTML, empty is fine
elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML))
{
$attrs[] = $name;
continue;
}
// Standard attribute text
$attrs[] = $name . '="' . $attr->value . '"';
}
$text .= ' ' . implode(' ', $attrs);
}
$text .= '>';
$fragment->appendChild(new DOMText($text));
}
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--)
{
$child = $element->childNodes->item(0);
$fragment->appendChild($child);
}
if (!in_array($tag, array('script', 'style')))
{
$fragment->appendChild(new DOMText('</' . $tag . '>'));
}
$element->parentNode->replaceChild($fragment, $element);
}
return;
}
elseif (in_array($tag, array('script', 'style')))
{
foreach ($elements as $element)
{
$element->parentNode->removeChild($element);
}
return;
}
else
{
foreach ($elements as $element)
{
$fragment = $document->createDocumentFragment();
$number = $element->childNodes->length;
for ($i = $number; $i > 0; $i--)
{
$child = $element->childNodes->item(0);
$fragment->appendChild($child);
}
$element->parentNode->replaceChild($fragment, $element);
}
}
}
protected function strip_attr($attrib, $document)
{
$xpath = new DOMXPath($document);
$elements = $xpath->query('//*[@' . $attrib . ']');
foreach ($elements as $element)
{
$element->removeAttribute($attrib);
}
}
}
| gdombchik/nabcacatholic | zzz wp-includes ORIG/SimplePie/Sanitize.php | PHP | gpl-2.0 | 15,698 |
<?php
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Constraint that asserts that a string is valid JSON.
*
* @author Sebastian Bergmann <sebastian@phpunit.de>
* @copyright Sebastian Bergmann <sebastian@phpunit.de>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @link http://www.phpunit.de/
* @since Class available since Release 3.7.20
*/
class PHPUnit_Framework_Constraint_IsJson extends PHPUnit_Framework_Constraint
{
/**
* Evaluates the constraint for parameter $other. Returns true if the
* constraint is met, false otherwise.
*
* @param mixed $other Value or object to evaluate.
* @return bool
*/
protected function matches($other)
{
json_decode($other);
if (json_last_error()) {
return false;
}
return true;
}
/**
* Returns the description of the failure
*
* The beginning of failure messages is "Failed asserting that" in most
* cases. This method should return the second part of that sentence.
*
* @param mixed $other Evaluated value or object.
* @return string
*/
protected function failureDescription($other)
{
json_decode($other);
$error = PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider::determineJsonError(
json_last_error()
);
return sprintf(
'%s is valid JSON (%s)',
$this->exporter->shortenedExport($other),
$error
);
}
/**
* Returns a string representation of the constraint.
*
* @return string
*/
public function toString()
{
return 'is valid JSON';
}
}
| ederunt/practicaN | vendor/phpunit/phpunit/src/Framework/Constraint/IsJson.php | PHP | bsd-3-clause | 1,922 |
class Sslyze < Formula
desc "SSL scanner"
homepage "https://github.com/nabla-c0d3/sslyze"
url "https://github.com/nabla-c0d3/sslyze/archive/release-0.11.tar.gz"
sha256 "d0adf9be09d5b27803a923dfabd459c84a2eddb457dac2418f1bf074153f8f93"
version "0.11.0"
bottle do
cellar :any
sha256 "af01a93c9a4b8d8e38c4b03255fd522234fdb24165cdde6b5a910187fa9fa16b" => :yosemite
sha256 "63f3129057130bc335464e64ac4a408947c39f58d04b051a55360644b05bc803" => :mavericks
sha256 "6ef8e398d5ecd7b71e80d8fe113c23acd5be75055bf8253dbb42e2e4a0e825d8" => :mountain_lion
end
depends_on :arch => :x86_64
depends_on :python if MacOS.version <= :snow_leopard
resource "nassl" do
url "https://github.com/nabla-c0d3/nassl/archive/v0.11.tar.gz"
sha256 "83fe1623ad3e67ba01a3e692211e9fde15c6388f5f3d92bd5c0423d4e9e79391"
end
resource "openssl" do
url "https://www.openssl.org/source/openssl-1.0.2a.tar.gz"
sha256 "15b6393c20030aab02c8e2fe0243cb1d1d18062f6c095d67bca91871dc7f324a"
end
resource "zlib" do
url "http://zlib.net/zlib-1.2.8.tar.gz"
sha256 "36658cb768a54c1d4dec43c3116c27ed893e88b02ecfcb44f2166f9c0b7f2a0d"
end
def install
# openssl fails on parallel build. Related issues:
# - http://rt.openssl.org/Ticket/Display.html?id=3736
# - http://rt.openssl.org/Ticket/Display.html?id=3737
ENV.deparallelize
resource("openssl").stage do
(buildpath/"nassl/openssl-1.0.2a").install Dir["*"]
end
resource("zlib").stage do
(buildpath/"nassl/zlib-1.2.8").install Dir["*"]
end
resource("nassl").stage do
(buildpath/"nassl").install Dir["*"]
end
cd "nassl" do
system "python", "buildAll_unix.py"
libexec.install "test/nassl"
end
libexec.install %w[plugins utils sslyze.py xml_out.xsd]
bin.install_symlink libexec/"sslyze.py" => "sslyze"
end
test do
assert_equal "0.11.0", shell_output("#{bin}/sslyze --version").strip
assert_match "SCAN COMPLETED", shell_output("#{bin}/sslyze --regular google.com")
end
end
| Lywangwenbin/homebrew | Library/Formula/sslyze.rb | Ruby | bsd-2-clause | 2,049 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: WebResult.php 24593 2012-01-05 20:35:02Z matthew $
*/
/**
* @see Zend_Service_Yahoo_Result
*/
require_once 'Zend/Service/Yahoo/Result.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Yahoo_WebResult extends Zend_Service_Yahoo_Result
{
/**
* A summary of the result
*
* @var string
*/
public $Summary;
/**
* The file type of the result (text, html, pdf, etc.)
*
* @var string
*/
public $MimeType;
/**
* The modification time of the result (as a unix timestamp)
*
* @var string
*/
public $ModificationDate;
/**
* The URL for the Yahoo cache of this page, if it exists
*
* @var string
*/
public $CacheUrl;
/**
* The size of the cache entry
*
* @var int
*/
public $CacheSize;
/**
* Web result namespace
*
* @var string
*/
protected $_namespace = 'urn:yahoo:srch';
/**
* Initializes the web result
*
* @param DOMElement $result
* @return void
*/
public function __construct(DOMElement $result)
{
$this->_fields = array('Summary', 'MimeType', 'ModificationDate');
parent::__construct($result);
$this->_xpath = new DOMXPath($result->ownerDocument);
$this->_xpath->registerNamespace('yh', $this->_namespace);
// check if the cache section exists
$cacheUrl = $this->_xpath->query('./yh:Cache/yh:Url/text()', $result)->item(0);
if ($cacheUrl instanceof DOMNode)
{
$this->CacheUrl = $cacheUrl->data;
}
$cacheSize = $this->_xpath->query('./yh:Cache/yh:Size/text()', $result)->item(0);
if ($cacheSize instanceof DOMNode)
{
$this->CacheSize = (int) $cacheSize->data;
}
}
}
| mattsimpson/entrada-1x | www-root/core/library/Zend/Service/Yahoo/WebResult.php | PHP | gpl-3.0 | 2,749 |
<?php
_deprecated_file( __FILE__, '4.0', 'Tribe__View_Helpers.php' );
class Tribe__Events__View_Helpers extends Tribe__View_Helpers {}
| pdpfsug/wp_raga10 | wp_raga10/wp-content/plugins/the-events-calendar/vendor/tickets/common/src/deprecated/Tribe__Events__View_Helpers.php | PHP | agpl-3.0 | 136 |
var hat = require('../');
var assert = require('assert');
exports.rack = function () {
var rack = hat.rack(4);
var seen = {};
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]$/));
}
assert.throws(function () {
for (var i = 0; i < 10; i++) rack()
});
};
exports.data = function () {
var rack = hat.rack(64);
var a = rack('a!');
var b = rack("it's a b!")
var c = rack([ 'c', 'c', 'c' ]);
assert.equal(rack.get(a), 'a!');
assert.equal(rack.get(b), "it's a b!");
assert.deepEqual(rack.get(c), [ 'c', 'c', 'c' ]);
assert.equal(rack.hats[a], 'a!');
assert.equal(rack.hats[b], "it's a b!");
assert.deepEqual(rack.hats[c], [ 'c', 'c', 'c' ]);
rack.set(a, 'AAA');
assert.equal(rack.get(a), 'AAA');
};
exports.expandBy = function () {
var rack = hat.rack(4, 16, 4);
var seen = {};
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]$/));
}
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]{1,2}$/));
}
for (var i = 0; i < 8; i++) {
var id = rack();
assert.ok(!seen[id], 'seen this id');
seen[id] = true;
assert.ok(id.match(/^[0-9a-f]{2}$/));
}
};
| hendrikusR/open-layer | widget/assets/draw/hat/test/rack.js | JavaScript | bsd-3-clause | 1,569 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.processor.aggregator;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.processor.aggregate.AggregateController;
import org.apache.camel.processor.aggregate.AggregationStrategy;
import org.apache.camel.processor.aggregate.DefaultAggregateController;
import org.junit.Test;
/**
*
*/
public class AggregateControllerTest extends ContextTestSupport {
private AggregateController controller;
public AggregateController getAggregateController() {
if (controller == null) {
controller = new DefaultAggregateController();
}
return controller;
}
@Test
public void testForceCompletionOfAll() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(2);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3", "test2test4");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfAllGroups();
assertEquals(2, groups);
assertMockEndpointsSatisfied();
}
@Test
public void testForceCompletionOfGroup() throws Exception {
getMockEndpoint("mock:aggregated").expectedMessageCount(0);
template.sendBodyAndHeader("direct:start", "test1", "id", "1");
template.sendBodyAndHeader("direct:start", "test2", "id", "2");
template.sendBodyAndHeader("direct:start", "test3", "id", "1");
template.sendBodyAndHeader("direct:start", "test4", "id", "2");
assertMockEndpointsSatisfied();
getMockEndpoint("mock:aggregated").expectedMessageCount(1);
getMockEndpoint("mock:aggregated").expectedBodiesReceivedInAnyOrder("test1test3");
getMockEndpoint("mock:aggregated").expectedPropertyReceived(Exchange.AGGREGATED_COMPLETED_BY, "force");
int groups = getAggregateController().forceCompletionOfGroup("1");
assertEquals(1, groups);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.aggregate(header("id"), new MyAggregationStrategy()).aggregateController(getAggregateController())
.completionSize(10)
.to("mock:aggregated");
}
};
}
public static class MyAggregationStrategy implements AggregationStrategy {
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
if (oldExchange == null) {
return newExchange;
}
String body1 = oldExchange.getIn().getBody(String.class);
String body2 = newExchange.getIn().getBody(String.class);
oldExchange.getIn().setBody(body1 + body2);
return oldExchange;
}
}
} | CandleCandle/camel | camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateControllerTest.java | Java | apache-2.0 | 4,309 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Feed\Writer\Extension\Threading\Renderer;
use DOMDocument;
use DOMElement;
use Zend\Feed\Writer\Extension;
/**
*/
class Entry extends Extension\AbstractRenderer
{
/**
* Set to TRUE if a rendering method actually renders something. This
* is used to prevent premature appending of a XML namespace declaration
* until an element which requires it is actually appended.
*
* @var bool
*/
protected $called = false;
/**
* Render entry
*
* @return void
*/
public function render()
{
if (strtolower($this->getType()) == 'rss') {
return; // Atom 1.0 only
}
$this->_setCommentLink($this->dom, $this->base);
$this->_setCommentFeedLinks($this->dom, $this->base);
$this->_setCommentCount($this->dom, $this->base);
if ($this->called) {
$this->_appendNamespaces();
}
}
/**
* Append entry namespaces
*
* @return void
*/
protected function _appendNamespaces()
{
$this->getRootElement()->setAttribute('xmlns:thr',
'http://purl.org/syndication/thread/1.0');
}
/**
* Set comment link
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentLink(DOMDocument $dom, DOMElement $root)
{
$link = $this->getDataContainer()->getCommentLink();
if (!$link) {
return;
}
$clink = $this->dom->createElement('link');
$clink->setAttribute('rel', 'replies');
$clink->setAttribute('type', 'text/html');
$clink->setAttribute('href', $link);
$count = $this->getDataContainer()->getCommentCount();
if ($count !== null) {
$clink->setAttribute('thr:count', $count);
}
$root->appendChild($clink);
$this->called = true;
}
/**
* Set comment feed links
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentFeedLinks(DOMDocument $dom, DOMElement $root)
{
$links = $this->getDataContainer()->getCommentFeedLinks();
if (!$links || empty($links)) {
return;
}
foreach ($links as $link) {
$flink = $this->dom->createElement('link');
$flink->setAttribute('rel', 'replies');
$flink->setAttribute('type', 'application/' . $link['type'] . '+xml');
$flink->setAttribute('href', $link['uri']);
$count = $this->getDataContainer()->getCommentCount();
if ($count !== null) {
$flink->setAttribute('thr:count', $count);
}
$root->appendChild($flink);
$this->called = true;
}
}
/**
* Set entry comment count
*
* @param DOMDocument $dom
* @param DOMElement $root
* @return void
*/
protected function _setCommentCount(DOMDocument $dom, DOMElement $root)
{
$count = $this->getDataContainer()->getCommentCount();
if ($count === null) {
return;
}
$tcount = $this->dom->createElement('thr:total');
$tcount->nodeValue = $count;
$root->appendChild($tcount);
$this->called = true;
}
}
| nickopris/musicapp | www/core/vendor/zendframework/zend-feed/Zend/Feed/Writer/Extension/Threading/Renderer/Entry.php | PHP | apache-2.0 | 3,659 |
import {Parser} from "./state"
import {SourceLocation} from "./locutil"
export class Node {
constructor(parser, pos, loc) {
this.type = ""
this.start = pos
this.end = 0
if (parser.options.locations)
this.loc = new SourceLocation(parser, loc)
if (parser.options.directSourceFile)
this.sourceFile = parser.options.directSourceFile
if (parser.options.ranges)
this.range = [pos, 0]
}
}
// Start an AST node, attaching a start offset.
const pp = Parser.prototype
pp.startNode = function() {
return new Node(this, this.start, this.startLoc)
}
pp.startNodeAt = function(pos, loc) {
return new Node(this, pos, loc)
}
// Finish an AST node, adding `type` and `end` properties.
function finishNodeAt(node, type, pos, loc) {
node.type = type
node.end = pos
if (this.options.locations)
node.loc.end = loc
if (this.options.ranges)
node.range[1] = pos
return node
}
pp.finishNode = function(node, type) {
return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
}
// Finish node at given position
pp.finishNodeAt = function(node, type, pos, loc) {
return finishNodeAt.call(this, node, type, pos, loc)
}
| hellokidder/js-studying | 微信小程序/wxtest/node_modules/acorn-jsx/node_modules/acorn/src/node.js | JavaScript | mit | 1,194 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class IgnorePlugin {
constructor(resourceRegExp, contextRegExp) {
this.resourceRegExp = resourceRegExp;
this.contextRegExp = contextRegExp;
this.checkIgnore = this.checkIgnore.bind(this);
}
/*
* Only returns true if a "resourceRegExp" exists
* and the resource given matches the regexp.
*/
checkResource(resource) {
if(!this.resourceRegExp) {
return false;
}
return this.resourceRegExp.test(resource);
}
/*
* Returns true if contextRegExp does not exist
* or if context matches the given regexp.
*/
checkContext(context) {
if(!this.contextRegExp) {
return true;
}
return this.contextRegExp.test(context);
}
/*
* Returns true if result should be ignored.
* false if it shouldn't.
*
* Not that if "contextRegExp" is given, both the "resourceRegExp"
* and "contextRegExp" have to match.
*/
checkResult(result) {
if(!result) {
return true;
}
return this.checkResource(result.request) && this.checkContext(result.context);
}
checkIgnore(result, callback) {
// check if result is ignored
if(this.checkResult(result)) {
return callback();
}
return callback(null, result);
}
apply(compiler) {
compiler.plugin("normal-module-factory", (nmf) => {
nmf.plugin("before-resolve", this.checkIgnore);
});
compiler.plugin("context-module-factory", (cmf) => {
cmf.plugin("before-resolve", this.checkIgnore);
});
}
}
module.exports = IgnorePlugin;
| shikun2014010800/manga | web/console/node_modules/webpack/lib/IgnorePlugin.js | JavaScript | mit | 1,617 |
#!/usr/bin/env python
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
# ansible-vault is a script that encrypts/decrypts YAML files. See
# https://docs.ansible.com/playbooks_vault.html for more details.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import time
import os
def main(args):
path = os.path.abspath(args[1])
fo = open(path, 'r+')
content = fo.readlines()
content.append('faux editor added at %s\n' % time.time())
fo.seek(0)
fo.write(''.join(content))
fo.close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[:]))
| EvanK/ansible | test/integration/targets/vault/faux-editor.py | Python | gpl-3.0 | 1,212 |
package trust
import (
"crypto/x509"
"errors"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"sync"
"time"
"github.com/Sirupsen/logrus"
"github.com/docker/libtrust/trustgraph"
)
type TrustStore struct {
path string
caPool *x509.CertPool
graph trustgraph.TrustGraph
expiration time.Time
fetcher *time.Timer
fetchTime time.Duration
autofetch bool
httpClient *http.Client
baseEndpoints map[string]*url.URL
sync.RWMutex
}
// defaultFetchtime represents the starting duration to wait between
// fetching sections of the graph. Unsuccessful fetches should
// increase time between fetching.
const defaultFetchtime = 45 * time.Second
var baseEndpoints = map[string]string{"official": "https://dvjy3tqbc323p.cloudfront.net/trust/official.json"}
func NewTrustStore(path string) (*TrustStore, error) {
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
// Create base graph url map
endpoints := map[string]*url.URL{}
for name, endpoint := range baseEndpoints {
u, err := url.Parse(endpoint)
if err != nil {
return nil, err
}
endpoints[name] = u
}
// Load grant files
t := &TrustStore{
path: abspath,
caPool: nil,
httpClient: &http.Client{},
fetchTime: time.Millisecond,
baseEndpoints: endpoints,
}
if err := t.reload(); err != nil {
return nil, err
}
return t, nil
}
func (t *TrustStore) reload() error {
t.Lock()
defer t.Unlock()
matches, err := filepath.Glob(filepath.Join(t.path, "*.json"))
if err != nil {
return err
}
statements := make([]*trustgraph.Statement, len(matches))
for i, match := range matches {
f, err := os.Open(match)
if err != nil {
return err
}
statements[i], err = trustgraph.LoadStatement(f, nil)
if err != nil {
f.Close()
return err
}
f.Close()
}
if len(statements) == 0 {
if t.autofetch {
logrus.Debugf("No grants, fetching")
t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
}
return nil
}
grants, expiration, err := trustgraph.CollapseStatements(statements, true)
if err != nil {
return err
}
t.expiration = expiration
t.graph = trustgraph.NewMemoryGraph(grants)
logrus.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration)
if t.autofetch {
nextFetch := expiration.Sub(time.Now())
if nextFetch < 0 {
nextFetch = defaultFetchtime
} else {
nextFetch = time.Duration(0.8 * (float64)(nextFetch))
}
t.fetcher = time.AfterFunc(nextFetch, t.fetch)
}
return nil
}
func (t *TrustStore) fetchBaseGraph(u *url.URL) (*trustgraph.Statement, error) {
req := &http.Request{
Method: "GET",
URL: u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Body: nil,
Host: u.Host,
}
resp, err := t.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode == 404 {
return nil, errors.New("base graph does not exist")
}
defer resp.Body.Close()
return trustgraph.LoadStatement(resp.Body, t.caPool)
}
// fetch retrieves updated base graphs. This function cannot error, it
// should only log errors
func (t *TrustStore) fetch() {
t.Lock()
defer t.Unlock()
if t.autofetch && t.fetcher == nil {
// Do nothing ??
return
}
fetchCount := 0
for bg, ep := range t.baseEndpoints {
statement, err := t.fetchBaseGraph(ep)
if err != nil {
logrus.Infof("Trust graph fetch failed: %s", err)
continue
}
b, err := statement.Bytes()
if err != nil {
logrus.Infof("Bad trust graph statement: %s", err)
continue
}
// TODO check if value differs
if err := ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600); err != nil {
logrus.Infof("Error writing trust graph statement: %s", err)
}
fetchCount++
}
logrus.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now())
if fetchCount > 0 {
go func() {
if err := t.reload(); err != nil {
logrus.Infof("Reload of trust graph failed: %s", err)
}
}()
t.fetchTime = defaultFetchtime
t.fetcher = nil
} else if t.autofetch {
maxTime := 10 * defaultFetchtime
t.fetchTime = time.Duration(1.5 * (float64)(t.fetchTime+time.Second))
if t.fetchTime > maxTime {
t.fetchTime = maxTime
}
t.fetcher = time.AfterFunc(t.fetchTime, t.fetch)
}
}
| rhuss/gofabric8 | vendor/github.com/docker/docker/trust/trusts.go | GO | apache-2.0 | 4,317 |
/*!
* Connect - cookieParser
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('./../utils')
, cookie = require('cookie');
/**
* Cookie parser:
*
* Parse _Cookie_ header and populate `req.cookies`
* with an object keyed by the cookie names. Optionally
* you may enabled signed cookie support by passing
* a `secret` string, which assigns `req.secret` so
* it may be used by other middleware.
*
* Examples:
*
* connect()
* .use(connect.cookieParser('optional secret string'))
* .use(function(req, res, next){
* res.end(JSON.stringify(req.cookies));
* })
*
* @param {String} secret
* @return {Function}
* @api public
*/
module.exports = function cookieParser(secret){
return function cookieParser(req, res, next) {
if (req.cookies) return next();
var cookies = req.headers.cookie;
req.secret = secret;
req.cookies = {};
req.signedCookies = {};
if (cookies) {
try {
req.cookies = cookie.parse(cookies);
if (secret) {
req.signedCookies = utils.parseSignedCookies(req.cookies, secret);
req.signedCookies = utils.parseJSONCookies(req.signedCookies);
}
req.cookies = utils.parseJSONCookies(req.cookies);
} catch (err) {
err.status = 400;
return next(err);
}
}
next();
};
};
| BrowenChen/classroomDashboard | zzishwebsite/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js | JavaScript | mit | 1,440 |
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.datasource;
/**
* Base implementation of {@link DataSubscriber} that ensures that the data source is closed when
* the subscriber has finished with it.
* <p>
* Sample usage:
* <pre>
* <code>
* dataSource.subscribe(
* new BaseDataSubscriber() {
* {@literal @}Override
* public void onNewResultImpl(DataSource dataSource) {
* // Store image ref to be released later.
* mCloseableImageRef = dataSource.getResult();
* // Use the image.
* updateImage(mCloseableImageRef);
* // No need to do any cleanup of the data source.
* }
*
* {@literal @}Override
* public void onFailureImpl(DataSource dataSource) {
* // No cleanup of the data source required here.
* }
* });
* </code>
* </pre>
*/
public abstract class BaseDataSubscriber<T> implements DataSubscriber<T> {
@Override
public void onNewResult(DataSource<T> dataSource) {
try {
onNewResultImpl(dataSource);
} finally {
if (dataSource.isFinished()) {
dataSource.close();
}
}
}
@Override
public void onFailure(DataSource<T> dataSource) {
try {
onFailureImpl(dataSource);
} finally {
dataSource.close();
}
}
@Override
public void onCancellation(DataSource<T> dataSource) {
}
@Override
public void onProgressUpdate(DataSource<T> dataSource) {
}
protected abstract void onNewResultImpl(DataSource<T> dataSource);
protected abstract void onFailureImpl(DataSource<T> dataSource);
}
| ppamorim/fresco | fbcore/src/main/java/com/facebook/datasource/BaseDataSubscriber.java | Java | bsd-3-clause | 1,838 |