text
stringlengths 2
6.14k
|
|---|
/**
* Created by JetBrains PhpStorm.
* User: dongyancen
* Date: 12-9-18
* Time: 下午4:33
* To change this template use File | Settings | File Templates.
*/
module( 'plugins.autofloat' );
test( '检查toolbar是否浮动在页面顶端', function() {
te.dom[0].parentNode.removeChild(te.dom[0]);
var sc = document.createElement("script");
sc.id="sc";
sc.type = "text/plain";
sc.style.height = "100px";
document.body.appendChild(sc);
var me = UE.getEditor('sc',{'autoFloatEnabled':true,'topOffset':60,'autoHeightEnabled':true,'scaleEnabled':false});
stop();
me.ready(function(){
setTimeout(function () {
me.setContent('<p><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>sdf</p>');
var screenX = window.screenX ? window.screenX : window.screenLeft;//不同浏览器兼容
var screenY = window.screenY ? window.screenY : window.screenTop;
setTimeout(function () {
var range = new baidu.editor.dom.Range(me.document);
range.setStart(me.body.firstChild, 1).collapse(1).select();
me.focus();
setTimeout(function () {
window.scrollBy(screenX, screenY + $(document.body).height());
setTimeout(function () {
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;//不同浏览器兼容
//// //ie6下,工具栏浮动不到正确位置
if (ua.browser.ie != 6&&!ua.browser.gecko)
equal(scrollTop, $(me.ui.getDom('toolbarbox')).offset().top - 60, '检查toolbar是否在页面顶端');
window.scrollTo(screenX, screenY - $(document.body).height());
setTimeout(function () {
equal(me.ui.getDom().childNodes[0].id, me.ui.getDom('toolbarbox').id, 'toolbar是第一个元素');
document.getElementById('sc').parentNode.removeChild(document.getElementById('sc'));
start();
}, 500);
}, 500);
}, 1000);
}, 200);
}, 800);
});
});
|
$UrlRouterProvider.$inject = ['$urlMatcherFactoryProvider'];
function $UrlRouterProvider( $urlMatcherFactory) {
var rules = [],
otherwise = null;
// Returns a string that is a prefix of all strings matching the RegExp
function regExpPrefix(re) {
var prefix = /^\^((?:\\[^a-zA-Z0-9]|[^\\\[\]\^$*+?.()|{}]+)*)/.exec(re.source);
return (prefix != null) ? prefix[1].replace(/\\(.)/g, "$1") : '';
}
// Interpolates matched values into a String.replace()-style pattern
function interpolate(pattern, match) {
return pattern.replace(/\$(\$|\d{1,2})/, function (m, what) {
return match[what === '$' ? 0 : Number(what)];
});
}
this.rule =
function (rule) {
if (!isFunction(rule)) throw new Error("'rule' must be a function");
rules.push(rule);
return this;
};
this.otherwise =
function (rule) {
if (isString(rule)) {
var redirect = rule;
rule = function () { return redirect; };
}
else if (!isFunction(rule)) throw new Error("'rule' must be a function");
otherwise = rule;
return this;
};
function handleIfMatch($injector, handler, match) {
if (!match) return false;
var result = $injector.invoke(handler, handler, { $match: match });
return isDefined(result) ? result : true;
}
this.when =
function (what, handler) {
var redirect, handlerIsString = isString(handler);
if (isString(what)) what = $urlMatcherFactory.compile(what);
if (!handlerIsString && !isFunction(handler) && !isArray(handler))
throw new Error("invalid 'handler' in when()");
var strategies = {
matcher: function (what, handler) {
if (handlerIsString) {
redirect = $urlMatcherFactory.compile(handler);
handler = ['$match', function ($match) { return redirect.format($match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));
}, {
prefix: isString(what.prefix) ? what.prefix : ''
});
},
regex: function (what, handler) {
if (what.global || what.sticky) throw new Error("when() RegExp must not be global or sticky");
if (handlerIsString) {
redirect = handler;
handler = ['$match', function ($match) { return interpolate(redirect, $match); }];
}
return extend(function ($injector, $location) {
return handleIfMatch($injector, handler, what.exec($location.path()));
}, {
prefix: regExpPrefix(what)
});
}
};
var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };
for (var n in check) {
if (check[n]) {
return this.rule(strategies[n](what, handler));
}
}
throw new Error("invalid 'what' in when()");
};
this.$get =
[ '$location', '$rootScope', '$injector',
function ($location, $rootScope, $injector) {
// TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree
function update(evt) {
if (evt && evt.defaultPrevented) return;
function check(rule) {
var handled = rule($injector, $location);
if (handled) {
if (isString(handled)) $location.replace().url(handled);
return true;
}
return false;
}
var n=rules.length, i;
for (i=0; i<n; i++) {
if (check(rules[i])) return;
}
// always check otherwise last to allow dynamic updates to the set of rules
if (otherwise) check(otherwise);
}
$rootScope.$on('$locationChangeSuccess', update);
return {
sync: function () {
update();
}
};
}];
}
angular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);
|
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
*
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* Creates an observer from a notification callback.
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
var handlerFunc = bindCallback(handler, thisArg, 1);
return new AnonymousObserver(function (x) {
return handlerFunc(notificationCreateOnNext(x));
}, function (e) {
return handlerFunc(notificationCreateOnError(e));
}, function () {
return handlerFunc(notificationCreateOnCompleted());
});
};
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
var source = this;
return new AnonymousObserver(
function (x) { source.onNext(x); },
function (e) { source.onError(e); },
function () { source.onCompleted(); }
);
};
|
if (!RedactorPlugins) var RedactorPlugins = {};
(function($)
{
RedactorPlugins.fontfamily = function()
{
return {
init: function ()
{
var fonts = [ 'Arial', 'Helvetica', 'Georgia', 'Times New Roman', 'Monospace' ];
var that = this;
var dropdown = {};
$.each(fonts, function(i, s)
{
dropdown['s' + i] = { title: s, func: function() { that.fontfamily.set(s); }};
});
/* concrete5 */
dropdown.remove = { title: this.lang.get('remove_font_family'), func: that.fontfamily.reset };
var button = this.button.add('fontfamily', this.lang.get('change_font_family'));
this.button.setAwesome('fontfamily', 'fa fa-font');
/* end concrete5 */
this.button.addDropdown(button, dropdown);
},
set: function (value)
{
this.inline.format('span', 'style', 'font-family:' + value + ';');
},
reset: function()
{
this.inline.removeStyleRule('font-family');
}
};
};
})(jQuery);
|
//>>built
define("dojox/charting/plot2d/Bars",["dojo/_base/kernel","dojo/_base/lang","dojo/_base/array","dojo/_base/declare","./Base","./common","dojox/gfx/fx","dojox/lang/utils","dojox/lang/functional","dojox/lang/functional/reversed"],function(_1,_2,_3,_4,_5,dc,fx,du,df,_6){
var _7=_6.lambda("item.purgeGroup()");
return _4("dojox.charting.plot2d.Bars",_5,{defaultParams:{hAxis:"x",vAxis:"y",gap:0,animate:null,enableCache:false},optionalParams:{minBarSize:1,maxBarSize:1,stroke:{},outline:{},shadow:{},fill:{},font:"",fontColor:""},constructor:function(_8,_9){
this.opt=_2.clone(this.defaultParams);
du.updateWithObject(this.opt,_9);
du.updateWithPattern(this.opt,_9,this.optionalParams);
this.series=[];
this.hAxis=this.opt.hAxis;
this.vAxis=this.opt.vAxis;
this.animate=this.opt.animate;
},getSeriesStats:function(){
var _a=dc.collectSimpleStats(this.series),t;
_a.hmin-=0.5;
_a.hmax+=0.5;
t=_a.hmin,_a.hmin=_a.vmin,_a.vmin=t;
t=_a.hmax,_a.hmax=_a.vmax,_a.vmax=t;
return _a;
},createRect:function(_b,_c,_d){
var _e;
if(this.opt.enableCache&&_b._rectFreePool.length>0){
_e=_b._rectFreePool.pop();
_e.setShape(_d);
_c.add(_e);
}else{
_e=_c.createRect(_d);
}
if(this.opt.enableCache){
_b._rectUsePool.push(_e);
}
return _e;
},render:function(_f,_10){
if(this.zoom&&!this.isDataDirty()){
return this.performZoom(_f,_10);
}
this.dirty=this.isDirty();
this.resetEvents();
if(this.dirty){
_3.forEach(this.series,_7);
this._eventSeries={};
this.cleanGroup();
var s=this.group;
df.forEachRev(this.series,function(_11){
_11.cleanGroup(s);
});
}
var t=this.chart.theme,f,gap,_12,ht=this._hScaler.scaler.getTransformerFromModel(this._hScaler),vt=this._vScaler.scaler.getTransformerFromModel(this._vScaler),_13=Math.max(0,this._hScaler.bounds.lower),_14=ht(_13),_15=this.events();
f=dc.calculateBarSize(this._vScaler.bounds.scale,this.opt);
gap=f.gap;
_12=f.size;
for(var i=this.series.length-1;i>=0;--i){
var run=this.series[i];
if(!this.dirty&&!run.dirty){
t.skip();
this._reconnectEvents(run.name);
continue;
}
run.cleanGroup();
if(this.opt.enableCache){
run._rectFreePool=(run._rectFreePool?run._rectFreePool:[]).concat(run._rectUsePool?run._rectUsePool:[]);
run._rectUsePool=[];
}
var _16=t.next("bar",[this.opt,run]),s=run.group,_17=new Array(run.data.length);
for(var j=0;j<run.data.length;++j){
var _18=run.data[j];
if(_18!==null){
var v=typeof _18=="number"?_18:_18.y,hv=ht(v),_19=hv-_14,w=Math.abs(_19),_1a=typeof _18!="number"?t.addMixin(_16,"bar",_18,true):t.post(_16,"bar");
if(w>=0&&_12>=1){
var _1b={x:_10.l+(v<_13?hv:_14),y:_f.height-_10.b-vt(j+1.5)+gap,width:w,height:_12};
var _1c=this._plotFill(_1a.series.fill,_f,_10);
_1c=this._shapeFill(_1c,_1b);
var _1d=this.createRect(run,s,_1b).setFill(_1c).setStroke(_1a.series.stroke);
run.dyn.fill=_1d.getFill();
run.dyn.stroke=_1d.getStroke();
if(_15){
var o={element:"bar",index:j,run:run,shape:_1d,x:v,y:j+1.5};
this._connectEvents(o);
_17[j]=o;
}
if(this.animate){
this._animateBar(_1d,_10.l+_14,-w);
}
}
}
}
this._eventSeries[run.name]=_17;
run.dirty=false;
}
this.dirty=false;
return this;
},_animateBar:function(_1e,_1f,_20){
fx.animateTransform(_2.delegate({shape:_1e,duration:1200,transform:[{name:"translate",start:[_1f-(_1f/_20),0],end:[0,0]},{name:"scale",start:[1/_20,1],end:[1,1]},{name:"original"}]},this.animate)).play();
}});
});
|
/**
* Copyright (c) 2014, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
var istanbul = require('istanbul');
function IstanbulCollector(sourceText, filename) {
var instr = new istanbul.Instrumenter();
this._coverageDataStore = {};
this._instrumentor = instr;
this._origSourceText = sourceText;
this._instrumentedSourceText = instr.instrumentSync(sourceText, filename);
}
IstanbulCollector.prototype.getCoverageDataStore = function() {
return this._coverageDataStore;
};
IstanbulCollector.prototype.getInstrumentedSource = function(storageVarName) {
return this._instrumentedSourceText + storageVarName + '.coverState=' +
this._instrumentor.currentState.trackerVar + ';';
};
IstanbulCollector.prototype.extractRuntimeCoverageInfo = function() {
return this._coverageDataStore.coverState;
};
module.exports = IstanbulCollector;
|
/*************************GO-LICENSE-START*********************************
* Copyright 2014 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************GO-LICENSE-END**********************************/
/* This function is to collapse or expand the side bar */
function toggleSidebar(link) {
$('sidebar').toggle();
$('doc3').toggleClassName('yui-t6').toggleClassName('yui-t7');
if (link.title == "Collapse sidebar") {
link.title = "Expand sidebar";
rememberSidebarStatus('collapse');
} else {
link.title = "Collapse sidebar";
rememberSidebarStatus('expand');
}
$(link).toggleClassName('collapse').toggleClassName('expand');
}
function expandSidebar(link) {
$('sidebar').hide();
$('doc3').removeClassName('yui-t6').addClassName('yui-t7');
link.title = "Collapse sidebar";
$(link).removeClassName('collapse').addClassName('expand');
}
function collapseSidebar(link){
if($('sidebar')){
$('sidebar').show();
$('doc3').removeClassName('yui-t7').addClassName('yui-t6');
link.title = "Expand sidebar";
$(link).addClassName('collapse').removeClassName('expand');
}
}
function rememberSidebarStatus(status) {
setCookie('sidebar-status', status);
}
function restoreSidebarStatus() {
var status = getCookie('sidebar-status');
var button = $('collapse-sidebar-link');
if(status && status == 'collapse' && button){
toggleSidebar(button);
}
}
|
Package.describe({
summary: "Meetup OAuth flow",
version: "1.6.0"
});
Package.onUse(function(api) {
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['client', 'server']);
api.use('http', ['server']);
api.use('templating', 'client');
api.use('underscore', 'client');
api.use('random', 'client');
api.use('service-configuration', ['client', 'server']);
api.export('Meetup');
api.addFiles(
['meetup_configure.html', 'meetup_configure.js'],
'client');
api.addFiles('meetup_server.js', 'server');
api.addFiles('meetup_client.js', 'client');
});
|
( function($) {
$( '#widgets-right' )
.on( 'click', '.view-icons', function(e) {
var $el = $(this),
$parent = $el.parents( '.widget-content' );
e.preventDefault();
$el.text( ( 'Hide Icons' == $el.text() ) ? 'View Icons' : 'Hide Icons' );
$parent.find( '.font-awesome-picker' ).toggle();
} )
.on( 'click', '.font-awesome-picker .c4', function(e) {
var $el = $(this),
$parent = $el.parents( '.widget-content' ),
selected_icon = $el.data( 'value' );
e.preventDefault();
$parent.find( '.image-widget-custom-icon' ).val( selected_icon ).trigger( 'change' );
$parent.find( '.custom-icon-container' ).html( '<i class="fa ' + selected_icon + '" />' );
} )
.on( 'click', '.delete-icon', function(e) {
var $parent = $(this).parents( '.widget-content' );
e.preventDefault();
$parent.find( '.image-widget-custom-icon' ).val( '' ).trigger( 'change' );
$parent.find( '.custom-icon-container' ).html( '' );
} );
} )(jQuery);
|
/**
* Modules dependencies
*/
var mocha = require('mocha'),
figc = require('figc'),
assert = require('chai').assert,
libPath = process.env['SOLR_CLIENT_COV'] ? '../lib-cov' : '../lib',
solr = require( libPath + '/solr'),
SolrError = require(libPath + '/error/solr-error'),
sassert = require('./sassert'),
versionUtils = require('./../lib/utils/version');
// Test suite
var config = figc(__dirname + '/config.json');
var client = solr.createClient(config.client);
var basePath = [config.client.path, config.client.core].join('/').replace(/\/$/,"");
describe('Client',function(){
describe('#delete("title_t","test",callback)',function(){
it('should delete all documents where the field "title_t" is "test"',function(done){
client.delete('title_t','test',function(err,data){
sassert.ok(err,data);
done();
});
});
});
describe('#delete("title_t","test",{ commit : true},callback)',function(){
it('should delete all documents where the field "title_t" is "test" and hard commit all changes',function(done){
var request = client.delete('title_t','test',{commit : true},function(err,data){
if(client.options.solrVersion && versionUtils.version(client.options.solrVersion) >= versionUtils.Solr4_0) {
assert.equal(request.path, basePath + '/update?commit=true&wt=json');
} else {
assert.equal(request.path, basePath + '/update/json?commit=true&wt=json');
}
sassert.ok(err,data);
done();
});
});
});
describe('#delete("title_t","test",{ softCommit : true},callback)',function(){
it('should delete all documents where the field "title_t" is "test" and soft commit all changes',function(done){
var request = client.delete('title_t','test',{softCommit : true},function(err,data){
if(client.options.solrVersion && versionUtils.version(client.options.solrVersion) >= versionUtils.Solr4_0) {
assert.equal(request.path, basePath + '/update?softCommit=true&wt=json');
} else {
assert.equal(request.path, basePath + '/update/json?softCommit=true&wt=json');
}
sassert.ok(err,data);
done();
});
});
});
describe('#delete("title_t","test",{ commitWithin : 10000},callback)',function(){
it('should delete all documents where the field "title_t" is "test" and commit within 10s all changes',function(done){
var request = client.delete('title_t','test',{commitWithin : 10000},function(err,data){
if(client.options.solrVersion && versionUtils.version(client.options.solrVersion) >= versionUtils.Solr4_0) {
assert.equal(request.path, basePath + '/update?commitWithin=10000&wt=json');
} else {
assert.equal(request.path, basePath + '/update/json?commitWithin=10000&wt=json');
}
sassert.ok(err,data);
done();
});
});
});
describe('#delete("unknownField","test",callback)',function(){
it('should return a `SolrError`',function(done){
client.delete('unknownField','test',function(err,data){
sassert.nok(err,data);;
done();
});
});
});
});
|
import Ember from 'ember';
const {computed} = Ember;
/**
* Defines a property similarly to `Ember.computed.oneway`,
* save that while a `oneway` loses its binding upon being set,
* the `BoundOneWay` will continue to listen for upstream changes.
*
* This is an ideal tool for working with values inside of {{input}}
* elements.
* @param {*} upstream
* @param {function} transform a function to transform the **upstream** value.
*/
export default function (upstream, transform) {
if (typeof transform !== 'function') {
// default to the identity function
transform = function (value) {
return value;
};
}
return computed(upstream, {
get() {
return transform(this.get(upstream));
},
set(key, value) {
return value;
}
});
}
|
/*
This file is part of Ext JS 3.4
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Build date: 2013-04-03 15:07:25
*/
Ext.ns('Ext.ux.tree');
/**
* @class Ext.ux.tree.TreeGridSorter
* @extends Ext.tree.TreeSorter
* Provides sorting of nodes in a {@link Ext.ux.tree.TreeGrid}. The TreeGridSorter automatically monitors events on the
* associated TreeGrid that might affect the tree's sort order (beforechildrenrendered, append, insert and textchange).
* Example usage:<br />
* <pre><code>
new Ext.ux.tree.TreeGridSorter(myTreeGrid, {
folderSort: true,
dir: "desc",
sortType: function(node) {
// sort by a custom, typed attribute:
return parseInt(node.id, 10);
}
});
</code></pre>
* @constructor
* @param {TreeGrid} tree
* @param {Object} config
*/
Ext.ux.tree.TreeGridSorter = Ext.extend(Ext.tree.TreeSorter, {
/**
* @cfg {Array} sortClasses The CSS classes applied to a header when it is sorted. (defaults to <tt>['sort-asc', 'sort-desc']</tt>)
*/
sortClasses : ['sort-asc', 'sort-desc'],
/**
* @cfg {String} sortAscText The text displayed in the 'Sort Ascending' menu item (defaults to <tt>'Sort Ascending'</tt>)
*/
sortAscText : 'Sort Ascending',
/**
* @cfg {String} sortDescText The text displayed in the 'Sort Descending' menu item (defaults to <tt>'Sort Descending'</tt>)
*/
sortDescText : 'Sort Descending',
constructor : function(tree, config) {
if(!Ext.isObject(config)) {
config = {
property: tree.columns[0].dataIndex || 'text',
folderSort: true
}
}
Ext.ux.tree.TreeGridSorter.superclass.constructor.apply(this, arguments);
this.tree = tree;
tree.on('headerclick', this.onHeaderClick, this);
tree.ddAppendOnly = true;
var me = this;
this.defaultSortFn = function(n1, n2){
var desc = me.dir && me.dir.toLowerCase() == 'desc',
prop = me.property || 'text',
sortType = me.sortType,
caseSensitive = me.caseSensitive === true,
leafAttr = me.leafAttr || 'leaf',
attr1 = n1.attributes,
attr2 = n2.attributes;
if(me.folderSort){
if(attr1[leafAttr] && !attr2[leafAttr]){
return 1;
}
if(!attr1[leafAttr] && attr2[leafAttr]){
return -1;
}
}
var prop1 = attr1[prop],
prop2 = attr2[prop],
v1 = sortType ? sortType(prop1) : (caseSensitive ? prop1 : prop1.toUpperCase());
v2 = sortType ? sortType(prop2) : (caseSensitive ? prop2 : prop2.toUpperCase());
if(v1 < v2){
return desc ? +1 : -1;
}else if(v1 > v2){
return desc ? -1 : +1;
}else{
return 0;
}
};
tree.on('afterrender', this.onAfterTreeRender, this, {single: true});
tree.on('headermenuclick', this.onHeaderMenuClick, this);
},
onAfterTreeRender : function() {
if(this.tree.hmenu){
this.tree.hmenu.insert(0,
{itemId:'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
{itemId:'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
);
}
this.updateSortIcon(0, 'asc');
},
onHeaderMenuClick : function(c, id, index) {
if(id === 'asc' || id === 'desc') {
this.onHeaderClick(c, null, index);
return false;
}
},
onHeaderClick : function(c, el, i) {
if(c && !this.tree.headersDisabled){
var me = this;
me.property = c.dataIndex;
me.dir = c.dir = (c.dir === 'desc' ? 'asc' : 'desc');
me.sortType = c.sortType;
me.caseSensitive === Ext.isBoolean(c.caseSensitive) ? c.caseSensitive : this.caseSensitive;
me.sortFn = c.sortFn || this.defaultSortFn;
this.tree.root.cascade(function(n) {
if(!n.isLeaf()) {
me.updateSort(me.tree, n);
}
});
this.updateSortIcon(i, c.dir);
}
},
// private
updateSortIcon : function(col, dir){
var sc = this.sortClasses,
hds = this.tree.innerHd.select('td').removeClass(sc);
hds.item(col).addClass(sc[dir == 'desc' ? 1 : 0]);
}
});
|
/*==================================================
* Localization of labellers.js
*==================================================
*/
// Timeline.GregorianDateLabeller.monthNames["pl"] = [
// "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
// ];
Timeline.GregorianDateLabeller.dayNames["pl"] = [
"Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"
];
|
/**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @typechecks
* @providesModule ReactCSSTransitionGroupChild
*/
"use strict";
var React = require('React');
var CSSCore = require('CSSCore');
var ReactTransitionEvents = require('ReactTransitionEvents');
var onlyChild = require('onlyChild');
// We don't remove the element from the DOM until we receive an animationend or
// transitionend event. If the user screws up and forgets to add an animation
// their node will be stuck in the DOM forever, so we detect if an animation
// does not start and if it doesn't, we just call the end listener immediately.
var TICK = 17;
var NO_EVENT_TIMEOUT = 5000;
var noEventListener = null;
if (__DEV__) {
noEventListener = function() {
console.warn(
'transition(): tried to perform an animation without ' +
'an animationend or transitionend event after timeout (' +
NO_EVENT_TIMEOUT + 'ms). You should either disable this ' +
'transition in JS or add a CSS animation/transition.'
);
};
}
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
transition: function(animationType, finishCallback) {
var node = this.getDOMNode();
var className = this.props.name + '-' + animationType;
var activeClassName = className + '-active';
var noEventTimeout = null;
var endListener = function(e) {
if (e && e.target !== node) {
return;
}
if (__DEV__) {
clearTimeout(noEventTimeout);
}
CSSCore.removeClass(node, className);
CSSCore.removeClass(node, activeClassName);
ReactTransitionEvents.removeEndEventListener(node, endListener);
// Usually this optional callback is used for informing an owner of
// a leave animation and telling it to remove the child.
finishCallback && finishCallback();
};
ReactTransitionEvents.addEndEventListener(node, endListener);
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClass(activeClassName);
if (__DEV__) {
noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT);
}
},
queueClass: function(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this.flushClassNameQueue, TICK);
}
},
flushClassNameQueue: function() {
if (this.isMounted()) {
this.classNameQueue.forEach(
CSSCore.addClass.bind(CSSCore, this.getDOMNode())
);
}
this.classNameQueue.length = 0;
this.timeout = null;
},
componentWillMount: function() {
this.classNameQueue = [];
},
componentWillUnmount: function() {
if (this.timeout) {
clearTimeout(this.timeout);
}
},
componentWillEnter: function(done) {
if (this.props.enter) {
this.transition('enter', done);
} else {
done();
}
},
componentWillLeave: function(done) {
if (this.props.leave) {
this.transition('leave', done);
} else {
done();
}
},
render: function() {
return onlyChild(this.props.children);
}
});
module.exports = ReactCSSTransitionGroupChild;
|
'use strict';
module.exports = {
set: function (v) {
this.setProperty('margin-bottom', v);
},
get: function () {
return this.getPropertyValue('margin-bottom');
},
enumerable: true
};
|
/*global window */
export default function(Handlebars) {
/* istanbul ignore next */
let root = typeof global !== 'undefined' ? global : window,
$Handlebars = root.Handlebars;
/* istanbul ignore next */
Handlebars.noConflict = function() {
if (root.Handlebars === Handlebars) {
root.Handlebars = $Handlebars;
}
};
}
|
define(
"dojox/editor/plugins/nls/da/InsertEntity", ({
insertEntity: "Indsæt symbol"
})
);
|
'use strict';
var should = require('chai').should();
var _ = require('lodash');
describe('toc', function(){
var toc = require('../../../lib/plugins/helper/toc');
var html = [
'<h1 id="title_1">Title 1</h1>',
'<h2 id="title_1_1">Title 1.1</h2>',
'<h3 id="title_1_1_1">Title 1.1.1</h3>',
'<h2 id="title_1_2">Title 1.2</h2>',
'<h2 id="title_1_3">Title 1.3</h2>',
'<h3 id="title_1_3_1">Title 1.3.1</h3>',
'<h1 id="title_2">Title 2</h1>',
'<h2 id="title_2_1">Title 2.1</h2>'
].join('');
var genResult = function(options){
options = _.extend({
class: 'toc',
list_number: true
}, options);
var className = options.class,
listNumber = options.list_number;
var result = [
'<ol class="' + className + '">',
'<li class="' + className + '-item ' + className + '-level-1">',
'<a class="' + className + '-link" href="#title_1">',
(listNumber ? '<span class="' + className + '-number">1.</span> ' : ''),
'<span class="' + className + '-text">Title 1</span>',
'</a>',
'<ol class="' + className + '-child">',
'<li class="' + className + '-item ' + className + '-level-2">',
'<a class="' + className + '-link" href="#title_1_1">',
(listNumber ? '<span class="' + className + '-number">1.1.</span> ' : ''),
'<span class="' + className + '-text">Title 1.1</span>',
'</a>',
'<ol class="' + className + '-child">',
'<li class="' + className + '-item ' + className + '-level-3">',
'<a class="' + className + '-link" href="#title_1_1_1">',
(listNumber ? '<span class="' + className + '-number">1.1.1.</span> ' : ''),
'<span class="' + className + '-text">Title 1.1.1</span>',
'</a>',
'</li>',
'</ol>',
'</li>',
'<li class="' + className + '-item ' + className + '-level-2">',
'<a class="' + className + '-link" href="#title_1_2">',
(listNumber ? '<span class="' + className + '-number">1.2.</span> ' : ''),
'<span class="' + className + '-text">Title 1.2</span>',
'</a>',
'</li>',
'<li class="' + className + '-item ' + className + '-level-2">',
'<a class="' + className + '-link" href="#title_1_3">',
(listNumber ? '<span class="' + className + '-number">1.3.</span> ' : ''),
'<span class="' + className + '-text">Title 1.3</span>',
'</a>',
'<ol class="' + className + '-child">',
'<li class="' + className + '-item ' + className + '-level-3">',
'<a class="' + className + '-link" href="#title_1_3_1">',
(listNumber ? '<span class="' + className + '-number">1.3.1.</span> ' : ''),
'<span class="' + className + '-text">Title 1.3.1</span>',
'</a>',
'</li>',
'</ol>',
'</li>',
'</ol>',
'</li>',
'<li class="' + className + '-item ' + className + '-level-1">',
'<a class="' + className + '-link" href="#title_2">',
(listNumber ? '<span class="' + className + '-number">2.</span> ' : ''),
'<span class="' + className + '-text">Title 2</span>',
'</a>',
'<ol class="' + className + '-child">',
'<li class="' + className + '-item ' + className + '-level-2">',
'<a class="' + className + '-link" href="#title_2_1">',
(listNumber ? '<span class="' + className + '-number">2.1.</span> ' : ''),
'<span class="' + className + '-text">Title 2.1</span>',
'</a>',
'</li>',
'</ol>',
'</li>',
'</ol>'
].join('');
return result;
};
it('default', function(){
genResult().should.eql(toc(html));
});
it('class', function(){
var options = {
class: 'foo'
};
genResult(options).should.eql(toc(html, options));
});
it('list_number', function(){
var options = {
list_number: false
};
genResult(options).should.eql(toc(html, options));
});
});
|
this is file 340
|
// Generated by CoffeeScript 1.9.1
(function() {
var XMLDeclaration, XMLNode, create, isObject,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
create = require('lodash/object/create');
isObject = require('lodash/lang/isObject');
XMLNode = require('./XMLNode');
module.exports = XMLDeclaration = (function(superClass) {
extend(XMLDeclaration, superClass);
function XMLDeclaration(parent, version, encoding, standalone) {
var ref;
XMLDeclaration.__super__.constructor.call(this, parent);
if (isObject(version)) {
ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
}
if (!version) {
version = '1.0';
}
this.version = this.stringify.xmlVersion(version);
if (encoding != null) {
this.encoding = this.stringify.xmlEncoding(encoding);
}
if (standalone != null) {
this.standalone = this.stringify.xmlStandalone(standalone);
}
}
XMLDeclaration.prototype.toString = function(options, level) {
var indent, newline, offset, pretty, r, ref, ref1, ref2, space;
pretty = (options != null ? options.pretty : void 0) || false;
indent = (ref = options != null ? options.indent : void 0) != null ? ref : ' ';
offset = (ref1 = options != null ? options.offset : void 0) != null ? ref1 : 0;
newline = (ref2 = options != null ? options.newline : void 0) != null ? ref2 : '\n';
level || (level = 0);
space = new Array(level + offset + 1).join(indent);
r = '';
if (pretty) {
r += space;
}
r += '<?xml';
r += ' version="' + this.version + '"';
if (this.encoding != null) {
r += ' encoding="' + this.encoding + '"';
}
if (this.standalone != null) {
r += ' standalone="' + this.standalone + '"';
}
r += '?>';
if (pretty) {
r += newline;
}
return r;
};
return XMLDeclaration;
})(XMLNode);
}).call(this);
|
var Q = require('q');
var fs = require('graceful-fs');
var path = require('path');
var mout = require('mout');
var resolvers = require('./resolvers');
var createError = require('../util/createError');
function createInstance(decEndpoint, config, logger, registryClient) {
return getConstructor(decEndpoint.source, config, registryClient)
.spread(function (ConcreteResolver, source, fromRegistry) {
var decEndpointCopy = mout.object.pick(decEndpoint, ['name', 'target']);
decEndpointCopy.source = source;
// Signal if it was fetched from the registry
if (fromRegistry) {
decEndpoint.registry = true;
// If no name was specified, assume the name from the registry
if (!decEndpointCopy.name) {
decEndpointCopy.name = decEndpoint.name = decEndpoint.source;
}
}
return new ConcreteResolver(decEndpointCopy, config, logger);
});
}
function getConstructor(source, config, registryClient) {
var absolutePath,
promise;
// Git case: git git+ssh, git+http, git+https
// .git at the end (probably ssh shorthand)
// git@ at the start
if (/^git(\+(ssh|https?))?:\/\//i.test(source) || /\.git\/?$/i.test(source) || /^git@/i.test(source)) {
source = source.replace(/^git\+/, '');
return Q.fcall(function () {
// If it's a GitHub repository, return the specialized resolver
if (resolvers.GitHub.getOrgRepoPair(source)) {
return [resolvers.GitHub, source];
}
return [resolvers.GitRemote, source];
});
}
// URL case
if (/^https?:\/\//i.exec(source)) {
return Q.fcall(function () {
return [resolvers.Url, source];
});
}
// Below we try a series of async tests to guess the type of resolver to use
// If a step was unable to guess the resolver, it throws an error
// If a step was able to guess the resolver, it resolves with a function
// That function returns a promise that will resolve with the concrete type
// If source is ./ or ../ or an absolute path
absolutePath = path.resolve(config.cwd, source);
if (/^\.\.?[\/\\]/.test(source) || /^~\//.test(source) || path.normalize(source).replace(/[\/\\]+$/, '') === absolutePath) {
promise = Q.nfcall(fs.stat, path.join(absolutePath, '.git'))
.then(function (stats) {
if (stats.isDirectory()) {
return function () {
return Q.resolve([resolvers.GitFs, absolutePath]);
};
}
throw new Error('Not a Git repository');
})
// If not, check if source is a valid file/folder
.fail(function () {
return Q.nfcall(fs.stat, absolutePath)
.then(function () {
return function () {
return Q.resolve([resolvers.Fs, absolutePath]);
};
});
});
} else {
promise = Q.reject(new Error('Not an absolute or relative file'));
}
return promise
// Check if is a shorthand and expand it
.fail(function (err) {
var parts;
// Skip ssh and/or URL with auth
if (/[:@]/.test(source)) {
throw err;
}
// Ensure exactly only one "/"
parts = source.split('/');
if (parts.length === 2) {
source = mout.string.interpolate(config.shorthandResolver, {
shorthand: source,
owner: parts[0],
package: parts[1]
});
return function () {
return getConstructor(source, config, registryClient);
};
}
throw err;
})
// As last resort, we try the registry
.fail(function (err) {
if (!registryClient) {
throw err;
}
return function () {
return Q.nfcall(registryClient.lookup.bind(registryClient), source)
.then(function (entry) {
if (!entry) {
throw createError('Package ' + source + ' not found', 'ENOTFOUND');
}
// TODO: Handle entry.type.. for now it's only 'alias'
// When we got published packages, this needs to be adjusted
source = entry.url;
return getConstructor(source, config, registryClient)
.spread(function (ConcreteResolver, source) {
return [ConcreteResolver, source, true];
});
});
};
})
// If we got the function, simply call and return
.then(function (func) {
return func();
// Finally throw a meaningful error
}, function () {
throw createError('Could not find appropriate resolver for ' + source, 'ENORESOLVER');
});
}
function clearRuntimeCache() {
mout.object.values(resolvers).forEach(function (ConcreteResolver) {
ConcreteResolver.clearRuntimeCache();
});
}
module.exports = createInstance;
module.exports.getConstructor = getConstructor;
module.exports.clearRuntimeCache = clearRuntimeCache;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/**
* Transport postMessage events from the fxa-content-server to the embedding
* webview.
*/
"use strict";
function handleAccountsCommand(evt) {
webkit.messageHandlers.accountsCommandHandler.postMessage({ type: evt.type, detail: evt.detail });
};
window.addEventListener("FirefoxAccountsCommand", handleAccountsCommand);
|
Prism.languages.wasm = {
'comment': [
/\(;[\s\S]*?;\)/,
{
pattern: /;;.*/,
greedy: true
}
],
'string': {
pattern: /"(?:\\[\s\S]|[^"\\])*"/,
greedy: true
},
'keyword': [
{
pattern: /\b(?:align|offset)=/,
inside: {
'operator': /=/
}
},
{
pattern: /\b(?:(?:f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))?|memory\.(?:grow|size))\b/,
inside: {
'punctuation': /\./
}
},
/\b(?:anyfunc|block|br(?:_if|_table)?|call(?:_indirect)?|data|drop|elem|else|end|export|func|get_(?:global|local)|global|if|import|local|loop|memory|module|mut|nop|offset|param|result|return|select|set_(?:global|local)|start|table|tee_local|then|type|unreachable)\b/
],
'variable': /\$[\w!#$%&'*+\-./:<=>?@\\^_`|~]+/i,
'number': /[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/,
'punctuation': /[()]/
};
|
//// [generatorTypeCheck6.ts]
function* g1(): number { }
//// [generatorTypeCheck6.js]
function* g1() { }
|
import type * as namespace from "bar";
|
import getOuterSizes from './getOuterSizes';
import getOppositePlacement from './getOppositePlacement';
/**
* Get offsets to the popper
* @method
* @memberof Popper.Utils
* @param {Object} position - CSS position the Popper will get applied
* @param {HTMLElement} popper - the popper element
* @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this)
* @param {String} placement - one of the valid placement options
* @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper
*/
export default function getPopperOffsets(popper, referenceOffsets, placement) {
placement = placement.split('-')[0];
// Get popper node sizes
const popperRect = getOuterSizes(popper);
// Add position, width and height to our offsets object
const popperOffsets = {
width: popperRect.width,
height: popperRect.height,
};
// depending by the popper placement we have to compute its offsets slightly differently
const isHoriz = ['right', 'left'].indexOf(placement) !== -1;
const mainSide = isHoriz ? 'top' : 'left';
const secondarySide = isHoriz ? 'left' : 'top';
const measurement = isHoriz ? 'height' : 'width';
const secondaryMeasurement = !isHoriz ? 'height' : 'width';
popperOffsets[mainSide] =
referenceOffsets[mainSide] +
referenceOffsets[measurement] / 2 -
popperRect[measurement] / 2;
if (placement === secondarySide) {
popperOffsets[secondarySide] =
referenceOffsets[secondarySide] - popperRect[secondaryMeasurement];
} else {
popperOffsets[secondarySide] =
referenceOffsets[getOppositePlacement(secondarySide)];
}
return popperOffsets;
}
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/General/BoldItalic/MathOperators.js
*
* Copyright (c) 2009-2016 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXGeneral-bold-italic"],{8706:[686,10,559,44,559],8722:[297,-209,606,51,555]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/General/BoldItalic/MathOperators.js");
|
/* YUI 3.9.1 (build 5852) Copyright 2013 Yahoo! Inc. http://yuilibrary.com/license/ */
YUI.add('autocomplete-highlighters', function (Y, NAME) {
/**
Provides pre-built result highlighters for AutoComplete.
@module autocomplete
@submodule autocomplete-highlighters
@class AutoCompleteHighlighters
@static
**/
var YArray = Y.Array,
Highlight = Y.Highlight,
Highlighters = Y.mix(Y.namespace('AutoCompleteHighlighters'), {
// -- Public Methods -------------------------------------------------------
/**
Highlights any individual query character that occurs anywhere in a result.
Case-insensitive.
@method charMatch
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
charMatch: function (query, results, caseSensitive) {
// The caseSensitive parameter is only intended for use by
// charMatchCase(). It's intentionally undocumented.
var queryChars = YArray.unique((caseSensitive ? query :
query.toLowerCase()).split(''));
return YArray.map(results, function (result) {
return Highlight.all(result.text, queryChars, {
caseSensitive: caseSensitive
});
});
},
/**
Case-sensitive version of `charMatch()`.
@method charMatchCase
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
charMatchCase: function (query, results) {
return Highlighters.charMatch(query, results, true);
},
/**
Highlights the complete query as a phrase anywhere within a result. Case-
insensitive.
@method phraseMatch
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
phraseMatch: function (query, results, caseSensitive) {
// The caseSensitive parameter is only intended for use by
// phraseMatchCase(). It's intentionally undocumented.
return YArray.map(results, function (result) {
return Highlight.all(result.text, [query], {
caseSensitive: caseSensitive
});
});
},
/**
Case-sensitive version of `phraseMatch()`.
@method phraseMatchCase
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
phraseMatchCase: function (query, results) {
return Highlighters.phraseMatch(query, results, true);
},
/**
Highlights the complete query as a phrase at the beginning of a result.
Case-insensitive.
@method startsWith
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
startsWith: function (query, results, caseSensitive) {
// The caseSensitive parameter is only intended for use by
// startsWithCase(). It's intentionally undocumented.
return YArray.map(results, function (result) {
return Highlight.all(result.text, [query], {
caseSensitive: caseSensitive,
startsWith : true
});
});
},
/**
Case-sensitive version of `startsWith()`.
@method startsWithCase
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
startsWithCase: function (query, results) {
return Highlighters.startsWith(query, results, true);
},
/**
Highlights portions of results in which words from the query match either
whole words or parts of words in the result. Non-word characters like
whitespace and certain punctuation are ignored. Case-insensitive.
@method subWordMatch
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
subWordMatch: function (query, results, caseSensitive) {
// The caseSensitive parameter is only intended for use by
// subWordMatchCase(). It's intentionally undocumented.
var queryWords = Y.Text.WordBreak.getUniqueWords(query, {
ignoreCase: !caseSensitive
});
return YArray.map(results, function (result) {
return Highlight.all(result.text, queryWords, {
caseSensitive: caseSensitive
});
});
},
/**
Case-sensitive version of `subWordMatch()`.
@method subWordMatchCase
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
subWordMatchCase: function (query, results) {
return Highlighters.subWordMatch(query, results, true);
},
/**
Highlights individual words in results that are also in the query. Non-word
characters like punctuation are ignored. Case-insensitive.
@method wordMatch
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
wordMatch: function (query, results, caseSensitive) {
// The caseSensitive parameter is only intended for use by
// wordMatchCase(). It's intentionally undocumented.
return YArray.map(results, function (result) {
return Highlight.words(result.text, query, {
caseSensitive: caseSensitive
});
});
},
/**
Case-sensitive version of `wordMatch()`.
@method wordMatchCase
@param {String} query Query to match
@param {Array} results Results to highlight
@return {Array} Highlighted results
@static
**/
wordMatchCase: function (query, results) {
return Highlighters.wordMatch(query, results, true);
}
});
}, '3.9.1', {"requires": ["array-extras", "highlight-base"]});
|
this is file 112
|
define([
"../var/support"
], function( support ) {
(function() {
var fragment = document.createDocumentFragment(),
div = document.createElement("div"),
input = document.createElement("input");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a>";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName( "tbody" ).length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone =
document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
input.type = "checkbox";
input.checked = true;
fragment.appendChild( input );
support.appendChecked = input.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE6-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
// #11217 - WebKit loses check when the name is after the checked attribute
fragment.appendChild( div );
div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
support.noCloneEvent = true;
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Execute the test only if not already executed in another module.
if (support.deleteExpando == null) {
// Support: IE<9
support.deleteExpando = true;
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
}
// Null elements to avoid leaks in IE.
fragment = div = input = null;
})();
return support;
});
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"SHORTMONTH": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"STANDALONEMONTH": [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "en-jm",
"localeID": "en_JM",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Custom binding for the Identity API.
var binding = require('binding').Binding.create('identity');
binding.registerCustomHook(function(binding, id, contextType) {
var apiFunctions = binding.apiFunctions;
var identity = binding.compiledApi;
apiFunctions.setHandleRequest('getRedirectURL', function(path) {
if (path === null || path === undefined)
path = '/';
else
path = String(path);
if (path[0] != '/')
path = '/' + path;
return 'https://' + id + '.chromiumapp.org' + path;
});
});
exports.binding = binding.generate();
|
suite('color-handler', function() {
test('parse colors', function() {
assert.deepEqual(parseColor(' ReD '), [255, 0, 0, 1]);
assert.deepEqual(parseColor(' magenta'), [255, 0, 255, 1]);
assert.deepEqual(parseColor('transparent'), [0, 0, 0, 0]);
assert.deepEqual(parseColor('#0f0'), [0, 255, 0, 1]);
assert.deepEqual(parseColor('rgb(0,10,20)'), [0, 10, 20, 1]);
assert.deepEqual(parseColor('rgba(65,40,20,0.2)'), [13, 8, 4, 0.2]);
assert.deepEqual(parseColor('hsl(120, 100%, 50%)'), [0, 255, 0, 1]);
});
test('invalid colors fail to parse', function() {
assert.isUndefined(parseColor(''));
assert.isUndefined(parseColor('bananayellow'));
assert.isUndefined(parseColor('rgb(10, 20, 30, 40)'));
});
test('color interpolation', function() {
assert.equal(webAnimations1.propertyInterpolation('color', '#00aa11', '#aa00bb')(0.2), 'rgba(34,136,51,1)');
assert.equal(webAnimations1.propertyInterpolation('color', 'transparent', '#004488')(0), 'transparent');
assert.equal(webAnimations1.propertyInterpolation('color', 'transparent', '#004488')(0.5), 'rgba(0,68,136,0.500)');
assert.equal(webAnimations1.propertyInterpolation('color', 'red', 'green')(2), 'rgba(0,255,0,1)');
assert.equal(webAnimations1.propertyInterpolation('color', 'red', 'green')(-1), 'rgba(255,0,0,1)');
});
});
|
// Copyright 2007 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview This class lives on the main thread and takes care of incoming
* logger commands from a worker thread.
*
* @author arv@google.com (Erik Arvidsson)
*/
goog.provide('goog.gears.LoggerServer');
goog.require('goog.Disposable');
goog.require('goog.debug.Logger');
goog.require('goog.debug.Logger.Level');
goog.require('goog.gears.Worker.EventType');
/**
* Creates an object that listens to incoming LOG commands and forwards them
* to a goog.debug.Logger
* @param {goog.gears.Worker} worker The worker thread that
* we are managing the loggers on.
* @param {number} logCommandId The command id used for logging.
* @param {string=} opt_workerName The name of the worker. If present then this
* is added to the log records and to exceptions as {@code workerName}.
* @constructor
* @extends {goog.Disposable}
*/
goog.gears.LoggerServer = function(worker, logCommandId, opt_workerName) {
goog.Disposable.call(this);
/**
* The command id to use to receive log commands from the workers.
* @type {number}
* @private
*/
this.logCommandId_ = logCommandId;
/**
* The worker thread object.
* @type {goog.gears.Worker}
* @private
*/
this.worker_ = worker;
/**
* The name of the worker.
* @type {string}
* @private
*/
this.workerName_ = opt_workerName || '';
/**
* Message prefix containing worker ID.
* @type {string}
* @private
*/
this.msgPrefix_ = '[' + worker.getId() + '] ';
// Listen for command's from the worker to handle the log command.
worker.addEventListener(goog.gears.Worker.EventType.COMMAND,
this.onCommand_, false, this);
};
goog.inherits(goog.gears.LoggerServer, goog.Disposable);
/**
* Whether to show the ID of the worker as a prefix to the shown message.
* @type {boolean}
* @private
*/
goog.gears.LoggerServer.prototype.useMessagePrefix_ = true;
/**
* @return {boolean} * Whether to show the ID of the worker as a prefix to the
* shown message.
*/
goog.gears.LoggerServer.prototype.getUseMessagePrefix = function() {
return this.useMessagePrefix_;
};
/**
* Whether to prefix the message text with the worker ID.
* @param {boolean} b True to prefix the messages.
*/
goog.gears.LoggerServer.prototype.setUseMessagePrefix = function(b) {
this.useMessagePrefix_ = b;
};
/**
* Event handler for the command event of the thread.
* @param {goog.gears.WorkerEvent} e The command event sent by the the
* worker thread.
* @private
*/
goog.gears.LoggerServer.prototype.onCommand_ = function(e) {
var message = /** @type {Array} */ (e.message);
var commandId = message[0];
if (commandId == this.logCommandId_) {
var params = message[1];
var i = 0;
var name = params[i++];
// The old version sent the level name as well. We no longer need it so
// we just step over it.
if (params.length == 5) {
i++;
}
var levelValue = params[i++];
var level = goog.debug.Logger.Level.getPredefinedLevelByValue(levelValue);
if (level) {
var msg = (this.useMessagePrefix_ ? this.msgPrefix_ : '') + params[i++];
var exception = params[i++];
var logger = goog.debug.Logger.getLogger(name);
var logRecord = logger.getLogRecord(level, msg, exception);
if (this.workerName_) {
logRecord.workerName = this.workerName_;
// Note that we happen to know that getLogRecord just references the
// exception object so we can continue to modify it as needed.
if (exception) {
exception.workerName = this.workerName_;
}
}
logger.logRecord(logRecord);
}
// ignore others for now
}
};
/** @override */
goog.gears.LoggerServer.prototype.disposeInternal = function() {
goog.gears.LoggerServer.superClass_.disposeInternal.call(this);
// Remove the event listener.
this.worker_.removeEventListener(
goog.gears.Worker.EventType.COMMAND, this.onCommand_, false, this);
this.worker_ = null;
};
|
//! moment.js locale configuration
//! locale : Tamil [ta]
//! author : Arjunkumar Krishnamoorthy : https://github.com/tk120404
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
var symbolMap = {
'1': '௧',
'2': '௨',
'3': '௩',
'4': '௪',
'5': '௫',
'6': '௬',
'7': '௭',
'8': '௮',
'9': '௯',
'0': '௦'
};
var numberMap = {
'௧': '1',
'௨': '2',
'௩': '3',
'௪': '4',
'௫': '5',
'௬': '6',
'௭': '7',
'௮': '8',
'௯': '9',
'௦': '0'
};
var ta = moment.defineLocale('ta', {
months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'),
weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'),
weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'),
weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'),
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY, HH:mm',
LLLL : 'dddd, D MMMM YYYY, HH:mm'
},
calendar : {
sameDay : '[இன்று] LT',
nextDay : '[நாளை] LT',
nextWeek : 'dddd, LT',
lastDay : '[நேற்று] LT',
lastWeek : '[கடந்த வாரம்] dddd, LT',
sameElse : 'L'
},
relativeTime : {
future : '%s இல்',
past : '%s முன்',
s : 'ஒரு சில விநாடிகள்',
m : 'ஒரு நிமிடம்',
mm : '%d நிமிடங்கள்',
h : 'ஒரு மணி நேரம்',
hh : '%d மணி நேரம்',
d : 'ஒரு நாள்',
dd : '%d நாட்கள்',
M : 'ஒரு மாதம்',
MM : '%d மாதங்கள்',
y : 'ஒரு வருடம்',
yy : '%d ஆண்டுகள்'
},
ordinalParse: /\d{1,2}வது/,
ordinal : function (number) {
return number + 'வது';
},
preparse: function (string) {
return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) {
return numberMap[match];
});
},
postformat: function (string) {
return string.replace(/\d/g, function (match) {
return symbolMap[match];
});
},
// refer http://ta.wikipedia.org/s/1er1
meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/,
meridiem : function (hour, minute, isLower) {
if (hour < 2) {
return ' யாமம்';
} else if (hour < 6) {
return ' வைகறை'; // வைகறை
} else if (hour < 10) {
return ' காலை'; // காலை
} else if (hour < 14) {
return ' நண்பகல்'; // நண்பகல்
} else if (hour < 18) {
return ' எற்பாடு'; // எற்பாடு
} else if (hour < 22) {
return ' மாலை'; // மாலை
} else {
return ' யாமம்';
}
},
meridiemHour : function (hour, meridiem) {
if (hour === 12) {
hour = 0;
}
if (meridiem === 'யாமம்') {
return hour < 2 ? hour : hour + 12;
} else if (meridiem === 'வைகறை' || meridiem === 'காலை') {
return hour;
} else if (meridiem === 'நண்பகல்') {
return hour >= 10 ? hour : hour + 12;
} else {
return hour + 12;
}
},
week : {
dow : 0, // Sunday is the first day of the week.
doy : 6 // The week that contains Jan 1st is the first week of the year.
}
});
return ta;
})));
|
'use strict';/*!
* This is a `i18n` language object.
*
* Korean
*
* @author
* Jalios (Twitter: @Jalios)
* Sascha 'SoftCreatR' Greuel
*
* @see core/i18n.js
*/
(function (exports) {
if (exports.ko === undefined) {
exports.ko = {
'mejs.plural-form': 0,
'mejs.download-file': '파일 다운로드',
'mejs.install-flash': 'Flash Player가 활성화되거나 설치되지 않은 브라우저를 사용 중입니다. 플래시 플레이어 플러그인을 켜거나 https://get.adobe.com/flashplayer/에서 최신 버전을 다운로드하십시오.',
'mejs.fullscreen': '전체화면',
'mejs.play': '작동',
'mejs.pause': '정지',
'mejs.time-slider': '시간 슬라이더',
'mejs.time-help-text': '1초 전진하려면 좌/우측 화살표를 사용하시고 10초 전진하려면 위/아래 화살표를 사용하세요.',
'mejs.live-broadcast' : '생방송',
'mejs.volume-help-text': '볼륨을 높이거나 낮추려면 위/아래 화살표를 이용하세요.',
'mejs.unmute': '음소거 해제',
'mejs.mute': '말 없는',
'mejs.volume-slider': '볼륨 슬라이더',
'mejs.video-player': '비디오 플레이어',
'mejs.audio-player': '오디오 플레이어',
'mejs.captions-subtitles': '캡션/자막',
'mejs.captions-chapters': '챕터',
'mejs.none': '없음',
'mejs.afrikaans': '아프리칸스어',
'mejs.albanian': '알바니아',
'mejs.arabic': '아랍어',
'mejs.belarusian': '벨로루시 어',
'mejs.bulgarian': '불가리아',
'mejs.catalan': '카탈로니아 어',
'mejs.chinese': '중국어',
'mejs.chinese-simplified': '중국어 (간체)',
'mejs.chinese-traditional': '중국어 (번체)',
'mejs.croatian': '크로아티아어',
'mejs.czech': '체코 어',
'mejs.danish': '덴마크어',
'mejs.dutch': '네덜란드어',
'mejs.english': '영어',
'mejs.estonian': '에스토니아',
'mejs.filipino': '필리핀',
'mejs.finnish': '핀란드어',
'mejs.french': '프랑스어',
'mejs.galician': '갈리시아인',
'mejs.german': '독일어',
'mejs.greek': '그리스어',
'mejs.haitian-creole': '아이티 크리올',
'mejs.hebrew': '히브리어',
'mejs.hindi': '힌디어',
'mejs.hungarian': '헝가리어',
'mejs.icelandic': '아이슬란드 어',
'mejs.indonesian': '인도네시아어',
'mejs.irish': '아일랜드어',
'mejs.italian': '이탈리아어',
'mejs.japanese': '일본어',
'mejs.korean': '한국어',
'mejs.latvian': '라트비아어',
'mejs.lithuanian': '리투아니아어',
'mejs.macedonian': '마케도니아인',
'mejs.malay': '말레이',
'mejs.maltese': '몰타어',
'mejs.norwegian': '노르웨이어',
'mejs.persian': '페르시아어',
'mejs.polish': '폴란드어',
'mejs.portuguese': '포르투갈어',
'mejs.romanian': '루마니아어',
'mejs.russian': '러시아어',
'mejs.serbian': '세르비아어',
'mejs.slovak': '슬로바키아어',
'mejs.slovenian': '슬로베니아어',
'mejs.spanish': '스페인어',
'mejs.swahili': '스와힐리어',
'mejs.swedish': '스웨덴어',
'mejs.tagalog': '타갈로그어',
'mejs.thai': '태국어',
'mejs.turkish': '터키어',
'mejs.ukrainian': '우크라이나어',
'mejs.vietnamese': '베트남인',
'mejs.welsh': '웨일스 어',
'mejs.yiddish': '이디시어'
};
}
})(mejs.i18n);
|
import Ember from 'ember';
export function isNot(params/*, hash*/) {
return !params;
}
export default Ember.HTMLBars.makeBoundHelper(isNot);
|
'use strict';
var path = require('path');
var fs = require('graceful-fs');
var stripBom = require('strip-bom');
var stripBomStream = require('strip-bom-stream');
var File = require('vinyl');
exports.read = function (pth, opts, cb) {
opts = opts || {};
if (typeof opts === 'function') {
cb = opts;
opts = {};
}
var cwd = opts.cwd || process.cwd();
var base = opts.base || cwd;
pth = path.resolve(cwd, pth);
fs.stat(pth, function (err, stat) {
if (err) {
cb(err);
return;
}
var file = new File({
cwd: cwd,
base: base,
path: pth,
stat: stat
});
if (opts.read === false) {
cb(null, file);
return;
}
if (opts.buffer === false) {
file.contents = fs.createReadStream(pth).pipe(stripBomStream());
cb(null, file);
return;
}
fs.readFile(pth, function (err, buf) {
if (err) {
cb(err);
return;
}
file.contents = stripBom(buf);
cb(null, file);
});
});
};
exports.readSync = function (pth, opts) {
opts = opts || {};
var cwd = opts.cwd || process.cwd();
var base = opts.base || cwd;
pth = path.resolve(cwd, pth);
var contents;
if (opts.read !== false) {
contents = opts.buffer === false ?
fs.createReadStream(pth).pipe(stripBomStream()) :
stripBom(fs.readFileSync(pth));
}
return new File({
cwd: cwd,
base: base,
path: pth,
stat: fs.statSync(pth),
contents: contents
});
};
|
/**
* `editor` type prompt
*/
var util = require('util');
var chalk = require('chalk');
var ExternalEditor = require('external-editor');
var Base = require('./base');
var observe = require('../utils/events');
var rx = require('rx-lite-aggregates');
/**
* Module exports
*/
module.exports = Prompt;
/**
* Constructor
*/
function Prompt() {
return Base.apply(this, arguments);
}
util.inherits(Prompt, Base);
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
Prompt.prototype._run = function (cb) {
this.done = cb;
this.editorResult = new rx.Subject();
// Open Editor on "line" (Enter Key)
var events = observe(this.rl);
this.lineSubscription = events.line.forEach(this.startExternalEditor.bind(this));
// Trigger Validation when editor closes
var validation = this.handleSubmitEvents(this.editorResult);
validation.success.forEach(this.onEnd.bind(this));
validation.error.forEach(this.onError.bind(this));
// Prevents default from being printed on screen (can look weird with multiple lines)
this.currentText = this.opt.default;
this.opt.default = null;
// Init
this.render();
return this;
};
/**
* Render the prompt to screen
* @return {Prompt} self
*/
Prompt.prototype.render = function (error) {
var bottomContent = '';
var message = this.getQuestion();
if (this.status === 'answered') {
message += chalk.dim('Received');
} else {
message += chalk.dim('Press <enter> to launch your preferred editor.');
}
if (error) {
bottomContent = chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
};
/**
* Launch $EDITOR on user press enter
*/
Prompt.prototype.startExternalEditor = function () {
// Pause Readline to prevent stdin and stdout from being modified while the editor is showing
this.rl.pause();
ExternalEditor.editAsync(this.currentText, this.endExternalEditor.bind(this));
};
Prompt.prototype.endExternalEditor = function (error, result) {
this.rl.resume();
if (error) {
this.editorResult.onError(error);
} else {
this.editorResult.onNext(result);
}
};
Prompt.prototype.onEnd = function (state) {
this.editorResult.dispose();
this.lineSubscription.dispose();
this.answer = state.value;
this.status = 'answered';
// Re-render prompt
this.render();
this.screen.done();
this.done(this.answer);
};
Prompt.prototype.onError = function (state) {
this.render(state.isValid);
};
|
x != y
|
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
export default baseProperty;
|
var uniqs = require('./');
var util = require('util');
var assert = require('assert');
var foo = { foo: 23 };
[
[ [[2, 1, 1], [2, 3, 3, 4], [4, 3, 2]], [2, 1, 3, 4] ],
[ [3, 2, 2, [1, 1, 2]], [3, 2, 1] ],
[ [[2, 2, 3, "a", 3, 1, foo, foo, "a" ]], [ 2, 3, "a", 1, foo ] ],
[ [23], [23] ],
[ [], [] ],
[ [[]], [] ],
[ [[null], null], [null] ]
]
.forEach(function(t) {
var args = t[0].map(JSON.stringify);
assert.deepEqual(uniqs.apply(this, t[0]), t[1],
util.format('✘ uniqs(%s) !== %j', args, t[1])
);
console.log('✔ uniqs(%s) == %j', args, t[1]);
});
|
//! moment.js locale configuration
//! locale : Estonian [et]
//! author : Henry Kehlmann : https://github.com/madhenry
//! improvements : Illimar Tambek : https://github.com/ragulka
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
function processRelativeTime(number, withoutSuffix, key, isFuture) {
var format = {
's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'],
'm' : ['ühe minuti', 'üks minut'],
'mm': [number + ' minuti', number + ' minutit'],
'h' : ['ühe tunni', 'tund aega', 'üks tund'],
'hh': [number + ' tunni', number + ' tundi'],
'd' : ['ühe päeva', 'üks päev'],
'M' : ['kuu aja', 'kuu aega', 'üks kuu'],
'MM': [number + ' kuu', number + ' kuud'],
'y' : ['ühe aasta', 'aasta', 'üks aasta'],
'yy': [number + ' aasta', number + ' aastat']
};
if (withoutSuffix) {
return format[key][2] ? format[key][2] : format[key][1];
}
return isFuture ? format[key][0] : format[key][1];
}
var et = moment.defineLocale('et', {
months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'),
monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),
weekdays : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'),
weekdaysShort : 'P_E_T_K_N_R_L'.split('_'),
weekdaysMin : 'P_E_T_K_N_R_L'.split('_'),
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'DD.MM.YYYY',
LL : 'D. MMMM YYYY',
LLL : 'D. MMMM YYYY H:mm',
LLLL : 'dddd, D. MMMM YYYY H:mm'
},
calendar : {
sameDay : '[Täna,] LT',
nextDay : '[Homme,] LT',
nextWeek : '[Järgmine] dddd LT',
lastDay : '[Eile,] LT',
lastWeek : '[Eelmine] dddd LT',
sameElse : 'L'
},
relativeTime : {
future : '%s pärast',
past : '%s tagasi',
s : processRelativeTime,
m : processRelativeTime,
mm : processRelativeTime,
h : processRelativeTime,
hh : processRelativeTime,
d : processRelativeTime,
dd : '%d päeva',
M : processRelativeTime,
MM : processRelativeTime,
y : processRelativeTime,
yy : processRelativeTime
},
ordinalParse: /\d{1,2}\./,
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return et;
}));
|
'use strict';
var KEYWORDS = [
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'enum',
'format',
'const'
];
module.exports = function (metaSchema, keywordsJsonPointers) {
for (var i=0; i<keywordsJsonPointers.length; i++) {
metaSchema = JSON.parse(JSON.stringify(metaSchema));
var segments = keywordsJsonPointers[i].split('/');
var keywords = metaSchema;
var j;
for (j=1; j<segments.length; j++)
keywords = keywords[segments[j]];
for (j=0; j<KEYWORDS.length; j++) {
var key = KEYWORDS[j];
var schema = keywords[key];
if (schema) {
keywords[key] = {
anyOf: [
schema,
{ $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/$data.json#' }
]
};
}
}
}
return metaSchema;
};
|
/* 설문 참여 함수 */
function doPoll(fo_obj) {
var checkcount = new Array();
var item = new Array();
for(var i=0;i<fo_obj.length;i++) {
var obj = fo_obj[i];
if(obj.nodeName != 'INPUT') continue;
var name = obj.name;
if(name.indexOf('checkcount')>-1) {
var t = name.split('_');
var poll_srl_index = parseInt(t[1],10);
checkcount[poll_srl_index] = obj.value;
item[poll_srl_index] = new Array();
} else if(name.indexOf('item_')>-1) {
var t = name.split('_');
var poll_srl = parseInt(t[1],10);
var poll_srl_index = parseInt(t[2],10);
if(obj.checked == true) item[poll_srl_index][item[poll_srl_index].length] = obj.value;
}
}
var poll_srl_indexes = "";
for(var poll_srl_index in checkcount) {
if(!checkcount.hasOwnProperty(poll_srl_index)) continue;
var count = checkcount[poll_srl_index];
var items = item[poll_srl_index];
if(items.length < 1 || count < items.length) {
alert(poll_alert_lang);
return false;
}
poll_srl_indexes += items.join(',')+',';
}
fo_obj.poll_srl_indexes.value = poll_srl_indexes;
fo_obj.submit();
}
jQuery(function($){
/* View poll result */
$('._poll_result').click(function(){
var cls = $(this).attr('class'), srl, skin;
try{
srl = cls.match(/\b_srl_(\d+)\b/)[1];
skin = cls.match(/\b_skin_(.+?)\b/)[1];
}catch(e){ };
if(!srl) return false;
if(!skin) skin = 'default';
function on_complete(ret) {
var $poll = $('#poll_'+srl), width;
width = $poll.width();
$poll.html(ret['tpl']);
$poll.width(width);
}
exec_xml(
'poll', // module
'procPollViewResult', // act
{poll_srl:srl, skin:skin}, // parameters
on_complete,
['error','message','tpl']
);
return false;
});
});
|
/*
YUI 3.17.1 (build 0eb5a52)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('button-group', function (Y, NAME) {
/**
* A Widget to create groups of buttons
*
* @module button-group
* @since 3.5.0
*/
var CONTENT_BOX = "contentBox",
CLICK_EVENT = "click",
CLASS_NAMES = Y.ButtonCore.CLASS_NAMES;
/**
* Creates a ButtonGroup
*
* @class ButtonGroup
* @extends Widget
* @param config {Object} Configuration object
* @constructor
*/
function ButtonGroup() {
ButtonGroup.superclass.constructor.apply(this, arguments);
}
/* ButtonGroup extends Widget */
Y.ButtonGroup = Y.extend(ButtonGroup, Y.Widget, {
/**
* @method renderUI
* @description Creates a visual representation of the widget based on existing parameters.
* @public
*/
renderUI: function() {
this.getButtons().plug(Y.Plugin.Button);
},
/**
* @method bindUI
* @description Hooks up events for the widget
* @public
*/
bindUI: function() {
var group = this,
cb = group.get(CONTENT_BOX);
cb.delegate(CLICK_EVENT, group._handleClick, Y.ButtonGroup.BUTTON_SELECTOR, group);
group.after('disabledChange', group._afterDisabledChange);
},
_afterDisabledChange: function (e) {
this.getButtons().each(e.newVal
? Y.ButtonCore.prototype.disable
: Y.ButtonCore.prototype.enable
);
},
/**
* @method getButtons
* @description Returns all buttons inside this this button group
* @public
*/
getButtons: function() {
var cb = this.get(CONTENT_BOX);
return cb.all(Y.ButtonGroup.BUTTON_SELECTOR);
},
/**
* @method getSelectedButtons
* @description Returns all Y.Buttons instances that are selected
* @public
*/
getSelectedButtons: function() {
var group = this,
selected = [],
buttons = group.getButtons(),
selectedClass = ButtonGroup.CLASS_NAMES.SELECTED;
buttons.each(function(node){
if (node.hasClass(selectedClass)){
selected.push(node);
}
});
return selected;
},
/**
* @method getSelectedValues
* @description Returns the values of all Y.Button instances that are selected
* @public
*/
getSelectedValues: function() {
var selected = this.getSelectedButtons(),
values = [],
value;
Y.Array.each(selected, function(node){
value = node.getContent();
values.push(value);
});
return values;
},
/**
* @method _handleClick
* @description A delegated click handler for when any button is clicked in the content box
* @param e {Object} An event object
* @private
*/
_handleClick: function(e){
var group = this,
clickedNode = e.target.ancestor('.' + ButtonGroup.CLASS_NAMES.BUTTON, true),
type = group.get('type'),
selectedClass = ButtonGroup.CLASS_NAMES.SELECTED,
isSelected = clickedNode.hasClass(selectedClass),
buttons;
// TODO: Anything for 'push' groups?
if (type === 'checkbox') {
clickedNode.toggleClass(selectedClass, !isSelected);
/**
* @event selectionChange
* @description fires when any button in the group changes its checked status
* @param {Event} the event object. It contains an "originEvent" property
* linking to the original DOM event that triggered the selection change
*/
group.fire('selectionChange', {originEvent: e});
}
else if (type === 'radio' && !isSelected) {
buttons = group.getButtons(); // Todo: getSelectedButtons()? Need it to return an arraylist then.
buttons.removeClass(selectedClass);
clickedNode.addClass(selectedClass);
group.fire('selectionChange', {originEvent: e});
}
}
}, {
// Y.ButtonGroup static properties
/**
* The identity of the widget.
*
* @property NAME
* @type {String}
* @default 'buttongroup'
* @readOnly
* @protected
* @static
*/
NAME: 'buttongroup',
/**
* Static property used to define the default attribute configuration of
* the Widget.
*
* @property ATTRS
* @type {Object}
* @protected
* @static
*/
ATTRS: {
/**
* @attribute type
* @type String
*/
type: {
writeOnce: 'initOnly',
value: 'radio'
}
},
/**
* List of class names to use for ButtonGroups
*
* @property CLASS_NAMES
* @type {Object}
* @static
*/
CLASS_NAMES: CLASS_NAMES,
/**
* Selector used to find buttons inside a ButtonGroup
* @property BUTTON_SELECTOR
* @type {String}
*/
BUTTON_SELECTOR: "button, input[type=button], input[type=reset], input[type=submit], input[type=radio], input[type=checkbox]"
});
}, '3.17.1', {"requires": ["button-plugin", "cssbutton", "widget"]});
|
'use strict';
/**
* @ngdoc directive
* @name memekit.directive:piklor
* @description
* # colorSwatches
*/
angular.module('memekit')
.directive('colorSwatches', function () {
return {
//require: '?ngModel',
template: '<div>'+
'<ul>'+
'<li style="background-color: {{ color }}" ng-click="changeColor(color)" ng-repeat="color in swatch">'+
'</li>' +
'</ul>',
restrict: 'EA',
scope: {
field: '=',
element: '='
},
link: function(scope, element) {
scope.swatch = ["#000", "#333", "#666", "#ccc", "#fff","#1295D8","#FFB511","#005581","#72CDF4", "#FFD200", "#FFE552", "#FF6E1B", "#FF8F28", "#E44C9A", "#FEB2E0", "#00778B", "#00A3AD", "#7C7E7F", "#8F8884", "#BEB6AF", "#DBD5CD", "#B4975A"];
scope.changeColor = function(color) {
scope.element.fill = color;
};
}
};
});
|
// String.trim for old browsers
if(typeof(String.prototype.trim) === "undefined") {
String.prototype.trim = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
|
var users = require('./users')();
var Promise = require('bluebird');
var user_list = require('./user_list');
var helpers = require('./helpers')(users);
describe("record counting", function() {
beforeAll(function(done) {
helpers.reset()
.then(function() {
return helpers.populate(user_list);
})
.finally(function() {
done();
});
});
it("should return the correct number of records", function(done) {
users.list()
.then(function(records) {
expect(records.length).toEqual(user_list.length);
})
.catch(function(error) {
fail(error);
})
.finally(function() {
done();
});
});
});
|
/** @license ISC License (c) copyright 2018 original and current authors */
/** @author Dale Francis */
const curry = require('../core/curry')
const isSameType = require('../core/isSameType')
const isFunction = require('../core/isFunction')
const Async = require('../core/types').proxy('Async')
const toPromise = m => {
if(!isSameType(Async, m)) {
throw new TypeError('asyncToPromise: Argument must be an Async or a Function that returns an Async')
}
return m.toPromise()
}
/** asyncToPromise :: m e a -> Promise a e */
/** asyncToPromise :: (a -> m e b) -> a -> Promise b e */
function asyncToPromise(m) {
return isFunction(m)
? x => toPromise(m(x))
: toPromise(m)
}
module.exports = curry(asyncToPromise)
|
'use strict';
let ivm = require('isolated-vm');
let isolate = new ivm.Isolate;
let size1 = isolate.getHeapStatisticsSync();
let context = isolate.createContextSync();
let global = context.global;
global.setSync('global', global.derefInto());
let script = isolate.compileScriptSync(`
global.data = new Uint8Array(1024);
global.garbage = [];
for (let ii = 0; ii < 100000; ++ii) {
garbage.push(Math.random());
}
`);
script.runSync(context);
let size2 = isolate.getHeapStatisticsSync();
if (size1.total_heap_size === size2.total_heap_size) {
console.log('heap didn\'t increase?');
} else if (size2.externally_allocated_size !== 1024) {
console.log('externally allocated size is wrong');
} else {
console.log('pass');
}
|
// MAP DATA CACHE ///////////////////////////////////
// cache for map data tiles.
window.DataCache = function() {
this.REQUEST_CACHE_FRESH_AGE = 3*60; // if younger than this, use data in the cache rather than fetching from the server
this.REQUEST_CACHE_MAX_AGE = 5*60; // maximum cache age. entries are deleted from the cache after this time
//NOTE: characters are 16 bits (ECMAScript standard), so divide byte size by two for correct limit
if (L.Browser.mobile) {
// on mobile devices, smaller cache size
this.REQUEST_CACHE_MAX_ITEMS = 300; // if more than this many entries, expire early
this.REQUEST_CACHE_MAX_CHARS = 5000000/2; // or more than this total size
} else {
// but on desktop, allow more
this.REQUEST_CACHE_MAX_ITEMS = 1000; // if more than this many entries, expire early
this.REQUEST_CACHE_MAX_CHARS = 20000000/2; // or more than this total size
}
this._cache = {};
this._cacheCharSize = 0;
this._interval = undefined;
};
window.DataCache.prototype.store = function(qk,data,freshTime) {
// fixme? common behaviour for objects is that properties are kept in the order they're added
// this is handy, as it allows easy retrieval of the oldest entries for expiring
// however, this is not guaranteed by the standards, but all our supported browsers work this way
this.remove(qk);
var time = new Date().getTime();
if (freshTime===undefined) freshTime = this.REQUEST_CACHE_FRESH_AGE*1000;
var expire = time + freshTime;
var dataStr = JSON.stringify(data);
this._cacheCharSize += dataStr.length;
this._cache[qk] = { time: time, expire: expire, dataStr: dataStr };
};
window.DataCache.prototype.remove = function(qk) {
if (qk in this._cache) {
this._cacheCharSize -= this._cache[qk].dataStr.length;
delete this._cache[qk];
}
};
window.DataCache.prototype.get = function(qk) {
if (qk in this._cache) return JSON.parse(this._cache[qk].dataStr);
else return undefined;
};
window.DataCache.prototype.getTime = function(qk) {
if (qk in this._cache) return this._cache[qk].time;
else return 0;
};
window.DataCache.prototype.isFresh = function(qk) {
if (qk in this._cache) {
var d = new Date();
var t = d.getTime();
if (this._cache[qk].expire >= t) return true;
else return false;
}
return undefined;
};
window.DataCache.prototype.startExpireInterval = function(period) {
if (this._interval === undefined) {
var savedContext = this;
this._interval = setInterval (function() { savedContext.runExpire(); }, period*1000);
}
};
window.DataCache.prototype.stopExpireInterval = function() {
if (this._interval !== undefined) {
stopInterval (this._interval);
this._interval = undefined;
}
};
window.DataCache.prototype.runExpire = function() {
var d = new Date();
var t = d.getTime()-this.REQUEST_CACHE_MAX_AGE*1000;
var cacheSize = Object.keys(this._cache).length;
for(var qk in this._cache) {
// fixme? our MAX_SIZE test here assumes we're processing the oldest first. this relies
// on looping over object properties in the order they were added. this is true in most browsers,
// but is not a requirement of the standards
if (cacheSize > this.REQUEST_CACHE_MAX_ITEMS || this._cacheCharSize > this.REQUEST_CACHE_MAX_CHARS || this._cache[qk].time < t) {
this._cacheCharSize -= this._cache[qk].dataStr.length;
delete this._cache[qk];
cacheSize--;
}
}
};
window.DataCache.prototype.debug = function() {
//NOTE: ECMAScript strings use 16 bit chars (it's in the standard), so convert for bytes/Kb
return 'Cache: '+Object.keys(this._cache).length+' items, '+(this._cacheCharSize*2).toLocaleString()+' bytes ('+Math.ceil(this._cacheCharSize/512).toLocaleString()+'K)';
}
|
'use strict';
// Promises/A interop (not A+, but A+ interops with A, so it should work for conformant impls)
var Promise = (function () {
function Promise(future) {
this._future = future;
}
Promise.prototype.then = function (callback, errback) {
this._future.done(function (err, val) {
if (err) {
if (errback)
errback(err);
}
else {
if (callback)
callback(val);
}
});
};
return Promise;
})();
module.exports = Promise;
|
#!/usr/bin/env node
'use strict'
const Liftoff = require('liftoff')
const chalk = require('chalk')
const pkg = require('../package.json')
const argv = require('minimist')(process.argv.slice(2))
const sh = require('shelljs')
sh.config.silent = true
let cli = new Liftoff({
name: 'lego',
processTitle: 'lego',
configName: 'legofile',
extensions: { ".js":null, ".json":null },
v8flags: ['--harmony']
})
cli.launch({
configPath: argv.legofile
}, (env) => {
const cmd = argv._[0]
const minior = argv._[1]
let ret = {}
switch (cmd) {
case 'version':
console.log(cli.name, chalk.blue(pkg.version))
break
case 'init':
const branch = minior || 'master'
ret = sh.exec(`git clone git@github.com:tvrcgo/lego.git -b ${branch} lego-init`)
if (!ret.code) {
console.log(chalk.green('Lego init finished.'))
}
break
case undefined:
sh.exit(0)
break
default:
console.error(chalk.red('Unknow command', cmd))
sh.exit(0)
}
if (ret.code) {
console.error(chalk.red('[ERROR]', ret.stderr))
}
})
|
require('babel/register')
require('./app')
|
'use strict';
var ApiHandler = require('../handlers/api');
var api = new ApiHandler();
module.exports = function (app) {
app.get('/', api.getInfo);
};
|
export function isFiltered(action, filter) {
if (!filter) return false;
const { whitelist, blacklist } = filter;
return (
whitelist && !action.type.match(whitelist) ||
blacklist && action.type.match(blacklist)
);
}
|
/**
* @file cache manager
*/
const debug = require('debug')('cache');
const Queue = require('./queue');
const Singleton = require('./singleton');
class Cache {
/**
* @param {number} total cache count
* @constructor
*/
constructor(maxSize) {
maxSize = maxSize || 100;
/**
* cache stores in the form of 'key: value', key is the current URI, value is transfered html
* @type {Queue}
* @private
*/
this.cache = new Queue(maxSize)
}
clean() {
this.cache.clean();
}
put(key, val) {
debug(`put key: ${key}, val: ${val}`);
debug(`size: ${this.size()}`)
this.cache.push(key, val);
}
get(key) {
debug(`key has val: ${this.cache.get(key)}`);
return this.cache.get(key);
}
size() {
return this.cache.size();
}
}
const CacheSingleton = new Singleton(Cache);
module.exports = CacheSingleton;
|
import { connect } from 'react-redux'
import { clearError } from '../actions/Error'
import { setToken } from '../actions/AccessToken'
import { fetchAccountsIfNeeded } from '../actions/Accounts'
import AccessTokenInput from '../components/AccessTokenInput'
const mapStateToProps = state => ({
isFetching: state.accounts.isFetching,
shouldHide: state.accounts.items.length > 0
})
const mapDispatchToProps = dispatch => ({
onClick: (e, input) => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(clearError())
dispatch(setToken(input.value))
dispatch(fetchAccountsIfNeeded(input.value))
}
})
const AccessToken = connect(mapStateToProps, mapDispatchToProps)(AccessTokenInput)
export default AccessToken
|
/* globals $ */
$.fn.gallery = function (cols) {
this.addClass('gallery');
var cols = cols || 4;
var imageContainers = this.find('.image-container');
imageContainers.each(function(index){
if (!(index%cols)) {
$(this).addClass('clearfix');
}
});
var selectedContainer = this.children('.selected');
selectedContainer.css('display', 'none');
var galleryList = this.children('.gallery-list');
var allImages = $('img', galleryList);
var prevImage = $('.previous-image img', selectedContainer);
var currentImage = $('.current-image img', selectedContainer);
var nextImage = $('.next-image img', selectedContainer);
var disableBackgroundDiv = $('<div />');
this.append(disableBackgroundDiv);
var currentImageIndex;
var prevImageIndex;
var nextImageIndex;
galleryList.on('click', 'img', function () {
var clickedImage = $(this);
selectedContainer.css('display', '');
currentImageIndex = clickedImage.attr('data-info') | 0;
currentImageIndex -= 1;
prevImageIndex = currentImageIndex - 1;
if (prevImageIndex < 0) {
prevImageIndex = allImages.length-1;
}
nextImageIndex = currentImageIndex + 1;
if (nextImageIndex>=allImages.length) {
nextImageIndex = 0;
}
currentImage.attr('src', clickedImage.attr('src'));
prevImage.attr('src', $(allImages[prevImageIndex]).attr('src'));
nextImage.attr('src', $(allImages[nextImageIndex]).attr('src'));
galleryList.addClass('blurred');
disableBackgroundDiv.addClass('disabled-background');
});
currentImage.on('click', function () {
selectedContainer.css('display', 'none');
galleryList.removeClass('blurred');
disableBackgroundDiv.removeClass('disabled-background');
});
nextImage.on('click', function () {
currentImageIndex += 1;
nextImageIndex += 1;
prevImageIndex +=1;
if (nextImageIndex >= allImages.length) {
nextImageIndex = 0;
} else if (currentImageIndex >= allImages.length) {
currentImageIndex = 0;
} else if (prevImageIndex >= allImages.length) {
prevImageIndex = 0;
}
currentImage.attr('src', $(allImages[currentImageIndex]).attr('src'));
prevImage.attr('src', $(allImages[prevImageIndex]).attr('src'));
nextImage.attr('src', $(allImages[nextImageIndex]).attr('src'));
});
prevImage.on('click', function () {
currentImageIndex -= 1;
nextImageIndex -= 1;
prevImageIndex -=1;
if (prevImageIndex < 0) {
prevImageIndex = allImages.length - 1;
} else if (currentImageIndex < 0) {
currentImageIndex = allImages.length - 1;
} else if (nextImageIndex < 0) {
nextImageIndex = allImages.length - 1;
}
currentImage.attr('src', $(allImages[currentImageIndex]).attr('src'));
prevImage.attr('src', $(allImages[prevImageIndex]).attr('src'));
nextImage.attr('src', $(allImages[nextImageIndex]).attr('src'));
});
};
|
define(function(require, exports, module) {
var template = require('template');
var Http = require('Http');
$(document).ready(function() {
var DATA = {
pageNumber: 1,
type: 1
};
var ISLOADING = false;
function initTempl(data) {
var html = template('impression_list', { list: data });
$('#list').append(html);
};
function scroll() {
var docHeight = $(document).height();
var winHeight = $(window).height();
var scrTop = $('body').scrollTop();
if (scrTop >= docHeight - winHeight && ISLOADING) {
$('body').off('touchmove').append('<div class="g-loading-next"><p class="g-font-1_4em">正在加载,请稍后...</p></div>');
DATA.pageNumber++;
getArticleList(DATA);
}
}
function getArticleList(data) {
ISLOADING = false;
Http.getArticleList({
data: data,
success: function(data) {
initTempl(data.list);
$('.g-loading-next').remove();
if (!data.lastPage) {
ISLOADING = true;
$('body').on('touchmove', scroll);
}
}
})
};
getArticleList(DATA);
$('body').on('touchmove', scroll);
});
})
|
///
// TEAM PAYPR
///
var utils = require('../lib/utils.js');
var gameRunner = {
info: {
name: 'paypr',
style: 1,
handicap: 1,
state: {
test: "hello"
}
},
ai: (playerState, enemiesState, gameEnvironment) => {
var hasAmmo = playerState.ammo > 0;
var i;
var directionToAmmo;
var closestAmmoPos;
var enemiesLeft = 0;
var lastEnemy;
for(i=0; i<enemiesState.length; i++) {
if(enemiesState[i].isAlive) {
enemiesLeft++;
lastEnemy = enemiesState[i];
}
}
console.log("PAYPR");
if(!playerState.custom) {
playerState.custom = {};
}
//kill if possible
if (utils.canKill(playerState, enemiesState) && playerState.ammo) {
return 'shoot';
}
//find closest ammo direction
if (gameEnvironment.ammoPosition.length > 0) {
var minDist = Math.abs(utils.getDistance(playerState.position, gameEnvironment.ammoPosition[0]));
closestAmmoPos = gameEnvironment.ammoPosition[0];
directionToAmmo = utils.getDirection(
playerState.position,
gameEnvironment.ammoPosition[0]
);
for(i=1; i<gameEnvironment.ammoPosition.length; i++) {
console.log(gameEnvironment.ammoPosition[i]);
var testDist = Math.abs(utils.getDistance(playerState.position, gameEnvironment.ammoPosition[i]));
console.log("comparing " + testDist + " < " + minDist);
if(testDist < minDist) {
console.log("testDist smaller");
minDist = testDist;
directionToAmmo = utils.getDirection(
playerState.position,
gameEnvironment.ammoPosition[i]
);
closestAmmoPos = gameEnvironment.ammoPosition[i];
}
}
}
//check to see if there are any enemies moving within direction
var myX = playerState.position[0];
var myY = playerState.position[1];
var myPos = playerState.position;
var isUp = function(myPosition, enemyPosition) {
return myPosition[1] - enemyPosition[1] < 0;
};
var isDown = function(myPosition, enemyPosition) {
return !isUp(myPosition,enemyPosition);
};
var isLeft = function(myPosition, enemyPosition) {
return myPosition[0] - enemyPosition[0] > 0;
};
var isRight = function(myPosition, enemyPosition) {
return !isLeft(myPosition,enemyPosition);
};
for(i=0; i<enemiesState.length && hasAmmo; i++) {
var enemy = enemiesState[i];
var enPos = enemy.position;
var enDir = enemy.direction;
//if they are in the same lane and not moving out of it
//then point and FIRE
if(enPos[0] === myX && (enDir == 'north' || enDir == 'south')) {
if(isUp(myPos, enPos)) {
return 'north';
}
else return 'south';
}
if(enPos[1] === myY && (enDir == 'east' || enDir == 'west')) {
if(isLeft(myPos, enPos)) {
return 'west';
}
else return 'east';
}
/*
// is moving left and facing east if moving right and facing west
if( (enPos[0]+1 === myX && enDir == 'east') || (enPos[0]-1 === myX && enDir == 'west')) { //is left and moving east
if(isUp(enPos, myPos)) {
console.log("PREDICTING ENEMY WILL BE NORTH");
return 'north';
}
console.log("PREDICTING ENEMY WILL BE SOUTH")
else return 'south';
}
*/
}
/*
if(hasAmmo) {
var predictEnemys = [];
for(i=0; i<enemiesState.length; i++) {
predictEnemys.push({
isAlive: enemiesState[i].isAlive,
position: enemiesState[i].position
});
}
for(i=0; i<predictEnemys.length; i++) {
var enemy = predictEnemys[i];
var enDir = enemy.direction;
if(enDir == 'north') { predictEnemys[i].position[1]++; }
if(enDir == 'south') { predictEnemys[i].position[1]--; }
if(enDir == 'west') { predictEnemys[i].position[0]--; }
if(enDir == 'east') { predictEnemys[i].position[0]++; }
}
var directions = ['north', 'south', 'east', 'west'];
for(i=0; i<directions.length; i++) {
var testPlayer = {
position: playerState.position,
direction: directions[i]
};
if(utils.canKill(testPlayer, predictEnemys)) {
return directions[i];
}
}
}
*/
if(hasAmmo && enemiesLeft === 1) {
//hunt the last player
var newDir = utils.getDirection(playerState.position,lastEnemy.position);
if(newDir !== playerState.direction) {
return newDir;
}
else {
return 'move';
}
}
//move to ammo
// if(!hasAmmo) {
if (directionToAmmo !== playerState.direction) {
console.log("turning to ammo");
return directionToAmmo;
}
console.log("moving to ammo");
return 'move';
// }
//otherwise hunt
if (gameEnvironment.ammoPosition.length > 0) {
console.log("hunting");
if(!utils.isVisible(playerState.position, closestAmmoPos, playerState.direction)) {
if (directionToAmmo !== playerState.direction) {
console.log("turning to ammo");
return directionToAmmo;
}
console.log("moving to ammo");
return 'move';
}
}
//return utils.randomMove();
}
};
module.exports = gameRunner;
|
const path = require('path');
var config = require('./common');
<%- if options.reactjs? -%>
var react_config = require('./react');
<%- end -%>
config.output = {
path: path.join(__dirname, '../../../app/assets/javascripts/generated'),
// filename: '[name]-bundle.js',
filename: '<%= name %>-bundle.js',
publicPath: '/assets/'
}
// load jQuery from cdn or rails asset pipeline
config.externals = { jquery: 'var jQuery' };
config.module.loaders.push(
// expose jQuery and $ to any JavaScript files loaded after <%= name %>-bundle.js in the Rails Asset Pipeline.
{ test: require.resolve('jquery'), loader: 'expose?jQuery' },
{ test: require.resolve('jquery'), loader: 'expose?$' }
);
<%- if options.reactjs? -%>
// Handle common react files in hot-reload
config.resolve.root.push(react_config.resolve.root);
config.resolve.extensions.push(react_config.resolve.extensions);
config.module.loaders.push(react_config.module.loaders);
config.module.loaders.push(
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel' }
);
<%- end -%>
// Add more entry points specific to rails
// config.entry.rails_only = path.join(__dirname, '../rails_only.js');
<%- if options.reactjs? -%>
// config.entry.app2 = path.join(__dirname, '../../assets/javascripts/app2.jsx');
<%- end -%>
module.exports = config;
|
import React from 'react'
import { textStyle } from '../../theme'
const margin = '1rem'
function Header(props) {
return (
<div
style={{
...textStyle,
fontSize: 12,
marginBottom: margin,
textAlign: 'center',
...props.style,
}}
>
{props.children}
</div>
)
}
export default Header
|
(function(){
angular
.module('app')
.controller('MainController', [
'navService', '$mdSidenav', '$mdBottomSheet', '$log', '$q', '$state', '$mdToast',
MainController
]);
function MainController(navService, $mdSidenav, $mdBottomSheet, $log, $q, $state, $mdToast) {
var vm = this;
vm.menuItems = [ ];
vm.selectItem = selectItem;
vm.toggleItemsList = toggleItemsList;
vm.showActions = showActions;
vm.title = $state.current.data.title;
vm.showSimpleToast = showSimpleToast;
vm.toggleRightSidebar = toggleRightSidebar;
navService
.loadAllItems()
.then(function(menuItems) {
vm.menuItems = [].concat(menuItems);
});
function toggleRightSidebar() {
$mdSidenav('right').toggle();
}
function toggleItemsList() {
var pending = $mdBottomSheet.hide() || $q.when(true);
pending.then(function(){
$mdSidenav('left').toggle();
});
}
function selectItem (item) {
vm.title = item.name;
vm.toggleItemsList();
// vm.showSimpleToast(vm.title);
}
function showActions($event) {
$mdBottomSheet.show({
parent: angular.element(document.getElementById('content')),
templateUrl: 'src/app/views/partials/bottomSheet.html',
controller: [ '$mdBottomSheet', SheetController],
controllerAs: "vm",
bindToController : true,
targetEvent: $event
}).then(function(clickedItem) {
clickedItem && $log.debug( clickedItem.name + ' clicked!');
});
function SheetController( $mdBottomSheet ) {
var vm = this;
vm.actions = [
{ name: 'Share', icon: 'share', url: 'https://twitter.com/intent/tweet?text=Angular%20Material%20Dashboard%20https://github.com/flatlogic/angular-material-dashboard%20via%20@flatlogicinc' },
{ name: 'Star', icon: 'star', url: 'https://github.com/flatlogic/angular-material-dashboard/stargazers' }
];
vm.performAction = function(action) {
$mdBottomSheet.hide(action);
};
}
}
function showSimpleToast(title) {
$mdToast.show(
$mdToast.simple()
.content(title)
.hideDelay(2000)
.position('bottom right')
);
}
}
})();
|
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
//资源市场
'default e2e tests': (browser) => {
// console.log(process.env.VUE_DEV_SERVER_URL)
browser.resizeWindow(1000, 800)
browser
.url('http://console.testfreelog.com/')
.waitForElementVisible('.login-section', 1e3)
.assert.elementPresent('.login-form')
.assert.containsText('.js-login-btn', '登录')
.setValue('input[name=username]', 'src@freelog.com')
.setValue('input[name=password]', '123456')
.click('.js-login-btn')
.waitForElementVisible('.app-wrapper', 1e3)
.assert.elementPresent('.user-profile')
.waitForElementPresent('.resource-list-item', 1e3)
.assert.containElements('.resource-list', '.resource-list-item')
browser.getCookies((result) => {
browser.assert.equal(result.value.length, 1)
browser.assert.equal(result.value[0].name, 'authInfo')
browser.assert.equal(result.value[0].domain, '.testfreelog.com')
})
browser.end()
}
}
|
module.exports = require('./lib/Shipper.js');
|
'use strict';
// `extend-joi.js`
// This only works at moment if you have a base JOI type like number.
const Hapi = require('hapi');
const Blipp = require('blipp');
const Inert = require('inert');
const Vision = require('vision');
const HapiSwagger = require('../');
const ExtendedJoi = require('./assets/extendedjoi.js');
// Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 3000
});
const goodOptions = {
ops: {
interval: 1000
},
reporters: {
console: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [
{
log: '*',
response: '*'
}
]
},
{
module: 'good-console'
},
'stdout'
]
}
};
const swaggerOptions = {
info: {
title: 'Test API Documentation',
description: 'This is a sample example of API documentation.'
}
};
// Start the server
server.register(
[
Inert,
Vision,
Blipp,
{
register: require('good'),
options: goodOptions
},
{
register: HapiSwagger,
options: swaggerOptions
}
],
err => {
if (err) {
throw err;
}
// Start the server
server.start(err => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
}
);
server.route({
method: 'PUT',
path: '/sum/dividableby/{number}',
config: {
handler: (request, reply) => {
return reply({
status: 'OK'
});
},
description: 'Dividable',
tags: ['api'],
validate: {
params: {
number: ExtendedJoi.number().round().dividable(3).required()
}
}
}
});
|
export default function CarouselFlipper({
transcriptOverlayButtonBackground,
transcriptOverlayButtonBackgroundOnDisabled,
transcriptOverlayButtonBackgroundOnFocus,
transcriptOverlayButtonBackgroundOnHover,
transcriptOverlayButtonColor,
transcriptOverlayButtonColorOnDisabled,
transcriptOverlayButtonColorOnFocus,
transcriptOverlayButtonColorOnHover
}) {
return {
'&.webchat__carousel-layout': {
'& .react-film__flipper': {
'& .react-film__flipper__body': {
backgroundColor: transcriptOverlayButtonBackground,
color: transcriptOverlayButtonColor,
outline: 0
},
'&:disabled, &[aria-disabled="true"]': {
'& .react-film__flipper__body': {
backgroundColor: transcriptOverlayButtonBackgroundOnDisabled,
color: transcriptOverlayButtonColorOnDisabled
}
},
'&:focus .react-film__flipper__body': {
backgroundColor: transcriptOverlayButtonBackgroundOnFocus,
color: transcriptOverlayButtonColorOnFocus || transcriptOverlayButtonColor
},
'&:hover .react-film__flipper__body': {
backgroundColor: transcriptOverlayButtonBackgroundOnHover,
color: transcriptOverlayButtonColorOnHover || transcriptOverlayButtonColor
}
}
}
};
}
|
import React from 'react';
import processNodes from '../processNodes';
import generatePropsFromAttributes from '../utils/generatePropsFromAttributes';
import VoidElements from '../dom/elements/VoidElements';
import isValidTagOrAttributeName from '../utils/isValidTagOrAttributeName';
/**
* Converts any element (excluding style - see StyleElementType - and script) to a react element.
*
* @param {Object} node The tag node
* @param {String} index The index of the React element relative to it's parent
* @param {Function} transform The transform function to apply to all children
* @returns {React.Element} The React tag element
*/
export default function TagElementType(node, index, transform) {
const tagName = node.name;
// validate tag name
if (!isValidTagOrAttributeName(tagName)) {
return null;
}
// generate props
const props = generatePropsFromAttributes(node.attribs, index);
// If the node is not a void element and has children then process them
let children = null;
if (VoidElements.indexOf(tagName) === -1) {
children = processNodes(node.children, transform);
}
// create and return the element
return React.createElement(tagName, props, children);
}
|
'use strict';
var $ = require('dominus');
var taunus = require('taunus');
var wiring = require('../../.bin/wiring');
var realtime = require('./conventions/realtime');
var analyticsService = require('./services/google-analytics');
var main = $.findOne('main');
require('./conventions/forms')();
require('./conventions/realtime')();
require('./conventions/autofocus')();
require('./thirdparty/google-analytics')();
function track () {
analyticsService.pageView();
}
function generateQueryString () {
return realtime.id ? { sid: realtime.id } : {};
}
taunus.on('change', track);
taunus.mount(main, wiring, {
qs: generateQueryString
});
|
Package.describe({
name : 'valedaemon:accounts-ldap-bootstrap',
summary: 'Meteor account login via LDAP',
version: '0.3.4',
git : 'https://github.com/valedaemon/meteor-accounts-ldap',
documentation: 'README.md'
});
Npm.depends({'ldapjs' : '0.7.1', 'connect' : '2.19.3'});
Package.on_use(function (api) {
api.versionsFrom('1.1.0.2');
api.use(['routepolicy', 'webapp'], 'server');
api.use(['accounts-base', 'underscore'], ['client', 'server']);
api.use('accounts-password', 'server');
api.imply('accounts-base', ['client', 'server']);
api.use(['ui', 'templating', 'jquery', 'spacebars', 'reactive-var'], 'client');
api.add_files([
'ldap_client.html',
'ldap_client.js',
'ldap_client.css'], 'client');
api.add_files('ldap_server.js', 'server');
api.export('LDAP');
});
|
'use strict';
var debug = require('debug')('express-http-proxy');
function connectionResetHandler(err, res) {
if (err && err.code === 'ECONNRESET') {
debug('Error: Connection reset due to timeout.');
res.setHeader('X-Timeout-Reason', 'express-http-proxy reset the request.');
res.writeHead(504, {'Content-Type': 'text/plain'});
res.end();
}
}
function handleProxyErrors(err, res, next) {
switch (err && err.code) {
case 'ECONNRESET': { return connectionResetHandler(err, res, next); }
default: { next(err); }
}
}
module.exports = handleProxyErrors;
|
define([
// Libraries
'jquery',
'underscore',
'backbone',
], function($, _, Backbone) {
var PageView = Backbone.View.extend({
initialize: function(options) {
var page = this;
var context = options.context || {}
// Get and compile template
require([ 'text!' + options.template ], function(template) {
page.template = _.template(template);
page.render(context);
});
},
render: function(context) {
// Replace HTML with contents of template. Takes optional
// `context` parameter to pass to template.
this.$el.html(this.template(context));
return this;
},
show: function() {
this.$el.show();
return this;
},
hide: function() {
this.$el.hide();
return this;
}
});
return PageView;
});
|
'use strict';
var inherits = require('util').inherits;
var Joi = require('joi');
var CommandBase = require('../commandbase');
var tsutils = require('./utils');
/**
* Provides the ListKeys class, its builder, and its response.
* @module TS
*/
/**
* Command used to list keys in a table.
*
* As a convenience, a builder class is provided;
*
* var listKeys = new ListKeys.Builder()
* .withTable('myTable')
* .withCallback(myCallback)
* .build();
*
* See {{#crossLink "ListKeys.Builder"}}ListKeys.Builder{{/crossLink}}
* @class ListKeys
* @constructor
* @param {Object} options The options for this command
* @param {String} options.table The table in Riak TS.
* @param {Boolean} [options.stream=true] Whether to stream or accumulate the result before calling callback.
* @param {Number} [options.timeout] Set a timeout for this operation.
* @param {Function} callback The callback to be executed when the operation completes.
* @param {String} callback.err An error message. Will be null if no error.
* @param {Object} callback.response the keys returned from Riak.
* @param {Boolean} callback.response.done True if you have received all the keys.
* @param {String[]} callback.response.keys The array of keys.
* @param {Object} callback.data additional error data. Will be null if no error.
* @extends CommandBase
*/
function ListKeys(options, callback) {
CommandBase.call(this, 'TsListKeysReq', 'TsListKeysResp', callback);
this.validateOptions(options, schema);
if (!this.options.stream) {
this.keys = [];
}
}
inherits(ListKeys, CommandBase);
ListKeys.prototype.constructPbRequest = function () {
var protobuf = this.getPbReqBuilder();
protobuf.setTable(new Buffer(this.options.table));
protobuf.setTimeout(this.options.timeout);
return protobuf;
};
ListKeys.prototype.onSuccess = function (rpbTsListKeysResp) {
var keysToSend = new Array(rpbTsListKeysResp.keys.length);
if (rpbTsListKeysResp.keys.length) {
for (var i = 0; i < rpbTsListKeysResp.keys.length; i++) {
var tsrow = rpbTsListKeysResp.keys[i];
var keycells = tsutils.convertTsRow(tsrow);
keysToSend[i] = keycells;
}
}
if (this.options.stream) {
this._callback(null, {
table: this.options.table, keys: keysToSend, done: rpbTsListKeysResp.done
});
} else {
Array.prototype.push.apply(this.keys, keysToSend);
if (rpbTsListKeysResp.done) {
this._callback(null, {
table: this.options.table, keys: this.keys, done: rpbTsListKeysResp.done
});
}
}
return rpbTsListKeysResp.done;
};
var schema = Joi.object().keys({
table: Joi.string().required(),
stream : Joi.boolean().default(true),
timeout: Joi.number().default(null)
});
/**
* A builder for constructing ListKeys instances.
*
* Rather than having to manually construct the __options__ and instantiating
* a ListKeys directly, this builder may be used.
*
* var listKeys = new ListKeys.Builder()
* .withTable('table')
* .withCallback(myCallback)
* .build();
*
* @class ListKeys.Builder
* @constructor
*/
function Builder() {}
Builder.prototype = {
/**
* Set the table.
* @method withTable
* @param {String} table The table in Riak TS
* @chainable
*/
withTable : function (table) {
this.table = table;
return this;
},
/**
* Stream the results.
* Setting this to true will cause you callback to be called as the results
* are returned from Riak TS. Set to false the result set will be buffered and
* delevered via a single call to your callback. Note that on large result sets
* this is very memory intensive.
* @method withStreaming
* @param {Boolean} [stream=true] Set whether or not to stream the results
* @chainable
*/
withStreaming : function (stream) {
this.stream = stream;
return this;
},
/**
* Set the callback to be executed when the operation completes.
* @method withCallback
* @param {Function} callback The callback to be executed when the operation completes.
* @param {String} callback.err An error message. Will be null if no error.
* @param {Object} callback.response the keys returned from Riak.
* @param {Boolean} callback.response.done True if you have received all the keys.
* @param {String} callback.response.table The table the keys are from.
* @param {String[]} callback.response.keys The array of keys.
* @chainable
*/
withCallback : function (callback) {
this.callback = callback;
return this;
},
/**
* Set a timeout for this operation.
* @method withTimeout
* @param {Number} timeout a timeout in milliseconds.
* @chainable
*/
withTimeout : function (timeout) {
this.timeout = timeout;
return this;
},
/**
* Construct a ListKeys instance.
* @method build
* @return {ListKeys}
*/
build : function () {
var cb = this.callback;
delete this.callback;
return new ListKeys(this, cb);
}
};
module.exports = ListKeys;
module.exports.Builder = Builder;
|
import './observe';
import toBeInstanceOf from './matcher/toBeInstanceOf';
beforeEach(() => {
jasmine.addMatchers(toBeInstanceOf);
});
|
angular.module('cloudconnect').directive('custom', function () {
return {
restrict: 'E',
replace: true,
controllerAs: 'CustomCtrl',
templateUrl: 'tabs/custom/custom.html',
controller: function ($scope, $element) {
var s = $scope.server;
var vm = this;
vm.getTunnel = function(){
return (s._tunnel && utils.isForwardConnection(s))?"Forward":"Socks";
}
vm.getPort = function(){
return (s._tunnel && utils.isForwardConnection(s))?s._tunnel.localPort:s._socks;
}
vm.getHost = function(){
return (s._tunnel && utils.isForwardConnection(s)) ? "localhost" : utils.getRemoteAddr(s);
}
}
}
});
|
8.0-alpha3:0cbc30603ed073aeeec80a005cbc79b9120654c37d53fec9487f6703d40c1070
8.0-alpha4:6b757662fec963c9f7362a33ee0ea097ea927b2c6185cd26a58d9535160e9aba
8.0-alpha5:6b757662fec963c9f7362a33ee0ea097ea927b2c6185cd26a58d9535160e9aba
8.0-alpha6:6b757662fec963c9f7362a33ee0ea097ea927b2c6185cd26a58d9535160e9aba
8.0-alpha7:228bc9f33bcbfe077582d6fa4d432a926e6618aa6cb95e9d0ea42870b4ab20f9
8.0-alpha8:4038052c9f3b6282fb5f1ce6f3c46a791d8409c5fb407c77b7f56ca7c6aae28e
8.0-alpha9:9be136e040226bff2e1efb2fee93063e0f7649534260c418ae04fbfdb04ab297
8.0-alpha10:d4c0cfacfc2fb4fa042942e28d639fde712abbd24bf1c4f73daa426811ea9703
8.0-alpha11:d4c0cfacfc2fb4fa042942e28d639fde712abbd24bf1c4f73daa426811ea9703
8.0-alpha12:d4c0cfacfc2fb4fa042942e28d639fde712abbd24bf1c4f73daa426811ea9703
8.0-alpha13:d4c0cfacfc2fb4fa042942e28d639fde712abbd24bf1c4f73daa426811ea9703
8.0.0-alpha14:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-alpha15:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-beta1:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-beta2:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-beta3:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-beta4:9d6a89ef8e6d350dc2204d4687d302ddee497cbe56957c4dac59740f45a57c7c
8.0.0-beta6:66fc88314565ab3e5cbb74232f1887678db6acefc353bf98425b5696b49a95c3
8.0.0-beta7:66fc88314565ab3e5cbb74232f1887678db6acefc353bf98425b5696b49a95c3
8.0.0-beta9:66fc88314565ab3e5cbb74232f1887678db6acefc353bf98425b5696b49a95c3
8.0.0-beta10:e6699311bcda85f22c25975d7e45b473414fbf4ad53e67460bfa9c26eb083f17
8.0.0-beta11:67d4034e3aa2d742846aa85bf38b3d0c15610798decada5746f780947b0aac3f
8.0.0-beta12:3132c849f6bacfd7d3374ebfde4893b002bd486614e9ee0cebda808b8032b8b9
8.0.0-beta13:3132c849f6bacfd7d3374ebfde4893b002bd486614e9ee0cebda808b8032b8b9
8.0.0-beta14:3132c849f6bacfd7d3374ebfde4893b002bd486614e9ee0cebda808b8032b8b9
8.0.0-beta15:d1e0f7a613586687c88bba1ef50dd829f5a682223001230baf5116664ebc9618
8.0.0-beta16:d1e0f7a613586687c88bba1ef50dd829f5a682223001230baf5116664ebc9618
8.0.0-rc1:d1e0f7a613586687c88bba1ef50dd829f5a682223001230baf5116664ebc9618
8.0.0-rc2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.0-rc3:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.0-rc4:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.3:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.4:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.5:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.6:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.0-beta1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.0-beta2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.0-rc1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.3:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.4:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.5:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.6:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.7:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.8:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.9:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.10:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0-beta1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0-beta2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0-beta3:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0-rc1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0-rc2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.3:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.4:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.5:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.6:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.3.0-alpha1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.3.0-beta1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.3.0-rc1:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.7:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.3.0-rc2:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.0.0:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.1.0:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.2.0:f7134a459aa19ae96fdb03fc979b4bb2330fd451ccdadca8d610e3aad3dfa4c1
8.3.0:d263b74df3027f260dc1cbc04f552ea8035e2eee00b5eb21676cff4372df6305
|
var expect = require("chai").expect;
var Keen = require("../../../../src/core"),
keenHelper = require("../../helpers/test-config");
describe("Keen.Query", function() {
beforeEach(function() {
this.project = new Keen({
projectId: keenHelper.projectId,
readKey: keenHelper.readKey
});
this.query = new Keen.Query("count", {
eventCollection: "test-collection"
});
});
afterEach(function(){
this.project = void 0;
this.query = void 0;
});
describe("constructor", function() {
it("should create a new Keen.Query instance", function(){
expect(this.query).to.be.an.instanceof(Keen.Query);
});
it("should have a correct analysis propery", function(){
expect(this.query).to.have.property("analysis").eql("count");
});
it("should have a params object", function(){
expect(this.query).to.have.property("params");
});
it("should have a params.event_collection property", function(){
expect(this.query.params).to.have.property("event_collection").eql("test-collection");
});
});
describe("#addFilter", function(){
it("should add filters correctly", function(){
this.query.addFilter("property", "eq", "value");
expect(this.query.params).to.have.property("filters")
.that.is.an('array')
.with.deep.property('[0]')
.that.deep.equals({
operator: "eq",
property_name: "property",
property_value: "value"
});
});
it("should allow filters with values that are null or false", function(){
this.query.addFilter("a", "eq", null);
this.query.addFilter("b", "eq", false);
expect(this.query.params.filters[0]).to.deep.equals({
operator: "eq",
property_name: "a",
property_value: null
});
expect(this.query.params.filters[1]).to.deep.equals({
operator: "eq",
property_name: "b",
property_value: false
});
});
it("should allow multiple filters on the same property name", function(){
this.query.addFilter("a", "eq", "b");
this.query.addFilter("a", "eq", "c");
expect(this.query.params.filters[0]).to.deep.equals({
operator: "eq",
property_name: "a",
property_value: "b"
});
expect(this.query.params.filters[1]).to.deep.equals({
operator: "eq",
property_name: "a",
property_value: "c"
});
});
});
describe("#get", function(){
it("should return values for camelCased attributes", function(){
expect(this.query.get("eventCollection")).to.eql("test-collection");
});
it("should return values for underscored attributes", function(){
expect(this.query.get("event_collection")).to.eql("test-collection");
});
});
describe("#set", function(){
it("should set multiple specified attributes", function(){
this.query.set({ timeframe: "this_7_days", interval: "daily" });
expect(this.query.params).to.have.property("timeframe").eql("this_7_days");
expect(this.query.params).to.have.property("interval").eql("daily");
});
it("should apply the latest attribute over previous values", function(){
this.query.set({ timeframe: "this_7_days", interval: "daily" });
this.query.set({ timeframe: "this_21_days" });
this.query.set({ timeframe: "this_14_days" });
expect(this.query.params).to.have.property("timeframe").eql("this_14_days");
expect(this.query.params).to.have.property("interval").eql("daily");
});
});
});
|
import React from "react";
import { connect, } from "react-redux";
import { getRecentTransactions, } from "selectors/currentBudget";
import DollarDisplay from "components/DollarDisplay";
class TransactionList extends React.Component {
render () {
return (
<ul>
{transactionListItems(this.props.currentTransactions)}
</ul>
);
}
};
const transactionListItems = (transactions) => {
const transList = transactions.map((transaction) => {
return <li key={transaction._id}>{transaction.name} - <DollarDisplay amount={transaction.amount} /></li>;
});
return transList;
};
const mapStateToProps = (state) => {
return {
currentTransactions: getRecentTransactions(state),
currentBudget: state.preferences.current_budget,
};
};
export default connect(
mapStateToProps,
undefined
)(TransactionList);
|
/* eslint-disable */
export default `function Tree (pause, highlight) {
class Node {
constructor(value) {
this.value = value;
this.children = [];
this._id = Math.floor(Math.random()*10000);
}
add(value) {
this.children.push(new Node(value));
}
traverse(cb) {
cb(this);
for (let child of this.children) {
child.traverse(cb);
}
}
}
let newTree = new Node(1)
pause(newTree);
newTree.add(2);
pause(newTree);
newTree.add(3);
pause(newTree);
newTree.traverse(highlight);
return newTree;
}`
|
const jsonlocale = require('../');
require('child_process').execSync(
`node ../src/json.js \
--outputDir=./locale \
--keep=numbers,currencies,languages \
--keepCalendars=gregorian \
--keepCalendarItems=months,days,dateFormats,timeFormats \
--keepNumberItems=symbolsFormatsNumberSystemLatn,currencies \
--localeFilter=en_US,spa_ES,spa_CL
`, {stdio:'inherit'});
// scripted build...
jsonlocale({
outputDir : './locale',
isoType : '639-1',
keep : [
'numbers',
'calendars' ],
isConvert_yy: true,
keepNumbersItems : [
'currencyFormatsNumberSystemLatn',
'symbolsNumberSystemLatn',
'decimalFormatsNumberSystemLatn' ],
localeDefault : 'de_DE',
keepCalendars : [
'coptic',
'japanese' ],
localeFilter : [
'de_DE', 'de_AT', 'fr_FR', 'fr_BE', 'nl_NL', 'nl_BE'
]
}, (err, res) => {
console.log('finished!');
});
|
var fs = require("fs");
var path = require("path");
var net = require('net');
var p = require("node-protobuf");
var mod = module.exports;
var pb = new p(fs.readFileSync(path.dirname(module.filename)+"/proto.desc"));
var hn, po;
function writeInt(stream, int){
var bytes = new Array(4)
bytes[0] = int >> 24
bytes[1] = int >> 16
bytes[2] = int >> 8
bytes[3] = int
stream.write(new Buffer(bytes))
}
function sendCommand(cmd, callback) {
var obj = {
"query": []
}
obj.query[0] = cmd;
try {
var buf = pb.serialize(obj, "QueryRequest");
var client = net.connect({host: hn, port: po},
function() {
writeInt(client, buf.length);
client.write(buf);
});
client.on('data', function(data) {
var sz = new Number(data.readUInt32BE(0));
var buf2 = data.slice(4);
var newObj = pb.parse(buf2, "QueryResponse");
var result = new Array();
for (x in newObj.data) {
result.push(newObj.data[x].subject+"-"+newObj.data[x].predicate+"-"+newObj.data[x].object);
}
client.end();
callback(false, result);
});
} catch (e) {
callback(true, "Error connecting to TrisDB");
}
}
mod.initialize = function(host, port) {
hn = typeof host !== 'undefined' ? host : "localhost";
po = typeof port !== 'undefined' ? port : 1205;
}
mod.create = function(s, p, o, cb) {
sendCommand('CREATE "'+s+'" "'+p+'" "'+o+'"', function(err, data) {
cb(err);
});
}
mod.get = function(s, p, o, cb) {
sendCommand('GET "'+s+'" "'+p+'" "'+o+'"', function(err, data) {
cb(err, data);
});
}
mod.delete = function(s, p, o, cb) {
sendCommand('DELETE "'+s+'" "'+p+'" "'+o+'"', function(err, data) {
cb(err);
});
}
mod.clear = function(cb) {
sendCommand('CLEAR', function(err, data) {
cb(err);
});
}
|
'use strict';
import test from 'ava';
var physics = require('../').physics;
// Circular collisions
test.todo('Physics.js', physics);
|
import { compose, pure, withHandlers } from 'recompose'
import { connect } from 'react-redux'
import { selectors as servicesSelectors } from 'modules/Services'
import ServiceDetail from './ServiceDetail'
const mapStateToProps = state => ( {
service: servicesSelectors.servicesSelector( state ),
} )
export default compose(
connect( mapStateToProps ),
withHandlers( {
onPressContactUs: ( { navigation } ) => () => navigation.navigate( 'contactUs' ),
} ),
pure
)( ServiceDetail )
|
var snakeBoard;
function newSnakeGame () {
snakeBoard = new Board(); // Create a new board
var htmlBoard = renderBoard({board: snakeBoard.board});
return {
board: snakeBoard.board,
head: snakeBoard.snake.head(),
food: snakeBoard.food,
html: htmlBoard
};
}
function moveSnake(moveDirection) {
if(!snakeBoard){
return {error: 'Error moving snake'};
}
snakeBoard.snake.move(moveDirection);
if(snakeBoard.gameOver){
return 'gameOver';
return;
}
var htmlBoard = renderBoard({board: snakeBoard.board});
return {
board: snakeBoard.board,
head: snakeBoard.snake.head(),
food: snakeBoard.food,
html: htmlBoard
};
}
|
var readline = require("readline");
var fs = require("fs");
var rl = readline.createInterface({
input:process.stdin,
output:process.stdout
});
rl.setPrompt("fan:")
// rl.question("请输入想要查看的文件名:",(filename)=>{
// fs.readFile(filename,(err,data)=>{
// rl.write(data);
// })
// })
rl.prompt();
rl.on("line",(cmd)=>{
console.log(`您敲入了: ${cmd}`)
})
rl.on("close",()=>{
// console.log("bye");
rl.write("bye");
process.exit(0);
})
|
'use strict';
var _ = require('lodash');
module.exports.getListItemFromValue = function(val) {
return { name: val + '', value: val };
};
module.exports.getFirstValue = function(array) {
return _.first(_.map(array, function(item) { return item.value; }));
};
module.exports.getItemNameByValue = function(array, val) {
return _.result(_.find(array, { 'value': val }), 'name');
};
|
var should = require('./base-test').should;
var idx = require('../index');
describe('Basic test example', function () {
it('#should.be.true ', function () {
var a = true;
a.should.be.true;
});
it('#should.not.exist', function () {
var und = null;
should.not.exist(und);
});
it('#deleteMe should exist', function(){
idx.deleteMe.should.exist;
idx.deleteMe();
})
});
|
import SlackBotService from './slack-bot'
import DBService from './db-service'
let Services = {
SlackBot: new SlackBotService(),
Mongo: new DBService()
}
export default Services
export function bootServices (config) {
var promises = []
Object.keys(config).forEach((key) => {
if (config[key].enabled) {
if (Services[key] && Services[key].boot !== 'undefined ') {
console.log(`\tBooting up ${key} service`)
try {
promises.push(Services[key].boot(config[key]))
} catch (e) {
console.log(e)
}
} else {
throw new Error(`${key} service is not defined`)
}
}
})
return Promise.all(promises)
}
|
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(' this is null or not defined');
}
// 1. Let O be the result of calling toObject() passing the
// |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get() internal
// method of O with the argument "length".
// 3. Let len be toUint32(lenValue).
var len = O.length >>> 0;
// 4. If isCallable(callback) is false, throw a TypeError exception. // See: http://es5.github.com/#x9.11
if (typeof callback !== "function") {
throw new TypeError(callback + ' is not a function');
}
// 5. If thisArg was supplied, let T be thisArg; else let
// T be undefined.
if (arguments.length > 1) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty
// internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal
// method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as
// the this value and argument list containing kValue, k, and O.
callback.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
|
/// <reference path="../typings/index.d.ts" />
define(["require", "exports", "./helloworld", "./secondModule"], function (require, exports, helloworld, secondModule) {
"use strict";
console.log(helloworld);
console.log(secondModule);
});
//import ajaxCall = require("./ajaxCall");console.log(ajaxCall);
//example ajaxCall
// requirejs(['../dev_modules/ajaxCall/dist/ajaxCall','helloworld'], function(ajaxCall) {
// try {
// var urlTest = "http://www.mercoglianoisidoro.com/api/saved_data/json";
// var call = new ajaxCall(urlTest);
// //call.setMethod('GET'); call.setDataDoSend({'param1':"val1"})
// console.log('result=', call.executeSync());
// } catch (error) {
// console.error('error during call', error);
// }
// });
|
import _ from 'lodash';
import module from '../module';
import GameState from '../../rogue/init/gamestate';
import { StartGameCycle } from '../../rogue/init/init';
import { NewState, SetState } from '../../rogue/init/gameupgrades';
import Upgrades from '../../rogue/constants/upgrades';
module.filter('visibleUpgrades', (CurrencyDataManager, UpgradeDataManager) => {
return (upgrades, type) => {
return _.filter(upgrades, upgrade => upgrade.cost / 2 < CurrencyDataManager.currency[type]
&& upgrade.currency === type
&& UpgradeDataManager.canSeeUpgrade(upgrade)
);
};
});
module.controller('Upgrades', ($scope, $localStorage,$timeout, CurrencyDataManager, UpgradeDataManager, TemplateDataManager) => {
$scope.upgrades = Upgrades;
$scope.upgradeDataManager = UpgradeDataManager;
$scope.currencyDataManager = CurrencyDataManager;
let curState = {};
$scope.buyUpgrade = (upgrade) => {
if(!UpgradeDataManager.buyUpgrade(upgrade)) return;
if(upgrade.operate) upgrade.operate(curState);
};
const rebuildUpgrades = () => {
const newState = curState = NewState();
_.each(newState.unlocked.race.concat(newState.unlocked.profession), random => {
if(_.contains(UpgradeDataManager.upgrades, `Random: ${random}`)) return;
UpgradeDataManager.upgrades.push(`Random: ${random}`);
});
_.each(UpgradeDataManager.upgrades, name => {
const upgrade = _.findWhere(Upgrades, { name });
if(upgrade && upgrade.operate) upgrade.operate(newState);
});
newState.templates = TemplateDataManager.templates;
SetState(newState);
};
const getCurrencyFrom = (store) => {
_.each(['sp', 'kp', 'vp'], key => {
const add = store[`${key}Earned`] || 0;
CurrencyDataManager.addCurrency(key, add);
});
};
if($localStorage.saveStateCache) {
getCurrencyFrom($localStorage.saveStateCache);
$localStorage.saveStateCache = null;
}
rebuildUpgrades();
StartGameCycle();
GameState.on('redraw', () => {
$localStorage.saveStateCache = {
spEarned: GameState.spEarned,
kpEarned: GameState.kpEarned
};
});
GameState.on('gameover', () => {
$timeout(function() {
getCurrencyFrom(GameState);
$localStorage.saveStateCache = null;
rebuildUpgrades();
});
});
});
|
function addLoadEvent(f) {
var oldLoad = window.onload;
if (typeof window.onload !== "function") {
window.onload = f;
} else {
window.onload = function() {
oldLoad();
f();
};
}
}
$ = function(e) {
return document.querySelectorAll(e);
}
function highLight() {
var txt = $("textarea")[0].value;
var input = $("input")[0];
var v = input.value;
var p = $("p")[0];
var s = new RegExp(v, "gi");
if (!v.trim().length) {
p.innerHTML = "";
return false;
}
p.innerHTML = txt.split(/\b/g).map(function(v) {return s.test(v) ? "<span class = 'red'>" + v + "</span>" : v;}).join("");
input.focus();
}
function addButtonEvent() {
var btn = $("button")[0];
btn.addEventListener("click", highLight);
}
function initTextarea() {
var defaulText = $("p")[1].innerHTML;
var textarea = $("textarea")[0];
var defaultColor = "#999";
var input = $("input")[0];
textarea.style.color = defaultColor;
textarea.value = defaulText;
textarea.addEventListener("focus", function() {
if (textareaState.init) {
textarea.value = "";
textarea.style.color = "black";
textareaState.init = false;
}
});
textarea.addEventListener("blur", function(){
if (!textareaState.init && !textarea.value) {
textarea.value = defaulText;
textarea.style.color = defaultColor;
textareaState.init = true;
}
});
input.addEventListener("keyup", function(e){
if (e.keyCode === 13) {
highLight();
}
});
}
var textareaState = {
init: true
};
addLoadEvent(addButtonEvent);
addLoadEvent(initTextarea);
|
const test = require('ava');
const { tfw } = require('./_utils');
tfw.init({ src: 'cn' });
test(
'cn-app-starts-ok',
async (t) => {
const { app } = t.context;
await app.client.waitUntilWindowLoaded();
const win = app.browserWindow;
t.is(await app.client.getWindowCount(), 3);
t.false(await win.isMinimized());
t.false(await win.isDevToolsOpened());
t.true(await win.isVisible());
t.true.skip(await win.isFocused());
const { width, height } = await win.getBounds();
t.true(width > 0);
t.true(height > 0);
},
);
test(
'cn-fav-new',
async (t) => {
t.plan(3);
const { app } = t.context;
const c = app.client;
await (await c.$('#cn_neu')).click();
const fav_name = await c.$('#cn_fav_name');
const favs = await c.$('#cn_favs .list_sel .name');
t.is(await fav_name.getValue(), '');
await favs.waitForExist();
t.is(await favs.getText(), 'unnamed');
await fav_name.setValue('myFav');
t.is(await favs.getText(), 'myFav');
},
);
test(
'cn-fav-clone',
async (t) => {
t.plan(5);
const { app } = t.context;
const c = app.client;
const cln = await c.$('#cn_cln');
await cln.click();
const fav_name = await c.$('#cn_fav_name');
const favs = await c.$('#cn_favs .list_sel .name');
t.is(await fav_name.getValue(), '(copy)');
await favs.waitForExist();
t.is(await favs.getText(), '(copy)');
await fav_name.setValue('myCopy');
t.is(await favs.getText(), 'myCopy');
await cln.click();
t.is(await fav_name.getValue(), 'myCopy(copy)');
await favs.waitForExist();
t.is(await favs.getText(), 'myCopy(copy)');
},
);
test(
'cn-start-raw',
async (t) => {
t.plan(3);
const { app } = t.context;
const c = app.client;
const cn_neu = await c.$('#cn_neu');
await cn_neu.click();
const cn_type = await c.$('#cn_type');
await cn_type.selectByVisibleText('Start');
t.is(await cn_type.getValue(), 'start');
const cn_subtype = await c.$('#cn_subtype');
await cn_subtype.selectByVisibleText('Local');
t.is(await cn_subtype.getValue(), 'raw');
const cn_go = await c.$('#cn_go');
await cn_go.click();
const ide = await c.$('#ide .lm_tab.lm_active');
await ide.waitForExist();
t.is(await ide.getAttribute('title'), 'Session');
},
);
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.lang.functional.numrec"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.lang.functional.numrec"] = true;
dojo.provide("dojox.lang.functional.numrec");
dojo.require("dojox.lang.functional.lambda");
dojo.require("dojox.lang.functional.util");
// This module provides recursion combinators:
// - a simplified numeric linear recursion combinator.
// Acknoledgements:
// - recursion combinators are inspired by Manfred von Thun's article
// "Recursion Theory and Joy"
// (http://www.latrobe.edu.au/philosophy/phimvt/joy/j05cmp.html)
// Notes:
// - recursion combinators produce a function, which implements
// their respective recusion patterns. String lambdas are inlined, if possible.
(function(){
var df = dojox.lang.functional, inline = df.inlineLambda,
_r_i = ["_r", "_i"];
df.numrec = function(/*Object*/ then, /*Function|String|Array*/ after){
// summary:
// Generates a function for the simplified numeric linear recursion pattern.
// All parameter functions are called in the context of "this" object.
// description:
// This is a simplification of the linear recursion combinator:
// - the generated function takes one numeric parameter "x",
// - the "cond" is fixed and checks for 0.
// - the "before" is fixed and the generated function is called with "x - 1".
// - the "above is called with two parameters: the return from the generated
// function, and with "x".
// - as you can see the recursion is done by decreasing the parameter,
// and calling itself until it reaches 0.
// then:
// The value, which is used upon termination of the recursion.
// It will be returned as the value of the generated function.
// above:
// The lambda expression, which is called after the recursive step.
// It accepts two parameters: the returned value from the recursive step, and
// the original parameter. The returned value will be returned as the value of
// the generated function.
var a, as, dict = {},
add2dict = function(x){ dict[x] = 1; };
if(typeof after == "string"){
as = inline(after, _r_i, add2dict);
}else{
a = df.lambda(after);
as = "_a.call(this, _r, _i)";
}
var locals = df.keys(dict),
f = new Function(["_x"], "var _t=arguments.callee,_r=_t.t,_i".concat( // Function
locals.length ? "," + locals.join(",") : "",
a ? ",_a=_t.a" : "",
";for(_i=1;_i<=_x;++_i){_r=",
as,
"}return _r"
));
f.t = then;
if(a){ f.a = a; }
return f;
};
})();
/*
For documentation only:
1) The original recursive version:
var numrec1 = function(then, after){
var after = df.lambda(after);
return function(x){
return x ? after.call(this, arguments.callee.call(this, x - 1), x) : then;
};
};
2) The original iterative version (before minification and inlining):
var numrec2 = function(then, after){
var after = df.lambda(after);
return function(x){
var ret = then, i;
for(i = 1; i <= x; ++i){
ret = after.call(this, ret, i);
}
return ret;
};
};
*/
}
|
import styled from 'styled-components';
const Ul = styled.ul `
`;
export default Ul;
|
/* Object/Relational mapping for instances of the Hit class.
- classes correspond to tables
- instances correspond to rows
- fields correspond to columns
In other words, this code defines how a row in the database hit table
maps to the JS Order object.
*/
var Promise = require('bluebird');
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Data", {
id: {type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true},
version: {type: DataTypes.INTEGER, allowNull: false, primaryKey: true},
name: {type: DataTypes.STRING},
iAmId: {type: DataTypes.INTEGER},
activeVersion: {type: DataTypes.INTEGER},
ideaId: {type: DataTypes.INTEGER},
dataContentSerialized: {type: DataTypes.STRING},
stateContentSerialized: {type: DataTypes.STRING},
decoratedDataId: {type: DataTypes.INTEGER},
isPublic: {type: DataTypes.BOOLEAN},
createdAt: {type: DataTypes.DATE},
updatedAt: {type: DataTypes.DATE}
}, {
// either one is good enough
freezeTableName: true,
tableName: 'data',
classMethods: {
getDatasById: function(dataIds){
var deferral = Promise.defer();
var findObj = {
where: {id: dataIds, ideaId: '1'}, /* id: '80', */
attributes: ['id', 'name', 'iAmId', 'version', 'ideaId', 'isPubic', 'decoratedDataId', 'createdAt', 'updatedAt'],
// http://sequelizejs.com/docs/latest/models
//limit: LIMIT_NO,
order: [['createdAt', 'DESC'], ['iAmId', 'DESC'], ['id', 'ASC']]
};
global.db.Data.findAll(findObj)
.success(function(datas) {
console.log("Loaded datas length: %d", datas.length);
//deferral.reject("[models/data.js] Iskuliraj, samo test!");
deferral.resolve(datas);
}).error(function(err) {
console.log(err);
deferral.reject(err);
});
return deferral.promise;
}
}
});
};
|
// Copyright 2014-2021, University of Colorado Boulder
/**
* Shows an Options dialog that consists of sim-global options.
*
* @author Jonathan Olson <jonathan.olson@colorado.edu>
* @author Chris Malley (PixelZoom, Inc.)
*/
import merge from '../../phet-core/js/merge.js';
import PhetFont from '../../scenery-phet/js/PhetFont.js';
import { Text } from '../../scenery/js/imports.js';
import Dialog from '../../sun/js/Dialog.js';
import Tandem from '../../tandem/js/Tandem.js';
import joist from './joist.js';
import joistStrings from './joistStrings.js';
class OptionsDialog extends Dialog {
/**
* @param {function(tandem:Tandem):Node} createContent - creates the dialog's content
* @param {Object} [options]
*/
constructor( createContent, options ) {
options = merge( {
titleAlign: 'center',
bottomMargin: 26,
ySpacing: 26,
// phet-io
tandem: Tandem.REQUIRED,
phetioDynamicElement: true
}, options );
assert && assert( !options.title, 'OptionsDialog sets title' );
options.title = new Text( joistStrings.options.title, {
font: new PhetFont( 30 ),
maxWidth: 400, // determined empirically
tandem: options.tandem.createTandem( 'title' )
} );
const content = createContent( options.tandem.createTandem( 'content' ) );
super( content, options );
// @private
this.disposeOptionsDialog = () => {
content.dispose();
options.title.dispose();
};
}
/**
* @public
* @override
*/
dispose() {
this.disposeOptionsDialog();
super.dispose();
}
}
OptionsDialog.DEFAULT_FONT = new PhetFont( 20 );
OptionsDialog.DEFAULT_SPACING = 14;
joist.register( 'OptionsDialog', OptionsDialog );
export default OptionsDialog;
|
/*
Copyright (c) 2010 Mike Desjardins
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.
*/
Components.utils.import("resource://app/chrome/content/js/global.js");
function toggleFollow(myUsername,myPassword,hisUserId) {
var check = document.getElementById('check-' + myUsername);
if (check.checked) {
follow(myUsername,myPassword,hisUserId);
} else {
unfollow(myUsername,myPassword,hisUserId);
}
}
function unfollow(myUsername,myPassword,hisScreenName) {
jsdump(myUsername + ' is unfollowing ' + hisUserId);
var throb = document.getElementById('throb-' + myUsername);
throb.style.display='inline';
var check = document.getElementById('check-' + myUsername);
check.style.display='none';
var am = new AccountManager();
account = am.getAccount(myUsername,Ctx.service);
Social.service(Ctx.service).unfollow({
"username": account.username,
"password": account.password,
"token": account.token,
"tokenSecret": account.tokenSecret,
"screenName": hisScreenName,
"onSuccess": function(result) { friendshipCallback(result,myUsername); },
"onError": function(status) {
jsdump("Error w/ unfollow, HTTP Status: " + status);
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
prompts.alert(window, "Sorry.", "There was an error processing your unfollow request (Error Code" + status + ").");
var check = document.getElementById('check-' + myUsername);
check.checked=true;
check.style.display='inline';
document.getElementById('throb-' + myUsername).style.display='none';
}
});
}
function follow(myUsername,myPassword,hisUserId) {
jsdump(myUsername + ' is following ' + hisUserId);
var throb = document.getElementById('throb-' + myUsername);
throb.style.display='inline';
var check = document.getElementById('check-' + myUsername);
check.style.display='none';
var hisUsername = document.getElementById('hisUsername').value;
var am = new AccountManager();
account = am.getAccount(myUsername,Ctx.service);
Social.service(Ctx.service).follow({
"username": account.username,
"password": account.password,
"token": account.token,
"tokenSecret": account.tokenSecret,
"screenName": hisUserId,
"onSuccess": function(result) { friendshipCallback(result,myUsername); },
"onError": function(status) {
jsdump('Error w/ follow: HTTP status: ' + status)
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
prompts.alert(window, "Sorry.", "There was an error processing your follow request (Error Code " + status + ").");
check.checked=false;
check.style.display='inline';
document.getElementById('throb-' + myUsername).style.display='none';
}
});
}
function friendshipCallback(transport,myUsername) {
var throb = document.getElementById('throb-' + myUsername);
throb.style.display='none';
var check = document.getElementById('check-' + myUsername);
check.style.display='inline';
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.