text
stringlengths 2
6.14k
|
|---|
'use strict';
/**
* StackPush
*
* [TOP][MAX][0][][][][MAX - 1]
*/
const Command = require('../../command');
class StackPush extends Command {
run(base, value, length = 1) {
this.writeLog(`base: ${base}, value: ${value}, length: ${length}`); //TODO
return true;
}
output(base, value, length = 1) {
const ret = [];
base = this.parseVar(base);
// isFull
if (length == 1) {
ret.push(`If(01, ${base}, 1, ${base + 1}, 1, 1)`); // equalでもいいけど……
} else {
const tmpVar = this.getTmpVarNumber(0);
ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 0, 1, ${base}, 0)`);
ret.push(`Variable(0, ${tmpVar}, ${tmpVar}, 1, 0, ${length - 1}, 0)`);
ret.push(`If(01, ${tmpVar}, 1, ${base + 1}, 1, 1)`);
}
// debug Message // TODO エラー処理
// ret.push(`Text("isFull")`);
ret.push(`Else`);
for (let i = 0; i < length; i ++) {
// push var
if (typeof value == 'string') {
// var
const valueVarNum = this.parseVar(value);
ret.push(`Variable(2, ${base}, 0, 0, 1, ${valueVarNum + i}, 0)`);
} else {
// int扱い
ret.push(`Variable(2, ${base}, 0, 0, 0, ${value}, 0)`);
}
// TOP++
ret.push(`Variable(0, ${base}, ${base}, 1, 0, 1, 0)`);
}
ret.push(`EndIf`);
return ret;
}
get JP_NAME() {
return 'SET:stack-PUSH';
}
}
module.exports = StackPush;
|
var setupMethods = function(specs, window){
var Element = window.Element || global.Element;
global.disableNegNth = true;
global.cannotDisableQSA = true;
window.SELECT = function(context, selector, append){
return Element.getElements(context, selector);
};
window.SELECT1 = function(context, selector){
return Element.getElement(context, selector);
};
window.MATCH = function(context, selector){
return Element.match(context, selector);
};
// window.isXML = function(document){
// return Slick.isXML(document);
// };
// window.PARSE = function(selector){
// return Slick.parse(selector);
// };
}
var verifySetupMethods = function(specs, window){
describe('Verify Setup',function(){
it('should define SELECT', function(){
expect( typeof window.SELECT ).toEqual('function');
expect( window.SELECT(window.document, '*').length ).not.toEqual(0);
});
it('should define MATCH', function(){
expect( typeof window.MATCH ).toEqual('function');
expect( window.MATCH(window.document.documentElement, '*') ).toEqual(true);
});
// it('should define isXML', function(){
// expect( typeof window.isXML ).toEqual('function');
// expect( typeof window.isXML(window.document) ).toEqual('boolean');
// });
});
};
var verifySetupContext = function(specs, context){
describe('Verify Context',function(){
it('should set the context properly', function(){
expect(context.document).toBeDefined();
expect(context.document.nodeType).toEqual(9);
var title = context.document.getElementsByTagName('title');
for (var i=0, l=title.length; i < l; i++)
if (title[i].firstChild)
expect(title[i].firstChild.nodeValue).not.toMatch(404);
});
});
};
|
ig.module(
'plugins.shade.util.math.geom'
).defines(function () {
window.sh = window.sh || {};
sh.util = sh.util || {};
sh.util.math = sh.util.math || {};
sh.util.math.geom = sh.util.math.geom || {};
sh.util.math.geom.projVert = function (a, b, x) {
var pos = a, dir = { x: b.x - a.x, y: b.y - a.y };
if (dir.x === 0) return null;
var t = (x - pos.x)/dir.x;
return (t < 0) ? null : (pos.y + t * dir.y);
};
sh.util.math.geom.projHorz = function (a, b, y) {
var pos = a, dir = { x: b.x - a.x, y: b.y - a.y };
if (dir.y === 0) return null;
var t = (y - pos.y)/dir.y;
return (t < 0) ? null : (pos.x + t * dir.x);
};
// TODO Clean up this method to make fewer comparisons
sh.util.math.geom.polyContains = function (points, test) {
var len = points.length, res = false;
for (var i = 0, j = len - 1; i < len; j = i++) {
var pi = points[i], pj = points[j];
if ((pi.x > test.x) !== (pj.x > test.x) && pi.y === pj.y && pi.y === test.y) {
return true;
}
if ((pi.y > test.y) !== (pj.y > test.y)) {
if (pi.x === pj.x && pi.x === test.x) {
return true;
}
if ((test.x < (pj.x - pi.x) * (test.y - pi.y) / (pj.y - pi.y) + pi.x)) {
res = !res;
}
}
}
return res;
};
});
|
function hello() {
if (Meteor.isCordova) {
alert("Hello, World!");
} else {
alert("Hello, World!");
}
}
function helloNative() {
if (Meteor.isCordova) {
navigator.notification.alert("Hello, World!", null, "");
} else {
alert("Hello, World!");
}
}
Template.appBody.events({
'click [data-action=hello]': hello,
'click [data-action=helloNative]': helloNative,
});
|
'use strict';
var $npm = {
utils: require('../utils'),
formatting: require('../formatting')
};
/**
* @class helpers.TableName
* @description
*
* **Alternative Syntax:** `TableName({table, [schema]})` ⇒ {@link helpers.TableName}
*
* Prepares and escapes a full table name that can be injected into queries directly.
*
* This is a read-only type that can be used wherever parameter `table` is supported.
*
* @param {String|Object} table
* Table name details, depending on the type:
*
* - table name, if `table` is a string
* - object `{table, [schema]}`
*
* @param {string} [schema]
* Database schema name.
*
* When `table` is passed in as `{table, [schema]}`, this parameter is ignored.
*
* @property {string} name
* Formatted/escaped full table name, based on properties `schema` + `table`.
*
* @property {string} table
* Table name.
*
* @property {string} schema
* Database schema name.
*
* It is `undefined` when no schema was specified (or if it was an empty string).
*
* @returns {helpers.TableName}
*
* @example
*
* var table = new pgp.helpers.TableName('my-table', 'my-schema');
* console.log(table);
* //=> "my-schema"."my-table"
*
*/
function TableName(table, schema) {
if (!(this instanceof TableName)) {
return new TableName(table, schema);
}
if (table && typeof table === 'object' && 'table' in table) {
schema = table.schema;
table = table.table;
}
if (!$npm.utils.isText(table)) {
throw new TypeError("Table name must be non-empty text string.");
}
if (!$npm.utils.isNull(schema)) {
if (typeof schema !== 'string') {
throw new TypeError("Invalid schema name.");
}
if (schema.length > 0) {
this.schema = schema;
}
}
this.table = table;
this.name = $npm.formatting.as.name(table);
if (this.schema) {
this.name = $npm.formatting.as.name(schema) + '.' + this.name;
}
Object.freeze(this);
}
/**
* @method helpers.TableName.toString
* @description
* Creates a well-formatted string that represents the object.
*
* It is called automatically when writing the object into the console.
*
* @returns {string}
*/
TableName.prototype.toString = function () {
return this.name;
};
TableName.prototype.inspect = function () {
return this.toString();
};
module.exports = TableName;
|
/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'notification', 'ko', {
closed: '알림이 닫힘.'
} );
|
/*
* This file is part of the Husky Validation.
*
* (c) MASSIVE ART WebServices GmbH
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*
*/
define([
'type/default'
], function(Default) {
'use strict';
var dataChangedHandler = function(data, $el) {
App.emit('sulu.preview.update', $el, data);
App.emit('sulu.content.changed');
};
return function($el, options) {
var defaults = {},
subType = {
initializeSub: function() {
var dataChangedEvent = 'sulu.media-selection.' + options.instanceName + '.data-changed';
App.off(dataChangedEvent, dataChangedHandler);
App.on(dataChangedEvent, dataChangedHandler);
},
setValue: function(value) {
// array of objects
if (App.util.typeOf(value) === 'array' && App.util.typeOf(value[0]) === 'object') {
var ids = [];
App.util.foreach(value, function(el) {
ids.push(el.id);
}.bind(this));
value = {ids: ids};
}
App.dom.data($el, 'media-selection', value);
},
getValue: function() {
return App.dom.data($el, 'media-selection');
},
needsValidation: function() {
return false;
},
validate: function() {
return true;
}
};
return new Default($el, defaults, options, 'smartContent', subType);
};
});
|
define(['object/ImageObject'], function(ImageObject) {
function Troll(id, x, y, scene) {
ImageObject.call(this, id, x, y, 100, scene, '/images/trollface_small.jpg');
return this;
}
Troll.prototype = new ImageObject();
Troll.prototype.constructor = Troll;
Troll.prototype.replace = function(canvasWidth, canvasHeight) {
// Need to make sure image will not be out of canvas boundary
var maxX = canvasWidth - this.image.width;
var x = Math.floor(Math.random() * maxX);
var maxY = canvasHeight - this.image.height;
var y = Math.floor(Math.random() * maxY);
// Update position in scene
this.position.x = x;
this.position.y = y;
};
return Troll;
});
|
//站点路径 js
(function ($) {
//配置样式
var pathStartWith = "web"; //从哪一级路径开始匹配
var divsionClass = "gt"; //分隔符样式
var divsionChartper = "/";//分隔符字符
var crumbsClassPrefix = "level";//面包屑样式前缀
var crumbs = function(){
//判断是否启用
if(this.attr("data-enable") == "false") return;
this.addClass("crumbs");
var paths = getNode();
var divsion = "<span class='"+ divsionClass +"'>"+ divsionChartper +"</span>";
var htmlstring = "";
for(var i =0 ; i< paths.length ; i++){
if(paths[i] != undefined){
var classname = crumbsClassPrefix + (i+1);
var href = paths[i].url;
var name = paths[i].name;
if(i>0){
htmlstring += divsion;
}
//若href空或者未定义就生成spna标签
if(href =="" || href == undefined){
htmlstring += "<span class='"+ classname +"'>"+ name +"</span>";
}
else{
htmlstring += "<a class='"+ classname +"' href='"+ href +"'>"+ name +"</a>";
}
}
}
//处理绑定的数据
htmlstring = bindData(this,htmlstring);
this.html(htmlstring);
}
//处理绑定的数据
var bindData = function($targ,htmlstring){
var start = htmlstring.indexOf("{") + 1;
var end = htmlstring.indexOf("}") - start;
if(start == 0|| end == -1){
return htmlstring;
}
var targerAttr = "data-" + htmlstring.substr(start,end);
var data = $targ.attr(targerAttr);
return htmlstring.replace("{" + htmlstring.substr(start,end) + "}",data);
}
//站点地图配置
var getNode = function(){
var path = window.location.pathname;
var nodes = getWebNodeArray(path).reverse();
var level1,level2,level3;
//找第一级
var node = nodes.pop();
if(node != undefined){
for(var i =0; i<sitemap.length ; i++ )
{
if(node.indexOf(sitemap[i].match) != -1){
//找到第一级元素
level1 = sitemap[i];
break;
}
}
}
//找第二级
var node = nodes.pop();
if(node != undefined && level1 != undefined && level1.item != undefined){
for(var i =0; i<level1.item.length ; i++ )
{
if(node.indexOf(level1.item[i].match) != -1){
//找到第二级元素
level2 = level1.item[i];
break;
}
}
}
//找第三级
var node = nodes.pop();
if(node != undefined && level2 != undefined && level2.item != undefined){
for(var i =0; i<level2.item.length ; i++ )
{
if(node.indexOf(level2.item[i].match) != -1){
//找到第二级元素
level3 = level2.item[i];
break;
}
}
}
return [level1,level2,level3];
}
var getWebNodeArray = function(path){
pathStartWith = pathStartWith.toLocaleLowerCase();
var nodes = [];
var arr=new Array();
arr=path.split('/');
var status = 0;
for(var i=0;i<arr.length;i++){
if(status==1){
nodes.push(arr[i]);
}
if(arr[i].indexOf(pathStartWith) != -1){
status = 1;
}
}
return nodes;
}
$.fn.crumbs = crumbs;
})(jQuery);
|
var ajax = require('ajax')
var Future = require("async-future")
var decodeDataUrl = require("./decodeDataUrl")
exports.fromUrl = function(sourceUrl, toSource) {
return ajax(sourceUrl, true).then(function(response) {
return fromSourceOrHeaders(response.headers, response.text, toSource)
})
}
exports.fromSource = function(sourceText, toSource) {
return fromSourceOrHeaders({}, sourceText, toSource)
}
function fromSourceOrHeaders(headers, sourceText, toSource) {
if(toSource === undefined) toSource = false
var sourcemapUrl = getSourceMapUrl(headers, sourceText)
if(sourcemapUrl === undefined) {
return Future(undefined)
} else if(toSource) {
if(sourcemapUrl.indexOf('data:') === 0) {
return Future(decodeDataUrl(sourcemapUrl))
} else {
return ajax(sourcemapUrl).then(function(response) {
return Future(response.text)
})
}
} else {
return Future(sourcemapUrl)
}
}
exports.cacheGet = ajax.cacheGet
exports.cacheSet = ajax.cacheSet
var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)'
var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")"
var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART
var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_PART
function getSourceMapUrl(headers, content) {
if(headers['SourceMap'] !== undefined) {
return headers['SourceMap']
} else if(headers['X-SourceMap']) {
return headers['X-SourceMap']
} else {
var match = content.match(SOURCE_MAP_PATTERN1)
if(match !== null) return match[1]
match = content.match(SOURCE_MAP_PATTERN2)
if(match !== null) return match[1]
}
}
|
const deposits = require('../models/deposits')
const NO_HISTORY = 'no_history_in_range'
async function insertNewRecord (playerId, voucherId) {
return deposits.create(playerId, voucherId)
}
async function findBetween (playerId, from, to, page, pagination) {
const histories = await deposits.findByOwnerAndCreationDuration(playerId, from, to, page - 1, pagination)
if (histories.length === 0) {
throw new Error(NO_HISTORY)
}
return histories
}
module.exports = {
NO_HISTORY,
insertNewRecord,
findBetween
}
|
'use strict';
(function (ga) {
function DataMetrics() {
this.init();
}
DataMetrics.prototype = {
init: function () {
this.addEventListeners();
},
addEventListeners: function () {
var elements = document.querySelectorAll('*[data-metrics]');
for (var i = 0; i < elements.length; i++) {
if (!this.isForm(elements[i])) {
elements[i].addEventListener('click', this.appendEvent.bind(this), false);
} else {
elements[i].onsubmit = this.appendEvent.bind(this);
}
}
},
isForm: function (elem) {
if (elem.tagName === 'FORM') {
return true;
} else {
return false;
}
},
appendEvent: function (e) {
var elem = e.currentTarget;
if (!elem.classList.contains('sending-metrics')) {
var params = elem.getAttribute('data-metrics').split('|');
if (params[1] === undefined) {
params[1] = null;
}
if (params[2] === undefined) {
params[2] = null;
}
this.sendToGA(params[0], params[1], params[2], elem);
elem.classList.add('sending-metrics');
if (!this.isForm(elem) && !elem.getAttribute('target')) {
e.preventDefault();
return false;
}
}
},
sendToGA: function (category, action, label, elem) {
var self = this;
window.ga('send', 'event', category, action, label, { 'hitCallback': function () {
self.onHitCallback(elem);
}});
},
onHitCallback: function (elem) {
if (elem) {
this.onEventIsDispatched(elem);
}
},
onEventIsDispatched: function (elem) {
if (elem.getAttribute('href') && !elem.getAttribute('target')) {
window.location.href = elem.getAttribute('href');
} else if (this.isForm(elem)) {
elem.submit();
}
elem.classList.remove('sending-metrics');
}
};
window.dataMetrics = new DataMetrics();
})(window.ga);
|
// 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 vendor/assets/javascripts of plugins, if any, 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
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require page-styles
//= require_tree .
|
"use strict";
/*
See License / Disclaimer https://raw.githubusercontent.com/DynamicTyped/Griddle/master/LICENSE
*/
var React = require("react");
var _ = require("underscore");
var ColumnProperties = require("./columnProperties.js");
var GridTitle = React.createClass({
displayName: "GridTitle",
getDefaultProps: function () {
return {
columnSettings: null,
rowSettings: null,
sortSettings: null,
headerStyle: null,
useGriddleStyles: true,
useGriddleIcons: true,
headerStyles: {} };
},
componentWillMount: function () {
this.verifyProps();
},
sort: function (event) {
this.props.sortSettings.changeSort(event.target.dataset.title || event.target.parentElement.dataset.title);
},
verifyProps: function () {
if (this.props.columnSettings === null) {
console.error("gridTitle: The columnSettings prop is null and it shouldn't be");
}
if (this.props.sortSettings === null) {
console.error("gridTitle: The sortSettings prop is null and it shouldn't be");
}
},
render: function () {
this.verifyProps();
var that = this;
var nodes = this.props.columnSettings.getColumns().map(function (col, index) {
var columnSort = "";
var sortComponent = null;
var titleStyles = null;
if (that.props.sortSettings.sortColumn == col && that.props.sortSettings.sortAscending) {
columnSort = that.props.sortSettings.sortAscendingClassName;
sortComponent = that.props.useGriddleIcons && that.props.sortSettings.sortAscendingComponent;
} else if (that.props.sortSettings.sortColumn == col && that.props.sortSettings.sortAscending === false) {
columnSort += that.props.sortSettings.sortDescendingClassName;
sortComponent = that.props.useGriddleIcons && that.props.sortSettings.sortDescendingComponent;
}
var meta = that.props.columnSettings.getColumnMetadataByName(col);
var columnIsSortable = that.props.columnSettings.getMetadataColumnProperty(col, "sortable", true);
var displayName = that.props.columnSettings.getMetadataColumnProperty(col, "displayName", col);
columnSort = meta == null ? columnSort : (columnSort && columnSort + " " || columnSort) + that.props.columnSettings.getMetadataColumnProperty(col, "cssClassName", "");
if (that.props.useGriddleStyles) {
titleStyles = {
backgroundColor: "#EDEDEF",
border: "0",
borderBottom: "1px solid #DDD",
color: "#222",
padding: "5px",
cursor: columnIsSortable ? "pointer" : "default"
};
}
return React.createElement(
"th",
{ onClick: columnIsSortable ? that.sort : null, "data-title": col, className: columnSort, key: displayName, style: titleStyles },
displayName,
sortComponent
);
});
//Get the row from the row settings.
var className = that.props.rowSettings && that.props.rowSettings.getHeaderRowMetadataClass() || null;
return React.createElement(
"thead",
null,
React.createElement(
"tr",
{
className: className,
style: this.props.headerStyles },
nodes
)
);
}
});
module.exports = GridTitle;
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
'use strict';
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'angular-cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-remap-istanbul'),
require('angular-cli/plugins/karma')
],
files: [
{ pattern: './src/test.ts', watched: false }
],
preprocessors: {
'./src/test.ts': ['angular-cli']
},
mime: {
'text/x-typescript': ['ts','tsx']
},
remapIstanbulReporter: {
reports: {
html: 'coverage',
lcovonly: './coverage/coverage.lcov'
}
},
angularCli: {
config: './angular-cli.json',
environment: 'dev'
},
reporters: config.angularCli && config.angularCli.codeCoverage
? ['progress', 'karma-remap-istanbul']
: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chromium'],
singleRun: false
});
};
|
var async = require('async'),
events = require('events'),
log = function (text, debug) {
if(debug) {
console.log(new Date().toLocaleTimeString(), '|', text);
}
},
generateAndApplyETags = function (newBuilds) {
for (var i = 0; i < newBuilds.length; i++) {
var build = newBuilds[i];
build.etag = require('crypto')
.createHash('md5')
.update(JSON.stringify(build))
.digest('hex');
}
},
sortBuilds = function (newBuilds, sortOrder) {
if(sortOrder == "project") {
newBuilds.sort(function (a, b) {
if(a.project > b.project) return 1;
if(a.project < b.project) return -1;
return 0;
});
}
else {
var takeDate = function (build) {
return build.isRunning ? build.startedAt : build.finishedAt;
};
newBuilds.sort(function (a, b) {
var dateA = takeDate(a);
var dateB = takeDate(b);
if(dateA < dateB) return 1;
if(dateA > dateB) return -1;
return 0;
});
}
},
distinctBuildsByETag = function (newBuilds) {
var unique = {};
for (var i = newBuilds.length - 1; i >= 0; i--) {
var build = newBuilds[i];
if (unique[build.etag]) {
newBuilds.splice(i, 1);
}
unique[build.etag] = true;
}
},
onlyTake = function (numberOfBuilds, newBuilds) {
newBuilds.splice(numberOfBuilds);
},
changed = function (currentBuilds, newBuilds) {
var newBuildsHash = newBuilds
.map(function (value) {
return value.etag;
})
.join('|');
var currentBuildsHash = currentBuilds
.map(function (value) {
return value.etag;
})
.join('|');
return newBuildsHash !== currentBuildsHash;
},
detectChanges = function (currentBuilds, newBuilds) {
var changes = {
added: [],
removed: [],
updated: []
},
getById = function (builds, id) {
return builds.filter(function (build) {
return build.id === id;
})[0];
};
var currentBuildIds = currentBuilds.map(function (build) { return build.id; });
var newBuildIds = newBuilds.map(function (build) { return build.id; });
newBuildIds.forEach(function (newBuildId) {
if (currentBuildIds.indexOf(newBuildId) === -1) {
changes.added.push(getById(newBuilds, newBuildId));
}
if (currentBuildIds.indexOf(newBuildId) >= 0) {
var currentBuild = getById(currentBuilds, newBuildId);
var newBuild = getById(newBuilds, newBuildId);
if (currentBuild.etag !== newBuild.etag) {
changes.updated.push(getById(newBuilds, newBuildId));
}
}
});
currentBuildIds.forEach(function (currentBuildId) {
if (newBuildIds.indexOf(currentBuildId) === -1) {
changes.removed.push(getById(currentBuilds, currentBuildId));
}
});
changes.order = newBuildIds;
return changes;
};
module.exports = function () {
var self = this;
self.configuration = {
interval: 5000,
numberOfBuilds: 12,
debug: false
};
self.plugins = [];
self.currentBuilds = [];
self.configure = function (config) {
self.configuration = config;
};
self.watchOn = function (plugin) {
self.plugins.push(plugin);
};
self.run = function () {
var allBuilds = [];
async.each(self.plugins, function (plugin, callback) {
log('Check for builds...', self.configuration.debug);
plugin.check(function (error, pluginBuilds) {
if (error) {
console.log('**********************************************************************');
console.log('An error occured when fetching builds for the following configuration:');
console.log('----------------------------------------------------------------------');
console.log(plugin.configuration);
console.log('----------------------------------------------------------------------');
console.log();
console.error(error);
console.log('**********************************************************************');
console.log();
console.log();
callback();
return;
}
if(self.configuration.latestBuildOnly) {
Array.prototype.push.apply(allBuilds, [pluginBuilds.shift()]);
}
else {
Array.prototype.push.apply(allBuilds, pluginBuilds);
}
callback();
});
},
function (error) {
log(allBuilds.length + ' builds found....', self.configuration.debug);
generateAndApplyETags(allBuilds);
distinctBuildsByETag(allBuilds);
sortBuilds(allBuilds, self.configuration.sortOrder);
if(!self.configuration.latestBuildOnly) {
onlyTake(self.configuration.numberOfBuilds, allBuilds);
}
if(changed(self.currentBuilds, allBuilds)) {
log('builds changed', self.configuration.debug);
self.emit('buildsChanged', detectChanges(self.currentBuilds, allBuilds));
self.currentBuilds = allBuilds;
}
setTimeout(self.run, self.configuration.interval);
});
};
};
module.exports.prototype = new events.EventEmitter();
|
function routes(handlers) {
const routeArr = [
{
method: 'GET',
path: '/img/{file*}',
handler: handlers.img
},
{
method: 'GET',
path: '/js/{file*}',
handler: handlers.js
},
{
method: 'GET',
path: '/',
handler: handlers.index
},
{
method: 'GET',
path: '/version',
handler: handlers.version
},
{
method: 'POST',
path: '/identify',
handler: handlers.identifyPeople
}];
return routeArr;
}
module.exports = routes;
|
app.controller('bodyController', ['$scope',
function($scope) {
'use strict';
$scope.setBodyClass = function(bodyClass) {
$scope.bodyClass = bodyClass;
$scope.loginPage = ($scope.bodyClass === 'login');
};
}
]);
|
import {inject, bindable, customElement} from 'aurelia-framework';
import './attribute-item.less';
@customElement('attribute-item')
@bindable('model')
@inject(Element)
export class AttributeItem {
constructor(element) {
this.element = element;
}
remove() {
let e = new window.CustomEvent('removed', { detail: this.model });
this.element.dispatchEvent(e);
}
}
|
/*globals template*/
var parse = function (key, obj) {
'use strict';
var ar = key.split('.');
while (obj && ar.length) {
obj = obj[ar.shift()];
}
return obj;
};
var extend = function (a, b) {
'use strict';
for (var i in b) {
if (a.hasOwnProperty(i) || b.hasOwnProperty(i)) {
a[i] = b[i];
}
}
return a;
};
var templateString = function (st, data, options, lng, defaults) {
'use strict';
var i;
var evaluate = /\{\{([\s\S]+?)\}\}/g;
var interpolate = /\{\{=([\s\S]+?)\}\}/g;
var escape = /\{\{-([\s\S]+?)\}\}/g;
options = options || {};
var settings = {
evaluate: options.evaluate || evaluate,
interpolate: options.interpolate || interpolate,
escape: options.escape || escape
};
var newDatas = extend(extend(defaults, defaults[lng]), data) ||
defaults || {};
var needsTemplate = false;
for (i in settings) {
if (settings.hasOwnProperty(i) && settings[i].test(st)) {
needsTemplate = true;
break;
}
}
if (needsTemplate && typeof st !== 'function' &&
typeof template === 'function') {
st = template(st, settings);
}
return typeof st === 'function' ? st(newDatas) : st;
};
var I18n = function () {
'use strict';
// PRIVATES
var localLang = 'en';
var dico = {};
var defaults = {};
this.add = function (lang, ns, locales) {
var i;
var obj;
dico[lang] = dico[lang] || {};
if (locales === undefined) {
locales = ns;
ns = undefined;
obj = dico[lang];
} else {
dico[lang][ns] = dico[lang][ns] || {};
obj = dico[lang][ns];
}
obj = extend(obj, locales);
};
this.has = function (key, lang) {
lang = lang || localLang;
var keyToParse = lang + '.' + key;
// Check for the lang
if (dico[key]) {
return true;
}
// Check for the key and lang
return parse(keyToParse, dico) ? true : false;
};
this.listLangs = function () {
var langs = [];
for (var i in dico) {
langs.push(i);
}
return langs;
};
this.getCurrentLang = function () {
return localLang;
};
this.getDico = function () {
return dico;
};
this.getDefaults = function () {
return defaults;
};
this.setLang = function (lang) {
localLang = lang;
return localLang;
};
this.setDefaults = function (options) {
defaults = extend(defaults, options || {});
};
this.get = function (key, data, options, lang) {
var lng = lang || localLang;
if (lang === undefined) {
if (typeof data === 'string') {
lng = data;
data = undefined;
} else if (typeof options === 'string') {
lng = options;
}
}
var obj = parse(lng + '.' + key, dico) ||
parse(lng + '.' + key, defaults) ||
parse(key, defaults);
options = options || {};
var toReturn = key;
if (typeof obj === 'string' || typeof obj === 'function') {
toReturn = templateString(obj, data, options, lng, defaults);
} else if (typeof obj === 'object') {
toReturn = obj;
}
return toReturn;
};
};
return new I18n();
|
$("#addOptionButton").on("click", function (event) {
let description = $("#optionDesc").val();
let id = location.href.split("=")[1];
let body = {
id: id,
description: description
};
$.ajax({
url: "/Question/AddOption",
type: "post",
cors: true,
contentType: "application/json",
data: JSON.stringify(body),
success: function (response) {
location.reload();
}
});
});
|
import jwt from 'jsonwebtoken';
import tokens from './tokenStore';
const token = {
issue: (payload, secret, options, connectionString) => {
let database;
return tokens.connect(connectionString).then((db) => {
database = db;
return tokens.find(database, payload);
})
.then((record) => {
if (record) { throw new Error('JWT already white listed.'); }
return tokens.save(database, payload);
})
.then((record) => {
if (!record) { throw new Error('Failed to whitelist JWT.'); }
return sign(payload, secret, options);
});
},
revoke: (decodedToken, connectionString) =>
tokens.connect(connectionString)
.then((db) => tokens.remove(db, decodedToken)),
verify: (token, secret, connectionString) => {
let decodedToken;
return verify(token, secret).then((decoded) => {
decodedToken = decoded;
return tokens.connect(connectionString);
})
.then((db) => tokens.find(db, decodedToken))
.then((record) => new Promise((resolve, reject) => {
if (!record) { return reject('JWT is not whitelisted.'); }
return resolve(decodedToken);
}));
}
};
function verify(token, secret) {
return new Promise((resolve, reject) => jwt.verify(token, secret, (err, decoded) => {
if (err) { return reject(err); }
return resolve(decoded);
}));
}
function sign(payload, secret, options) {
return new Promise((resolve) => {
let token = jwt.sign(payload, secret, options);
return resolve(token);
});
}
module.exports = token;
|
module.exports = function(app , func , mail, upload, storage, mailer, multer, validator, Services, paginate, cors){
app.get("/services/" , servicelist);
app.get("/services/view/:id" , serviceview);
app.get("/services/add" , serviceadd);
app.post("/services/add" , serviceadd);
app.get("/services/edit/:id" , serviceedit);
app.post("/services/edit/:id" , serviceedit);
app.get("/services/delete/:id" , servicedelete);
function servicelist(req, res){
var sess = req.session;
//req.session.flashmessage = "";
func.isGuestSession(req.session , res);
var data = {
};
if(req.query.title && validator.trim(req.query.title.trim())){
var searchtitle = req.query.title.trim();
data.title = searchtitle;
}
if(req.query.price && validator.trim(req.query.price.trim())){
var searchprice = req.query.price.trim();
data.price = searchprice;
}
if(req.query.cost && validator.trim(req.query.cost.trim())){
var searchcost = req.query.cost.trim();
data.cost = searchcost;
}
if(req.query.limit){
perPage = req.query.limit;
}
else {
perPage = 1;
}
page = req.query.page > 0 ? req.query.page:1;
Services.find(data).limit(perPage).skip(perPage * (page-1)).sort({'title': 'asc'}).exec(function(err, services){
console.log(services);
Services.count().exec(function (err, count) {
console.log(count);
res.render("services/index" , {
services:services,
session:sess,
pages: count/perPage,
count: count,
pagelimit:perPage,
currentpage:page
});
});
});
}
function serviceview(req, res){
var sess = req.session;
var serviceid = req.params.id;
func.isGuestSession(req.session , res);
Services.find({_id:serviceid}, function(err, services) {
if (err) throw err;
console.log(services);
res.render("services/view" , {
service:services,
session:sess
});
});
}
function servicedelete(req, res){
var sess = req.session;
var serviceid = req.params.id;
func.isGuestSession(req.session , res);
Services.findOneAndRemove({ _id: serviceid }, function(err) {
if (err) throw err;
console.log('Service successfully deleted!');
sess.flashmessage = "Service detail deleted successfully";
res.redirect("../");
});
}
function serviceadd(req, res){
var sess = req.session;
var error = [];
var data = {};
func.isGuestSession(req.session , res);
if(req.method=="POST"){
if(!validator.trim(req.body.title)){
error.push("Enter Title");
}
if(!validator.trim(req.body.description)){
error.push("Enter Description");
}
if(!validator.trim(req.body.price)){
error.push("Enter Price");
}
if(!validator.trim(req.body.cost)){
error.push("Enter Cost");
}
if(!validator.trim(req.body.status)){
error.push("Select Status");
}
if(error.length<=0){
data = {
title:req.body.title.trim(),
description:req.body.description.trim(),
price:req.body.price.trim(),
cost:req.body.cost.trim(),
status:req.body.status.trim()
};
var detail = new Services(data);
detail.save(function(err){
if(err) throw err;
console.log('Service saved successfully!');
sess.flashmessage = "Service detail saved successfully";
res.redirect('../services');
});
}
else {
res.render("services/add" , {
service:req.body,
errors:error
});
}
}
else {
res.render("services/add" , {
service:req.body,
errors:error
});
}
}
function serviceedit(req, res){
var sess = req.session;
var serviceid = req.params.id;
var error = [];
var data = [];
var servicedata = [];
func.isGuestSession(req.session , res);
if(req.method=="POST"){
if(!validator.trim(req.body.title)){
error.push("Enter Title");
}
if(!validator.trim(req.body.description)){
error.push("Enter Description");
}
if(!validator.trim(req.body.price)){
error.push("Enter Price");
}
if(!validator.trim(req.body.cost)){
error.push("Enter Cost");
}
if(!validator.trim(req.body.status)){
error.push("Select Status");
}
if(error.length<=0){
var data = {
title:req.body.title.trim(),
description:req.body.description.trim(),
price:req.body.price.trim(),
cost:req.body.cost.trim(),
status:req.body.status.trim()
};
Services.findOneAndUpdate({ _id: serviceid }, data, function(err, services) {
if (err) throw err;
console.log(services);
sess.flashmessage = "Service detail updated successfully";
res.redirect("../");
});
}
}
Services.find({_id:serviceid}, function(err, services) {
if (err) throw err;
console.log(services);
res.render("services/edit" , {
service:services,
id:serviceid,
errors:error
});
});
}
}
|
var i = 0;
function timedCount() {
i = i + 1;
postMessage(i);
setTimeout("timedCount()", 500);
}
timedCount();
|
const jwt = require('jsonwebtoken');
import { usersData } from '../data/users';
export const checkLogin = (req, res, next) => {
let user = usersData.find(({firstName}) => firstName === req.body.firstName);
if (!user || user.lastName !== req.body.lastName) {
res.status(403).json({success: false, message: 'User or password is invalid'})
} else {
user.token = jwt.sign(user, 'enigma', {expiresIn: 3600})
req.user = user;
next()
}
};
|
import { storiesOf } from '@storybook/polymer';
import { html } from 'lit-html';
import moment from 'moment';
import { object, text } from '@storybook/addon-knobs';
import '@lit-any/lit-any/lit-view';
import ViewTemplates from '@lit-any/lit-any/views';
import { defaultValue } from './knobs';
import basic from './notes/lit-view/basic';
import recursive from './notes/lit-view/recursive';
import recursiveElements from './notes/lit-view/recursive-elements';
import recursiveWithParams from './notes/lit-view/recursive-with-params';
storiesOf('lit-view', module)
.add('basic', () => {
ViewTemplates.byName('basic')
.when
.valueMatches(v => v.type === 'Person')
.renders(v => html`Hello, my name is ${v.fullName}`);
const value = {
type: 'Person',
fullName: 'Louis Litt',
};
return basic(html`<lit-view .value="${defaultValue(object, value)}"
template-registry="basic"></lit-view>`);
});
storiesOf('lit-view/nesting', module)
.add('using callback', () => {
ViewTemplates.byName('recursive')
.when
.valueMatches(value => value.type === 'Person')
.renders((person, render) =>
html`Hello, my name is ${person.fullName}.
I was born ${render(person.birthDate)}`);
ViewTemplates.byName('recursive').when
.valueMatches(value => value instanceof Date || Date.parse(value))
.renders(date => html`${moment(date).fromNow()}`);
const value = {
type: 'Person',
fullName: 'Louis Litt',
birthDate: new Date(1976, 8, 12),
};
return recursive(html`<lit-view .value="${defaultValue(object, value)}"
template-registry="recursive"></lit-view>`);
});
storiesOf('lit-view/nesting', module)
.add('using view element', () => {
ViewTemplates.byName('nested')
.when
.valueMatches(value => value.type === 'Person')
.renders(person =>
html`Hello, my name is ${person.fullName}.
I was born
<lit-view .value="${person.birthDate}"
template-registry="nested"></lit-view>`);
ViewTemplates.byName('nested').when
.valueMatches(value => value instanceof Date || Date.parse(value))
.renders(date => html`${moment(date).fromNow()}`);
const value = {
type: 'Person',
fullName: 'Louis Litt',
birthDate: new Date(1976, 8, 12),
};
return recursiveElements(html`<lit-view .value="${defaultValue(object, value)}"
template-registry="nested"></lit-view>`);
});
storiesOf('lit-view/nesting', module)
.add('passing context params', () => {
ViewTemplates.byName('recursive-with-params')
.when
.valueMatches(value => value.type === 'Person')
.renders((person, render) => {
const params = {
format: text('Date format', 'LL'),
};
return html`Hello, my name is ${person.fullName}.
I was born on ${render(person.birthDate, params)}`;
});
ViewTemplates.byName('recursive-with-params').when
.valueMatches(value => value instanceof Date || Date.parse(value))
.renders((date, next, scope, params) => html`${moment(date).format(params.format)}`);
const value = {
type: 'Person',
fullName: 'Louis Litt',
birthDate: new Date(1976, 8, 12),
};
return recursiveWithParams(html`<lit-view .value="${defaultValue(object, value)}"
template-registry="recursive-with-params"></lit-view>`);
});
|
/*
* Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
define(function (require, exports, module) {
"use strict";
var Immutable = require("immutable");
/**
* @constructor
* @param {object} model
*/
var HistoryState = Immutable.Record({
/**
* @type {Document}
*/
document: null,
/**
* @type {DocumentExports}
*/
documentExports: null,
/**
* @type {string}
*/
name: null,
/**
* @type {number}
*/
id: null,
/**
* @type {boolean}
*/
rogue: false
});
/**
* Return true if either a document or documentExports is provided,
* and it is not equal to its associated property on this object
*
* @param {Document} document
* @param {DocumentExports} documentExports
* @return {boolean}
*/
HistoryState.prototype.isInconsistent = function (document, documentExports) {
return (this.document && this.document !== document) ||
(this.documentExports && this.documentExports !== documentExports);
};
module.exports = HistoryState;
});
|
// Wait till the browser is ready to render the game (avoids glitches)
window.requestAnimationFrame(function () {
new GameManager(4, KeyboardInputManager, HTMLActuator, LocalStorageManager);
});
|
#!/usr/bin/env node
/* eslint-disable */
const pkg = require('../package.json')
console.log(pkg.version)
process.exit()
|
webpackJsonp([60335399758886],{87:function(t,a){t.exports={data:{site:{siteMetadata:{title:"Barricade Records"}}},layoutContext:{}}}});
//# sourceMappingURL=path----ae8e548c4bb56394be0b.js.map
|
export {default} from './Button';
export {default as Button, buttonFactory} from './Button';
|
version https://git-lfs.github.com/spec/v1
oid sha256:73320a5fc05e6688b53e1b947564a252791cd3276ffaf049b3d44cab8df45a98
size 366
|
version https://git-lfs.github.com/spec/v1
oid sha256:2f5d9bf5f89960a25c3091c26915d16a709d4a24499fb76626d92231faa42fef
size 1918
|
import {Schema} from "prosemirror-model"
// ::Schema Document schema for the data model used by CommonMark.
export const schema = new Schema({
nodes: {
doc: {
content: "block+"
},
paragraph: {
content: "inline*",
group: "block",
parseDOM: [{tag: "p"}],
toDOM() { return ["p", 0] }
},
blockquote: {
content: "block+",
group: "block",
parseDOM: [{tag: "blockquote"}],
toDOM() { return ["blockquote", 0] }
},
horizontal_rule: {
group: "block",
parseDOM: [{tag: "hr"}],
toDOM() { return ["div", ["hr"]] }
},
heading: {
attrs: {level: {default: 1}},
content: "(text | image)*",
group: "block",
defining: true,
parseDOM: [{tag: "h1", attrs: {level: 1}},
{tag: "h2", attrs: {level: 2}},
{tag: "h3", attrs: {level: 3}},
{tag: "h4", attrs: {level: 4}},
{tag: "h5", attrs: {level: 5}},
{tag: "h6", attrs: {level: 6}}],
toDOM(node) { return ["h" + node.attrs.level, 0] }
},
code_block: {
content: "text*",
group: "block",
code: true,
defining: true,
marks: "",
attrs: {params: {default: ""}},
parseDOM: [{tag: "pre", preserveWhitespace: "full", getAttrs: node => (
{params: node.getAttribute("data-params") || ""}
)}],
toDOM(node) { return ["pre", node.attrs.params ? {"data-params": node.attrs.params} : {}, ["code", 0]] }
},
ordered_list: {
content: "list_item+",
group: "block",
attrs: {order: {default: 1}, tight: {default: false}},
parseDOM: [{tag: "ol", getAttrs(dom) {
return {order: dom.hasAttribute("start") ? +dom.getAttribute("start") : 1,
tight: dom.hasAttribute("data-tight")}
}}],
toDOM(node) {
return ["ol", {start: node.attrs.order == 1 ? null : node.attrs.order,
"data-tight": node.attrs.tight ? "true" : null}, 0]
}
},
bullet_list: {
content: "list_item+",
group: "block",
attrs: {tight: {default: false}},
parseDOM: [{tag: "ul", getAttrs: dom => ({tight: dom.hasAttribute("data-tight")})}],
toDOM(node) { return ["ul", {"data-tight": node.attrs.tight ? "true" : null}, 0] }
},
list_item: {
content: "paragraph block*",
defining: true,
parseDOM: [{tag: "li"}],
toDOM() { return ["li", 0] }
},
text: {
group: "inline"
},
image: {
inline: true,
attrs: {
src: {},
alt: {default: null},
title: {default: null}
},
group: "inline",
draggable: true,
parseDOM: [{tag: "img[src]", getAttrs(dom) {
return {
src: dom.getAttribute("src"),
title: dom.getAttribute("title"),
alt: dom.getAttribute("alt")
}
}}],
toDOM(node) { return ["img", node.attrs] }
},
hard_break: {
inline: true,
group: "inline",
selectable: false,
parseDOM: [{tag: "br"}],
toDOM() { return ["br"] }
}
},
marks: {
em: {
parseDOM: [{tag: "i"}, {tag: "em"},
{style: "font-style", getAttrs: value => value == "italic" && null}],
toDOM() { return ["em"] }
},
strong: {
parseDOM: [{tag: "b"}, {tag: "strong"},
{style: "font-weight", getAttrs: value => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null}],
toDOM() { return ["strong"] }
},
link: {
attrs: {
href: {},
title: {default: null}
},
inclusive: false,
parseDOM: [{tag: "a[href]", getAttrs(dom) {
return {href: dom.getAttribute("href"), title: dom.getAttribute("title")}
}}],
toDOM(node) { return ["a", node.attrs] }
},
code: {
parseDOM: [{tag: "code"}],
toDOM() { return ["code"] }
}
}
})
|
/*-------------------------------------
EASY WAYPOINT FUNCTIONS
-------------------------------------*/
// Creates a standerd waypoint with the option of custom logic. To pass in
// the custom logic, just create a function with all the logic you would
// like to call when the waypoint is activated, then pass just the name of the
// function into this function without qoutes. Note that these waypoint functions are
// available to any js file in this project
// Example Single Waypoint: createWaypoint('.that', 'is-active', '35%', animateThat)
function createWaypoint(element, classToToggle, offset, cb) {
return jQuery(element).waypoint(function(direction) {
jQuery(element).toggleClass(classToToggle);
if (typeof cb !== "undefined") {
cb(element, classToToggle, offset, direction);
}
}, { offset: offset });
}
// A loop for standerd waypoint creation. Also has the ability to pass in custom
// logic, and classToToggle. Both are optional.
// Example Multiple Waypoints: waypointer(['.that', '#that', '#this'], 'resolved', '10%', animate);
function waypointer(elementArray, classToToggle, offset, cb) {
for (var i=0; i < elementArray.length; i++) {
createWaypoint(elementArray[i], classToToggle, offset, cb);
}
return true;
}
// This will be invoked when the page loads
;(function($){
$(function() {
// place waypoints here
});
}(jQuery));
|
version https://git-lfs.github.com/spec/v1
oid sha256:6b3e4decf59fdb2e9c8a552b36cea9986e875fb957b248276bd04888917730ff
size 5429
|
var React = require('react');
var MainSection = require('./components/MainSection.component');
React.render(<MainSection />, document.getElementById('container'));
|
var classktt_1_1_parameter_pair =
[
[ "ParameterPair", "classktt_1_1_parameter_pair.html#aa1a0cc60c3c77a523d2a82533e1cba5e", null ],
[ "ParameterPair", "classktt_1_1_parameter_pair.html#ad5ec1fe348f5084be1bb93a72e36300c", null ],
[ "ParameterPair", "classktt_1_1_parameter_pair.html#a0542a9454902488e990906cc276197ef", null ],
[ "getName", "classktt_1_1_parameter_pair.html#a330e6a703f523d4d8654b0baf9f55542", null ],
[ "getValue", "classktt_1_1_parameter_pair.html#a3a84a10729e19dd2158abd219c49e165", null ],
[ "getValueDouble", "classktt_1_1_parameter_pair.html#a196698403542667a5754e3a0f2428609", null ],
[ "hasValueDouble", "classktt_1_1_parameter_pair.html#a0222cbe77642692479552ac73391be3a", null ],
[ "setValue", "classktt_1_1_parameter_pair.html#a5cc19f299e2409aa3bc584d7c195ff47", null ]
];
|
'@fixture Test fixture';
'@page http://my.page.url';
function ultraSuperHelperFunc() {
return 'nothing';
}
'@test'['My first test'] = {
'1.Do smthg cool' : function () {
var foo = 'bar',
baz = 0;
for (var i = 0; i < 50; i++)
baz++;
act.click(foo);
},
'2.Stop here' : function () {
act.wait(500);
},
'3.Not a mixin' : '@mixin Undefined yeah'
};
var someUselessVar = 'blahblahblah';
'@test'['I want more tests!'] = {
'1.Here we go' : function () {
while (true) {
var a = 3 + 2;
console.log('This is infinite loop lol');
}
},
"2.I'm really tired creating stupid names for test steps" : function () {
callSomeUselessFunc();
act.drag();
},
'3.This is a final step' : function () {
finish();
}
};
alert('Hi there!');
|
// ==============================
// MANUFACTURER (DIRECTOR)
// ==============================
export default class Manufacturer {
static manufacture(builder) {
builder.motherboard = "Asus Z170-A ATX LGA1151";
builder.cpu = "Intel Core i7 6950X";
builder.ram = "HyperX Fury 8 GB";
builder.ssd = "SanDisk SSD PLUS 240 GB";
builder.nic = "D-Link DGE-528T";
builder.powerSupply = "Corsair RM750x";
builder.caseDesign = "Cooler Master HAF X";
return builder.assemblePC();
}
}
|
"use strict";
const mongoose = require('mongoose');
module.exports = function (application, done) {
application.db = mongoose.connection;
application.models = require('./common/models')(application);
application.db.on('error', function (err) {
application.log.error(err);
});
application.db.on('connected', function() {
application.log.info('MongoDB connected!');
});
application.db.once('open', function() {
application.log.info('MongoDB connection opened!');
});
application.db.on('reconnected', function () {
application.log.info('MongoDB reconnected!');
});
application.db.on('disconnected', function() {
application.log.info('MongoDB disconnected!');
});
mongoose.connect(application.config.mongo.uri, application.config.mongo.options, function(err) {
if(err) {
application.log.error(err);
}
done();
});
};
// Close the Mongoose connection, when receiving SIGINT
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Force to close the MongoDB conection');
process.exit(0);
});
});
|
(function() {
var Post, create, edit;
Post = function() {
this.title = "";
this.content = "";
this.author = "";
this.categories = [];
this.tags = [];
this.date = "";
this.modified = "";
return this.published = true;
};
create = function(title, content, categories, tags, published) {
var post;
post = new Post();
post.title = title;
post.content = content;
post.categories = categories;
post.tags = tags;
post.published = published;
post.date = Date.now();
return post;
};
edit = function(title, content, categories, tags, published) {
var modified, post;
post = new Post();
title = title;
content = content;
categories = categories;
tags = tags;
published = published;
modified = Date.now();
return post;
};
exports.create = create;
exports.edit = edit;
}).call(this);
|
describe('Loading Nuora', function () {
//using nuora as a module
var colors = require('colors'),
Nuora = require('../'),
nuora,
zuora,
tests;
it('has opts property', function () {
expect(Nuora).to.have.property('opts');
});
Nuora.opts.option('--reporter [value]', '');
Nuora.opts.option('-r [value]', '');
it('builds Nuora', function () {
nuora = Nuora.build();
zuora = nuora.zuora;
describe('Nuora build', function () {
it('has zuora property', function () {
expect(nuora).to.have.property('zuora');
});
it('has zuora.soap property', function () {
expect(zuora).to.have.property('soap');
});
});
tests = function () {
describe('Perform a query', function () {
this.timeout(10000);
it('should return an array of no more than two elements', function (done) {
var sql = "select id from account limit 1",
i = 0,
callback = function (err, data) {
describe('Query ResultObject', function () {
it('should have property id', function () {
assert(data.result.records.hasOwnProperty('Id'));
});
});
done(err);
};
zuora.query(sql, callback, true);
});
});
};
});
describe('Logging in', function () {
it('connected to the server', function (done) {
zuora.on('loggedin', function () {
done();
tests();
});
});
});
});
|
/*
* Node-side Configuration
*/
OVERRIDE(NODE_CONFIG, (origin) => {
global.NODE_CONFIG = COMBINE([{
isSingleCoreMode : false,
// maxUploadFileMB
// isNotToModelInitialize
// 룸 서버를 사용하지 않을지 여부 설정
isNotUsingRoomServer : false
}, origin]);
});
|
"use strict";
//
// Debugging
//
// Declare DEBUG constant, but be sure we aren't in production
var DEBUG = Browser.inProduction() ? false : true;
// Disable logging if in production
if (!DEBUG) {
window.console = {};
window.console.log = function(){};
window.console.info = function(){};
window.console.warn = function(){};
window.console.error = function(){};
}
//
// Shorthand to localStorage, used everywhere, as essential here as jQuery
//
var ls = localStorage;
//
// All other constants
//
// API server
var API_SERVER = 'https://passoa.online.ntnu.no/api/';
// Loops & intervals
var BACKGROUND_LOOP = 60000; // 60s
var BACKGROUND_LOOP_DEBUG = 5000; // 5s, respond fairly quickly for us developers
var PAGE_LOOP = 10000; // 10s
var PAGE_LOOP_DEBUG = 5000; // 5s
var ONLINE_MESSAGE = '\nNow online, run mainloop\n';
var OFFLINE_MESSAGE = '\nNow offline, stop execution\n';
// Update stuff at every X intervals
var UPDATE_AFFILIATION_INTERVAL = 1; // recommended: 1
var UPDATE_CANTINAS_INTERVAL = 60; // recommended: 60
var UPDATE_BUS_INTERVAL = 2; // recommended: 1
var UPDATE_NEWS_INTERVAL = 20; // recommended: 20
// Hard totals
// It's this, or doing synchronous XMLHttpRequests, which have been deprecated in Chrome now, so.. yeah.
var MEME_AMOUNT = 31;
|
'use strict';
/**
* @ngdoc overview
* @name gabineteApp
* @description
* # gabineteApp
*
* Main module of the application.
*/
angular
.module('gabineteApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'slugifier'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/integrantes.html',
controller: 'IntegrantesCtrl',
controllerAs: 'main'
})
.when('/integrantes/:persona', {
templateUrl: 'views/integrantes.html',
controller: 'IntegrantesCtrl',
controllerAs: 'main'
})
.otherwise({
redirectTo: '/'
});
})
.service('TabletopService', function ($q,Slug) {
this.keys = false;
this.data = false;
this.loading = false;
this.getData = function(){
var that = this;
return $q(function(resolve, reject) {
if(!that.data){
// if(!that.loading){
that.loading = true;
d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vSZG-bnXn217ELlkVTAuNZDdmtdPTdsbJ6CGYxAXyFEz24Uk503mOeMtr2dEVUNlg2OowwWpCOKGgIr/pub?gid=1766965020&single=true&output=csv")
.then(function(indexData) {
var fileList = [];
that.keys = {}
that.data = {}
indexData.forEach(function(row){
fileList.push(
d3.csv("https://docs.google.com/spreadsheets/d/e/2PACX-1vSZG-bnXn217ELlkVTAuNZDdmtdPTdsbJ6CGYxAXyFEz24Uk503mOeMtr2dEVUNlg2OowwWpCOKGgIr/pub?single=true&output=csv&gid="+row.id_hoja)
.then(function(data) {return data})
)
that.keys[Slug.slugify(row.grupo)] = row.grupo;
})
Promise.all(fileList).then(function(responses) {
indexData.map(function(row,ix) {
that.data[row.grupo] = {elements: responses[ix]};
})
that.loading = false;
resolve({ data: that.data, keys: that.keys });
})
return indexData;
});
// }
} else {
resolve({data:that.data,keys:that.keys});
}
});
};
});
|
import * as evaluator from './evaluator.js';
import * as environment from './environment.js';
function parseExpression(program) {
program = skipSpace(program);
var match, expr;
if (match = /^"([^"]*)"/.exec(program)) {
expr = {type: "value", value: match[1]};
}
else if (match = /^\d+\b/.exec(program)) {
expr = {type: "value", value: Number(match[0])};
}
else if (match = /^[^\s(),"]+/.exec(program)) {
expr = {type: "word", name: match[0]};
}
else {
throw new SyntaxError("Unexpected syntax: " + program)
}
return parseApply(expr, program.slice(match[0].length));
}
function skipSpace(string) {
var first = string.search(/\S/);
if (first == -1) {
return "";
}
return string.slice(first);
}
function parseApply(expr, program) {
program = skipSpace(program);
if (program[0] != "(") {
return {expr: expr, rest: program};
}
program = skipSpace(program.slice(1));
expr = {type: "apply", operator: expr, args: []};
while (program[0] != ")") {
var arg = parseExpression(program);
expr.args.push(arg.expr);
program = skipSpace(arg.rest);
if (program[0] == ",") {
program = skipSpace(program.slice(1));
}
else if (program[0] != ")") {
throw new SyntaxError("Expected ',' or ')'");
}
}
return parseApply(expr, program.slice(1));
}
function parse(program) {
var result = parseExpression(program);
if (skipSpace(result.rest).length > 0) {
throw new SyntaxError("Unexpected text after program");
}
return result.expr;
}
|
const NON_WORD_REGEXP = /[^A-Za-z0-9]/g
export const DEFAULT_RANGES = ['0-9', 'A-B', 'C-D', 'E-F', 'G-H', 'I-J', 'K-L', 'M-N', 'O-P', 'Q-R', 'S-T', 'U-V', 'W-X', 'Y-Z']
export function groupBrandsByRanges (brands, ranges = DEFAULT_RANGES) {
let rangeBrandsHash = {}
for (let brand of brands) {
addBrandToRangedBrandHash(rangeBrandsHash, brand, ranges)
}
return rangeBrandsHash
}
export function addBrandToRangedBrandHash (rangeBrandsHash, brand, ranges = DEFAULT_RANGES) {
const range = getBrandRange(brand.brand_copy[0].brand_name, ranges)
if (!range) { return }
if (!rangeBrandsHash[range]) { rangeBrandsHash[range] = [] }
brandFastInsert(rangeBrandsHash[range], brand)
}
export function normalizeString (s) {
return s.replace(NON_WORD_REGEXP, '').toLowerCase()
}
export function stringsAreInDescendingOrder (s1, s2, equality = false) {
if (equality) { return normalizeString(s1) >= normalizeString(s2) }
return normalizeString(s1) > normalizeString(s2)
}
export function stringsAreInAscendingOrder (s1, s2, equality = false) {
if (equality) { return normalizeString(s1) <= normalizeString(s2) }
return normalizeString(s1) < normalizeString(s2)
}
function getBrandRange (brandName, ranges = DEFAULT_RANGES) {
const normalizedName = normalizeString(brandName)
if (normalizedName.length === 0) { return undefined }
const zeroChar = normalizedName.charAt(0).toUpperCase()
for (let range of ranges) {
const left = range.charAt(0)
const right = range.charAt(2)
if (zeroChar >= left && zeroChar <= right) {
return range
}
}
return undefined
}
// here i'm using binary insertion algorithm with slight modification
// http://machinesaredigging.com/2014/04/27/binary-insert-how-to-keep-an-array-sorted-as-you-insert-data-in-it/
function brandFastInsert (brands, brand, left, right) {
const length = brands.length
const l = typeof (left) !== 'undefined' ? left : 0
const r = typeof (right) !== 'undefined' ? right : length - 1
const m = (l + r) >> 1
const brandName = brand.brand_copy[0].brand_name
if (brands.length === 0) {
brands.push(brand)
return
}
if (stringsAreInDescendingOrder(brandName, brands[r].brand_copy[0].brand_name, true)) {
brands.splice(r + 1, 0, brand)
return
}
if (stringsAreInAscendingOrder(brandName, brands[l].brand_copy[0].brand_name, true)) {
brands.splice(l, 0, brand)
return
}
if (l >= r) { return }
if (stringsAreInAscendingOrder(brandName, brands[m].brand_copy[0].brand_name, true)) {
brandFastInsert(brands, brand, l, m - 1)
return
}
if (stringsAreInDescendingOrder(brandName, brands[m].brand_copy[0].brand_name, true)) {
brandFastInsert(brands, brand, m + 1, r)
return
}
}
|
import cheerio from 'cheerio'
import { join } from 'path'
import {
findPort,
launchApp,
killApp,
nextStart,
nextBuild,
renderViaHTTP,
File,
} from 'next-test-utils'
jest.setTimeout(1000 * 60 * 5)
let app
let appPort
const appDir = join(__dirname, '..')
const nextConfig = new File(join(appDir, 'next.config.js'))
const runTests = () => {
it('should have gip in __NEXT_DATA__', async () => {
const html = await renderViaHTTP(appPort, '/')
const $ = cheerio.load(html)
expect(JSON.parse($('#__NEXT_DATA__').text()).gip).toBe(true)
})
it('should not have gip in __NEXT_DATA__ for non-GIP page', async () => {
const html = await renderViaHTTP(appPort, '/normal')
const $ = cheerio.load(html)
expect('gip' in JSON.parse($('#__NEXT_DATA__').text())).toBe(false)
})
it('should have correct router.asPath for direct visit dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/blog/1')
const $ = cheerio.load(html)
expect($('#as-path').text()).toBe('/blog/1')
})
it('should have correct router.asPath for direct visit dynamic page rewrite direct', async () => {
const html = await renderViaHTTP(appPort, '/blog/post/1')
const $ = cheerio.load(html)
expect($('#as-path').text()).toBe('/blog/post/1')
})
}
describe('getInitialProps', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('serverless mode', () => {
beforeAll(async () => {
await nextConfig.replace('// replace me', `target: 'serverless', `)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
nextConfig.restore()
})
runTests()
})
describe('production mode', () => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ServerOptions_1 = require("./ServerOptions");
const Http = require("http");
const Https = require("https");
const express = require("express");
const debug = require("debug");
const compression = require("compression");
const path = require("path");
const datefmt = require("dateformat");
const favicon = require("serve-favicon");
const fs = require("fs");
const cluster = require("cluster");
const process = require("process");
const os = require("os");
const cors = require("cors");
const logError = debug('saco:error');
const logInfo = debug('saco:info');
var ClusterMessage;
(function (ClusterMessage) {
ClusterMessage[ClusterMessage["WORKER_LISTENING"] = 0] = "WORKER_LISTENING";
})(ClusterMessage || (ClusterMessage = {}));
class Server {
constructor(options) {
this.startedWorkersCount = 0;
this.app = express();
this.options = Object.assign({}, ServerOptions_1.DEFAULT_OPTIONS, options);
this.options.workers = Math.min(Math.max(this.options.workers, 1), os.cpus().length);
this.appConfigure();
}
isHttps() {
return this.options.key != null && this.options.cert != null;
}
setMaxSockets() {
if (this.isHttps()) {
Https.globalAgent.maxSockets = Infinity;
logInfo('Https max sockets set to %O', Https.globalAgent.maxSockets);
}
else {
Http.globalAgent.maxSockets = Infinity;
logInfo('Http max sockets set to %O', Http.globalAgent.maxSockets);
}
}
appConfigure() {
this.app.disable('x-powered-by');
if (this.options.cors) {
this.app.use(cors());
}
this.app.use(compression());
if (this.options.behindProxy) {
this.app.enable('trust proxy');
}
if (this.options.verbose) {
this.app.use((req, res, next) => {
logInfo(this.options.name, datefmt(new Date(), this.options.dateformat), 'pid:', process.pid, 'ip:', req.ip, '\t', req.method, '\t', req.url);
next();
});
}
this.app.use(this.options.assets.url, express.static(path.join(this.options.rootPath, this.options.assets.path), { maxAge: this.options.maxAge }));
this.app.get(this.options.index.url, (req, res) => {
res.setHeader('Cache-Control', `public, max-age=${this.options.maxAge}`);
res.sendFile(path.join(this.options.rootPath, this.options.index.path));
});
this.app.use((err, req, res, next) => {
logError(datefmt(new Date(), this.options.dateformat), '\t:', req.method, req.url);
logError(err.stack);
res.status(500).send('Something broke!');
});
if (this.options.favicon != null) {
this.app.use(this.options.favicon.url, favicon(path.join(this.options.rootPath, this.options.favicon.path)));
}
}
createServer() {
if (this.isHttps()) {
logInfo('Starting https server on worker %O...', process.pid);
let httpsOptions = {
key: fs.readFileSync(this.options.key),
cert: fs.readFileSync(this.options.cert)
};
return Https.createServer(httpsOptions, this.app);
}
else {
logInfo('Starting http server on worker %O...', process.pid);
return Http.createServer(this.app);
}
}
startMaster() {
var self = this;
return new Promise((resolve, reject) => {
for (let i = 0; i < self.options.workers; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
logInfo(`Worker %O died`, worker.process.pid);
self.startedWorkersCount--;
if (self.startedWorkersCount === 0) {
logInfo('Bye');
}
});
cluster.on('message', (worker, data) => {
logInfo('Process %O listening on port %O', data.pid, self.options.port);
self.startedWorkersCount++;
if (self.startedWorkersCount === self.options.workers) {
logInfo('Server ready');
resolve(self.startedWorkersCount);
}
});
cluster.on('online', worker => {
logInfo('Process %O just went online', worker.process.pid);
});
});
}
sendMaster(pid, msg) {
process.send({ pid, msg });
}
startWorker() {
var self = this;
return new Promise((resolve, reject) => {
self.server = self.createServer();
self.server
.listen(self.options.port, self.options.ip, () => {
self.sendMaster(process.pid, ClusterMessage.WORKER_LISTENING);
resolve();
})
.on('error', () => {
logError('Failed to start the server on port %O', self.options.port);
reject();
});
});
}
// returnes a promise that resolves only after all workers
// have sent ClusterMessage.WORKER_LISTENING to the master
start() {
var self = this;
return new Promise((resolve, reject) => {
if (cluster.isMaster) {
logInfo(`Starting %O master %O...`, this.options.name, process.pid);
logInfo('Options: %O', self.options);
self.setMaxSockets();
resolve(self.startMaster());
}
else {
logInfo(`Starting %O worker %O...`, this.options.name, process.pid);
self.startWorker();
}
});
}
// returnes a promise that resolves only after all
// workers have send 'exit' event to the master
stop() {
return new Promise((resolve, reject) => {
cluster.disconnect(() => {
resolve();
});
});
}
}
exports.Server = Server;
//# sourceMappingURL=Server.js.map
|
$(function () {
var root = this,
viewers = root.viewers || {},
WDZV = (viewers.WDZV = {});
root.viewers = viewers;
var canvas = document.getElementById("map-wdz"),
context = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 512;
var N = Scl.N, M = Scl.M;
WDZV.paint = function (data) {
context.clearRect(0, 0, 640, 512);
for (var i = 0; i < N; i++) {
for (var j = 0; j <= M; j++) {
var measure = data.map[i][j],
wdz = measure[8],
fill = "#000000";
if (wdz > 100 || wdz < -100) {
fill = "#ffffff";
} else {
var hight = 100 + wdz;
var low = wdz;
hight = Math.floor(hight / 200.0 * 255).toString(16);
low = Math.floor(low / 200.0 * 255).toString(16);
fill = "rgb(" + hight + ", 88, " + low + ")";
}
context.fillStyle = fill;
context.fillRect(5 * i, 4 * j, 5, 4);
if (i === 0 && j === 50) {
$("#wdz1").html(wdz);
}
if (i === 150 && j === 50) {
$("#wdz2").html(wdz);
}
}
}
};
});
|
import React, { PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Editor from '../Editor';
import TodoItem from '../TodoItem';
import { getTodos } from '../../actions';
class TodoList extends React.Component {
render() {
const rows = this.props.todos.map((item, index) =>
<TodoItem key={index} index={index} item={item} />);
if (this.props.adding) {
rows.push(<Editor key={-1} />);
}
return (
<table className="table">
<tbody>
{rows}
</tbody>
</table>
);
}
}
TodoList.propTypes = {
todos: React.PropTypes.arrayOf(React.PropTypes.object),
adding: PropTypes.bool,
getTodos: PropTypes.func,
};
const mapStateToProps = state => ({
todos: state.todos,
adding: state.adding,
});
const mapDispatchToProps = dispatch => ({
getTodos: bindActionCreators(getTodos, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
|
/* global hexo */
'use strict';
const renderer = require('./lib/renderer');
hexo.extend.renderer.register('swig', 'html', renderer, true);
|
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize underscore exports="amd" -o ./underscore/`
* Copyright 2012-2014 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.6.0 <http://underscorejs.org/LICENSE>
* Copyright 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
define(['../internals/createAggregator'], function(createAggregator) {
/** Used for native method references */
var objectProto = Object.prototype;
/** Native method shortcuts */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` through the callback. The corresponding value
* of each key is the number of times the key was returned by the callback.
* The callback is bound to `thisArg` and invoked with three arguments;
* (value, index|key, collection).
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Collections
* @param {Array|Object|string} collection The collection to iterate over.
* @param {Function|Object|string} [callback=identity] The function called
* per iteration. If a property name or object is provided it will be used
* to create a "_.pluck" or "_.where" style callback respectively.
* @param {*} [thisArg] The `this` binding of `callback`.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); });
* // => { '4': 1, '6': 2 }
*
* _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math);
* // => { '4': 1, '6': 2 }
*
* _.countBy(['one', 'two', 'three'], 'length');
* // => { '3': 2, '5': 1 }
*/
var countBy = createAggregator(function(result, value, key) {
(hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1);
});
return countBy;
});
|
{
"name": "43places",
"domain": "43places.com",
"urlMappings": [{
"urlTemplate": "http://www.43places.com/person/{username}",
"schema": "None",
"contentType": "Profile",
"mediaType": "Html"
}],
"www": true
}
|
'use strict';
angular.module('studyApp')
.service('User', function User() {
// AngularJS will instantiate a singleton by calling "new" on this function
});
|
'use strict';
var requireHelper = require(process.env.TEST_DIR + '/require_helper');
var Game = requireHelper('models/game');
var expect = require('chai').expect;
describe('Game', function() {
describe('contructor', function() {
var game1 = new Game();
it('should create a new Game with ID equals 1', function() {
expect(game1.id).to.equals(1);
});
it('should create a new Game with a specific grid', function() {
expect(game1.grid).to.have.length(5);
expect(game1.grid[0]).to.have.length(5);
expect(game1.grid[0][0]).to.equals('B');
});
it('shoud create the next Game with a different ID', function() {
var game2 = new Game();
expect(game2.id).to.not.equals(game1.id);
});
});
});
|
'use strict';
angular
.module('app.module')
.factory('exception', exception);
exception.$inject = ['logger'];
function exception(logger) {
var service = {
catcher: catcher
};
return service;
function catcher(message) {
return function(reason) {
logger.error(message, reason);
};
}
}
/*
angular //TODO: get back to this
.module('blocks.exception')
.config(exceptionConfig);
exceptionConfig.$inject = ['$provide'];
function exceptionConfig($provide) {
$provide.decorator('$exceptionHandler', extendExceptionHandler);
}
extendExceptionHandler.$inject = ['$delegate'];
function extendExceptionHandler($delegate) {
return function(exception, cause) {
$delegate(exception, cause);
var errorData = {
exception: exception,
cause: cause
};
//toastr.error(exception.msg, errorData);
console.error("ExceptionDecoService: " +exception.msg +" " +errorData)
};
}
*/
|
/**
* Write text.
*
* Any number of columns. Everything is displayed as text.
*
* @class sgvizler.visualization.Generic
* @extends sgvizler.charts.Chart
* @constructor
* @param {Object} container The container element where the
* chart will be drawn.
* @since 0.6.1
**/
/**
* Available options:
*
* In `NoX` `X` should replaced with a number 1 =< X =< no. of columns.
*
* - 'dataFunction' : function applied to every cell value. (default: identify function)
* - 'includeHeaders' : include column headings or not. (default: false)
* - 'headingCellSep' : string to separate cells in each column. (default: '')
* - 'headingCellSepNoX' : string to separate cells in each column. (default: headingCellSep)
* - 'headingCellPrefix' : string to prefix each cell with. (default: '')
* - 'headingCellPostfix' : string to postfix each cell with. (default: '')
* - 'headingCellPrefixNoX' : string to prefix each cell with. (default: headingCellPrefixNoX)
* - 'headingCellPostfixNoX' : string to postfix each cell with. (default: headingCellPostfixNoX)
* - 'headingRowPrefix' : string to prefix each row with. (default: '')
* - 'headingRowPostfix' : string to postfix each row with. (default: '')
* - 'headingRowPrefixNoX' : string to prefix each row with. (default: headingRowPrefixNoX)
* - 'headingRowPostfixNoX' : string to postfix each row with. (default: headingRowPostfixNoX)
* - 'cellSep' : string (can be html) to separate cells in each column. (default: '')
* - 'cellSepNoX' : string (can be html) to separate cells in each column. (default: cellSep)
* - 'cellPrefix' : string (can be html) to prefix each cell with. (default: '')
* - 'cellPostfix' : string (can be html) to postfix each cell with. (default: '')
* - 'cellPrefixNoX' : string (can be html) to prefix each first cell in every row with. (default: cellPrefix)
* - 'cellPostfixNoX' : string (can be html) to postfix each first cell in every row with. (default: cellPostfix)
* - 'rowPrefix' : string (can be html) to prefix each row with. (default: '')
* - 'rowPostfix' : string (can be html) to postfix each row with. (default: '')
* - 'rowPrefixNoX' : string (can be html) to prefix each row with. (default: rowPrefix)
* - 'rowPostfixNoX' : string (can be html) to postfix each row with. (default: rowPostfix)
* - 'resultsPrefix' : string (can be html) to prefix the results with. (default: '')
* - 'resultsPostfix' : string (can be html) to postfix the results with. (default: '')
*
* @method draw
* @public
* @param {google.visualization.DataTable} data
* @param {Object} [chartOptions]
* @since 0.6.1
**/
C.Generic = charts.add(modSC, "Generic",
function (data, chartOptions) {
var text = C.util.genericTextDraw(data, $.extend({}, chartOptions));
$(this.container)
.empty()
.html(text);
this.fireListener('ready');
}
);
|
/**
* Copyright (c) 2014, Oracle and/or its affiliates.
* All rights reserved.
*/
"use strict";var l={"NZL_WELLINGTON":[null,"\u05D5\u05D5\u05DC\u05D9\u05E0\u05D2\u05D8\u05D5\u05DF"],"AUS_CANBERRA":[null,"\u05E7\u05E0\u05D1\u05E8\u05D4"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["australia","cities",l]);
|
const getBaseType = require('./_getBaseType')
/**
*
* @param {Object} value
*/
const isNumber = value => getBaseType('Number')(value)
module.exports = isNumber
|
import React from 'react';
import styled from 'styled-components';
import { Button, Icon, Col, Tag, Typography } from 'antd';
import JSONEditor from './JSONEditor';
import EditorViewer from './EditorViewer';
import variations from './variations';
import { createImageChildren } from './CarouselSlideItem';
import ItemsCarousel from '../../src/ItemsCarousel';
import CenteredRow from './CenteredRow';
import DemoHeader from './DemoHeader';
const Wrapper = styled.div`
`;
const Variations = styled.div`
display: flex;
flex-wrap: wrap;
align-items: center;
height: 40px;
`;
const Variation = styled(Tag.CheckableTag)`
cursor: pointer;
`;
export class ItemsCarouselPlayground extends React.Component {
state = {
activeItemIndex: 0,
activeVariation: variations[0],
};
render() {
const { activeVariation } = this.state;
const {
noOfChildren,
wrapperStyle,
componentProps,
} = activeVariation.state;
const children = createImageChildren(noOfChildren);
return (
<Wrapper>
<DemoHeader
title={'Playground'}
description={'Play around with props to see if this library suits your needs'}
/>
<div style={wrapperStyle}>
<ItemsCarousel
{...componentProps}
activeItemIndex={this.state.activeItemIndex}
requestToChangeActive={value => this.setState({ activeItemIndex: value })}
rightChevron={
<Button shape="circle">
<Icon type="right" />
</Button>
}
leftChevron={
<Button shape="circle">
<Icon type="left" />
</Button>
}
children={children}
/>
</div>
<CenteredRow gutter={12}>
<Col xs={24} md={12}>
<Typography.Title level={3}>Change props here</Typography.Title>
<Variations>
{variations.map((variation, index) => (
<Variation
checked={variation.name === activeVariation.name}
key={index}
onChange={() => this.setState({ activeItemIndex: 0, activeVariation: variation })}
>
{variation.name}
</Variation>
))}
</Variations>
<JSONEditor
json={{
noOfChildren,
wrapperStyle,
componentProps,
}}
onJSONChange={({ noOfChildren, wrapperStyle, componentProps }) => {
this.setState({
activeVariation: {
name: activeVariation.name,
state: {
noOfChildren,
wrapperStyle,
componentProps,
},
},
});
}}
/>
</Col>
<Col xs={24} md={12}>
<Typography.Title level={3}>Usage <Typography.Text type={'secondary'}>(Read-Only)</Typography.Text></Typography.Title>
<Variations />
<EditorViewer
noOfChildren={noOfChildren}
wrapperStyle={wrapperStyle}
componentProps={componentProps}
/>
</Col>
</CenteredRow>
</Wrapper>
);
}
}
export default ItemsCarouselPlayground;
|
(function (){
'use strict';
function <%= ctrlname %> (){
var vm = this;
}
angular.module('<%= appname %>').controller('<%= ctrlname %>', <%= ctrlname %>);
})();
|
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
const ArrowUpCircle = forwardRef(({ color = 'currentColor', size = 24, ...rest }, ref) => {
return (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...rest}
>
<circle cx="12" cy="12" r="10" />
<polyline points="16 12 12 8 8 12" />
<line x1="12" y1="16" x2="12" y2="8" />
</svg>
);
});
ArrowUpCircle.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
ArrowUpCircle.displayName = 'ArrowUpCircle';
export default ArrowUpCircle;
|
(function () {
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var injectdep = require('gulp-inject');
var bowerFiles = require('main-bower-files');
var angularFilesort = require('gulp-angular-filesort');
var order = require('gulp-order');
var argv = require('yargs').argv;
var paths = require('./path.json');
// inject js
gulp.task('inject:js', ['inject:init'], function () {
return gulp.src(paths.indexSrc)
.pipe(injectdep(
gulp.src(paths.js, {
read: true // true it's needed by angularFilesort()
})
.pipe(angularFilesort()), {
ignorePath: paths.ignorePath,
addRootSlash: paths.addRootSlash
}))
.pipe(gulp.dest(paths.dest));
});
// inject css
gulp.task('inject:css', ['inject:js'], function () {
return gulp.src(paths.indexSrc)
.pipe(injectdep(
gulp.src(paths.css, {
read: false
}), {
ignorePath: paths.ignorePath,
addRootSlash: paths.addRootSlash
}))
.pipe(gulp.dest(paths.dest));
});
// inject bower components
gulp.task('inject:bower', ['inject:css'], function () {
return gulp.src(paths.indexSrc)
.pipe(
injectdep(
gulp.src(
bowerFiles(), {
read: false
}
)
.pipe(order(paths.bowerOrder)), {
ignorePath: paths.ignorePath,
addRootSlash: paths.addRootSlash,
starttag: '<!-- bower:{{ext}} -->'
}
)
)
.pipe(
injectdep(
gulp.src(
paths.vendors, {
read: false
}
), {
ignorePath: paths.ignorePath,
addRootSlash: paths.addRootSlash,
starttag: '<!-- vendor:{{ext}} -->'
}
)
)
.pipe(gulp.dest(paths.dest));
});
gulp.task('inject:init', function () {
var fs = require('fs');
var rename = require('gulp-rename');
var gulpNgConfig = require('gulp-ng-config');
var config;
var configString;
var configFile = 'local-config.json';
if (argv.production) {
configFile = 'production-config.json';
}
try {
configString = fs.readFileSync(configFile);
config = JSON.parse(configString);
} catch (err) {
gutil.log('There has been an error parsing your JSON. A default values will be created');
config = {
socketUrl: 'http://192.168.33.10:3000',
restBaseUrl: 'http://192.168.33.10:3000'
};
configString = JSON.stringify(config);
try {
fs.writeFileSync(configFile, configString, 'utf8');
} catch (err) {
console.log('There has been an error saving your configuration data.');
console.log(err.message);
return;
}
}
gulp.src(configFile)
.pipe(gulpNgConfig('xyz.socket.chat.env'))
.pipe(gulp.dest(paths.envFolder));
return gulp.src(paths.template)
.pipe(rename('index.html'))
.pipe(gulp.dest(paths.dest));
});
gulp.task('inject', ['inject:bower']);
})();
|
import React, {Component} from 'react';
import styles from './styles.scss';
class TopMenuProfile extends Component {
render() {
return (
<ul>
<li style={{display: 'inline', verticalAlign: 'middle'}}><img className={styles.profileImage} src="http://image.xboxlive.com/global/t.434f07d2/tile/0/28002" /></li>
<li style={{display: 'inline-block', verticalAlign: 'middle'}}>
<ul style={{listStyle: 'none', paddingLeft: '0.5vw'}}>
<li style={{position: 'relative', top: '0.5vw'}}><b>Yotam</b></li>
<li className={styles.statusOnlineCircle}></li>
<li style={{fontSize: '0.75vw', display: 'inline-block'}}>Online</li>
<li style={{display: 'inline-block', color: '#617009'}}>
<i className="fa fa-angle-down" aria-hidden="true" style={{position: 'relative', top:'0.7vw', fontSize:'1.75vw'}}></i>
</li>
</ul>
</li>
</ul>
);
}
}
export default TopMenuProfile;
|
var redis = require('redis').createClient();
var uuid = require('node-uuid');
var mongoose = require('mongoose');
var request = require('request');
var Alarm = mongoose.model('Alarm');
var timeGen = function (){
var t = new Date;
var m = t.getMinutes(),
h = t.getHours()
return 1111;
}
var running_alarm_step = {};
var running_alarm_step_counter = {};
var playPluginWithId = function (id, attr, stream, cb){
try {
var p = require(process.cwd() + '/plugins/' + id + '/index.js');
p(stream, attr, cb);
} catch (e){
console.log(e);
return stream.status(500).send('FAILERINO');
cb(e);
}
}
module.exports = {
stream: function (req, res, next){
var id = req.params.id;
Alarm.getAlarmByUuid(id, function (err, alarm){
if(err) return res.send(500);
if(!alarm) return res.send(404);
if(running_alarm_step_counter[uuid] == undefined){
console.log('FIRST REQUEST');
running_alarm_step_counter[uuid] = 0;
}
if(running_alarm_step_counter[uuid] % 2 == 0){
running_alarm_step_counter[uuid] += 1;
console.log('IGNORING REQUEST');
return res.send(500);
} else {
if(running_alarm_step && running_alarm_step[uuid] >= 0){
console.log('STEP:' + running_alarm_step[uuid]);
var i = running_alarm_step[uuid];
var to_run = Object.keys(alarm.plugins)[i];
if(!to_run){
console.log('NOMOAR');
delete running_alarm_step[uuid];
return res.send(404);
}
console.log('RUN-STEP', to_run);
var attr = alarm.plugins[to_run] || {};
running_alarm_step[uuid] += 1;
playPluginWithId(to_run, attr, res, function (err){
console.log(err, 'Pluging finished playing');
});
} else if ( alarm.enable && alarm.time ){
console.log('Saying good morning');
running_alarm_step[uuid] = 0;
playPluginWithId('alarm', {text: 'Good morning!', lang: 'en'}, res, function (err){
console.log(err, 'Pluging finished playing');
});
} else {
res.send('NON PLAYERINOS');
}
}
});
},
setup: function (req, res, next){
redis.incr('client_counter', function (err, count){
var id = uuid.v1();
var major = parseInt(count / 65536, 10);
var minor = parseInt(count % 65536);
var stringId = 'id:'+major+'-'+minor;
redis.set(stringId, id);
redis.set('uuid:'+id, major+'-'+minor);
res.send({
minor: minor,
major: major,
client_id: id,
stream_url: '/stream/' + id
});
});
},
shutup: function (req, res, next){
var id = req.params.id;
res.status(200).end();
},
erase: function (req, res, next){
var id = req.params.id;
if(streams && streams[id]){
streams[id].close();
delete streams[id];
}
redis.get('uuid:'+id, function (err, ids){
if(err){
res.status(500).end();
next();
}
if(!ids){
res.status(404).end(); next();
}
redis.del('uuid:'+id);
redis.del('id:'+ids);
res.status(200).end();
next();
});
}
}
|
'use strict';
app.factory('accountService',
function ($http, $q, $location, localStorageService, tsBBSettings) {
var serviceBase = tsBBSettings.apiBaseUri;
var accountServiceFactory = {};
var _authentication = {
token: '',
email: '',
authenticated: false
};
var _users = function () {
var deferred = $q.defer();
$http
.get(serviceBase + 'account/users')
.then(function (response) {
deferred.resolve(response);
})
.catch(function (err) {
deferred.reject(err);
});
return deferred.promise;
};
var _login = function (user) {
var userData = {
email: user.email,
password: user.password
};
var deferred = $q.defer();
$http
.post(serviceBase + 'account/login', userData)
.then(function (response) {
_authentication.token = response.data.token;
_authentication.email = response.data.Email;
_authentication.authenticated = true;
localStorageService.set('userData', _authentication);
deferred.resolve(response);
})
.catch(function (err) {
deferred.reject(err);
});
return deferred.promise;
};
var _register = function (user) {
var userData = {
email: user.email,
password: user.password
};
var deferred = $q.defer();
$http
.post(serviceBase + 'account/register', userData)
.then(function (response) {
deferred.resolve(response);
})
.catch(function (err) {
deferred.reject(err);
});
return deferred.promise;
};
var _logOut = function () {
localStorageService.remove('userData');
_authentication.authenticated = false;
_authentication.token = "";
$location.path('/');
};
var _userData = function () {
var userData = localStorageService.get('userData');
if (userData) {
_authentication.authenticated = userData.authenticated;
}
};
var _authorize = function (accountService) {
if (accountService && accountService.authentication.authenticated === true)
return true;
throw new AuthorizationError("User not authenticated.");
};
accountServiceFactory.users = _users;
accountServiceFactory.login = _login;
accountServiceFactory.register = _register;
accountServiceFactory.logOut = _logOut;
accountServiceFactory.userData = _userData;
accountServiceFactory.authentication = _authentication;
accountServiceFactory.authorize = _authorize;
return accountServiceFactory;
}
);
// Custom error type
function AuthorizationError(description) {
this.forbidden = "Forbidden";
this.message = description || this.forbidden;
this.description = description || this.message;
}
AuthorizationError.prototype = Object.create(Error.prototype);
AuthorizationError.prototype.constructor = AuthorizationError;
|
"use strict"
module.exports = imshow
var consoleImg = require("console-image")
var savePixels = require("save-pixels")
var colorize = require("./do-colorize.js")
function imshow(array, options) {
colorize(array, options, function(img) {
consoleImg(savePixels(img, "canvas"))
})
}
|
search_result['449']=["topic_00000000000000DE.html","StringExtension Class",""];
|
"use strict";
var CleanCss = require("clean-css");
var _cleanCssOptions = {
// 例如 top: 7px; 与 top: 5px\9; 同时存在后者会被优化掉
noAdvanced : true
};
var CssCompressor = {
__name__ : "CssCompressor",
"__proto__" : null,
/**
* @brief 压缩代码
*
* @param {string} code 代码文本
* @param {function} next 回调函数
* @return void
*
* @details 压缩代码文本
*/
compress : function (code, next) {
next(null, new CleanCss(_cleanCssOptions).minify(code));
}
};
module.exports = CssCompressor;
|
import {
FETCH_USER, FETCH_USER_ARTISTS, FETCH_USER_EVENTS, FETCH_ARTIST_EVENTS, HIDE_ARTIST_EVENTS, SHOW_ARTIST_EVENTS,
fetchUser, fetchUserArtists, fetchArtistEvents, hideArtistEvents, showArtistEvents
} from '../../src/actions';
describe('(Actions)', () => {
describe('fetchUser', function() {
it('has the correct type', function() {
expect(fetchUser().type).to.eql(FETCH_USER);
});
});
describe('fetchUserArtists', function() {
it('has the correct type', function() {
expect(fetchUserArtists().type).to.eql(FETCH_USER_ARTISTS);
});
});
describe('fetchArtistEvents', function() {
it('has the correct type', function() {
expect(fetchArtistEvents().type).to.eql(FETCH_ARTIST_EVENTS);
});
});
describe('hideArtistEvents', function() {
it('has the correct type', function() {
expect(hideArtistEvents().type).to.eql(HIDE_ARTIST_EVENTS);
});
});
describe('showArtistEvents', function() {
it('has the correct type', function() {
expect(showArtistEvents().type).to.eql(SHOW_ARTIST_EVENTS);
});
});
});
|
requirejs.config({
paths: {
'jquery': '../lib/jquery/dist/jquery'
}
});
define(['app', 'jquery'], function(App, $) {
var app = new App($('body'));
app.render();
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import Routes from './routes';
import { Provider } from 'react-redux';
import { Store } from './Redux';
import './index.css';
ReactDOM.render(
<Provider store={Store}><Routes /></Provider>,
document.getElementById('root')
);
|
'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/myapp4',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular/angular.min.js',
'public/lib/angular-resource/angular-resource.min.js',
'public/lib/angular-animate/angular-animate.min.js',
'public/lib/angular-ui-router/release/angular-ui-router.min.js',
'public/lib/angular-ui-utils/ui-utils.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js'
]
},
css: 'public/dist/application.min.css',
js: 'public/dist/application.min.js'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'https://localhost:443/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
/**
* Created by nbenes on 11/16/13.
*/
var $window = $(window)
var $body = $(document.body)
var navHeight = $('.navbar').outerHeight(true) + 10
$body.scrollspy({
target: '.crc-sidebar',
offset: navHeight
})
$window.on('load', function () {
$body.scrollspy('refresh')
})
$('.crc-container [href=#]').click(function (e) {
e.preventDefault()
})
// back to top
setTimeout(function () {
var $sideBar = $('.crc-sidebar')
$sideBar.affix({
offset: {
top: function () {
var offsetTop = $sideBar.offset().top
var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10)
var navOuterHeight = $('.crc-nav').height()
return (this.top = offsetTop - navOuterHeight - sideBarMargin)
}
, bottom: function () {
return (this.bottom = $('.crc-footer').outerHeight(true))
}
}
})
}, 100)
setTimeout(function () {
$('.crc-top').affix()
}, 100)
|
/**
* Swiper 6.2.0
* Most modern mobile touch slider and framework with hardware accelerated transitions
* http://swiperjs.com
*
* Copyright 2014-2020 Vladimir Kharlampidi
*
* Released under the MIT License
*
* Released on: September 4, 2020
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var Swiper = _interopDefault(require('./cjs/components/core/core-class'));
var Virtual = _interopDefault(require('./cjs/components/virtual/virtual'));
var Keyboard = _interopDefault(require('./cjs/components/keyboard/keyboard'));
var Mousewheel = _interopDefault(require('./cjs/components/mousewheel/mousewheel'));
var Navigation = _interopDefault(require('./cjs/components/navigation/navigation'));
var Pagination = _interopDefault(require('./cjs/components/pagination/pagination'));
var Scrollbar = _interopDefault(require('./cjs/components/scrollbar/scrollbar'));
var Parallax = _interopDefault(require('./cjs/components/parallax/parallax'));
var Zoom = _interopDefault(require('./cjs/components/zoom/zoom'));
var Lazy = _interopDefault(require('./cjs/components/lazy/lazy'));
var Controller = _interopDefault(require('./cjs/components/controller/controller'));
var A11y = _interopDefault(require('./cjs/components/a11y/a11y'));
var History = _interopDefault(require('./cjs/components/history/history'));
var HashNavigation = _interopDefault(require('./cjs/components/hash-navigation/hash-navigation'));
var Autoplay = _interopDefault(require('./cjs/components/autoplay/autoplay'));
var EffectFade = _interopDefault(require('./cjs/components/effect-fade/effect-fade'));
var EffectCube = _interopDefault(require('./cjs/components/effect-cube/effect-cube'));
var EffectFlip = _interopDefault(require('./cjs/components/effect-flip/effect-flip'));
var EffectCoverflow = _interopDefault(require('./cjs/components/effect-coverflow/effect-coverflow'));
var Thumbs = _interopDefault(require('./cjs/components/thumbs/thumbs'));
// Swiper Class
var components = [Virtual, Keyboard, Mousewheel, Navigation, Pagination, Scrollbar, Parallax, Zoom, Lazy, Controller, A11y, History, HashNavigation, Autoplay, EffectFade, EffectCube, EffectFlip, EffectCoverflow, Thumbs];
Swiper.use(components);
exports.Swiper = Swiper;
exports.default = Swiper;
|
export default function(n) {
return n < 10 ? '0' + n : n;
}
|
describe("clone", function() {
"use strict";
var link;
beforeEach(function() {
jasmine.sandbox.set("<a id='link'><input id='input'></a>");
link = DOM.find("#link");
});
it("allows to clone all clildren", function() {
var clone = link.clone(true),
child = clone.child(0);
jasmine.sandbox.set(clone);
expect(clone).not.toBe(link);
expect(clone).toHaveTag("a");
expect(clone).toHaveId("link");
expect(child).not.toBe(link.child(0));
expect(child).toHaveTag("input");
expect(child).toHaveId("input");
});
it("should allow to do a shallow copy", function() {
var clone = link.clone(false);
expect(clone).not.toBe(link);
expect(clone).toHaveTag("a");
expect(clone).toHaveId("link");
expect(clone.children().length).toBe(0);
});
it("should work on empty elements", function() {
var emptyEl = DOM.find("xxx");
expect(emptyEl.clone(false)).toBeTruthy();
});
it("should throw error if argument is invalud", function() {
expect(function() { link.clone() }).toThrow();
expect(function() { link.clone(1) }).toThrow();
expect(function() { link.clone({}) }).toThrow();
expect(function() { link.clone(function() {}) }).toThrow();
expect(function() { link.clone(null) }).toThrow();
expect(function() { link.clone("abc") }).toThrow();
});
});
|
import React from "react";
import TextWithLineBreaks from "../components/TextWithLineBreaks";
const RecipeNotes = ({ note, updateInput, editing }) => (
<section className="section">
<p className="section__title">Notes supplémentaires :</p>
{editing ? (
<textarea className="add-form-textfield" name="note" value={note} onChange={updateInput} />
) : (
<TextWithLineBreaks className="recipe-notes" text={note} />
)}
</section>
);
export default RecipeNotes;
|
'use strict';
module.exports = function(app, passport, express) {
let homeController = require('../controllers/home-controller')();
let homeRouter = new express.Router();
homeRouter
.get('/', homeController.home)
.post('/api/contact', homeController.sendEmail);
app.use(homeRouter);
};
|
const { STRING, ENUM, TEXT } = require('sequelize')
module.exports = db => db.define('reviews', {
title: {
type: STRING(30),
allowNull: false
},
description: {
type: TEXT,
allowNull: false
},
rating: {
type: ENUM,
values: ['1', '2', '3', '4', '5']
}
}, {
getterMethods: {
shortTitle() {
return this.title.substring(0, 20) + '...'
}
}
})
module.exports.associations = (Review, {Product, User}) => {
Review.belongsTo(User)
Review.belongsTo(Product)
}
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function()
{
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
a=s.createElement(o),m=s.getElementsByTagName(o)[0];
a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
}
)
(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-79766165-2', 'auto');
ga('send', 'pageview');
|
'use strict';
localReadControllers.controller('ConversationCtrl',
function($scope,$ionicScrollDelegate,
UserModel,
ConversationModel,
LocalReadsModelService) {
$scope.conversationModel = ConversationModel;
$scope.conversationModel.sendMessage = function(){
LocalReadsModelService
.sendComment(ConversationModel.activeConversation.id,ConversationModel.activeMessage);
};
$scope.isCurrentUserSnippet = function(snippet){
return snippet.senderUserId == UserModel.user.id;
};
$scope.$watch('conversationModel.activeConversation.snippets.length',function(newValue,oldValue){
if(newValue != oldValue){
$ionicScrollDelegate.$getByHandle('activeConversationContent').scrollBottom(true);
}
});
$scope.$watch('conversationModel.activeConversation',function(newValue,oldValue){
$ionicScrollDelegate.$getByHandle('activeConversationContent').scrollBottom();
});
});
|
// Copyright (c) The LHTML team
// See LICENSE for details.
const {app, BrowserWindow, Menu, protocol, ipcMain} = require('electron');
const log = require('electron-log');
const {autoUpdater} = require("electron-updater");
//-------------------------------------------------------------------
// Logging
//
// THIS SECTION IS NOT REQUIRED
//
// This logging setup is not required for auto-updates to work,
// but it sure makes debugging easier :)
//-------------------------------------------------------------------
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');
//-------------------------------------------------------------------
// Define the menu
//
// THIS SECTION IS NOT REQUIRED
//-------------------------------------------------------------------
let template = []
if (process.platform === 'darwin') {
// OS X
const name = app.getName();
template.unshift({
label: name,
submenu: [
{
label: 'About ' + name,
role: 'about'
},
{
label: 'Quit',
accelerator: 'Command+Q',
click() { app.quit(); }
},
]
})
}
//-------------------------------------------------------------------
// Open a window that displays the version
//
// THIS SECTION IS NOT REQUIRED
//
// This isn't required for auto-updates to work, but it's easier
// for the app to show a window than to have to click "About" to see
// that updates are working.
//-------------------------------------------------------------------
let win;
function sendStatusToWindow(text) {
log.info(text);
win.webContents.send('message', text);
}
function createDefaultWindow() {
win = new BrowserWindow();
// win.webContents.openDevTools();
win.on('closed', () => {
win = null;
});
// win.loadURL(`file://${__dirname}/version.html#v${app.getVersion()}`);
win.loadURL(`file://${__dirname}/index.html#v${app.getVersion()}`);
return win;
}
autoUpdater.on('checking-for-update', () => {
sendStatusToWindow('Checking for update...');
})
autoUpdater.on('update-available', (ev, info) => {
sendStatusToWindow('Update available.');
})
autoUpdater.on('update-not-available', (ev, info) => {
sendStatusToWindow('Update not available.');
})
autoUpdater.on('error', (ev, err) => {
sendStatusToWindow('Error in auto-updater.');
})
autoUpdater.on('download-progress', (progressObj) => {
let log_message = "Download speed: " + progressObj.bytesPerSecond;
log_message = log_message + ' - Downloaded ' + progressObj.percent + '%';
log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')';
sendStatusToWindow(log_message);
})
autoUpdater.on('update-downloaded', (ev, info) => {
sendStatusToWindow('Update downloaded; will install in 5 seconds');
});
app.on('ready', function() {
// Create the Menu
// const menu = Menu.buildFromTemplate(template);
// Menu.setApplicationMenu(menu);
// 7/1/17 JMH call the new menu
require('./menu/mainmenu');
createDefaultWindow();
});
app.on('window-all-closed', () => {
app.quit();
});
//-------------------------------------------------------------------
// Auto updates
//
// For details about these events, see the Wiki:
// https://github.com/electron-userland/electron-builder/wiki/Auto-Update#events
//
// The app doesn't need to listen to any events except `update-downloaded`
//
// Uncomment any of the below events to listen for them. Also,
// look in the previous section to see them being used.
//-------------------------------------------------------------------
// autoUpdater.on('checking-for-update', () => {
// })
// autoUpdater.on('update-available', (ev, info) => {
// })
// autoUpdater.on('update-not-available', (ev, info) => {
// })
// autoUpdater.on('error', (ev, err) => {
// })
// autoUpdater.on('download-progress', (ev, progressObj) => {
// })
autoUpdater.on('update-downloaded', (ev, info) => {
// Wait 5 seconds, then quit and install
// In your application, you don't need to wait 5 seconds.
// You could call autoUpdater.quitAndInstall(); immediately
setTimeout(function() {
autoUpdater.quitAndInstall();
}, 5000)
})
app.on('ready', function() {
autoUpdater.checkForUpdates();
});
|
//Execution function
$('document').ready(function () {
"use strict";
//introduction jeu intro.js
intro();
$('.sound').click(function () {
if (sonOn) {
sonOn = false;
$(this).html('Sound off')
} else {
sonOn = true;
$(this).html('Sound on');
}
});
//declencheur du jeu
$('.launch').click(function () {
//suppression du dom de l'intro
document.getElementById('introSon').pause();
$(this).hide('puff', 1500, function () {
$(this).remove();
launchGame();
});
$('.how-to-play').hide('puff', 1500, function () {
$('.how-to-play').remove();
});
$('#intro').hide(1500, function () {
$('#intro').remove();
});
}) //click
});// end
let launchGame = function () {
//affichage du tableau
$('.misc').show(1500);
//tableau des scores en arriere plan
// $('.container').css('z-index', 1500);
// met le jeu en pause a la perte du focus de la fenetre
// var timeOut;
// $(window).focus(function() {
// alert('Jeu mis en pause, appuyer sur ok pour continuer');
// timeOut = '';
// });
var main = document.getElementById('main');
setInterval(function () {
//lancement du son
if (sonOn & !perso.isDying) {
main.play()
main.loop = true;
main.volume = 0.07;
} //stopper le son
else {
main.pause()
}
}, 400)
// Chargement du terrain
field.creation().animate();
//Chargement des nuages
creationNuage();
//chagement des objets Background
creationBackground();
// crer un nouvel hero à l'aide de la fonction constructeur !
var perso = new ObjetRyu();
// Positionnement générale de ryu!
$('#game').append("<img id='contenu'></div>");
$('#contenu').attr('src', perso.src).wrap($('<div id="container"></div>')).css('position', 'absolute');
//launch frame idle
perso.creation().heroFixed();
/////
// Test des Collisions //
/////
// detecter les collisions du Hero avec les Dinos
perso.testCollision();
// detecter les collisions des balles avec les Dinos
// Affichage de la vie
$('#health').text(perso.energie)
// Affichage du score
$('#score').text(perso.score);
//Affichage de la dynamite
$('#supply').html(perso.supply);
// var Obstacle = [usineObstacle(0), usineObstacle(1), usineObstacle()];
creationObstacle(perso);
/////
//Déplacement //
/////
var container = document.getElementById('container');
var hammer = Hammer(container, {
transform_always_block: true,
tap_always: false,
drag_min_distance: 0
});
hammer.on("tap", (event) => {
actionHammer(event);
});
var actionHammer = (event) => {
switch (event.type) {
case "tap":
persoIsShootingWithSpace(event,perso);
//ObjetBalleEnMouvement(event,perso);
break;
}
};
eventListener(perso);
//chargement du compteur
creationTimer(perso);
}; // launch game
|
var pause = undefined;
var play = undefined;
var audio = undefined;
var tapesound = undefined;
// var staticsound = undefined;
function endstatic()
{
document.body.style.backgroundImage = "none";
document.body.style.backgroundColor = "white";
//staticsound.pause();
}
function startmusic()
{
audio.play();
}
function startstyle()
{
rude.style.display = "none";
curvebox.style.display = "none";
spun.style.display = null;
cover.classList.add("wrapper");
}
function startsound()
{
tapesound.play();
}
function delayedlaw()
{
lawbreaker.style.display = null;
}
function onplay(e)
{
var curvebox = document.getElementById("curvebox");
var rude = document.getElementById("rude");
var spun = document.getElementById("spun");
var cover = document.getElementById("cover");
var lawbreaker = document.getElementById("lawbreaker");
curvebox.classList.add("getmeinofhere");
rude.classList.add("getmeoutofhere");
rude.style.display = null;
setTimeout(startmusic, 1600);
setTimeout(startstyle, 2000);
setTimeout(delayedlaw, 4800);
setTimeout(endstatic, 2000);
}
function reset()
{
audio.currentTime = 0;
audio.pause();
tapesound.currentTime = 0;
tapesound.pause();
// staticsound.play();
var string = "/img/tiled static.gif";
document.body.style.backgroundImage = "url('" + string + "')";
document.body.style.backgroundColor = "white";
}
window.onload = function()
{
var button = document.getElementById("OHGODWORK");
button.onclick = onplay;
console.log("load successed");
tapesound = document.createElement("audio");
tapesound.src = "/tapefeed.mp3";
tapesound.pause();
audio = document.createElement("audio");
audio.src = " https://oman.imjake.me/LawBreaker.mp3 ";
audio.pause();
audio.addEventListener('ended',function(){
reset();
},false);
}
|
jsonp({"cep":"79242000","cidade":"Boqueir\u00e3o","uf":"MS","estado":"Mato Grosso do Sul"});
|
jsonp({"cep":"64230000","cidade":"Buriti dos Lopes","uf":"PI","estado":"Piau\u00ed"});
|
// Import the LitElement base class and html helper function
import { LitElement, html, css } from 'lit-element';
// Extend the LitElement base class
export class MyProgress extends LitElement {
static get properties() {
return {
id: { type: String },
name: { type: String },
min: { type: String },
max: { type: String },
value: { type: String }
};
}
constructor() {
super();
this.id = ""
this.name = ""
this.min = "0";
this.max = "100";
this.value = "0";
}
handleValueChange(e) {
var myaddr = this.id;
var object = {
"address": myaddr,
"data": {
value: this.value
}
};
Window.mySocket.send(JSON.stringify(object) + "\n");
}
/**
* Implement `render` to define a template for your element.
*
* You must provide an implementation of `render` for any element
* that uses LitElement as a base class.
*/
render(){
/**
* `render` must return a lit-html `TemplateResult`.
*
* To create a `TemplateResult`, tag a JavaScript template literal
* with the `html` helper function:
*/
return html`
<!-- template content -->
<div class="progresscontainer">
<p><strong>${this.name}</strong></p>
<progress min="${this.min}" max="${this.max}" value="${this.value}" class="progress" id="myProgress" @input="${this.handleValueChange}">
</div>
`;
}
static get styles() {
return css`
.progresscontainer {
width: 100% /* Width of the outisde container */
}
.progress {
opacity: 0.7;
width: 100%
background: #4CAF50; /* green */
}
.progress:hover {
opacity: 1; /* Fully shown on mouse-over */
}
p { color: blue; }
`;
}
}
// Register the new element with the browser.
customElements.define('arro-progress', MyProgress);
|
// @flow
export type Report = {
id: string,
branch: string,
parentId: string,
deleted: boolean,
name: string,
timestamp: string,
}
|
'use strict';
module.exports = function(grunt) {
// Force use of Unix newlines
grunt.util.linefeed = '\n';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
year: grunt.template.today('yyyy'),
less: {
core: {
options: {
sourceMap: true,
sourceMapURL: '<%= pkg.name %>.css.map',
outputSourceFiles: true
},
src: 'less/<%= pkg.name %>.less',
dest: 'css/<%= pkg.name %>.css'
}
},
cssmin: {
core: {
options: {
compatibility: 'ie9',
sourceMap: true
},
expand: true,
src: 'css/*.css',
ext: '.min.css'
}
},
uglify: {
core: {
options: {
sourceMap: true,
sourceMapName: 'js/bootstrap-drilldown-select.js.map'
},
files: {
'js/bootstrap-drilldown-select.min.js': ['js/bootstrap-drilldown-select.js']
}
}
}
});
// These plugins provide necessary tasks.
require('load-grunt-tasks')(grunt, {
scope: 'devDependencies'
});
grunt.registerTask('default', [
'less',
'cssmin',
'uglify'
]);
};
|
describe('sjl.stdlib.Iterator', function () {
// ~~~ STRIP ~~~
// This part gets stripped out when
// generating browser version of test(s).
'use strict';
var chai = require('chai'),
sjl = require('./../../src/sjl'),
expect = chai.expect;
// These variables get set at the top IIFE in the browser.
// ~~~ /STRIP ~~~
var interfaceKeys = [
'current', 'next', 'rewind', 'valid'
],
basicArray = 'abcdefghijklmnopqrstuvwxyz'.split(''),
Iterator = sjl.ns.stdlib.Iterator,
iterator = new Iterator(basicArray);
it ('should create a new `Iterator`.', function () {
expect(iterator instanceof Iterator).to.equal(true);
expect((new Iterator(basicArray)) instanceof Iterator).to.equal(true);
});
it ('should have `_values` and `pointer` properties of the correct types', function () {
expect(sjl.issetAndOfType(iterator._values, 'Array')).to.equal(true);
expect(sjl.issetAndOfType(iterator.pointer, 'Number')).to.equal(true);
});
it ('should have the appropriate interface: [' + interfaceKeys.join(', ') + '] .', function () {
expect(Object.keys(Iterator.prototype).filter(function (key) {
return interfaceKeys.indexOf(key) > -1;
}).length === interfaceKeys.length).to.equal(true);
});
it ('should be able to iterate through all values in `iterator`.', function () {
var value;
while (iterator.valid()) {
value = iterator.next();
expect(value.value).to.equal(basicArray[iterator.pointer - 1]);
expect(value.done).to.equal(false);
}
expect(iterator.valid()).to.equal(false);
});
it ('should be able to be rewound.', function () {
expect(iterator.pointer).to.equal(basicArray.length);
expect(iterator.rewind().pointer).to.equal(0);
});
it ('should be able to set the __internal `pointer` via the `pointer` method.', function () {
iterator.pointer = 16;
expect(iterator.pointer).to.equal(16);
});
it ('should be able to set the __internal `values` via the `values` method.', function () {
iterator.values = ['a', 'b', 'c'];
expect(iterator.values.length).to.equal(3);
});
it ('should be able to get the value at the `current` pointer position via the `current` method.', function () {
iterator.pointer = 1;
expect(iterator.current().value).to.equal('b');
});
});
|
export const GP_PROJECT = process.env.NODE_ENV === 'production' ? 'wpcom' : 'test';
export const GP_BASE_URL = 'https://translate.wordpress.com';
export const GP_PROJECT_TRANSLATION_SET_SLUGS = {
de_formal: 'formal',
};
export const ENABLE_TRANSLATOR_KEY = 'enable_translator';
|
$(function () {
$('#supportsearch').typeahead({
name: 'supsearch',
valueKey: "line1",
limit: 25,
beforeSend: function (jqXhr, settings) {
$.SetLoadingIndicator();
},
remote: '/MissionTripEmail2/Search/{0}?q=%QUERY'.format($("#PeopleId").val()),
minLength: 3,
template: 'dummy string',
engine: {
compile: function (t) {
return {
render: function (context) {
var r = "<div{2}>{0}{1}</div>".format(
context.line1,
context.line2
? "<br>" + context.line2
: "",
context.addmargin
? ""
: "");
return r;
}
};
}
}
});
$('#supportsearch').bind('typeahead:selected', function (obj, datum, name) {
$.post(datum.url, {}, function(ret) {
$("#recipients").html(ret).ready(function() {
$("#supportsearch").val("");
$("#recipients .newsupporter").effect("highlight", { color: '#eaab00' }, 2000);
});
});
});
$('body').on('click', '#recipients a.remove', function (ev) {
ev.preventDefault();
var href = this.href;
$.post(href, {}, function (ret) {
$("#recipients").html(ret);
});
return false;
});
$("#edit-supporters").click(function (ev) {
ev.preventDefault();
var href = this.href;
$("#edit-supporters").hide();
$("#editing").show();
$("#edit-help").hide();
$("#done-help").show();
$.post(href, {}, function (ret) {
$("#recipients").html(ret);
});
return false;
});
$("#cancel-editing").click(function (ev) {
ev.preventDefault();
var href = this.href;
$("#editing").hide();
$("#edit-supporters").show();
$("#edit-help").show();
$("#done-help").hide();
$.post(href, {}, function (ret) {
$("#recipients").html(ret);
});
return false;
});
$("#done-editing").click(function (ev) {
ev.preventDefault();
var href = this.href;
$("#editing").hide();
$("#edit-supporters").show();
$("#edit-help").show();
$("#done-help").hide();
var q = $("#SendEmail,#recipients").serialize();
$.post(href, q, function (ret) {
$("#recipients").html(ret);
});
return false;
});
var currentDiv = null;
$.clearFunction = undefined;
$.addFunction = undefined;
$.clearTemplateClass = function () {
if (typeof $.clearFunction != 'undefined') {
$.clearFunction();
}
};
$.addTemplateClass = function () {
if (typeof $.addFunction != 'undefined') {
$.addFunction();
}
};
window.displayEditor = function (div) {
currentDiv = div;
$('#editor-modal').modal('show');
};
$('#editor-modal').on('shown.bs.modal', function () {
if ($('#htmleditor').data('fa.editable')) {
$('#htmleditor').froalaEditable('destroy');
}
var extraSmallDevice = $('.device-xs').is(':visible');
var editorButtons = ['bold', 'italic', 'underline', 'fontSize', 'fontFamily', 'color', 'removeFormat', 'sep', 'formatBlock', 'align', 'insertOrderedList', 'insertUnorderedList', 'outdent', 'indent', 'sep', 'createLink', 'insertImage', 'uploadFile', 'table', 'undo', 'redo', 'html', 'fullscreen'];
var editorHeight = 400;
if (extraSmallDevice) {
editorButtons = ['bold', 'createLink', 'specialLink', 'insertImage', 'html', 'fullscreen'];
editorHeight = 200;
}
$('#htmleditor').froalaEditable({
inlineMode: false,
spellcheck: true,
useFileName: false,
useClasses: false,
zIndex: 2501,
height: editorHeight,
theme: 'custom',
buttons: editorButtons,
imageUploadURL: '/Account/FroalaUpload',
fileUploadURL: '/Account/FroalaUpload',
maxFileSize: (1024 * 1024 * 15)
});
var html = $(currentDiv).html();
if (html !== "Click here to edit content") {
$('#htmleditor').froalaEditable('setHTML', html);
}
});
function adjustIframe() {
var iFrameID = document.getElementById('email-body');
if (iFrameID) {
// here you can make the height, I delete it first, then I make it again
iFrameID.height = "";
iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + 20 + "px";
}
}
$('#editor-modal').on('click', '#save-edit', function () {
var h = $('#htmleditor').froalaEditable('getHTML');
$(currentDiv).html(h);
adjustIframe();
$('#editor-modal').modal('hide');
});
$(".send").click(function () {
$('#Body').val($('#email-body').contents().find('#tempateBody').html());
var q = $("#SendEmail").serialize();
$.post('/MissionTripEmail2/Send', q, function (ret) {
if (ret.startsWith("/MissionTripEmail"))
window.location = ret;
else
swal("Error!", ret, "error");
});
});
$(".testsend").click(function () {
$.clearTemplateClass();
$("#Body").val($('#email-body').contents().find('#tempateBody').html());
$.addTemplateClass();
var q = $("#SendEmail").serialize();
$.post('/MissionTripEmail2/TestSend', q, function (ret) {
if (ret.error) {
swal("Error!", ret.message, "error");
}
else {
swal({
title: "Test email sent!",
type: "success"
});
}
}, 'json');
});
});
|
jQuery(document).ready(function($){
elementuipanel={
initpanel:function(){
},
add_body_panel:function(self){
object_id=self.closest('.properties').attr('data-object-id');
ajaxInsertElement=$.ajax({
type: "GET",
url: this_host+'/index.php',
data: (function () {
dataPost = {
option: 'com_utility',
task: 'utility.aJaxInsertRow',
parentColumnId:object_id,
menuItemActiveId:menuItemActiveId,
ajaxgetcontent:1,
screenSize:screen_size_id
};
return dataPost;
})(),
beforeSend: function () {
// $('.loading').popup();
},
success: function (response) {
}
});
}
}
});
|
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var multer = require('multer');
var fs = require('fs')
var exec = require('child_process').exec;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
app.listen(8888,function(){
console.log("2333");
})
var wenjian = multer({ dest: './public/wz/' })
var wenjian_img = multer({ dest: './public/wz/tx/' })
app.post('/update', wenjian_img, function (req, res) {
console.log(req.files);
var cmdStr = 'mv '+req.files.tupian.path+" "+"public/wz/tx/233/";
exec(cmdStr, function (err, stdout, stderr) {
var cmdStr = 'rm '+req.files.tupian.path;
exec(cmdStr, function (err, stdout, stderr) {
console.log(stdout)
})
})
})
|
'use strict';
angular.module('allocine-api').factory('AlloCineAPIExposed', ['$resource', function($resource) {
return {
search: function(toSearch, count, filter) {
return $resource('api/allocine/:apiAction', {}, {
search: {
method: 'GET',
params: {
apiAction: 'search',
toSearch: toSearch,
count: count,
filter: filter
},
isArray: true
}
}).search();
},
getMediaInfo: function(code, mediaType) {
return $resource('api/allocine/:apiAction', {}, {
getMediaInfo: {
method: 'GET',
params: {
apiAction: 'getMediaInfo',
code: code,
mediaType: mediaType
}
}
}).getMediaInfo();
}
};
}
]);
|
/* jshint nomen: false */
( function( mw, $ ) {
// TODO come now, there has to be a better way
mediaWiki.messages.set( {
'mwe-upwiz-code-unknown': 'Unknown language'
} );
/**
* Utility class which knows about languages, and how to construct HTML to select them
* TODO: make this a more common library, used by this and TimedText
*/
mw.LanguageUpWiz = {
defaultCode: null,
initialized: false,
UNKNOWN: 'unknown',
/**
* List of default languages
* Make sure you have language templates set up for each of these on your wiki, e.g. {{en}}
* TODO make this more configurable.
* This is set in the initialize().
*/
languages: null,
// Helper function to see if a language is in the list.
checkForLang: function( lang ) {
for ( var langIndex in mw.LanguageUpWiz.languages ) {
if ( mw.LanguageUpWiz.languages[langIndex].code === lang ) {
return true;
}
}
return false;
},
/**
* cache some useful objects
* 1) mostly ready-to-go language HTML menu. When/if we upgrade, make it a jQuery combobox
* 2) dict of language code to name -- useful for testing for existence, maybe other things.
*/
initialize: function() {
var langs, langcode,
thisUri = new mw.Uri( window.location.href, { overrideKeys: true } ),
$select = $( '<select>' );
if ( mw.LanguageUpWiz.initialized ) {
return;
}
mw.LanguageUpWiz.languages = [];
langs = mw.UploadWizard.config.uwLanguages;
for ( langcode in langs ) {
mw.LanguageUpWiz.languages.push( { code: langcode, text: langs[langcode] } );
}
// If a descriptionlang param is passed in the query string, use that,
// otherwise choose a good default for the description language.
if ( thisUri.query.descriptionlang && mw.LanguageUpWiz.checkForLang( thisUri.query.descriptionlang ) ) {
mw.LanguageUpWiz.defaultCode = thisUri.query.descriptionlang;
} else if ( mw.LanguageUpWiz.checkForLang( mw.config.get( 'wgUserLanguage' ) ) ) {
mw.LanguageUpWiz.defaultCode = mw.config.get( 'wgUserLanguage' );
} else if ( mw.LanguageUpWiz.checkForLang( mw.config.get( 'wgContentLanguage' ) ) ) {
mw.LanguageUpWiz.defaultCode = mw.config.get( 'wgContentLanguage' );
} else if ( mw.LanguageUpWiz.checkForLang( 'en' ) ) {
mw.LanguageUpWiz.defaultCode = 'en';
} else {
mw.LanguageUpWiz.defaultCode = mw.LanguageUpWiz.languages[0].code;
}
mw.LanguageUpWiz.codes = {};
$.each( mw.LanguageUpWiz.languages, function( i, language ) {
// add an option for each language
var $opt = $( '<option>' )
.prop( 'value', language.code )
.text( language.text )
.prop( 'selected', language.code === this.defaultCode );
$select.append( $opt );
// add each language into dictionary
mw.LanguageUpWiz.codes[language.code] = language.text;
} );
mw.LanguageUpWiz.$select = $select;
mw.LanguageUpWiz.initialized = true;
},
/**
* Get an HTML select menu of all our languages.
* @param name desired name of select element
* @param code selected language code
* @return HTML select element configured as desired
*/
getMenu: function( name, code ) {
mw.LanguageUpWiz.initialize();
/* If we did not request a specific selected language code, see if we have a default. */
if ( mw.LanguageUpWiz.defaultCode !== null && code === mw.LanguageUpWiz.UNKNOWN ) {
code = mw.LanguageUpWiz.defaultCode;
}
var $select = mw.LanguageUpWiz.$select
.clone()
.prop( 'name', name );
if ( code === mw.LanguageUpWiz.UNKNOWN ) {
// n.b. MediaWiki LanguageHandler has ability to add custom label for 'Unknown'; possibly as pseudo-label
$select
.prepend(
$( '<option>' )
.prop( 'value', mw.LanguageUpWiz.UNKNOWN )
.text( mw.message( 'mwe-upwiz-code-unknown' ).text() )
)
.val( mw.LanguageUpWiz.UNKNOWN );
}
/* Pre select the 'code' language */
if ( code !== undefined && mw.LanguageUpWiz.checkForLang( code ) ) {
$select.val( mw.LanguageUpWiz.getClosest( code ));
}
return $select.get( 0 );
},
/**
* Figure out the closest language we have to a supplied language code.
* It seems that people on Mediawiki set their language code as freetext, and it could be anything, even
* variants we don't have a record for, or ones that are not in any ISO standard.
*
* Logic copied from MediaWiki:LanguageHandler.js
* handle null cases, special cases for some Chinese variants
* Otherwise, if handed "foo-bar-baz" language, try to match most specific language,
* "foo-bar-baz", then "foo-bar", then "foo"
*
* @param code A string representing a language code, which we may or may not have.
* Expected to be separated with dashes as codes from ISO 639, e.g. "zh-tw" for Chinese ( Traditional )
* @return a language code which is close to the supplied parameter, or fall back to mw.LanguageUpWiz.defaultCode
*/
getClosest: function( code ) {
mw.LanguageUpWiz.initialize();
if ( typeof ( code ) !== 'string' || code === null || code.length === 0 ) {
return mw.LanguageUpWiz.defaultCode;
}
if ( code === 'nan' || code === 'minnan' ) {
return 'zh-min-nan';
} else if ( mw.LanguageUpWiz.codes[code] !== undefined ) {
return code;
}
return mw.LanguageUpWiz.getClosest( code.substring( 0, code.indexOf( '-' )) );
}
};
}( mediaWiki, jQuery ) );
|
(function(angular) {
angular.module('authors', [
'ui.bootstrap',
'authors.directives',
'authors.controllers'
]);
})(angular);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.