code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
// A DOM operation helper. Append an Element to a parent
export default function append(parent, ...children) {
// Always select the first item of a list, similarly to jQuery
if (Array.isArray(parent)) {
parent = parent[0]
}
children.forEach(parent.appendChild, parent)
return parent
}
| vigetlabs/washi | src/append.js | JavaScript | mit | 301 |
///
// Dependencies
///
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import classNames from 'classnames';
import isString from 'lodash/isString';
import * as types from './types';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ExpanderButton from '../elements/ExpanderButton';
import Icon from '../elements/Icon';
import Scrollable from '../elements/Scrollable';
import * as actions from './actions';
import * as formsActions from '../forms/actions';
///
// View
///
class OverviewPanelItemView extends Component {
///
// Construction / Hooks
///
constructor(props) {
super(props);
this.onToggle = this.onToggle.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onShowForm = this.onShowForm.bind(this);
}
///
// Event handling
///
onToggle() {
this.props.toggleItem(this.props.name);
}
onSelect() {
this.props.selectItem(this.props.name);
}
onShowForm() {
this.props.clearForm(this.props.name);
this.props.showForm(this.props.name);
}
///
// Rendering
///
renderIcon(icon) {
if(! icon) return '';
if(isString(icon)) {
icon = (
<Icon name={icon} />
);
}
return (
<div className="item-icon">
{icon}
</div>
);
}
render() {
const isSelected = this.props.selected === this.props.name;
const isExpanded = isSelected || this.props.overview.getIn(
['panels', this.props.name, 'isExpanded']
);
const itemClassName = classNames('overview-panel-item', {
selected: isSelected,
expanded: isExpanded,
});
return (
<div className={itemClassName}>
<div className="item-header">
<ExpanderButton
expanded={isExpanded}
disabled={isSelected}
onClick={this.onToggle}
/>
<h4
className="item-title"
onClick={this.onSelect}
>
{this.renderIcon(this.props.icon)}
{this.props.title}
</h4>
<Button
className="add-button"
onClick={this.onShowForm}
>
<Icon name="plus" />
</Button>
</div>
<Panel
collapsible expanded={isExpanded}
className="item-content"
>
{this.props.notifications}
<Scrollable>
{this.props.children}
</Scrollable>
</Panel>
</div>
);
}
}
OverviewPanelItemView.propTypes = {
name: PropTypes.string.isRequired,
icon: PropTypes.node,
title: PropTypes.node.isRequired,
selected: PropTypes.string,
notifications: PropTypes.node,
overview: types.Overview.isRequired,
toggleItem: PropTypes.func.isRequired,
selectItem: PropTypes.func.isRequired,
clearForm: PropTypes.func.isRequired,
showForm: PropTypes.func.isRequired,
children: PropTypes.node,
};
export { OverviewPanelItemView };
///
// Container
///
function mapStateToProps(state) {
return {
selected: state.getIn(['overview', 'root', 'selected']),
overview: state.get('overview'),
};
}
function mapDispatchToProps(dispatch) {
return {
toggleItem: (name) => dispatch(actions.toggleItem(name)),
selectItem: (name) => dispatch(actions.selectItem(name)),
clearForm: (name) => dispatch(formsActions.clearForm(name)),
showForm: (name) => dispatch(formsActions.showForm(name)),
};
}
const connector = connect(
mapStateToProps,
mapDispatchToProps
);
export default connector(OverviewPanelItemView);
| dash-/netjumpio-tabs-web | src/overview/OverviewPanelItem.js | JavaScript | mit | 3,349 |
/* global moment, angular */
function TimePickerCtrl($scope, $mdDialog, time, autoSwitch, ampm, confirmText, cancelText, $mdMedia) {
var self = this;
this.VIEW_HOURS = 1;
this.VIEW_MINUTES = 2;
this.currentView = this.VIEW_HOURS;
this.time = moment(time);
this.autoSwitch = !!autoSwitch;
this.ampm = !!ampm;
this.confirmText= confirmText ? confirmText :"OK";
this.cancelText= cancelText ? cancelText :"Cancel";
this.hoursFormat = self.ampm ? "h" : "H";
this.minutesFormat = "mm";
this.clockHours = parseInt(this.time.format(this.hoursFormat));
this.clockMinutes = parseInt(this.time.format(this.minutesFormat));
$scope.$mdMedia = $mdMedia;
this.switchView = function() {
self.currentView = self.currentView == self.VIEW_HOURS ? self.VIEW_MINUTES : self.VIEW_HOURS;
};
this.setAM = function() {
if(self.time.hours() >= 12)
self.time.hour(self.time.hour() - 12);
};
this.setPM = function() {
if(self.time.hours() < 12)
self.time.hour(self.time.hour() + 12);
};
this.cancel = function() {
$mdDialog.cancel();
};
this.confirm = function() {
$mdDialog.hide(this.time.toDate());
};
}
function ClockCtrl($scope) {
var TYPE_HOURS = "hours";
var TYPE_MINUTES = "minutes";
var self = this;
this.STEP_DEG = 360 / 12;
this.steps = [];
this.CLOCK_TYPES = {
"hours": {
range: self.ampm ? 12 : 24,
},
"minutes": {
range: 60,
}
}
this.getPointerStyle = function() {
var divider = 1;
switch(self.type) {
case TYPE_HOURS:
divider = self.ampm ? 12 : 24;
break;
case TYPE_MINUTES:
divider = 60;
break;
}
var degrees = Math.round(self.selected * (360 / divider)) - 180;
return {
"-webkit-transform": "rotate(" + degrees + "deg)",
"-ms-transform": "rotate(" + degrees + "deg)",
"transform": "rotate(" + degrees + "deg)"
}
};
this.setTimeByDeg = function(deg) {
deg = deg >= 360 ? 0 : deg;
var divider = 0;
switch(self.type) {
case TYPE_HOURS:
divider = self.ampm ? 12 : 24;
break;
case TYPE_MINUTES:
divider = 60;
break;
}
self.setTime(
Math.round(divider / 360 * deg)
);
};
this.setTime = function(time, type) {
this.selected = time;
switch(self.type) {
case TYPE_HOURS:
if(self.ampm && self.time.format("A") == "PM") time += 12;
this.time.hours(time);
break;
case TYPE_MINUTES:
if(time > 59) time -= 60;
this.time.minutes(time);
break;
}
};
this.init = function() {
self.type = self.type || "hours";
switch(self.type) {
case TYPE_HOURS:
var f = self.ampm ? 1 : 2;
var t = self.ampm ? 12 : 23;
for(var i = f; i <= t; i+=f)
self.steps.push(i);
if (!self.ampm) self.steps.push(0);
self.selected = self.time.hours() || 0;
if(self.ampm && self.selected > 12) self.selected -= 12;
break;
case TYPE_MINUTES:
for(var i = 5; i <= 55; i+=5)
self.steps.push(i);
self.steps.push(0);
self.selected = self.time.minutes() || 0;
break;
}
};
this.init();
}
module.directive("mdpClock", ["$animate", "$timeout", function($animate, $timeout) {
return {
restrict: 'E',
bindToController: {
'type': '@?',
'time': '=',
'autoSwitch': '=?',
'ampm': '=?'
},
replace: true,
template: '<div class="mdp-clock">' +
'<div class="mdp-clock-container">' +
'<md-toolbar class="mdp-clock-center md-primary"></md-toolbar>' +
'<md-toolbar ng-style="clock.getPointerStyle()" class="mdp-pointer md-primary">' +
'<span class="mdp-clock-selected md-button md-raised md-primary"></span>' +
'</md-toolbar>' +
'<md-button ng-class="{ \'md-primary\': clock.selected == step }" class="md-icon-button md-raised mdp-clock-deg{{ ::(clock.STEP_DEG * ($index + 1)) }}" ng-repeat="step in clock.steps" ng-click="clock.setTime(step)">{{ step }}</md-button>' +
'</div>' +
'</div>',
controller: ["$scope", ClockCtrl],
controllerAs: "clock",
link: function(scope, element, attrs, ctrl) {
var pointer = angular.element(element[0].querySelector(".mdp-pointer")),
timepickerCtrl = scope.$parent.timepicker;
var onEvent = function(event) {
var containerCoords = event.currentTarget.getClientRects()[0];
var x = ((event.currentTarget.offsetWidth / 2) - (event.pageX - containerCoords.left)),
y = ((event.pageY - containerCoords.top) - (event.currentTarget.offsetHeight / 2));
var deg = Math.round((Math.atan2(x, y) * (180 / Math.PI)));
$timeout(function() {
ctrl.setTimeByDeg(deg + 180);
if(ctrl.autoSwitch && ["mouseup", "click"].indexOf(event.type) !== -1 && timepickerCtrl) timepickerCtrl.switchView();
});
};
element.on("mousedown", function() {
element.on("mousemove", onEvent);
});
element.on("mouseup", function(e) {
element.off("mousemove");
});
element.on("click", onEvent);
scope.$on("$destroy", function() {
element.off("click", onEvent);
element.off("mousemove", onEvent);
});
}
}
}]);
module.provider("$mdpTimePicker", function() {
this.$get = ["$mdDialog", function($mdDialog) {
var timePicker = function(time, options) {
if(!angular.isDate(time)) time = Date.now();
if (!angular.isObject(options)) options = {};
return $mdDialog.show({
controller: ['$scope', '$mdDialog', 'time', 'autoSwitch', 'ampm', 'confirmText', 'cancelText', '$mdMedia', TimePickerCtrl],
controllerAs: 'timepicker',
clickOutsideToClose: true,
template: '<md-dialog aria-label="" class="mdp-timepicker" ng-class="{ \'portrait\': !$mdMedia(\'gt-xs\') }">' +
'<md-dialog-content layout-gt-xs="row" layout-wrap>' +
'<md-toolbar layout-gt-xs="column" layout-xs="row" layout-align="center center" flex class="mdp-timepicker-time md-hue-1 md-primary">' +
'<div class="mdp-timepicker-selected-time">' +
'<span ng-class="{ \'active\': timepicker.currentView == timepicker.VIEW_HOURS }" ng-click="timepicker.currentView = timepicker.VIEW_HOURS">{{ timepicker.time.format(timepicker.hoursFormat) }}</span>:' +
'<span ng-class="{ \'active\': timepicker.currentView == timepicker.VIEW_MINUTES }" ng-click="timepicker.currentView = timepicker.VIEW_MINUTES">{{ timepicker.time.format(timepicker.minutesFormat) }}</span>' +
'</div>' +
'<div layout="column" ng-show="timepicker.ampm" class="mdp-timepicker-selected-ampm">' +
'<span ng-click="timepicker.setAM()" ng-class="{ \'active\': timepicker.time.hours() < 12 }">AM</span>' +
'<span ng-click="timepicker.setPM()" ng-class="{ \'active\': timepicker.time.hours() >= 12 }">PM</span>' +
'</div>' +
'</md-toolbar>' +
'<div>' +
'<div class="mdp-clock-switch-container" ng-switch="timepicker.currentView" layout layout-align="center center">' +
'<mdp-clock class="mdp-animation-zoom" ampm="timepicker.ampm" auto-switch="timepicker.autoSwitch" time="timepicker.time" type="hours" ng-switch-when="1"></mdp-clock>' +
'<mdp-clock class="mdp-animation-zoom" ampm="timepicker.ampm" auto-switch="timepicker.autoSwitch" time="timepicker.time" type="minutes" ng-switch-when="2"></mdp-clock>' +
'</div>' +
'<md-dialog-actions layout="row">' +
'<span flex></span>' +
'<md-button ng-click="timepicker.cancel()" aria-label="{{timepicker.cancelText}}">{{timepicker.cancelText}}</md-button>' +
'<md-button ng-click="timepicker.confirm()" class="md-primary" aria-label="{{timepicker.confirmText}}">{{timepicker.confirmText}}</md-button>' +
'</md-dialog-actions>' +
'</div>' +
'</md-dialog-content>' +
'</md-dialog>',
targetEvent: options.targetEvent,
locals: {
time: time,
autoSwitch: options.autoSwitch,
ampm: options.ampm,
confirmText: options.confirmText,
cancelText: options.cancelText
},
skipHide: true
});
};
return timePicker;
}];
});
module.directive("mdpTimePicker", ["$mdpTimePicker", "$timeout", function($mdpTimePicker, $timeout) {
return {
restrict: 'E',
require: 'ngModel',
transclude: true,
template: function(element, attrs) {
var noFloat = angular.isDefined(attrs.mdpNoFloat),
placeholder = angular.isDefined(attrs.mdpPlaceholder) ? attrs.mdpPlaceholder : "",
openOnClick = angular.isDefined(attrs.mdpOpenOnClick) ? true : false;
return '<div layout layout-align="start start">' +
'<md-button class="md-icon-button" ng-click="showPicker($event)"' + (angular.isDefined(attrs.mdpDisabled) ? ' ng-disabled="disabled"' : '') + '>' +
'<md-icon md-svg-icon="mdp-access-time"></md-icon>' +
'</md-button>' +
'<md-input-container' + (noFloat ? ' md-no-float' : '') + ' md-is-error="isError()">' +
'<input type="{{ ::type }}"' + (angular.isDefined(attrs.mdpDisabled) ? ' ng-disabled="disabled"' : '') + ' aria-label="' + placeholder + '" placeholder="' + placeholder + '"' + (openOnClick ? ' ng-click="showPicker($event)" ' : '') + ' />' +
'</md-input-container>' +
'</div>';
},
scope: {
"timeFormat": "@mdpFormat",
"placeholder": "@mdpPlaceholder",
"autoSwitch": "=?mdpAutoSwitch",
"disabled": "=?mdpDisabled",
"ampm": "=?mdpAmpm",
"confirmText": "@mdpConfirmText",
"cancelText": "@mdpCancelText"
},
link: function(scope, element, attrs, ngModel, $transclude) {
var inputElement = angular.element(element[0].querySelector('input')),
inputContainer = angular.element(element[0].querySelector('md-input-container')),
inputContainerCtrl = inputContainer.controller("mdInputContainer");
$transclude(function(clone) {
inputContainer.append(clone);
});
var messages = angular.element(inputContainer[0].querySelector("[ng-messages]"));
scope.type = scope.timeFormat ? "text" : "time"
scope.timeFormat = scope.timeFormat || "HH:mm";
scope.autoSwitch = scope.autoSwitch || false;
scope.confirmText= scope.confirmText ? scope.confirmText :"OK";
scope.cancelText= scope.cancelText ? scope.cancelText :"Cancel";
scope.$watch(function() { return ngModel.$error }, function(newValue, oldValue) {
inputContainerCtrl.setInvalid(!ngModel.$pristine && !!Object.keys(ngModel.$error).length);
}, true);
// update input element if model has changed
ngModel.$formatters.unshift(function(value) {
var time = angular.isDate(value) && moment(value);
if(time && time.isValid())
updateInputElement(time.format(scope.timeFormat));
else
updateInputElement(null);
});
ngModel.$validators.format = function(modelValue, viewValue) {
return !viewValue || angular.isDate(viewValue) || moment(viewValue, scope.timeFormat, true).isValid();
};
ngModel.$validators.required = function(modelValue, viewValue) {
return angular.isUndefined(attrs.required) || !ngModel.$isEmpty(modelValue) || !ngModel.$isEmpty(viewValue);
};
ngModel.$parsers.unshift(function(value) {
var parsed = moment(value, scope.timeFormat, true);
if(parsed.isValid()) {
if(angular.isDate(ngModel.$modelValue)) {
var originalModel = moment(ngModel.$modelValue);
originalModel.minutes(parsed.minutes());
originalModel.hours(parsed.hours());
originalModel.seconds(parsed.seconds());
parsed = originalModel;
}
return parsed.toDate();
} else
return null;
});
// update input element value
function updateInputElement(value) {
inputElement[0].value = value;
inputContainerCtrl.setHasValue(!ngModel.$isEmpty(value));
}
function updateTime(time) {
var value = moment(time, angular.isDate(time) ? null : scope.timeFormat, true),
strValue = value.format(scope.timeFormat);
if(value.isValid()) {
updateInputElement(strValue);
ngModel.$setViewValue(strValue);
} else {
updateInputElement(time);
ngModel.$setViewValue(time);
}
if(!ngModel.$pristine &&
messages.hasClass("md-auto-hide") &&
inputContainer.hasClass("md-input-invalid")) messages.removeClass("md-auto-hide");
ngModel.$render();
}
scope.showPicker = function(ev) {
$mdpTimePicker(ngModel.$modelValue, {
targetEvent: ev,
autoSwitch: scope.autoSwitch,
ampm: scope.ampm,
confirmText: scope.confirmText,
cancelText: scope.cancelText
}).then(function(time) {
updateTime(time, true);
});
};
function onInputElementEvents(event) {
if(event.target.value !== ngModel.$viewVaue)
updateTime(event.target.value);
}
inputElement.on("reset input blur", onInputElementEvents);
scope.$on("$destroy", function() {
inputElement.off("reset input blur", onInputElementEvents);
})
}
};
}]);
module.directive("mdpTimePicker", ["$mdpTimePicker", "$timeout", function($mdpTimePicker, $timeout) {
return {
restrict: 'A',
require: 'ngModel',
scope: {
"timeFormat": "@mdpFormat",
"autoSwitch": "=?mdpAutoSwitch",
"ampm": "=?mdpAmpm",
"confirmText": "@mdpConfirmText",
"cancelText": "@mdpCancelText"
},
link: function(scope, element, attrs, ngModel, $transclude) {
scope.format = scope.format || "HH:mm";
scope.confirmText= scope.confirmText;
scope.cancelText= scope.cancelText;
function showPicker(ev) {
$mdpTimePicker(ngModel.$modelValue, {
targetEvent: ev,
autoSwitch: scope.autoSwitch,
ampm: scope.ampm,
confirmText: scope.confirmText,
cancelText: scope.cancelText
}).then(function(time) {
ngModel.$setViewValue(moment(time).format(scope.format));
ngModel.$render();
});
};
element.on("click", showPicker);
scope.$on("$destroy", function() {
element.off("click", showPicker);
});
}
}
}]);
| mpicciolli/angular-material-picker | src/components/mdpTimePicker/mdpTimePicker.js | JavaScript | mit | 17,544 |
"use strict";
// Mail Body Parser
var logger = require('./logger');
var Header = require('./mailheader').Header;
var utils = require('./utils');
var events = require('events');
var util = require('util');
var Iconv = require('./mailheader').Iconv;
var attstr = require('./attachment_stream');
var buf_siz = 65536;
function Body (header, options) {
this.header = header || new Header();
this.header_lines = [];
this.is_html = false;
this.options = options || {};
this.bodytext = '';
this.body_text_encoded = '';
this.children = []; // if multipart
this.state = 'start';
this.buf = new Buffer(buf_siz);
this.buf_fill = 0;
}
util.inherits(Body, events.EventEmitter);
exports.Body = Body;
Body.prototype.parse_more = function (line) {
return this["parse_" + this.state](line);
}
Body.prototype.parse_child = function (line) {
// check for MIME boundary
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
line = this.children[this.children.length -1].parse_end(line);
if (this.children[this.children.length -1].state === 'attachment') {
var child = this.children[this.children.length - 1];
if (child.buf_fill > 0) {
// see below for why we create a new buffer here.
var to_emit = new Buffer(child.buf_fill);
child.buf.copy(to_emit, 0, 0, child.buf_fill);
child.attachment_stream.emit_data(to_emit);
}
child.attachment_stream.emit('end');
}
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
this.state = 'end';
}
else {
var bod = new Body(new Header(), this.options);
this.listeners('attachment_start').forEach(function (cb) { bod.on('attachment_start', cb) });
this.listeners('attachment_data' ).forEach(function (cb) { bod.on('attachment_data', cb) });
this.listeners('attachment_end' ).forEach(function (cb) { bod.on('attachment_end', cb) });
this.children.push(bod);
bod.state = 'headers';
}
return line;
}
// Pass data into last child
return this.children[this.children.length - 1].parse_more(line);
}
Body.prototype.parse_headers = function (line) {
if (/^\s*$/.test(line)) {
// end of headers
this.header.parse(this.header_lines);
delete this.header_lines;
this.state = 'start';
}
else {
this.header_lines.push(line);
}
return line;
}
Body.prototype.parse_start = function (line) {
var ct = this.header.get_decoded('content-type') || 'text/plain';
var enc = this.header.get_decoded('content-transfer-encoding') || '8bit';
var cd = this.header.get_decoded('content-disposition') || '';
if (/text\/html/i.test(ct)) {
this.is_html = true;
}
enc = enc.toLowerCase().split("\n").pop().trim();
if (!enc.match(/^base64|quoted-printable|[78]bit$/i)) {
logger.logerror("Invalid CTE on email: " + enc + ", using 8bit");
enc = '8bit';
}
enc = enc.replace(/^quoted-printable$/i, 'qp');
this.decode_function = this["decode_" + enc];
if (!this.decode_function) {
logger.logerror("No decode function found for: " + enc);
this.decode_function = this.decode_8bit;
}
this.ct = ct;
if (/^(?:text|message)\//i.test(ct) && !/^attachment/i.test(cd) ) {
this.state = 'body';
}
else if (/^multipart\//i.test(ct)) {
var match = ct.match(/boundary\s*=\s*["']?([^"';]+)["']?/i);
this.boundary = match ? match[1] : '';
this.state = 'multipart_preamble';
}
else {
var match = cd.match(/name\s*=\s*["']?([^'";]+)["']?/i);
if (!match) {
match = ct.match(/name\s*=\s*["']?([^'";]+)["']?/i);
}
var filename = match ? match[1] : '';
this.attachment_stream = attstr.createStream();
this.emit('attachment_start', ct, filename, this, this.attachment_stream);
this.buf_fill = 0;
this.state = 'attachment';
}
return this["parse_" + this.state](line);
}
function _get_html_insert_position (buf) {
// TODO: consider re-writing this to go backwards from the end
for (var i=0,l=buf.length; i<l; i++) {
if (buf[i] === 60 && buf[i+1] === 47) { // found: "</"
if ( (buf[i+2] === 98 || buf[i+2] === 66) && // "b" or "B"
(buf[i+3] === 111 || buf[i+3] === 79) && // "o" or "O"
(buf[i+4] === 100 || buf[i+4] === 68) && // "d" or "D"
(buf[i+5] === 121 || buf[i+5] === 89) && // "y" or "Y"
buf[i+6] === 62)
{
// matched </body>
return i;
}
if ( (buf[i+2] === 104 || buf[i+2] === 72) && // "h" or "H"
(buf[i+3] === 116 || buf[i+3] === 84) && // "t" or "T"
(buf[i+4] === 109 || buf[i+4] === 77) && // "m" or "M"
(buf[i+5] === 108 || buf[i+5] === 76) && // "l" or "L"
buf[i+6] === 62)
{
// matched </html>
return i;
}
}
}
return buf.length - 1; // default is at the end
}
Body.prototype.parse_end = function (line) {
if (!line) {
line = '';
}
// ignore these lines - but we could store somewhere I guess.
if (this.body_text_encoded.length && this.bodytext.length === 0) {
var buf = this.decode_function(this.body_text_encoded);
var ct = this.header.get_decoded('content-type') || 'text/plain';
var enc = 'UTF-8';
var matches = /\bcharset\s*=\s*(?:\"|3D|')?([\w_\-]*)(?:\"|3D|')?/.exec(ct);
if (matches) {
enc = matches[1];
}
this.body_encoding = enc;
if (this.options.banner && /^text\//i.test(ct)) {
// up until this point we've returned '' for line, so now we insert
// the banner and return the whole lot as one line, re-encoded using
// whatever encoding scheme we had to use to decode it in the first
// place.
// First we convert the banner to the same encoding as the body
var banner_str = this.options.banner[this.is_html ? 1 : 0];
var banner_buf = null;
if (Iconv) {
try {
var converter = new Iconv("UTF-8", enc + "//IGNORE");
banner_buf = converter.convert(banner_str);
}
catch (err) {
logger.logerror("iconv conversion of banner to " + enc + " failed: " + err);
}
}
if (!banner_buf) {
banner_buf = new Buffer(banner_str);
}
// Allocate a new buffer: (6 or 1 is <p>...</p> vs \n...\n - correct that if you change those!)
var new_buf = new Buffer(buf.length + banner_buf.length + (this.is_html ? 6 : 1));
// Now we find where to insert it and combine it with the original buf:
if (this.is_html) {
var insert_pos = _get_html_insert_position(buf);
// copy start of buf into new_buf
buf.copy(new_buf, 0, 0, insert_pos);
// add in <p>
new_buf[insert_pos++] = 60;
new_buf[insert_pos++] = 80;
new_buf[insert_pos++] = 62;
// copy all of banner into new_buf
banner_buf.copy(new_buf, insert_pos);
new_buf[banner_buf.length + insert_pos++] = 60;
new_buf[banner_buf.length + insert_pos++] = 47;
new_buf[banner_buf.length + insert_pos++] = 80;
new_buf[banner_buf.length + insert_pos++] = 62;
// copy remainder of buf into new_buf, if there is buf remaining
if (buf.length > (insert_pos - 6)) {
buf.copy(new_buf, insert_pos + banner_buf.length, insert_pos - 7);
}
}
else {
buf.copy(new_buf);
new_buf[buf.length] = 10; // \n
banner_buf.copy(new_buf, buf.length + 1);
new_buf[buf.length + banner_buf.length + 1] = 10; // \n
}
// Now convert back to base_64 or QP if required:
if (this.decode_function === this.decode_qp) {
line = utils.encode_qp(new_buf.toString("binary")) + "\n" + line;
}
else if (this.decode_function === this.decode_base64) {
line = new_buf.toString("base64").replace(/(.{1,76})/g, "$1\n") + line;
}
else {
line = new_buf.toString("binary") + line; // "binary" is deprecated, lets hope this works...
}
}
// Now convert the buffer to UTF-8 to store in this.bodytext
if (Iconv) {
if (/UTF-?8/i.test(enc)) {
this.bodytext = buf.toString();
}
else {
try {
var converter = new Iconv(enc, "UTF-8");
this.bodytext = converter.convert(buf).toString();
}
catch (err) {
logger.logerror("iconv conversion from " + enc + " to UTF-8 failed: " + err);
this.body_encoding = 'broken//' + enc;
this.bodytext = buf.toString();
}
}
}
else {
this.body_encoding = 'no_iconv';
this.bodytext = buf.toString();
}
// delete this.body_text_encoded;
}
return line;
}
Body.prototype.parse_body = function (line) {
this.body_text_encoded += line;
if (this.options.banner)
return '';
return line;
}
Body.prototype.parse_multipart_preamble = function (line) {
if (this.boundary) {
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
}
else {
// next section
var bod = new Body(new Header(), this.options);
this.listeners('attachment_start').forEach(function (cb) { bod.on('attachment_start', cb) });
this.children.push(bod);
bod.state = 'headers';
this.state = 'child';
}
return line;
}
}
this.body_text_encoded += line;
return line;
}
Body.prototype.parse_attachment = function (line) {
if (this.boundary) {
if (line.substr(0, (this.boundary.length + 2)) === ('--' + this.boundary)) {
if (line.substr(this.boundary.length + 2, 2) === '--') {
// end
}
else {
// next section
this.state = 'headers';
}
return line;
}
}
var buf = this.decode_function(line);
if ((buf.length + this.buf_fill) > buf_siz) {
// now we have to create a new buffer, because if we write this out
// using async code, it will get overwritten under us. Creating a new
// buffer eliminates that problem (at the expense of a malloc and a
// memcpy())
var to_emit = new Buffer(this.buf_fill);
this.buf.copy(to_emit, 0, 0, this.buf_fill);
this.attachment_stream.emit_data(to_emit);
if (buf.length > buf_siz) {
// this is an unusual case - the base64/whatever data is larger
// than our buffer size, so we just emit it and reset the counter.
this.attachment_stream.emit_data(buf);
this.buf_fill = 0;
}
else {
buf.copy(this.buf);
this.buf_fill = buf.length;
}
}
else {
buf.copy(this.buf, this.buf_fill);
this.buf_fill += buf.length;
}
return line;
}
Body.prototype.decode_qp = utils.decode_qp;
Body.prototype.decode_base64 = function (line) {
return new Buffer(line, "base64");
}
Body.prototype.decode_8bit = function (line) {
return new Buffer(line);
}
Body.prototype.decode_7bit = Body.prototype.decode_8bit;
| z9g/Haraka | mailbody.js | JavaScript | mit | 12,345 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M19.5 3.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2v20l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5zM19 19.09H5V4.91h14v14.18zM6 15h12v2H6zm0-4h12v2H6zm0-4h12v2H6z"
}), 'ReceiptOutlined'); | AlloyTeam/Nuclear | components/icon/esm/receipt-outlined.js | JavaScript | mit | 387 |
'use strict';
/* App Module */
var granuleApp = angular.module('granuleApp', [ 'ngRoute', 'angularBasicAuth', 'granuleControllers', 'granuleServices']);
granuleApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'partials/login.html',
controller: 'LoginCtrl'
}).
when('/activity', {
templateUrl: 'partials/activity-list.html',
controller: 'ActivityListCtrl'
}).
when('/activity/:activityId', {
templateUrl: 'partials/activity-detail.html',
controller: 'ActivityDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
}]); | mr-robot/granule | plate/app/js/app.js | JavaScript | mit | 684 |
import * as lamb from "../..";
import { nonFunctions, wannabeEmptyArrays } from "../../__tests__/commons";
describe("count / countBy", function () {
var getCity = lamb.getKey("city");
var persons = [
{ name: "Jane", surname: "Doe", age: 12, city: "New York" },
{ name: "John", surname: "Doe", age: 40, city: "New York" },
{ name: "Mario", surname: "Rossi", age: 18, city: "Rome" },
{ name: "Paolo", surname: "Bianchi", age: 15 }
];
var personsCityCount = {
"New York": 2,
Rome: 1,
undefined: 1
};
var personsAgeGroupCount = {
under20: 3,
over20: 1
};
var splitByAgeGroup = function (person, idx, list) {
expect(list).toBe(persons);
expect(persons[idx]).toBe(person);
return person.age > 20 ? "over20" : "under20";
};
it("should count the occurences of the key generated by the provided iteratee", function () {
expect(lamb.count(persons, getCity)).toEqual(personsCityCount);
expect(lamb.countBy(getCity)(persons)).toEqual(personsCityCount);
expect(lamb.count(persons, splitByAgeGroup)).toEqual(personsAgeGroupCount);
expect(lamb.countBy(splitByAgeGroup)(persons)).toEqual(personsAgeGroupCount);
});
it("should work with array-like objects", function () {
var result = {
h: 1, e: 1, l: 3, o: 2, " ": 1, w: 1, r: 1, d: 1
};
expect(lamb.count("hello world", lamb.identity)).toEqual(result);
expect(lamb.countBy(lamb.identity)("hello world")).toEqual(result);
});
it("should throw an exception if the iteratee isn't a function", function () {
nonFunctions.forEach(function (value) {
expect(function () { lamb.count(persons, value); }).toThrow();
expect(function () { lamb.countBy(value)(persons); }).toThrow();
});
expect(function () { lamb.count(persons); }).toThrow();
expect(function () { lamb.countBy()(persons); }).toThrow();
});
it("should consider deleted or unassigned indexes in sparse arrays as `undefined` values", function () {
var arr = [1, , 3, void 0, 5]; // eslint-disable-line no-sparse-arrays
var result = { false: 3, true: 2 };
expect(lamb.count(arr, lamb.isUndefined)).toEqual(result);
expect(lamb.countBy(lamb.isUndefined)(arr)).toEqual(result);
});
it("should throw an exception if called without the data argument", function () {
expect(lamb.count).toThrow();
expect(lamb.countBy(lamb.identity)).toThrow();
});
it("should throw an exception if supplied with `null` or `undefined`", function () {
expect(function () { lamb.count(null, lamb.identity); }).toThrow();
expect(function () { lamb.count(void 0, lamb.identity); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(null); }).toThrow();
expect(function () { lamb.countBy(lamb.identity)(void 0); }).toThrow();
});
it("should treat every other value as an empty array and return an empty object", function () {
wannabeEmptyArrays.forEach(function (value) {
expect(lamb.countBy(lamb.identity)(value)).toEqual({});
expect(lamb.count(value, lamb.identity)).toEqual({});
});
});
});
| ascartabelli/lamb | src/array/__tests__/count.spec.js | JavaScript | mit | 3,319 |
import React from 'react';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
// import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
export default class NewTaskDialog extends React.Component {
state = {
open: false,
valid: false,
title: '',
description: ''
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.resetDialog();
this.setState({open: false});
};
resetDialog = () => {
this.setState({title: '', description: '', valid: false})
};
handleCreateTask = (e) => {
e.preventDefault();
this.props.onCreateTask({
title: this.state.title,
description: this.state.description
});
this.handleClose();
};
onTitleChange = (e) => {
this.setState({ title: e.target.value });
this.validate();
};
onDescriptionChange = (e) => {
this.setState({ description: e.target.value });
this.validate();
};
validate = () => {
if(this.state.title && this.state.description) {
this.setState({valid: true});
}
};
render() {
const actions = [
<FlatButton
label="Cancel"
primary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Create Task"
primary={true}
disabled={!this.state.valid}
onTouchTap={this.handleCreateTask}
/>,
];
return (
<div>
<FlatButton label="New Task" onTouchTap={this.handleOpen} />
<Dialog
title="Create New Task"
actions={actions}
modal={true}
open={this.state.open}>
<TextField id="task-title"
hintText="Title"
value={this.state.title}
onChange={this.onTitleChange}/>
<br/>
<TextField id="task-description"
hintText="Description"
value={this.state.description}
onChange={this.onDescriptionChange}/>
<br/>
</Dialog>
</div>
);
}
} | zednis/parsnip | src/components/NewTaskDialog.js | JavaScript | mit | 2,527 |
/* eslint key-spacing : 0 */
const EventEmitter = require('events');
class CAS extends EventEmitter {
constructor() {
super();
this.timeout = {
encode_ignition : null,
};
} // constructor()
// [0x130] Ignition status
decode_ignition(data) {
data.command = 'bro';
let new_level_name;
// Save previous ignition status
const previous_level = status.vehicle.ignition_level;
// Set ignition status value
update.status('vehicle.ignition_level', data.msg[0], false);
switch (data.msg[0]) {
case 0x00 : new_level_name = 'off'; break;
case 0x40 : // Whilst just beginning to turn the key
case 0x41 : new_level_name = 'accessory'; break;
case 0x45 : new_level_name = 'run'; break;
case 0x55 : new_level_name = 'start'; break;
default : new_level_name = 'unknown';
}
update.status('vehicle.ignition', new_level_name, false);
if (data.msg[0] > previous_level) { // Ignition going up
switch (data.msg[0]) { // Evaluate new ignition state
case 0x40 :
case 0x41 : { // Accessory
log.module('Powerup state');
break;
}
case 0x45 : { // Run
log.module('Run state');
// Perform KOMBI gauge sweep, if enabled
KOMBI.gauge_sweep();
break;
}
case 0x55 : { // Start
switch (previous_level) {
case 0x00 : { // If the accessory (1) ignition message wasn't caught
log.module('Powerup state');
break;
}
case 0x45 : { // If the run (3) ignition message wasn't caught
log.module('Run state');
break;
}
default : {
log.module('Start-begin state');
}
}
}
}
}
else if (data.msg[0] < previous_level) { // Ignition going down
switch (data.msg[0]) { // Evaluate new ignition state
case 0x00 : { // Off
// If the accessory (1) ignition message wasn't caught
if (previous_level === 0x45) {
log.module('Powerdown state');
}
log.module('Poweroff state');
break;
}
case 0x40 :
case 0x41 : { // Accessory
log.module('Powerdown state');
break;
}
case 0x45 : { // Run
log.module('Start-end state');
}
}
}
data.value = 'ignition status: ' + status.vehicle.ignition;
return data;
} // decode_ignition(data)
// Ignition status
encode_ignition(action) {
// Bounce if not enabled
if (config.emulate.cas !== true) return;
// Handle setting/unsetting timeout
switch (action) {
case false : {
// Return here if timeout is already null
if (this.timeout.encode_ignition !== null) {
clearTimeout(this.timeout.encode_ignition);
this.timeout.encode_ignition = null;
log.module('Unset ignition status timeout');
}
// Send ignition off message
bus.data.send({
bus : config.cas.can_intf,
id : 0x12F,
data : Buffer.from([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ]),
});
// Return here since we're not re-sending again
return;
}
case true : {
if (this.timeout.encode_ignition === null) {
log.module('Set ignition status timeout');
}
this.timeout.encode_ignition = setTimeout(this.encode_ignition, 100);
}
}
const msg = {
bus : config.cas.can_intf,
};
switch (config.cas.generation.toLowerCase()) {
case 'exx' : { // CIC
msg.id = 0x4F8;
msg.data = [ 0x00, 0x42, 0xFE, 0x01, 0xFF, 0xFF, 0xFF, 0xFF ];
break;
}
case 'fxx' : { // NBT
msg.id = 0x12F;
msg.data = [ 0x37, 0x7C, 0x8A, 0xDD, 0xD4, 0x05, 0x33, 0x6B ];
break;
}
default : {
log.error('config.cas.generation must be set to one of Exx or Fxx');
return;
}
}
// Convert data array to Buffer
msg.data = Buffer.from(msg.data);
// Send message
bus.data.send(msg);
} // encode_ignition(action)
// Broadcast: Key fob status
// [0x23A] Decode a key fob bitmask message, and act upon the results
decode_status_keyfob(data) {
data.command = 'bro';
data.value = 'key fob status - ';
const mask = bitmask.check(data.msg[2]).mask;
const keyfob = {
button : null,
button_str : null,
buttons : {
lock : mask.bit2 && !mask.bit0 && !mask.bit4 && !mask.bit8,
unlock : !mask.bit2 && mask.bit0 && !mask.bit4 && !mask.bit8,
trunk : !mask.bit2 && !mask.bit0 && mask.bit4 && !mask.bit8,
none : !mask.bit2 && !mask.bit0 && !mask.bit4,
},
};
// Loop button object to populate log string
for (const button in keyfob.buttons) {
if (keyfob.buttons[button] !== true) continue;
keyfob.button = button;
keyfob.button_str = 'button: ' + button;
break;
}
// Update status object
update.status('cas.keyfob.button', keyfob.button, false);
update.status('cas.keyfob.buttons.lock', keyfob.buttons.lock, false);
update.status('cas.keyfob.buttons.none', keyfob.buttons.none, false);
update.status('cas.keyfob.buttons.trunk', keyfob.buttons.trunk, false);
update.status('cas.keyfob.buttons.unlock', keyfob.buttons.unlock, false);
// Emit keyfob event
this.emit('keyfob', keyfob);
// Assemble log string
data.value += keyfob.key_str + ', ' + keyfob.button_str + ', ' + keyfob.low_batt_str;
return data;
} // decode_status_keyfob(data)
// [0x2FC] Decode a door status message from CAS and act upon the results
decode_status_opened(data) {
data.command = 'bro';
data.value = 'door status';
// Set status from message by decoding bitmask
update.status('doors.front_left', bitmask.test(data.msg[1], 0x01), false);
update.status('doors.front_right', bitmask.test(data.msg[1], 0x04), false);
update.status('doors.hood', bitmask.test(data.msg[2], 0x04), false);
update.status('doors.rear_left', bitmask.test(data.msg[1], 0x10), false);
update.status('doors.rear_right', bitmask.test(data.msg[1], 0x40), false);
update.status('doors.trunk', bitmask.test(data.msg[2], 0x01), false);
// Set status.doors.closed if all doors are closed
const update_closed_doors = (!status.doors.front_left && !status.doors.front_right && !status.doors.rear_left && !status.doors.rear_right);
update.status('doors.closed', update_closed_doors, false);
// Set status.doors.opened if any doors are opened
update.status('doors.opened', (update_closed_doors === false), false);
// Set status.doors.sealed if all doors and flaps are closed
const update_sealed_doors = (status.doors.closed && !status.doors.hood && !status.doors.trunk);
update.status('doors.sealed', update_sealed_doors, false);
return data;
} // decode_status_opened(data)
init_listeners() {
// Bounce if not enabled
if (config.emulate.cas !== true && config.retrofit.cas !== true) return;
// Perform commands on power lib active event
power.on('active', data => {
this.encode_ignition(data.new);
});
log.module('Initialized listeners');
} // init_listeners()
// Parse data sent to module
parse_in(data) {
// Bounce if not enabled
if (config.emulate.cas !== true) return;
return data;
} // parse_in(data);
// Parse data sent from module
parse_out(data) {
switch (data.src.id) {
case 0x130 : return this.decode_ignition(data); // 0x12F / 0x4F8
case 0x23A : return this.decode_status_keyfob(data);
case 0x2FC : return this.decode_status_opened(data);
}
return data;
} // parse_out();
}
module.exports = CAS;
| kmalinich/node-bmw-client | modules/CAS.js | JavaScript | mit | 7,363 |
/*globals describe, afterEach, beforeEach, it*/
var should = require('should'),
sinon = require('sinon'),
Promise = require('bluebird'),
// Stuff we're testing
db = require('../../server/data/db'),
errors = require('../../server/errors'),
exporter = require('../../server/data/export'),
schema = require('../../server/data/schema'),
settings = require('../../server/api/settings'),
schemaTables = Object.keys(schema.tables),
sandbox = sinon.sandbox.create();
require('should-sinon');
describe('Exporter', function () {
var versionStub, tablesStub, queryMock, knexMock, knexStub;
afterEach(function () {
sandbox.restore();
knexStub.restore();
});
describe('doExport', function () {
beforeEach(function () {
versionStub = sandbox.stub(schema.versioning, 'getDatabaseVersion').returns(new Promise.resolve('004'));
tablesStub = sandbox.stub(schema.commands, 'getTables').returns(schemaTables);
queryMock = {
select: sandbox.stub()
};
knexMock = sandbox.stub().returns(queryMock);
// this MUST use sinon, not sandbox, see sinonjs/sinon#781
knexStub = sinon.stub(db, 'knex', {get: function () { return knexMock; }});
});
it('should try to export all the correct tables', function (done) {
// Setup for success
queryMock.select.returns(new Promise.resolve({}));
// Execute
exporter.doExport().then(function (exportData) {
// No tables, less the number of excluded tables
var expectedCallCount = schemaTables.length - 4;
should.exist(exportData);
versionStub.should.be.calledOnce();
tablesStub.should.be.calledOnce();
knexStub.get.should.be.called();
knexMock.should.be.called();
queryMock.select.should.be.called();
knexMock.should.have.callCount(expectedCallCount);
queryMock.select.should.have.callCount(expectedCallCount);
knexMock.getCall(0).should.be.calledWith('posts');
knexMock.getCall(1).should.be.calledWith('users');
knexMock.getCall(2).should.be.calledWith('roles');
knexMock.getCall(3).should.be.calledWith('roles_users');
knexMock.getCall(4).should.be.calledWith('permissions');
knexMock.getCall(5).should.be.calledWith('permissions_users');
knexMock.getCall(6).should.be.calledWith('permissions_roles');
knexMock.getCall(7).should.be.calledWith('permissions_apps');
knexMock.getCall(8).should.be.calledWith('settings');
knexMock.getCall(9).should.be.calledWith('tags');
knexMock.getCall(10).should.be.calledWith('posts_tags');
knexMock.getCall(11).should.be.calledWith('apps');
knexMock.getCall(12).should.be.calledWith('app_settings');
knexMock.getCall(13).should.be.calledWith('app_fields');
knexMock.should.not.be.calledWith('clients');
knexMock.should.not.be.calledWith('client_trusted_domains');
knexMock.should.not.be.calledWith('refreshtokens');
knexMock.should.not.be.calledWith('accesstokens');
done();
}).catch(done);
});
it('should catch and log any errors', function (done) {
// Setup for failure
var errorStub = sandbox.stub(errors, 'logAndThrowError');
queryMock.select.returns(new Promise.reject({}));
// Execute
exporter.doExport().then(function (exportData) {
should.not.exist(exportData);
errorStub.should.be.calledOnce();
done();
}).catch(done);
});
});
describe('exportFileName', function () {
it('should return a correctly structured filename', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve({settings: [{value: 'testblog'}]})
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^testblog\.ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings is empty', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.resolve()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
it('should return a correctly structured filename if settings errors', function (done) {
var settingsStub = sandbox.stub(settings, 'read').returns(
new Promise.reject()
);
exporter.fileName().then(function (result) {
should.exist(result);
settingsStub.should.be.calledOnce();
result.should.match(/^ghost\.[0-9]{4}-[0-9]{2}-[0-9]{2}\.json$/);
done();
}).catch(done);
});
});
});
| wjagodfrey/kaseyandco | core/test/unit/exporter_spec.js | JavaScript | mit | 5,629 |
'use strict';
const Sites = require('./reducers/sites-list');
const Site = require('./reducers/site-form');
const User = require('./reducers/user');
const Delete = require('./reducers/delete');
const Count = require('./reducers/count');
const Redux = require('redux');
module.exports = Redux.createStore(
Redux.combineReducers({
delete: Delete,
sites: Sites,
site: Site,
count: Count,
user: User
})
);
| interra/data-admin | client/pages/sites/store.js | JavaScript | mit | 453 |
/**
* Linked lists utilities
* Algorithm author: Harold Gonzalez
* Twitter: @haroldcng
* Questions: harold.gonzalez.tech@gmail.com
*/
'use strict';
/**
* Definition of Linked List Node Data Structure
*/
module.exports.ListNode = function(v){
this.val = v;
this.next = null;
};
/**
* Prints a linked list from the given node to the end
*/
module.exports.printLinkedList = (node) => {
while(node !== null){
process.stdout.write(node.val + " -> ");
node = node.next;
}
console.log("NULL");
}; | haroldcng/coding-challenges | cracking-the-coding-interview-6th/lib/linked-lists.js | JavaScript | mit | 563 |
/**
* System commands
* Pokemon Showdown - http://pokemonshowdown.com/
*
* These are system commands - commands required for Pokemon Showdown
* to run. A lot of these are sent by the client.
*
* System commands should not be modified, added, or removed. If you'd
* like to modify or add commands, add or edit files in chat-plugins/
*
* For the API, see chat-plugins/COMMANDS.md
*
* @license MIT license
*/
var crypto = require('crypto');
var fs = require('fs');
// MODIFICADO PARA POKEFABRICA EMOTICONOS
var parseEmoticons = require('./chat-plugins/emoticons').parseEmoticons;
// MODIFICADO PARA POKEFABRICA EMOTICONOS
const MAX_REASON_LENGTH = 300;
const MUTE_LENGTH = 7 * 60 * 1000;
const HOURMUTE_LENGTH = 60 * 60 * 1000;
var commands = exports.commands = {
version: function (target, room, user) {
if (!this.canBroadcast()) return;
this.sendReplyBox("Server version: <b>" + CommandParser.package.version + "</b>");
},
auth: 'authority',
stafflist: 'authority',
globalauth: 'authority',
authlist: 'authority',
authority: function (target, room, user, connection) {
var rankLists = {};
var ranks = Object.keys(Config.groups);
for (var u in Users.usergroups) {
var rank = Users.usergroups[u].charAt(0);
if (rank === ' ' || rank === '+') continue;
// In case the usergroups.csv file is not proper, we check for the server ranks.
if (ranks.indexOf(rank) >= 0) {
var name = Users.usergroups[u].substr(1);
if (!rankLists[rank]) rankLists[rank] = [];
if (name) rankLists[rank].push(name);
}
}
var buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank: 0}).rank - (Config.groups[a] || {rank: 0}).rank;
}).forEach(function (r) {
buffer.push((Config.groups[r] ? Config.groups[r].name + "s (" + r + ")" : r) + ":\n" + rankLists[r].sortBy(toId).join(", "));
});
if (!buffer.length) buffer = "This server has no global authority.";
connection.popup(buffer.join("\n\n"));
},
me: function (target, room, user, connection) {
// By default, /me allows a blank message
if (target) target = this.canTalk(target);
if (!target) return;
return '/me ' + target;
},
mee: function (target, room, user, connection) {
// By default, /mee allows a blank message
if (target) target = this.canTalk(target);
if (!target) return;
return '/mee ' + target;
},
avatar: function (target, room, user) {
if (!target) return this.parse('/avatars');
var parts = target.split(',');
var avatar = parseInt(parts[0]);
if (parts[0] === '#bw2elesa') {
avatar = parts[0];
}
if (typeof avatar === 'number' && (!avatar || avatar > 294 || avatar < 1)) {
if (!parts[1]) {
this.sendReply("Invalid avatar.");
}
return false;
}
user.avatar = avatar;
if (!parts[1]) {
this.sendReply("Avatar changed to:\n" +
'|raw|<img src="//play.pokemonshowdown.com/sprites/trainers/' + (typeof avatar === 'string' ? avatar.substr(1) : avatar) + '.png" alt="" width="80" height="80" />');
}
},
avatarhelp: ["/avatar [avatar number 1 to 293] - Change your trainer sprite."],
signout: 'logout',
logout: function (target, room, user) {
user.resetName();
},
requesthelp: 'report',
report: function (target, room, user) {
if (room.id === 'help') {
this.sendReply("Ask one of the Moderators (@) in the Help room.");
} else {
this.parse('/join help');
}
},
r: 'reply',
reply: function (target, room, user) {
if (!target) return this.parse('/help reply');
if (!user.lastPM) {
return this.sendReply("No one has PMed you yet.");
}
return this.parse('/msg ' + (user.lastPM || '') + ', ' + target);
},
replyhelp: ["/reply OR /r [message] - Send a private message to the last person you received a message from, or sent a message to."],
pm: 'msg',
whisper: 'msg',
w: 'msg',
msg: function (target, room, user, connection) {
if (!target) return this.parse('/help msg');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!target) {
this.sendReply("You forgot the comma.");
return this.parse('/help msg');
}
this.pmTarget = (targetUser || this.targetUsername);
if (!targetUser || !targetUser.connected) {
if (targetUser && !targetUser.connected) {
this.errorReply("User " + this.targetUsername + " is offline.");
return;
} else {
this.errorReply("User " + this.targetUsername + " not found. Did you misspell their name?");
return this.parse('/help msg');
}
return;
}
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.errorReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to PM users.");
return false;
}
}
if (user.locked && !targetUser.can('lock')) {
return this.errorReply("You can only private message members of the moderation team (users marked by %, @, &, or ~) when locked.");
}
if (targetUser.locked && !user.can('lock')) {
return this.errorReply("This user is locked and cannot PM.");
}
if (targetUser.ignorePMs && targetUser.ignorePMs !== user.group && !user.can('lock')) {
if (!targetUser.can('lock')) {
return this.errorReply("This user is blocking private messages right now.");
} else if (targetUser.can('bypassall')) {
return this.errorReply("This admin is too busy to answer private messages right now. Please contact a different staff member.");
}
}
if (user.ignorePMs && user.ignorePMs !== targetUser.group && !targetUser.can('lock')) {
return this.errorReply("You are blocking private messages right now.");
}
target = this.canTalk(target, null, targetUser);
if (!target) return false;
if (target.charAt(0) === '/' && target.charAt(1) !== '/') {
// PM command
var innerCmdIndex = target.indexOf(' ');
var innerCmd = (innerCmdIndex >= 0 ? target.slice(1, innerCmdIndex) : target.slice(1));
var innerTarget = (innerCmdIndex >= 0 ? target.slice(innerCmdIndex + 1) : '');
switch (innerCmd) {
case 'me':
case 'mee':
case 'announce':
break;
case 'invite':
case 'inv':
var targetRoom = Rooms.search(innerTarget);
if (!targetRoom || targetRoom === Rooms.global) return this.errorReply('The room "' + innerTarget + '" does not exist.');
if (targetRoom.staffRoom && !targetUser.isStaff) return this.errorReply('User "' + this.targetUsername + '" requires global auth to join room "' + targetRoom.id + '".');
if (targetRoom.isPrivate === true && targetRoom.modjoin && targetRoom.auth) {
if (Config.groupsranking.indexOf(targetRoom.auth[targetUser.userid] || ' ') < Config.groupsranking.indexOf(targetRoom.modjoin) && !targetUser.can('bypassall')) {
return this.errorReply('The room "' + innerTarget + '" does not exist.');
}
}
if (targetRoom.modjoin) {
if (targetRoom.auth && (targetRoom.isPrivate === true || targetUser.group === ' ') && !(targetUser.userid in targetRoom.auth)) {
this.parse('/roomvoice ' + targetUser.name, false, targetRoom);
if (!(targetUser.userid in targetRoom.auth)) {
return;
}
}
}
target = '/invite ' + targetRoom.id;
break;
default:
return this.errorReply("The command '/" + innerCmd + "' was unrecognized or unavailable in private messages. To send a message starting with '/" + innerCmd + "', type '//" + innerCmd + "'.");
}
}
// MODIFICADO POKEFABRICA PARA EMOTICONOS
var emoteMsg = parseEmoticons(target, room, user, true);
if (emoteMsg) target = '/html ' + emoteMsg;
// MODIFICADO POKEFABRICA PARA EMOTICONOS
var message = '|pm|' + user.getIdentity() + '|' + targetUser.getIdentity() + '|' + target;
user.send(message);
if (targetUser !== user) targetUser.send(message);
targetUser.lastPM = user.userid;
user.lastPM = targetUser.userid;
},
msghelp: ["/msg OR /whisper OR /w [username], [message] - Send a private message."],
blockpm: 'ignorepms',
blockpms: 'ignorepms',
ignorepm: 'ignorepms',
ignorepms: function (target, room, user) {
if (user.ignorePMs === (target || true)) return this.sendReply("You are already blocking private messages! To unblock, use /unblockpms");
if (user.can('lock') && !user.can('bypassall')) return this.sendReply("You are not allowed to block private messages.");
user.ignorePMs = true;
if (target in Config.groups) {
user.ignorePMs = target;
return this.sendReply("You are now blocking private messages, except from staff and " + target + ".");
}
return this.sendReply("You are now blocking private messages, except from staff.");
},
ignorepmshelp: ["/blockpms - Blocks private messages. Unblock them with /unignorepms."],
unblockpm: 'unignorepms',
unblockpms: 'unignorepms',
unignorepm: 'unignorepms',
unignorepms: function (target, room, user) {
if (!user.ignorePMs) return this.sendReply("You are not blocking private messages! To block, use /blockpms");
user.ignorePMs = false;
return this.sendReply("You are no longer blocking private messages.");
},
unignorepmshelp: ["/unblockpms - Unblocks private messages. Block them with /blockpms."],
idle: 'away',
afk: 'away',
away: function (target, room, user) {
this.parse('/blockchallenges');
this.parse('/blockpms ' + target);
},
awayhelp: ["/away - Blocks challenges and private messages. Unblock them with /back."],
unaway: 'back',
unafk: 'back',
back: function () {
this.parse('/unblockpms');
this.parse('/unblockchallenges');
},
backhelp: ["/back - Unblocks challenges and/or private messages, if either are blocked."],
makeprivatechatroom: 'makechatroom',
makechatroom: function (target, room, user, connection, cmd) {
if (!this.can('makeroom')) return;
// `,` is a delimiter used by a lot of /commands
// `|` and `[` are delimiters used by the protocol
// `-` has special meaning in roomids
if (target.includes(',') || target.includes('|') || target.includes('[') || target.includes('-')) {
return this.sendReply("Room titles can't contain any of: ,|[-");
}
var id = toId(target);
if (!id) return this.parse('/help makechatroom');
// Check if the name already exists as a room or alias
if (Rooms.search(id)) return this.sendReply("The room '" + target + "' already exists.");
if (Rooms.global.addChatRoom(target)) {
if (cmd === 'makeprivatechatroom') {
var targetRoom = Rooms.search(target);
targetRoom.isPrivate = true;
targetRoom.chatRoomData.isPrivate = true;
Rooms.global.writeChatRoomData();
if (Rooms('upperstaff')) {
Rooms('upperstaff').add('|raw|<div class="broadcast-green">Private chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
return this.sendReply("The private chat room '" + target + "' was created.");
} else {
if (Rooms('staff')) {
Rooms('staff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
if (Rooms('upperstaff')) {
Rooms('upperstaff').add('|raw|<div class="broadcast-green">Public chat room created: <b>' + Tools.escapeHTML(target) + '</b></div>').update();
}
return this.sendReply("The chat room '" + target + "' was created.");
}
}
return this.sendReply("An error occurred while trying to create the room '" + target + "'.");
},
makechatroomhelp: ["/makechatroom [roomname] - Creates a new room named [roomname]. Requires: ~"],
makegroupchat: function (target, room, user, connection, cmd) {
if (!user.autoconfirmed) {
return this.errorReply("You don't have permission to make a group chat right now.");
}
if (target.length > 64) return this.errorReply("Title must be under 32 characters long.");
var targets = target.split(',', 2);
// Title defaults to a random 8-digit number.
var title = targets[0].trim();
if (title.length >= 32) {
return this.errorReply("Title must be under 32 characters long.");
} else if (!title) {
title = ('' + Math.floor(Math.random() * 100000000));
} else if (Config.chatfilter) {
var filterResult = Config.chatfilter.call(this, title, user, null, connection);
if (!filterResult) return;
if (title !== filterResult) {
return this.errorReply("Invalid title.");
}
}
// `,` is a delimiter used by a lot of /commands
// `|` and `[` are delimiters used by the protocol
// `-` has special meaning in roomids
if (title.includes(',') || title.includes('|') || title.includes('[') || title.includes('-')) {
return this.errorReply("Room titles can't contain any of: ,|[-");
}
// Even though they're different namespaces, to cut down on confusion, you
// can't share names with registered chatrooms.
var existingRoom = Rooms.search(toId(title));
if (existingRoom && !existingRoom.modjoin) return this.errorReply("The room '" + title + "' already exists.");
// Room IDs for groupchats are groupchat-TITLEID
var titleid = toId(title);
if (!titleid) {
titleid = '' + Math.floor(Math.random() * 100000000);
}
var roomid = 'groupchat-' + user.userid + '-' + titleid;
// Titles must be unique.
if (Rooms.search(roomid)) return this.errorReply("A group chat named '" + title + "' already exists.");
// Tab title is prefixed with '[G]' to distinguish groupchats from
// registered chatrooms
title = title;
if (ResourceMonitor.countGroupChat(connection.ip)) {
this.errorReply("Due to high load, you are limited to creating 4 group chats every hour.");
return;
}
// Privacy settings, default to hidden.
var privacy = toId(targets[1]) || 'hidden';
var privacySettings = {private: true, hidden: 'hidden', public: false};
if (!(privacy in privacySettings)) privacy = 'hidden';
var groupChatLink = '<code><<' + roomid + '>></code>';
var groupChatURL = '';
if (Config.serverid) {
groupChatURL = 'http://' + (Config.serverid === 'showdown' ? 'psim.us' : Config.serverid + '.psim.us') + '/' + roomid;
groupChatLink = '<a href="' + groupChatURL + '">' + groupChatLink + '</a>';
}
var titleHTML = '';
if (/^[0-9]+$/.test(title)) {
titleHTML = groupChatLink;
} else {
titleHTML = Tools.escapeHTML(title) + ' <small style="font-weight:normal;font-size:9pt">' + groupChatLink + '</small>';
}
var targetRoom = Rooms.createChatRoom(roomid, '[G] ' + title, {
isPersonal: true,
isPrivate: privacySettings[privacy],
auth: {},
introMessage: '<h2 style="margin-top:0">' + titleHTML + '</h2><p>There are several ways to invite people:<br />- in this chat: <code>/invite USERNAME</code><br />- anywhere in PS: link to <code><<' + roomid + '>></code>' + (groupChatURL ? '<br />- outside of PS: link to <a href="' + groupChatURL + '">' + groupChatURL + '</a>' : '') + '</p><p>This room will expire after 40 minutes of inactivity or when the server is restarted.</p><p style="margin-bottom:0"><button name="send" value="/roomhelp">Room management</button>'
});
if (targetRoom) {
// The creator is RO.
targetRoom.auth[user.userid] = '#';
// Join after creating room. No other response is given.
user.joinRoom(targetRoom.id);
return;
}
return this.errorReply("An unknown error occurred while trying to create the room '" + title + "'.");
},
makegroupchathelp: ["/makegroupchat [roomname], [private|hidden|public] - Creates a group chat named [roomname]. Leave off privacy to default to hidden."],
deregisterchatroom: function (target, room, user) {
if (!this.can('makeroom')) return;
var id = toId(target);
if (!id) return this.parse('/help deregisterchatroom');
var targetRoom = Rooms.search(id);
if (!targetRoom) return this.sendReply("The room '" + target + "' doesn't exist.");
target = targetRoom.title || targetRoom.id;
if (Rooms.global.deregisterChatRoom(id)) {
this.sendReply("The room '" + target + "' was deregistered.");
this.sendReply("It will be deleted as of the next server restart.");
return;
}
return this.sendReply("The room '" + target + "' isn't registered.");
},
deregisterchatroomhelp: ["/deregisterchatroom [roomname] - Deletes room [roomname] after the next server restart. Requires: ~"],
hideroom: 'privateroom',
hiddenroom: 'privateroom',
secretroom: 'privateroom',
publicroom: 'publicroom',
privateroom: function (target, room, user, connection, cmd) {
if (room.battle || room.isPersonal) {
if (!this.can('editroom', null, room)) return;
} else {
// registered chatrooms show up on the room list and so require
// higher permissions to modify privacy settings
if (!this.can('makeroom')) return;
}
var setting;
switch (cmd) {
case 'privateroom':
return this.parse('/help privateroom');
break;
case 'publicroom':
setting = false;
break;
case 'secretroom':
setting = true;
break;
default:
if (room.isPrivate === true && target !== 'force') {
return this.sendReply("This room is a secret room. Use `/publicroom` to make it public, or `/hiddenroom force` to force hidden.");
}
setting = 'hidden';
break;
}
if ((setting === true || room.isPrivate === true) && !room.isPersonal) {
if (!this.can('makeroom')) return;
}
if (target === 'off' || !setting) {
delete room.isPrivate;
this.addModCommand("" + user.name + " made this room public.");
if (room.chatRoomData) {
delete room.chatRoomData.isPrivate;
Rooms.global.writeChatRoomData();
}
} else {
if (room.isPrivate === setting) {
return this.errorReply("This room is already " + (setting === true ? 'secret' : setting) + ".");
}
room.isPrivate = setting;
this.addModCommand("" + user.name + " made this room " + (setting === true ? 'secret' : setting) + ".");
if (room.chatRoomData) {
room.chatRoomData.isPrivate = setting;
Rooms.global.writeChatRoomData();
}
}
},
privateroomhelp: ["/secretroom - Makes a room secret. Secret rooms are visible to & and up. Requires: & ~",
"/hiddenroom [on/off] - Makes a room hidden. Hidden rooms are visible to % and up, and inherit global ranks. Requires: \u2605 & ~",
"/publicroom - Makes a room public. Requires: \u2605 & ~"],
modjoin: function (target, room, user) {
if (room.battle || room.isPersonal) {
if (!this.can('editroom', null, room)) return;
} else {
if (!this.can('makeroom')) return;
}
if (target === 'off' || target === 'false') {
delete room.modjoin;
this.addModCommand("" + user.name + " turned off modjoin.");
if (room.chatRoomData) {
delete room.chatRoomData.modjoin;
Rooms.global.writeChatRoomData();
}
} else {
if ((target === 'on' || target === 'true' || !target) || !user.can('editroom')) {
room.modjoin = true;
this.addModCommand("" + user.name + " turned on modjoin.");
} else if (target in Config.groups) {
room.modjoin = target;
this.addModCommand("" + user.name + " set modjoin to " + target + ".");
} else {
this.sendReply("Unrecognized modjoin setting.");
return false;
}
if (room.chatRoomData) {
room.chatRoomData.modjoin = room.modjoin;
Rooms.global.writeChatRoomData();
}
if (!room.modchat) this.parse('/modchat ' + Config.groupsranking[1]);
if (!room.isPrivate) this.parse('/hiddenroom');
}
},
officialchatroom: 'officialroom',
officialroom: function (target, room, user) {
if (!this.can('makeroom')) return;
if (!room.chatRoomData) {
return this.sendReply("/officialroom - This room can't be made official");
}
if (target === 'off') {
delete room.isOfficial;
this.addModCommand("" + user.name + " made this chat room unofficial.");
delete room.chatRoomData.isOfficial;
Rooms.global.writeChatRoomData();
} else {
room.isOfficial = true;
this.addModCommand("" + user.name + " made this chat room official.");
room.chatRoomData.isOfficial = true;
Rooms.global.writeChatRoomData();
}
},
roomdesc: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.desc) return this.sendReply("This room does not have a description set.");
this.sendReplyBox("The room description is: " + Tools.escapeHTML(room.desc));
return;
}
if (!this.can('declare')) return false;
if (target.length > 80) return this.sendReply("Error: Room description is too long (must be at most 80 characters).");
var normalizedTarget = ' ' + target.toLowerCase().replace('[^a-zA-Z0-9]+', ' ').trim() + ' ';
if (normalizedTarget.includes(' welcome ')) {
return this.sendReply("Error: Room description must not contain the word 'welcome'.");
}
if (normalizedTarget.slice(0, 9) === ' discuss ') {
return this.sendReply("Error: Room description must not start with the word 'discuss'.");
}
if (normalizedTarget.slice(0, 12) === ' talk about ' || normalizedTarget.slice(0, 17) === ' talk here about ') {
return this.sendReply("Error: Room description must not start with the phrase 'talk about'.");
}
room.desc = target;
this.sendReply("(The room description is now: " + target + ")");
this.privateModCommand("(" + user.name + " changed the roomdesc to: \"" + target + "\".)");
if (room.chatRoomData) {
room.chatRoomData.desc = room.desc;
Rooms.global.writeChatRoomData();
}
},
topic: 'roomintro',
roomintro: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.introMessage) return this.sendReply("This room does not have an introduction set.");
this.sendReply('|raw|<div class="infobox infobox-limited">' + room.introMessage + '</div>');
if (!this.broadcasting && user.can('declare', null, room)) {
this.sendReply('Source:');
this.sendReplyBox('<code>/roomintro ' + Tools.escapeHTML(room.introMessage) + '</code>');
}
return;
}
target = target.trim();
if (!this.can('declare', null, room)) return false;
if (!this.canHTML(target)) return;
if (!/</.test(target)) {
// not HTML, do some simple URL linking
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g;
target = target.replace(re, '<a href="$1">$1</a>');
}
if (target.substr(0, 11) === '/roomintro ') target = target.substr(11);
room.introMessage = target;
this.sendReply("(The room introduction has been changed to:)");
this.sendReply('|raw|<div class="infobox infobox-limited">' + target + '</div>');
this.privateModCommand("(" + user.name + " changed the roomintro.)");
if (room.chatRoomData) {
room.chatRoomData.introMessage = room.introMessage;
Rooms.global.writeChatRoomData();
}
},
stafftopic: 'staffintro',
staffintro: function (target, room, user) {
if (!target) {
if (!this.can('mute', null, room)) return false;
if (!room.staffMessage) return this.sendReply("This room does not have a staff introduction set.");
this.sendReply('|raw|<div class="infobox">' + room.staffMessage + '</div>');
if (user.can('ban', null, room)) {
this.sendReply('Source:');
this.sendReplyBox('<code>/staffintro ' + Tools.escapeHTML(room.staffMessage) + '</code>');
}
return;
}
if (!this.can('ban', null, room)) return false;
target = target.trim();
if (!this.canHTML(target)) return;
if (!/</.test(target)) {
// not HTML, do some simple URL linking
var re = /(https?:\/\/(([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?))/g;
target = target.replace(re, '<a href="$1">$1</a>');
}
if (target.substr(0, 12) === '/staffintro ') target = target.substr(12);
room.staffMessage = target;
this.sendReply("(The staff introduction has been changed to:)");
this.sendReply('|raw|<div class="infobox">' + target + '</div>');
this.privateModCommand("(" + user.name + " changed the staffintro.)");
if (room.chatRoomData) {
room.chatRoomData.staffMessage = room.staffMessage;
Rooms.global.writeChatRoomData();
}
},
roomalias: function (target, room, user) {
if (!target) {
if (!this.canBroadcast()) return;
if (!room.aliases || !room.aliases.length) return this.sendReplyBox("This room does not have any aliases.");
return this.sendReplyBox("This room has the following aliases: " + room.aliases.join(", ") + "");
}
if (!this.can('setalias')) return false;
var alias = toId(target);
if (!alias.length) return this.sendReply("Only alphanumeric characters are valid in an alias.");
if (Rooms.get(alias) || Rooms.aliases[alias]) return this.sendReply("You cannot set an alias to an existing room or alias.");
if (room.isPersonal) return this.sendReply("Personal rooms can't have aliases.");
Rooms.aliases[alias] = room.id;
this.privateModCommand("(" + user.name + " added the room alias '" + target + "'.)");
if (!room.aliases) room.aliases = [];
room.aliases.push(alias);
if (room.chatRoomData) {
room.chatRoomData.aliases = room.aliases;
Rooms.global.writeChatRoomData();
}
},
removeroomalias: function (target, room, user) {
if (!room.aliases) return this.sendReply("This room does not have any aliases.");
if (!this.can('setalias')) return false;
var alias = toId(target);
if (!alias.length || !Rooms.aliases[alias]) return this.sendReply("Please specify an existing alias.");
if (Rooms.aliases[alias] !== room.id) return this.sendReply("You may only remove an alias from the current room.");
this.privateModCommand("(" + user.name + " removed the room alias '" + target + "'.)");
var aliasIndex = room.aliases.indexOf(alias);
if (aliasIndex >= 0) {
room.aliases.splice(aliasIndex, 1);
delete Rooms.aliases[alias];
Rooms.global.writeChatRoomData();
}
},
roomowner: function (target, room, user) {
if (!room.chatRoomData) {
return this.sendReply("/roomowner - This room isn't designed for per-room moderation to be added");
}
if (!target) return this.parse('/help roomowner');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' is not online.");
if (!this.can('makeroom')) return false;
if (!room.auth) room.auth = room.chatRoomData.auth = {};
var name = targetUser.name;
room.auth[targetUser.userid] = '#';
this.addModCommand("" + name + " was appointed Room Owner by " + user.name + ".");
room.onUpdateIdentity(targetUser);
Rooms.global.writeChatRoomData();
},
roomownerhelp: ["/roomowner [username] - Appoints [username] as a room owner. Removes official status. Requires: ~"],
roomdeowner: 'deroomowner',
deroomowner: function (target, room, user) {
if (!room.auth) {
return this.sendReply("/roomdeowner - This room isn't designed for per-room moderation");
}
if (!target) return this.parse('/help roomdeowner');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var name = this.targetUsername;
var userid = toId(name);
if (!userid || userid === '') return this.sendReply("User '" + name + "' does not exist.");
if (room.auth[userid] !== '#') return this.sendReply("User '" + name + "' is not a room owner.");
if (!this.can('makeroom')) return false;
delete room.auth[userid];
this.sendReply("(" + name + " is no longer Room Owner.)");
if (targetUser) targetUser.updateIdentity();
if (room.chatRoomData) {
Rooms.global.writeChatRoomData();
}
},
deroomownerhelp: ["/roomdeowner [username] - Removes [username]'s status as a room owner. Requires: ~"],
roomdemote: 'roompromote',
roompromote: function (target, room, user, connection, cmd) {
if (!room.auth) {
this.sendReply("/roompromote - This room isn't designed for per-room moderation");
return this.sendReply("Before setting room mods, you need to set it up with /roomowner");
}
if (!target) return this.parse('/help roompromote');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = toId(this.targetUsername);
var name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help roompromote');
if (!room.auth || !room.auth[userid]) {
if (!targetUser) {
return this.sendReply("User '" + name + "' is offline and unauthed, and so can't be promoted.");
}
if (!targetUser.registered) {
return this.sendReply("User '" + name + "' is unregistered, and so can't be promoted.");
}
}
var currentGroup = ((room.auth && room.auth[userid]) || (room.isPrivate !== true && targetUser.group) || ' ');
var nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.sendReply("Please specify a group such as /roomvoice or /roomdeauth");
}
if (!Config.groups[nextGroup]) {
return this.sendReply("Group '" + nextGroup + "' does not exist.");
}
if (Config.groups[nextGroup].globalonly || (Config.groups[nextGroup].battleonly && !room.battle)) {
return this.sendReply("Group 'room" + Config.groups[nextGroup].id + "' does not exist as a room rank.");
}
var groupName = Config.groups[nextGroup].name || "regular user";
if ((room.auth[userid] || Config.groupsranking[0]) === nextGroup) {
return this.sendReply("User '" + name + "' is already a " + groupName + " in this room.");
}
if (!user.can('makeroom')) {
if (currentGroup !== ' ' && !user.can('room' + (Config.groups[currentGroup] ? Config.groups[currentGroup].id : 'voice'), null, room)) {
return this.sendReply("/" + cmd + " - Access denied for promoting/demoting from " + (Config.groups[currentGroup] ? Config.groups[currentGroup].name : "an undefined group") + ".");
}
if (nextGroup !== ' ' && !user.can('room' + Config.groups[nextGroup].id, null, room)) {
return this.sendReply("/" + cmd + " - Access denied for promoting/demoting to " + Config.groups[nextGroup].name + ".");
}
}
if (nextGroup === ' ') {
delete room.auth[userid];
} else {
room.auth[userid] = nextGroup;
}
if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) {
this.privateModCommand("(" + name + " was demoted to Room " + groupName + " by " + user.name + ".)");
if (targetUser && Rooms.rooms[room.id].users[targetUser.userid]) targetUser.popup("You were demoted to Room " + groupName + " by " + user.name + ".");
} else if (nextGroup === '#') {
this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + ".");
} else {
this.addModCommand("" + name + " was promoted to Room " + groupName + " by " + user.name + ".");
}
if (targetUser) targetUser.updateIdentity(room.id);
if (room.chatRoomData) Rooms.global.writeChatRoomData();
},
roompromotehelp: ["/roompromote OR /roomdemote [username], [group symbol] - Promotes/demotes the user to the specified room rank. Requires: @ # & ~",
"/room[group] [username] - Promotes/demotes the user to the specified room rank. Requires: @ # & ~",
"/roomdeauth [username] - Removes all room rank from the user. Requires: @ # & ~"],
roomstaff: 'roomauth',
roomauth: function (target, room, user, connection) {
var targetRoom = room;
if (target) targetRoom = Rooms.search(target);
var unavailableRoom = targetRoom && (targetRoom !== room && (targetRoom.modjoin || targetRoom.staffRoom) && !user.can('makeroom'));
if (!targetRoom || unavailableRoom) return this.sendReply("The room '" + target + "' does not exist.");
if (!targetRoom.auth) return this.sendReply("/roomauth - The room '" + (targetRoom.title ? targetRoom.title : target) + "' isn't designed for per-room moderation and therefore has no auth list.");
var rankLists = {};
for (var u in targetRoom.auth) {
if (!rankLists[targetRoom.auth[u]]) rankLists[targetRoom.auth[u]] = [];
rankLists[targetRoom.auth[u]].push(u);
}
var buffer = [];
Object.keys(rankLists).sort(function (a, b) {
return (Config.groups[b] || {rank:0}).rank - (Config.groups[a] || {rank:0}).rank;
}).forEach(function (r) {
buffer.push((Config.groups[r] ? Config.groups[r] .name + "s (" + r + ")" : r) + ":\n" + rankLists[r].sort().join(", "));
});
if (!buffer.length) {
connection.popup("The room '" + targetRoom.title + "' has no auth.");
return;
}
if (targetRoom !== room) buffer.unshift("" + targetRoom.title + " room auth:");
connection.popup(buffer.join("\n\n"));
},
userauth: function (target, room, user, connection) {
var targetId = toId(target) || user.userid;
var targetUser = Users.getExact(targetId);
var targetUsername = (targetUser ? targetUser.name : target);
var buffer = [];
var innerBuffer = [];
var group = Users.usergroups[targetId];
if (group) {
buffer.push('Global auth: ' + group.charAt(0));
}
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || curRoom.isPrivate) continue;
group = curRoom.auth[targetId];
if (!group) continue;
innerBuffer.push(group + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Room auth: ' + innerBuffer.join(', '));
}
if (targetId === user.userid || user.can('lock')) {
innerBuffer = [];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate === true) continue;
var auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Hidden room auth: ' + innerBuffer.join(', '));
}
}
if (targetId === user.userid || user.can('makeroom')) {
innerBuffer = [];
for (var i = 0; i < Rooms.global.chatRooms.length; i++) {
var curRoom = Rooms.global.chatRooms[i];
if (!curRoom.auth || !curRoom.isPrivate) continue;
if (curRoom.isPrivate !== true) continue;
var auth = curRoom.auth[targetId];
if (!auth) continue;
innerBuffer.push(auth + curRoom.id);
}
if (innerBuffer.length) {
buffer.push('Private room auth: ' + innerBuffer.join(', '));
}
}
if (!buffer.length) {
buffer.push("No global or room auth.");
}
buffer.unshift("" + targetUsername + " user auth:");
connection.popup(buffer.join("\n\n"));
},
rb: 'roomban',
roomban: function (target, room, user, connection) {
if (!target) return this.parse('/help roomban');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
var name = this.targetUsername;
var userid = toId(name);
if (!userid || !targetUser) return this.sendReply("User '" + name + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('ban', targetUser, room)) return false;
if (!room.bannedUsers || !room.bannedIps) {
return this.sendReply("Room bans are not meant to be used in room " + room.id + ".");
}
if (room.bannedUsers[userid] && room.bannedIps[targetUser.latestIp]) return this.sendReply("User " + targetUser.name + " is already banned from room " + room.id + ".");
if (targetUser in room.users) {
targetUser.popup(
"|html|<p>" + Tools.escapeHTML(user.name) + " has banned you from the room " + room.id + ".</p>" + (target ? "<p>Reason: " + Tools.escapeHTML(target) + "</p>" : "") +
"<p>To appeal the ban, PM the staff member that banned you" + (room.auth ? " or a room owner. </p><p><button name=\"send\" value=\"/roomauth " + room.id + "\">List Room Staff</button></p>" : ".</p>")
);
}
this.addModCommand("" + targetUser.name + " was banned from room " + room.id + " by " + user.name + "." + (target ? " (" + target + ")" : ""));
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
var alts = room.roomBan(targetUser);
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "roombanned alts: " + alts.join(", ") + ")");
for (var i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
this.add('|unlink|' + this.getLastIdOf(targetUser));
},
roombanhelp: ["/roomban [username] - Bans the user from the room you are in. Requires: @ # & ~"],
unroomban: 'roomunban',
roomunban: function (target, room, user, connection) {
if (!target) return this.parse('/help roomunban');
if (!room.bannedUsers || !room.bannedIps) {
return this.sendReply("Room bans are not meant to be used in room " + room.id + ".");
}
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = room.isRoomBanned(targetUser) || toId(target);
if (!userid) return this.sendReply("User '" + target + "' is an invalid username.");
if (targetUser && !this.can('ban', targetUser, room)) return false;
var unbannedUserid = room.unRoomBan(userid);
if (!unbannedUserid) return this.sendReply("User " + userid + " is not banned from room " + room.id + ".");
this.addModCommand("" + unbannedUserid + " was unbanned from room " + room.id + " by " + user.name + ".");
},
roomunbanhelp: ["/roomunban [username] - Unbans the user from the room you are in. Requires: @ # & ~"],
autojoin: function (target, room, user, connection) {
Rooms.global.autojoinRooms(user, connection);
var targets = target.split(',');
var autojoins = [];
if (targets.length > 9 || Object.keys(connection.rooms).length > 1) return;
for (var i = 0; i < targets.length; i++) {
if (user.tryJoinRoom(targets[i], connection) === null) {
autojoins.push(targets[i]);
}
}
connection.autojoins = autojoins.join(',');
},
joim: 'join',
j: 'join',
join: function (target, room, user, connection) {
if (!target) return false;
if (user.tryJoinRoom(target, connection) === null) {
connection.sendTo(target, "|noinit|namerequired|The room '" + target + "' does not exist or requires a login to join.");
}
},
leave: 'part',
part: function (target, room, user, connection) {
if (room.id === 'global') return false;
var targetRoom = Rooms.search(target);
if (target && !targetRoom) {
return this.sendReply("The room '" + target + "' does not exist.");
}
user.leaveRoom(targetRoom || room, connection);
},
/*********************************************************
* Moderating: Punishments
*********************************************************/
kick: 'warn',
k: 'warn',
warn: function (target, room, user) {
if (!target) return this.parse('/help warn');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (room.isPersonal && !user.can('warn')) return this.sendReply("Warning is unavailable in group chats.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (!(targetUser in room.users)) {
return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + ".");
}
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('warn', targetUser, room)) return false;
this.addModCommand("" + targetUser.name + " was warned by " + user.name + "." + (target ? " (" + target + ")" : ""));
targetUser.send('|c|~|/warn ' + target);
this.add('|unlink|' + this.getLastIdOf(targetUser));
},
warnhelp: ["/warn OR /k [username], [reason] - Warns a user showing them the Pok\u00e9mon Showdown Rules and [reason] in an overlay. Requires: % @ # & ~"],
redirect: 'redir',
redir: function (target, room, user, connection) {
if (!target) return this.parse('/help redirect');
if (room.isPrivate || room.isPersonal) return this.sendReply("Users cannot be redirected from private or personal rooms.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
var targetRoom = Rooms.search(target);
if (!targetRoom || targetRoom.modjoin) {
return this.sendReply("The room '" + target + "' does not exist.");
}
if (!this.can('warn', targetUser, room) || !this.can('warn', targetUser, targetRoom)) return false;
if (!targetUser || !targetUser.connected) {
return this.sendReply("User " + this.targetUsername + " not found.");
}
if (targetRoom.id === "global") return this.sendReply("Users cannot be redirected to the global room.");
if (targetRoom.isPrivate || targetRoom.isPersonal) {
return this.parse('/msg ' + this.targetUsername + ', /invite ' + targetRoom.id);
}
if (Rooms.rooms[targetRoom.id].users[targetUser.userid]) {
return this.sendReply("User " + targetUser.name + " is already in the room " + targetRoom.title + "!");
}
if (!Rooms.rooms[room.id].users[targetUser.userid]) {
return this.sendReply("User " + this.targetUsername + " is not in the room " + room.id + ".");
}
if (targetUser.joinRoom(targetRoom.id) === false) return this.sendReply("User " + targetUser.name + " could not be joined to room " + targetRoom.title + ". They could be banned from the room.");
this.addModCommand("" + targetUser.name + " was redirected to room " + targetRoom.title + " by " + user.name + ".");
targetUser.leaveRoom(room);
},
redirhelp: ["/redirect OR /redir [username], [roomname] - Attempts to redirect the user [username] to the room [roomname]. Requires: % @ & ~"],
m: 'mute',
mute: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help mute');
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
var muteDuration = ((cmd === 'hm' || cmd === 'hourmute') ? HOURMUTE_LENGTH : MUTE_LENGTH);
if (!this.can('mute', targetUser, room)) return false;
var canBeMutedFurther = ((room.getMuteTime(targetUser) || 0) <= (muteDuration * 5 / 6));
if ((room.isMuted(targetUser) && !canBeMutedFurther) || targetUser.locked || !targetUser.connected) {
var problem = " but was already " + (!targetUser.connected ? "offline" : targetUser.locked ? "locked" : "muted");
if (!target) {
return this.privateModCommand("(" + targetUser.name + " would be muted by " + user.name + problem + ".)");
}
return this.addModCommand("" + targetUser.name + " would be muted by " + user.name + problem + "." + (target ? " (" + target + ")" : ""));
}
if (targetUser in room.users) targetUser.popup("|modal|" + user.name + " has muted you in " + room.id + " for " + muteDuration.duration() + ". " + target);
this.addModCommand("" + targetUser.name + " was muted by " + user.name + " for " + muteDuration.duration() + "." + (target ? " (" + target + ")" : ""));
if (targetUser.autoconfirmed && targetUser.autoconfirmed !== targetUser.userid) this.privateModCommand("(" + targetUser.name + "'s ac account: " + targetUser.autoconfirmed + ")");
this.add('|unlink|' + this.getLastIdOf(targetUser));
room.mute(targetUser, muteDuration, false);
},
mutehelp: ["/mute OR /m [username], [reason] - Mutes a user with reason for 7 minutes. Requires: % @ # & ~"],
hm: 'hourmute',
hourmute: function (target) {
if (!target) return this.parse('/help hourmute');
this.run('mute');
},
hourmutehelp: ["/hourmute OR /hm [username], [reason] - Mutes a user with reason for an hour. Requires: % @ # & ~"],
um: 'unmute',
unmute: function (target, room, user) {
if (!target) return this.parse('/help unmute');
target = this.splitTarget(target);
if (room.isMuted(user) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!this.can('mute', null, room)) return false;
var targetUser = this.targetUser;
var successfullyUnmuted = room.unmute(targetUser ? targetUser.userid : this.targetUsername, "Your mute in '" + room.title + "' has been lifted.");
if (successfullyUnmuted) {
this.addModCommand("" + (targetUser ? targetUser.name : successfullyUnmuted) + " was unmuted by " + user.name + ".");
} else {
this.sendReply("" + (targetUser ? targetUser.name : this.targetUsername) + " is not muted.");
}
},
unmutehelp: ["/unmute [username] - Removes mute from user. Requires: % @ # & ~"],
forcelock: 'lock',
l: 'lock',
ipmute: 'lock',
lock: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help lock');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('lock', targetUser)) return false;
if ((targetUser.locked || Users.checkBanned(targetUser.latestIp)) && !target) {
var problem = " but was already " + (targetUser.locked ? "locked" : "banned");
return this.privateModCommand("(" + targetUser.name + " would be locked by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forcelock') {
var from = targetUser.deconfirm();
ResourceMonitor.log("[CrisisMonitor] " + targetUser.name + " was locked by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to lock them use /forcelock.");
}
} else if (cmd === 'forcelock') {
return this.sendReply("Use /lock; " + targetUser.name + " is not a confirmed user.");
}
targetUser.popup("|modal|" + user.name + " has locked you from talking in chats, battles, and PMing regular users." + (target ? "\n\nReason: " + target : "") + "\n\nIf you feel that your lock was unjustified, you can still PM staff members (%, @, &, and ~) to discuss it" + (Config.appealurl ? " or you can appeal:\n" + Config.appealurl : ".") + "\n\nYour lock will expire in a few days.");
this.addModCommand("" + targetUser.name + " was locked from talking by " + user.name + "." + (target ? " (" + target + ")" : ""));
var alts = targetUser.getAlts();
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "locked alts: " + alts.join(", ") + ")");
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
var userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
this.globalModlog("LOCK", targetUser, " by " + user.name + (target ? ": " + target : ""));
targetUser.lock(false, userid);
return true;
},
lockhelp: ["/lock OR /l [username], [reason] - Locks the user from talking in all chats. Requires: % @ & ~"],
unlock: function (target, room, user) {
if (!target) return this.parse('/help unlock');
if (!this.can('lock')) return false;
var targetUser = Users.get(target);
var reason = '';
if (targetUser && targetUser.locked && targetUser.locked.charAt(0) === '#') {
reason = ' (' + targetUser.locked + ')';
}
var unlocked = Users.unlock(target);
if (unlocked) {
var names = Object.keys(unlocked);
this.addModCommand(names.join(", ") + " " + ((names.length > 1) ? "were" : "was") +
" unlocked by " + user.name + "." + reason);
if (!reason) this.globalModlog("UNLOCK", target, " by " + user.name);
if (targetUser) targetUser.popup("" + user.name + " has unlocked you.");
} else {
this.sendReply("User '" + target + "' is not locked.");
}
},
unlockhelp: ["/unlock [username] - Unlocks the user. Requires: % @ & ~"],
forceban: 'ban',
b: 'ban',
ban: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help ban');
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser) return this.sendReply("User '" + this.targetUsername + "' does not exist.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The reason is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('ban', targetUser)) return false;
if (Users.checkBanned(targetUser.latestIp) && !target && !targetUser.connected) {
var problem = " but was already banned";
return this.privateModCommand("(" + targetUser.name + " would be banned by " + user.name + problem + ".)");
}
if (targetUser.confirmed) {
if (cmd === 'forceban') {
var from = targetUser.deconfirm();
ResourceMonitor.log("[CrisisMonitor] " + targetUser.name + " was banned by " + user.name + " and demoted from " + from.join(", ") + ".");
} else {
return this.sendReply("" + targetUser.name + " is a confirmed user. If you are sure you would like to ban them use /forceban.");
}
} else if (cmd === 'forceban') {
return this.sendReply("Use /ban; " + targetUser.name + " is not a confirmed user.");
}
targetUser.popup("|modal|" + user.name + " has banned you." + (target ? "\n\nReason: " + target : "") + (Config.appealurl ? "\n\nIf you feel that your ban was unjustified, you can appeal:\n" + Config.appealurl : "") + "\n\nYour ban will expire in a few days.");
this.addModCommand("" + targetUser.name + " was banned by " + user.name + "." + (target ? " (" + target + ")" : ""), " (" + targetUser.latestIp + ")");
var alts = targetUser.getAlts();
var acAccount = (targetUser.autoconfirmed !== targetUser.userid && targetUser.autoconfirmed);
if (alts.length) {
var guests = 0;
alts = alts.filter(function (alt) {
if (alt.substr(0, 6) !== 'Guest ') return true;
guests++;
return false;
});
this.privateModCommand("(" + targetUser.name + "'s " + (acAccount ? " ac account: " + acAccount + ", " : "") + "banned alts: " + alts.join(", ") + (guests ? " [" + guests + " guests]" : "") + ")");
for (var i = 0; i < alts.length; ++i) {
this.add('|unlink|' + toId(alts[i]));
}
} else if (acAccount) {
this.privateModCommand("(" + targetUser.name + "'s ac account: " + acAccount + ")");
}
var userid = this.getLastIdOf(targetUser);
this.add('|unlink|hide|' + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|hide|' + toId(this.inputUsername));
targetUser.ban(false, userid);
this.globalModlog("BAN", targetUser, " by " + user.name + (target ? ": " + target : ""));
return true;
},
banhelp: ["/ban OR /b [username], [reason] - Kick user from all rooms and ban user's IP address with reason. Requires: @ & ~"],
unban: function (target, room, user) {
if (!target) return this.parse('/help unban');
if (!this.can('ban')) return false;
var name = Users.unban(target);
if (name) {
this.addModCommand("" + name + " was unbanned by " + user.name + ".");
this.globalModlog("UNBAN", name, " by " + user.name);
} else {
this.sendReply("User '" + target + "' is not banned.");
}
},
unbanhelp: ["/unban [username] - Unban a user. Requires: @ & ~"],
unbanall: function (target, room, user) {
if (!this.can('rangeban')) return false;
// we have to do this the hard way since it's no longer a global
var punishKeys = ['bannedIps', 'bannedUsers', 'lockedIps', 'lockedUsers', 'lockedRanges', 'rangeLockedUsers'];
for (var i = 0; i < punishKeys.length; i++) {
var dict = Users[punishKeys[i]];
for (var entry in dict) delete dict[entry];
}
this.addModCommand("All bans and locks have been lifted by " + user.name + ".");
},
unbanallhelp: ["/unbanall - Unban all IP addresses. Requires: & ~"],
banip: function (target, room, user) {
target = target.trim();
if (!target) {
return this.parse('/help banip');
}
if (!this.can('rangeban')) return false;
if (Users.bannedIps[target] === '#ipban') return this.sendReply("The IP " + (target.charAt(target.length - 1) === '*' ? "range " : "") + target + " has already been temporarily banned.");
Users.bannedIps[target] = '#ipban';
this.addModCommand("" + user.name + " temporarily banned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target);
},
baniphelp: ["/banip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"],
unbanip: function (target, room, user) {
target = target.trim();
if (!target) {
return this.parse('/help unbanip');
}
if (!this.can('rangeban')) return false;
if (!Users.bannedIps[target]) {
return this.sendReply("" + target + " is not a banned IP or IP range.");
}
delete Users.bannedIps[target];
this.addModCommand("" + user.name + " unbanned the " + (target.charAt(target.length - 1) === '*' ? "IP range" : "IP") + ": " + target);
},
unbaniphelp: ["/unbanip [ip] - Kick users on this IP or IP range from all rooms and bans it. Accepts wildcards to ban ranges. Requires: & ~"],
rangelock: function (target, room, user) {
if (!target) return this.sendReply("Please specify a range to lock.");
if (!this.can('rangeban')) return false;
var isIp = (target.slice(-1) === '*' ? true : false);
var range = (isIp ? target : Users.shortenHost(target));
if (Users.lockedRanges[range]) return this.sendReply("The range " + range + " has already been temporarily locked.");
Users.lockRange(range, isIp);
this.addModCommand("" + user.name + " temporarily locked the range: " + range);
},
unrangelock: 'rangeunlock',
rangeunlock: function (target, room, user) {
if (!target) return this.sendReply("Please specify a range to unlock.");
if (!this.can('rangeban')) return false;
var range = (target.slice(-1) === '*' ? target : Users.shortenHost(target));
if (!Users.lockedRanges[range]) return this.sendReply("The range " + range + " is not locked.");
Users.unlockRange(range);
this.addModCommand("" + user.name + " unlocked the range " + range + ".");
},
/*********************************************************
* Moderating: Other
*********************************************************/
mn: 'modnote',
modnote: function (target, room, user, connection) {
if (!target) return this.parse('/help modnote');
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (target.length > MAX_REASON_LENGTH) {
return this.sendReply("The note is too long. It cannot exceed " + MAX_REASON_LENGTH + " characters.");
}
if (!this.can('receiveauthmessages', null, room)) return false;
return this.privateModCommand("(" + user.name + " notes: " + target + ")");
},
modnotehelp: ["/modnote [note] - Adds a moderator note that can be read through modlog. Requires: % @ # & ~"],
globalpromote: 'promote',
promote: function (target, room, user, connection, cmd) {
if (!target) return this.parse('/help promote');
target = this.splitTarget(target, true);
var targetUser = this.targetUser;
var userid = toId(this.targetUsername);
var name = targetUser ? targetUser.name : this.targetUsername;
if (!userid) return this.parse('/help promote');
var currentGroup = ((targetUser && targetUser.group) || Users.usergroups[userid] || ' ')[0];
var nextGroup = target;
if (target === 'deauth') nextGroup = Config.groupsranking[0];
if (!nextGroup) {
return this.sendReply("Please specify a group such as /globalvoice or /globaldeauth");
}
if (!Config.groups[nextGroup]) {
return this.sendReply("Group '" + nextGroup + "' does not exist.");
}
if (Config.groups[nextGroup].roomonly) {
return this.sendReply("Group '" + nextGroup + "' does not exist as a global rank.");
}
var groupName = Config.groups[nextGroup].name || "regular user";
if (currentGroup === nextGroup) {
return this.sendReply("User '" + name + "' is already a " + groupName);
}
if (!user.canPromote(currentGroup, nextGroup)) {
return this.sendReply("/" + cmd + " - Access denied.");
}
if (!Users.setOfflineGroup(name, nextGroup)) {
return this.sendReply("/promote - WARNING: This user is offline and could be unregistered. Use /forcepromote if you're sure you want to risk it.");
}
if (Config.groups[nextGroup].rank < Config.groups[currentGroup].rank) {
this.privateModCommand("(" + name + " was demoted to " + groupName + " by " + user.name + ".)");
if (targetUser) targetUser.popup("You were demoted to " + groupName + " by " + user.name + ".");
} else {
this.addModCommand("" + name + " was promoted to " + groupName + " by " + user.name + ".");
}
if (targetUser) targetUser.updateIdentity();
},
promotehelp: ["/promote [username], [group] - Promotes the user to the specified group. Requires: & ~"],
globaldemote: 'demote',
demote: function (target) {
if (!target) return this.parse('/help demote');
this.run('promote');
},
demotehelp: ["/demote [username], [group] - Demotes the user to the specified group. Requires: & ~"],
forcepromote: function (target, room, user) {
// warning: never document this command in /help
if (!this.can('forcepromote')) return false;
target = this.splitTarget(target, true);
var name = this.targetUsername;
var nextGroup = target;
if (!Config.groups[nextGroup]) return this.sendReply("Group '" + nextGroup + "' does not exist.");
if (!Users.setOfflineGroup(name, nextGroup, true)) {
return this.sendReply("/forcepromote - Don't forcepromote unless you have to.");
}
this.addModCommand("" + name + " was promoted to " + (Config.groups[nextGroup].name || "regular user") + " by " + user.name + ".");
},
devoice: 'deauth',
deauth: function (target, room, user) {
return this.parse('/demote ' + target + ', deauth');
},
deroomvoice: 'roomdeauth',
roomdevoice: 'roomdeauth',
deroomauth: 'roomdeauth',
roomdeauth: function (target, room, user) {
return this.parse('/roomdemote ' + target + ', deauth');
},
modchat: function (target, room, user) {
if (!target) return this.sendReply("Moderated chat is currently set to: " + room.modchat);
if ((user.locked || room.isMuted(user)) && !user.can('bypassall')) return this.sendReply("You cannot do this while unable to talk.");
if (!this.can('modchat', null, room)) return false;
if (room.modchat && room.modchat.length <= 1 && Config.groupsranking.indexOf(room.modchat) > 1 && !user.can('modchatall', null, room)) {
return this.sendReply("/modchat - Access denied for removing a setting higher than " + Config.groupsranking[1] + ".");
}
target = target.toLowerCase();
var currentModchat = room.modchat;
switch (target) {
case 'off':
case 'false':
case 'no':
case ' ':
room.modchat = false;
break;
case 'ac':
case 'autoconfirmed':
room.modchat = 'autoconfirmed';
break;
case '*':
case 'player':
target = '\u2605';
/* falls through */
default:
if (!Config.groups[target]) {
return this.parse('/help modchat');
}
if (Config.groupsranking.indexOf(target) > 1 && !user.can('modchatall', null, room)) {
return this.sendReply("/modchat - Access denied for setting higher than " + Config.groupsranking[1] + ".");
}
room.modchat = target;
break;
}
if (currentModchat === room.modchat) {
return this.sendReply("Modchat is already set to " + currentModchat + ".");
}
if (!room.modchat) {
this.add("|raw|<div class=\"broadcast-blue\"><b>Moderated chat was disabled!</b><br />Anyone may talk now.</div>");
} else {
var modchat = Tools.escapeHTML(room.modchat);
this.add("|raw|<div class=\"broadcast-red\"><b>Moderated chat was set to " + modchat + "!</b><br />Only users of rank " + modchat + " and higher can talk.</div>");
}
this.logModCommand(user.name + " set modchat to " + room.modchat);
if (room.chatRoomData) {
room.chatRoomData.modchat = room.modchat;
Rooms.global.writeChatRoomData();
}
},
modchathelp: ["/modchat [off/autoconfirmed/+/%/@/#/&/~] - Set the level of moderated chat. Requires: @ for off/autoconfirmed/+ options, # & ~ for all the options"],
declare: function (target, room, user) {
if (!target) return this.parse('/help declare');
if (!this.can('declare', null, room)) return false;
if (!this.canTalk()) return;
this.add('|raw|<div class="broadcast-blue"><b>' + Tools.escapeHTML(target) + '</b></div>');
this.logModCommand(user.name + " declared " + target);
},
declarehelp: ["/declare [message] - Anonymously announces a message. Requires: # & ~"],
htmldeclare: function (target, room, user) {
if (!target) return this.parse('/help htmldeclare');
if (!this.can('gdeclare', null, room)) return false;
if (!this.canTalk()) return;
this.add('|raw|<div class="broadcast-blue"><b>' + target + '</b></div>');
this.logModCommand(user.name + " declared " + target);
},
htmldeclarehelp: ["/htmldeclare [message] - Anonymously announces a message using safe HTML. Requires: ~"],
gdeclare: 'globaldeclare',
globaldeclare: function (target, room, user) {
if (!target) return this.parse('/help globaldeclare');
if (!this.can('gdeclare')) return false;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>');
}
this.logModCommand(user.name + " globally declared " + target);
},
globaldeclarehelp: ["/globaldeclare [message] - Anonymously announces a message to every room on the server. Requires: ~"],
cdeclare: 'chatdeclare',
chatdeclare: function (target, room, user) {
if (!target) return this.parse('/help chatdeclare');
if (!this.can('gdeclare')) return false;
for (var id in Rooms.rooms) {
if (id !== 'global') if (Rooms.rooms[id].type !== 'battle') Rooms.rooms[id].addRaw('<div class="broadcast-blue"><b>' + target + '</b></div>');
}
this.logModCommand(user.name + " globally declared (chat level) " + target);
},
chatdeclarehelp: ["/cdeclare [message] - Anonymously announces a message to all chatrooms on the server. Requires: ~"],
wall: 'announce',
announce: function (target, room, user) {
if (!target) return this.parse('/help announce');
if (!this.can('announce', null, room)) return false;
target = this.canTalk(target);
if (!target) return;
return '/announce ' + target;
},
announcehelp: ["/announce OR /wall [message] - Makes an announcement. Requires: % @ # & ~"],
fr: 'forcerename',
forcerename: function (target, room, user) {
if (!target) return this.parse('/help forcerename');
var reason = this.splitTarget(target, true);
var targetUser = this.targetUser;
if (!targetUser) {
this.splitTarget(target);
if (this.targetUser) {
return this.sendReply("User has already changed their name to '" + this.targetUser.name + "'.");
}
return this.sendReply("User '" + target + "' not found.");
}
if (!this.can('forcerename', targetUser)) return false;
var entry = targetUser.name + " was forced to choose a new name by " + user.name + (reason ? ": " + reason : "");
this.privateModCommand("(" + entry + ")");
Rooms.global.cancelSearch(targetUser);
targetUser.resetName();
targetUser.send("|nametaken||" + user.name + " considers your name inappropriate" + (reason ? ": " + reason : "."));
return true;
},
forcerenamehelp: ["/forcerename OR /fr [username], [reason] - Forcibly change a user's name and shows them the [reason]. Requires: % @ & ~"],
hidetext: function (target, room, user) {
if (!target) return this.parse('/help hidetext');
var reason = this.splitTarget(target);
var targetUser = this.targetUser;
var name = this.targetUsername;
if (!targetUser) return this.errorReply("User '" + name + "' does not exist.");
var userid = this.getLastIdOf(targetUser);
var hidetype = '';
if (!user.can('lock', targetUser) && !user.can('ban', targetUser, room)) {
this.errorReply('/hidetext' + this.namespaces.concat(this.cmd).join(" ") + " - Access denied.");
return false;
}
if (targetUser.locked || Users.checkBanned(targetUser.latestIp)) {
hidetype = 'hide|';
} else if (room.bannedUsers[toId(name)] && room.bannedIps[targetUser.latestIp]) {
hidetype = 'roomhide|';
} else {
return this.errorReply("User '" + name + "' is not banned from this room or locked.");
}
this.addModCommand("" + targetUser.name + "'s messages were cleared from room " + room.id + " by " + user.name + ".");
this.add('|unlink|' + hidetype + userid);
if (userid !== toId(this.inputUsername)) this.add('|unlink|' + hidetype + toId(this.inputUsername));
},
hidetexthelp: ["/hidetext [username] - Removes a locked or banned user's messages from chat (includes users banned from the room). Requires: % (global only), @ & ~"],
modlog: function (target, room, user, connection) {
var lines = 0;
// Specific case for modlog command. Room can be indicated with a comma, lines go after the comma.
// Otherwise, the text is defaulted to text search in current room's modlog.
var roomId = (room.id === 'staff' ? 'global' : room.id);
var hideIps = !user.can('lock');
var path = require('path');
var isWin = process.platform === 'win32';
var logPath = 'logs/modlog/';
if (target.includes(',')) {
var targets = target.split(',');
target = targets[1].trim();
roomId = toId(targets[0]) || room.id;
}
if (room.id.startsWith('battle-') || room.id.startsWith('groupchat-')) {
return this.errorReply("Battles and groupchats do not have modlogs.");
}
// Let's check the number of lines to retrieve or if it's a word instead
if (!target.match('[^0-9]')) {
lines = parseInt(target || 20, 10);
if (lines > 100) lines = 100;
}
var wordSearch = (!lines || lines < 0);
// Control if we really, really want to check all modlogs for a word.
var roomNames = '';
var filename = '';
var command = '';
if (roomId === 'all' && wordSearch) {
if (!this.can('modlog')) return;
roomNames = "all rooms";
// Get a list of all the rooms
var fileList = fs.readdirSync('logs/modlog');
for (var i = 0; i < fileList.length; ++i) {
filename += path.normalize(__dirname + '/' + logPath + fileList[i]) + ' ';
}
} else {
if (!this.can('modlog', null, Rooms.get(roomId))) return;
roomNames = "the room " + roomId;
filename = path.normalize(__dirname + '/' + logPath + 'modlog_' + roomId + '.txt');
}
// Seek for all input rooms for the lines or text
if (isWin) {
command = path.normalize(__dirname + '/lib/winmodlog') + ' tail ' + lines + ' ' + filename;
} else {
command = 'tail -' + lines + ' ' + filename;
}
var grepLimit = 100;
if (wordSearch) { // searching for a word instead
if (target.match(/^["'].+["']$/)) target = target.substring(1, target.length - 1);
if (isWin) {
command = path.normalize(__dirname + '/lib/winmodlog') + ' ws ' + grepLimit + ' "' + target.replace(/%/g, "%%").replace(/([\^"&<>\|])/g, "^$1") + '" ' + filename;
} else {
command = "awk '{print NR,$0}' " + filename + " | sort -nr | cut -d' ' -f2- | grep -m" + grepLimit + " -i '" + target.replace(/\\/g, '\\\\\\\\').replace(/["'`]/g, '\'\\$&\'').replace(/[\{\}\[\]\(\)\$\^\.\?\+\-\*]/g, '[$&]') + "'";
}
}
// Execute the file search to see modlog
require('child_process').exec(command, function (error, stdout, stderr) {
if (error && stderr) {
connection.popup("/modlog empty on " + roomNames + " or erred");
console.log("/modlog error: " + error);
return false;
}
if (stdout && hideIps) {
stdout = stdout.replace(/\([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\)/g, '');
}
stdout = stdout.split('\n').map(function (line) {
var bracketIndex = line.indexOf(']');
var parenIndex = line.indexOf(')');
if (bracketIndex < 0) return Tools.escapeHTML(line);
var time = line.slice(1, bracketIndex);
var timestamp = new Date(time).format('{yyyy}-{MM}-{dd} {hh}:{mm}{tt}');
var parenIndex = line.indexOf(')');
var roomid = line.slice(bracketIndex + 3, parenIndex);
if (!hideIps && Config.modloglink) {
var url = Config.modloglink(time, roomid);
if (url) timestamp = '<a href="' + url + '">' + timestamp + '</a>';
}
return '<small>[' + timestamp + '] (' + roomid + ')</small>' + Tools.escapeHTML(line.slice(parenIndex + 1));
}).join('<br />');
if (lines) {
if (!stdout) {
connection.popup("The modlog is empty. (Weird.)");
} else {
connection.popup("|wide||html|<p>The last " + lines + " lines of the Moderator Log of " + roomNames + ":</p>" + stdout);
}
} else {
if (!stdout) {
connection.popup("No moderator actions containing '" + target + "' were found on " + roomNames + ".");
} else {
connection.popup("|wide||html|<p>The last " + grepLimit + " logged actions containing '" + target + "' on " + roomNames + ":</p>" + stdout);
}
}
});
},
modloghelp: ["/modlog [roomid|all], [n] - Roomid defaults to current room.",
"If n is a number or omitted, display the last n lines of the moderator log. Defaults to 15.",
"If n is not a number, search the moderator log for 'n' on room's log [roomid]. If you set [all] as [roomid], searches for 'n' on all rooms's logs. Requires: % @ # & ~"],
/*********************************************************
* Server management commands
*********************************************************/
hotpatch: function (target, room, user) {
if (!target) return this.parse('/help hotpatch');
if (!this.can('hotpatch')) return false;
this.logEntry(user.name + " used /hotpatch " + target);
if (target === 'chat' || target === 'commands') {
try {
CommandParser.uncacheTree('./command-parser.js');
delete require.cache[require.resolve('./commands.js')];
delete require.cache[require.resolve('./chat-plugins/info.js')];
global.CommandParser = require('./command-parser.js');
var runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
return this.sendReply("Chat commands have been hot-patched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch chat: \n" + e.stack);
}
} else if (target === 'tournaments') {
try {
var runningTournaments = Tournaments.tournaments;
CommandParser.uncacheTree('./tournaments');
global.Tournaments = require('./tournaments');
Tournaments.tournaments = runningTournaments;
return this.sendReply("Tournaments have been hot-patched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch tournaments: \n" + e.stack);
}
} else if (target === 'battles') {
Simulator.SimulatorProcess.respawn();
return this.sendReply("Battles have been hotpatched. Any battles started after now will use the new code; however, in-progress battles will continue to use the old code.");
} else if (target === 'formats') {
try {
var toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
global.Tools = require('./tools.js')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds
// rebuild the formats list
Rooms.global.formatListText = Rooms.global.getFormatListText();
// respawn validator processes
TeamValidator.ValidatorProcess.respawn();
// respawn simulator processes
Simulator.SimulatorProcess.respawn();
// broadcast the new formats list to clients
Rooms.global.send(Rooms.global.formatListText);
return this.sendReply("Formats have been hotpatched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch formats: \n" + e.stack);
}
} else if (target === 'learnsets') {
try {
var toolsLoaded = !!Tools.isLoaded;
// uncache the tools.js dependency tree
CommandParser.uncacheTree('./tools.js');
// reload tools.js
global.Tools = require('./tools.js')[toolsLoaded ? 'includeData' : 'includeFormats'](); // note: this will lock up the server for a few seconds
return this.sendReply("Learnsets have been hotpatched.");
} catch (e) {
return this.sendReply("Something failed while trying to hotpatch learnsets: \n" + e.stack);
}
}
this.sendReply("Your hot-patch command was unrecognized.");
},
hotpatchhelp: ["Hot-patching the game engine allows you to update parts of Showdown without interrupting currently-running battles. Requires: ~",
"Hot-patching has greater memory requirements than restarting.",
"/hotpatch chat - reload commands.js and the chat-plugins",
"/hotpatch battles - spawn new simulator processes",
"/hotpatch formats - reload the tools.js tree, rebuild and rebroad the formats list, and also spawn new simulator processes"],
savelearnsets: function (target, room, user) {
if (!this.can('hotpatch')) return false;
fs.writeFile('data/learnsets.js', 'exports.BattleLearnsets = ' + JSON.stringify(Tools.data.Learnsets) + ";\n");
this.sendReply("learnsets.js saved.");
},
disableladder: function (target, room, user) {
if (!this.can('disableladder')) return false;
if (LoginServer.disabled) {
return this.sendReply("/disableladder - Ladder is already disabled.");
}
LoginServer.disabled = true;
this.logModCommand("The ladder was disabled by " + user.name + ".");
this.add("|raw|<div class=\"broadcast-red\"><b>Due to high server load, the ladder has been temporarily disabled</b><br />Rated games will no longer update the ladder. It will be back momentarily.</div>");
},
enableladder: function (target, room, user) {
if (!this.can('disableladder')) return false;
if (!LoginServer.disabled) {
return this.sendReply("/enable - Ladder is already enabled.");
}
LoginServer.disabled = false;
this.logModCommand("The ladder was enabled by " + user.name + ".");
this.add("|raw|<div class=\"broadcast-green\"><b>The ladder is now back.</b><br />Rated games will update the ladder now.</div>");
},
lockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
for (var id in Rooms.rooms) {
if (id === 'global') continue;
var curRoom = Rooms.rooms[id];
curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>");
if (curRoom.requestKickInactive && !curRoom.battle.ended) {
curRoom.requestKickInactive(user, true);
if (curRoom.modchat !== '+') {
curRoom.modchat = '+';
curRoom.addRaw("<div class=\"broadcast-red\"><b>Moderated chat was set to +!</b><br />Only users of rank + and higher can talk.</div>");
}
}
}
this.logEntry(user.name + " used /lockdown");
},
lockdownhelp: ["/lockdown - locks down the server, which prevents new battles from starting so that the server can eventually be restarted. Requires: ~"],
prelockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = 'pre';
this.sendReply("Tournaments have been disabled in preparation for the server restart.");
this.logEntry(user.name + " used /prelockdown");
},
slowlockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
Rooms.global.lockdown = true;
for (var id in Rooms.rooms) {
if (id === 'global') continue;
var curRoom = Rooms.rooms[id];
if (curRoom.battle) continue;
curRoom.addRaw("<div class=\"broadcast-red\"><b>The server is restarting soon.</b><br />Please finish your battles quickly. No new battles can be started until the server resets in a few minutes.</div>");
}
this.logEntry(user.name + " used /slowlockdown");
},
endlockdown: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (!Rooms.global.lockdown) {
return this.sendReply("We're not under lockdown right now.");
}
if (Rooms.global.lockdown === true) {
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("<div class=\"broadcast-green\"><b>The server shutdown was canceled.</b></div>");
}
} else {
this.sendReply("Preparation for the server shutdown was canceled.");
}
Rooms.global.lockdown = false;
this.logEntry(user.name + " used /endlockdown");
},
emergency: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (Config.emergency) {
return this.sendReply("We're already in emergency mode.");
}
Config.emergency = true;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("<div class=\"broadcast-red\">The server has entered emergency mode. Some features might be disabled or limited.</div>");
}
this.logEntry(user.name + " used /emergency");
},
endemergency: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (!Config.emergency) {
return this.sendReply("We're not in emergency mode.");
}
Config.emergency = false;
for (var id in Rooms.rooms) {
if (id !== 'global') Rooms.rooms[id].addRaw("<div class=\"broadcast-green\"><b>The server is no longer in emergency mode.</b></div>");
}
this.logEntry(user.name + " used /endemergency");
},
kill: function (target, room, user) {
if (!this.can('lockdown')) return false;
if (Rooms.global.lockdown !== true) {
return this.sendReply("For safety reasons, /kill can only be used during lockdown.");
}
if (CommandParser.updateServerLock) {
return this.sendReply("Wait for /updateserver to finish before using /kill.");
}
for (var i in Sockets.workers) {
Sockets.workers[i].kill();
}
if (!room.destroyLog) {
process.exit();
return;
}
room.destroyLog(function () {
room.logEntry(user.name + " used /kill");
}, function () {
process.exit();
});
// Just in the case the above never terminates, kill the process
// after 10 seconds.
setTimeout(function () {
process.exit();
}, 10000);
},
killhelp: ["/kill - kills the server. Can't be done unless the server is in lockdown state. Requires: ~"],
loadbanlist: function (target, room, user, connection) {
if (!this.can('hotpatch')) return false;
connection.sendTo(room, "Loading ipbans.txt...");
fs.readFile('config/ipbans.txt', function (err, data) {
if (err) return;
data = ('' + data).split('\n');
var rangebans = [];
for (var i = 0; i < data.length; ++i) {
var line = data[i].split('#')[0].trim();
if (!line) continue;
if (line.includes('/')) {
rangebans.push(line);
} else if (line && !Users.bannedIps[line]) {
Users.bannedIps[line] = '#ipban';
}
}
Users.checkRangeBanned = Cidr.checker(rangebans);
connection.sendTo(room, "ipbans.txt has been reloaded.");
});
},
loadbanlisthelp: ["/loadbanlist - Loads the bans located at ipbans.txt. The command is executed automatically at startup. Requires: ~"],
refreshpage: function (target, room, user) {
if (!this.can('hotpatch')) return false;
Rooms.global.send('|refresh|');
this.logEntry(user.name + " used /refreshpage");
},
updateserver: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/updateserver - Access denied.");
}
if (CommandParser.updateServerLock) {
return this.sendReply("/updateserver - Another update is already in progress.");
}
CommandParser.updateServerLock = true;
var logQueue = [];
logQueue.push(user.name + " used /updateserver");
connection.sendTo(room, "updating...");
var exec = require('child_process').exec;
exec('git diff-index --quiet HEAD --', function (error) {
var cmd = 'git pull --rebase';
if (error) {
if (error.code === 1) {
// The working directory or index have local changes.
cmd = 'git stash && ' + cmd + ' && git stash pop';
} else {
// The most likely case here is that the user does not have
// `git` on the PATH (which would be error.code === 127).
connection.sendTo(room, "" + error);
logQueue.push("" + error);
logQueue.forEach(function (line) {
room.logEntry(line);
});
CommandParser.updateServerLock = false;
return;
}
}
var entry = "Running `" + cmd + "`";
connection.sendTo(room, entry);
logQueue.push(entry);
exec(cmd, function (error, stdout, stderr) {
("" + stdout + stderr).split("\n").forEach(function (s) {
connection.sendTo(room, s);
logQueue.push(s);
});
logQueue.forEach(function (line) {
room.logEntry(line);
});
CommandParser.updateServerLock = false;
});
});
},
crashfixed: function (target, room, user) {
if (Rooms.global.lockdown !== true) {
return this.sendReply('/crashfixed - There is no active crash.');
}
if (!this.can('hotpatch')) return false;
Rooms.global.lockdown = false;
if (Rooms.lobby) {
Rooms.lobby.modchat = false;
Rooms.lobby.addRaw("<div class=\"broadcast-green\"><b>We fixed the crash without restarting the server!</b><br />You may resume talking in the lobby and starting new battles.</div>");
}
this.logEntry(user.name + " used /crashfixed");
},
crashfixedhelp: ["/crashfixed - Ends the active lockdown caused by a crash without the need of a restart. Requires: ~"],
'memusage': 'memoryusage',
memoryusage: function (target) {
if (!this.can('hotpatch')) return false;
var memUsage = process.memoryUsage();
var results = [memUsage.rss, memUsage.heapUsed, memUsage.heapTotal];
var units = ["B", "KiB", "MiB", "GiB", "TiB"];
for (var i = 0; i < results.length; i++) {
var unitIndex = Math.floor(Math.log2(results[i]) / 10); // 2^10 base log
results[i] = "" + (results[i] / Math.pow(2, 10 * unitIndex)).toFixed(2) + " " + units[unitIndex];
}
this.sendReply("Main process. RSS: " + results[0] + ". Heap: " + results[1] + " / " + results[2] + ".");
},
bash: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/bash - Access denied.");
}
var exec = require('child_process').exec;
exec(target, function (error, stdout, stderr) {
connection.sendTo(room, ("" + stdout + stderr));
});
},
eval: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/eval - Access denied.");
}
if (!this.canBroadcast()) return;
if (!this.broadcasting) this.sendReply('||>> ' + target);
try {
var battle = room.battle;
var me = user;
this.sendReply('||<< ' + eval(target));
} catch (e) {
this.sendReply('||<< error: ' + e.message);
var stack = '||' + ('' + e.stack).replace(/\n/g, '\n||');
connection.sendTo(room, stack);
}
},
evalbattle: function (target, room, user, connection) {
if (!user.hasConsoleAccess(connection)) {
return this.sendReply("/evalbattle - Access denied.");
}
if (!this.canBroadcast()) return;
if (!room.battle) {
return this.sendReply("/evalbattle - This isn't a battle room.");
}
room.battle.send('eval', target.replace(/\n/g, '\f'));
},
ebat: 'editbattle',
editbattle: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!target) return this.parse('/help editbattle');
if (!room.battle) {
this.sendReply("/editbattle - This is not a battle room.");
return false;
}
var cmd;
var spaceIndex = target.indexOf(' ');
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex).toLowerCase();
target = target.substr(spaceIndex + 1);
} else {
cmd = target.toLowerCase();
target = '';
}
if (cmd.charAt(cmd.length - 1) === ',') cmd = cmd.slice(0, -1);
var targets = target.split(',');
function getPlayer(input) {
if (room.battle.playerids[0] === toId(input)) return 'p1';
if (room.battle.playerids[1] === toId(input)) return 'p2';
if (input.includes('1')) return 'p1';
if (input.includes('2')) return 'p2';
return 'p3';
}
function getPokemon(input) {
if (/^[0-9]+$/.test(input)) {
return '.pokemon[' + (parseInt(input) - 1) + ']';
}
return ".pokemon.find(function(p){return p.speciesid==='" + toId(targets[1]) + "'})";
}
switch (cmd) {
case 'hp':
case 'h':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.sethp(" + parseInt(targets[2]) + ");if (p.isActive)battle.add('-damage',p,p.getHealth);");
break;
case 'status':
case 's':
room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.setStatus('" + toId(targets[2]) + "');if (!p.isActive){battle.add('','please ignore the above');battle.add('-status',pl.active[0],pl.active[0].status,'[silent]');}");
break;
case 'pp':
room.battle.send('eval', "var pl=" + getPlayer(targets[0]) + ";var p=pl" + getPokemon(targets[1]) + ";p.moveset[p.moves.indexOf('" + toId(targets[2]) + "')].pp = " + parseInt(targets[3]));
break;
case 'boost':
case 'b':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";battle.boost({" + toId(targets[2]) + ":" + parseInt(targets[3]) + "},p)");
break;
case 'volatile':
case 'v':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + getPokemon(targets[1]) + ";p.addVolatile('" + toId(targets[2]) + "')");
break;
case 'sidecondition':
case 'sc':
room.battle.send('eval', "var p=" + getPlayer(targets[0]) + ".addSideCondition('" + toId(targets[1]) + "')");
break;
case 'fieldcondition': case 'pseudoweather':
case 'fc':
room.battle.send('eval', "battle.addPseudoWeather('" + toId(targets[0]) + "')");
break;
case 'weather':
case 'w':
room.battle.send('eval', "battle.setWeather('" + toId(targets[0]) + "')");
break;
case 'terrain':
case 't':
room.battle.send('eval', "battle.setTerrain('" + toId(targets[0]) + "')");
break;
default:
this.errorReply("Unknown editbattle command: " + cmd);
break;
}
},
editbattlehelp: ["/editbattle hp [player], [pokemon], [hp]",
"/editbattle status [player], [pokemon], [status]",
"/editbattle pp [player], [pokemon], [move], [pp]",
"/editbattle boost [player], [pokemon], [stat], [amount]",
"/editbattle volatile [player], [pokemon], [volatile]",
"/editbattle sidecondition [player], [sidecondition]",
"/editbattle fieldcondition [fieldcondition]",
"/editbattle weather [weather]",
"/editbattle terrain [terrain]",
"Short forms: /ebat h OR s OR pp OR b OR v OR sc OR fc OR w OR t",
"[player] must be a username or number, [pokemon] must be species name or number (not nickname), [move] must be move name"],
/*********************************************************
* Battle commands
*********************************************************/
forfeit: function (target, room, user) {
if (!room.battle) {
return this.sendReply("There's nothing to forfeit here.");
}
if (!room.forfeit(user)) {
return this.sendReply("You can't forfeit this battle.");
}
},
savereplay: function (target, room, user, connection) {
if (!room || !room.battle) return;
var logidx = 0; // spectator log (no exact HP)
if (room.battle.ended) {
// If the battle is finished when /savereplay is used, include
// exact HP in the replay log.
logidx = 3;
}
var data = room.getLog(logidx).join("\n");
var datahash = crypto.createHash('md5').update(data.replace(/[^(\x20-\x7F)]+/g, '')).digest('hex');
var players = room.battle.lastPlayers.map(Users.getExact);
LoginServer.request('prepreplay', {
id: room.id.substr(7),
loghash: datahash,
p1: players[0] ? players[0].name : room.battle.lastPlayers[0],
p2: players[1] ? players[1].name : room.battle.lastPlayers[1],
format: room.format
}, function (success) {
if (success && success.errorip) {
connection.popup("This server's request IP " + success.errorip + " is not a registered server.");
return;
}
connection.send('|queryresponse|savereplay|' + JSON.stringify({
log: data,
id: room.id.substr(7)
}));
});
},
mv: 'move',
attack: 'move',
move: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'move ' + target);
},
sw: 'switch',
switch: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'switch ' + parseInt(target, 10));
},
choose: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', target);
},
undo: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'undo', target);
},
team: function (target, room, user) {
if (!room.decision) return this.sendReply("You can only do this in battle rooms.");
room.decision(user, 'choose', 'team ' + target);
},
addplayer: function (target, room, user) {
if (!target) return this.parse('/help addplayer');
if (!room.battle) return this.sendReply("You can only do this in battle rooms.");
if (room.rated) return this.sendReply("You can only add a Player to unrated battles.");
target = this.splitTarget(target, true);
var userid = toId(this.targetUsername);
var targetUser = this.targetUser;
var name = this.targetUsername;
if (!targetUser) return this.sendReply("User " + name + " not found.");
if (targetUser.can('joinbattle', null, room)) {
return this.sendReply("" + name + " can already join battles as a Player.");
}
if (!this.can('joinbattle', null, room)) return;
room.auth[targetUser.userid] = '\u2605';
this.addModCommand("" + name + " was promoted to Player by " + user.name + ".");
},
addplayerhelp: ["/addplayer [username] - Allow the specified user to join the battle as a player."],
joinbattle: function (target, room, user) {
if (!room.joinBattle) return this.sendReply("You can only do this in battle rooms.");
if (!user.can('joinbattle', null, room)) return this.popupReply("You must be a set as a player to join a battle you didn't start. Ask a player to use /addplayer on you to join this battle.");
room.joinBattle(user);
},
partbattle: 'leavebattle',
leavebattle: function (target, room, user) {
if (!room.leaveBattle) return this.sendReply("You can only do this in battle rooms.");
room.leaveBattle(user);
},
kickbattle: function (target, room, user) {
if (!room.leaveBattle) return this.sendReply("You can only do this in battle rooms.");
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.sendReply("User " + this.targetUsername + " not found.");
}
if (!this.can('kick', targetUser)) return false;
if (room.leaveBattle(targetUser)) {
this.addModCommand("" + targetUser.name + " was kicked from a battle by " + user.name + (target ? " (" + target + ")" : ""));
} else {
this.sendReply("/kickbattle - User isn't in battle.");
}
},
kickbattlehelp: ["/kickbattle [username], [reason] - Kicks a user from a battle with reason. Requires: % @ & ~"],
kickinactive: function (target, room, user) {
if (room.requestKickInactive) {
room.requestKickInactive(user);
} else {
this.sendReply("You can only kick inactive players from inside a room.");
}
},
timer: function (target, room, user) {
target = toId(target);
if (room.requestKickInactive) {
if (target === 'off' || target === 'false' || target === 'stop') {
var canForceTimer = user.can('timer', null, room);
if (room.resetTimer) {
room.stopKickInactive(user, canForceTimer);
if (canForceTimer) room.send('|inactiveoff|Timer was turned off by staff. Please do not turn it back on until our staff say it\'s okay');
}
} else if (target === 'on' || target === 'true' || !target) {
room.requestKickInactive(user, user.can('timer'));
} else {
this.sendReply("'" + target + "' is not a recognized timer state.");
}
} else {
this.sendReply("You can only set the timer from inside a battle room.");
}
},
autotimer: 'forcetimer',
forcetimer: function (target, room, user) {
target = toId(target);
if (!this.can('autotimer')) return;
if (target === 'off' || target === 'false' || target === 'stop') {
Config.forcetimer = false;
this.addModCommand("Forcetimer is now OFF: The timer is now opt-in. (set by " + user.name + ")");
} else if (target === 'on' || target === 'true' || !target) {
Config.forcetimer = true;
this.addModCommand("Forcetimer is now ON: All battles will be timed. (set by " + user.name + ")");
} else {
this.sendReply("'" + target + "' is not a recognized forcetimer setting.");
}
},
forcetie: 'forcewin',
forcewin: function (target, room, user) {
if (!this.can('forcewin')) return false;
if (!room.battle) {
this.sendReply("/forcewin - This is not a battle room.");
return false;
}
room.battle.endType = 'forced';
if (!target) {
room.battle.tie();
this.logModCommand(user.name + " forced a tie.");
return false;
}
var targetUser = Users.getExact(target);
if (!targetUser) return this.sendReply("User '" + target + "' not found.");
target = targetUser ? targetUser.userid : '';
if (target) {
room.battle.win(targetUser);
this.logModCommand(user.name + " forced a win for " + target + ".");
}
},
forcewinhelp: ["/forcetie - Forces the current match to end in a tie. Requires: & ~",
"/forcewin [user] - Forces the current match to end in a win for a user. Requires: & ~"],
/*********************************************************
* Challenging and searching commands
*********************************************************/
cancelsearch: 'search',
search: function (target, room, user) {
if (target) {
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to search for a battle.");
return false;
}
}
Rooms.global.searchBattle(user, target);
} else {
Rooms.global.cancelSearch(user);
}
},
chall: 'challenge',
challenge: function (target, room, user, connection) {
target = this.splitTarget(target);
var targetUser = this.targetUser;
if (!targetUser || !targetUser.connected) {
return this.popupReply("The user '" + this.targetUsername + "' was not found.");
}
if (targetUser.blockChallenges && !user.can('bypassblocks', targetUser)) {
return this.popupReply("The user '" + this.targetUsername + "' is not accepting challenges right now.");
}
if (Config.pmmodchat) {
var userGroup = user.group;
if (Config.groupsranking.indexOf(userGroup) < Config.groupsranking.indexOf(Config.pmmodchat)) {
var groupName = Config.groups[Config.pmmodchat].name || Config.pmmodchat;
this.popupReply("Because moderated chat is set, you must be of rank " + groupName + " or higher to challenge users.");
return false;
}
}
user.prepBattle(Tools.getFormat(target).id, 'challenge', connection, function (result) {
if (result) user.makeChallenge(targetUser, target);
});
},
bch: 'blockchallenges',
blockchall: 'blockchallenges',
blockchalls: 'blockchallenges',
blockchallenges: function (target, room, user) {
if (user.blockChallenges) return this.sendReply("You are already blocking challenges!");
user.blockChallenges = true;
this.sendReply("You are now blocking all incoming challenge requests.");
},
blockchallengeshelp: ["/blockchallenges - Blocks challenges so no one can challenge you. Unblock them with /unblockchallenges."],
unbch: 'allowchallenges',
unblockchall: 'allowchallenges',
unblockchalls: 'allowchallenges',
unblockchallenges: 'allowchallenges',
allowchallenges: function (target, room, user) {
if (!user.blockChallenges) return this.sendReply("You are already available for challenges!");
user.blockChallenges = false;
this.sendReply("You are available for challenges from now on.");
},
allowchallengeshelp: ["/unblockchallenges - Unblocks challenges so you can be challenged again. Block them with /blockchallenges."],
cchall: 'cancelChallenge',
cancelchallenge: function (target, room, user) {
user.cancelChallengeTo(target);
},
accept: function (target, room, user, connection) {
var userid = toId(target);
var format = '';
if (user.challengesFrom[userid]) format = user.challengesFrom[userid].format;
if (!format) {
this.popupReply(target + " cancelled their challenge before you could accept it.");
return false;
}
user.prepBattle(Tools.getFormat(format).id, 'challenge', connection, function (result) {
if (result) user.acceptChallengeFrom(userid);
});
},
reject: function (target, room, user) {
user.rejectChallengeFrom(toId(target));
},
saveteam: 'useteam',
utm: 'useteam',
useteam: function (target, room, user) {
user.team = target;
},
vtm: function (target, room, user, connection) {
if (ResourceMonitor.countPrepBattle(connection.ip, user.name)) {
connection.popup("Due to high load, you are limited to 6 team validations every 3 minutes.");
return;
}
var format = Tools.getFormat(target);
if (format.effectType !== 'Format') format = Tools.getFormat('Anything Goes');
if (format.effectType !== 'Format') {
connection.popup("Please provide a valid format.");
return;
}
TeamValidator.validateTeam(format.id, user.team, function (success, details) {
if (success) {
connection.popup("Your team is valid for " + format.name + ".");
} else {
connection.popup("Your team was rejected for the following reasons:\n\n- " + details.replace(/\n/g, '\n- '));
}
});
},
/*********************************************************
* Low-level
*********************************************************/
cmd: 'query',
query: function (target, room, user, connection) {
// Avoid guest users to use the cmd errors to ease the app-layer attacks in emergency mode
var trustable = (!Config.emergency || (user.named && user.registered));
if (Config.emergency && ResourceMonitor.countCmd(connection.ip, user.name)) return false;
var spaceIndex = target.indexOf(' ');
var cmd = target;
if (spaceIndex > 0) {
cmd = target.substr(0, spaceIndex);
target = target.substr(spaceIndex + 1);
} else {
target = '';
}
if (cmd === 'userdetails') {
var targetUser = Users.get(target);
if (!trustable || !targetUser) {
connection.send('|queryresponse|userdetails|' + JSON.stringify({
userid: toId(target),
rooms: false
}));
return false;
}
var roomList = {};
for (var i in targetUser.roomCount) {
if (i === 'global') continue;
var targetRoom = Rooms.get(i);
if (!targetRoom || targetRoom.isPrivate) continue;
var roomData = {};
if (targetRoom.battle) {
var battle = targetRoom.battle;
roomData.p1 = battle.p1 ? ' ' + battle.p1 : '';
roomData.p2 = battle.p2 ? ' ' + battle.p2 : '';
}
roomList[i] = roomData;
}
if (!targetUser.roomCount['global']) roomList = false;
var userdetails = {
userid: targetUser.userid,
avatar: targetUser.avatar,
rooms: roomList
};
connection.send('|queryresponse|userdetails|' + JSON.stringify(userdetails));
} else if (cmd === 'roomlist') {
if (!trustable) return false;
connection.send('|queryresponse|roomlist|' + JSON.stringify({
rooms: Rooms.global.getRoomList(target)
}));
} else if (cmd === 'rooms') {
if (!trustable) return false;
connection.send('|queryresponse|rooms|' + JSON.stringify(
Rooms.global.getRooms(user)
));
} else if (cmd === 'laddertop') {
if (!trustable) return false;
Ladders(target).getTop().then(function (result) {
connection.send('|queryresponse|laddertop|' + JSON.stringify(result));
});
} else {
// default to sending null
if (!trustable) return false;
connection.send('|queryresponse|' + cmd + '|null');
}
},
trn: function (target, room, user, connection) {
var commaIndex = target.indexOf(',');
var targetName = target;
var targetRegistered = false;
var targetToken = '';
if (commaIndex >= 0) {
targetName = target.substr(0, commaIndex);
target = target.substr(commaIndex + 1);
commaIndex = target.indexOf(',');
targetRegistered = target;
if (commaIndex >= 0) {
targetRegistered = !!parseInt(target.substr(0, commaIndex), 10);
targetToken = target.substr(commaIndex + 1);
}
}
user.rename(targetName, targetToken, targetRegistered, connection);
},
a: function (target, room, user) {
if (!this.can('rawpacket')) return false;
// secret sysop command
room.add(target);
},
/*********************************************************
* Help commands
*********************************************************/
commands: 'help',
h: 'help',
'?': 'help',
help: function (target, room, user) {
target = target.toLowerCase();
// overall
if (target === 'help' || target === 'h' || target === '?' || target === 'commands') {
// TRADUCIDO PARA POKEFABRICA
this.sendReply("/help o /h o /? - Te resolverá dudas.");
} else if (!target) {
this.sendReply("COMMANDOS: /nick, /avatar, /rating, /whois, /msg, /reply, /ignore, /away, /back, /timestamps, /highlight, /helado, /emoticons, /slap, /twitter");
this.sendReply("COMANDOS INFORMATIVOS: /data, /dexsearch, /movesearch, /groups, /faq, /reglas, /intro, /formatshelp, /othermetas, /learn, /analysis, /calc, /pxpmetas, /pkfintro, /lideres, /staff (reemplaza con ! para hacer que se muestre a todos. Pero para ello requiere: + % @ # & ~)");
this.sendReply("COMANDOS PxP BOT: .about, .say, .tell, .seen, .salt, .whois, .helix, .rps");
if (user.group !== Config.groupsranking[0]) {
this.sendReply("DRIVER COMMANDS: /salahelp, /kick, /warn, /mute, /hourmute, /unmute, /alts, /forcerename, /modlog, /modnote, /lock, /unlock, /announce, /redirect");
this.sendReply("MODERATOR COMMANDS: /ban, /unban, /ip, /modchat");
this.sendReply("LEADER COMMANDS: /declare, /forcetie, /forcewin, /promote, /demote, /banip, /host, /unbanall");
}
this.sendReply("Para una vista general de los comandos de la sala, usa /roomhelp (no puede ser usado en Looby ni en batallas)");
this.sendReply("Para detalles de un comando específico, usa algo como: /help data");
// TRADUCIDO PARA POKEFABRICA
} else {
var altCommandHelp;
var helpCmd;
var targets = target.split(' ');
var allCommands = CommandParser.commands;
if (typeof allCommands[target] === 'string') {
// If a function changes with command name, help for that command name will be searched first.
altCommandHelp = target + 'help';
if (altCommandHelp in allCommands) {
helpCmd = altCommandHelp;
} else {
helpCmd = allCommands[target] + 'help';
}
} else if (targets.length > 1 && typeof allCommands[targets[0]] === 'object') {
// Handle internal namespace commands
var helpCmd = targets[targets.length - 1] + 'help';
var namespace = allCommands[targets[0]];
for (var i = 1; i < targets.length - 1; i++) {
if (!namespace[targets[i]]) return this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
namespace = namespace[targets[i]];
}
if (typeof namespace[helpCmd] === 'object') {
return this.sendReply(namespace[helpCmd].join('\n'));
} else if (typeof namespace[helpCmd] === 'function') {
return this.parse('/' + targets.slice(0, targets.length - 1).concat(helpCmd).join(' '));
} else {
return this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
}
} else {
helpCmd = target + 'help';
}
if (helpCmd in allCommands) {
if (typeof allCommands[helpCmd] === 'function') {
// If the help command is a function, parse it instead
this.parse('/' + helpCmd);
} else if (Array.isArray(allCommands[helpCmd])) {
this.sendReply(allCommands[helpCmd].join('\n'));
}
} else {
this.sendReply("Help for the command '" + target + "' was not found. Try /help for general help");
}
}
}
};
| Raguzero/PKF | commands.js | JavaScript | mit | 104,867 |
'use strict';
const Support = require('../support');
const DataTypes = require('../../../lib/data-types');
const chai = require('chai');
const sinon = require('sinon');
const expect = chai.expect;
const current = Support.sequelize;
const _ = require('lodash');
describe(Support.getTestDialectTeaser('Model'), () => {
describe('update', () => {
beforeEach(async function() {
this.Account = this.sequelize.define('Account', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
});
await this.Account.sync({ force: true });
});
it('should only update the passed fields', async function() {
const account = await this.Account
.create({ ownerId: 2 });
await this.Account.update({
name: Math.random().toString()
}, {
where: {
id: account.get('id')
}
});
});
describe('skips update query', () => {
it('if no data to update', async function() {
const spy = sinon.spy();
await this.Account.create({ ownerId: 3 });
const result = await this.Account.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
it('skips when timestamps disabled', async function() {
const Model = this.sequelize.define('Model', {
ownerId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'owner_id'
},
name: {
type: DataTypes.STRING
}
}, {
timestamps: false
});
const spy = sinon.spy();
await Model.sync({ force: true });
await Model.create({ ownerId: 3 });
const result = await Model.update({
unknownField: 'haha'
}, {
where: {
ownerId: 3
},
logging: spy
});
expect(result[0]).to.equal(0);
expect(spy.called, 'Update query was issued when no data to update').to.be.false;
});
});
it('changed should be false after reload', async function() {
const account0 = await this.Account.create({ ownerId: 2, name: 'foo' });
account0.name = 'bar';
expect(account0.changed()[0]).to.equal('name');
const account = await account0.reload();
expect(account.changed()).to.equal(false);
});
it('should ignore undefined values without throwing not null validation', async function() {
const ownerId = 2;
const account0 = await this.Account.create({
ownerId,
name: Math.random().toString()
});
await this.Account.update({
name: Math.random().toString(),
ownerId: undefined
}, {
where: {
id: account0.get('id')
}
});
const account = await this.Account.findOne();
expect(account.ownerId).to.be.equal(ownerId);
});
if (_.get(current.dialect.supports, 'returnValues.returning')) {
it('should return the updated record', async function() {
const account = await this.Account.create({ ownerId: 2 });
const [, accounts] = await this.Account.update({ name: 'FooBar' }, {
where: {
id: account.get('id')
},
returning: true
});
const firstAcc = accounts[0];
expect(firstAcc.ownerId).to.be.equal(2);
expect(firstAcc.name).to.be.equal('FooBar');
});
}
if (current.dialect.supports['LIMIT ON UPDATE']) {
it('should only update one row', async function() {
await this.Account.create({
ownerId: 2,
name: 'Account Name 1'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 2'
});
await this.Account.create({
ownerId: 2,
name: 'Account Name 3'
});
const options = {
where: {
ownerId: 2
},
limit: 1
};
const account = await this.Account.update({ name: 'New Name' }, options);
expect(account[0]).to.equal(1);
});
}
});
});
| jayprakash1/sequelize | test/integration/model/update.test.js | JavaScript | mit | 4,404 |
// @flow
import React, { Component } from 'react'
import { View, StatusBar } from 'react-native'
import NavigationRouter from '../Navigation/NavigationRouter'
import { connect } from 'react-redux'
import StartupActions from '../Redux/StartupRedux'
import ReduxPersist from '../Config/ReduxPersist'
// Styles
import styles from './Styles/RootContainerStyle'
class RootContainer extends Component {
componentDidMount () {
// if redux persist is not active fire startup action
if (!ReduxPersist.active) {
this.props.startup()
}
}
render () {
return (
<View style={styles.applicationView}>
<StatusBar barStyle='light-content' />
<NavigationRouter />
</View>
)
}
}
const mapStateToDispatch = (dispatch) => ({
startup: () => dispatch(StartupActions.startup())
})
export default connect(null, mapStateToDispatch)(RootContainer)
| Alabaster-Aardvarks/traveller | traveller/App/Containers/RootContainer.js | JavaScript | mit | 891 |
document.onmousemove = moveDefence;
var width = 1200;
var height = 600;
var ballPerSeconds = 1;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var allBalls = new Array();
var defence = {
start: 0,
end: (Math.PI) / 3,
jiao: 0
};
var HP = 100;
var draw = drawInGame;
var score = 0;
function moveDefence(evt) {
if (!evt) {
evt = window.event
}
var xx = evt.clientX - width * 0.5;
var yy = evt.clientY - height * 0.5;
if (yy >= 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy >= 0 && xx < 0) {
defence.jiao = Math.PI + Math.atan(yy / xx)
}
if (yy < 0 && xx >= 0) {
defence.jiao = Math.atan(yy / xx)
}
if (yy < 0 && xx < 0) {
defence.jiao = Math.atan(yy / xx) - Math.PI
}
defence.start = defence.jiao - (Math.PI / 3);
defence.end = defence.jiao + (Math.PI / 3)
}
function Ball() {
if (Math.random() <= 0.25) {
this.x = 2;
this.y = height * Math.random()
}
if ((Math.random() > 0.25) && (Math.random() <= 0.5)) {
this.x = 998;
this.y = height * Math.random()
}
if ((Math.random() < 0.75) && (Math.random() > 0.5)) {
this.y = 798;
this.x = width * Math.random()
}
if (Math.random() >= 0.75) {
this.y = 2;
this.x = width * Math.random()
}
this.act = function() {
this.x = this.x + 10;
this.y = this.y + 10
}
}
function create() {
var cre;
for (cre = 0; cre < ballPerSeconds; cre++) {
var ball = new Ball();
allBalls.push(ball)
}
}
function drawEnd() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
ctx.font = "Bold 60px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("游戏结束", width * 0.5, height * 0.5);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText("得分:", width * 0.5, height * 0.5 + 60);
ctx.font = "Bold 40px Arial";
ctx.textAlign = "center";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(score.toString(), width * 0.5, height * 0.5 + 100)
}
function drawInGame() {
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, width, height);
var i;
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 60, defence.start, defence.end, false);
ctx.fillStyle = "#00A67C";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 56, 0, Math.PI * 2, true);
ctx.fillStyle = "#000000";
ctx.fill();
ctx.beginPath();
ctx.arc(width * 0.5, height * 0.5, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#B7F200";
ctx.fill();
for (i = 0; i < allBalls.length; i++) {
ctx.beginPath();
ctx.arc(allBalls[i].x, allBalls[i].y, 5, 0, Math.PI * 2, true);
ctx.fillStyle = "#EF002A";
ctx.fill()
}
ctx.fillStyle = "#DE0052";
ctx.fillRect(0, 0, HP * 3, 25);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#FFFFFF";
ctx.fillText(HP.toString(), 20, 20);
ctx.font = "Bold 20px Arial";
ctx.textAlign = "left";
ctx.fillStyle = "#EE6B9C";
scoretext = "得分:" + score.toString();
ctx.fillText(scoretext, 20, 50)
}
function act() {
for (var i = 0; i < allBalls.length; i++) {
var ax = width * 0.5 - allBalls[i].x;
var by = height * 0.5 - allBalls[i].y;
var movex = 1.5 * ax * (1.5 / Math.sqrt(ax * ax + by * by));
var movey = 1.5 * by * (1.5 / Math.sqrt(ax * ax + by * by));
allBalls[i].x = allBalls[i].x + movex;
allBalls[i].y = allBalls[i].y + movey
}
}
function check() {
for (var i = 0; i < allBalls.length; i++) {
var ax = allBalls[i].x - width * 0.5;
var by = allBalls[i].y - height * 0.5;
var distance = Math.sqrt(ax * ax + by * by);
var angel;
if (by >= 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by >= 0 && ax < 0) {
angel = Math.PI + Math.atan(by / ax)
}
if (by < 0 && ax >= 0) {
angel = Math.atan(by / ax)
}
if (by < 0 && ax < 0) {
angel = Math.atan(by / ax) - Math.PI
}
if (distance <= 63 && distance >= 57 && ((angel > defence.start && angel < defence.end) || (angel + 2 * Math.PI > defence.start && angel + 2 * Math.PI < defence.end) || (angel - 2 * Math.PI > defence.start && angel - 2 * Math.PI < defence.end))) {
allBalls.splice(i, 1);
if (HP < 100)
HP = HP + 2;
score = score + Math.floor(1000 / HP)
}
if (distance <= 5) {
allBalls.splice(i, 1);
HP = HP - 10;
if (HP < 0) {
draw = drawEnd;
window.clearInterval(int)
}
}
}
}
function start() {
act();
check();
draw()
}
var int = setInterval("start()", 30);
setInterval("create()", 500);
| elecsiuz/elecsiuz.github.io | projects/DotDefence/lib/lib.js | JavaScript | mit | 5,021 |
/********************** tine translations of Setup**********************/
Locale.Gettext.prototype._msgs['./LC_MESSAGES/Setup'] = new Locale.Gettext.PO(({
""
: "Project-Id-Version: Tine 2.0\nPOT-Creation-Date: 2008-05-17 22:12+0100\nPO-Revision-Date: 2012-09-19 08:58+0000\nLast-Translator: corneliusweiss <mail@corneliusweiss.de>\nLanguage-Team: Russian (http://www.transifex.com/projects/p/tine20/language/ru/)\nMIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\nLanguage: ru\nPlural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\nX-Poedit-Country: GB\nX-Poedit-Language: en\nX-Poedit-SourceCharset: utf-8\n"
, "Name"
: "Имя"
, "Enabled"
: "Позволенный"
, "Order"
: "Последовательность"
, "Installed Version"
: "Установленная версия"
, "Available Version"
: "Доступная версия"
, "Status"
: "Статус"
, "Depends on"
: "Зависит от"
, "Install application"
: "Установить приложение"
, "Uninstall application"
: "Удалить приложение"
, "Update application"
: "Обновить приложение"
, "Go to {0} login"
: ""
, "uninstall"
: "удалить"
, "Do you really want to uninstall the application(s)?"
: "Вы действительно хотите удалить приложение(я)?"
, "This may take a while"
: "Это может занять некоторое время"
, "Dependency Violation"
: ""
, "Delete all existing users and groups"
: "Удалить всех существующих пользователей и группы"
, "Switching from SQL to LDAP will delete all existing User Accounts, Groups and Roles. Do you really want to switch the accounts storage backend to LDAP ?"
: ""
, "Backend"
: ""
, "Initial Admin User"
: ""
, "Initial admin login name"
: ""
, "Initial admin Password"
: ""
, "Password confirmation"
: "Подтверждение пароля"
, "Authentication provider"
: "Проверка подлинности поставщика"
, "Try to split username"
: "Попробуйте разделить имя пользователя"
, "Yes"
: "Да"
, "No"
: "Нет"
, "Account canonical form"
: ""
, "Account domain name "
: ""
, "Account domain short name"
: ""
, "Host"
: "Хост"
, "Port"
: "Порт"
, "Login name"
: ""
, "Password"
: "Пароль"
, "Bind requires DN"
: ""
, "Base DN"
: ""
, "Search filter"
: "Фильтр поиска"
, "Hostname"
: "Имя узла"
, "Secure Connection"
: "Безопасное подключение"
, "None"
: "Нет"
, "TLS"
: "TLS"
, "SSL"
: "SSL"
, "Append domain to login name"
: ""
, "Accounts storage"
: ""
, "Default user group name"
: ""
, "Default admin group name"
: ""
, "User DN"
: ""
, "User Filter"
: "Фильтр пользователей"
, "User Search Scope"
: ""
, "Groups DN"
: "DN групп"
, "Group Filter"
: "Фильтр группы"
, "Group Search Scope"
: ""
, "Password encoding"
: ""
, "Use Rfc 2307 bis"
: "Использовать Rfc 2307 bis"
, "Min User Id"
: "Мин ID пользователя"
, "Max User Id"
: "Макс ID пользователя"
, "Min Group Id"
: "Минимальный ID группы"
, "Max Group Id"
: "Максимальный ID группы"
, "Group UUID Attribute name"
: ""
, "User UUID Attribute name"
: ""
, "Readonly access"
: ""
, "Password Settings"
: ""
, "User can change password"
: "Пользователь должен сменить пароль"
, "Enable password policy"
: ""
, "Only ASCII"
: ""
, "Minimum length"
: ""
, "Minimum word chars"
: ""
, "Minimum uppercase chars"
: ""
, "Minimum special chars"
: ""
, "Minimum numbers"
: ""
, "Redirect Settings"
: ""
, "Redirect Url (redirect to login screen if empty)"
: ""
, "Redirect Always (if No, only redirect after logout)"
: ""
, "Redirect to referring site, if exists"
: ""
, "Save config and install"
: ""
, "Save config"
: "Сохранить конфигурацию"
, "Passwords don't match"
: "Пароли не совпадают"
, "Should not be empty"
: "Не должен быть пустым"
, "File"
: "Файл"
, "Adapter"
: "Адаптер"
, "Setup Authentication"
: "Аутентификация установки"
, "Username"
: "Имя пользователя"
, "Database"
: "База данных"
, "User"
: "Пользователь"
, "Prefix"
: "Префикс"
, "Logging"
: "Регистрация"
, "Filename"
: "Имя файла"
, "Priority"
: "Приоритет"
, "Caching"
: "Кэширование"
, "Path"
: "Путь"
, "Lifetime (seconds)"
: "Время жизни (секунд)"
, "Temporary files"
: "Временные файлы"
, "Temporary Files Path"
: "Путь к временным файлам"
, "Session"
: "Сессия"
, "Filestore directory"
: "Каталог хранилища файлов"
, "Filestore Path"
: ""
, "Addressbook Map panel"
: ""
, "Map panel"
: ""
, "disabled"
: "отключен"
, "enabled"
: "включен"
, "Config file is not writable"
: "Config файл защищен от записи"
, "Download config file"
: "Загрузить файл конфигурации"
, "Standard IMAP"
: "Стандартный IMAP"
, "Standard SMTP"
: "Стандартный SMTP"
, "Imap"
: "Imap"
, "Use system account"
: "Использование системной учетной записи"
, "Cyrus Admin"
: ""
, "Cyrus Admin Password"
: ""
, "Smtp"
: "Smtp"
, "Authentication"
: ""
, "Login"
: ""
, "Plain"
: ""
, "Primary Domain"
: ""
, "Secondary Domains (comma separated)"
: ""
, "Notifications service address"
: ""
, "Notification Username"
: ""
, "Notification Password"
: ""
, "Notifications local client (hostname or IP address)"
: ""
, "SIEVE"
: ""
, "MySql Hostname"
: ""
, "MySql Database"
: "База данных MySql"
, "MySql User"
: "Пользователь MySql"
, "MySql Password"
: "Пароль MySql"
, "MySql Port"
: "Порт MySql"
, "User or UID"
: "Пользователь или UID"
, "Group or GID"
: "Группа или GID"
, "Home Template"
: ""
, "Password Scheme"
: "Схема пароля"
, "PLAIN-MD5"
: "PLAIN-MD5"
, "MD5-CRYPT"
: "MD5-CRYPT"
, "SHA1"
: "SHA1"
, "SHA256"
: "SHA256"
, "SSHA256"
: "SSHA256"
, "SHA512"
: "SHA512"
, "SSHA512"
: "SSHA512"
, "PLAIN"
: "PLAIN"
, "Performing Environment Checks..."
: "Проведение проверок окружения..."
, "There could not be found any {0}. Please try to change your filter-criteria, view-options or the {1} you search in."
: ""
, "Check"
: "Проверка"
, "Result"
: "Результат"
, "Error"
: "Ошибка"
, "Run setup tests"
: "Запуск тестов установки"
, "Ignore setup tests"
: ""
, "Terms and Conditions"
: ""
, "Setup Checks"
: "Проверки установки"
, "Config Manager"
: "Управление конфигурацией"
, "Authentication/Accounts"
: ""
, "Email"
: ""
, "Application Manager"
: "Управление приложениями"
, "Application, Applications"
: [
"Приложение"
,"Приложения"
,"Приложений"
]
, "I have read the license agreement and accept it"
: ""
, "License Agreement"
: ""
, "I have read the privacy agreement and accept it"
: ""
, "Privacy Agreement"
: ""
, "Accept Terms and Conditions"
: ""
, "Application"
: "Приложение"
}));
| jodier/tmpdddf | web/private/tine20/Setup/js/Setup-lang-ru-debug.js | JavaScript | mit | 7,614 |
var socketio = require('socket.io');
exports.listen = function( server, Manager ) {
var io = socketio.listen(server);
Manager.findAllUsers(function ( err, data ) {
if(!err){
if(data.length === 0){
Manager.addUser({'login': 'madzia26', 'password': 'qwertyuiop', 'id': new Date().getTime() }, function ( err, data ) {
if(!err){
console.log('first user added');
}
});
}
}
});
io.sockets.on('connection', function ( client ) {
'use strict';
// console.log('socket.io connected');
// console.log(client.id);
//init
client.on('init', function () {
Manager.findAllUsers(function ( err, data ) {
if(!err){
var res = {
'users': [],
'categories': []
};
for(var i = 0; i < data.length; i++){
res.users.push({'login': data[i].login, "id": data[i].id});
}
Manager.findAllCategories( function ( err, data) {
if(!err){
res.categories = data;
Manager.findAllCds( function ( err, data) {
if(!err){
res.cds = data;
client.emit('init', res);
// console.log('init');
}
});
}
});
}
});
});
//users
client.on('addUser', function ( user ) {
Manager.addUser(user, function ( err, data ) {
if(!err){
// var token = new Date().getTime();
// User.signin(data.login, data.id, token);
client.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.broadcast.emit('add', {'coll': 'users', 'data': {'login': data.login, 'id': data.id} });
client.emit('auth', {'login': data.login, 'id': data.id });
}
});
});
//categories
client.on('addCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = { 'name': data.data.name, 'owner': data.data.owner };
Manager.addCategory(category, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'categories', 'data': category });
client.broadcast.emit('add', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('editCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.editCategory(category, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'categories', 'data': category });
client.broadcast.emit('update', {'coll': 'categories', 'data': category });
}
});
}
});
client.on('rmCategory', function ( data ) {
if( data.user.id === data.data.owner ) {
var category = data.data;
Manager.rmCategory(category, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'categories', 'data': category });
client.broadcast.emit('remove', {'coll': 'categories', 'data': category });
}
});
}
});
//cds
client.on('addCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = { 'name': data.data.name, 'owner': data.data.owner,
'category': data.data.category, 'url': data.data.url };
Manager.addCd(cd, function ( err, data ) {
if(!err){
client.emit('add', {'coll': 'cds', 'data': cd });
client.broadcast.emit('add', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('editCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.editCd(cd, function ( err, data ) {
if(!err){
client.emit('update', {'coll': 'cds', 'data': cd });
client.broadcast.emit('update', {'coll': 'cds', 'data': cd });
}
});
}
});
client.on('rmCd', function ( data ) {
if( data.user.id === data.data.owner ) {
var cd = data.data;
Manager.rmCd(cd, function ( err, data ) {
if(!err){
client.emit('remove', {'coll': 'cds', 'data': cd });
client.broadcast.emit('remove', {'coll': 'cds', 'data': cd });
}
});
}
});
});
};
| Madzia/angularjs_CDList | server/lib/server.js | JavaScript | mit | 4,421 |
var Document = require('pelias-model').Document;
var docs = {};
docs.named = new Document('item1',1);
docs.named.setName('default','poi1');
docs.unnamed = new Document('item2',2); // no name
docs.unnamedWithAddress = new Document('item3',3);
docs.unnamedWithAddress.setCentroid({lat:3,lon:3});
docs.unnamedWithAddress.address = {
number: '10', street: 'Mapzen pl'
};
docs.namedWithAddress = new Document('item4',4);
docs.namedWithAddress.setName('default','poi4');
docs.namedWithAddress.setCentroid({lat:4,lon:4});
docs.namedWithAddress.address = {
number: '11', street: 'Sesame st'
};
docs.invalidId = new Document('item5',5);
docs.invalidId._meta.id = undefined; // unset the id
docs.invalidId.setCentroid({lat:5,lon:5});
docs.invalidId.address = {
number: '12', street: 'Old st'
};
docs.completeDoc = new Document('item6',6);
docs.completeDoc.address = {
number: '13', street: 'Goldsmiths row', test: 'prop'
};
docs.completeDoc
.setName('default','item6')
.setName('alt','item six')
.setCentroid({lat:6,lon:6})
.setAlpha3('FOO')
.setAdmin('admin0','country')
.setAdmin('admin1','state')
.setAdmin('admin1_abbr','STA')
.setAdmin('admin2','city')
.setAdmin('local_admin','borough')
.setAdmin('locality','town')
.setAdmin('neighborhood','hood')
.setMeta('foo','bar')
.setMeta('bing','bang');
docs.osmNode1 = new Document('item7',7)
.setName('osmnode','node7')
.setCentroid({lat:7,lon:7});
docs.osmWay1 = new Document('osmway',8)
.setName('osmway','way8')
.setMeta('nodes', [
{ lat: 10, lon: 10 },
{ lat: 06, lon: 10 },
{ lat: 06, lon: 06 },
{ lat: 10, lon: 06 }
]);
docs.osmRelation1 = new Document('item9',9)
.setName('osmrelation','relation9')
.setCentroid({lat:9,lon:9});
// ref: https://github.com/pelias/openstreetmap/issues/21
docs.semicolonStreetNumbers = new Document('item10',10);
docs.semicolonStreetNumbers.setName('default','poi10');
docs.semicolonStreetNumbers.setCentroid({lat:10,lon:10});
docs.semicolonStreetNumbers.address = {
number: '1; 2 ;3', street: 'Pennine Road'
};
// has no 'nodes' and a preset centroid
docs.osmWay2 = new Document('osmway',11)
.setName('osmway','way11')
.setCentroid({lat:11,lon:11});
module.exports = docs; | hannesj/openstreetmap | test/fixtures/docs.js | JavaScript | mit | 2,233 |
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
//basePath: '../src/',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'../src/**/*.js',
'../test/**/*.js'
],
// list of files to exclude
exclude: [
],
// test results reporter to use
reporters: ['progress', 'coverage'],
preprocessors: {
'../src/**/*.js': ['coverage']
},
// configure code coverage
coverageReporter: {
reporters: [
{type: 'html', dir: '../coverage/'},
{type: 'lcov', dir: '../coverage/'},
{type: 'text-summary'}
]
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
| coffeedriven/card.js | test/karma.conf.js | JavaScript | mit | 1,485 |
/* BBY261 */
/* Sayısal Loto Uygulaması */
//Çekiliş yapılacak sayıların dizisi
var rakamlar = new Array(49);
//Oynanacak kolonun dizisi
var loto = new Array(6);
document.write('<center><img src="sayisalloto.jpg" width=70% ></center>');
//Rakam havuzunun oluşturulması
for(var i=0; i<49; i++){
rakamlar[i]=i+1;
}
document.write('<table cellpadding="6" cellspacing="10" border="0" align="center">');
//6 kolonun ekrana yazdırılması
for(var i4=0; i4<6; i4++){
document.write('<tr>');
//Kolonun oluşturulması
for(var i2=0; i2<6; i2++){
var havuz = rakamlar.length;
var secilen = Math.floor(Math.random() * havuz);
loto[i2]=rakamlar[secilen];
rakamlar.splice(secilen,1);
}
loto.sort(function(a, b){return a-b});
//Tek kolonun yazdırılması
for(var i3=0; i3<6; i3++){
document.write('<td width=23 heigth=23 background="top.png" id="yazitipi">'+loto[i3]+'</td>');
}
document.write('</tr>');
}
document.write('</table>');
document.write('<p><center><img src="buton.png" onclick="yenile()" ></center></p>');
function yenile(){
window.location.href="index.html";
} | senem35yildirim/bby261.senemyildirim.loto | rakamUret.js | JavaScript | mit | 1,125 |
angular.module('tabss.controllers', [])
.controller('TabssCtrl', function($scope,$state) {
$scope.gotoTabs =function(){
$state.go('tabs')
}
$scope.gotoNearby =function(){
$state.go('app.nearby')
}
$scope.gotoEditProfile =function(){
$state.go('editprofile')
}
$scope.gotoQRCode =function(){
$state.go('qrcode')
}
$scope.gotoHome =function(){
$state.go('app.home')
}
$scope.gotoAddFavorite =function(){
$state.go('addfavorite')
}
$scope.gotoFavoriteMenu1 =function(){
$state.go('favoritemenu1')
}
$scope.gotoCoffeeShop1 =function(){
$state.go('coffeeshop1')
}
$scope.gotoNewsPromotion =function(){
$state.go('newspromotion')
}
$scope.gotoNews =function(){
$state.go('news')
}
})
| Mikumikuni/coffee-hub-customer | www/js/tabsscontrollers.js | JavaScript | mit | 875 |
'use strict';
var http = require('http');
var Pusher = require('pusher');
var Network = require('./model/network');
var Node = require('./model/node');
var Sensor = require('./model/sensor');
var Feature = require('./model/feature');
require('./model/relations');
// https://pusher.com/docs/server_api_guide/interact_rest_api
var pusher = new Pusher({
appId: process.env.PUSHER_ID,
key: process.env.PUSHER_KEY,
secret: process.env.PUSHER_SECRET
});
/**
* Reverse object keys and values.
*/
function reverse(o) {
console.log('[index.js] reverse');
console.time('[index.js] reverse');
var result = {};
for(var key in o) {
result[o[key]] = key;
}
console.timeEnd('[index.js] reverse');
return result;
}
/**
* Extract the base64 data encoded in the kinesis record to an object.
* @return {Object}
*/
function decode(record) {
console.log('[index.js] decode');
console.time('[index.js] decode');
var data = new Buffer(record.kinesis.data, 'base64').toString();
try {
return JSON.parse(data);
} catch (SyntaxError) {
return {};
}
console.timeEnd('[index.js] decode');
}
/**
* If the sensor maps to an available feature of interest, provide it, otherwise
* reject it as null.
* @return {Object}
*/
function format(record, networkMap) {
var network = record.network;
var node = record.node;
var sensor = record.sensor;
var networkMetadata = networkMap[network];
if (!networkMetadata) {
return null;
}
var nodeMetadata = networkMetadata[node];
if (!nodeMetadata) {
return null;
}
var sensorMetadata = nodeMetadata[sensor];
if (!sensorMetadata) {
return null;
}
var mapping = sensorMetadata;
var feature = '';
for (var property in record.data) {
if (!(property in mapping)) {
return null;
}
feature = mapping[property].split('.')[0];
var formalName = mapping[property].split('.')[1];
record.data[formalName] = record.data[property];
if (formalName != property) {
delete record.data[property];
}
}
record.feature = feature;
record.results = record.data;
delete record.data;
return record;
}
/**
* Determine if a record can be published to a channel.
* @return {Boolean}
*/
function match(record, channel) {
var prefix = channel.split('-')[0];
channel = channel.split('-')[1];
if (prefix != 'private') return false;
var channelParts = channel.split(';');
var network = channelParts[0];
var node = channelParts[1];
var sensor = channelParts[2];
var feature = channelParts[3];
if (network != record.network) return false;
if (node && record.node != node) return false;
if (sensor && record.sensor != sensor) return false;
if (feature && record.feature != feature) return false;
return true;
}
/**
* Iterate through incoming records and emit to the appropriate channels.
*/
function emit(records, channels) {
console.log('[index.js] emit');
console.time('[index.js] emit');
records.forEach((record) => {
if (!record) return;
channels.forEach((channel) => {
var message = { message: JSON.stringify(record) };
if (match(record, channel)) {
pusher.trigger(channel, 'data', message);
}
});
});
console.timeEnd('[index.js] emit');
}
/**
* Implementation of required handler for an incoming batch of kinesis records.
* http://docs.aws.amazon.com/lambda/latest/dg/with-kinesis-example-deployment-pkg.html#with-kinesis-example-deployment-pkg-nodejs
*/
function handler(event, context) {
console.log('[index.js] handler');
console.time('[index.js] handler');
var records = event.Records.map(decode);
var promise = getSensorNetworkTree().then((networkMap) => {
records = records.map((record) => format(record, networkMap));
var valids = records.filter(r => r);
pusher.get({path: '/channels'}, (error, request, response) => {
console.log(response.body);
var result = JSON.parse(response.body);
var channels = Object.keys(result.channels);
emit(records, channels);
});
console.timeEnd('[index.js] handler');
return [records.length, valids.length];
});
return promise;
}
exports.handler = handler;
function extractFeatures(sensors) {
console.log('[index.js] extractFeatures');
console.time('[index.js] extractFeatures');
var result = {};
for (var sensor of sensors) {
result[sensor.name] = sensor.observed_properties;
}
console.timeEnd('[index.js] extractFeatures');
return result;
}
function extractSensors(nodes) {
console.log('[index.js] extractSensors');
console.time('[index.js] extractSensors');
var result = {};
for (var node of nodes) {
result[node.name] = extractFeatures(node.sensor__sensor_metadata);
}
console.timeEnd('[index.js] extractSensors');
return result;
}
function getSensorNetworkTree() {
console.log('[index.js] getSensorNetworkTree');
console.time('[index.js] getSensorNetworkTree');
var networkNames = [];
var promises = [];
return Network.findAll().then( networks => {
for (var network of networks) {
networkNames.push(network.name);
promises.push(network.getNodes({ include: [{ model: Sensor }]}));
}
return Promise.all(promises);
}).then( results => {
var tree = {};
for (var i = 0; i < results.length; i++) {
tree[networkNames[i]] = extractSensors(results[i]);
}
console.timeEnd('[index.js] getSensorNetworkTree');
return tree;
});
}
| UrbanCCD-UChicago/plenario-lambdas | Publish/index.js | JavaScript | mit | 5,891 |
define(['handlebars'], function (Handlebars) {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['ma-ecca-treenode'] = template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [4,'>= 1.0.0'];
helpers = this.merge(helpers, Handlebars.helpers); data = data || {};
var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this;
function program1(depth0,data) {
var stack1;
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { return stack1; }
else { return ''; }
}
function program2(depth0,data) {
var stack1;
if (stack1 = helpers.expandedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.expandedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program4(depth0,data) {
var stack1;
if (stack1 = helpers.collapsedClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.collapsedClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
return escapeExpression(stack1);
}
function program6(depth0,data) {
return "display: none;";
}
buffer += "<ins class='ecca-tree-icon ";
stack1 = helpers['if'].call(depth0, depth0.childNodesAllowed, {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'> </ins><a href='#' class='ecca-tree-node'><ins class='ecca-tree-icon-folder ";
stack1 = helpers['if'].call(depth0, depth0.expanded, {hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += " ";
if (stack1 = helpers.iconClass) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.iconClass; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "'> </ins><span>";
if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); }
else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; }
buffer += escapeExpression(stack1)
+ "</span></a><ul style='";
stack1 = helpers.unless.call(depth0, depth0.expanded, {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data});
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "'></ul>";
return buffer;
});
}); | moodysanalytics/MA.ECCA.TreeView | src/templates/compiled/ma-ecca-treenode.js | JavaScript | mit | 2,708 |
import {combineEpics} from 'redux-observable';
import {combineReducers} from 'redux';
import {
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
pastebinReducer,
pastebinContentEpic,
pastebinContentRejectedEpic,
} from './pastebin';
import {
firecoReducer,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
} from './fireco';
import {
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoReducer,
} from './monaco';
import {
monacoEditorsEpic,
monacoEditorsReducer,
mountedEditorEpic,
} from './monacoEditor';
import {
updatePlaygroundReducer,
} from './playground';
import {updateBundleReducer} from './liveExpressionStore';
export const rootEpic = combineEpics(
disposePastebinEpic,
pastebinLayoutEpic,
pastebinEpic,
pastebinContentEpic,
pastebinContentRejectedEpic,
pastebinTokenEpic,
pastebinTokenRejectedEpic,
mountedEditorEpic,
configureMonacoModelsEpic,
updateMonacoModelsEpic,
configureMonacoThemeSwitchEpic,
monacoEditorsEpic,
// updatePlaygroundEpic,
// updatePlaygroundInstrumentationEpic,
firecoEditorsEpic,
firecoActivateEpic,
firecoEditorEpic,
firecoChatEpic,
firecoPersistableComponentEpic,
);
export const rootReducer = combineReducers({
pastebinReducer,
monacoReducer,
monacoEditorsReducer,
firecoReducer,
updateBundleReducer,
updatePlaygroundReducer,
});
| tlatoza/SeeCodeRun | scr-app/src/redux/modules/root.js | JavaScript | mit | 1,609 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h(h.f, null, h("path", {
d: "M21.41 11.58l-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42zM13 20.01L4 11V4h7v-.01l9 9-7 7.02z"
}), h("circle", {
cx: "6.5",
cy: "6.5",
r: "1.5"
}), h("path", {
d: "M8.9 12.55c0 .57.23 1.07.6 1.45l3.5 3.5 3.5-3.5c.37-.37.6-.89.6-1.45 0-1.13-.92-2.05-2.05-2.05-.57 0-1.08.23-1.45.6l-.6.6-.6-.59c-.37-.38-.89-.61-1.45-.61-1.13 0-2.05.92-2.05 2.05z"
})), 'LoyaltyOutlined'); | AlloyTeam/Nuclear | components/icon/esm/loyalty-outlined.js | JavaScript | mit | 629 |
export default function isSingleTextTree(treeList) {
return treeList.length === 1 && treeList[0].type === 'text';
} | krambuhl/rogain-parser | lib/isSingleTextTree.js | JavaScript | mit | 117 |
const Comparator = require('../../util/comparator');
/**
* Swaps two elements in the array
*/
const swap = (array, x, y) => {
const tmp = array[y];
array[y] = array[x];
array[x] = tmp;
};
/**
* Chooses a pivot and makes every element that is
* lower than the pivot move to its left, and every
* greater element moves to its right
*
* @return Number the positon of the pivot
*/
const partition = (a, comparator, lo, hi) => {
// pick a random element, swap with the rightmost and
// use it as pivot
swap(a, Math.floor(Math.random() * (hi - lo)) + lo, hi);
const pivot = hi;
// dividerPosition keeps track of the position
// where the pivot should be inserted
let dividerPosition = lo;
for (let i = lo; i < hi; i++) {
if (comparator.lessThan(a[i], a[pivot])) {
swap(a, i, dividerPosition);
dividerPosition++;
}
}
swap(a, dividerPosition, pivot);
return dividerPosition;
};
/**
* Quicksort recursively sorts parts of the array in
* O(n.lg n)
*/
const quicksortInit = (array, comparatorFn) => {
const comparator = new Comparator(comparatorFn);
return (function quicksort(array, lo, hi) {
while (lo < hi) {
const p = partition(array, comparator, lo, hi);
// Chooses only the smallest partition to use recursion on and
// tail-optimize the other. This guarantees O(log n) space in worst case.
if (p - lo < hi - p) {
quicksort(array, lo, p - 1);
lo = p + 1;
} else {
quicksort(array, p + 1, hi);
hi = p - 1;
}
}
return array;
})(array, 0, array.length - 1);
};
module.exports = quicksortInit;
| felipernb/algorithms.js | src/algorithms/sorting/quicksort.js | JavaScript | mit | 1,638 |
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let compression = require('compression');
let session = require('express-session');
let index = require('./routes/index');
let users = require('./routes/users');
let server = express();
server.set('views', path.join(__dirname, 'views'));
server.set('view engine', 'hbs');
// uncomment after placing your favicon in /public
//server.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
server.use(logger('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(express.static(path.join(__dirname, 'public')));
server.use(compression())
// express-sessions setup
server.use(session({
secret: 'blueberry pie',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 600000
}
// db: knex
}))
server.use('/', index);
server.use('/users', users);
// catch 404 and forward to error handler
server.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (server.get('env') === 'development') {
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
server.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = server;
| mix-bank/Mix-Bank | server.js | JavaScript | mit | 1,795 |
const landingText = (
``
)
const aboutText = (
`We are a team of expert web developers coming from diverse backgrounds who
are passionate about building a better web experience and delivering quality
code to our clients`
)
| PhaseFive/landing | src/components/About/index.js | JavaScript | mit | 232 |
import React, { PropTypes } from 'react';
export default function ImageDesciption({desc, price}) {
return (
<div className="text">
<h3>{desc}</h3>
<p className="price">{price}</p>
</div>
);
}
| kris1226/clymer-metal-crafts | components/Image/ImageDescription.js | JavaScript | mit | 217 |
var gulp = require("gulp");
var $ = require("gulp-load-plugins");
gulp.task("html", function () {
gulp.src("./src/index.html")
.pipe(gulp.dest("./.tmp"));
});
| logiXbomb/react-hottowel | gulpfile.js | JavaScript | mit | 166 |
const _ = require('lodash');
module.exports = _.extend(
require('./users/users.authentication.server.controller'),
require('./users/users.authorization.server.controller'),
require('./users/users.password.server.controller'),
require('./users/users.profile.server.controller')
);
| invercity/iris | modules/users/server/controllers/users.server.controller.js | JavaScript | mit | 289 |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Review Schema
*/
var ReviewSchema = new Schema({
content: {
type: String,
default: '',
trim: true
},
contentHTML: {
type: String,
default: ''
},
name: {
type: String,
default: '',
trim: true
},
score: {
type: Number,
default: 5,
required: 'Must rate the game out of 5',
min: [0, 'Score must be at least 0'],
max: [5, 'Score cannot be higher than 5']
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
gameId: {
type: String,
required: 'Game for review required'
},
game: {
type: Schema.ObjectId,
ref: 'Game'
},
triaged: {
type: Boolean,
default: false
},
liked: {
type: Number,
default: 0
},
disliked: {
type: Number,
default: 0
},
reports: [{
type: String,
enum: [
'Spam',
'Vote Manipulation',
'Personal Information',
'Troll',
'Harrassment'
]
}]
});
mongoose.model('Review', ReviewSchema); | dSolver/workshop | app/models/review.server.model.js | JavaScript | mit | 1,351 |
$(document).ready(function(){
var $nomeInput = $('#nomeInput');
var $descricaoInput = $('#descricaoInput');
var $precoInput = $('#precoInput');
var $categoriaSelect = $('#categoriaSelect');
var $novidadeSelect = $('#novidadeSelect');
var $carregandoImg = $('#carregandoImg');
$carregandoImg.hide();
var $btnSalvar = $('#salvar');
var $btnFechar = $('#fechar');
var $listaProdutos = $('#listaProdutos');
$listaProdutos.hide();
function obterValoresdeProdutos(){
return {'nome' : $nomeInput.val() , 'descricao' : $descricaoInput.val(), 'preco': $precoInput.val() , 'categoria' : $categoriaSelect.val(), 'novidade' : $novidadeSelect.val()}
}
function limparValores(){
$('input[type="text"]').val('');
$novidadeSelect.val('');
}
$.get('/produtos/admin/rest/listar').success(function(produtos){
$.each(produtos,function(index, p){
adicionarProduto(p);
})
});
function adicionarProduto (produto) {
var msg = '<tr id="tr-produto_'+produto.id+'"><td>'+produto.id+'</td><td>'+produto.nome+'</td><td>'+produto.categoria+'</td><td>'+produto.descricao+'</td><td>'+produto.preco+'</td><td>'+(produto.novidade == "1" ? 'Sim' : 'Não')+'</td><td><a href="/produtos/admin/editar/'+produto.id+'" class="btn btn-warning glyphicon glyphicon-pencil"></a></td><td><button id="btn-deletar_'+produto.id+'" class="btn btn-danger"><i class="glyphicon glyphicon-trash"></i></button></td></tr>';
$listaProdutos.show();
$listaProdutos.append(msg);
$('#btn-deletar_'+produto.id).click(function(){
if (confirm("Deseja apagar esse registro? "))
{
var resp = $.post('/produtos/admin/rest/deletar' , {produto_id : produto.id});
resp.success(function(){
$('#tr-produto_'+produto.id).remove()
});
}
});
}
$btnSalvar.click(function(){
$('.has-error').removeClass('has-error');
$('.help-block').empty();
$btnSalvar.attr('disabled' , 'disabled');
$carregandoImg.fadeIn('fast');
var resp = $.post('/produtos/admin/rest/salvar', obterValoresdeProdutos());
resp.success(function(produto){
limparValores();
$btnFechar.click();
adicionarProduto(produto);
})
resp.error(function(erros){
for(campos in erros.responseJSON)
{
$('#'+campos+'Div').addClass('has-error');
$('#'+campos+'Span').text(erros.responseJSON[campos]);
}
}).always(function(){
$btnSalvar.removeAttr('disabled','disabled');
$carregandoImg.hide();
});
});
});
| iwilliam317/tekton | backend/appengine/static/js/produtos.js | JavaScript | mit | 2,496 |
// Karma configuration
// Generated on Wed Jul 15 2015 09:44:02 GMT+0200 (Romance Daylight Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular2/node_modules/zone.js/dist/zone-microtask.js',
'node_modules/angular2/node_modules/zone.js/dist/long-stack-trace-zone.js',
'node_modules/angular2/node_modules/zone.js/dist/jasmine-patch.js',
'node_modules/angular2/node_modules/traceur/bin/traceur-runtime.js',
'node_modules/es6-module-loader/dist/es6-module-loader-sans-promises.src.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/reflect-metadata/Reflect.js',
{ pattern: 'test/**/*.js', included: false, watched: true },
{ pattern: 'node_modules/angular2/**/*.js', included: false, watched: false },
'test-main.js',
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
| tjercus/angular2-events | karma.conf.js | JavaScript | mit | 2,232 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.5.4.20-4-55
description: >
String.prototype.trim handles whitepace and lineterminators
(\u000A\u000A)
includes: [runTestCase.js]
---*/
function testcase() {
if ("\u000A\u000A".trim() === "") {
return true;
}
}
runTestCase(testcase);
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/String/prototype/trim/15.5.4.20-4-55.js | JavaScript | mit | 635 |
'use strict';
const os = require('os');
const cluster = require('cluster');
const DEFAULT_DEADLINE_MS = 30000;
function makeWorker(workerFunc) {
var server = workerFunc(cluster.worker.id);
server.on('close', function() {
process.exit();
});
process.on('SIGTERM', function() {
server.close();
});
return server;
}
const Regiment = function(workerFunc, options) {
if (cluster.isWorker) return makeWorker(workerFunc);
options = options || {};
const numCpus = os.cpus().length;
let running = true;
const deadline = options.deadline || DEFAULT_DEADLINE_MS;
const numWorkers = options.numWorkers || numCpus;
const logger = options.logger || console;
function messageHandler(msg) {
if (running && msg.cmd && msg.cmd === 'need_replacement') {
const workerId = msg.workerId;
const replacement = spawn();
logger.log(`Replacing worker ${workerId} with worker ${replacement.id}`);
replacement.on('listening', (address) => {
logger.log(`Replacement ${replacement.id} is listening, killing ${workerId}`);
kill(cluster.workers[workerId]);
})
}
}
function spawn() {
const worker = cluster.fork();
worker.on('message', messageHandler);
return worker;
}
function fork() {
for (var i=0; i<numWorkers; i++) {
spawn();
}
}
function kill(worker) {
logger.log(`Killing ${worker.id}`);
worker.process.kill();
ensureDeath(worker);
}
function ensureDeath(worker) {
setTimeout(() => {
logger.log(`Ensured death of ${worker.id}`);
worker.kill();
}, deadline).unref();
worker.disconnect();
}
function respawn(worker, code, signal) {
if (running && !worker.exitedAfterDisconnect) {
logger.log(`Respawning ${worker.id} after it exited`);
spawn();
}
}
function listen() {
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
cluster.on('exit', respawn);
}
function shutdown() {
running = false;
logger.log(`Shutting down!`);
for (var id in cluster.workers) {
kill(cluster.workers[id]);
}
}
listen();
fork();
}
Regiment.middleware = require('./middleware');
module.exports = Regiment;
| HustleInc/regiment | lib/regiment.js | JavaScript | mit | 2,225 |
var chai = require('chai')
, expect = chai.expect
, Support = require(__dirname + '/../support')
, dialect = Support.getTestDialect()
, DataTypes = require(__dirname + "/../../lib/data-types")
, _ = require('lodash')
, sequelize = require(__dirname + '/../../lib/sequelize');
chai.config.includeStack = true
if (dialect.match(/^postgres/)) {
describe('[POSTGRES Specific] DAO', function() {
beforeEach(function(done) {
this.sequelize.options.quoteIdentifiers = true
this.User = this.sequelize.define('User', {
username: DataTypes.STRING,
email: { type: DataTypes.ARRAY(DataTypes.TEXT) },
settings: DataTypes.HSTORE,
document: { type: DataTypes.HSTORE, defaultValue: { default: 'value' } },
phones: DataTypes.ARRAY(DataTypes.HSTORE),
emergency_contact: DataTypes.JSON
})
this.User.sync({ force: true }).success(function() {
done()
})
})
afterEach(function(done) {
this.sequelize.options.quoteIdentifiers = true
done()
})
it('should be able to search within an array', function(done) {
this.User.all({where: {email: ['hello', 'world']}}).on('sql', function(sql) {
expect(sql).to.equal('SELECT "id", "username", "email", "settings", "document", "phones", "emergency_contact", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."email" && ARRAY[\'hello\',\'world\']::TEXT[];')
done()
})
})
it('should be able to find a record while searching in an array', function(done) {
var self = this
this.User.bulkCreate([
{username: 'bob', email: ['myemail@email.com']},
{username: 'tony', email: ['wrongemail@email.com']}
]).success(function() {
self.User.all({where: {email: ['myemail@email.com']}}).success(function(user) {
expect(user).to.be.instanceof(Array)
expect(user).to.have.length(1)
expect(user[0].username).to.equal('bob')
done()
})
})
})
describe('json', function () {
it('should tell me that a column is json', function() {
return this.sequelize.queryInterface.describeTable('Users')
.then(function (table) {
expect(table.emergency_contact.type).to.equal('JSON');
});
});
it('should stringify json with insert', function () {
return this.User.create({
username: 'bob',
emergency_contact: { name: 'joe', phones: [1337, 42] }
}).on('sql', function (sql) {
var expected = 'INSERT INTO "Users" ("id","username","document","emergency_contact","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',\'"default"=>"value"\',\'{"name":"joe","phones":[1337,42]}\''
expect(sql.indexOf(expected)).to.equal(0);
});
});
it('should be able retrieve json value as object', function () {
var self = this;
var emergencyContact = { name: 'kate', phone: 1337 };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact); // .eql does deep value comparison instead of strict equal comparison
return self.User.find({ where: { username: 'swen' }, attributes: ['emergency_contact'] });
})
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
});
});
it('should be able to retrieve element of array by index', function () {
var self = this;
var emergencyContact = { name: 'kate', phones: [1337, 42] };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.phones.1'), 'firstEmergencyNumber']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('firstEmergencyNumber'))).to.equal(42);
});
});
it('should be able to retrieve root level value of an object by key', function () {
var self = this;
var emergencyContact = { kate: 1337 };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate'), 'katesNumber']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('katesNumber'))).to.equal(1337);
});
});
it('should be able to retrieve nested value of an object by path', function () {
var self = this;
var emergencyContact = { kate: { email: 'kate@kate.com', phones: [1337, 42] } };
return this.User.create({ username: 'swen', emergency_contact: emergencyContact })
.then(function (user) {
expect(user.emergency_contact).to.eql(emergencyContact);
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate.email'), 'katesEmail']] });
})
.then(function (user) {
expect(user.getDataValue('katesEmail')).to.equal('kate@kate.com');
})
.then(function () {
return self.User.find({ where: { username: 'swen' }, attributes: [[sequelize.json('emergency_contact.kate.phones.1'), 'katesFirstPhone']] });
})
.then(function (user) {
expect(parseInt(user.getDataValue('katesFirstPhone'))).to.equal(42);
});
});
it('should be able to retrieve a row based on the values of the json document', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({ where: sequelize.json("emergency_contact->>'name'", 'kate'), attributes: ['username', 'emergency_contact'] });
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('kate');
});
});
it('should be able to query using the nested query language', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({
where: sequelize.json({ emergency_contact: { name: 'kate' } })
});
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('kate');
});
});
it('should be ablo to query using dot syntax', function () {
var self = this;
return this.sequelize.Promise.all([
this.User.create({ username: 'swen', emergency_contact: { name: 'kate' } }),
this.User.create({ username: 'anna', emergency_contact: { name: 'joe' } })])
.then(function () {
return self.User.find({ where: sequelize.json('emergency_contact.name', 'joe') });
})
.then(function (user) {
expect(user.emergency_contact.name).to.equal('joe');
});
});
});
describe('hstore', function() {
it('should tell me that a column is hstore and not USER-DEFINED', function(done) {
this.sequelize.queryInterface.describeTable('Users').success(function(table) {
expect(table.settings.type).to.equal('HSTORE')
expect(table.document.type).to.equal('HSTORE')
done()
})
})
it('should stringify hstore with insert', function(done) {
this.User.create({
username: 'bob',
email: ['myemail@email.com'],
settings: {mailing: false, push: 'facebook', frequency: 3}
}).on('sql', function(sql) {
var expected = 'INSERT INTO "Users" ("id","username","email","settings","document","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"mailing"=>false,"push"=>"facebook","frequency"=>3\',\'"default"=>"value"\''
expect(sql.indexOf(expected)).to.equal(0)
done()
})
})
})
describe('enums', function() {
it('should be able to ignore enum types that already exist', function(done) {
var User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
User.sync({ force: true }).success(function() {
User.sync().success(function() {
done()
})
})
})
it('should be able to create/drop enums multiple times', function(done) {
var User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
User.sync({ force: true }).success(function() {
User.sync({ force: true }).success(function() {
done()
})
})
})
it("should be able to create/drop multiple enums multiple times", function(done) {
var DummyModel = this.sequelize.define('Dummy-pg', {
username: DataTypes.STRING,
theEnumOne: {
type: DataTypes.ENUM,
values:[
'one',
'two',
'three',
]
},
theEnumTwo: {
type: DataTypes.ENUM,
values:[
'four',
'five',
'six',
],
}
})
DummyModel.sync({ force: true }).done(function(err) {
expect(err).not.to.be.ok
// now sync one more time:
DummyModel.sync({force: true}).done(function(err) {
expect(err).not.to.be.ok
// sync without dropping
DummyModel.sync().done(function(err) {
expect(err).not.to.be.ok
done();
})
})
})
})
it('should be able to add enum types', function(done) {
var self = this
, User = this.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('happy', 'sad', 'meh')
})
var _done = _.after(4, function() {
done()
})
User.sync({ force: true }).success(function() {
User = self.sequelize.define('UserEnums', {
mood: DataTypes.ENUM('neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful')
})
User.sync().success(function() {
expect(User.rawAttributes.mood.values).to.deep.equal(['neutral', 'happy', 'sad', 'ecstatic', 'meh', 'joyful'])
_done()
}).on('sql', function(sql) {
if (sql.indexOf('neutral') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'neutral' BEFORE 'happy'")
_done()
}
else if (sql.indexOf('ecstatic') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'ecstatic' BEFORE 'meh'")
_done()
}
else if (sql.indexOf('joyful') > -1) {
expect(sql).to.equal("ALTER TYPE \"enum_UserEnums_mood\" ADD VALUE 'joyful' AFTER 'meh'")
_done()
}
})
})
})
})
describe('integers', function() {
describe('integer', function() {
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
aNumber: DataTypes.INTEGER
})
this.User.sync({ force: true }).success(function() {
done()
})
})
it('positive', function(done) {
var User = this.User
User.create({aNumber: 2147483647}).success(function(user) {
expect(user.aNumber).to.equal(2147483647)
User.find({where: {aNumber: 2147483647}}).success(function(_user) {
expect(_user.aNumber).to.equal(2147483647)
done()
})
})
})
it('negative', function(done) {
var User = this.User
User.create({aNumber: -2147483647}).success(function(user) {
expect(user.aNumber).to.equal(-2147483647)
User.find({where: {aNumber: -2147483647}}).success(function(_user) {
expect(_user.aNumber).to.equal(-2147483647)
done()
})
})
})
})
describe('bigint', function() {
beforeEach(function(done) {
this.User = this.sequelize.define('User', {
aNumber: DataTypes.BIGINT
})
this.User.sync({ force: true }).success(function() {
done()
})
})
it('positive', function(done) {
var User = this.User
User.create({aNumber: '9223372036854775807'}).success(function(user) {
expect(user.aNumber).to.equal('9223372036854775807')
User.find({where: {aNumber: '9223372036854775807'}}).success(function(_user) {
expect(_user.aNumber).to.equal('9223372036854775807')
done()
})
})
})
it('negative', function(done) {
var User = this.User
User.create({aNumber: '-9223372036854775807'}).success(function(user) {
expect(user.aNumber).to.equal('-9223372036854775807')
User.find({where: {aNumber: '-9223372036854775807'}}).success(function(_user) {
expect(_user.aNumber).to.equal('-9223372036854775807')
done()
})
})
})
})
})
describe('model', function() {
it("create handles array correctly", function(done) {
this.User
.create({ username: 'user', email: ['foo@bar.com', 'bar@baz.com'] })
.success(function(oldUser) {
expect(oldUser.email).to.contain.members(['foo@bar.com', 'bar@baz.com'])
done()
})
.error(function(err) {
console.log(err)
})
})
it("should save hstore correctly", function(done) {
this.User
.create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
.success(function(newUser) {
// Check to see if the default value for an hstore field works
expect(newUser.document).to.deep.equal({ default: 'value' })
expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})
// Check to see if updating an hstore field works
newUser.updateAttributes({settings: {should: 'update', to: 'this', first: 'place'}}).success(function(oldUser){
// Postgres always returns keys in alphabetical order (ascending)
expect(oldUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
done()
})
})
.error(console.log)
})
it('should save hstore array correctly', function(done) {
this.User.create({
username: 'bob',
email: ['myemail@email.com'],
phones: [{ number: '123456789', type: 'mobile' }, { number: '987654321', type: 'landline' }]
}).on('sql', function(sql) {
var expected = 'INSERT INTO "Users" ("id","username","email","document","phones","createdAt","updatedAt") VALUES (DEFAULT,\'bob\',ARRAY[\'myemail@email.com\']::TEXT[],\'"default"=>"value"\',ARRAY[\'"number"=>"123456789","type"=>"mobile"\',\'"number"=>"987654321","type"=>"landline"\']::HSTORE[]'
expect(sql).to.contain(expected)
done()
})
})
it("should update hstore correctly", function(done) {
var self = this
this.User
.create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
.success(function(newUser) {
// Check to see if the default value for an hstore field works
expect(newUser.document).to.deep.equal({default: 'value'})
expect(newUser.settings).to.deep.equal({ created: { test: '"value"' }})
// Check to see if updating an hstore field works
self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, {where: newUser.identifiers}).success(function() {
newUser.reload().success(function() {
// Postgres always returns keys in alphabetical order (ascending)
expect(newUser.settings).to.deep.equal({first: 'place', should: 'update', to: 'this'})
done()
});
})
})
.error(console.log)
})
it("should update hstore correctly and return the affected rows", function(done) {
var self = this
this.User
.create({ username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
.success(function(oldUser) {
// Update the user and check that the returned object's fields have been parsed by the hstore library
self.User.update({settings: {should: 'update', to: 'this', first: 'place'}}, {where: oldUser.identifiers, returning: true }).spread(function(count, users) {
expect(count).to.equal(1);
expect(users[0].settings).to.deep.equal({should: 'update', to: 'this', first: 'place'})
done()
})
})
.error(console.log)
})
it("should read hstore correctly", function(done) {
var self = this
var data = { username: 'user', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}}
this.User
.create(data)
.success(function() {
// Check that the hstore fields are the same when retrieving the user
self.User.find({ where: { username: 'user' }})
.success(function(user) {
expect(user.settings).to.deep.equal(data.settings)
done()
})
})
.error(console.log)
})
it('should read an hstore array correctly', function(done) {
var self = this
var data = { username: 'user', email: ['foo@bar.com'], phones: [{ number: '123456789', type: 'mobile' }, { number: '987654321', type: 'landline' }] }
this.User
.create(data)
.success(function() {
// Check that the hstore fields are the same when retrieving the user
self.User.find({ where: { username: 'user' }})
.success(function(user) {
expect(user.phones).to.deep.equal(data.phones)
done()
})
})
})
it("should read hstore correctly from multiple rows", function(done) {
var self = this
self.User
.create({ username: 'user1', email: ['foo@bar.com'], settings: { created: { test: '"value"' }}})
.then(function() {
return self.User.create({ username: 'user2', email: ['foo2@bar.com'], settings: { updated: { another: '"example"' }}})
})
.then(function() {
// Check that the hstore fields are the same when retrieving the user
return self.User.findAll({ order: 'username' })
})
.then(function(users) {
expect(users[0].settings).to.deep.equal({ created: { test: '"value"' }})
expect(users[1].settings).to.deep.equal({ updated: { another: '"example"' }})
done()
})
.error(console.log)
})
})
describe('[POSTGRES] Unquoted identifiers', function() {
it("can insert and select", function(done) {
var self = this
this.sequelize.options.quoteIdentifiers = false
this.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = false
this.User = this.sequelize.define('Userxs', {
username: DataTypes.STRING,
fullName: DataTypes.STRING // Note mixed case
}, {
quoteIdentifiers: false
})
this.User.sync({ force: true }).success(function() {
self.User
.create({ username: 'user', fullName: "John Smith" })
.success(function(user) {
// We can insert into a table with non-quoted identifiers
expect(user.id).to.exist
expect(user.id).not.to.be.null
expect(user.username).to.equal('user')
expect(user.fullName).to.equal('John Smith')
// We can query by non-quoted identifiers
self.User.find({
where: {fullName: "John Smith"}
})
.success(function(user2) {
self.sequelize.options.quoteIndentifiers = true
self.sequelize.getQueryInterface().QueryGenerator.options.quoteIdentifiers = true
self.sequelize.options.logging = false
// We can map values back to non-quoted identifiers
expect(user2.id).to.equal(user.id)
expect(user2.username).to.equal('user')
expect(user2.fullName).to.equal('John Smith')
done()
})
})
})
})
})
})
}
| cusspvz/sequelize | test/postgres/dao.test.js | JavaScript | mit | 21,724 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import { post } from '../../api';
class PostActionButton extends Component {
static propTypes = {
bsStyle: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
hideContentOnAction: PropTypes.bool.isRequired,
action: PropTypes.string.isRequired,
body: PropTypes.object.isRequired,
onSuccess: PropTypes.func,
onError: PropTypes.func,
};
static defaultProps = {
body: {},
hideContentOnAction: false,
onSuccess: () => {},
onError: () => {},
};
constructor(props) {
super(props);
this.state = { isWorking: false };
}
onClick = () => {
this.setState({ isWorking: true });
const { body, action, onSuccess, onError } = this.props;
post(action, body).then(() => {
this.setState({ isWorking: false });
onSuccess();
}, (err) => {
console.error(err);
onError(err);
});
};
render() {
const { isWorking } = this.state;
const { hideContentOnAction, bsStyle, children } = this.props;
const renderChildren = !isWorking || (isWorking && !hideContentOnAction);
return (
<Button onClick={this.onClick} bsStyle={bsStyle}>
{isWorking &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {renderChildren && children}
</Button>
);
}
}
export default PostActionButton;
| DjLeChuck/recalbox-manager | client/src/components/utils/PostActionButton.js | JavaScript | mit | 1,526 |
import $ from 'jquery'
const DURATION_MS = 400
export default function scrollToTop () {
const scrollTop = $('.auction-artworks-HeaderDesktop').offset().top - $('.mlh-navbar').height()
$('html,body').animate({ scrollTop }, DURATION_MS)
}
| kanaabe/force | src/desktop/apps/auction/utils/scrollToTop.js | JavaScript | mit | 243 |
version https://git-lfs.github.com/spec/v1
oid sha256:96c89faf399ad903c813617aca830b28b3330c35d8af37d08743722e06d9323d
size 84
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.18.0/dd-drop/index.js | JavaScript | mit | 127 |
module.exports = function(grunt) {
grunt.initConfig({
web_server: {
options: {
cors: true,
port: 8000,
nevercache: true,
logRequests: true
},
foo: 'bar'
},
uglify: {
my_target: {
files: {
'dist/ng-video-preview.min.js': ['video-preview.js']
}
}
},
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-web-server');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', ['jshint']);
}; | jiin/ng-video-preview | Gruntfile.js | JavaScript | mit | 831 |
var model = require('./model');
var backbone = require('backbone');
var fs = require('fs');
var util = require('util');
var fpath = require('path');
var hive = require('./hive');
var EMPTY_FILE = '';
var exports = module.exports = model.extend({
initialize: function(attributes) {
var _self = this;
var path = this.get('path');
if(path) {
var name = fpath.basename(path);
if(name) {
this.set({name: name});
}
if(attributes.watch) {
fs.watchFile(path, function() {
_self.sync('read', _self);
_self.change();
});
}
}
return this;
},
ext: function() {
return fpath.extname(this.get('name'));
},
absolute: function() {
return fpath.resolve(this.get('path'));
},
dir: function() {
return fpath.dirname(this.absolute());
},
sync: function(method, model) {
model.syncing = true;
var path = model.absolute();
switch(method) {
case 'create':
case 'update':
hive.log(method + '-ing file @ ' + path);
fs.writeFile(path, model.get('data') || EMPTY_FILE, model.get('encoding'), function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: model.get('data'), exists: true}, true);
});
break;
case 'read':
hive.log(method + '-ing file @ ' + path);
fs.readFile(path, function(err, data) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: data.toString(), exists: true});
});
break;
case 'delete':
hive.log(method + '-ing file @ ' + path);
fs.unlink(path, function(err) {
hive.log(method + 'd file @ ' + path);
if(err) return model.error(err);
model.success({data: null, exists: false});
});
break;
}
},
paste: function(destination, name) {
var _self = this;
_self.syncing = true;
if(typeof destination === 'string') {
destination = new hive.Dir({path: destination});
}
var name = name || _self.get('name'),
path = destination.get('path') + '/' + name;
if(!path) _self.error('Could not paste file to hive.Dir without a path');
var i = fs.createReadStream(_self.get('path')),
o = fs.createWriteStream(path);
util.pump(i, o, function() {
hive.log('wrote file @ ' + path);
_self.trigger('pasted');
_self.success({data: o});
});
return this;
},
update: function(callback, done) {
var _self = this;
hive.log('**UPDATING**', _self);
_self.fetch(function() {
hive.log('**UPDATING**', 'fetched');
hive.log('**UPDATING** data - ', _self.get('data'));
var changed = callback(_self.get('data') || '');
hive.log('**UPDATING** changed - ', changed);
_self.set({data: changed}, {silent: true});
_self.once('success', function() {
hive.log('**UPDATING**', 'done');
done && done();
});
_self.save();
});
}
}); | oayandosu/hive | lib/file.js | JavaScript | mit | 2,837 |
/**
min任务
-------------
min脚本,样式,图片或html
### 用法
<min src='my.js' dest='my.min.js'/>
<min file='reset.css' destfile='reset.min.css'/>
@class min
**/
module.exports = function(bee) {
bee.register('min', function(options, callback) {
var path = require('path');
var minifier = require('node-minifier');
var src = options.src || options.file;
var destfile = options.destfile || options.dest;
if (!src || !destfile) {
return callback(new Error('src/file and dest/destfile are required in minify task.'));
}
var childNodes = options.childNodes;
var banner, footer;
options.childNodes.forEach(function(item){
if(item.name === 'banner' || item.name === 'header'){
banner = item.value.value;
}else if(item.name === 'footer'){
footer = item.value.value;
}
});
var readWrite = function(transform, input, output, callback) {
var encoding = options.encoding || 'utf-8';
var filecontent = bee.file.read(input, encoding);
filecontent = transform(filecontent, options);
bee.file.mkdir(path.dirname(output));
bee.file.write(output, filecontent, encoding);
callback();
}
var minifyJS = function(input, output, callback) {
bee.log('minify JS input:' + input + ' output: ' + output);
var remove = options.remove ? options.remove.split(',') : [];
readWrite(function(filecontent) {
return minifier.minifyJS(filecontent, {
remove: remove,
copyright: options.copyright || true,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyCSS = function(input, output, callback) {
bee.log('minify CSS input:' + input + ' output: ' + output);
readWrite(function(filecontent) {
return minifier.minifyCSS(filecontent, {
datauri: options.datauri,
banner: banner,
footer: footer
});
}, input, output, callback);
}
var minifyHTML = function(input, output, callback) {
bee.log('minify HTML input:' + input + ' output: ' + output);
options.banner = banner;
options.footer = footer;
readWrite(function(filecontent) {
return minifier.minifyHTML(filecontent, options);
}, input, output, callback);
}
var minifyImage = function(input, output, callback) {
bee.log('minify Image input:' + input + ' output: ' + output);
minifier.minifyImage(input, output, function(e, data) {
if (e) {
callback && callback(e);
} else {
callback(null);
}
}, {
service: options.service
})
}
var extname = options.type || bee.file.extname(src).toLowerCase();
var method;
if (extname == 'js') {
method = minifyJS;
} else if (extname == 'css') {
method = minifyCSS;
} else if (['html', 'htm'].indexOf(extname) >= 0) {
method = minifyHTML;
} else if (['png', 'jpg', 'jpeg', 'gif'].indexOf(extname) >= 0) {
method = minifyImage;
}
if(!method){
bee.warn('the filetype of ' + src + ' cannot be minified.')
return callback();
}
method(src, destfile, callback);
});
} | colorhook/bee-min | lib/min.js | JavaScript | mit | 3,378 |
// Generated by CoffeeScript 1.10.0
(function() {
(function($) {
return $(".some_button").on("click", function(event) {
console.log("some_button clicked!");
return event.preventDefault();
});
})(jQuery);
}).call(this);
| 17koa/source | web/coffee/compiled/click-with-callback.js | JavaScript | mit | 244 |
const mongoose = require('mongoose')
const TABLE_NAME = 'Post'
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const escape = (require('../utils')).escape
const PostSchema = new Schema({
//类型
type: {
type: String,
default: 'post' // post | page
},
//标题
title: {
type: String,
trim: true,
set: escape
},
//别名
alias: {
type: String,
trim: true,
set: escape
},
//创建者
user: {
type: ObjectId,
ref: 'User'
},
//类别
category: {
type: ObjectId,
ref: 'Category'
},
//摘要
excerpt: {
type: String,
trim: true,
},
//内容
contents: {
type: String,
trim: true,
},
//markdown
markdown: {
type: String,
trim: true,
},
//标签
tags: Array,
//缩略图
thumbnail: {
type: String,
trim: true,
set: escape
},
//统计
count: {
//浏览次数
views: {
type: Number,
default: 1,
},
//评论数
comments: {
type: Number,
default: 0,
},
//点赞数
praises: {
type: Number,
default: 1
}
},
//状态
status: {
type: Number,
default: 1 // 1:发布, 0 :草稿, -1 :删除
},
//置顶
top: Boolean,
//允许评论
allowComment: {
type: Boolean,
default: true
},
//允许打赏
allowReward: Boolean,
//著名版权
license: Boolean,
//使用密码
usePassword: Boolean,
//密码
password: {
type: String,
trim: true
},
order: {
type: Number,
default: 1
},
//创建时间
createTime: {
type: Date,
default: Date.now()
},
//修改时间
updateTime: {
type: Date,
default: Date.now()
}
}, {
connection: TABLE_NAME,
versionKey: false,
})
module.exports = mongoose.model(TABLE_NAME, PostSchema) | S-mohan/mblog | server/model/post.js | JavaScript | mit | 1,843 |
var test = require("tape")
var mongo = require("continuable-mongo")
var uuid = require("node-uuid")
var setTimeout = require("timers").setTimeout
var eventLog = require("../index")
var client = mongo("mongodb://localhost:27017/colingo-group-tests")
var collectionName = uuid()
var col = client.collection(collectionName)
var rawCollection = client.collection(collectionName + "@")
var SECOND = 1000
var MINUTE = 60 * SECOND
var HOUR = 60 * MINUTE
test("ensure col is capped", function (assert) {
client(function (err, db) {
assert.ifError(err)
db.createCollection(collectionName, {
capped: true
, size: 100000
}, function (err, res) {
assert.ifError(err)
assert.end()
})
})
})
test("can add to eventLog", function (assert) {
var log = eventLog(col, {
timeToLive: HOUR
, rawCollection: rawCollection
})
var id = uuid()
log.add("add", {
id: id
, timestamp: Date.now()
, type: "some-event"
}, function (err, value) {
assert.ifError(err)
assert.equal(value.eventType, "add")
assert.ok(value._id)
assert.equal(value.value.id, id)
log.close()
assert.end()
})
})
test("can read from eventLog", function (assert) {
var log = eventLog(col, {
rawCollection: rawCollection
, timeToLive: HOUR
})
var stream = log.read(Date.now() - 1000)
setTimeout(function () {
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted after"
}, function (err, value) {
assert.ifError(err)
})
}, 20)
log.add("add", {
id: uuid()
, timestamp: Date.now()
, type: "some-event"
, foo: "inserted before"
}, function (err, value) {
assert.ifError(err)
var list = []
var cleanupCounter = 2
stream.on("data", function (chunk) {
list.push(chunk)
if (list.length === 3) {
next()
}
})
stream.resume()
function next() {
assert.equal(list.length, 3)
assert.equal(list[0].value.type, "some-event")
assert.equal(list[1].value.foo, "inserted before")
assert.equal(list[2].value.foo, "inserted after")
rawCollection(function (err, rawCollection) {
assert.ifError(err)
rawCollection.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
col(function (err, col) {
assert.ifError(err)
col.drop(function (err) {
assert.ifError(err)
if (--cleanupCounter === 0) {
cleanup()
}
})
})
}
function cleanup() {
log.close()
client.close(function (err) {
assert.ifError(err)
assert.end()
})
}
})
})
| Colingo/event-log | test/simple.js | JavaScript | mit | 3,258 |
version https://git-lfs.github.com/spec/v1
oid sha256:356614d2260c69b92680d59e99601dcd5e068f761756f22fb959b5562b9a7d62
size 17413
| yogeshsaroya/new-cdnjs | ajax/libs/json2/20110223/json2.js | JavaScript | mit | 130 |
import * as React from 'react';
import {Row,Col,Table,Code,Items,Item} from 'yrui';
import thead from './thead';
let items=[{
key:'style',
expr:'设置items样式',
type:'object',
values:'-',
default:'-',
}];
let item=[{
key:'border',
expr:'设置border样式',
type:'string',
values:'-',
default:'-',
}];
const code=`
<Items>
<Item>
<h2>items配置</h2>
<Table thead={thead} tbody={items} />
</Item>
<Item>
<h2>item配置</h2>
<Table thead={thead} tbody={item} />
</Item>
</Items>
`;
export default class ItemsDemo extends React.Component{
render(){
return(
<Items>
<Item>
<h2>代码示例</h2>
<Code title="input" code={code} />
</Item>
<Item>
<Row gutter={8}>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={items} noBorder={true} />
</Col>
<Col span={6} sm={12}>
<h2>参数说明</h2>
<Table thead={thead} tbody={item} noBorder={true} />
</Col>
</Row>
</Item>
</Items>
);
}
}
| ahyiru/phoenix-boilerplate | app/api/itemdemo.js | JavaScript | mit | 1,154 |
define(function() {
'use strict';
/* @ngInject */
var gameCtrl = function($scope, commoditySrvc, citySrvc, accountSrvc, gameSrvc, tutorialSrvc, $modal) {
//todo: find a better way to expose services to template
this.gameSrvc = gameSrvc;
this.commoditySrvc = commoditySrvc;
this.citySrvc = citySrvc;
this.accountSrvc = accountSrvc;
this.tutorialOptions = tutorialSrvc.options;
this.$modal = $modal;
this.$scope = $scope;
if (!citySrvc.currentCity) {
commoditySrvc.setCitySpecialty();
citySrvc.getRandomCity();
commoditySrvc.updatePrices();
}
//todo: figure out why this ctrl gets called twice on page load
if (gameSrvc.initialLoad) {
this.showModal('start');
gameSrvc.initialLoad = false;
}
};
gameCtrl.prototype.submitScore = function() {
this.showModal('gameOver', this.accountSrvc.netWorth);
this.gameSrvc.gameOver();
};
gameCtrl.prototype.goToCity = function(city) {
this.citySrvc.setCurrentCity(city);
this.commoditySrvc.updatePrices();
this.gameSrvc.reduceDaysLeft();
};
gameCtrl.prototype.buyItem = function(item, quantity) {
this.commoditySrvc.buyCommodity(item, quantity);
};
gameCtrl.prototype.sellItem = function(item) {
this.commoditySrvc.sellCommodity(item);
};
gameCtrl.prototype.setMarketHoverItem = function(item) {
this.marketHoverItem = item.name;
};
gameCtrl.prototype.resetMarketHoverItem = function() {
this.marketHoverItem = '';
};
gameCtrl.prototype.isCurrentCity = function(city) {
return city.name === this.citySrvc.currentCity.name;
};
gameCtrl.prototype.getPotentialProfit = function(item) {
var expectedProfit = 'unknown';
if (item.averageSellPrice) {
expectedProfit = ((item.averageSellPrice - item.currentPrice) * item.maxQuantityPurchasable) / 100;
}
return expectedProfit;
};
gameCtrl.prototype.openMenu = function() {
this.showModal('gameMenu');
};
gameCtrl.prototype.showModal = function(type, score) {
var templateUrl, self = this;
switch (type) {
case 'start':
templateUrl = 'components/game/gameModalStart.tmpl.html';
break;
case 'gameMenu':
templateUrl = 'components/game/gameModalGameMenu.tmpl.html';
break;
case 'gameOver':
templateUrl = 'components/game/gameModalGameOver.tmpl.html';
break;
}
var modalInstance = this.$modal.open({
templateUrl: templateUrl,
controller: 'gameModalInstanceCtrl',
size: 'sm',
resolve: {
type: function() {
return type;
},
score: function() {
return score;
}
}
});
modalInstance.result.then(function(action) {
switch (action) {
case 'startTutorial':
self.$scope.startTutorial();
break;
case 'resetGame':
self.gameSrvc.gameOver(true);
break;
}
}, function() {
});
};
return gameCtrl;
}); | jarekb84/ngTrader | app/components/game/gameCtrl.js | JavaScript | mit | 3,023 |
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
// Example route
// var user = require('./routes/user');
// below added by tommy
var login = require('./routes/login');
var messages = require('./routes/messages');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// Add routes here
app.get('/', index.view);
// Example route
// app.get('/users', user.list);
//below added by tommy
app.get('/login', login.view);
app.get('/messages', messages.view);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
| Vanemoinen/div-a6-login | app.js | JavaScript | mit | 1,342 |
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import React from 'react';
import EditMediaDialog from '../../containers/EditMediaDialog';
import LoginDialog from '../../containers/LoginDialog';
import PreviewMediaDialog from '../../containers/PreviewMediaDialog';
var _ref =
/*#__PURE__*/
_jsx("div", {
className: "Dialogs"
}, void 0, _jsx(EditMediaDialog, {}), _jsx(LoginDialog, {}), _jsx(PreviewMediaDialog, {}));
var Dialogs = function Dialogs() {
return _ref;
};
export default Dialogs;
//# sourceMappingURL=index.js.map
| welovekpop/uwave-web-welovekpop.club | es/components/Dialogs/index.js | JavaScript | mit | 540 |
import {
addClass,
removeClass,
EVENTS,
on,
off,
getViewportSize,
getClosest,
getParents
} from '../../utils/domUtils'
import {nodeListToArray} from '../../utils/arrayUtils'
function ScrollSpy (element, target = 'body', options = {}) {
this.el = element
this.opts = Object.assign({}, ScrollSpy.DEFAULTS, options)
this.opts.target = target
if (target === 'body') {
this.scrollElement = window
} else {
this.scrollElement = document.querySelector(`[id=${target}]`)
}
this.selector = 'li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
if (this.scrollElement) {
this.refresh()
this.process()
}
}
ScrollSpy.DEFAULTS = {
offset: 10,
callback: (ele) => 0
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
const isWindow = this.scrollElement === window
list
.map(ele => {
const href = ele.getAttribute('href')
if (/^#./.test(href)) {
const doc = document.documentElement
const rootEl = isWindow ? document : this.scrollElement
const hrefEl = rootEl.querySelector(`[id='${href.slice(1)}']`)
const windowScrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0)
const offset = isWindow ? hrefEl.getBoundingClientRect().top + windowScrollTop : hrefEl.offsetTop + this.scrollElement.scrollTop
return [offset, href]
} else {
return null
}
})
.filter(item => item)
.sort((a, b) => a[0] - b[0])
.forEach(item => {
this.offsets.push(item[0])
this.targets.push(item[1])
})
// console.log(this.offsets, this.targets)
}
ScrollSpy.prototype.process = function () {
const isWindow = this.scrollElement === window
const scrollTop = (isWindow ? window.pageYOffset : this.scrollElement.scrollTop) + this.opts.offset
const scrollHeight = this.getScrollHeight()
const scrollElementHeight = isWindow ? getViewportSize().height : this.scrollElement.getBoundingClientRect().height
const maxScroll = this.opts.offset + scrollHeight - scrollElementHeight
const offsets = this.offsets
const targets = this.targets
const activeTarget = this.activeTarget
let i
if (this.scrollHeight !== scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget !== (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget !== targets[i] &&
scrollTop >= offsets[i] &&
(offsets[i + 1] === undefined || scrollTop < offsets[i + 1]) &&
this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
const selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
const activeCallback = this.opts.callback
let active = nodeListToArray(this.el.querySelectorAll(selector))
active.forEach(ele => {
getParents(ele, 'li')
.forEach(item => {
addClass(item, 'active')
activeCallback(item)
})
if (getParents(ele, '.dropdown-menu').length) {
addClass(getClosest(ele, 'li.dropdown'), 'active')
}
})
}
ScrollSpy.prototype.clear = function () {
let list = nodeListToArray(this.el.querySelectorAll(this.selector))
list.forEach(ele => {
getParents(ele, '.active', this.opts.target).forEach(item => {
removeClass(item, 'active')
})
})
}
const INSTANCE = '_uiv_scrollspy_instance'
const events = [EVENTS.RESIZE, EVENTS.SCROLL]
const bind = (el, binding) => {
// console.log('bind')
unbind(el)
}
const inserted = (el, binding) => {
// console.log('inserted')
const scrollSpy = new ScrollSpy(el, binding.arg, binding.value)
if (scrollSpy.scrollElement) {
scrollSpy.handler = () => {
scrollSpy.process()
}
events.forEach(event => {
on(scrollSpy.scrollElement, event, scrollSpy.handler)
})
}
el[INSTANCE] = scrollSpy
}
const unbind = (el) => {
// console.log('unbind')
let instance = el[INSTANCE]
if (instance && instance.scrollElement) {
events.forEach(event => {
off(instance.scrollElement, event, instance.handler)
})
delete el[INSTANCE]
}
}
const update = (el, binding) => {
// console.log('update')
const isArgUpdated = binding.arg !== binding.oldArg
const isValueUpdated = binding.value !== binding.oldValue
if (isArgUpdated || isValueUpdated) {
bind(el, binding)
inserted(el, binding)
}
}
export default {bind, unbind, update, inserted}
| wxsms/uiv | src/directives/scrollspy/scrollspy.js | JavaScript | mit | 4,954 |
import { red } from "./colors.js";
export default `body { background: url("${
new URL("./file.png" + __resourceQuery, import.meta.url).href
}"); color: ${red}; }`;
| webpack/webpack | test/configCases/loader-import-module/css/stylesheet.js | JavaScript | mit | 165 |
angular.module('app').directive('ngReallyClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.ngReallyMessage;
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
});
}
}
}]); | flextry/RateMyX | public/app/directives/reallyClick.js | JavaScript | mit | 407 |
// New Spotify object
function Spotify(tab){
this.tab = tab;
}
// search for a song
// open spotify if theres a match
Spotify.prototype.search = function(title, artist, album){
var query = 'title:"' + title + '"';
query += 'artist:"' + artist + '"';
if(album){
query += 'album:"' + album + '"';
}
$.ajax(
{
'url': constants.SPOTIFY.SEARCH,
'type': 'GET',
'data': {
'q': query
}
}
).then(
this.determineSearch.bind(this),
function(){
this.tab.sendServiceAction(
false,
'Error searching for song on Spotify',
'open',
'Spotify'
);
}.bind(this)
)
}
// does the search result match what we provided it?
// If so open Spotify app
Spotify.prototype.determineSearch = function(json){
if(json.tracks.length > 0){
this.tab.openThenClose(json.tracks[0].href);
this.tab.sendServiceAction(
true,
'Song opened on Spotify',
'open',
'Spotify'
);
}
else{
this.tab.sendServiceAction(
false,
'Song not found on Spotify',
'open',
'Spotify'
);
}
} | exfm/chrome | js/services/spotify.js | JavaScript | mit | 1,282 |
(function($){
$.fn.extend({
inputNumberFormat: function(options) {
this.defaultOptions = {
'decimal': 2,
'decimalAuto': 2,
'separator': '.',
'separatorAuthorized': ['.', ','],
'allowNegative': false
};
var settings = $.extend({}, this.defaultOptions, options);
var matchValue = function(value, options) {
var found = [];
var regexp = "^[0-9]+";
if (options.allowNegative){
regexp = "^-{0,1}[0-9]*";
}
if(options.decimal) {
regexp += "["+options.separatorAuthorized.join("")+"]?[0-9]{0," + options.decimal + "}";
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
if(!found){
regexp = "^["+options.separatorAuthorized.join("")+"][0-9]{0," + options.decimal + "}";
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
}
}else{
regexp = new RegExp(regexp + "$");
found = value.match(regexp);
}
return found;
}
var formatValue = function(value, options) {
var formatedValue = value;
if(!formatedValue) {
return formatedValue;
}
if(formatedValue == "-") {
return "";
}
formatedValue = formatedValue.replace(",", options.separator);
if(options.decimal && options.decimalAuto) {
formatedValue = Math.round(formatedValue*Math.pow(10,options.decimal))/(Math.pow(10,options.decimal))+"";
if(formatedValue.indexOf(options.separator) === -1) {
formatedValue += options.separator;
}
var nbDecimalToAdd = options.decimalAuto - formatedValue.split(options.separator)[1].length;
for(var i=1; i <= nbDecimalToAdd; i++) {
formatedValue += "0";
}
}
return formatedValue;
}
return this.each(function() {
var $this = $(this);
$this.on('keypress', function(e) {
if(e.ctrlKey) {
return;
}
if(e.key.length > 1) {
return;
}
var options = $.extend({}, settings, $(this).data());
var beginVal = $(this).val().substr(0, e.target.selectionStart);
var endVal = $(this).val().substr(e.target.selectionEnd, $(this).val().length - 1);
var val = beginVal + e.key + endVal;
if(!matchValue(val, options)) {
e.preventDefault();
return;
}
});
$this.on('blur', function(e) {
var options = $.extend({}, settings, $(this).data());
$(this).val(formatValue($(this).val(), options));
});
$this.on('change', function(e) {
var options = $.extend({}, settings, $(this).data());
$(this).val(formatValue($(this).val(), options));
});
});
}
});
})(jQuery);
| 24eme/jquery-input-number-format | input-number-format.jquery.js | JavaScript | mit | 3,669 |
describe("Image", function() {
beforeEach(function() {
$("body").append($('<div id="sandbox"></div>'));
});
afterEach(function() {
$('#sandbox').remove();
$('.ui-dialog').remove();
});
it("add image into item content by factory", function() {
$('#sandbox').wikimate({});
$('#sandbox').wikimate('newItem', {type: 'factory'});
$('.new-image').click();
var image = "data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
$('.image_url_input').val(image);
var done = $('.ui-button').filter(function(i, button) {
return $(button).text() == "Done";
});
done.click();
expect($('#sandbox .item').prop('class')).toEqual('item image');
expect($('#sandbox .item img').length).toEqual(1);
expect($('#sandbox .item img').prop('src')).toEqual(image);
expect($('#sandbox .item').story_item('data').type).toEqual('image');
expect($('#sandbox .item').story_item('data').text).toEqual(image);
});
it("should not add image when image url is blank", function() {
$('#sandbox').wikimate({});
$('#sandbox').wikimate('newItem', {type: 'factory'});
$('.new-image').click();
var done = $('.ui-button').filter(function(i, button) {
return $(button).text() == "Done";
});
done.click();
expect($('#sandbox .item').length).toEqual(0);
});
});
| xli/wikimate | spec/javascripts/image_spec.js | JavaScript | mit | 1,545 |
var dogVideos = [
"http://media.giphy.com/media/l2JHZ7CDZa6jp1rAQ/giphy.mp4",
"http://media.giphy.com/media/26tnmOjq7uQ98qxZC/giphy.mp4",
"http://media.giphy.com/media/26tnazn9Fm4V3VUMU/giphy.mp4",
"http://media.giphy.com/media/26tnhrpR1B6iOnUgo/giphy.mp4",
"http://media.giphy.com/media/26tn2A11Cgd3xvIqc/giphy.mp4",
"http://media.giphy.com/media/l2JHTMc51UdCYCn2o/giphy.mp4",
"http://media.giphy.com/media/l2JI9XQlqkRLYIWCA/giphy.mp4",
"http://media.giphy.com/media/26tn4dAvXHkHcHncQ/giphy.mp4",
"http://media.giphy.com/media/26tn956W5qLmbO9YQ/giphy.mp4",
"http://media.giphy.com/media/l2JHQGY0SoanXpvck/giphy.mp4",
"http://media.giphy.com/media/l2JIcb3CvvjMZ9akU/giphy.mp4",
"http://media.giphy.com/media/26tmZGflCf82PGbjq/giphy.mp4",
"http://media.giphy.com/media/26tn5ZBO276MhXjiw/giphy.mp4",
"http://media.giphy.com/media/26tncxLvZXWff0FlS/giphy.mp4",
"http://media.giphy.com/media/l2JHSUA0chBuwY63e/giphy.mp4",
"http://media.giphy.com/media/l2JIkLzS2M9c5XD0I/giphy.mp4"
];
function displayRandomVideo() {
var randomIndex = Math.floor((Math.random() * dogVideos.length));
$("#dog-video").attr("src", dogVideos[randomIndex]);
$("#video")[0].load();
}
$(document).ready(function(){
displayRandomVideo();
});
| ahimmelstoss/dog-time | public/js/video.js | JavaScript | mit | 1,254 |
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery.serializejson
//= require jquery.transit
//= require underscore
//= require moment
//= require backbone
//= require_tree ./utils
//= require maildog
//= require_tree ../templates
//= require_tree ./mixins
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .
| petrgazarov/Maildog | app/assets/javascripts/application.js | JavaScript | mit | 971 |
angular.module('resource.magacinska', ['ngResource'])
.factory('Kartica', function ($resource) {
return $resource('http://localhost:8080/xws/api/magacinska-karticaK/:idMagacinskaKartica', { idMagacinskaKartica: '@idMagacinskaKartica' }, {
'update': { method:'PUT' }
});
})
| MihailoIsakov/warehaus | frontend/app/scripts/factories/magCardFactory.js | JavaScript | mit | 288 |
/*
---
name: Element.Data.Specs
description: n/a
requires: [Behavior/Element.Data]
provides: [Element.Data.Specs]
...
*/
(function(){
var target = new Element('div', {
'data-filters': 'Test1 Test2',
'data-json':'{"foo": "bar", "nine": 9, "arr": [1, 2, 3]}'
});
describe('Element.Data', function(){
it('should get a data property from an element', function(){
expect(target.getData('filters')).toBe('Test1 Test2');
});
it('should set a data property on an element', function(){
target.setData('foo', 'bar');
expect(target.getData('foo')).toBe('bar');
});
it('should read a property as JSON', function(){
var json = target.getJSONData('json');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should set a property as JSON', function(){
target.setJSONData('json2', {
foo: 'bar', nine: 9, arr: [1,2,3]
});
var json = target.getJSONData('json2');
expect(json.foo).toBe('bar');
expect(json.nine).toBe(9);
expect(json.arr).toEqual([1,2,3]);
});
it('should return null for a non-defined property', function(){
expect(target.getData('baz')).toBeNull();
});
});
})(); | cloudera/behavior | Specs/Behavior/Element.Data.Specs.js | JavaScript | mit | 1,193 |
/*
*
* apiView
*
*/
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { FormattedMessage } from 'react-intl'
import { connect } from 'react-redux'
import ReadMargin from 'components/ReadMargin'
import View from 'components/View'
import P from 'components/P'
import messages from './messages'
class WorldView extends PureComponent {
componentDidMount() {
}
render() {
return (
<div>
<View left={true}>
<ReadMargin>
<P><FormattedMessage {...messages.arasaacInWorld} /></P>
</ReadMargin>
</View>
<iframe src="https://www.google.com/maps/d/u/0/embed?mid=1EBR3psLxK-G_WujU93NMWkfisTYK4HwY" width="100%" height="800"></iframe>
</div>
)
}
}
WorldView.propTypes = {
theme: PropTypes.string.isRequired
}
const mapStateToProps = (state) => ({
theme: state.get('theme')
})
export default connect(mapStateToProps)(WorldView)
| juanda99/arasaac-frontend | app/containers/WorldView/index.js | JavaScript | mit | 950 |
module.exports = function(RED) {
"use strict";
var reconnect = RED.settings.ibmdbReconnectTime || 30000;
var db2 = require('ibm_db');
var Promise = require('promise');
function IbmDBNode(n) {
RED.nodes.createNode(this,n);
this.host = n.host;
this.port = n.port;
this.connected = false;
this.connecting = false;
this.dbname = n.db;
var node = this;
function doConnect(conncb) {
node.connecting = true;
node.conn = {};
node.connection = {
connect: (cb) => {
var conStr = "DRIVER={DB2};DATABASE="+node.dbname
+";HOSTNAME="+node.host
+";UID="+node.credentials.user
+";PWD="+node.credentials.password
+";PORT="+node.port+";PROTOCOL=TCPIP";
db2.open(conStr, function (err,conn) {
if (err) {
cb(err, null);
}
else {
console.log('connection to ' + node.dbname);
conn.connName = node.dbname;
cb(null, conn);
}
});
},
end: (conn) => {
conn.close(() => {
console.log('connection closed');
});
}
};
node.connection.connect(function(err, conn) {
node.connecting = false;
if (err) {
node.error(err);
console.log("connection error " + err);
} else {
node.conn = conn;
node.connected = true;
}
conncb(err);
});
}
this.connect = function() {
return new Promise((resolve, reject) => {
if (!this.connected && !this.connecting) {
doConnect((err)=>{
if(err) reject(err);
else resolve();
});
}
else{
resolve();
}
});
}
this.on('close', function (done) {
if (this.connection) {
node.connection.end(this.conn);
}
done();
});
}
RED.nodes.registerType("IbmDBdatabase", IbmDBNode, {
credentials: {
user: {type: "text"},
password: {type: "password"}
}
});
function IbmDBNodeIn(n) {
RED.nodes.createNode(this,n);
this.mydb = n.mydb;
var node = this;
node.query = function(node, db, msg){
if ( msg.payload !== null && typeof msg.payload === 'string' && msg.payload !== '') {
db.conn.query(msg.payload, function(err, rows) {
if (err) {
console.log("QUERY ERROR "+ err);
node.error(err,msg);
}
else {
rows.forEach(function(row) {
node.send({ topic: msg.topic, payload: row });
})
node.send([ null, { topic: msg.topic, control: 'end' }]);
}
});
}
else {
if (msg.payload === null) {
node.error("msg.payload : the query is not defined");
}
if (typeof msg.payload !== 'string') {
node.error("msg.payload : the query is not defined as a string");
}
if (typeof msg.payload === 'string' && msg.payload === '') {
node.error("msg.payload : the query string is empty");
}
}
}
node.on("input", (msg) => {
if ( msg.database !== null && typeof msg.database === 'string' && msg.database !== '') {
node.mydbNode = RED.nodes.getNode(n.mydb);
if (node.mydbNode) {
node.send([ null, { control: 'start', query: msg.payload, database: n.mydb } ]);
if(node.mydbNode.conn && node.mydbNode.conn.connName === msg.database){
console.log("already connected");
node.query(node, node.mydbNode, msg);
}
else{
var findNode;
RED.nodes.eachNode((node)=>{
if(node.db && node.db === msg.database){
findNode = RED.nodes.getNode(node.id);
node.mydb = node.id;
}
})
findNode.connect()
.then(()=>{
node.query(node, findNode, msg);
});
}
}
else {
this.error("database not configured");
}
}
else{
this.error("database not specified");
}
});
}
RED.nodes.registerType("ibmdb", IbmDBNodeIn);
}
| mfou/node-red-contrib-db2 | ibmdb.js | JavaScript | mit | 5,477 |
import { linkTo } from '@storybook/addon-links';
export default {
title: 'Addon/Links',
};
export const GoToWelcome = () => ({
template: '<my-button :rounded="true" @click="click" >This buttons links to Welcome</my-button>',
methods: {
click: linkTo('Welcome'),
},
});
GoToWelcome.story = {
name: 'Go to welcome',
};
| storybooks/react-storybook | examples/vue-kitchen-sink/src/stories/addon-links.stories.js | JavaScript | mit | 334 |
jQuery(document).ready(function($){
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
//open team-member bio
$('#cd-team').find('ul a').on('click', function(event){
event.preventDefault();
var selected_member = $(this).data('type');
$('.cd-member-bio.'+selected_member+'').addClass('slide-in');
$('#mainNav').hide();
$('.cd-member-bio-close').addClass('is-visible');
// firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden
if( is_firefox ) {
$('main').addClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
$('body').addClass('overflow-hidden');
});
} else {
$('main').addClass('slide-out');
$('body').addClass('overflow-hidden');
}
});
//close team-member bio
$(document).on('click', '.cd-overlay, .cd-member-bio-close', function(event){
event.preventDefault();
$('.cd-member-bio').removeClass('slide-in');
$('#mainNav').show();
$('.cd-member-bio-close').removeClass('is-visible');
if( is_firefox ) {
$('main').removeClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
$('body').removeClass('overflow-hidden');
});
} else {
$('main').removeClass('slide-out');
$('body').removeClass('overflow-hidden');
}
});
}); | MetaProd/MetaProd.github.io | js/main.js | JavaScript | mit | 1,450 |
(function($) {
}) (JQuery); | budaimcs/layout-designer | http/script/app/models.js | JavaScript | mit | 32 |
'use strict';
describe('Service: ScreenSpySrv', function () {
// load the service's module
beforeEach(module('brandonMcgregorApp'));
// instantiate service
var ScreenSpySrv;
beforeEach(inject(function (_ScreenSpySrv_) {
ScreenSpySrv = _ScreenSpySrv_;
}));
it('should do something', function () {
expect(!!ScreenSpySrv).toBe(true);
});
});
| IAmBrandonMcGregor/brandon-mcgregor | test/spec/services/ScreenSpySrv.js | JavaScript | mit | 368 |
'use strict';
angular.module('baka')
.controller('NavbarCtrl', function ($scope, AuthenticationService) {
$scope.logout = function () {
AuthenticationService.logout();
};
});
| spyl94/baka | web/assets/src/js/navbar/navbar.crtl.js | JavaScript | mit | 210 |
/**
* Created by Adrian on 2016-05-08.
*/
import angular from "angular";
import angularMeteor from "angular-meteor";
import uiRouter from "angular-ui-router";
import "./mobile.html";
import {Tasks} from "../../../api/tasks/index";
import {name as TaskItem} from "../taskItem/taskItem";
class TasksList {
constructor($scope, $reactive) {
'ngInject';
$reactive(this).attach($scope);
this.subscribe('tasks');
this.helpers({
tasks() {
return Tasks.find();
}
});
}
}
const template = 'mobile';
const name = 'tasksList';
export default angular.module(name, [
angularMeteor,
uiRouter,
TaskItem
]).component(name, {
templateUrl: `imports/ui/components/${name}/${template}.html`,
controllerAs: name,
controller: TasksList
}); | adik993/mobile-agents | imports/ui/components/tasksList/tasksList.js | JavaScript | mit | 866 |
// colors and line weights
var NOTHING = 0;
var EVERYTHING = 255;
var MOSTLY = 200;
var THICK_WEIGHT = 4;
var THIN_WEIGHT = 1;
// background
var CANVAS_WIDTH = 1000;
var CANVAS_HEIGHT = 750;
// touchpad
var BOX_SIZE = 50;
var X_MIN = CANVAS_WIDTH - (2 * BOX_SIZE);
var X_MAX = X_MIN + BOX_SIZE;
var Y_MIN = BOX_SIZE;
var Y_MAX = Y_MIN + BOX_SIZE;
// the circle
var DIAMETER = 20;
var EASING = 0.1;
var x_now = 0;
var y_now = 0;
var remap_cursor = function(sketch){
sketch.setup = function(){
sketch.createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT);
sketch.background(NOTHING, NOTHING, EVERYTHING);
sketch.stroke(EVERYTHING);
sketch.strokeWeight(THIN_WEIGHT);
sketch.fill(NOTHING, NOTHING, EVERYTHING);
sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE);
}// end sketch.setup
sketch.draw = function(){
// refresh the background
sketch.background(NOTHING, NOTHING, EVERYTHING, MOSTLY);
sketch.strokeWeight(THIN_WEIGHT);
sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE);
// map the mouse position in the box to the larger image
mx = sketch.map(sketch.mouseX, X_MIN, X_MAX, 0, CANVAS_WIDTH);
my = sketch.map(sketch.mouseY, Y_MIN, Y_MAX, 0, CANVAS_HEIGHT);
// add easing
x_now = x_now + (mx - x_now) * EASING;
y_now = y_now + (my - y_now) * EASING;
// draw the circle
sketch.strokeWeight(THICK_WEIGHT);
sketch.ellipse(x_now, y_now,
DIAMETER, DIAMETER);
}// end sketch.draw
}// end remap_cursor
| necromuralist/visualization | visualape/p5exploration/response/map_space.js | JavaScript | mit | 1,487 |
/*!
* VisualEditor DataModel TransactionProcessor tests.
*
* @copyright 2011-2014 VisualEditor Team and others; see AUTHORS.txt
* @license The MIT License (MIT); see LICENSE.txt
*/
QUnit.module( 've.dm.TransactionProcessor' );
/* Tests */
QUnit.test( 'commit', function ( assert ) {
var i, originalData, originalDoc,
msg, testDoc, tx, expectedData, expectedDoc,
n = 0,
store = ve.dm.example.createExampleDocument().getStore(),
bold = ve.dm.example.createAnnotation( ve.dm.example.bold ),
italic = ve.dm.example.createAnnotation( ve.dm.example.italic ),
underline = ve.dm.example.createAnnotation( ve.dm.example.underline ),
metaElementInsert = {
type: 'alienMeta',
attributes: {
style: 'comment',
text: ' inline '
}
},
metaElementInsertClose = { type: '/alienMeta' },
metadataExample = [
{ type: 'paragraph' },
'a', 'b',
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- comment -->' ).toArray()
}
},
{ type: '/alienMeta' },
'c', 'd',
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- comment -->' ).toArray()
}
},
{ type: '/alienMeta' },
'e', 'f',
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- comment -->' ).toArray()
}
},
{ type: '/alienMeta' },
'g', 'h',
{ type: '/paragraph' }
],
cases = {
'no operations': {
calls: [],
expected: function () {}
},
retaining: {
calls: [['pushRetain', 38]],
expected: function () {}
},
'annotating content': {
calls: [
['pushRetain', 1],
['pushStartAnnotating', 'set', bold],
['pushRetain', 1],
['pushStopAnnotating', 'set', bold],
['pushRetain', 1],
['pushStartAnnotating', 'clear', italic],
['pushStartAnnotating', 'set', bold],
['pushStartAnnotating', 'set', underline],
['pushRetain', 1],
['pushStopAnnotating', 'clear', italic],
['pushStopAnnotating', 'set', bold],
['pushStopAnnotating', 'set', underline]
],
expected: function ( data ) {
data[1] = ['a', store.indexes( [ bold ] )];
data[2] = ['b', store.indexes( [ bold ] )];
data[3] = ['c', store.indexes( [ bold, underline ] )];
}
},
'annotating content and leaf elements': {
calls: [
['pushRetain', 38],
['pushStartAnnotating', 'set', bold],
['pushRetain', 4],
['pushStopAnnotating', 'set', bold]
],
expected: function ( data ) {
data[38] = ['h', store.indexes( [ bold ] )];
data[39].annotations = store.indexes( [ bold ] );
data[41] = ['i', store.indexes( [ bold ] )];
}
},
'annotating across metadata': {
data: metadataExample,
calls: [
['pushRetain', 2],
['pushStartAnnotating', 'set', bold],
['pushRetain', 2],
['pushStopAnnotating', 'set', bold],
['pushRetain', 6]
],
expected: function ( data ) {
data[2] = ['b', store.indexes( [ bold ] )];
data[3].annotations = store.indexes( [ bold ] );
data[5] = ['c', store.indexes( [ bold ] )];
}
},
'annotating with metadata at edges': {
data: metadataExample,
calls: [
['pushRetain', 3],
['pushStartAnnotating', 'set', bold],
['pushRetain', 4],
['pushStopAnnotating', 'set', bold],
['pushRetain', 3]
],
expected: function ( data ) {
data[7].annotations = store.indexes( [ bold ] );
data[5] = ['c', store.indexes( [ bold ] )];
data[6] = ['d', store.indexes( [ bold ] )];
data[9] = ['e', store.indexes( [ bold ] )];
data[10] = ['f', store.indexes( [ bold ] )];
}
},
'unannotating metadata': {
data: [
{ type: 'paragraph' },
'a', ['b', store.indexes( [ bold ] )],
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- comment -->' ).toArray()
},
annotations: store.indexes( [ bold ] )
},
{ type: '/alienMeta' },
['c', store.indexes( [ bold ] )], 'd',
{ type: '/paragraph' }
],
calls: [
['pushRetain', 2],
['pushStartAnnotating', 'clear', bold],
['pushRetain', 2],
['pushStopAnnotating', 'clear', bold],
['pushRetain', 6]
],
expected: function ( data ) {
data[2] = 'b';
data[5] = 'c';
delete data[3].annotations;
}
},
'using an annotation method other than set or clear throws an exception': {
calls: [
['pushStartAnnotating', 'invalid-method', bold],
['pushRetain', 1],
['pushStopAnnotating', 'invalid-method', bold]
],
exception: Error
},
'annotating branch opening element throws an exception': {
calls: [
['pushStartAnnotating', 'set', bold],
['pushRetain', 1],
['pushStopAnnotating', 'set', bold]
],
exception: Error
},
'annotating branch closing element throws an exception': {
calls: [
['pushRetain', 4],
['pushStartAnnotating', 'set', bold],
['pushRetain', 1],
['pushStopAnnotating', 'set', bold]
],
exception: Error
},
'setting duplicate annotations throws an exception': {
calls: [
['pushRetain', 2],
['pushStartAnnotating', 'set', bold],
['pushRetain', 1],
['pushStopAnnotating', 'set', bold]
],
exception: Error
},
'removing non-existent annotations throws an exception': {
calls: [
['pushRetain', 1],
['pushStartAnnotating', 'clear', bold],
['pushRetain', 1],
['pushStopAnnotating', 'clear', bold]
],
exception: Error
},
'changing, removing and adding attributes': {
calls: [
['pushReplaceElementAttribute', 'level', 1, 2],
['pushRetain', 12],
['pushReplaceElementAttribute', 'style', 'bullet', 'number'],
['pushReplaceElementAttribute', 'test', undefined, 'abcd'],
['pushRetain', 27],
['pushReplaceElementAttribute', 'src', ve.dm.example.imgSrc, undefined]
],
expected: function ( data ) {
data[0].attributes.level = 2;
data[12].attributes.style = 'number';
data[12].attributes.test = 'abcd';
delete data[39].attributes.src;
}
},
'changing attributes on non-element data throws an exception': {
calls: [
['pushRetain', 1],
['pushReplaceElementAttribute', 'foo', 23, 42]
],
exception: Error
},
'inserting text': {
calls: [
['pushRetain', 1],
['pushReplace', 1, 0, ['F', 'O', 'O']]
],
expected: function ( data ) {
data.splice( 1, 0, 'F', 'O', 'O' );
}
},
'removing text': {
calls: [
['pushRetain', 1],
['pushReplace', 1, 1, []]
],
expected: function ( data ) {
data.splice( 1, 1 );
}
},
'replacing text': {
calls: [
['pushRetain', 1],
['pushReplace', 1, 1, ['F', 'O', 'O']]
],
expected: function ( data ) {
data.splice( 1, 1, 'F', 'O', 'O' );
}
},
'emptying text': {
calls: [
['pushRetain', 10],
['pushReplace', 10, 1, []]
],
expected: function ( data ) {
data.splice( 10, 1 );
}
},
'inserting mixed content': {
calls: [
['pushRetain', 1],
['pushReplace', 1, 1, ['F', 'O', 'O', { type: 'image' }, { type: '/image' }, 'B', 'A', 'R']]
],
expected: function ( data ) {
data.splice( 1, 1, 'F', 'O', 'O', { type: 'image' }, { type: '/image' }, 'B', 'A', 'R' );
}
},
'converting an element': {
calls: [
['pushReplace', 0, 1, [{ type: 'paragraph' }]],
['pushRetain', 3],
['pushReplace', 4, 1, [{ type: '/paragraph' }]]
],
expected: function ( data ) {
data[0].type = 'paragraph';
delete data[0].attributes;
data[4].type = '/paragraph';
}
},
'splitting an element': {
calls: [
['pushRetain', 2],
[
'pushReplace', 2, 0,
[{ type: '/heading' }, { type: 'heading', attributes: { level: 1 } }]
]
],
expected: function ( data ) {
data.splice(
2,
0,
{ type: '/heading' },
{ type: 'heading', attributes: { level: 1 } }
);
}
},
'merging an element': {
calls: [
['pushRetain', 57],
['pushReplace', 57, 2, []]
],
expected: function ( data ) {
data.splice( 57, 2 );
}
},
'stripping elements': {
calls: [
['pushRetain', 3],
['pushReplace', 3, 1, []],
['pushRetain', 6],
['pushReplace', 10, 1, []]
],
expected: function ( data ) {
data.splice( 10, 1 );
data.splice( 3, 1 );
}
},
'inserting text after alien node at the end': {
data: [
{ type: 'paragraph' },
'a',
{ type: 'alienInline' },
{ type: '/alienInline' },
{ type: '/paragraph' }
],
calls: [
['pushRetain', 4],
['pushReplace', 4, 0, ['b']]
],
expected: function ( data ) {
data.splice( 4, 0, 'b' );
}
},
'inserting metadata element into existing element list': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 11 ],
['pushRetainMetadata', 2 ],
['pushReplaceMetadata', [], [ metaElementInsert ] ],
['pushRetainMetadata', 2 ],
['pushRetain', 1 ]
],
expected: function ( data ) {
data.splice( 25, 0, metaElementInsert, metaElementInsertClose );
}
},
'inserting metadata element into empty list': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 3 ],
['pushReplaceMetadata', [], [ metaElementInsert ] ],
['pushRetain', 9 ]
],
expected: function ( data ) {
data.splice( 7, 0, metaElementInsert, metaElementInsertClose );
}
},
'removing all metadata elements from a metadata list': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 11 ],
['pushReplaceMetadata', ve.dm.example.withMetaMetaData[11], [] ],
['pushRetain', 1 ]
],
expected: function ( data ) {
data.splice( 21, 8 );
}
},
'removing some metadata elements from metadata list': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 11 ],
['pushRetainMetadata', 1 ],
['pushReplaceMetadata', ve.dm.example.withMetaMetaData[11].slice( 1, 3 ), [] ],
['pushRetainMetadata', 1 ],
['pushRetain', 1 ]
],
expected: function ( data ) {
data.splice( 23, 4 );
}
},
'replacing metadata at end of list': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 11 ],
['pushRetainMetadata', 3 ],
['pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][3] ], [ metaElementInsert ] ],
['pushRetain', 1 ]
],
expected: function ( data ) {
data.splice( 27, 2, metaElementInsert, metaElementInsertClose );
}
},
'replacing metadata twice at the same offset': {
data: ve.dm.example.withMeta,
calls: [
[ 'pushRetain', 11 ],
[ 'pushRetainMetadata', 1 ],
[ 'pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][1] ], [ metaElementInsert ] ],
[ 'pushRetainMetadata', 1 ],
[ 'pushReplaceMetadata', [ ve.dm.example.withMetaMetaData[11][3] ], [ metaElementInsert ] ],
[ 'pushRetain', 1 ]
],
expected: function ( data ) {
data.splice( 23, 2, metaElementInsert, metaElementInsertClose );
data.splice( 27, 2, metaElementInsert, metaElementInsertClose );
}
},
'removing data from between metadata merges metadata': {
data: ve.dm.example.withMeta,
calls: [
['pushRetain', 7 ],
['pushReplace', 7, 2, []],
['pushRetain', 2 ]
],
expected: function ( data ) {
data.splice( 15, 2 );
}
},
'structural replacement starting at an offset without metadata': {
data: [
{ type: 'paragraph' },
'F',
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- foo -->' ).toArray()
}
},
{ type: '/alienMeta' },
'o', 'o',
{ type: '/paragraph' }
],
calls: [
['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]]
],
expected: function ( data ) {
data.splice( 0, 2 );
data.splice( 2, 3, { type: 'table' }, { type: '/table' } );
}
},
'structural replacement starting at an offset with metadata': {
data: [
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- foo -->' ).toArray()
}
},
{ type: '/alienMeta' },
{ type: 'paragraph' },
'F',
{
type: 'alienMeta',
attributes: {
style: 'comment',
text: ' inline '
}
},
{ type: '/alienMeta' },
'o', 'o',
{ type: '/paragraph' }
],
calls: [
['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]]
],
expected: function ( data ) {
// metadata is merged.
data.splice( 2, 2 );
data.splice( 4, 3, { type: 'table' }, { type: '/table' } );
}
},
'structural replacement ending at an offset with metadata': {
data: [
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- foo -->' ).toArray()
}
},
{ type: '/alienMeta' },
{ type: 'paragraph' },
'F',
{
type: 'alienMeta',
attributes: {
style: 'comment',
text: ' inline '
}
},
{ type: '/alienMeta' },
'o', 'o',
{ type: '/paragraph' },
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- bar -->' ).toArray()
}
},
{ type: '/alienMeta' },
{ type: 'paragraph' },
'B', 'a', 'r',
{ type: '/paragraph' }
],
calls: [
['pushReplace', 0, 5, [ { type: 'table' }, { type: '/table' } ]],
['pushRetain', 5 ]
],
expected: function ( data ) {
// metadata is merged.
data.splice( 2, 2 );
data.splice( 4, 3, { type: 'table' }, { type: '/table' } );
}
},
'structural deletion ending at an offset with metadata': {
data: [
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- foo -->' ).toArray()
}
},
{ type: '/alienMeta' },
{ type: 'paragraph' },
'F',
{
type: 'alienMeta',
attributes: {
style: 'comment',
text: ' inline '
}
},
{ type: '/alienMeta' },
'o', 'o',
{ type: '/paragraph' },
{
type: 'alienMeta',
attributes: {
domElements: $( '<!-- bar -->' ).toArray()
}
},
{ type: '/alienMeta' },
{ type: 'paragraph' },
'B', 'a', 'r',
{ type: '/paragraph' }
],
calls: [
['pushReplace', 0, 5, [] ],
['pushRetain', 5 ]
],
expected: function ( data ) {
// metadata is merged.
data.splice( 2, 2 );
data.splice( 4, 3 );
}
},
'preserves metadata on unwrap': {
data: ve.dm.example.listWithMeta,
calls: [
[ 'newFromWrap', new ve.Range( 1, 11 ),
[ { type: 'list' } ], [],
[ { type: 'listItem', attributes: { styles: ['bullet'] } } ], []
]
],
expected: function ( data ) {
data.splice( 35, 1 ); // remove '/list'
data.splice( 32, 1 ); // remove '/listItem'
data.splice( 20, 1 ); // remove 'listItem'
data.splice( 17, 1 ); // remove '/listItem'
data.splice( 5, 1 ); // remove 'listItem'
data.splice( 2, 1 ); // remove 'list'
}
},
'inserting trailing metadata (1)': {
data: ve.dm.example.listWithMeta,
calls: [
[ 'newFromMetadataInsertion', 12, 0, [
{
type: 'alienMeta',
attributes: {
domElements: $( '<meta property="fourteen" />' ).toArray()
}
}
] ]
],
expected: function ( data ) {
ve.batchSplice( data, data.length - 2, 0, [
{
type: 'alienMeta',
attributes: {
domElements: $( '<meta property="fourteen" />' ).toArray()
}
},
{
type: '/alienMeta'
}
] );
}
},
'inserting trailing metadata (2)': {
data: ve.dm.example.listWithMeta,
calls: [
[ 'newFromMetadataInsertion', 12, 1, [
{
type: 'alienMeta',
attributes: {
domElements: $( '<meta property="fourteen" />' ).toArray()
}
}
] ]
],
expected: function ( data ) {
ve.batchSplice( data, data.length, 0, [
{
type: 'alienMeta',
attributes: {
domElements: $( '<meta property="fourteen" />' ).toArray()
}
},
{
type: '/alienMeta'
}
] );
}
},
'removing trailing metadata': {
data: ve.dm.example.listWithMeta,
calls: [
[ 'newFromMetadataRemoval', 12, new ve.Range( 0, 1 ) ]
],
expected: function ( data ) {
ve.batchSplice( data, data.length - 2, 2, [] );
}
},
'preserves trailing metadata': {
data: ve.dm.example.listWithMeta,
calls: [
[ 'newFromInsertion', 4, [ 'b' ] ]
],
expected: function ( data ) {
ve.batchSplice( data, 12, 0, [ 'b' ] );
}
}
};
for ( msg in cases ) {
n += ( 'expected' in cases[msg] ) ? 4 : 1;
}
QUnit.expect( n );
// Run tests
for ( msg in cases ) {
// Generate original document
originalData = cases[msg].data || ve.dm.example.data;
originalDoc = new ve.dm.Document(
ve.dm.example.preprocessAnnotations( ve.copy( originalData ), store )
);
originalDoc.buildNodeTree();
testDoc = new ve.dm.Document(
ve.dm.example.preprocessAnnotations( ve.copy( originalData ), store )
);
testDoc.buildNodeTree();
tx = new ve.dm.Transaction();
for ( i = 0; i < cases[msg].calls.length; i++ ) {
// some calls need the document as its first argument
if ( /^(pushReplace$|new)/.test( cases[msg].calls[i][0] ) ) {
cases[msg].calls[i].splice( 1, 0, testDoc );
}
// special case static methods of Transaction
if ( /^new/.test( cases[msg].calls[i][0] ) ) {
tx = ve.dm.Transaction[cases[msg].calls[i][0]].apply( null, cases[msg].calls[i].slice( 1 ) );
break;
}
tx[cases[msg].calls[i][0]].apply( tx, cases[msg].calls[i].slice( 1 ) );
}
if ( 'expected' in cases[msg] ) {
// Generate expected document
expectedData = ve.copy( originalData );
cases[msg].expected( expectedData );
expectedDoc = new ve.dm.Document(
ve.dm.example.preprocessAnnotations( expectedData, store )
);
expectedDoc.buildNodeTree();
// Commit
testDoc.commit( tx );
assert.deepEqualWithDomElements( testDoc.getFullData(), expectedDoc.getFullData(), 'commit (data): ' + msg );
assert.equalNodeTree(
testDoc.getDocumentNode(),
expectedDoc.getDocumentNode(),
'commit (tree): ' + msg
);
// Rollback
testDoc.commit( tx.reversed() );
assert.deepEqualWithDomElements( testDoc.getFullData(), originalDoc.getFullData(), 'rollback (data): ' + msg );
assert.equalNodeTree(
testDoc.getDocumentNode(),
originalDoc.getDocumentNode(),
'rollback (tree): ' + msg
);
} else if ( 'exception' in cases[msg] ) {
/*jshint loopfunc:true */
assert.throws(
function () {
testDoc.commit( tx );
},
cases[msg].exception,
'commit: ' + msg
);
}
}
} );
| johan--/tahi | public/visual-editor/modules/ve/tests/dm/ve.dm.TransactionProcessor.test.js | JavaScript | mit | 18,920 |
/**
* Takes an array of strings that represent functional dependencies and returns
* them as an array of objects containing functionaldependency objects.
*/
var parseInput = function(lines) {
lines = lines.split('\n');
var functionalDependencies = new DependencySet();
for(var i = 0; i < lines.length; ++i) {
var line = lines[i];
var arrowIndex = line.indexOf('->');
if(arrowIndex >= 0) {
var lhs = line.substring(0, arrowIndex).trim().split(',');
var rhs = line.substring(arrowIndex + 2, line.length).trim().split(',');
/* Trim all the individual attributes */
for(var j=0;j<lhs.length;++j)
lhs[j] = lhs[j].trim();
for(var k=0;k<rhs.length;++k)
rhs[k] = rhs[k].trim();
/* Make sure they're nonzero and add them to the list */
if(lhs.length > 0 && rhs.length > 0) {
var functionalDependency = new FunctionalDependency(lhs, rhs);
functionalDependencies.add(functionalDependency);
}
}
}
return functionalDependencies;
}; | abejfehr/database-normalizer | dev/parseInput.js | JavaScript | mit | 1,032 |
var test = require('tape');
var url = require('url');
var curli = require('../');
var testServer = require('./server.js');
var buildUAString = require('../lib/util').buildUAString;
test('Default user agent being set', function(t) {
var server = testServer.createServer();
var ua = buildUAString();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Default user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(href, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
test('Custom user agent', function(t) {
var server = testServer.createServer();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
var options = url.parse(href);
options.headers = {
'User-Agent': 'Node'
};
var ua = options.headers['User-Agent'];
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(options, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
test('Custom user agent, funky header', function(t) {
var server = testServer.createServer();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
var options = url.parse(href);
options.headers = {
'UsER-AgeNt': 'kNode'
};
var ua = options.headers['UsER-AgeNt'];
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(options, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
| joshgillies/node-curli | test/test-user-agent.js | JavaScript | mit | 2,264 |
var path = require('path'),
config;
config = {
production: {
url: 'http://localhost:2368',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '../node_modules/ghost/content/data/ghost-dev.db')
},
debug: false
},
server: {
host: '127.0.0.1',
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '../node_modules/ghost/content/')
}
}
};
// Export config
module.exports = config;
| myronrodrigues/myronrodrigues.com | gulp/ghost-prod-config.js | JavaScript | mit | 495 |
// All symbols in the Phoenician block as per Unicode v6.1.0:
[
'\uD802\uDD00',
'\uD802\uDD01',
'\uD802\uDD02',
'\uD802\uDD03',
'\uD802\uDD04',
'\uD802\uDD05',
'\uD802\uDD06',
'\uD802\uDD07',
'\uD802\uDD08',
'\uD802\uDD09',
'\uD802\uDD0A',
'\uD802\uDD0B',
'\uD802\uDD0C',
'\uD802\uDD0D',
'\uD802\uDD0E',
'\uD802\uDD0F',
'\uD802\uDD10',
'\uD802\uDD11',
'\uD802\uDD12',
'\uD802\uDD13',
'\uD802\uDD14',
'\uD802\uDD15',
'\uD802\uDD16',
'\uD802\uDD17',
'\uD802\uDD18',
'\uD802\uDD19',
'\uD802\uDD1A',
'\uD802\uDD1B',
'\uD802\uDD1C',
'\uD802\uDD1D',
'\uD802\uDD1E',
'\uD802\uDD1F'
]; | mathiasbynens/unicode-data | 6.1.0/blocks/Phoenician-symbols.js | JavaScript | mit | 609 |
import React, {PropTypes} from "react";
import {Provider} from "react-redux";
import {Router} from "react-router";
import {getRoutes} from "./routes";
export default function Root({history, store}) {
return (
<Provider store={store}>
<Router history={history} routes={getRoutes(store.getState)}/>
</Provider>
);
}
Root.propTypes = {
history: PropTypes.object.isRequired,
store: PropTypes.object.isRequired
}; | otwm/React-Firebase-Todo | src/views/root.js | JavaScript | mit | 454 |
/*********************************************************************************
* File Name : loader.js
* Created By : Jone Casper(xu.chenhui@live.com)
* Creation Date : [2014-03-25 22:14]
* Last Modified : [2014-04-06 05:17]
* Description : A loader for loading module
**********************************************************************************/
(function(root, name, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(function(){
return factory();
});
}else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){
module.exports = factory();
}else{
var namespaces = name.split("."),
scope = root || this;
for (var i=0; i<namespaces.length; i++) {
var p = namespaces[i],
ex = scope[p];
scope = scope[p] = (i === namespaces.length - 1) ?
factory():
(ex || {});
}
}
}(this, "backchart.base.loader",function(){
var root = this;
var exports = function(name, callback){
var args = [];
if (typeof define === 'function' && define.amd) {
require(name instanceof Array ? name : [name], callback);
}else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){
if (name instanceof Array){
for (var i=0; i<name.length ; i++){
args.push(require(name[i]));
}
callback.apply(this, args);
}else{
callback.call(this, require(name));
}
}else{
if (typeof name === "string" || name instanceof String){
name = [name];
}
for (var n=0; n<name.length; n++){
var namespaces = name[n],
scope = root;
namespaces = namespaces.replace("/",".").split(".");
for (var j=0; j<namespaces.length; j++) {
var p = namespaces[j],
ex = scope[p];
if (!ex) {
args.push(null);
break;
//callback.call(this, null);
}
if (j === namespaces.length -1){
args.push(ex);
//callback.call(this, ex);
}
scope = ex;
}
}
callback.apply(this, args);
}
};
return exports;
}));
| liorch88/backchart | src/backchart.base/loader.js | JavaScript | mit | 2,673 |
/*jshint esversion: 6 */
(function () {
let locationPromise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((position) => {
resolve(position);
});
});
locationPromise
.then(displayLocation)
.catch((error) => {
// var errMessage = document.getElementById("main");
let errMessage = $("#main");
errMessage.html("Can not get location");
});
function displayLocation(position) {
let imgSrc = `http://maps.googleapis.com/maps/api/staticmap?center=${position.coords.latitude},${position.coords.longitude}&zoom=18&size=600x600&sensor=true`;
$("#locationMap").attr("src", imgSrc);
}
}()); | tpopov94/Telerik-Academy-2016 | JavaScript Applications/PromisesAndAsynchronousProgramming/01. TaskOne/main.js | JavaScript | mit | 735 |
"use strict";
System.register([], function (_export, _context) {
"use strict";
var ClickCounter;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return {
setters: [],
execute: function () {
_export("ClickCounter", ClickCounter = function () {
function ClickCounter() {
_classCallCheck(this, ClickCounter);
this.count = 0;
}
ClickCounter.prototype.increment = function increment() {
this.count++;
};
return ClickCounter;
}());
_export("ClickCounter", ClickCounter);
}
};
}); | Hochfrequenz/aurelia-openui5-bridge | dist/system/click-counter.js | JavaScript | mit | 713 |
/*!
* Jade - Lexer
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Initialize `Lexer` with the given `str`.
*
* Options:
*
* - `colons` allow colons for attr delimiters
*
* @param {String} str
* @param {Object} options
* @api private
*/
var Lexer = module.exports = function Lexer(str, options) {
options = options || {};
this.input = str.replace(/\r\n|\r/g, '\n');
this.colons = options.colons;
this.deferredTokens = [];
this.lastIndents = 0;
this.lineno = 1;
this.stash = [];
this.indentStack = [];
this.indentRe = null;
this.pipeless = false;
};
/**
* Lexer prototype.
*/
Lexer.prototype = {
/**
* Construct a token with the given `type` and `val`.
*
* @param {String} type
* @param {String} val
* @return {Object}
* @api private
*/
tok: function(type, val){
return {
type: type
, line: this.lineno
, val: val
}
},
/**
* Consume the given `len` of input.
*
* @param {Number} len
* @api private
*/
consume: function(len){
this.input = this.input.substr(len);
},
/**
* Scan for `type` with the given `regexp`.
*
* @param {String} type
* @param {RegExp} regexp
* @return {Object}
* @api private
*/
scan: function(regexp, type){
var captures;
if (captures = regexp.exec(this.input)) {
this.consume(captures[0].length);
return this.tok(type, captures[1]);
}
},
/**
* Defer the given `tok`.
*
* @param {Object} tok
* @api private
*/
defer: function(tok){
this.deferredTokens.push(tok);
},
/**
* Lookahead `n` tokens.
*
* @param {Number} n
* @return {Object}
* @api private
*/
lookahead: function(n){
var fetch = n - this.stash.length;
while (fetch-- > 0) this.stash.push(this.next());
return this.stash[--n];
},
/**
* Return the indexOf `start` / `end` delimiters.
*
* @param {String} start
* @param {String} end
* @return {Number}
* @api private
*/
indexOfDelimiters: function(start, end){
var str = this.input
, nstart = 0
, nend = 0
, pos = 0;
for (var i = 0, len = str.length; i < len; ++i) {
if (start == str.charAt(i)) {
++nstart;
} else if (end == str.charAt(i)) {
if (++nend == nstart) {
pos = i;
break;
}
}
}
return pos;
},
/**
* Stashed token.
*/
stashed: function() {
return this.stash.length
&& this.stash.shift();
},
/**
* Deferred token.
*/
deferred: function() {
return this.deferredTokens.length
&& this.deferredTokens.shift();
},
/**
* end-of-source.
*/
eos: function() {
if (this.input.length) return;
if (this.indentStack.length) {
this.indentStack.shift();
return this.tok('outdent');
} else {
return this.tok('eos');
}
},
/**
* Comment.
*/
comment: function() {
var captures;
if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('comment', captures[2]);
tok.buffer = '-' != captures[1];
return tok;
}
},
/**
* Tag.
*/
tag: function() {
var captures;
if (captures = /^(\w[-:\w]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok, name = captures[1];
if (':' == name[name.length - 1]) {
name = name.slice(0, -1);
tok = this.tok('tag', name);
this.defer(this.tok(':'));
while (' ' == this.input[0]) this.input = this.input.substr(1);
} else {
tok = this.tok('tag', name);
}
return tok;
}
},
/**
* Filter.
*/
filter: function() {
return this.scan(/^:(\w+)/, 'filter');
},
/**
* Doctype.
*/
doctype: function() {
return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype');
},
/**
* Id.
*/
id: function() {
return this.scan(/^#([\w-]+)/, 'id');
},
/**
* Class.
*/
className: function() {
return this.scan(/^\.([\w-]+)/, 'class');
},
/**
* Text.
*/
text: function() {
return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
},
/**
* Extends.
*/
"extends": function() {
return this.scan(/^extends +([^\n]+)/, 'extends');
},
/**
* Block prepend.
*/
prepend: function() {
var captures;
if (captures = /^prepend +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'prepend'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block append.
*/
append: function() {
var captures;
if (captures = /^append +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'append'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block.
*/
block: function() {
var captures;
if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = captures[1] || 'replace'
, name = captures[2]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Yield.
*/
yield: function() {
return this.scan(/^yield */, 'yield');
},
/**
* Include.
*/
include: function() {
return this.scan(/^include +([^\n]+)/, 'include');
},
/**
* Case.
*/
"case": function() {
return this.scan(/^case +([^\n]+)/, 'case');
},
/**
* When.
*/
when: function() {
return this.scan(/^when +([^:\n]+)/, 'when');
},
/**
* Default.
*/
"default": function() {
return this.scan(/^default */, 'default');
},
/**
* Assignment.
*/
assignment: function() {
var captures;
if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) {
this.consume(captures[0].length);
var name = captures[1]
, val = captures[2];
return this.tok('code', 'var ' + name + ' = (' + val + ');');
}
},
/**
* Mixin.
*/
mixin: function(){
var captures;
if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('mixin', captures[1]);
tok.args = captures[2];
return tok;
}
},
/**
* Conditional.
*/
conditional: function() {
var captures;
if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var type = captures[1]
, js = captures[2];
switch (type) {
case 'if': js = 'if (' + js + ')'; break;
case 'unless': js = 'if (!(' + js + '))'; break;
case 'else if': js = 'else if (' + js + ')'; break;
case 'else': js = 'else'; break;
}
return this.tok('code', js);
}
},
/**
* While.
*/
"while": function() {
var captures;
if (captures = /^while +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
return this.tok('code', 'while (' + captures[1] + ')');
}
},
/**
* Each.
*/
each: function() {
var captures;
if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('each', captures[1]);
tok.key = captures[2] || '$index';
tok.code = captures[3];
return tok;
}
},
/**
* Code.
*/
code: function() {
var captures;
if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var flags = captures[1];
captures[1] = captures[2];
var tok = this.tok('code', captures[1]);
tok.escape = flags[0] === '=';
tok.buffer = flags[0] === '=' || flags[1] === '=';
return tok;
}
},
/**
* Attributes.
*/
attrs: function() {
if ('(' == this.input.charAt(0)) {
var index = this.indexOfDelimiters('(', ')')
, str = this.input.substr(1, index-1)
, tok = this.tok('attrs')
, len = str.length
, colons = this.colons
, states = ['key']
, key = ''
, val = ''
, quote
, c;
function state(){
return states[states.length - 1];
}
function interpolate(attr) {
return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
return quote + " + (" + expr + ") + " + quote;
});
}
this.consume(index + 1);
tok.attrs = {};
function parse(c) {
var real = c;
// TODO: remove when people fix ":"
if (colons && ':' == c) c = '=';
switch (c) {
case ',':
case '\n':
switch (state()) {
case 'expr':
case 'array':
case 'string':
case 'object':
val += c;
break;
default:
states.push('key');
val = val.trim();
key = key.trim();
if ('' == key) return;
tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
? true
: interpolate(val);
key = val = '';
}
break;
case '=':
switch (state()) {
case 'key char':
key += real;
break;
case 'val':
case 'expr':
case 'array':
case 'string':
case 'object':
val += real;
break;
default:
states.push('val');
}
break;
case '(':
if ('val' == state()
|| 'expr' == state()) states.push('expr');
val += c;
break;
case ')':
if ('expr' == state()
|| 'val' == state()) states.pop();
val += c;
break;
case '{':
if ('val' == state()) states.push('object');
val += c;
break;
case '}':
if ('object' == state()) states.pop();
val += c;
break;
case '[':
if ('val' == state()) states.push('array');
val += c;
break;
case ']':
if ('array' == state()) states.pop();
val += c;
break;
case '"':
case "'":
switch (state()) {
case 'key':
states.push('key char');
break;
case 'key char':
states.pop();
break;
case 'string':
if (c == quote) states.pop();
val += c;
break;
default:
states.push('string');
val += c;
quote = c;
}
break;
case '':
break;
default:
switch (state()) {
case 'key':
case 'key char':
key += c;
break;
default:
val += c;
}
}
}
for (var i = 0; i < len; ++i) {
parse(str.charAt(i));
}
parse(',');
return tok;
}
},
/**
* Indent | Outdent | Newline.
*/
indent: function() {
var captures, re;
// established regexp
if (this.indentRe) {
captures = this.indentRe.exec(this.input);
// determine regexp
} else {
// tabs
re = /^\n(\t*) */;
captures = re.exec(this.input);
// spaces
if (captures && !captures[1].length) {
re = /^\n( *)/;
captures = re.exec(this.input);
}
// established
if (captures && captures[1].length) this.indentRe = re;
}
if (captures) {
var tok
, indents = captures[1].length;
++this.lineno;
this.consume(indents + 1);
if (' ' == this.input[0] || '\t' == this.input[0]) {
throw new Error('Invalid indentation, you can use tabs or spaces but not both');
}
// blank line
if ('\n' == this.input[0]) return this.tok('newline');
// outdent
if (this.indentStack.length && indents < this.indentStack[0]) {
while (this.indentStack.length && this.indentStack[0] > indents) {
this.stash.push(this.tok('outdent'));
this.indentStack.shift();
}
tok = this.stash.pop();
// indent
} else if (indents && indents != this.indentStack[0]) {
this.indentStack.unshift(indents);
tok = this.tok('indent', indents);
// newline
} else {
tok = this.tok('newline');
}
return tok;
}
},
/**
* Pipe-less text consumed only when
* pipeless is true;
*/
pipelessText: function() {
if (this.pipeless) {
if ('\n' == this.input[0]) return;
var i = this.input.indexOf('\n');
if (-1 == i) i = this.input.length;
var str = this.input.substr(0, i);
this.consume(str.length);
return this.tok('text', str);
}
},
/**
* ':'
*/
colon: function() {
return this.scan(/^: */, ':');
},
/**
* Return the next token object, or those
* previously stashed by lookahead.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.stashed()
|| this.next();
},
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
next: function() {
return this.deferred()
|| this.eos()
|| this.pipelessText()
|| this.yield()
|| this.doctype()
|| this["case"]()
|| this.when()
|| this["default"]()
|| this["extends"]()
|| this.append()
|| this.prepend()
|| this.block()
|| this.include()
|| this.mixin()
|| this.conditional()
|| this.each()
|| this["while"]()
|| this.assignment()
|| this.tag()
|| this.filter()
|| this.code()
|| this.id()
|| this.className()
|| this.attrs()
|| this.indent()
|| this.comment()
|| this.colon()
|| this.text();
}
};
| rauchg/jade | lib/lexer.js | JavaScript | mit | 14,546 |
var express = require('express');
var request = require('request');
var rp = require('rp');
var config = require('../../config')
var router = express.Router();
var twilio = require('twilio');
var mysql = require('mysql');
var connection = mysql.createConnection(config.mysqlConfig);
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: '네이버 채용 알리미' });
});
router.post('/enlist', function(req, res, next) {
if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
return res.json({"response" : "Please complete recaptcha."});
}
var regex = /^\d{3}-\d{4}-\d{4}$/;
if(!req.body.phonenumber.match(regex)){
return res.json({"response" : "Please input a correct phone number. (000-0000-0000)"});
}
request.post({url:"https://www.google.com/recaptcha/api/siteverify", form:{"secret" : config.captchasecret, "response" : req.body['g-recaptcha-response']}}, function(error, response, body){
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if(body.success !== undefined && !body.success) {
return res.json({"response" : "Recaptcha validation failed, please try again."})
}
//everything OK, now we add the phone number to the DB.
connection.query('INSERT INTO `NotifyList`(phonenumber) VALUES("'+req.body.phonenumber+'");', function(error, cursor){
if(error==null){
var twclient = new twilio(config.twaccountSid, config.twaccountToken);
twclient.messages.create({
body: "Welcome to Naver job opening notification service!"+" / 구독취소:gyuhyeonlee.com",
to: '+82'+req.body.phonenumber,
from: '+12568184331'
})
.then((message) => console.log(message.sid));
return res.json({"response" : "Success! Please wait for confirmation SMS."});
}
else{
return res.json({"response" : "We're sorry, but either our DB is not working, or you're already subscribed!"});
}
}); //end of insert connection.query
}); //end of request.post (sorry for callback hell!)
}) //end of router post handling
router.post('/unsubscribe', function(req, res, next) {
if(req.body['g-recaptcha-response'] === undefined || req.body['g-recaptcha-response'] === '' || req.body['g-recaptcha-response'] === null) {
return res.json({"response" : "Please complete recaptcha."});
}
var regex = /^\d{3}-\d{4}-\d{4}$/;
if(!req.body.phonenumber.match(regex)){
return res.json({"response" : "Please input a correct phone number. (000-0000-0000)"});
}
request.post({url:"https://www.google.com/recaptcha/api/siteverify", form:{"secret" : config.captchasecret, "response" : req.body['g-recaptcha-response']}}, function(error, response, body){
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if(body.success !== undefined && !body.success) {
return res.json({"response" : "Recaptcha validation failed, please try again."})
}
//everything OK, now we add the phone number to the DB.
connection.query('DELETE FROM `NaverJobs`.`NotifyList` WHERE `phonenumber`="'+req.body.phonenumber+'";', function(error, cursor){
if(error==null){
if(cursor.affectedRows>0){
return res.json({"response" : "Success! Your number has been deleted."});
}
else{
return res.json({"response" : "Your number is not in the database!"});
}
}
else{
return res.json({"response" : "We're sorry, our DB seems to be down right now..."});
}
}); //end of insert connection.query
}); //end of request.post (sorry for callback hell!)
});
// line webhook for receiving sub&unsub events.
router.post('/lineevents', function(req, res, next) {
let insertvalues = [];
let removevalues = [];
if(req.body.events!==null && req.body.events!==undefined){
for (let i = 0; i < req.body.events.length; ++i) {
if (req.body.events[i].type == 'follow') {
insertvalues.push(req.body.events[i].source.userId);
}
else if(req.body.events[i].type == 'unfollow') {
removevalues.push(req.body.events[i].source.userId);
}
}
if (insertvalues.length > 0) {
// don't really care about data consistency. All we need make sure is that removing takes priority over adding.
connection.query('INSERT INTO `NaverJobs`.`LineFriends`(id) VALUES (?);', insertvalues, function(error, cursor){
if(error == null){
let options = {
method: "POST",
uri: "https://api.line.me/v2/bot/message/multicast",
headers: {
'Content-Type':'application/json',
'Authorization':'Bearer {'+config.linetoken+'}'
},
body: {
to: insertvalues,
messages: [{"type":"text", "text": "구독 신청 감사합니다! 변경사항이 있을 경우 바로 알려드릴게요 :)"}]
},
json: true // this encodes our body as json when SENDING POST request.
// in GET requests, this means it will encode RESPONSE in json when we RECEIVE IT.
// pretty confusing...
};
rp(options).catch((e) => console.log(e)); // one way request, don't really need .then() promises. Send greetings to new users.
}
else{
console.log("DB error : "+error);
}
});
}
if (removevalues.length > 0) {
connection.query('DELETE FROM `NaverJobs`.`LineFriends` WHERE `id`=?;', removevalues, function(error){
if(error != null){
console.log("DB error : "+error);
}
});
}
}
res.set('Content-Type', 'text/plain');
res.send("Thanks LINE!");
});
module.exports = router; | gyuhyeon/NaverRecruitNotifier | routes/index.js | JavaScript | mit | 6,542 |
/**
* local_resize_img
* by hefish@gmail.com
* 2015-04-08
*/
var MAX_SIZE = 600;
var LIT_SIZE = 80;
$.fn.local_resize_img = function(obj) {
this.on('change', function() {
var file_path = this.files[0];
load_image(file_path);
});
function is_android() {
var ua = navigator.userAgent.toLowerCase();
is_android_browser = ua.indexOf("android") > -1;
return is_android_browser;
}
function is_ios() {
var ua = navigator.userAgent.toLowerCase();
is_android_browser = ua.indexOf("iphone") > -1;
return is_android_browser;
}
function load_image(file_path) {
if (! file_path.type.match(/image.*/)) {
if (window.console) {
console.log("我说哥哥,只能选图片");
}else {
window.confirm("我说哥哥,只能选图片啊");
}
return ;
}
var reader = new FileReader() ;
reader.onloadend = function(e) {
//获取到图片内容,准备渲染 (内容是base64滴,还带header)
render(e.target.result);
};
reader.readAsDataURL(file_path);
};
function render(img_data) {
var img = new Image() ;
img.src = img_data; //先把图啊,用个img对象装起来
img.onload = function () {
var this_img = this;
var w = this_img.width, lit_w, lit_h,
h = this_img.height,
scale = w/h; //宽高比
//计算缩放之后的宽高
if (Math.min(w,h) > MAX_SIZE) {
if (w > h) {
h=MAX_SIZE; w=h*scale;
lit_h = LIT_SIZE; lit_w = lit_h * scale;
}
else {
w=MAX_SIZE; h = w/scale;
lit_w = LIT_SIZE ; lit_h = w/scale;
}
}
//取exif.orientation
EXIF.getData(this);
var orientation = EXIF.getTag(this, "Orientation") || 1;
var rotate_degree = 0;
switch(orientation) {
case 1:
rotate_degree = 0; break;
case 8:
rotate_degree = -90;
break;
case 3:
rotate_degree = 180;
break;
case 6:
rotate_degree = 90;
break;
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
if (rotate_degree == 90 || rotate_degree == -90) {
$(canvas).attr({width: h, height: w});
}else {
$(canvas).attr({width: w, height: h});
}
//draw on big resized canvas MAX_SIZE
var canvas_width = $(canvas).attr("width");
var canvas_height = $(canvas).attr("height");
if (is_ios()) {
var mp_img = new MegaPixImage(img);
mp_img.render(canvas, {maxWidth:w, maxHeight:h, orientation:orientation});
}else {
ctx.translate(canvas_width/2, canvas_height/2);
ctx.rotate(rotate_degree * Math.PI/180);
ctx.drawImage(this_img, -w/2,-h/2, w,h);
}
var base64 = canvas.toDataURL("image/jpeg", 0.8);
if (base64.indexOf("image/jpeg") > 0) {
}
else {
var encoder = new JPEGEncoder(80);
var img_data = ctx.getImageData(0,0,canvas_width,canvas_height);
base64 = encoder.encode(img_data);
}
var result = {
base64: base64,
};
obj.success(result);
};
}
};
| hefish/local_resize_img | js/local_resize_img.js | JavaScript | mit | 3,950 |
'use strict';
angular.module("services")
.factory('mapSVC', [ "colorsSVC", function(colorsSVC) {
// Converts two coordinates to a GoogleLatLong
var cnvLatLong = function (x) {
return new google.maps.LatLng(x[0],x[1]);
};
var setPathMode = function (mode) {
if(mode == "driving"){
return google.maps.DirectionsTravelMode.DRIVING;
}
else if(mode == "walking"){
return google.maps.DirectionsTravelMode.WALKING;
}
else if(mode == "transit"){
return google.maps.DirectionsTravelMode.TRANSIT;
}
else if(mode == "bicycling"){
return google.maps.DirectionsTravelMode.BICYCLING;
}
}
// Sets the colors of the chart, from RGB data to Hex
var setColors = function (colors) {
var util = [];
for(var i=0;i<colors.length;i++){
var rgb = colors[i];
var color = colorsSVC.rgbToHex(rgb.red, rgb.green, rgb.blue);
util.push(color);
}
return util;
}
var createPolyline = function (pathLine, color, map) {
return new google.maps.Polyline({ path: pathLine
, strokeColor: color
, strokeOpacity: 1.0
, strokeWeight: 3
, map: map
, visible: true
});
};
var createMarker = function (point, map) {
var marker = new MarkerWithLabel({ position: new google.maps.LatLng(point.latitude, point.longitude)
, map: map
, title: point.id.toString()
, icon: { url: 'aps/res/markerBI_24.png'
, size: new google.maps.Size(24,24)
, anchor: new google.maps.Point(12,12)
}
, zIndex: 1
, labelContent: point.id < 100 ? (point.id < 10 ? "T0" + point.id.toString() : "T" + point.id.toString()) : point.id.toString()
, labelAnchor: new google.maps.Point(8, 7)
, labelClass: "mrkLa"
, labelZIndex: 2
});
return marker;
}
var buildPath = function(path, color, map, polylines, method) {
var pathline = [];
var service = new google.maps.DirectionsService();
for(var i=0; i<path.length-1; i++) {
service.route({ origin: cnvLatLong(path[i]) // Consumes a point from the path
, destination: cnvLatLong(path[i+1]) // Recursively calls itself for the next points
, travelMode: setPathMode(method)
}
, function(result, status) { // Async Callback, gets the response from Google Maps Directions
if(status == google.maps.DirectionsStatus.OK) {
var path = result.routes[0].overview_path;
var legs = result.routes[0].legs;
for (var i=0;i<legs.length;i++) { // Parses the subroutes between two points
var steps = legs[i].steps;
for (var j=0;j<steps.length;j++) {
var nextSegment = steps[j].path;
for (var k=0;k<nextSegment.length;k++) { // Pushes the segment on the path
pathline.push(nextSegment[k]);
}
}
}
// Generates the Polyline of the calculated path
polylines.push(createPolyline(pathline,color,map));
pathline = [];
}
});
}
};
var resetMap = function (map, polylines, markers, id, position) {
for(var line in polylines){
polylines[line].setMap(null);
}
for(var marker in markers){
markers[marker].setMap(null);
}
};
return { createPolyline : createPolyline
, buildPath : buildPath
, setColors : setColors
, buildLegend : function (map, position, id) {
var legend = document.getElementById('mapLegend');
if (position == "top-right"){
if(map.controls[google.maps.ControlPosition.TOP_RIGHT].length > 0){
map.controls[google.maps.ControlPosition.TOP_RIGHT].pop();
}
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(legend);
}
if (position == "top-left"){
if(map.controls[google.maps.ControlPosition.TOP_LEFT].length > 0){
map.controls[google.maps.ControlPosition.TOP_LEFT].pop();
}
map.controls[google.maps.ControlPosition.TOP_LEFT].push(legend);
}
if (position == "bottom-right"){
if(map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].length > 0){
map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].pop();
}
map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push(legend);
}
if (position == "bottom-left"){
if(map.controls[google.maps.ControlPosition.BOTTOM_LEFT].length > 0){
map.controls[google.maps.ControlPosition.BOTTOM_LEFT].pop();
}
map.controls[google.maps.ControlPosition.BOTTOM_LEFT].push(legend);
}
}
, createMarker: createMarker
, updateMovie : function (markers, newData, map) {
for(var marker in markers) {
var toBeRemoved = true; // It's always pending removal, except when it has to be updated!
for(var i=0;i<newData.newPoints.length && toBeRemoved == true;i++) {
// Then update it!
if(markers[marker].title == newData.newPoints[i].id.toString() || markers[marker].title == newData.newPoints[i].id){
markers[marker].setPosition(new google.maps.LatLng(newData.newPoints[i].latitude, newData.newPoints[i].longitude));
newData.newPoints.splice(i,1);
toBeRemoved = false;
}
}
if(toBeRemoved) {
// I guess its time has come
markers[marker].setMap();
delete markers[marker];
}
}
// A new life is born!
for(var obj in newData.newPoints) {
markers[newData.newPoints[obj].id] = createMarker(newData.newPoints[obj], map);
}
}
, resetMap: resetMap
}
}]); | FlameTech/Norris | RA/Codice/norris-aps/aps/scripts/services/mapSVC.js | JavaScript | mit | 7,647 |
module.exports = require('identity-obj-proxy');
| michalholasek/react-boilerplate | config/styleMock.js | JavaScript | mit | 48 |
Meteor.startup(function () {
Meteor.defer(function () {
Session.setDefault("checked", $("input[type=checkbox]").is(":checked"));
});
if (Meteor.isCordova) {
window.alert = navigator.notification.alert;
}
Push.addListener('message', function(notification) {
// Called on every message
console.log(JSON.stringify(notification))
function alertDismissed() {
NotificationHistory.update({_id: notification.payload.historyId}, {
$set: {
"recievedAt": new Date()
}
});
}
alert(notification.message, alertDismissed, notification.payload.title, "Ok");
});
}); | spcsser/meteor-grdn-gnome | client/startup.js | JavaScript | mit | 708 |
// dependencies
var AWS = require('aws-sdk'); //Provided by lambda (no need to install)
var async = require('async');
var gm = require('gm')
.subClass({ imageMagick: true }); // Enable ImageMagick integration.
var util = require('util');
var fs = require("fs");
var path = require("path");
// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {
// Load config.json
var configPath = path.resolve(__dirname, "config.json");
var config = JSON.parse(fs.readFileSync(configPath, { encoding: "utf8" }));
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
var dstBucket = config.dstBucket; //from config.json
var dstKey = srcKey;
// Sanity check: validate that source and destination are different buckets.
if (srcBucket == dstBucket) {
console.error("Destination bucket must not match source bucket.");
return;
}
var thumbs = config.thumbs; // From config.json
var thumbs2 = thumbs; // Take a copy to iterate, but leave original alone
for (var i=0, tot=thumbs2.length; i < tot; i++) {
async.waterfall(
[
function download(next) {
// Download the image from S3 into a buffer.
s3.getObject(
{
Bucket: srcBucket,
Key: srcKey
},
next
);
},
function getFormat(response, next) {
gm(response.Body).format(function (err, format) {
// console.log('Format: '+ format);
next(null, format, response);
});
},
function transform(imageType, response, next) {
// console.log('imageType: '+ imageType);
var current_thumb = thumbs.pop();
if(current_thumb.type=='thumbnail'){
if (typeof current_thumb.geometry == 'undefined') current_thumb.geometry = '960x540';
console.log('Thumbnail '+ current_thumb.geometry);
gm(response.Body)
.autoOrient()
.noProfile()
.command('convert')
.out('-quality', 95)
.out('-gravity', 'center')
.out('-resize', current_thumb.geometry+'^')
.out('-crop', current_thumb.geometry+'+0+0')
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer, current_thumb.folder);
}
});
} else if(current_thumb.type=='resize'){
if (typeof current_thumb.width == 'undefined') current_thumb.width = null;
if (typeof current_thumb.height == 'undefined') current_thumb.height = null;
console.log('Resize '+ current_thumb.width + 'x' + current_thumb.height);
gm(response.Body)
.resize(current_thumb.width, current_thumb.height)
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer, current_thumb.folder);
}
});
}
},
function upload(contentType, data, folder, next) {
// Stream the transformed image to a different S3 bucket.
console.log('Uploading '+ folder + '/' + dstKey);
s3.putObject(
{
Bucket: dstBucket,
Key: folder + '/' + dstKey,
Body: data,
ContentType: contentType
},
next
);
}
],
function (err) {
if (err) {
console.error(
'Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + dstBucket + '/' + dstKey +
' due to an error: ' + err
);
} else {
console.log(
'Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + dstKey
);
}
//callback(null, "message");
}
);
}
};
| DnSu/aws-s3-lambda-crop-n-resize | index.js | JavaScript | mit | 4,296 |
import Yoga from '@react-pdf/yoga';
import setJustifyContent from '../../src/node/setJustifyContent';
describe('node setJustifyContent', () => {
const mock = jest.fn();
const node = { _yogaNode: { setJustifyContent: mock } };
beforeEach(() => {
mock.mockReset();
});
test('should return node if no yoga node available', () => {
const emptyNode = { box: { width: 10, height: 20 } };
const result = setJustifyContent(null)(emptyNode);
expect(result).toBe(emptyNode);
});
test('Should set center', () => {
const result = setJustifyContent('center')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_CENTER);
expect(result).toBe(node);
});
test('Should set flex-end', () => {
const result = setJustifyContent('flex-end')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_END);
expect(result).toBe(node);
});
test('Should set flex-start', () => {
const result = setJustifyContent('flex-start')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_START);
expect(result).toBe(node);
});
test('Should set space-between', () => {
const result = setJustifyContent('space-between')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_BETWEEN);
expect(result).toBe(node);
});
test('Should set space-around', () => {
const result = setJustifyContent('space-around')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_AROUND);
expect(result).toBe(node);
});
test('Should set space-evenly', () => {
const result = setJustifyContent('space-evenly')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_EVENLY);
expect(result).toBe(node);
});
});
| diegomura/react-pdf | packages/layout/tests/node/setJustifyContent.test.js | JavaScript | mit | 1,991 |
// Constants
export const USERS_INCREMENT = 'USERS_INCREMENT'
export const USERS_DOUBLE_ASYNC = 'USERS_DOUBLE_ASYNC'
// Actions
export function increment(value = 1) {
return {
type: USERS_INCREMENT,
payload: value
}
}
export const doubleAsync = () => {
return (dispatch, getState) => {
return new Promise((resolve) => {
setTimeout(() => {
dispatch({
type: USERS_DOUBLE_ASYNC,
payload: getState().users
})
resolve()
}, 200)
})
}
}
export const actions = {
increment,
doubleAsync
}
// Action Handlers
const ACTION_HANDLERS = {
[USERS_INCREMENT]: (state, action) => state + action.payload,
[USERS_DOUBLE_ASYNC]: (state) => state * 2
}
// Reducer
const initialState = 0
export default function usersReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
| jancarloviray/graphql-react-starter | src/client/routes/Users/modules/users.js | JavaScript | mit | 928 |
import React from 'react';
import SvgExclamation from '../svg/Exclamation.js';
import styles from './InputArea.scss';
const exclamation = () =>
<div className={styles.suffix + ' ' + styles.exclamation}>
<SvgExclamation width={2} height={11}/>
</div>;
export default exclamation;
| nirhart/wix-style-react | src/InputArea/Exclamation.js | JavaScript | mit | 290 |
var TestTime = require('logux-core').TestTime
var ServerSync = require('../server-sync')
var TestPair = require('../test-pair')
var sync
function createTest () {
var test = new TestPair()
sync = new ServerSync('server', TestTime.getLog(), test.left)
test.leftSync = sync
return test.left.connect().then(function () {
return test
})
}
afterEach(function () {
sync.destroy()
})
it('sends debug messages', function () {
return createTest().then(function (test) {
test.leftSync.sendDebug('testType', 'testData')
return test.wait('right')
}).then(function (test) {
expect(test.leftSent).toEqual([['debug', 'testType', 'testData']])
})
})
it('emits a debug on debug error messages', function () {
var pair = new TestPair()
sync = new ServerSync('server', TestTime.getLog(), pair.left)
sync.authenticated = true
var debugs = []
sync.on('debug', function (type, data) {
debugs.push(type, data)
})
sync.onMessage(['debug', 'error', 'testData'])
expect(debugs).toEqual(['error', 'testData'])
})
it('checks types', function () {
var wrongs = [
['debug'],
['debug', 0],
['debug', []],
['debug', {}, 'abc'],
['debug', 'error', 0],
['debug', 'error', []],
['debug', 'error', {}]
]
return Promise.all(wrongs.map(function (command) {
return createTest().then(function (test) {
test.right.send(command)
return test.wait('right')
}).then(function (test) {
expect(test.leftSync.connected).toBeFalsy()
expect(test.leftSent).toEqual([
['error', 'wrong-format', JSON.stringify(command)]
])
})
}))
})
| logux/logux-sync | test/debug.test.js | JavaScript | mit | 1,628 |
'use strict';
var util = require('util'),
Transform = require('stream').Transform,
Response = require('../response');
function ResponseStream (multiline) {
this.multiline = multiline || false;
var response;
this._transform = function (chunk, encoding, callback) {
if (undefined === response) {
response = Response.createFromString(encoding === 'buffer' ? chunk.toString() : chunk);
if (false === this.multiline) {
this.push(response);
this.end();
}
} else {
response.lines.push(chunk);
}
callback();
};
this._flush = function (callback) {
this.push(response);
callback();
};
Transform.call(this, { objectMode: true });
}
util.inherits(ResponseStream, Transform);
module.exports = ResponseStream;
| RobinvdVleuten/node-nntp | lib/streams/response.js | JavaScript | mit | 791 |
/* eslint-env browser */
/**
* Module dependencies.
*/
var Base = require('./base');
var utils = require('../utils');
var Progress = require('../browser/progress');
var escapeRe = require('escape-string-regexp');
var escape = utils.escape;
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
/* eslint-disable no-unused-vars, no-native-reassign */
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/* eslint-enable no-unused-vars, no-native-reassign */
/**
* Expose `HTML`.
*/
exports = module.exports = HTML;
/**
* Stats template.
*/
var statsTemplate = '<ul id="mocha-stats">'
+ '<li class="progress"><canvas width="40" height="40"></canvas></li>'
+ '<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>'
+ '<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>'
+ '<li class="duration">duration: <em>0</em>s</li>'
+ '</ul>';
/**
* Initialize a new `HTML` reporter.
*
* @api public
* @param {Runner} runner
*/
function HTML(runner) {
Base.call(this, runner);
var self = this;
var stats = this.stats;
var stat = fragment(statsTemplate);
var items = stat.getElementsByTagName('li');
var passes = items[1].getElementsByTagName('em')[0];
var passesLink = items[1].getElementsByTagName('a')[0];
var failures = items[2].getElementsByTagName('em')[0];
var failuresLink = items[2].getElementsByTagName('a')[0];
var duration = items[3].getElementsByTagName('em')[0];
var canvas = stat.getElementsByTagName('canvas')[0];
var report = fragment('<ul id="mocha-report"></ul>');
var stack = [report];
var progress;
var ctx;
var root = document.getElementById('mocha');
if (canvas.getContext) {
var ratio = window.devicePixelRatio || 1;
canvas.style.width = canvas.width;
canvas.style.height = canvas.height;
canvas.width *= ratio;
canvas.height *= ratio;
ctx = canvas.getContext('2d');
ctx.scale(ratio, ratio);
progress = new Progress();
}
if (!root) {
return error('#mocha div missing, add it to your document');
}
// pass toggle
on(passesLink, 'click', function() {
unhide();
var name = (/pass/).test(report.className) ? '' : ' pass';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) {
hideSuitesWithout('test pass');
}
});
// failure toggle
on(failuresLink, 'click', function() {
unhide();
var name = (/fail/).test(report.className) ? '' : ' fail';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) {
hideSuitesWithout('test fail');
}
});
root.appendChild(stat);
root.appendChild(report);
if (progress) {
progress.size(40);
}
runner.on('suite', function(suite) {
if (suite.root) {
return;
}
// suite
var url = self.suiteURL(suite);
var el = fragment('<li class="suite"><h1><a href="%e">%e</a></h1></li>', url, suite.title);
// container
stack[0].appendChild(el);
stack.unshift(document.createElement('ul'));
el.appendChild(stack[0]);
});
runner.on('suite end', function(suite) {
if (suite.root) {
return;
}
stack.shift();
});
runner.on('fail', function(test) {
if (test.type === 'hook') {
runner.emit('test end', test);
}
});
runner.on('test end', function(test) {
// TODO: add to stats
var percent = stats.tests / this.total * 100 | 0;
if (progress) {
progress.update(percent).draw(ctx);
}
// update stats
var ms = new Date() - stats.start;
text(passes, stats.passes);
text(failures, stats.failures);
text(duration, (ms / 1000).toFixed(2));
// test
var el;
if (test.state === 'passed') {
var url = self.testURL(test);
el = fragment('<li class="test pass %e"><h2>%e<span class="duration">%ems</span> <a href="%e" class="replay">‣</a></h2></li>', test.speed, test.title, test.duration, url);
} else if (test.pending) {
el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
} else {
el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay">‣</a></h2></li>', test.title, self.testURL(test));
var stackString; // Note: Includes leading newline
var message = test.err.toString();
// <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
// check for the result of the stringifying.
if (message === '[object Error]') {
message = test.err.message;
}
if (test.err.stack) {
var indexOfMessage = test.err.stack.indexOf(test.err.message);
if (indexOfMessage === -1) {
stackString = test.err.stack;
} else {
stackString = test.err.stack.substr(test.err.message.length + indexOfMessage);
}
} else if (test.err.sourceURL && test.err.line !== undefined) {
// Safari doesn't give you a stack. Let's at least provide a source line.
stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
}
stackString = stackString || '';
if (test.err.htmlMessage && stackString) {
el.appendChild(fragment('<div class="html-error">%s\n<pre class="error">%e</pre></div>', test.err.htmlMessage, stackString));
} else if (test.err.htmlMessage) {
el.appendChild(fragment('<div class="html-error">%s</div>', test.err.htmlMessage));
} else {
el.appendChild(fragment('<pre class="error">%e%e</pre>', message, stackString));
}
}
// toggle code
// TODO: defer
if (!test.pending) {
var h2 = el.getElementsByTagName('h2')[0];
on(h2, 'click', function() {
pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
});
var pre = fragment('<pre><code>%e</code></pre>', utils.clean(test.fn.toString()));
el.appendChild(pre);
pre.style.display = 'none';
}
// Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
if (stack[0]) {
stack[0].appendChild(el);
}
});
}
/**
* Makes a URL, preserving querystring ("search") parameters.
*
* @param {string} s
* @return {string} A new URL.
*/
function makeUrl(s) {
var search = window.location.search;
// Remove previous grep query parameter if present
if (search) {
search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
}
return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s));
}
/**
* Provide suite URL.
*
* @param {Object} [suite]
*/
HTML.prototype.suiteURL = function(suite) {
return makeUrl(suite.fullTitle());
};
/**
* Provide test URL.
*
* @param {Object} [test]
*/
HTML.prototype.testURL = function(test) {
return makeUrl(test.fullTitle());
};
/**
* Display error `msg`.
*
* @param {string} msg
*/
function error(msg) {
document.body.appendChild(fragment('<div id="mocha-error">%e</div>', msg));
}
/**
* Return a DOM fragment from `html`.
*
* @param {string} html
*/
function fragment(html) {
var args = arguments;
var div = document.createElement('div');
var i = 1;
div.innerHTML = html.replace(/%([se])/g, function(_, type) {
switch (type) {
case 's': return String(args[i++]);
case 'e': return escape(args[i++]);
// no default
}
});
return div.firstChild;
}
/**
* Check for suites that do not have elements
* with `classname`, and hide them.
*
* @param {text} classname
*/
function hideSuitesWithout(classname) {
var suites = document.getElementsByClassName('suite');
for (var i = 0; i < suites.length; i++) {
var els = suites[i].getElementsByClassName(classname);
if (!els.length) {
suites[i].className += ' hidden';
}
}
}
/**
* Unhide .hidden suites.
*/
function unhide() {
var els = document.getElementsByClassName('suite hidden');
while (els.length > 0) {
els[0].className = els[0].className.replace('suite hidden', 'suite');
}
}
/**
* Set an element's text contents.
*
* @param {HTMLElement} el
* @param {string} contents
*/
function text(el, contents) {
if (el.textContent) {
el.textContent = contents;
} else {
el.innerText = contents;
}
}
/**
* Listen on `event` with callback `fn`.
*/
function on(el, event, fn) {
if (el.addEventListener) {
el.addEventListener(event, fn, false);
} else {
el.attachEvent('on' + event, fn);
}
}
| GerHobbelt/mocha | lib/reporters/html.js | JavaScript | mit | 8,621 |
// Regular expression that matches all symbols with the `Pattern_White_Space` property as per Unicode v6.3.0:
/[\x09-\x0D\x20\x85\u200E\u200F\u2028\u2029]/; | mathiasbynens/unicode-data | 6.3.0/properties/Pattern_White_Space-regex.js | JavaScript | mit | 156 |
$(function() {
// When we're using HTTPS, use WSS too.
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
var to_focus = $("#message");
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/ws/");
chatsock.onmessage = function(message) {
if($("#no_messages").length){
$("#no_messages").remove();
}
var data = JSON.parse(message.data);
if(data.type == "presence"){
//update lurkers count
lurkers = data.payload.lurkers;
lurkers_ele = document.getElementById("lurkers-count");
lurkers_ele.innerText = lurkers;
//update logged in users list
user_list = data.payload.members;
document.getElementById("loggedin-users-count").innerText = user_list.length;
user_list_obj = document.getElementById("user-list");
user_list_obj.innerText = "";
//alert(user_list);
for(var i = 0; i < user_list.length; i++ ){
var user_ele = document.createElement('li');
user_ele.setAttribute('class', 'list-group-item');
user_ele.innerText = user_list[i];
user_list_obj.append(user_ele);
}
return;
}
var chat = $("#chat")
var ele = $('<li class="list-group-item"></li>')
ele.append(
'<strong>'+data.user+'</strong> : ')
ele.append(
data.message)
chat.append(ele)
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
};
$("#chatform").on("submit", function(event) {
var message = {
message: $('#message').val()
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
});
setInterval(function() {
chatsock.send(JSON.stringify("heartbeat"));
}, 10000);
});
| delitamakanda/BukkakeGram | registration/static/scripts/realtime.js | JavaScript | mit | 2,042 |
"use strict";
/** @module router
* A module that defines a class for routing
* http requests to handler functions
*/
module.exports = {
Router: Router
};
var url = require('url');
function Router(db) {
this.db = db;
this.routeMap = {
get: [],
post: []
}
}
/** @function route
* Routes an incoming request to the proper registered
* request handler, or sends a 404 error if no match
* is found. Modifies the request object to contain a
* params associative array of tokens parsed from the
* reqeust object.
* @param {http.incomingRequest} req - the reqeust object
* @param {http.serverResponse} res - the response object
*/
Router.prototype.route = function(req, res) {
console.log("Routing!");
// The method is used to determine which routeMap
// to search for the route in
var routeMap = this.routeMap[req.method.toLowerCase()];
// The resource string from the request url will
// be matched against the routeMap regular expressions
var resource = url.parse(req.url).pathname;
// Find the correct route for the requested resource
// INVARIANT: route has not yet been found.
for(var i = 0; i < routeMap.length; i++){
var match = routeMap[i].regexp.exec(resource);
if(match) {
// Store the parameters as an object
// on the request
req.params = {}
routeMap[i].tokens.forEach(function(token, j){
// Each token corresponds to a capture group
// from the regular expression match. These are
// offset by 1, as the first entry in the match
// array is the full matching string.
req.params[token] = match[j+1];
});
// Trigger the handler and return, stopping execution
return routeMap[i].handler(req, res);
}
}
console.log("Resource Not Mapped");
// If we reach this point, the resource was not mapped
// to a route, so send a 404 error
res.statusCode = 404;
res.statusMessage = "Resource not found";
res.end("Resource not found");
}
/** @function get
* Adds a GET route with associated handler to
* the get routemap.
* @param {string} route - the route to add
* @param {function} handler - the function to
* call when a match is found
*/
Router.prototype.get = function(route, handler) {
addRoute(this.routeMap.get, route, handler);
}
/** @function post
* Adds a POST route with associated handler to
* the get routemap.
* @param {string} route - the route to add
* @param {function} handler - the function to
* call when a match is found
*/
Router.prototype.post = function(route, handler) {
addRoute(this.routeMap.post, route, handler);
}
/** @function resource
* This is a shorthand method for generating restful
* routes for a resource, i.e.:
* GET route/ -> resource.list()
* POST route/ -> resource.add()
* GET route/:id -> resource.show()
* POST route/:id -> resource.update()
* GET route/:id/edit -> resource.edit()
* POST route/:id/destroy -> resource.destroy()
* @param {string} route - the resource route
* @param {object} resource - an object implementing the
* above methods
*/
Router.prototype.resource = function(route, resource) {
var db = this.db;
console.log("Route: "+route);
if(resource.list) this.get(route, function(req, res) {resource.list(req, res, db)});
if(resource.create) this.post(route, function(req, res) {resource.create(req, res, db)});
if(resource.read) this.get(route + '/:id', function(req, res) {resource.read(req, res, db)});
if(resource.edit) this.get(route + '/:id/edit', function(req, res) {resource.read(req, res, db)});
if(resource.update) this.post(route + '/:id', function(req, res) {resource.update(req, res, db)});
if(resource.destroy) this.get(route + '/:id/destroy', function(req, res) {resource.destroy(req, res, db)});
}
/** @function addRoute
* This helper function adds a route to a routeMap
* associative array
* @param {object} routeMap - the routemap to add the route to
* @param {string} route - the route to add
* @param {function} handler - the handler to add
*/
function addRoute(routeMap, route, handler) {
var tokens = [];
// Convert the route into a regular expression
var parts = route.split('/').map(function(part) {
if(part.charAt(0) == ':') {
// This is a token, so store the token and
// add a regexp capture group to our parts array
tokens.push(part.slice(1));
return '(\\w+)';
} else {
// This is a static sequence of characters,
// so leave it as-is
return part;
}
});
var regexp = new RegExp('^' + parts.join('/') + '/?$');
// Store the route in the routemap
routeMap.push({
regexp: regexp,
tokens: tokens,
handler: handler
});
}
| jdhoward5/itdb | lib/route.js | JavaScript | mit | 4,700 |
function almostPerfect() {
console.log("Hello, world!");
};
for(var i = 0; i < 10; i++)
almostPerfect();
| smikes/fez | examples/jshint/src/b.js | JavaScript | mit | 111 |
'use strict';
var _ = require( 'lodash' );
/* RESPONSE DATA STRUCTURE
==========================================================================
data = [ ..., { // Day Object
stop_id: '2681',
stop_name: 'Highland Ave @ Benton Rd',
mode: [ ..., { // Mode Object
mode_name: 'Bus',
route_type: '3',
route: [ ..., { // Route Object
route_id: '88',
route_name: '88',
direction: [ ..., { // Direction Object
direction_id: '1',
direction_name: 'Inbound',
trip: [ ..., { // Trip Object
sch_arr_dt: '1434278820',
sch_dep_dt: '1434278820',
trip_id: '26616679',
trip_name: '6:40 am from Clarendon Hill Busway to Lechmere'
}]
}]
}]
}]
}]
*/
/**
* Convert from a Day Object to a flat array of data objects representing trips
* @param {Number} dayIndex A numeric index for a weekday, from 0 to 6
* @param {Object} route A route object from the API response
* @return {Array} A flat array of trip data objects
*/
function convertRouteToTripsArray( dayIndex, route ) {
/* jshint camelcase: false */
var routeId = route.route_id;
var routeName = route.route_name;
return _.map( route.direction, function( direction ) {
return _.map( direction.trip, function( trip ) {
return {
day: +dayIndex,
name: trip.trip_name,
route: routeName,
routeId: routeId,
time: +trip.sch_arr_dt,
// Trip ID is NOT UNIQUE: avoid collection issues by avoiding 'id'
tripId: +trip.trip_id
};
});
});
}
/**
* Convert the raw API responses into a flat array of trips
* @param {Array} data The API response object
* @return {Array} A flat array of object literals describing trips
*/
function parseData( data ) {
return _.chain( data )
.reduce(function( memo, day, dayIndex ) {
var trips = _.chain( day.mode )
.pluck( 'route' )
.flatten()
// Create the mapper method for the relevant day
.map( _.partial( convertRouteToTripsArray, dayIndex ) )
.flattenDeep() // Deep flatten
.value();
// Concatenate with the prior results
return memo.concat( trips );
}, [])
.sortBy(function( trip ) {
return trip.time;
})
.value();
}
module.exports = parseData;
| kadamwhite/bus-frequency-vis | lib/parse-data.js | JavaScript | mit | 2,468 |
'use strict';
var extend = require('../utils/extend');
var LoginTask = require('./login');
var IonicAppLib = require('ionic-app-lib');
var IonicProject = IonicAppLib.project;
var Share = IonicAppLib.share;
var log = IonicAppLib.logging.logger;
var Login = IonicAppLib.login;
var appLibUtils = IonicAppLib.utils;
var settings = {
title: 'share',
name: 'share',
summary: 'Share an app with a client, co-worker, friend, or customer',
args: {
'<EMAIL>': 'The email to share the app with'
},
isProjectTask: true
};
function run(ionic, argv) {
var project;
if (argv._.length < 2) {
return appLibUtils.fail('Invalid command', 'share');
}
try {
project = IonicProject.load();
} catch (ex) {
appLibUtils.fail(ex.message);
return;
}
if (project.get('app_id') === '') {
return appLibUtils.fail('You must first upload the app to share it');
}
var email = argv._[1];
if (email.indexOf('@') < 0) {
return appLibUtils.fail('Invalid email address', 'share');
}
log.info(['Sharing app ', project.get('name'), ' (', project.get('app_id'), ') with ', email, '.'].join('').green);
return Login.retrieveLogin()
.then(function(jar) {
if (!jar) {
log.info('No previous login existed. Attempting to log in now.');
return LoginTask.login(argv);
}
return jar;
})
.then(function(jar) {
return Share.shareApp(process.cwd(), jar, email);
})
.catch(function(ex) {
return appLibUtils.fail(ex);
});
}
module.exports = extend(settings, {
run: run
});
| jeneser/hpuHelper | node_modules/ionic/lib/ionic/share.js | JavaScript | mit | 1,541 |