code stringlengths 2 1.05M |
|---|
//Part of the Spelling Corrector app
//Licensed under the MIT license, see COPYING.txt for details
"use strict";
/** @namespace sc
*
* Contains all the functions and properties that the spelling corrector uses.
*
* Note that this depends on the accompanying HTML page, and will not work well without it.
*
* For a basic overview of what the spelling corrector is, see
* `{@link https://github.com/SavageWolf/Spelling-Corrector}`.
*/
window.sc = {};
/** The current word that needs to be typed into the input box.
* @type string
*/
sc.currentWord = "";
/** An array of all the words that have been registered. Each element is a string.
* @type array
*/
sc.wordList = [];
//Check the words value has been set
if(!localStorage.words) localStorage.words = "[]";
if(!("length" in JSON.parse(localStorage.words))) localStorage.words = "[]";
/** Loads the words from an array saved at `localStorage.words`. */
sc.loadWords = function() {
sc.wordList = JSON.parse(localStorage.words);
};
/** Saves the words to an array at `localStorage.words`. */
sc.saveWords = function() {
localStorage.words = JSON.stringify(sc.wordList);
};
/** Adds a word to the list of words.
* @param {string} word The word to add.
*/
sc.addWord = function(word) {
sc.wordList[sc.wordList.length] = word;
sc.saveWords();
sc.updateSettingsArea();
};
/** Sets the param as the word that should be typed in the main typing area thing.
* @param {string} w The word to set.
*/
sc.setWord = function(w) {
sc.currentWord = w;
$("#wordOrigin").html(sc.currentWord);
$("#wordEntry").val("");
$("#wordOrigin").slideDown();
};
/** Called when a key is pressed in the word entry. Checks if the user is typing the word correctly and sets the
* background accordingly. If the word is finished, then it calls `sc.generateNextWord`.
*/
sc.checkWord = function() {
var value = $("#wordEntry").val();
$("#wordOrigin").slideUp();
if(sc.currentWord.substr(0, value.length).toLowerCase() != value.toLowerCase()) {
//They are wrong
$("body").removeClass("yes");
$("body").addClass("no");
$("#wordEntry").removeClass("yes");
$("#wordEntry").addClass("no");
}else{
//They are correct
$("body").removeClass("no");
$("body").addClass("yes");
$("#wordEntry").removeClass("no");
$("#wordEntry").addClass("yes");
}
if(value.toLowerCase() == sc.currentWord.toLowerCase()) {
sc.generateNextWord();
}
if(!value.toLowerCase()) {
$("#wordOrigin").slideDown();
}
};
/** Updates the setting area; should be called when a word is added or removed. */
sc.updateSettingsArea = function() {
sc.wordList.sort();
sc.saveWords();
//Clear the settings table
$("#settings").html("");
var hold = ""
//Loop through every word, adding them to the string
for(var i = 0; i < sc.wordList.length; i ++) {
hold += "<span>\
<span class='deleteButton' title='Delete Word' onclick='sc.deleteWord("+i+");'>X</span>\
<span class='settingsWord'>"+sc.wordList[i]+"</span>\
</span>";
}
sc.saveWords();
$("#settings").html(hold);
};
/** Called when the "settings" button is pressed. Shows or hides the settings area. */
sc.toggleSettingsDiv = function() {
if($("#mainSettings").css("display") == "none") {
sc.updateSettingsArea();
$("#mainSettings").slideDown();
}else{
$("#mainSettings").slideUp();
}
};
/** Called when a key is pressed on the "add new word" thing. Checks if enter has been pressed and adds the word if so.
*/
sc.checkInput = function(e) {
if(e.keyCode == 13 || e.which == 13) {
sc.addWordFromInput();
$("#addWordField").focus();
}
};
/** Deletes the word from the word list.
* @param {integer} i The index of the word to delete.
*/
sc.deleteWord = function(i) {
sc.wordList.splice(i, 1);
sc.saveWords();
sc.updateSettingsArea();
};
/** Reads the word in the "new word" textbox, and adds it to the list of words. */
sc.addWordFromInput = function() {
sc.wordList[sc.wordList.length] = $("#addWordField").val();
sc.saveWords();
sc.updateSettingsArea();
if(sc.wordList.length == 1) sc.generateNextWord();
};
/** Called on page load and when the current word is finished. Generates a new word from the word list to use. */
sc.generateNextWord = function() {
sc.loadWords();
if(!sc.wordList.length) {
sc.setWord("No words, add some in the settings above!");
}else if(sc.wordList.length == 1){
sc.setWord(sc.wordList[0]);
}else{
var attemptWord = sc.currentWord;
while(attemptWord == sc.currentWord){
attemptWord = sc.wordList[~~(Math.random()*sc.wordList.length)];
}
sc.setWord(attemptWord);
}
};
|
/**
*
* Web Starter Kit
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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
*
*/
'use strict';
// This gulpfile makes use of new JavaScript features.
// Babel handles this without us having to do anything. It just works.
// You can read more about the new JavaScript features here:
// https://babeljs.io/docs/learn-es2015/
import path from 'path';
import gulp from 'gulp';
import del from 'del';
import runSequence from 'run-sequence';
import browserSync from 'browser-sync';
import swPrecache from 'sw-precache';
import gulpLoadPlugins from 'gulp-load-plugins';
import {output as pagespeed} from 'psi';
import pkg from './package.json';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
// deploy task
gulp.task('deploy', ['default'], () => {
return gulp.src('dist/**/*')
.pipe($.ghPages());
});
// Lint JavaScript
gulp.task('lint', () =>
gulp.src(['app/scripts/**/*.js','!node_modules/**'])
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError()))
);
// Optimize images
gulp.task('images', () =>
gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
.pipe($.size({title: 'images'}))
);
// Copy all files at the root level (app)
gulp.task('copy', () =>
gulp.src([
'app/*',
'!app/*.html',
'node_modules/apache-server-configs/dist/.htaccess'
], {
dot: true
}).pipe(gulp.dest('dist'))
.pipe($.size({title: 'copy'}))
);
// Compile and automatically prefix stylesheets
gulp.task('styles', () => {
const AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
// For best performance, don't add Sass partials to `gulp.src`
return gulp.src([
'app/styles/**/*.scss',
'app/styles/**/*.css'
])
.pipe($.newer('.tmp/styles'))
.pipe($.sourcemaps.init())
.pipe($.sass({
precision: 10
}).on('error', $.sass.logError))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('.tmp/styles'))
// Concatenate and minify styles
.pipe($.if('*.css', $.cssnano()))
.pipe($.size({title: 'styles'}))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest('dist/styles'));
});
// Concatenate and minify JavaScript. Optionally transpiles ES2015 code to ES5.
// to enable ES2015 support remove the line `"only": "gulpfile.babel.js",` in the
// `.babelrc` file.
gulp.task('scripts', () =>
gulp.src([
// Note: Since we are not using useref in the scripts build pipeline,
// you need to explicitly list your scripts here in the right order
// to be correctly concatenated
// Component handler
'./app/styles/src/mdlComponentHandler.js',
// Base components
'./app/styles/src/button/button.js',
'./app/styles/src/checkbox/checkbox.js',
'./app/styles/src/icon-toggle/icon-toggle.js',
'./app/styles/src/menu/menu.js',
'./app/styles/src/progress/progress.js',
'./app/styles/src/radio/radio.js',
'./app/styles/src/slider/slider.js',
'./app/styles/src/spinner/spinner.js',
'./app/styles/src/switch/switch.js',
'./app/styles/src/tabs/tabs.js',
'./app/styles/src/textfield/textfield.js',
'./app/styles/src/tooltip/tooltip.js',
// Complex components (which reuse base components)
'./app/styles/src/layout/layout.js',
'./app/styles/src/data-table/data-table.js',
// And finally, the ripples
'./app/styles/src/ripple/ripple.js',
// Other scripts,
'./app/scripts/main.js'
])
.pipe($.newer('.tmp/scripts'))
.pipe($.sourcemaps.init())
.pipe($.babel())
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/scripts'))
.pipe($.concat('main.min.js'))
.pipe($.uglify({preserveComments: 'some'}))
// Output files
.pipe($.size({title: 'scripts'}))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest('dist/scripts'))
);
// Scan your HTML for assets & optimize them
gulp.task('html', () => {
return gulp.src('app/**/*.html')
.pipe($.useref({
searchPath: '{.tmp,app}',
noAssets: true
}))
// Minify any HTML
.pipe($.if('*.html', $.htmlmin({
removeComments: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
removeOptionalTags: true
})))
// Output files
.pipe($.if('*.html', $.size({title: 'html', showFiles: true})))
.pipe(gulp.dest('dist'));
});
// Clean output directory
gulp.task('clean', () => del(['.tmp', 'dist/*', '!dist/.git'], {dot: true}));
// Watch files for changes & reload
gulp.task('serve', ['scripts', 'styles'], () => {
browserSync({
notify: false,
// Customize the Browsersync console logging prefix
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: ['.tmp', 'app'],
port: 3000
});
gulp.watch(['app/**/*.html'], reload);
gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
gulp.watch(['app/scripts/**/*.js'], ['lint', 'scripts', reload]);
gulp.watch(['app/images/**/*'], reload);
});
// Build and serve the output from the dist build
gulp.task('serve:dist', ['default'], () =>
browserSync({
notify: false,
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: 'dist',
port: 3001
})
);
// Build production files, the default task
gulp.task('default', ['clean'], cb =>
runSequence(
'styles',
['lint', 'html', 'scripts', 'images', 'copy'],
'generate-service-worker',
cb
)
);
// Run PageSpeed Insights
gulp.task('pagespeed', cb =>
// Update the below URL to the public URL of your site
pagespeed('example.com', {
strategy: 'mobile'
// By default we use the PageSpeed Insights free (no API key) tier.
// Use a Google Developer API key if you have one: http://goo.gl/RkN0vE
// key: 'YOUR_API_KEY'
}, cb)
);
// Copy over the scripts that are used in importScripts as part of the generate-service-worker task.
gulp.task('copy-sw-scripts', () => {
return gulp.src(['node_modules/sw-toolbox/sw-toolbox.js', 'app/scripts/sw/runtime-caching.js'])
.pipe(gulp.dest('dist/scripts/sw'));
});
// See http://www.html5rocks.com/en/tutorials/service-worker/introduction/ for
// an in-depth explanation of what service workers are and why you should care.
// Generate a service worker file that will provide offline functionality for
// local resources. This should only be done for the 'dist' directory, to allow
// live reload to work as expected when serving from the 'app' directory.
gulp.task('generate-service-worker', ['copy-sw-scripts'], () => {
const rootDir = 'dist';
const filepath = path.join(rootDir, 'service-worker.js');
return swPrecache.write(filepath, {
// Used to avoid cache conflicts when serving on localhost.
cacheId: pkg.name || 'web-starter-kit',
// sw-toolbox.js needs to be listed first. It sets up methods used in runtime-caching.js.
importScripts: [
'scripts/sw/sw-toolbox.js',
'scripts/sw/runtime-caching.js'
],
staticFileGlobs: [
// Add/remove glob patterns to match your directory setup.
`${rootDir}/images/**/*`,
`${rootDir}/scripts/**/*.js`,
`${rootDir}/styles/**/*.css`,
`${rootDir}/*.{html,json}`
],
// Translates a static file path to the relative URL that it's served from.
// This is '/' rather than path.sep because the paths returned from
// glob always use '/'.
stripPrefix: rootDir + '/'
});
});
// Load custom tasks from the `tasks` directory
// Run: `npm install --save-dev require-dir` from the command-line
// try { require('require-dir')('tasks'); } catch (err) { console.error(err); }
|
// @flow
import React from 'react'
import styles from './styles/CommentPlaceholder.css'
export default function CommentPlaceholder() {
return <div className={styles.placeholder} />
}
|
(function() {
App.SessionsEditView = Ember.View.extend({
templateName: 'sessions/edit',
resourceBinding: 'controller.resource',
submit: function(event) {
this.get('resource').save();
Tower.router.transitionTo('sessions.index');
return false;
}
});
}).call(this);
|
import describe from 'tape-bdd';
import login from 'src/domain/services/login'; // eslint-disable-line import/no-extraneous-dependencies
describe('Login', (it) => {
it('sends back a welcome message and instructions message', (assert) => {
// Given
const lead = {
platform: 'facebook',
id: 123456,
};
// When
const result = login({ lead });
// Then
assert.deepEqual(result, [
{
type: 'welcome-message',
payload: lead,
},
{ type: 'instructions-message' },
]);
});
it('welcomes back a player that already exists', (assert) => {
// Given
const lead = {
platform: 'facebook',
id: 123456,
};
const player = {
id: '1234-2345-3456-4567-5678',
identities: [lead],
};
// When
const result = login({ player, lead });
// Then
assert.deepEqual(result, [
{
type: 'welcome-back-message',
payload: {
lead,
player,
},
},
]);
});
});
|
// blur up
!function(){
var images = document.querySelectorAll("img[data-placeholder]");
var i = images.length;
var obj = {};
function bob(el, i){
if(el.naturalHeight){
clearInterval(obj[i]);
el.parentNode.style.height = el.naturalHeight + "px";
}
}
//image.src = 'data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'' + image.width + '\' height=\'' + image.height + '\'%3E%3C/svg%3E';
while(i--){
if(!images[i].complete){
images[i].addEventListener('load', function (e) {
console.log('boom');
});
//images[i].style.background = 'url(' + images[i].getAttribute("data-placeholder") + ')' + 'no-repeat, url(' + images[i].src + ')';
images[i].style.backgroundImage = 'url(' + images[i].getAttribute("data-placeholder") + ')';
images[i].style.backgroundSize = "cover";
//images[i].src = "";
//images[i].parentNode.style.backgroundImage = 'url(' + images[i].getAttribute("data-placeholder") + ')';
var bb = images[i].getBoundingClientRect();
//images[i].parentNode.style.width = bb.width + "px";
//obj[i] = setInterval(bob, 50, images[i], i);
}
}
}(); |
__CLASS__('Page1Screen', Screen,
{
OnLoad: function()
{
alert("Page1Screen OnLoad");
this.Click(this.clickButton, '#button');
},
clickButton: function(sender)
{
alert("Page1 Button click = " + $(sender).text());
this.PushScreen('#page2', Page2Screen, null, jqmLoader)
}
});
|
#!/usr/bin/env node
const minimist = require('minimist')
const configManager = require('./lib/configManager.js')
const podManager = require('./lib/podManager.js')
function run () {
configManager.loadFromArgs(minimist(process.argv.slice(2)))
podManager.start()
}
if (require.main === module) {
run()
}
|
/*
(c) Copyright 2016-2017 Hewlett Packard Enterprise Development LP
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.
*/
import Enhance from '../oneview-sdk/utils/enhance';
import ResourceTransforms from './utils/resource-transforms';
import DeveloperListener from './developer';
import ServerHardwareListener from './server-hardware';
import ServerProfilesListener from './server-profiles';
import ServerProfileTemplateListener from './server-profile-templates';
import DashboardListener from './dashboard-listener';
import AlertsListener from './alerts-listener';
import DefaultListener from './default-listener';
import BotListener from './bot';
import NotificationsFilter from './notifications-filter';
const url = require('url');
export default function(robot, client) {
const transform = new ResourceTransforms(robot);
const filter = new NotificationsFilter(robot);
const dev = new DeveloperListener(robot, client, transform);
const sh = new ServerHardwareListener(robot, client, transform);
const sp = new ServerProfilesListener(robot, client, transform, sh);
const spt = new ServerProfileTemplateListener(robot, client, transform, sh, sp);
const dash = new DashboardListener(robot, client, transform);
const al = new AlertsListener(robot, client, transform);
const deft = new DefaultListener(robot, transform);
// LAST!!
new BotListener(robot, client, transform, dev, sh, sp, spt);
// TODO: Bug This should not be bound here, probably want a NotificationsListener instead
// TODO This is a total hack, we need to pull the transformer out of the client
robot.on('__hpe__notification__', function (message) {
let uri = url.parse('https://' + message.resourceUri);
let auth = client.getAuthToken(uri.hostname);
const enhance = new Enhance(uri.hostname);
//remove host before transform
message.resourceUri = uri.path;
let resource = enhance.transformHyperlinks(auth, message);
let checkedMessage = filter.check(resource);
if (typeof checkedMessage !== 'undefined' && checkedMessage.length > 0) {
transform.messageRoom(client.notificationsRoom, resource.resource);
}
});
}
|
import { click, visit } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
module('Acceptance | application', function(hooks) {
setupApplicationTest(hooks);
test('double render failing test', async function(assert) {
await visit('/double-render');
assert.dom('.computed').hasText('test val 1');
await click('button');
assert.dom('.computed').hasText('test val 2');
await click('button');
assert.dom('.computed').hasText('test val 3');
});
test('no rerender failing test', async function(assert) {
await visit('/no-rerender');
assert.dom('.items').hasText('1');
await click('button');
assert.dom('.items').hasText('0');
await click('button');
assert.dom('.items').hasText('1');
});
});
|
'use strict';
module.exports = new (require('events')).EventEmitter();
|
/*
* angular-purge - v0.0.1 - 2015-10-14
* https://github.com/VanMess/angular-purge
* Copyright (c) 2014 Van (http://vanmess.github.io/)
*/
!(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['angular'], factory);
} else {
// Global Variables
factory(window.angular);
}
})(function(ng) {
'use strict';
|
/**
* @file mip-change-page 组件
* @author
*/
define(function (require) {
'use strict';
var customElement = require('customElement').create();
/**
* 第一次进入可视区回调,只会执行一次
*/
customElement.prototype.firstInviewCallback = function () {
// 获取元素
var myThis = this.element;
// 获取元素
var domBox = myThis.querySelector('#box');
var domList = myThis.querySelector('.list');
var domBoxboxs = myThis.querySelectorAll('.boxboxs');
var preNum = 0;
var jsonLen = domBoxboxs.length;
// 设置规则
var each = parseInt(myThis.getAttribute('data-number'), 0);
var page = Math.ceil(jsonLen / each);
// 设置内容
for (var i = 0; i < each; i++) {
var domP = '<div class="mip-change-boxs">';
domP += domBoxboxs[i].innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
// 设置列表页数
for (var i = 0; i < page; i++) {
var domA = document.createElement('a');
domA.href = 'javascript:;';
domA.innerHTML = i + 1;
domList.insertBefore(domA, null);
}
// 获取元素
var domListChild = domList.children;
// 获取页数
var domListLen = domListChild.length;
// 记录上一次单击的元素
var preDom = domList.children[0];
preDom.className = 'current';
// 切换页
domList.addEventListener('click', function (e) {
// 获取目标元素
var target = e.target;
// 获取目标元素的标签名,并统一转换成小写
var targetName = target.nodeName.toLocaleLowerCase();
if (targetName === 'a') {
// 添加class
preDom.className = '';
target.className = 'current';
// 改变当前单击的元素。
preDom = target;
// 改变当前元素索引
preNum = target.innerHTML - 1;
// 先清空上个页面的内容
domBox.innerHTML = '';
// 因为顺序在1,2,3的时候没有规则,所以进行了判断。
if (target.innerHTML !== '1') {
if (target.innerHTML === '2') {
// 遍历每页的条数,并将内容添加到domBox中。
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[i - 1 + (target.innerHTML * (each - 1))];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
}
else if (target.innerHTML === '3') {
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[i + (target.innerHTML * (each - 1))];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
}
else {
for (var i = 0; i < each; i++) {
var numa = target.innerHTML - each;
var numb = target.innerHTML * (each - 1);
var arrJsonCurrent = domBoxboxs[i + numa + numb];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
}
}
else {
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[i];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
}
}
});
// 获取上一页和下一页元素
var pagePreDom = myThis.querySelector('#pre');
var pageNextDom = myThis.querySelector('#next');
// 上一页
pagePreDom.addEventListener('click', function () {
// 判断当前元素索引
if (preNum > 0) {
preNum--;
}
changeHtml(domBox, preNum, each);
});
// 下一页
pageNextDom.addEventListener('click', function () {
// 判断当前元素索引
if (preNum < domListLen - 1) {
preNum++;
}
changeHtml(domBox, preNum, each);
});
// 改变box内容
function changeHtml(domBox, currentNum, each) {
domBox.innerHTML = '';
preDom.className = '';
domListChild[currentNum].className = 'current';
preDom = domListChild[currentNum];
switch (currentNum) {
case 0:
// 遍历元素
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[currentNum + i];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
break;
case 1:
// 遍历元素
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[each + i];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
break;
default:
// 遍历元素
for (var i = 0; i < each; i++) {
var arrJsonCurrent = domBoxboxs[currentNum * each + i];
if (arrJsonCurrent == null) {
break;
}
var domP = '<div class="mip-change-boxs">';
domP += arrJsonCurrent.innerHTML;
domP += '</div>';
domBox.innerHTML += domP;
}
break;
}
}
};
return customElement;
});
|
'use strict';
/**
* @ngdoc overview
* @name angularSearchApp
* @description
* # angularSearchApp
*
* Main module of the application.
*/
(function() {
angular
.module('angularSearchApp', ["search-directives"]);
})();
|
/*
PhantomJS "main"-script
*/
var getSource = require('./getSource.js');
var system = require('system');
var fs = require('fs');
var basePath = './';
var prefix = 'output-';
function output(data) {
var timestamp = +new Date();
var path = [basePath, '/', prefix, timestamp, '.json'].join('');
var toStdOut = {'path': path, 'timestamp': timestamp};
// output to file because of limitations of stdout-kb-size (for debugging)
fs.write(path, JSON.stringify(data, null, 4), 'w');
if (data.systemError === true){
toStdOut.systemError = true;
if (data.common){
if (data.common.errors){
toStdOut.errors = data.common.errors;
}
if (data.common.systemErrors){
toStdOut.systemErrors = data.common.systemErrors;
}
}
}
// output to stdout
console.log(
JSON.stringify(toStdOut)
);
}
function systemError(data) {
data.systemError = true;
output(data);
phantom.exit(1);
}
// phantom breaking errors, most likely error in current file or arguments too the process
phantom.onError = function (msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function (t) {
var fn = (t.function ? ' (in function ' + t.function +')' : '');
msgStack.push(' -> ' + (t.file || t.sourceURL) + ':' + t.line + fn);
});
}
systemError({
message: msg,
stack: msgStack.join('\n')
});
return false;
};
var page = require('webpage').create();
var result = {
common: {
startTime: new Date(),
systemErrors: [],
errors: []
}
};
page.onError = function (message, trace) {
result.common.errors.push({
type: 'main::page.error',
message: message,
trace: trace.map(function(entry){
return {
line: entry.line,
sourceURL: entry.file,
'function': entry['function']
};
}),
date: new Date()
});
return true;
};
var createHooks;
var hooksApi;
try {
createHooks = require('./createHooks.js');
hooksApi = require('./hooksApi.js');
} catch (e) {
systemError({
message: 'Failed require inline modules:' + e.message,
trace: getSource(e)
});
}
if (system.args.length <= 1) {
systemError({
message: 'Missing arguments / options'
});
} else {
// Extended by defaults before injected
var opt = page.options = JSON.parse(system.args[1]);
// debug
// result.input = opt;
basePath = opt.outputDirectory;
// Init Hooks
var api;
try {
api = hooksApi(phantom, page, result);
api.trigger = createHooks(page, opt, api, result);
} catch (e) {
if (e) {
systemError({
message: 'Failed to create hooks:' + e.message,
trace: getSource(e)
});
}
}
/*
CONFIG:
*/
page.customHeaders = opt.headers;
page.settings.userAgent = opt.userAgent;
page.viewportSize = {
width: opt.viewport.width,
height: opt.viewport.height
};
page.javaScriptConsoleMessageSent('!internal - Page.open starting, opening up '+opt.parentUrl);
page.open(opt.parentUrl, function (status) {
if (status !== 'success') {
return systemError({
message: 'Failed to load the url: ' + opt.parentUrl,
key: 'pageUrl',
catchedBy: 'phantom.open'
});
}
try {
api.trigger('onPageOpen');
} catch (e) {
if (e) {
return systemError({
message: 'Failed to trigger onOpen: ' + e.message,
trace: getSource(e)
});
}
}
setTimeout(function(){
try {
api.trigger('onHalfTime');
} catch (e) {
if (e) {
return systemError({
message: 'Failed to trigger onHalfTime: ' + e.message,
trace: getSource(e)
});
}
}
}, Math.round(opt.pageRunTime / 2));
setTimeout(function () {
page.javaScriptConsoleMessageSent('!internal - Exit started');
try {
api.trigger('onBeforeExit');
} catch (e) {
if (e) {
return systemError({
message: 'Failed to trigger onBeforeExit: ' + e.message,
trace: getSource(e)
});
}
}
page.javaScriptConsoleMessageSent('!internal - Exit done');
//finish off
result.common.endTime = new Date();
output(result);
phantom.exit();
}, opt.pageRunTime);
});
}
|
define([
'lib/pluginManager'
], (pluginManager) => {
describe('Check out the KBaseServiceManager module exists', () => {
it('module loads', () => {
expect(pluginManager).toBeTruthy();
});
});
// describe('Instantiate with good and bad values', function () {
// it('Good values, but wouldnt run an app.', function (done) {
// var rootNode = document.createElement('div');
// rootNode.id = 'myrootnode';
// document.body.appendChild(rootNode);
// var app = App.make({
// appConfig: {
// some: 'property'
// },
// nodes: {
// root: {
// selector: '#myrootnode'
// }
// },
// plugins: [],
// services: {}
// });
// expect(app).toBeTruthy();
// done();
// });
// });
});
|
'use strict';
const test = require('tape').test
const fs = require('fs')
const tls = require('tls')
const persistents = require('../')
const provider = require('./util/get-provider')('TLSWRAP')
const PORT = 3000
const fixturesDir = __dirname + '/fixtures';
function resWithServer(results) {
for (let i = 0; i < results.length; i++)
if (results[i].owner && results[i].owner.server) return results[i]
}
test('\ntlswrap: tls.creatServer then tls.connect ', function (t) {
const options = {
key: fs.readFileSync(fixturesDir + '/ec-key.pem'),
cert: fs.readFileSync(fixturesDir + '/ec-cert.pem')
}
const server = tls.createServer(options).listen(PORT, function() {
tls.connect(PORT, { rejectUnauthorized: false }, onconnected);
const res = persistents.collect()[provider]
t.equal(res.length, 1, 'initially one tlswrap')
})
function onconnected() {
const res = persistents.collect()[provider]
t.equal(res.length, 2, 'after connected two tlswraps')
t.equal(resWithServer(res).owner.server.key, options.key, 'the first one is the server we created')
this.destroy()
server.close(t.end)
}
})
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, Mustache */
/*unittests: FindReplace*/
/**
* Adds Find and Replace commands
*
* Originally based on the code in CodeMirror2/lib/util/search.js.
*/
define(function (require, exports, module) {
"use strict";
var CommandManager = require("command/CommandManager"),
AppInit = require("utils/AppInit"),
Commands = require("command/Commands"),
DocumentManager = require("document/DocumentManager"),
ProjectManager = require("project/ProjectManager"),
Strings = require("strings"),
StringUtils = require("utils/StringUtils"),
Editor = require("editor/Editor"),
EditorManager = require("editor/EditorManager"),
FindBar = require("search/FindBar").FindBar,
FindUtils = require("search/FindUtils"),
FindInFilesUI = require("search/FindInFilesUI"),
ScrollTrackMarkers = require("search/ScrollTrackMarkers"),
PanelManager = require("view/PanelManager"),
Resizer = require("utils/Resizer"),
StatusBar = require("widgets/StatusBar"),
PreferencesManager = require("preferences/PreferencesManager"),
_ = require("thirdparty/lodash"),
CodeMirror = require("thirdparty/CodeMirror2/lib/codemirror");
/**
* Maximum file size to search within (in chars)
* @const {number}
*/
var FIND_MAX_FILE_SIZE = 500000;
/**
* If the number of matches exceeds this limit, inline text highlighting and scroll-track tickmarks are disabled
* @const {number}
*/
var FIND_HIGHLIGHT_MAX = 2000;
/**
* Instance of the currently opened document when replaceAllPanel is visible
* @type {?Document}
*/
var currentDocument = null;
/**
* Currently open Find or Find/Replace bar, if any
* @type {?FindBar}
*/
var findBar;
function SearchState() {
this.searchStartPos = null;
this.parsedQuery = null;
this.queryInfo = null;
this.foundAny = false;
this.marked = [];
this.resultSet = [];
this.matchIndex = -1;
this.markedCurrent = null;
}
function getSearchState(cm) {
if (!cm._searchState) {
cm._searchState = new SearchState();
}
return cm._searchState;
}
function getSearchCursor(cm, state, pos) {
// Heuristic: if the query string is all lowercase, do a case insensitive search.
return cm.getSearchCursor(state.parsedQuery, pos, !state.queryInfo.isCaseSensitive);
}
function parseQuery(queryInfo) {
if (findBar) {
findBar.showError(null);
}
if (!queryInfo || !queryInfo.query) {
return "";
}
// Is it a (non-blank) regex?
if (queryInfo.isRegexp) {
try {
return new RegExp(queryInfo.query, queryInfo.isCaseSensitive ? "" : "i");
} catch (e) {
if (findBar) {
findBar.showError(e.message);
}
return "";
}
} else {
return queryInfo.query;
}
}
/**
* @private
* Determine the query from the given info and store it in the state.
* @param {SearchState} state The state to store the parsed query in
* @param {{query: string, caseSensitive: boolean, isRegexp: boolean}} queryInfo
* The query info object as returned by FindBar.getQueryInfo()
*/
function setQueryInfo(state, queryInfo) {
state.queryInfo = queryInfo;
if (!queryInfo) {
state.parsedQuery = null;
} else {
state.parsedQuery = parseQuery(queryInfo);
}
}
/**
* @private
* Show the current match index by finding matchRange in the resultSet stored
* in the search state if this is the first call for a new search query. For
* subsequent calls, just compare matchRange with the next match in the resultSet
* based on the search direction and show the next match if they are the same.
* If not, then find the match index by searching matchRange in the entire resultSet.
*
* @param {!SearchState} state The search state that has the array of search result
* @param {!{from: {line: number, ch: number}, to: {line: number, ch: number}}} matchRange - the range of current match
* @param {!boolean} searchBackwards true if searching backwards
*/
function _updateFindBarWithMatchInfo(state, matchRange, searchBackwards) {
// Bail if there is no result set.
if (!state.foundAny) {
return;
}
if (findBar) {
if (state.matchIndex === -1) {
state.matchIndex = _.findIndex(state.resultSet, matchRange);
} else {
state.matchIndex = searchBackwards ? state.matchIndex - 1 : state.matchIndex + 1;
// Adjust matchIndex for modulo wraparound
state.matchIndex = (state.matchIndex + state.resultSet.length) % state.resultSet.length;
// Confirm that we find the right matchIndex. If not, then search
// matchRange in the entire resultSet.
if (!_.isEqual(state.resultSet[state.matchIndex], matchRange)) {
state.matchIndex = _.findIndex(state.resultSet, matchRange);
}
}
if (state.matchIndex !== -1) {
// Convert to 1-based by adding one before showing the index.
findBar.showFindCount(StringUtils.format(Strings.FIND_MATCH_INDEX,
state.matchIndex + 1, state.resultSet.length));
}
}
}
/**
* @private
* Returns the next match for the current query (from the search state) before/after the given position. Wraps around
* the end of the document if no match is found before the end.
*
* @param {!Editor} editor The editor to search in
* @param {boolean} searchBackwards true to search backwards
* @param {{line: number, ch: number}=} pos The position to start from. Defaults to the current primary selection's
* head cursor position.
* @param {boolean=} wrap Whether to wrap the search around if we hit the end of the document. Default true.
* @return {?{start: {line: number, ch: number}, end: {line: number, ch: number}}} The range for the next match, or
* null if there is no match.
*/
function _getNextMatch(editor, searchBackwards, pos, wrap) {
var cm = editor._codeMirror;
var state = getSearchState(cm);
var cursor = getSearchCursor(cm, state, pos || editor.getCursorPos(false, searchBackwards ? "start" : "end"));
state.lastMatch = cursor.find(searchBackwards);
if (!state.lastMatch && wrap !== false) {
// If no result found before hitting edge of file, try wrapping around
cursor = getSearchCursor(cm, state, searchBackwards ? {line: cm.lineCount() - 1} : {line: 0, ch: 0});
state.lastMatch = cursor.find(searchBackwards);
}
if (!state.lastMatch) {
// No result found, period: clear selection & bail
cm.setCursor(editor.getCursorPos()); // collapses selection, keeping cursor in place to avoid scrolling
return null;
}
return {start: cursor.from(), end: cursor.to()};
}
/**
* @private
* Sets the given selections in the editor and applies some heuristics to determine whether and how we should
* center the primary selection.
*
* @param {!Editor} editor The editor to search in
* @param {!Array<{start:{line:number, ch:number}, end:{line:number, ch:number}, primary:boolean, reversed: boolean}>} selections
* The selections to set. Must not be empty.
* @param {boolean} center Whether to try to center the primary selection vertically on the screen. If false, the selection will still be scrolled
* into view if it's offscreen, but will not be centered.
* @param {boolean=} preferNoScroll If center is true, whether to avoid scrolling if the hit is in the top half of the screen. Default false.
*/
function _selectAndScrollTo(editor, selections, center, preferNoScroll) {
var primarySelection = _.find(selections, function (sel) { return sel.primary; }) || _.last(selections),
resultVisible = editor.isLineVisible(primarySelection.start.line),
centerOptions = Editor.BOUNDARY_CHECK_NORMAL;
if (preferNoScroll && resultVisible) {
// no need to scroll if the line with the match is in view
centerOptions = Editor.BOUNDARY_IGNORE_TOP;
}
// Make sure the primary selection is fully visible on screen.
var primary = _.find(selections, function (sel) {
return sel.primary;
});
if (!primary) {
primary = _.last(selections);
}
editor._codeMirror.scrollIntoView({from: primary.start, to: primary.end});
editor.setSelections(selections, center, centerOptions);
}
/**
* Returns the range of the word surrounding the given editor position. Similar to getWordAt() from CodeMirror.
*
* @param {!Editor} editor The editor to search in
* @param {!{line: number, ch: number}} pos The position to find a word at.
* @return {{start:{line: number, ch: number}, end:{line:number, ch:number}, text:string}} The range and content of the found word. If
* there is no word, start will equal end and the text will be the empty string.
*/
function _getWordAt(editor, pos) {
var cm = editor._codeMirror,
start = pos.ch,
end = start,
line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) {
--start;
}
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) {
++end;
}
return {start: {line: pos.line, ch: start}, end: {line: pos.line, ch: end}, text: line.slice(start, end)};
}
/**
* @private
* Helper function. Returns true if two selections are equal.
* @param {!{start: {line: number, ch: number}, end: {line: number, ch: number}}} sel1 The first selection to compare
* @param {!{start: {line: number, ch: number}, end: {line: number, ch: number}}} sel2 The second selection to compare
* @return {boolean} true if the selections are equal
*/
function _selEq(sel1, sel2) {
return (CodeMirror.cmpPos(sel1.start, sel2.start) === 0 && CodeMirror.cmpPos(sel1.end, sel2.end) === 0);
}
/**
* Expands each empty range in the selection to the nearest word boundaries. Then, if the primary selection
* was already a range (even a non-word range), adds the next instance of the contents of that range as a selection.
*
* @param {!Editor} editor The editor to search in
* @param {boolean=} removePrimary Whether to remove the current primary selection in addition to adding the
* next one. If true, we add the next match even if the current primary selection is a cursor (we expand it
* first to determine what to match).
*/
function _expandWordAndAddNextToSelection(editor, removePrimary) {
editor = editor || EditorManager.getActiveEditor();
if (!editor) {
return;
}
var selections = editor.getSelections(),
primarySel,
primaryIndex,
searchText,
added = false;
_.each(selections, function (sel, index) {
var isEmpty = (CodeMirror.cmpPos(sel.start, sel.end) === 0);
if (sel.primary) {
primarySel = sel;
primaryIndex = index;
if (!isEmpty) {
searchText = editor.document.getRange(primarySel.start, primarySel.end);
}
}
if (isEmpty) {
var wordInfo = _getWordAt(editor, sel.start);
sel.start = wordInfo.start;
sel.end = wordInfo.end;
if (sel.primary && removePrimary) {
// Get the expanded text, even though we're going to remove this selection,
// since in this case we still want to select the next match.
searchText = wordInfo.text;
}
}
});
if (searchText && searchText.length) {
// We store this as a query in the state so that if the user next does a "Find Next",
// it will use the same query (but throw away the existing selection).
var state = getSearchState(editor._codeMirror);
setQueryInfo(state, { query: searchText, isCaseSensitive: false, isRegexp: false });
// Skip over matches that are already in the selection.
var searchStart = primarySel.end,
nextMatch,
isInSelection;
do {
nextMatch = _getNextMatch(editor, false, searchStart);
if (nextMatch) {
// This is a little silly, but if we just stick the equivalence test function in here
// JSLint complains about creating a function in a loop, even though it's safe in this case.
isInSelection = _.find(selections, _.partial(_selEq, nextMatch));
searchStart = nextMatch.end;
// If we've gone all the way around, then all instances must have been selected already.
if (CodeMirror.cmpPos(searchStart, primarySel.end) === 0) {
nextMatch = null;
break;
}
}
} while (nextMatch && isInSelection);
if (nextMatch) {
nextMatch.primary = true;
selections.push(nextMatch);
added = true;
}
}
if (removePrimary) {
selections.splice(primaryIndex, 1);
}
if (added) {
// Center the new match, but avoid scrolling to matches that are already on screen.
_selectAndScrollTo(editor, selections, true, true);
} else {
// If all we did was expand some selections, don't center anything.
_selectAndScrollTo(editor, selections, false);
}
}
function _skipCurrentMatch(editor) {
return _expandWordAndAddNextToSelection(editor, true);
}
/**
* Takes the primary selection, expands it to a word range if necessary, then sets the selection to
* include all instances of that range. Removes all other selections. Does nothing if the selection
* is not a range after expansion.
*/
function _findAllAndSelect(editor) {
editor = editor || EditorManager.getActiveEditor();
if (!editor) {
return;
}
var sel = editor.getSelection(),
newSelections = [];
if (CodeMirror.cmpPos(sel.start, sel.end) === 0) {
sel = _getWordAt(editor, sel.start);
}
if (CodeMirror.cmpPos(sel.start, sel.end) !== 0) {
var searchStart = {line: 0, ch: 0},
state = getSearchState(editor._codeMirror),
nextMatch;
setQueryInfo(state, { query: editor.document.getRange(sel.start, sel.end), isCaseSensitive: false, isRegexp: false });
while ((nextMatch = _getNextMatch(editor, false, searchStart, false)) !== null) {
if (_selEq(sel, nextMatch)) {
nextMatch.primary = true;
}
newSelections.push(nextMatch);
searchStart = nextMatch.end;
}
// This should find at least the original selection, but just in case...
if (newSelections.length) {
// Don't change the scroll position.
editor.setSelections(newSelections, false);
}
}
}
/** Removes the current-match highlight, leaving all matches marked in the generic highlight style */
function clearCurrentMatchHighlight(cm, state) {
if (state.markedCurrent) {
state.markedCurrent.clear();
}
}
/**
* Selects the next match (or prev match, if searchBackwards==true) starting from either the current position
* (if pos unspecified) or the given position (if pos specified explicitly). The starting position
* need not be an existing match. If a new match is found, sets to state.lastMatch either the regex
* match result, or simply true for a plain-string match. If no match found, sets state.lastMatch
* to false.
* @param {!Editor} editor
* @param {?boolean} searchBackwards
* @param {?boolean} preferNoScroll
* @param {?Pos} pos
*/
function findNext(editor, searchBackwards, preferNoScroll, pos) {
var cm = editor._codeMirror;
cm.operation(function () {
var state = getSearchState(cm);
clearCurrentMatchHighlight(cm, state);
var nextMatch = _getNextMatch(editor, searchBackwards, pos);
if (nextMatch) {
_updateFindBarWithMatchInfo(getSearchState(editor._codeMirror),
{from: nextMatch.start, to: nextMatch.end}, searchBackwards);
_selectAndScrollTo(editor, [nextMatch], true, preferNoScroll);
state.markedCurrent = cm.markText(nextMatch.start, nextMatch.end,
{ className: "searching-current-match", startStyle: "searching-first", endStyle: "searching-last" });
} else {
cm.setCursor(editor.getCursorPos()); // collapses selection, keeping cursor in place to avoid scrolling
}
});
}
/** Clears all match highlights, including the current match */
function clearHighlights(cm, state) {
cm.operation(function () {
state.marked.forEach(function (markedRange) {
markedRange.clear();
});
clearCurrentMatchHighlight(cm, state);
});
state.marked.length = 0;
state.markedCurrent = null;
ScrollTrackMarkers.clear();
state.resultSet = [];
state.matchIndex = -1;
}
function clearSearch(cm) {
cm.operation(function () {
var state = getSearchState(cm);
if (!state.parsedQuery) {
return;
}
setQueryInfo(state, null);
clearHighlights(cm, state);
});
}
function toggleHighlighting(editor, enabled) {
// Temporarily change selection color to improve highlighting - see LESS code for details
if (enabled) {
$(editor.getRootElement()).addClass("find-highlighting");
} else {
$(editor.getRootElement()).removeClass("find-highlighting");
}
ScrollTrackMarkers.setVisible(editor, enabled);
}
/**
* Called each time the search query changes or document is modified (via Replace). Updates
* the match count, match highlights and scrollbar tickmarks. Does not change the cursor pos.
*/
function updateResultSet(editor) {
var cm = editor._codeMirror,
state = getSearchState(cm);
function indicateHasMatches(numResults) {
// Make the field red if it's not blank and it has no matches (which also covers invalid regexes)
findBar.showNoResults(!state.foundAny && findBar.getQueryInfo().query);
// Navigation buttons enabled if we have a query and more than one match
findBar.enableNavigation(state.foundAny && numResults > 1);
findBar.enableReplace(state.foundAny);
}
cm.operation(function () {
// Clear old highlights
if (state.marked) {
clearHighlights(cm, state);
}
if (!state.parsedQuery) {
// Search field is empty - no results
findBar.showFindCount("");
state.foundAny = false;
indicateHasMatches();
return;
}
// Find *all* matches, searching from start of document
// (Except on huge documents, where this is too expensive)
var cursor = getSearchCursor(cm, state);
if (cm.getValue().length <= FIND_MAX_FILE_SIZE) {
// FUTURE: if last query was prefix of this one, could optimize by filtering last result set
state.resultSet = [];
while (cursor.findNext()) {
state.resultSet.push(cursor.pos); // pos is unique obj per search result
}
// Highlight all matches if there aren't too many
if (state.resultSet.length <= FIND_HIGHLIGHT_MAX) {
toggleHighlighting(editor, true);
state.resultSet.forEach(function (result) {
state.marked.push(cm.markText(result.from, result.to,
{ className: "CodeMirror-searching", startStyle: "searching-first", endStyle: "searching-last" }));
});
var scrollTrackPositions = state.resultSet.map(function (result) {
return result.from;
});
ScrollTrackMarkers.addTickmarks(editor, scrollTrackPositions);
}
// Here we only update find bar with no result. In the case of a match
// a findNext() call is guaranteed to be followed by this function call,
// and findNext() in turn calls _updateFindBarWithMatchInfo() to show the
// match index.
if (state.resultSet.length === 0) {
findBar.showFindCount(Strings.FIND_NO_RESULTS);
}
state.foundAny = (state.resultSet.length > 0);
indicateHasMatches(state.resultSet.length);
} else {
// On huge documents, just look for first match & then stop
findBar.showFindCount("");
state.foundAny = cursor.findNext();
indicateHasMatches();
}
});
}
/**
* Called each time the search query field changes. Updates state.parsedQuery (parsedQuery will be falsy if the field
* was blank OR contained a regexp with invalid syntax). Then calls updateResultSet(), and then jumps to
* the first matching result, starting from the original cursor position.
* @param {!Editor} editor The editor we're searching in.
* @param {Object} state The current query state.
* @param {boolean} initial Whether this is the initial population of the query when the search bar opens.
* In that case, we don't want to change the selection unnecessarily.
*/
function handleQueryChange(editor, state, initial) {
setQueryInfo(state, findBar.getQueryInfo());
updateResultSet(editor);
if (state.parsedQuery) {
// 3rd arg: prefer to avoid scrolling if result is anywhere within view, since in this case user
// is in the middle of typing, not navigating explicitly; viewport jumping would be distracting.
findNext(editor, false, true, state.searchStartPos);
} else if (!initial) {
// Blank or invalid query: just jump back to initial pos
editor._codeMirror.setCursor(state.searchStartPos);
}
}
/**
* Creates a Find bar for the current search session.
* @param {!Editor} editor
* @param {boolean} replace Whether to show the Replace UI; default false
*/
function openSearchBar(editor, replace) {
var cm = editor._codeMirror,
state = getSearchState(cm);
// Use the selection start as the searchStartPos. This way if you
// start with a pre-populated search and enter an additional character,
// it will extend the initial selection instead of jumping to the next
// occurrence.
state.searchStartPos = editor.getCursorPos(false, "start");
// Prepopulate the search field
var initialQuery;
if (findBar) {
// Use the previous query. This can happen if the user switches from Find to Replace.
initialQuery = findBar.getQueryInfo().query;
} else {
initialQuery = FindUtils.getInitialQueryFromSelection(editor);
}
// Close our previous find bar, if any. (The open() of the new findBar will
// take care of closing any other find bar instances.)
if (findBar) {
findBar.close();
}
// Create the search bar UI (closing any previous find bar in the process)
findBar = new FindBar({
multifile: false,
replace: replace,
initialQuery: initialQuery,
queryPlaceholder: Strings.FIND_QUERY_PLACEHOLDER
});
findBar.open();
$(findBar)
.on("queryChange.FindReplace", function (e) {
handleQueryChange(editor, state);
})
.on("doFind.FindReplace", function (e, searchBackwards) {
findNext(editor, searchBackwards);
})
.on("close.FindReplace", function (e) {
// Clear highlights but leave search state in place so Find Next/Previous work after closing
clearHighlights(cm, state);
// Dispose highlighting UI (important to restore normal selection color as soon as focus goes back to the editor)
toggleHighlighting(editor, false);
$(findBar).off(".FindReplace");
findBar = null;
});
handleQueryChange(editor, state, true);
}
/**
* If no search pending, opens the Find dialog. If search bar already open, moves to
* next/prev result (depending on 'searchBackwards')
*/
function doSearch(editor, searchBackwards) {
var state = getSearchState(editor._codeMirror);
if (state.parsedQuery) {
findNext(editor, searchBackwards);
return;
}
openSearchBar(editor, false);
}
/**
* @private
* When the user switches documents (or closes the last document), ensure that the find bar
* closes, and also close the Replace All panel.
*/
function _handleDocumentChange() {
if (findBar) {
findBar.close();
}
}
function doReplace(editor, all) {
var cm = editor._codeMirror,
state = getSearchState(cm),
replaceText = findBar.getReplaceText();
if (all) {
findBar.close();
// Delegate to Replace in Files.
FindInFilesUI.searchAndShowResults(state.queryInfo, editor.document.file, null, replaceText);
} else {
cm.replaceSelection(state.queryInfo.isRegexp ? FindUtils.parseDollars(replaceText, state.lastMatch) : replaceText);
updateResultSet(editor); // we updated the text, so result count & tickmarks must be refreshed
findNext(editor);
if (!state.lastMatch) {
// No more matches, so destroy find bar
findBar.close();
}
}
}
function replace(editor) {
// If Replace bar already open, treat the shortcut as a hotkey for the Replace button
if (findBar && findBar.getOptions().replace && findBar.isReplaceEnabled()) {
doReplace(editor, false);
return;
}
openSearchBar(editor, true);
$(findBar)
.on("doReplace.FindReplace", function (e) {
doReplace(editor, false);
})
.on("doReplaceAll.FindReplace", function (e) {
doReplace(editor, true);
});
}
function _launchFind() {
var editor = EditorManager.getActiveEditor();
if (editor) {
// Create a new instance of the search bar UI
clearSearch(editor._codeMirror);
doSearch(editor, false);
}
}
function _findNext() {
var editor = EditorManager.getActiveEditor();
if (editor) {
doSearch(editor);
}
}
function _findPrevious() {
var editor = EditorManager.getActiveEditor();
if (editor) {
doSearch(editor, true);
}
}
function _replace() {
var editor = EditorManager.getActiveEditor();
if (editor) {
replace(editor);
}
}
$(DocumentManager).on("currentDocumentChange", _handleDocumentChange);
CommandManager.register(Strings.CMD_FIND, Commands.CMD_FIND, _launchFind);
CommandManager.register(Strings.CMD_FIND_NEXT, Commands.CMD_FIND_NEXT, _findNext);
CommandManager.register(Strings.CMD_REPLACE, Commands.CMD_REPLACE, _replace);
CommandManager.register(Strings.CMD_FIND_PREVIOUS, Commands.CMD_FIND_PREVIOUS, _findPrevious);
CommandManager.register(Strings.CMD_FIND_ALL_AND_SELECT, Commands.CMD_FIND_ALL_AND_SELECT, _findAllAndSelect);
CommandManager.register(Strings.CMD_ADD_NEXT_MATCH, Commands.CMD_ADD_NEXT_MATCH, _expandWordAndAddNextToSelection);
CommandManager.register(Strings.CMD_SKIP_CURRENT_MATCH, Commands.CMD_SKIP_CURRENT_MATCH, _skipCurrentMatch);
// For unit testing
exports._getWordAt = _getWordAt;
exports._expandWordAndAddNextToSelection = _expandWordAndAddNextToSelection;
exports._findAllAndSelect = _findAllAndSelect;
});
|
const WebKit = require('../');
const expect = require('expect.js');
const fs = require('fs');
const Path = require('path');
const rimraf = require('rimraf');
// this test doesn't really work
describe("init method", () => {
before((done) => {
rimraf(Path.join(__dirname, '..', 'cache/test?'), done);
});
it("should initialize cacheDir with call to init", function(done) {
this.timeout(10000);
WebKit({cacheDir: "cache/test1"}, (err, w) => {
expect(err).to.not.be.ok();
w.load('http://google.com', (err) => {
fs.exists("./cache/test1", (yes) => {
expect(yes).to.be.ok();
done();
});
});
});
});
it("should clear cache", function(done) {
this.timeout(15000);
let count = 0;
const server = require('http').createServer((req, res) => {
if (req.url == '/index.html') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 'public, max-age=100000');
res.setHeader('Last-Modified', (new Date()).toUTCString());
res.setHeader('Expires', (new Date(Date.now() + 100000000)).toUTCString());
res.end("<!doctype html><html><head><script src='test.js'></script></head></html>");
} else if (req.url == "/test.js") {
res.setHeader('Content-Type', 'text/javascript');
res.setHeader('Cache-Control', 'public, max-age=100000');
res.setHeader('Last-Modified', (new Date()).toUTCString());
res.setHeader('Expires', (new Date(Date.now() + 100000000)).toUTCString());
res.end('console.log("me");');
count++;
} else {
res.statusCode = 404;
res.end("Not Found");
}
}).listen(() => {
const url = `http://localhost:${server.address().port}/index.html`;
let w;
WebKit({cacheDir: "cache/test2"}).then((inst) => {
w = inst;
return w.load(url).when('idle');
}).then(() => {
return w.load(url).when('idle');
}).then(() => {
expect(count).to.be(1);
w.clearCache();
return new Promise((resolve) => {
setTimeout(resolve, 100);
});
}).then(() => {
return w.load(url).when('idle');
}).then(() => {
expect(count).to.be(2);
done();
}).catch((err) => {
setImmediate(() => {
throw err;
});
});
});
});
});
|
const sj = require("../");
const vm = require("vm");
const net = require("net");
const server = net.createServer(
{ allowHalfOpen: true },
(stream) => {
const output = new sj.DataStream();
output.JSONStringify().pipe(stream);
const input = stream.pipe(new sj.StringStream())
.JSONParse()
.shift(1, async ([msg]) => {
server.unref();
try {
const transforms = msg.transforms.map((func) => {
if (typeof func === "string") {
return vm.runInThisContext(func);
} else if (!Array.isArray(func)) {
throw new Error("Transforms must come as functions or Array's");
}
let ret = require(func[0]);
if (func[1]) {
ret = func[1]
.split(".")
.reduce(
(acc, key) => acc[key],
ret
);
}
return ret.bind(...func.slice(2));
});
if (msg.plugins)
for (let plugin of msg.plugins) {
sj.plugin(require(plugin));
}
let current = input.pipe(
new sj[msg.streamClass]()
);
for (let transform of transforms) {
current = await transform(current);
}
current
// this requires a better protocol with error resolution down stream
.catch(({ message, stack }) => output.end({ error: { message, stack } }))
.pipe(output);
} catch (e) {
const { message, stack } = e;
return output.whenWrote({ error: { message, stack } })
.then(output.end());
}
});
}
);
server.listen(0, process.argv[2], () => {
const port = server.address().port;
process.send({ port });
});
if (+process.argv[3]) setTimeout(() => server.unref(), +process.argv[3]);
process.on("error", e => process.send({ error: { message: e.message, stack: e.stack } }));
process.on("unhandledRejection", e => process.send({ error: { message: e.message, stack: e.stack } }));
|
Numbers.test = {};
Numbers.test.toRoman = function(assert, json) {
var test;
var message = function(param, expected) {
return 'Converting ' + param + ' into ' + expected;
};
for (var i = 1; i <= json.numbers.length; i++) {
assert.strictEqual(Numbers.toRoman(i), json.numbers[i-1], message(i, json.numbers[i-1]));
}
for (var i = 0; i < json.special.length; i++) {
test = json.special[i];
assert.strictEqual(Numbers.toRoman(test.params), test.expected, message(test.params, test.expected));
}
};
QUnit.test("Roman numbers conversion", new Tests().remote('data/roman.json').test(Numbers.test.toRoman));
|
const throttle = function (func, wait, options = {
heading: true, // 是否需要头部,false表示不需要
trailing: true, // 是否需要最后一次执行,false表示不需要
}) {
let timeout;
let context;
let args;
let pre = 0;
let next = function () {
pre = options.heading === false ? 0 : Date.now();
func.apply(context, args);
timeout = context = args = null;
};
let throttled = function () {
let now = Date.now();
if (!pre && options.heading === false) {
pre = now;
}
let remaining = wait - (now - pre);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
timeout && clearTimeout(timeout);
pre = now;
func.apply(context, args);
timeout = context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(next, remaining);
}
};
return throttled;
};
module.exports = {
throttle,
}; |
const express = require('express');
const graphqlHTTP = require('express-graphql');
const Scrapper = require('../index');
const schema = require('../graph/schema');
const converter = require('../graph/gqlConverter');
const mockedData = require('../sampleData/example.json') || {};
const scrapper = new Scrapper();
class OverScrapServer {
constructor(config) {
this.server = express();
this.server.get('/api', (req, res) => {
const { tag, region, mode } = req.query;
if (!tag || !region || !mode) {
res.status(400).json({ error: 'Invalid parameters, missing at least tag, region or mode query param' });
}
this.scrap(req.query.tag, req.query.region, req.query.gameMode).then(data => {
res.json(data);
});
});
this.server.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: {
statsByHeroName: (options) => {
return this.scrap(options.battleTag, options.region, options.mode)
.then(data => {
const singleHeroStats = converter.selectHeroStats(data.heroesStats, options.heroName);
const rawHeroStats = converter.compressHeroDataKeys(singleHeroStats);
converter.moveHeroSpecificDataFromMiscToHeroSpecific(rawHeroStats);
return {
name: options.heroName,
heroSpecific: { raw: rawHeroStats.heroSpecific },
combat: rawHeroStats.combat,
assists: rawHeroStats.assists,
best: rawHeroStats.best,
average: rawHeroStats.average,
deaths: rawHeroStats.deaths ? rawHeroStats.deaths.deaths : null,
matchAwards: rawHeroStats.matchAwards,
game: rawHeroStats.game,
miscellaneous: rawHeroStats.miscellaneous,
kdr: rawHeroStats.kdr,
raw:data,
};
});
},
},
graphiql: true,
}));
this.port = config.port;
}
scrap(tag, region, mode) {
if (process.env['OVERSCRAP_ENV'] === 'production') {
return scrapper.loadDataFromProfile(tag, region, mode);
} else {
return Promise.resolve(mockedData);
}
}
start() {
if (!this.instance) {
this.instance = this.server.listen(this.port, () => {
console.log(`Server running on port:${this.instance.address().port}`); // eslint-disable-line
});
return true;
}
return false;
}
stop() {
if (this.instance) {
this.instance.close(() => {
delete this.instance;
console.log('Server shutdown complete'); // eslint-disable-line
});
return true;
}
return false;
}
}
const initServer = config => {
return new OverScrapServer(config);
};
module.exports = initServer;
|
/**
* Place your JS-code here.
*/
$(document).ready(function(){
'use strict';
// Function to update shopping cart
var updateCart = function(data) {
$('#content').html(data.content);
$('#numitems').html(data.numitems);
$('#sum').html(data.sum);
$('#status').html('Shopping cart refreshed.');
$.each(data.items, function(){
console.log('item.');
});
setTimeout(function(){
$('#status').fadeOut(function(){
$('#status').html('').fadeIn();
});
}, 1000);
console.log('Shopping cart updated.');
};
// Init the shopping cart
var initCart = function() {
$.ajax({
type: 'post',
url: 'shop.php',
dataType: 'json',
success: function(data){
updateCart(data);
console.log('Ajax request returned successfully. Shopping cart initiated.');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
}
});
};
initCart();
// Callback when making a purchase
$('.purchase').click(function() {
var id = $(this).attr('id');
$.ajax({
type: 'post',
url: 'shop.php?action=add',
data: {
itemid: id
},
dataType: 'json',
success: function(data){
updateCart(data);
console.log('Ajax request returned successfully.');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
console.log('Clicked to buy id: ' + id)
});
// Callback to clear all values in shopping cart
$("#clear").click(function() {
$.ajax({
type: 'post',
url: 'shop.php?action=clear',
dataType: 'json',
success: function(data){
updateCart(data);
console.log('Ajax request returned successfully.');
},
error: function(jqXHR, textStatus, errorThrown){
console.log('Ajax request failed: ' + textStatus + ', ' + errorThrown);
},
});
console.log('Clearing shopping cart.')
});
console.log('Ready to roll.');
});
|
'use strict';
/**
* @ngdoc overview
* @name dresdenjsApp
* @description
* # dresdenjsApp
*
* center maps on resize created by ui-gmap-google-map directive.
*/
angular
.module('dresdenjsApp')
.directive('uiGmapGoogleMap', function (uiGmapGoogleMapApi) {
return {
require: '^uiGmapGoogleMap',
scope: false,
link: function (scope, element, attrs, MapCtrl) {
// uiGmapGoogleMapApi is a promise.
// The "then" callback function provides the google.maps object.
uiGmapGoogleMapApi.then(function(maps) {
// get map scope from maps controller
var mapScope = MapCtrl.getScope();
// bind resize event
// http://stackoverflow.com/a/8792945/1146207
// http://hsmoore.com/blog/keep-google-map-v3-centered-when-browser-is-resized/
maps.event.addDomListener(window, "resize", function() {
var gmap = mapScope.map,
center = gmap.getCenter();
maps.event.trigger(gmap, "resize");
gmap.setCenter(center);
});
});
}
};
});
|
function initConf(){/*初始化页面组件配置参数*/
pageName="";
gridToolbar = [btnAdd,btnEdit,btnDel,btnRefresh,btnSearch];
dgConf={
url:'data1.json',
title:label.dg_title,
columns:[[
{field:'itemid',width:80,editor:'text',title:'aa',halign:'center'},
{field:'productid',width:160,editor:'text',title:'aa',halign:'center'},
{field:'unitcost',width:80,editor:'text',title:'aa',halign:'center'},
{field:'attr1',width:280,editor:'text',title:'aa',halign:'center'},
{field:'listprice',width:160,editor:'text',title:'aa',halign:'center'}
]]
};
dg1Conf={
url:'data2.json',
columns:[[
{field:'itemid',width:80,editor:'text',title:'aa',halign:'center'},
{field:'productid',width:160,editor:'text',title:'aa',halign:'center'},
{field:'unitcost',width:80,editor:'text',title:'aa',halign:'center'},
{field:'attr1',width:80,editor:'text',title:'aa',halign:'center'},
{field:'listprice',width:160,editor:'text',title:'aa',halign:'center'}
]]
};
}
function rowChange(rowData){
}
function doSave(callback){
return true;
}
function doUpdate(callback){
return true;
}
function doDelete(callback){
return true;
}
function doSearch(callback){
}
function doCommit(){
return true;
}
$(pageLoad); |
var Contact = DS.Model.extend({
name: DS.attr('string'),
twitter: DS.attr('string'),
notes: DS.attr('string')
});
export default Contact;
|
'use strict';
var Recorder = require('../Recorder');
var self = {
activate: function (game) {
game.recorder = new Recorder();
game.eventEmitter.on(game.PRIZES_SAVED, self.saveRecord);
},
deactivate: function (game) {
game.eventEmitter.removeListener(game.PRIZES_SAVED, self.saveRecord);
},
/**
* save a record of this game
*/
saveRecord: function (game) {
game.recorder.users = game.players;
game.recorder.save(game._id, function (err) {
if (err) {
game.emit('error', err);
}
game.eventEmitter.emit(game.RECORD_SAVED, game);
});
}
};
module.exports = self; |
describe('CrossBrowserTesting', function() {
require('./crossbrowsertesting/tunnel-deps')
require('./crossbrowsertesting/manager')
require('./crossbrowsertesting/tunnel')
})
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function isFolders(preset) {
return preset.toLowerCase().includes('folders');
}
exports.isFolders = isFolders;
function getFunc(preset) {
switch (preset) {
case 'hideFolders':
return (iconsJson) => Object.keys(iconsJson.folderNames).length === 0 &&
iconsJson.iconDefinitions._folder.iconPath === '';
case 'foldersAllDefaultIcon':
return (iconsJson) => Object.keys(iconsJson.folderNames).length === 0 &&
iconsJson.iconDefinitions._folder.iconPath !== '';
default:
throw new Error('Not Implemented');
}
}
exports.getFunc = getFunc;
function getIconName(preset) {
switch (preset) {
case 'angular':
return 'ng';
case 'jsOfficial':
return 'js_official';
case 'tsOfficial':
return 'typescript_official';
case 'jsonOfficial':
return 'json_official';
default:
throw new Error('Not Implemented');
}
}
exports.getIconName = getIconName;
//# sourceMappingURL=helper.js.map |
var current_version = '1.1.1';
var new_version = '2.0.0';
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-replace');
grunt.initConfig({
replace: {
task1: {
options: {
patterns: [
{
match: current_version,
replacement: new_version
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'VERSION.md'
]
}
]
},
task2: {
options: {
patterns: [
{
match: 'dockerizedrupal/backer:' + current_version,
replacement: 'dockerizedrupal/backer:' + new_version
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'docker-compose.yml',
'README.md'
]
}
]
},
task3: {
options: {
patterns: [
{
match: 'git checkout ' + current_version,
replacement: 'git checkout ' + new_version
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'README.md'
]
}
]
},
task4: {
options: {
patterns: [
{
match: '"version": "' + current_version + '"',
replacement: '"version": "' + new_version + '"'
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'package.json'
]
}
]
},
task5: {
options: {
patterns: [
{
match: 'export FACTER_VERSION="' + current_version + '"',
replacement: 'export FACTER_VERSION="' + new_version + '"'
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'src/backer/variables.sh'
]
}
]
},
task6: {
options: {
patterns: [
{
match: 'VERSION = "' + current_version + '"',
replacement: 'VERSION = "' + new_version + '"'
}
],
usePrefix: false
},
files: [
{
expand: true,
src: [
'Vagrantfile'
]
}
]
}
}
});
grunt.registerTask('bump', 'replace');
grunt.registerTask('default', 'replace');
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const main_1 = require("./main");
/**
* represents a Player that the api can interact with
*/
class Player {
/**
* creates the player according to the given string
* @param uuidOrName the name or uuid of the player: interpreted as name if it has less or equal to 16 characters
* otherwise as uuid
*/
constructor(uuidOrName) {
if (uuidOrName.length > 16) {
this._uuid = uuidOrName;
}
else {
this._name = uuidOrName;
}
}
/**
* the uuid of the player
* @return uuid
*/
get uuid() {
return this._uuid;
}
/**
* the name of the player
* @return name
*/
get name() {
return this._name;
}
/**
* requests the [[PlayerInfo global information of the player]] if they aren't cached already
*
* this also updates the name an uuid to the data provided by the api
*
* @param forceRefresh true if the cache should be ignored
* @return a promise that resolves to the information
*/
info(forceRefresh = false) {
return main_1.fetch(main_1.Methods.PLAYER(this.requestUuid), forceRefresh)
.then(res => new main_1.PlayerInfoFactory().fromResponse(res).create())
.then(res => {
this._uuid = res.uuid;
this._name = res.name;
return res;
});
}
/**
* requests information about a player in a certain [[GameType]] and returns a respective [[PlayerGameInfo]]
*
* currently [[PlayerGameInfo]] instances
* * TIMV - [[TimvPlayerGameInfo]]
*
* every other game just uses [[RawPlayerGameInfo]] with the raw data of the response
*
* @param gameType the game to request the data about
* @param forceRefresh should it be requested from the api even if it is cached
* @return a promise that resolves to the respective [[PlayerGameInfo]]
*/
gameInfo(gameType, forceRefresh = false) {
return main_1.fetch(main_1.Methods.PLAYER_GAME_STATS(this.requestUuid, gameType.id), forceRefresh)
.then((res) => new gameType.playerGameInfoFactory().fromResponse(res).create());
}
/**
* returns the uuid if it sets otherwise the name
* @return {string} uuid if existing, name otherwise
*/
get requestUuid() {
return this.uuid ? this.uuid : this.name;
}
}
exports.Player = Player;
//# sourceMappingURL=Player.js.map |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('em-phone-input', 'Integration | Component | em-input', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{em-phone-input}}`);
assert.equal(this.$().text().trim(), '');
});
|
google.load("visualization", "1", {packages:["corechart"], 'language': 'en'});
(function($) {
$(document).ready(function() {
var loading = $('#loading');
$.getJSON("/api/v1/users", function(result) {
var dropdown = $("#user_id");
$.each(result, function(key, value) {
dropdown.append($("<option />").val(value.id).text(value.name));
});
dropdown.show();
loading.hide();
});
$('#user_id').change(function() {
var selected_user = $("#user_id").val(),
chart_div = $('#chart_div'),
avatar_div = $('#avatar'),
avatar_img = $('#avatar img'),
no_data_div = $('#no_data');
if(selected_user) {
no_data_div.hide();
loading.show();
avatar_div.hide();
chart_div.hide();
$.getJSON("/api/v1/presence_weekday/"+selected_user, function(result) {
var data = google.visualization.arrayToDataTable(result),
options = {};
$.get("/api/v1/users/"+selected_user, function(data) {
avatar_img.attr('src', data.image);
});
avatar_div.show();
chart_div.show();
loading.hide();
var chart = new google.visualization.PieChart(chart_div[0]);
chart.draw(data, options);
}).fail(function() {
loading.hide();
no_data_div.show();
});
}
});
});
})(jQuery);
|
var tx = require('../index.js');
//tx.init('test');
tx.end('test');
|
/**
* Created by csharon on 6/18/14.
*/
angular.module('mc.views.ComicList', [
'mc.components.ListGroup',
'xd.services.toastr',
'mc.components.ComicFilter',
'mc.services.ComicListModel'
])
.controller('comicListCtrl', function ($scope, comicListModel) {
$scope.comics = [];
$scope.comicsLoading = false;
$scope.$watch(
function () {
return comicListModel.comics();
},
function (val) {
$scope.comics = val;
}
);
$scope.$watch(
function () {
return comicListModel.comicsLoading();
},
function (val) {
$scope.comicsLoading = val;
}
);
}); |
var app = angular.module('myApp', []),
apiKey = 'MDExODQ2OTg4MDEzNzQ5OTM4Nzg5MzFiZA001',
nprUrl = 'http://api.npr.org/query?id=61&fields=relatedLink,title,byline,text,audio,image,pullQuote,all&output=JSON';
app.factory('audio', function($document) {
var audio = $document[0].createElement('audio');
return audio;
});
app.factory('player', function(audio, $rootScope) {
var player = {
current: null,
progress: 0,
playing: false,
ready: false,
play: function(program) {
if (player.playing)
player.stop();
var url = program.audio[0].format.mp4.$text;
player.current = program;
audio.src = url;
audio.play();
player.playing = true;
},
stop: function() {
if (player.playing) {
audio.pause();
player.playing = false;
player.current = null;
}
},
currentTime: function() {
return audio.currentTime;
},
currentDuration: function() {
return audio.duration;
}
};
audio.addEventListener('canplay', function(evt) {
$rootScope.$apply(function() {
player.ready = true;
});
});
audio.addEventListener('timeupdate', function(evt) {
$rootScope.$apply(function() {
player.progress = player.currentTime();
player.progress_percent = player.progress / player.currentDuration();
});
});
audio.addEventListener('ended', function() {
$rootScope.$apply(player.stop());
});
return player;
});
app.factory('nprService', function($http) {
var doRequest = function(apiKey) {
return $http({
method: 'JSONP',
url: nprUrl + '&apiKey=' + apiKey + '&callback=JSON_CALLBACK'
});
}
return {
programs: function(apiKey) { return doRequest(apiKey); }
};
});
app.directive('nprLink', function() {
return {
restrict: 'EA',
require: ['^ngModel'],
replace: true,
scope: {
ngModel: '=',
player: '='
},
templateUrl: 'views/nprListItem.html',
link: function(scope, ele, attr) {
scope.duration = scope.ngModel.audio[0].duration.$text;
}
}
});
app.directive('playerView', [function(){
return {
restrict: 'EA',
require: ['^ngModel'],
scope: {
ngModel: '='
},
templateUrl: 'views/playerView.html',
link: function(scope, iElm, iAttrs, controller) {
scope.$watch('ngModel.current', function(newVal) {
if (newVal) {
scope.playing = true;
scope.title = scope.ngModel.current.title.$text;
scope.$watch('ngModel.ready', function(newVal) {
if (newVal) {
scope.duration = scope.ngModel.currentDuration();
}
});
scope.$watch('ngModel.progress', function(newVal) {
scope.secondsProgress = scope.ngModel.progress;
scope.percentComplete = scope.ngModel.progress_percent;
});
}
});
scope.stop = function() {
scope.ngModel.stop();
scope.playing = false;
}
}
};
}]);
app.controller('PlayerController', function($scope, nprService, player) {
$scope.player = player;
nprService.programs(apiKey)
.success(function(data, status) {
$scope.programs = data.list.story;
})
});
app.controller('RelatedController', function($scope, player) {
$scope.player = player;
$scope.$watch('player.current', function(newVal) {
if (newVal) {
$scope.related = [];
angular.forEach(newVal.relatedLink, function(link) {
$scope.related.push({link: link.link[0].$text, caption: link.caption.$text});
});
}
});
});
// Parent scope
app.controller('FrameController', function($scope) {
});
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
controller: 'HomeController',
template: '<h2>We are home</h2>'
})
.otherwise({redirectTo: '/'});
}]); |
import { createSelector } from 'reselect';
import { COUNTRY_COMPARE_COLORS } from 'data/constants';
const COUNTRIES_TO_SELECT = 3;
const getCountries = state => state.countriesData || null;
const getLocations = state => state.locations || null;
export const getSelectedCountries = createSelector(
[getCountries, getLocations],
(countries, locations) => {
if (!countries && !countries.length) return null;
const selectedCountriesData = [...locations];
while (selectedCountriesData.length < COUNTRIES_TO_SELECT) {
selectedCountriesData.push(null);
}
const selectedCountries = selectedCountriesData.map(location => {
if (!location) return null;
const countryDetail = countries.find(
country => country.iso_code3 === location
);
return {
label: countryDetail && countryDetail.wri_standard_name,
value: countryDetail && countryDetail.iso_code3
};
});
return selectedCountries;
}
);
export const getHideResetButton = createSelector(
[getSelectedCountries],
countries => countries.filter(c => c && !!c.value).length === 1
);
export const getCountriesOptions = createSelector(
[getCountries, getSelectedCountries],
(countries, selectedCountries) => {
const selectedCountriesLabels = selectedCountries.map(
s => (s ? s.value : null)
);
return countries
.filter(
country => selectedCountriesLabels.indexOf(country.iso_code3) === -1
)
.map(country => ({
label: country.wri_standard_name,
value: country.iso_code3
}));
}
);
export const getCountryConfig = createSelector(
[getSelectedCountries],
countries => {
if (!countries && !countries.length) return null;
return countries.map((country, i) => ({
country,
color: COUNTRY_COMPARE_COLORS[i]
}));
}
);
export default {
getCountriesOptions,
getSelectedCountries,
getCountryConfig
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, compose } from 'redux';
import { Provider, connect } from 'react-redux';
import DevTools from './DevTools';
import reducers from './reducers/FormReducer';
import Form from './components/Form';
const finalCreateStore = compose(
DevTools.instrument()
)(createStore);
const store = finalCreateStore(reducers);
class Root extends React.Component {
render() {
return (
<Provider store={store}>
<div>
<DevTools />
<App />
</div>
</Provider>
);
}
}
@connect(state => {
return {
form: state,
};
})
class App extends React.Component {
render() {
return (
<Form {...this.props.form} dispatch={this.props.dispatch} />
);
}
}
ReactDOM.render(<Root />, document.getElementById('app'));
|
import '../../api/documents/documents.methods'
import '../../api/documents/server/documents.publications'
|
import './Main.html';
import './Guestbook';
import './Home';
Meteor.subscribe("userAvatar");
Meteor.subscribe("images");
|
import React, {PropTypes} from 'react';
import { Link } from 'react-router';
import ForumArray from 'containers/ForumArray';
import TermItem from 'containers/TermItem';
import ContentHolder from 'Organisms/ContentHolder';
class ChapterItem extends React.Component {
static propTypes = {
chapterItem: PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
order: PropTypes.number.isRequired,
}).isRequired
};
bindContentHolderItem = () =>({
uniquePrefix: `chapter-item-with-id-${this.props.chapterItem.id}`,
titleElement: <Link to={`/Conference/Forum/${this.props.chapterItem.id}`}>{this.props.chapterItem.title}</Link>,
bodyContent: <ForumArray chapterId={this.props.chapterItem.id}/>,
firstColumnTerm: <TermItem term={{id: 1, value: 'Topics'}} />,
secondColumnTerm:<TermItem term={{id: 2, value: 'Posts'}} />,
thirdColumnTerm: <TermItem term={{id: 3, value: 'Last message in'}} />
})
collapseSettings = () => ({
collapsable: true,
openedByDefault: false
})
render(){
return(
this.props.chapterItem.id ?
<ContentHolder contentHolderItem={this.bindContentHolderItem()} collapseSettings={this.collapseSettings()} /> :
null
);
}
}
export default ChapterItem;
|
// Polyfill for DOM matches() function for IE11 and Edge
Element.prototype.matches = Element.prototype.matches
|| Element.prototype.msMatchesSelector;
(function () {
const databasesList = document.querySelector('.list');
databasesList.addEventListener('click', function (e) {
if (!e.target || !e.target.matches('button')) {
return;
}
e.preventDefault();
const targetItem = e.target.parentNode.parentNode,
targetButton = e.target;
if (targetItem.classList.contains('expanded')) {
targetItem.classList.remove('expanded');
targetButton.textContent = '+';
targetButton.setAttribute('aria-label', 'Expand');
} else {
targetItem.classList.add('expanded');
targetButton.textContent = '–';
targetButton.setAttribute('aria-label', 'Collapse');
}
targetButton.blur();
});
// For explanation of the filter syntax, take a look here:
// https://github.com/Albert221/FromSelect/issues/9#issuecomment-274047742
const filterField = document.getElementById('filter');
filterField.addEventListener('input', function (e) {
const phrase = filterField.value;
// Split phrase using delimeter `.`.
const phrases = phrase.split('.');
let database, databaseStrict, table, tableStrict;
database = phrases[0];
// Set strict search if phrase is surrounded by quotation marks.
databaseStrict = database.indexOf('"') == 0 && database.indexOf('"', 1) == database.length - 1;
database = database.replace(/"/g, '');
// Set table to database if not specified, so that user can use `foobar` syntax (see issue comment).
table = phrases.length > 1 ? phrases[1] : phrases[0];
tableStrict = table.indexOf('"') == 0 && table.indexOf('"', 1) == table.length - 1;
table = table.replace(/"/g, '');
databasesList.querySelectorAll('li').forEach(el => el.classList.remove('hidden', 'search-expanded'));
// Databases filter.
databasesList.querySelectorAll('.list > li').forEach(databaseEl => {
if (databaseEl.classList.contains('new')) {
return;
}
if (database != '' && table != '') {
databaseEl.classList.add('search-expanded');
}
if (database != '') {
const value = databaseEl.querySelector('a').textContent.replace(/[\–\+]/, '').trim();
if (databaseStrict) {
const pattern = '^' + database + '$';
if (value.search(new RegExp(pattern, 'i')) == -1) {
databaseEl.classList.add('hidden');
}
} else if (value.search(new RegExp(database, 'i')) == -1) {
databaseEl.classList.add('hidden');
}
}
let empty = true;
// Tables filter.
databaseEl.querySelectorAll('li').forEach(tableEl => {
if (table == '') {
empty = false;
return;
}
const value = tableEl.querySelector('a').textContent;
if (tableStrict) {
const pattern = '^' + table + '$';
if (value.search(new RegExp(pattern, 'i')) == -1) {
tableEl.classList.add('hidden');
} else {
empty = false;
}
} else if (value.search(new RegExp(table, 'i')) == -1) {
tableEl.classList.add('hidden');
} else {
empty = false;
}
});
// If database has tables that were not hidden, then show database.
if (empty && database == '') {
databaseEl.classList.add('hidden');
}
// If the database is not due to strictly-database search and has
// not hidden tables, then show database.
if (!empty && database == table) {
databaseEl.classList.remove('hidden');
}
// Show databases which tables are filtered.
if (!empty && database == '' && table != '') {
databaseEl.classList.add('search-expanded');
}
// If database is already hidden remove its expansion.
if (databaseEl.classList.contains('hidden')) {
databaseEl.classList.remove('search-expanded');
}
});
});
})();
|
{
var cloned = new VNode(
vnode.tag,
vnode.data,
vnode.children,
vnode.text,
vnode.elm,
vnode.context,
vnode.componentOptions,
vnode.asyncFactory
);
cloned.ns = vnode.ns;
cloned.isStatic = vnode.isStatic;
cloned.key = vnode.key;
cloned.isComment = vnode.isComment;
cloned.isCloned = true;
return cloned;
}
|
import Header from './components/Header/index.js';
import Main from './components/Main/index.js';
import Footer from './components/Footer/index.js';
// 匹配路由时一定要注意先后顺序,他们会是同辈元素
export default [{
'path': '/',
'components': Header + Main + Footer
}, {
'path': '/Main',
'components': Main
}, {
'path': '/Footer',
'components': Footer
}, {
'path': '/Header',
'components': Header
}]; |
import FormValidationProvider from './form-validation.provider';
angular.module('symfony-form', [])
.provider('FormValidation', FormValidationProvider); |
if ('serviceWorker' in navigator) {
/*
Defer service worker registration
https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
*/
window.addEventListener('load', function () {
navigator
.serviceWorker
.register('/service-worker.js')
.then(function () {
//success
}).catch(function (error) {
console.log('Could not register service worker', error);
});
});
}
// var angular = require('angular');
// var ngModule = angular.module('app',[]);
// console.log(ngModule); |
/** @constructor */
ScalaJS.c.scala_collection_MapLike$DefaultKeySet = (function() {
ScalaJS.c.scala_collection_AbstractSet.call(this);
this.$$outer$f = null
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype = new ScalaJS.inheritable.scala_collection_AbstractSet();
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.constructor = ScalaJS.c.scala_collection_MapLike$DefaultKeySet;
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.contains__O__Z = (function(key) {
return this.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike().contains__O__Z(key)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.iterator__Lscala_collection_Iterator = (function() {
return this.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike().keysIterator__Lscala_collection_Iterator()
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$$plus__O__Lscala_collection_Set = (function(elem) {
return ScalaJS.as.scala_collection_SetLike(ScalaJS.modules.scala_collection_Set().apply__Lscala_collection_Seq__Lscala_collection_GenTraversable(ScalaJS.modules.scala_collection_immutable_Nil())).$$plus$plus__Lscala_collection_GenTraversableOnce__Lscala_collection_Set(this).$$plus__O__Lscala_collection_Set(elem)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$$minus__O__Lscala_collection_Set = (function(elem) {
return ScalaJS.as.scala_collection_SetLike(ScalaJS.modules.scala_collection_Set().apply__Lscala_collection_Seq__Lscala_collection_GenTraversable(ScalaJS.modules.scala_collection_immutable_Nil())).$$plus$plus__Lscala_collection_GenTraversableOnce__Lscala_collection_Set(this).$$minus__O__Lscala_collection_Set(elem)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.size__I = (function() {
return this.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike().size__I()
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.foreach__Lscala_Function1__V = (function(f) {
this.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike().keysIterator__Lscala_collection_Iterator().foreach__Lscala_Function1__V(f)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike = (function() {
return this.$$outer$f
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$$minus__O__O = (function(elem) {
return this.$$minus__O__Lscala_collection_Set(elem)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$$minus__O__Lscala_collection_generic_Subtractable = (function(elem) {
return this.$$minus__O__Lscala_collection_Set(elem)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$$plus__O__O = (function(elem) {
return this.$$plus__O__Lscala_collection_Set(elem)
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.init___Lscala_collection_MapLike = (function($$outer) {
if (($$outer === null)) {
throw new ScalaJS.c.java_lang_NullPointerException().init___()
} else {
this.$$outer$f = $$outer
};
ScalaJS.c.scala_collection_AbstractSet.prototype.init___.call(this);
return this
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.scala$collection$MapLike$DefaultKeySet$$$outer__ = (function() {
return this.scala$collection$MapLike$DefaultKeySet$$$outer__Lscala_collection_MapLike()
});
/** @constructor */
ScalaJS.inheritable.scala_collection_MapLike$DefaultKeySet = (function() {
/*<skip>*/
});
ScalaJS.inheritable.scala_collection_MapLike$DefaultKeySet.prototype = ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype;
ScalaJS.is.scala_collection_MapLike$DefaultKeySet = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_collection_MapLike$DefaultKeySet)))
});
ScalaJS.as.scala_collection_MapLike$DefaultKeySet = (function(obj) {
if ((ScalaJS.is.scala_collection_MapLike$DefaultKeySet(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.collection.MapLike$DefaultKeySet")
}
});
ScalaJS.isArrayOf.scala_collection_MapLike$DefaultKeySet = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_collection_MapLike$DefaultKeySet)))
});
ScalaJS.asArrayOf.scala_collection_MapLike$DefaultKeySet = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_collection_MapLike$DefaultKeySet(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.collection.MapLike$DefaultKeySet;", depth)
}
});
ScalaJS.data.scala_collection_MapLike$DefaultKeySet = new ScalaJS.ClassTypeData({
scala_collection_MapLike$DefaultKeySet: 0
}, false, "scala.collection.MapLike$DefaultKeySet", ScalaJS.data.scala_collection_AbstractSet, {
scala_collection_MapLike$DefaultKeySet: 1,
scala_Serializable: 1,
java_io_Serializable: 1,
scala_collection_AbstractSet: 1,
scala_collection_Set: 1,
scala_collection_SetLike: 1,
scala_collection_generic_Subtractable: 1,
scala_collection_GenSet: 1,
scala_collection_generic_GenericSetTemplate: 1,
scala_collection_GenSetLike: 1,
scala_Function1: 1,
scala_collection_AbstractIterable: 1,
scala_collection_Iterable: 1,
scala_collection_IterableLike: 1,
scala_Equals: 1,
scala_collection_GenIterable: 1,
scala_collection_GenIterableLike: 1,
scala_collection_AbstractTraversable: 1,
scala_collection_Traversable: 1,
scala_collection_GenTraversable: 1,
scala_collection_generic_GenericTraversableTemplate: 1,
scala_collection_TraversableLike: 1,
scala_collection_GenTraversableLike: 1,
scala_collection_Parallelizable: 1,
scala_collection_TraversableOnce: 1,
scala_collection_GenTraversableOnce: 1,
scala_collection_generic_FilterMonadic: 1,
scala_collection_generic_HasNewBuilder: 1,
java_lang_Object: 1
});
ScalaJS.c.scala_collection_MapLike$DefaultKeySet.prototype.$classData = ScalaJS.data.scala_collection_MapLike$DefaultKeySet;
//@ sourceMappingURL=MapLike$DefaultKeySet.js.map
|
import {MAKE_BARK} from '../actions/dog-actions';
import Immutable from 'immutable';
const initialState = Immutable.Map({
hasBarked: false,
});
const dogReducer = (state = initialState, action) => {
switch (action.type) {
case MAKE_BARK:
return state.set('hasBarked', action.payload);
default:
return state;
}
};
export default dogReducer;
|
//= include ../../../bower_components/respond/dest/respond.src.js |
// Chart option
var options = {
legendTemplate : "<% for (var i=0; i<datasets.length; i++){%><li><span style=\"color:<%=datasets[i].strokeColor%>\">■</span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%>"
};
// GC count
var gc_chart_ctx = document.getElementById('gc_chart').getContext('2d');
var gc_chart = new Chart(gc_chart_ctx).Line({
labels: [],
datasets: [
{
label: 'minor GC count',
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: []
},
{
label: 'major GC Count',
fillColor: 'rgba(151,187,205,0.2)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(151,187,205,1)',
data: []
}
]
}, options);
document.getElementById('gc_legend').innerHTML = gc_chart.generateLegend();
// total object
var total_object_ctx = document.getElementById('total_object').getContext('2d');
var total_object_chart = new Chart(total_object_ctx).Line({
labels: [],
datasets: [
{
label: 'total allocated object',
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data: []
},
{
label: 'total freed object',
fillColor: 'rgba(151,187,205,0.2)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(151,187,205,1)',
data: []
}
]
}, options);
document.getElementById('total_object_legend').innerHTML = total_object_chart.generateLegend();
// malloc increase
var malloc_increase_ctx = document.getElementById('malloc_increase').getContext('2d');
var malloc_increase_chart = new Chart(malloc_increase_ctx).Line({
labels: [],
datasets: [
{
label: 'malloc increase bytes limit',
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
data: []
},
{
label: 'malloc increase bytes',
fillColor: 'rgba(151,187,205,0.2)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
pointStrokeColor: '#fff',
data: []
}
]
}, options);
document.getElementById('malloc_increase_legend').innerHTML = malloc_increase_chart.generateLegend();
// old objects
var old_objects_ctx = document.getElementById('old_objects').getContext('2d');
var old_objects_chart = new Chart(old_objects_ctx).Line({
labels: [],
datasets: [
{
label: 'old objects limit',
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
data: []
},
{
label: 'old objects',
fillColor: 'rgba(151,187,205,0.2)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
pointStrokeColor: '#fff',
data: []
}
]
}, options);
document.getElementById('old_objects_legend').innerHTML = old_objects_chart.generateLegend();
// SSE
var source = new EventSource('/rackprof/gc_stream');
source.onmessage = function(event) {
data = JSON.parse(event.data);
var gc_data = [data.minor_gc_count, data.major_gc_count];
var total_object_data = [data.total_allocated_objects, data.total_freed_objects];
var malloc_increase_data = [data.malloc_increase_bytes_limit, data.malloc_increase_bytes];
var old_objects_data = [data.old_objects_limit, data.old_objects];
gc_chart.addData(gc_data, new Date().getSeconds());
if (gc_chart.datasets[0].points.length > 10) {
gc_chart.removeData();
}
total_object_chart.addData(total_object_data, new Date().getSeconds());
if (total_object_chart.datasets[0].points.length > 10) {
total_object_chart.removeData();
}
malloc_increase_chart.addData(malloc_increase_data, new Date().getSeconds());
if (malloc_increase_chart.datasets[0].points.length > 10) {
malloc_increase_chart.removeData();
}
old_objects_chart.addData(old_objects_data, new Date().getSeconds());
if (old_objects_chart.datasets[0].points.length > 10) {
old_objects_chart.removeData();
}
};
|
var Flume = require('../')
var OffsetLog = require('flumelog-offset')
require('./memlog')(
Flume(
OffsetLog(
'/tmp/test_flumedb-offset' + Date.now() + '/log',
1024,
require('flumecodec/json')
)
)
)
require('./memlog')(
Flume(
OffsetLog(
'/tmp/test_flumedb-offset' + Date.now() + '/log',
1024,
require('flumecodec/json')
),
null,
function (val, cb) {
cb(null, val)
}
)
)
require('./memlog-map')(
OffsetLog(
'/tmp/test_flumedb-offset2' + Date.now() + '/log',
1024,
require('flumecodec/json')
)
)
|
exports.up = (knex, Promise) => {
return knex.schema.createTableIfNotExists('users', table => {
table.increments('id').primary()
table.string('ghid')
table.string('username')
table.binary('hash')
table.boolean('is_approved')
})
}
exports.down = (knex, Promise) => {
return knex.schema.dropTableIfExists('users')
}
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
var msRestAzure = require('ms-rest-azure');
exports.Resource = msRestAzure.Resource;
exports.SubResource = msRestAzure.SubResource;
exports.CloudError = msRestAzure.CloudError;
exports.StorageAccountCheckNameAvailabilityParameters = require('./storageAccountCheckNameAvailabilityParameters');
exports.CheckNameAvailabilityResult = require('./checkNameAvailabilityResult');
exports.StorageAccountCreateParameters = require('./storageAccountCreateParameters');
exports.Endpoints = require('./endpoints');
exports.Foo = require('./foo');
exports.Bar = require('./bar');
exports.CustomDomain = require('./customDomain');
exports.StorageAccount = require('./storageAccount');
exports.StorageAccountKeys = require('./storageAccountKeys');
exports.StorageAccountListResult = require('./storageAccountListResult');
exports.StorageAccountUpdateParameters = require('./storageAccountUpdateParameters');
exports.StorageAccountRegenerateKeyParameters = require('./storageAccountRegenerateKeyParameters');
exports.UsageName = require('./usageName');
exports.Usage = require('./usage');
exports.UsageListResult = require('./usageListResult');
|
var transformer = require('./transformer');
var transMethod = process.argv[2];
function readBitmap(data) {
// save head information from bitmap file
var headerField1 = data.readUInt8(0);
var headerField2 = data.readUInt8(1);
var headerFieldParsed = String.fromCharCode(headerField1) +
String.fromCharCode(headerField2);
var size = data.readUInt32LE(2);
var headerSize = data.readUInt32LE(14) +14;
var pixelDataStart = data.readUInt32LE(10);
var palleteSize = pixelDataStart - headerSize;
// Split head and pixel data into separate new Buffers
var headBuffer = new Buffer(headerSize);
var palleteBuffer = new Buffer(pixelDataStart - headerSize);
var pixelBuffer = new Buffer(size - pixelDataStart);
// Loop through the head of the original file to populate headBuffer
for (i = 0; i < headerSize; i+=2) {
var storage = data.readUInt16LE(i);
headBuffer.writeUInt16LE(storage, i);
}
switch(transMethod) {
case ("brighten"):
console.log("brightening...");
break;
case ("darken"):
console.log('darkening...');
break;
case ("invert"):
console.log('inverting...');
break;
case ("randomize"):
console.log('randomizing...');
break;
case ("whiten"):
console.log('whitening...');
break;
case ("blacken"):
console.log('blackening');
break;
default:
console.log('transformation not found!');
return;
}
// Loop through and populate palleteBuffer, transforming in the process
for (i = headerSize; i < palleteSize; i++) {
var temp = data.readUInt8(i);
switch(transMethod) {
case ("brighten"):
temp = transformer.transform.brighten(temp);
break;
case ("darken"):
temp = transformer.transform.darken(temp);
break;
case ("invert"):
temp = transformer.transform.invert(temp);
break;
case ("randomize"):
temp = transformer.transform.randomize(temp);
break;
case ("whiten"):
temp = transformer.transform.whiten(temp);
break;
case ("blacken"):
temp = transformer.transform.blacken(temp);
break;
default:
break;
}
palleteBuffer.writeUInt8(temp, i - headerSize);
}
// Loop through body of the original file to populate pixelBuffer with
// transformed pixels
for (i = pixelDataStart; i < size; i++) {
var tmp = data.readUInt8(i);
pixelBuffer.writeUInt8(tmp, i - pixelDataStart);
}
// Since the .concat method takes a list of buffers, assign an array with a list
// of the buffers and then join them with .concat
var buffers = [headBuffer, palleteBuffer, pixelBuffer];
return buffers;
}
exports.readBitmap = readBitmap;
|
module.exports = { prefix: 'far', iconName: 'sliders-h-square', icon: [448, 512, [], "f3f0", "M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-6 400H54c-3.3 0-6-2.7-6-6V86c0-3.3 2.7-6 6-6h340c3.3 0 6 2.7 6 6v340c0 3.3-2.7 6-6 6zm-42-244v8c0 6.6-5.4 12-12 12H192v24c0 13.3-10.7 24-24 24h-16c-13.3 0-24-10.7-24-24v-24h-20c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h20v-24c0-13.3 10.7-24 24-24h16c13.3 0 24 10.7 24 24v24h148c6.6 0 12 5.4 12 12zm0 128v8c0 6.6-5.4 12-12 12h-20v24c0 13.3-10.7 24-24 24h-16c-13.3 0-24-10.7-24-24v-24H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h148v-24c0-13.3 10.7-24 24-24h16c13.3 0 24 10.7 24 24v24h20c6.6 0 12 5.4 12 12z"] }; |
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const webpack = require('webpack')
// Define two different css extractors
const extractBundle = new ExtractTextPlugin('[name]-[hash].css')
const extractVendor = new ExtractTextPlugin('vendor-[hash].css')
module.exports = {
entry: {
main: [
path.join(__dirname, './src/client/index')
]
},
output: {
path: path.join(__dirname, 'dist', 'public'),
filename: '[name]-[chunkhash].js',
chunkFilename: '[name].[chunkhash].js'
},
resolve: {
extensions: ['.js', '.jsx'],
modules: ['node_modules']
},
module: {
rules: [
{
test: /\.js$|\.jsx$/,
exclude: /node_modules\/(?!(map-obj|camelcase)\/).*/,
loader: 'babel-loader'
},
{
test: /\.css$/,
include: /node_modules/,
loader: extractVendor.extract({
fallback: 'style-loader?sourceMap',
use: 'css-loader?sourceMap'
})
},
{
test: /\.css$/,
exclude: /node_modules/,
loader: extractBundle.extract({
fallback: 'style-loader?sourceMap',
use: 'css-loader?sourceMap'
})
}
]
},
devtool: 'source-map',
plugins: [
extractVendor,
extractBundle,
new CleanWebpackPlugin(path.join(__dirname, 'dist', 'public'), { verbose: false }),
new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
new webpack.EnvironmentPlugin([
'NODE_ENV',
'API'
]),
new HtmlWebpackPlugin({ template: path.join(__dirname, 'src', 'client', 'index.ejs') })
]
}
|
import { APP_CREDENTIALS } from '../../../constants';
let platform;
let geocoder;
export function getPlatform() {
if (!platform) {
/*jshint camelcase: false */
platform = new H.service.Platform({
app_id: APP_CREDENTIALS.ID,
app_code: APP_CREDENTIALS.CODE,
useHTTPS: location.protocol === 'https:'
});
}
return platform;
}
export function getGeocoder() {
if (!geocoder) {
geocoder = platform.getGeocodingService();
}
return geocoder;
}
|
/**
*
* site
*
* @description
* @author Fantasy <fantasyshao@icloud.com>
* @create 2014-09-05
* @update 2014-09-05
*/
module.exports = {
index: function *() {
yield this.render('site/index');
}
};
|
'use strict';
const request = require('request');
const bearer = 'BEARER eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjU0NzA2MTUsInR5cGUiOiJleHRlcm5hbCIsInVzZXIiOiJqdWFuQHRha2VwYXJ0LmNvbS5hciJ9.EqmkqlVDR4mzlLQOPrKL92zx2raZOPfIAEgCDsVHJKI5SQevBE3Mu9tfz66nP4qp_I-mrI128t3ssQ4dVamdtw';
const apiUSD = 'http://api.estadisticasbcra.com/usd';
const router = require('express').Router();
router.use((req, res, next) => {
console.log('Endpoint: ' + req.rawHeaders[1] + req.url);
next();
});
router.use('/usd', (req, res) => {
var options = {
url: apiUSD,
headers: {
'Authorization': bearer
}
};
const callback = (error, response, body) => {
console.log(error);
console.log(response);
return response;
}
// res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
request(options, callback).pipe(res);
});
router.use('/', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
"host": req.rawHeaders[1],
"endpoints":[
'/usd'
]}))
});
module.exports = router;
|
var webpack = require('webpack');
var config = require('./webpack.config.server');
var _ = require('lodash');
var config = module.exports = _.assign(_.clone(config), {
plugins: (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false }
}),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurenceOrderPlugin(true),
]),
});
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'cheap-module-source-map',
resolve: {
root: [
path.resolve(__dirname, '..', 'src')
]
},
entry: './demo/index',
output: {
path: path.join(__dirname, '..', 'build'),
filename: 'bundle.js'
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
}, {
test: /\.scss$/,
loader: 'style!css!autoprefixer?{browsers:["last 2 version"]}!sass'
}]
},
devServer: {
contentBase: './demo',
noInfo: true,
inline: true,
hot: true
}
};
|
import Ember from 'ember';
import config from '../config/environment';
export default Ember.Component.extend({
tagName: "a",
href: "#",
cordova: Ember.inject.service(),
click() {
if (config.cordova.enabled) {
cordova.InAppBrowser.open(this.decodeLink(), "_system");
} else {
window.open(this.decodeLink(), "_system");
}
return false;
},
decodeLink: function(){
var link = this.attrs.linkUrl.value || this.attrs.linkUrl;
return link.replace(/&/g, '&');
}
});
|
var CheckPointCommand = function() {
this.Extends = Command;
this.initialize = function() {
try {
this.parent(Command.CKP);
} catch(error) {
Utils.alert("CheckPointCommand/constructor Error: "+error.message,Utils.LOG_LEVEL_ERROR);
}
};
//Getters & Setters
//Functions
this.clone = function() {
Utils.alert("CheckPointCommand/clone");
var result = null;
try {
result = new CheckPointCommand();
if (result) {
var properties = Utils.eval(this,false); //true);
if (properties) {
for (var key in properties) {
result[key] = properties[key];
}
}
}
} catch(error) {
Utils.alert("CheckPointCommand/clone Error: "+error.message,Utils.LOG_LEVEL_ERROR);
} finally {
return result;
}
};
this.print = function(html,keysOnly) {
var _html = ((html !== undefined) && (html !== null))?html:false;
var _keysOnly = ((keysOnly !== undefined) && (keysOnly !== null))?keysOnly:false;
var _nl = (_html)?'<br/>':'\n';
var result = 'CheckPointCommand:'+_nl;
try {
result += this.parent();
} catch(error) {
Utils.alert("CheckPointCommand/print Error: "+error.message,Utils.LOG_LEVEL_ERROR);
} finally {
return result;
}
};
};
CheckPointCommand = new Class(new CheckPointCommand());
//Statics
CheckPointCommand.test = function() {
var command = null;
try {
command = new CheckPointCommand();
} catch(error) {
Utils.alert("CheckPointCommand/test Error: "+error.message,Utils.LOG_LEVEL_ERROR);
} finally {
return "CheckPointCommand/test\n"+command.print();
}
};
|
import Ember from 'ember';
export default Ember.View.extend({
templateName: 'forms/list/select'
}); |
'use strict';
const BbPromise = require('bluebird');
const expect = require('chai').expect;
const sinon = require('sinon');
const proxyquire = require('proxyquire');
const killIntentPath = srcPath('./alexa/intents/kill');
const chaosService = { terminate: () => ({}) };
const killIntent = proxyquire(killIntentPath, {
'../../chaos-service': {}
});
describe('#killIntent', () => {
const getTerminateStub = (result) =>
sinon.stub(chaosService, 'terminate').returns(result)
const expectCountByCalled = (getTerminateStub) => {
expect(getTerminateStub.calledOnce).to.equal(true);
expect(getTerminateStub.args[0][1]).to.deep.equal({
count: 1
});
}
const expectTextResult = (text, result) => {
expect(result).to.deep.equal({
sessionAttributes: {},
cardTitle: "Kill",
speechOutput: text,
repromptText: "",
shouldEndSession: true
})
}
it('should return total count - when no groups', () => {
const countByStub = getTerminateStub(BbPromise.resolve())
killIntent().then((result) => {
expectCountByCalled(countByStub);
expectTextResult(
'Booooom',
result
);
});
});
});
|
/** @jsx React.DOM */
'use strict';
var React = require('react');
var SearchView = React.createClass({displayName: 'SearchView',
render: function() {
return (
React.DOM.div( {className:"col-xs-12 col-sm-6 col-md-8"},
React.DOM.h3(null, "Etsi pysäkki"),
React.DOM.label( {htmlFor:"stop-id"}, "Anna pysäkin koodi"),
React.DOM.input( {type:"text", name:"stop-id", id:"stop-id", placeholder:"1251", onChange:this.handleChange} ),
React.DOM.button( {className:"btn btn-primary", id:"find-stop", onClick:this.findStop}, "Hae")
)
);
},
getInitialState: function() {
return {code: ''};
},
handleChange: function(event) {
this.setState({code: event.target.value});
},
findStop: function() {
if (this.state.code === '') {
return false;
}
appRouter.navigate('stop/'+this.state.code, {trigger: true});
return false;
}
});
module.exports = SearchView; |
function isBoolean(o) {
return o === true || o === false || o instanceof Boolean;
} |
/**
* jquery.dump.js
* @author Torkild Dyvik Olsen
* @version 1.0
*
* A simple debug function to gather information about an object.
* Returns a nested tree with information.
*
* http://plugins.jquery.com/files/jquery.dump.js.txt
*/
(function($) {
$.d = function(object) {
alert($.dump(object));
};
$.fn.d = function() {
alert($.dump(this));
return this;
};
$.fn.dump = function() {
return $.dump(this);
};
$.dump = function(object) {
var recursion = function(obj, level) {
if (!level) level = 0;
if (level > 3) return "**recursion level 3**";
var dump = "",
p = "";
for (i = 0; i < level; i++) p += "\t";
t = type(obj);
switch (t) {
case "string":
return '"' + obj + '"';
break;
case "number":
return obj.toString();
break;
case "boolean":
return obj ? "true" : "false";
case "date":
return "Date: " + obj.toLocaleString();
case "array":
dump += "Array ( \n";
$.each(obj, function(k, v) {
dump += p + "\t" + k + " => " + recursion(v, level + 1) + "\n";
});
dump += p + ")";
break;
case "object":
dump += "Object { \n";
$.each(obj, function(k, v) {
dump += p + "\t" + k + ": " + recursion(v, level + 1) + "\n";
});
dump += p + "}";
break;
case "jquery":
dump += "jQuery Object { \n";
$.each(obj, function(k, v) {
dump += p + "\t" + k + " = " + recursion(v, level + 1) + "\n";
});
dump += p + "}";
break;
case "regexp":
return "RegExp: " + obj.toString();
case "error":
return obj.toString();
case "document":
case "domelement":
dump +=
"DOMElement [ \n" +
p +
"\tnodeName: " +
obj.nodeName +
"\n" +
p +
"\tnodeValue: " +
obj.nodeValue +
"\n" +
p +
"\tinnerHTML: [ \n";
$.each(obj.childNodes, function(k, v) {
if (k < 1) var r = 0;
if (type(v) == "string") {
if (v.textContent.match(/[^\s]/)) {
dump +=
p +
"\t\t" +
(k - (r || 0)) +
" = String: " +
trim(v.textContent) +
"\n";
} else {
r--;
}
} else {
dump +=
p +
"\t\t" +
(k - (r || 0)) +
" = " +
recursion(v, level + 2) +
"\n";
}
});
dump += p + "\t]\n" + p + "]";
break;
case "function":
var match = obj.toString().match(/^(.*)\(([^\)]*)\)/im);
match[1] = trim(match[1].replace(new RegExp("[\\s]+", "g"), " "));
match[2] = trim(match[2].replace(new RegExp("[\\s]+", "g"), " "));
return match[1] + "(" + match[2] + ")";
case "window":
default:
dump += "N/A: " + t + " " + obj;
break;
}
return dump;
};
var type = function(obj) {
var type = typeof obj;
if (type != "object") {
return type;
}
switch (obj) {
case null:
return "null";
case window:
return "window";
case document:
return "document";
case window.event:
return "event";
default:
break;
}
if (obj.jquery) {
return "jquery";
}
switch (obj.constructor) {
case Array:
return "array";
case Boolean:
return "boolean";
case Date:
return "date";
case Object:
return "object";
case RegExp:
return "regexp";
case ReferenceError:
case Error:
return "error";
case null:
default:
break;
}
switch (obj.nodeType) {
case 1:
return "domelement";
case 3:
return "string";
case null:
default:
break;
}
return "Unknown";
};
return recursion(object);
};
function trim(str) {
return ltrim(rtrim(str));
}
function ltrim(str) {
return str.replace(new RegExp("^[\\s]+", "g"), "");
}
function rtrim(str) {
return str.replace(new RegExp("[\\s]+$", "g"), "");
}
})(jQuery);
|
'use strict';
module.exports = {
db: 'mongodb://localhost/easywork-test',
port: 3001,
app: {
title: 'easywork - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
import React from 'react';
import PropTypes from 'prop-types';
import { Text, StyleSheet, ViewPropTypes } from 'react-native';
import { OnePressButton } from '../OnePressButton';
import { BottomModal } from './BottomModal';
import globalStyles, { SUSSOL_ORANGE } from '../../globalStyles';
import { modalStrings } from '../../localization';
export function BottomConfirmModal(props) {
const {
onCancel,
onConfirm,
questionText,
confirmText,
cancelText,
style,
...modalProps
} = props;
return (
<BottomModal {...modalProps} style={[localStyles.modal, style]}>
<Text style={[globalStyles.text, localStyles.questionText]}>{questionText}</Text>
<OnePressButton
style={[globalStyles.button, localStyles.cancelButton]}
textStyle={[globalStyles.buttonText, localStyles.buttonText]}
text={cancelText}
onPress={onCancel}
/>
<OnePressButton
style={[globalStyles.button, localStyles.deleteButton]}
textStyle={[globalStyles.buttonText, localStyles.buttonText]}
text={confirmText}
onPress={onConfirm}
/>
</BottomModal>
);
}
BottomConfirmModal.propTypes = {
style: ViewPropTypes.style,
isOpen: PropTypes.bool.isRequired,
questionText: PropTypes.string.isRequired,
onCancel: PropTypes.func.isRequired,
onConfirm: PropTypes.func.isRequired,
cancelText: PropTypes.string,
confirmText: PropTypes.string,
};
BottomConfirmModal.defaultProps = {
style: {},
cancelText: modalStrings.cancel,
confirmText: modalStrings.confirm,
};
const localStyles = StyleSheet.create({
modal: {
paddingRight: 3,
},
questionText: {
color: 'white',
fontSize: 22,
paddingRight: 10,
},
buttonText: {
color: 'white',
},
cancelButton: {
borderColor: 'white',
},
deleteButton: {
borderColor: 'white',
backgroundColor: SUSSOL_ORANGE,
},
});
|
angular.module('awsStarterApp', ['ngRoute', 'ngFacebook'])
.run( function( $rootScope ) {
// Load the facebook SDK asynchronously
(function(){
// If we've already installed the SDK, we're done
if (document.getElementById('facebook-jssdk')) {return;}
// Get the first script element, which we'll use to find the parent node
var firstScriptElement = document.getElementsByTagName('script')[0];
// Create a new script element and set its id
var facebookJS = document.createElement('script');
facebookJS.id = 'facebook-jssdk';
// Set the new script's source to the source of the Facebook JS SDK
facebookJS.src = '//connect.facebook.net/en_US/sdk.js';
// Insert the Facebook JS SDK into the DOM
firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
}())})
.config(function ($routeProvider, $facebookProvider) {
$facebookProvider.setAppId('FB_APP_ID'); // NEED TO CHANGE THIS
$facebookProvider.setVersion("v2.2");
$routeProvider.when('/', {
controller: 'MainController',
templateUrl: 'templates/main.template.html'
})
.otherwise({
redirectTo: '/'
});
}); |
import Formatter from '../core/Formatter';
import Tokenizer from '../core/Tokenizer';
const reservedWords = [
'ALL',
'ALTER',
'ANALYZE',
'AND',
'ANY',
'ARRAY',
'AS',
'ASC',
'BEGIN',
'BETWEEN',
'BINARY',
'BOOLEAN',
'BREAK',
'BUCKET',
'BUILD',
'BY',
'CALL',
'CASE',
'CAST',
'CLUSTER',
'COLLATE',
'COLLECTION',
'COMMIT',
'CONNECT',
'CONTINUE',
'CORRELATE',
'COVER',
'CREATE',
'DATABASE',
'DATASET',
'DATASTORE',
'DECLARE',
'DECREMENT',
'DELETE',
'DERIVED',
'DESC',
'DESCRIBE',
'DISTINCT',
'DO',
'DROP',
'EACH',
'ELEMENT',
'ELSE',
'END',
'EVERY',
'EXCEPT',
'EXCLUDE',
'EXECUTE',
'EXISTS',
'EXPLAIN',
'FALSE',
'FETCH',
'FIRST',
'FLATTEN',
'FOR',
'FORCE',
'FROM',
'FUNCTION',
'GRANT',
'GROUP',
'GSI',
'HAVING',
'IF',
'IGNORE',
'ILIKE',
'IN',
'INCLUDE',
'INCREMENT',
'INDEX',
'INFER',
'INLINE',
'INNER',
'INSERT',
'INTERSECT',
'INTO',
'IS',
'JOIN',
'KEY',
'KEYS',
'KEYSPACE',
'KNOWN',
'LAST',
'LEFT',
'LET',
'LETTING',
'LIKE',
'LIMIT',
'LSM',
'MAP',
'MAPPING',
'MATCHED',
'MATERIALIZED',
'MERGE',
'MINUS',
'MISSING',
'NAMESPACE',
'NEST',
'NOT',
'NULL',
'NUMBER',
'OBJECT',
'OFFSET',
'ON',
'OPTION',
'OR',
'ORDER',
'OUTER',
'OVER',
'PARSE',
'PARTITION',
'PASSWORD',
'PATH',
'POOL',
'PREPARE',
'PRIMARY',
'PRIVATE',
'PRIVILEGE',
'PROCEDURE',
'PUBLIC',
'RAW',
'REALM',
'REDUCE',
'RENAME',
'RETURN',
'RETURNING',
'REVOKE',
'RIGHT',
'ROLE',
'ROLLBACK',
'SATISFIES',
'SCHEMA',
'SELECT',
'SELF',
'SEMI',
'SET',
'SHOW',
'SOME',
'START',
'STATISTICS',
'STRING',
'SYSTEM',
'THEN',
'TO',
'TRANSACTION',
'TRIGGER',
'TRUE',
'TRUNCATE',
'UNDER',
'UNION',
'UNIQUE',
'UNKNOWN',
'UNNEST',
'UNSET',
'UPDATE',
'UPSERT',
'USE',
'USER',
'USING',
'VALIDATE',
'VALUE',
'VALUED',
'VALUES',
'VIA',
'VIEW',
'WHEN',
'WHERE',
'WHILE',
'WITH',
'WITHIN',
'WORK',
'XOR'
];
const reservedToplevelWords = [
'DELETE FROM',
'EXCEPT ALL',
'EXCEPT',
'EXPLAIN DELETE FROM',
'EXPLAIN UPDATE',
'EXPLAIN UPSERT',
'FROM',
'GROUP BY',
'HAVING',
'INFER',
'INSERT INTO',
'INTERSECT ALL',
'INTERSECT',
'LET',
'LIMIT',
'MERGE',
'NEST',
'ORDER BY',
'PREPARE',
'SELECT',
'SET CURRENT SCHEMA',
'SET SCHEMA',
'SET',
'UNION ALL',
'UNION',
'UNNEST',
'UPDATE',
'UPSERT',
'USE KEYS',
'VALUES',
'WHERE'
];
const reservedNewlineWords = [
'AND',
'INNER JOIN',
'JOIN',
'LEFT JOIN',
'LEFT OUTER JOIN',
'OR',
'OUTER JOIN',
'RIGHT JOIN',
'RIGHT OUTER JOIN',
'XOR'
];
let tokenizer;
export default class N1qlFormatter {
/**
* @param {Object} cfg Different set of configurations
*/
constructor(cfg) {
this.cfg = cfg;
}
/**
* Format the whitespace in a N1QL string to make it easier to read
*
* @param {String} query The N1QL string
* @return {String} formatted string
*/
format(query) {
if (!tokenizer) {
tokenizer = new Tokenizer({
reservedWords,
reservedToplevelWords,
reservedNewlineWords,
stringTypes: [`""`, "''", '``'],
openParens: ['(', '[', '{'],
closeParens: [')', ']', '}'],
namedPlaceholderTypes: ['$'],
lineCommentTypes: ['#', '--']
});
}
return new Formatter(this.cfg, tokenizer).format(query);
}
}
|
var Fs = core.System.IO.Fs;
var $mod$0 = core.VW.Ecma2015.Utils.module(require('path'));
var $mod$1 = core.VW.Ecma2015.Utils.module(require('zlib'));
{
var Creator = function Creator() {
Creator.$constructor ? Creator.$constructor.apply(this, arguments) : Creator.$superClass && Creator.$superClass.apply(this, arguments);
};
Object.defineProperty(Creator, '$constructor', {
enumerable: false,
value: function (dir, out) {
this.dir = dir;
this.out = out;
this.files = [];
this.open();
}
});
Object.defineProperty(Creator.prototype, 'open', {
enumerable: false,
value: function () {
var out = this.out;
if (out instanceof core.System.IO.Stream) {
this.stream = out;
} else {
var stream = new core.System.IO.FileStream(out, core.System.IO.FileMode.Truncate, core.System.IO.FileAccess.Write);
this.stream = stream;
}
}
});
Object.defineProperty(Creator.prototype, 'compile', {
enumerable: false,
value: (typeof regeneratorRuntime != 'object' ? core.VW.Ecma2015.Parser : undefined, function callee$0$0() {
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1)
switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.next = 2;
return regeneratorRuntime.awrap(this.process(this.dir));
case 2:
context$1$0.next = 4;
return regeneratorRuntime.awrap(this.end());
case 4:
case 'end':
return context$1$0.stop();
}
}, null, this);
})
});
Object.defineProperty(Creator.prototype, 'end', {
enumerable: false,
value: (typeof regeneratorRuntime != 'object' ? core.VW.Ecma2015.Parser : undefined, function callee$0$0() {
var buf;
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1)
switch (context$1$0.prev = context$1$0.next) {
case 0:
buf = new Buffer(JSON.stringify(this.files));
context$1$0.next = 3;
return regeneratorRuntime.awrap(this.stream.writeAsync(buf, 0, buf.length));
case 3:
case 'end':
return context$1$0.stop();
}
}, null, this);
})
});
Object.defineProperty(Creator.prototype, 'process', {
enumerable: false,
value: (typeof regeneratorRuntime != 'object' ? core.VW.Ecma2015.Parser : undefined, function callee$0$0(path) {
var files, file, stat, content, gziped, buf, ufile, i;
return regeneratorRuntime.async(function callee$0$0$(context$1$0) {
while (1)
switch (context$1$0.prev = context$1$0.next) {
case 0:
context$1$0.next = 2;
return regeneratorRuntime.awrap(Fs.async.readdir(path));
case 2:
files = context$1$0.sent;
i = 0;
case 4:
if (!(i < files.length)) {
context$1$0.next = 27;
break;
}
file = files[i];
ufile = $mod$0.default.join(path, file);
context$1$0.next = 9;
return regeneratorRuntime.awrap(Fs.async.stat(ufile));
case 9:
stat = context$1$0.sent;
if (!stat.isDirectory()) {
context$1$0.next = 15;
break;
}
context$1$0.next = 13;
return regeneratorRuntime.awrap(this.process(ufile));
case 13:
context$1$0.next = 24;
break;
case 15:
context$1$0.next = 17;
return regeneratorRuntime.awrap(Fs.async.readFile(ufile));
case 17:
content = context$1$0.sent;
gziped = $mod$1.default.gzipSync(content, { level: 8 });
stat.isdirectory = stat.isDirectory();
stat.isfile = stat.isFile();
this.files.push({
file: $mod$0.default.relative(this.dir, ufile),
offset: this.stream.position,
length: gziped.length,
stat: stat
});
context$1$0.next = 24;
return regeneratorRuntime.awrap(this.stream.writeAsync(gziped, 0, gziped.length));
case 24:
i++;
context$1$0.next = 4;
break;
case 27:
case 'end':
return context$1$0.stop();
}
}, null, this);
})
});
}
exports.default = Creator; |
'use strict';
var path = require('path'),
YAML = require('yamljs');
exports.speakers = require('./speakers.yml').map(function (speaker) {
var firstName = speaker.name.split(' ')[0],
id = firstName.toLowerCase();
speaker.id = id;
speaker.firstName = firstName;
speaker.photo = id + '.jpg';
return speaker;
});
exports.schedule = require('./schedule.yml').map(function (meeting) {
meeting.speaker = getSpeaker(meeting.speaker);
return meeting;
});
exports.breakouts = require('./breakouts.yml').map(function (session) {
if (session.speaker) {
session.speaker = getSpeaker(session.speaker);
session.name = session.speaker.name;
session.url = '/speakers/#' + session.speaker.id;
}
return session;
});
function getSpeaker(id) {
var speaker = null;
exports.speakers.some(function (s) {
if (s.id === id) {
speaker = s;
return true;
}
});
return speaker;
}
|
var path = require('path');
var wordwrap = require('wordwrap');
/* Hack an instance of Argv with process.argv into Argv
so people can do
require('optimist')(['--beeble=1','-z','zizzle']).argv
to parse a list of args and
require('optimist').argv
to get a parsed version of process.argv.
*/
var inst = Argv(process.argv.slice(2));
Object.keys(inst).forEach(function (key) {
Argv[key] = typeof inst[key] == 'function'
? inst[key].bind(inst)
: inst[key];
});
var exports = module.exports = Argv;
function Argv (args, cwd) {
var self = {};
if (!cwd) cwd = process.cwd();
self.$0 = process.argv
.slice(0,2)
.map(function (x) {
var b = rebase(cwd, x);
return x.match(/^\//) && b.length < x.length
? b : x
})
.join(' ')
;
if (process.argv[1] == process.env._) {
self.$0 = process.env._.replace(
path.dirname(process.execPath) + '/', ''
);
}
var flags = { bools : {}, strings : {} };
self.boolean = function (bools) {
if (!Array.isArray(bools)) {
bools = [].slice.call(arguments);
}
bools.forEach(function (name) {
flags.bools[name] = true;
});
return self;
};
self.string = function (strings) {
if (!Array.isArray(strings)) {
strings = [].slice.call(arguments);
}
strings.forEach(function (name) {
flags.strings[name] = true;
});
return self;
};
var aliases = {};
self.alias = function (x, y) {
if (typeof x === 'object') {
Object.keys(x).forEach(function (key) {
self.alias(key, x[key]);
});
}
else if (Array.isArray(y)) {
y.forEach(function (yy) {
self.alias(x, yy);
});
}
else {
var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y);
aliases[x] = zs.filter(function (z) { return z != x });
aliases[y] = zs.filter(function (z) { return z != y });
}
return self;
};
var demanded = {};
self.demand = function (keys) {
if (typeof keys == 'number') {
if (!demanded._) demanded._ = 0;
demanded._ += keys;
}
else if (Array.isArray(keys)) {
keys.forEach(function (key) {
self.demand(key);
});
}
else {
demanded[keys] = true;
}
return self;
};
var usage;
self.usage = function (msg, opts) {
if (!opts && typeof msg === 'object') {
opts = msg;
msg = null;
}
usage = msg;
if (opts) self.options(opts);
return self;
};
function fail (msg) {
self.showHelp();
if (msg) console.error(msg);
process.exit(1);
}
var checks = [];
self.check = function (f) {
checks.push(f);
return self;
};
var defaults = {};
self.default = function (key, value) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.default(k, key[k]);
});
}
else {
defaults[key] = value;
}
return self;
};
var descriptions = {};
self.describe = function (key, desc) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.describe(k, key[k]);
});
}
else {
descriptions[key] = desc;
}
return self;
};
self.parse = function (args) {
return Argv(args).argv;
};
self.option = self.options = function (key, opt) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.options(k, key[k]);
});
}
else {
if (opt.alias) self.alias(key, opt.alias);
if (opt.demand) self.demand(key);
if (opt.default) self.default(key, opt.default);
if (opt.boolean || opt.type === 'boolean') {
self.boolean(key);
}
if (opt.string || opt.type === 'string') {
self.string(key);
}
var desc = opt.describe || opt.description || opt.desc;
if (desc) {
self.describe(key, desc);
}
}
return self;
};
var wrap = null;
self.wrap = function (cols) {
wrap = cols;
return self;
};
self.showHelp = function (fn) {
if (!fn) fn = console.error;
fn(self.help());
};
self.help = function () {
var keys = Object.keys(
Object.keys(descriptions)
.concat(Object.keys(demanded))
.concat(Object.keys(defaults))
.reduce(function (acc, key) {
if (key !== '_') acc[key] = true;
return acc;
}, {})
);
var help = keys.length ? [ 'Options:' ] : [];
if (usage) {
help.unshift(usage.replace(/\$0/g, self.$0), '');
}
var switches = keys.reduce(function (acc, key) {
acc[key] = [ key ].concat(aliases[key] || [])
.map(function (sw) {
return (sw.length > 1 ? '--' : '-') + sw
})
.join(', ')
;
return acc;
}, {});
var switchlen = longest(Object.keys(switches).map(function (s) {
return switches[s] || '';
}));
var desclen = longest(Object.keys(descriptions).map(function (d) {
return descriptions[d] || '';
}));
keys.forEach(function (key) {
var kswitch = switches[key];
var desc = descriptions[key] || '';
if (wrap) {
desc = wordwrap(switchlen + 4, wrap)(desc)
.slice(switchlen + 4)
;
}
var spadding = new Array(
Math.max(switchlen - kswitch.length + 3, 0)
).join(' ');
var dpadding = new Array(
Math.max(desclen - desc.length + 1, 0)
).join(' ');
var type = null;
if (flags.bools[key]) type = '[boolean]';
if (flags.strings[key]) type = '[string]';
if (!wrap && dpadding.length > 0) {
desc += dpadding;
}
var prelude = ' ' + kswitch + spadding;
var extra = [
type,
demanded[key]
? '[required]'
: null
,
defaults[key] !== undefined
? '[default: ' + JSON.stringify(defaults[key]) + ']'
: null
,
].filter(Boolean).join(' ');
var body = [ desc, extra ].filter(Boolean).join(' ');
if (wrap) {
var dlines = desc.split('\n');
var dlen = dlines.slice(-1)[0].length
+ (dlines.length === 1 ? prelude.length : 0)
body = desc + (dlen + extra.length > wrap - 2
? '\n'
+ new Array(wrap - extra.length + 1).join(' ')
+ extra
: new Array(wrap - extra.length - dlen + 1).join(' ')
+ extra
);
}
help.push(prelude + body);
});
help.push('');
return help.join('\n');
};
Object.defineProperty(self, 'argv', {
get : parseArgs,
|
(function() {
'use strict';
angular
.module('demo')
.config(setupRoutes);
setupRoutes.$inject = ['$stateProvider', '$urlRouterProvider'];
function setupRoutes($stateProvider, $urlRouterProvider) {
// For any unmatched url show the demo
$urlRouterProvider.otherwise("/demo");
$stateProvider.state('demo', {
url: '/demo',
templateUrl: 'partials/demo.html',
controller: 'DemoController'
});
$stateProvider.state('docs', {
url: '/docs',
templateUrl: 'partials/docs.html'
});
}
})();
|
// Generated Code for the Draw2D touch HTML5 lib
//
// http://www.draw2d.org
//
// Go to the Designer http://www.draw2d.org
// to design your own shape or download user generated
//
var draw2d_circuit_alu_FullAdder = draw2d.SetFigure.extend({
NAME: "draw2d_circuit_alu_FullAdder",
init:function(attr, setter, getter)
{
this._super( $.extend({stroke:0, bgColor:null, width:70,height:78.37429999999995},attr), setter, getter);
var port;
// output_s
port = this.createPort("output", new draw2d.layout.locator.XYRelPortLocator(101.17942857142874, 23.046457831202336));
port.setConnectionDirection(1);
port.setBackgroundColor("#37B1DE");
port.setName("output_s");
port.setMaxFanOut(20);
// output_c
port = this.createPort("output", new draw2d.layout.locator.XYRelPortLocator(102.60800000000017, 77.03328769762535));
port.setConnectionDirection(1);
port.setBackgroundColor("#37B1DE");
port.setName("output_c");
port.setMaxFanOut(20);
// input_a
port = this.addPort(new DecoratedInputPort(), new draw2d.layout.locator.XYRelPortLocator(-1.3188571428573985, 16.666815524987157));
port.setConnectionDirection(3);
port.setBackgroundColor("#37B1DE");
port.setName("input_a");
port.setMaxFanOut(20);
// input_b
port = this.addPort(new DecoratedInputPort(), new draw2d.layout.locator.XYRelPortLocator(-1.3188571428573985, 51.12651723843185));
port.setConnectionDirection(3);
port.setBackgroundColor("#37B1DE");
port.setName("input_b");
port.setMaxFanOut(20);
// input_c
port = this.addPort(new DecoratedInputPort(), new draw2d.layout.locator.XYRelPortLocator(-1.3188571428573985, 80.86107308135446));
port.setConnectionDirection(3);
port.setBackgroundColor("#37B1DE");
port.setName("input_c");
port.setMaxFanOut(20);
this.persistPorts=false;
},
createShapeElement : function()
{
var shape = this._super();
this.originalWidth = 70;
this.originalHeight= 78.37429999999995;
return shape;
},
createSet: function()
{
this.canvas.paper.setStart();
// BoundingBox
shape = this.canvas.paper.path("M0,0 L70,0 L70,78.37429999999995 L0,78.37429999999995");
shape.attr({"stroke":"none","stroke-width":0,"fill":"none"});
shape.data("name","BoundingBox");
// Rectangle
shape = this.canvas.paper.path('M0,5.140100000000075Q0,4.140100000000075 1, 4.140100000000075L69,4.140100000000075Q70,4.140100000000075 70, 5.140100000000075L70,73.14010000000007Q70,74.14010000000007 69, 74.14010000000007L1,74.14010000000007Q0,74.14010000000007 0, 73.14010000000007L0,5.140100000000075');
shape.attr({"stroke":"#303030","stroke-width":1,"fill":"#FFFFFF","dasharray":null,"opacity":1});
shape.data("name","Rectangle");
// Label
shape = this.canvas.paper.text(0,0,'Full');
shape.attr({"x":24.65625,"y":33.125,"text-anchor":"start","text":"Full","font-family":"\"Arial\"","font-size":10,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'Adder');
shape.attr({"x":21.7170000000001,"y":46.37429999999995,"text-anchor":"start","text":"Adder","font-family":"\"Arial\"","font-size":10,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'A');
shape.attr({"x":5,"y":14,"text-anchor":"start","text":"A","font-family":"\"Arial\"","font-size":16,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'B');
shape.attr({"x":6,"y":42.125,"text-anchor":"start","text":"B","font-family":"\"Arial\"","font-size":16,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'S');
shape.attr({"x":52.34375,"y":20,"text-anchor":"start","text":"S","font-family":"\"Arial\"","font-size":16,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'C');
shape.attr({"x":52.34375,"y":61.125,"text-anchor":"start","text":"C","font-family":"\"Arial\"","font-size":16,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'C');
shape.attr({"x":6,"y":64.37429999999995,"text-anchor":"start","text":"C","font-family":"\"Arial\"","font-size":16,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
// Label
shape = this.canvas.paper.text(0,0,'in');
shape.attr({"x":16.7170000000001,"y":67.125,"text-anchor":"start","text":"in","font-family":"\"Arial\"","font-size":12,"stroke":"none","fill":"#080808","stroke-scale":true,"font-weight":"normal","stroke-width":0,"opacity":1});
shape.data("name","Label");
return this.canvas.paper.setFinish();
},
applyAlpha: function()
{
},
layerGet: function(name, attributes)
{
if(this.svgNodes===null) return null;
var result=null;
this.svgNodes.some(function(shape){
if(shape.data("name")===name){
result=shape;
}
return result!==null;
});
return result;
},
layerAttr: function(name, attributes)
{
if(this.svgNodes===null) return;
this.svgNodes.forEach(function(shape){
if(shape.data("name")===name){
shape.attr(attributes);
}
});
},
layerShow: function(name, flag, duration)
{
if(this.svgNodes===null) return;
if(duration){
this.svgNodes.forEach(function(node){
if(node.data("name")===name){
if(flag){
node.attr({ opacity : 0 }).show().animate({ opacity : 1 }, duration);
}
else{
node.animate({ opacity : 0 }, duration, function () { this.hide() });
}
}
});
}
else{
this.svgNodes.forEach(function(node){
if(node.data("name")===name){
if(flag){node.show();}
else{node.hide();}
}
});
}
},
calculate: function()
{
},
onStart: function()
{
},
onStop:function()
{
},
getParameterSettings: function()
{
return [];
},
/**
* @method
*/
addPort: function(port, locator)
{
this._super(port, locator);
return port;
},
/**
* @method
* Return an objects with all important attributes for XML or JSON serialization
*
* @returns {Object}
*/
getPersistentAttributes : function()
{
var memento = this._super();
// add all decorations to the memento
//
memento.labels = [];
this.children.each(function(i,e){
var labelJSON = e.figure.getPersistentAttributes();
labelJSON.locator=e.locator.NAME;
memento.labels.push(labelJSON);
});
return memento;
},
/**
* @method
* Read all attributes from the serialized properties and transfer them into the shape.
*
* @param {Object} memento
* @returns
*/
setPersistentAttributes : function(memento)
{
this._super(memento);
// remove all decorations created in the constructor of this element
//
this.resetChildren();
// and add all children of the JSON document.
//
$.each(memento.labels, $.proxy(function(i,json){
// create the figure stored in the JSON
var figure = eval("new "+json.type+"()");
// apply all attributes
figure.attr(json);
// instantiate the locator
var locator = eval("new "+json.locator+"()");
// add the new figure as child to this figure
this.add(figure, locator);
},this));
}
});
/**
* by 'Draw2D Shape Designer'
*
* Custom JS code to tweak the standard behaviour of the generated
* shape. add your custome code and event handler here.
*
*
*/
draw2d_circuit_alu_FullAdder = draw2d_circuit_alu_FullAdder.extend({
init: function(attr, setter, getter){
this._super(attr, setter, getter);
this.attr({resizeable:false});
this.installEditPolicy(new draw2d.policy.figure.AntSelectionFeedbackPolicy());
},
/**
* Called by the simulator for every calculation
* loop
* @required
**/
calculate:function()
{
var a = this.getInputPort("input_a").getValue();
var b = this.getInputPort("input_b").getValue();
var c = this.getInputPort("input_c").getValue();
// s = a XOR b XOR c
this.getOutputPort("output_s").setValue(a ^ b ^ c);
// c = (at least two bits are set)
this.getOutputPort("output_c").setValue((a+b+c)>1);
},
/**
* Called if the simulation mode is starting
* @required
**/
onStart:function()
{
},
/**
* Called if the simulation mode is stopping
* @required
**/
onStop:function()
{
}
});
draw2d_circuit_alu_FullAdder.github="./shapes/org/draw2d/circuit/alu/FullAdder.shape"; |
export { default, truncateText } from 'talentrh-components/helpers/truncate-text';
|
define(['exports', 'module', 'react', 'classnames', './AffixMixin', './utils/domUtils'], function (exports, module, _react, _classnames, _AffixMixin, _utilsDomUtils) {
'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _React = _interopRequireDefault(_react);
var _classNames = _interopRequireDefault(_classnames);
var _AffixMixin2 = _interopRequireDefault(_AffixMixin);
var _domUtils = _interopRequireDefault(_utilsDomUtils);
console.warn('This file is deprecated, and will be removed in v0.24.0. Use react-bootstrap.js or react-bootstrap.min.js instead.');
console.warn('You can read more about it at https://github.com/react-bootstrap/react-bootstrap/issues/693');
var Affix = _React['default'].createClass({
displayName: 'Affix',
statics: {
domUtils: _domUtils['default']
},
mixins: [_AffixMixin2['default']],
render: function render() {
var holderStyle = { top: this.state.affixPositionTop };
return _React['default'].createElement(
'div',
_extends({}, this.props, {
className: (0, _classNames['default'])(this.props.className, this.state.affixClass),
style: holderStyle }),
this.props.children
);
}
});
module.exports = Affix;
}); |
import React, { Component } from 'react';
import './style.css';
class Pagination extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
getRange() { // 显示的页码按钮数量, 默认为 10
return this.props.range || this.props.pages || 5;
}
getCurrentPage() { // 获取当前页面,默认 1
return this.props.currentPage || this.props.index || 1;
}
getPages() {
const { totalPages } = this.props; // 总页数
let left,
right;
const range = this.getRange(); // 显示的页码按钮数量
const pages = [];
let currentPage = this.getCurrentPage(); // 当前页码
if (currentPage > totalPages) {
currentPage = totalPages;
}
left = currentPage - Math.floor(range / 2) + 1;
if (left < 1) {
left = 1;
}
right = left + range - 2;
if (right >= totalPages) {
right = totalPages;
left = right - range + 2;
if (left < 1) {
left = 1;
}
} else {
right -= left > 1 ? 1 : 0;
}
if (left > 1) {
pages.push(1);
}
if (left > 2) {
pages.push('<..');
}
for (let i = left; i < right + 1; i++) {
pages.push(i);
}
if (right < totalPages - 1) {
pages.push('..>');
}
if (right < totalPages) {
pages.push(totalPages);
}
return { pages, totalPages };
}
handleChange(value) {
if (this.props.onChange) {
this.props.onChange(value);
}
}
render() {
const currentPage = this.getCurrentPage();
const items = [];
const { pages, totalPages } = this.getPages();
items.push(
<li
key="previous"
className={ currentPage <= 1 ? 'disabled' : '' }
onClick={ currentPage <= 1 ? null : () => this.handleChange(currentPage - 1) }
>
<span><</span>
</li>
);
pages.forEach((value) => {
if (value === '<..' || value === '..>') {
items.push(<li key={ value }><span>...</span></li>);
} else {
items.push(
<li
key={ value }
className={ value === currentPage ? 'active' : '' }
onClick={ value === currentPage ? null : () => this.handleChange(value) }
>
<span>{ value }</span>
</li>
);
}
});
items.push(
<li
key="next"
className={ currentPage >= totalPages ? 'disabled' : '' }
onClick={ currentPage >= totalPages ? null : () => this.handleChange(currentPage + 1) }
>
<span>></span>
</li>
);
return (
<ul className="pagination">
{ items }
</ul>
);
}
}
export default Pagination;
|
OC.L10N.register(
"systemtags",
{
"Tags" : "Метки",
"Tagged files" : "Файлы с метками",
"Select tags to filter by" : "Выберите метки для фильтра",
"Please select tags to filter by" : "Выберите метки для фильтра",
"No files found for the selected tags" : "Для выбранных меток файлов не найдено",
"<strong>System tags</strong> for a file have been modified" : "<strong>Системные метки</strong> файла были изменены",
"You assigned system tag %3$s" : "Вы назначили системную метку %3$s",
"%1$s assigned system tag %3$s" : "%1$s назначил системную метку %3$s",
"You unassigned system tag %3$s" : "Вы убрали системную метку %3$s",
"%1$s unassigned system tag %3$s" : "%1$s убрал системную метку %3$s",
"You created system tag %2$s" : "Вы создали системную метку %2$s",
"%1$s created system tag %2$s" : "%1$s создал системную метку %2$s",
"You deleted system tag %2$s" : "Вы удалили системную метку %2$s",
"%1$s deleted system tag %2$s" : "%1$s удалил системную метку %2$s",
"You updated system tag %3$s to %2$s" : "Вы обновили системную метку %3$s на %2$s",
"%1$s updated system tag %3$s to %2$s" : "%1$s обновил системную метку %3$s для %2$s",
"You assigned system tag %3$s to %2$s" : "Вы назначили системную метку %3$s на %2$s",
"%1$s assigned system tag %3$s to %2$s" : "%1$s назначил системную метку %3$s для %2$s",
"You unassigned system tag %3$s from %2$s" : "Вы назначили системную метку %3$s из %2$s",
"%1$s unassigned system tag %3$s from %2$s" : "%1$s убрал системную метку %3$s с %2$s",
"%s (restricted)" : "%s (ограничено)",
"%s (invisible)" : "%s (невидимые)",
"%s (static)" : "%s (статические)",
"No files in here" : "Здесь нет файлов",
"No entries found in this folder" : "Нет элементов в этом каталоге",
"Name" : "Имя",
"Size" : "Размер",
"Modified" : "Изменён"
},
"nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);");
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* dolity: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Angular.js 1.x & zylkanexy
* dolity is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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.
*
*/
'use strict';
moduloPrueba.controller('PruebaNewController', ['$scope', '$routeParams', '$location', 'serverService', 'pruebaService', 'sharedSpaceService', '$filter', '$uibModal',
function ($scope, $routeParams, $location, serverService, pruebaService, sharedSpaceService, $filter, $uibModal) {
$scope.fields = pruebaService.getFields();
$scope.obtitle = pruebaService.getObTitle();
$scope.icon = pruebaService.getIcon();
$scope.ob = pruebaService.getTitle();
$scope.title = "Creando " + $scope.obtitle;
$scope.op = "plist";
$scope.status = null;
$scope.debugging = serverService.debugging();
$scope.bean = {id: 0};
$scope.bean.obj_episodio = {"id": 0};
$scope.expression = serverService.getRegExpr('decimal');
//----
if ($routeParams.id_episodio) {
serverService.promise_getOne('episodio', $routeParams.id_episodio).then(function (response) {
if (response.data.message.id != 0) {
$scope.bean.obj_episodio = response.data.message;
$scope.show_obj_episodio = false;
$scope.title = "Nueva prueba del usuario " + $scope.bean.obj_episodio.description;
}
});
} else {
$scope.show_obj_episodio = true;
}
$scope.save = function () {
var jsonToSend = {json: JSON.stringify(serverService.array_identificarArray($scope.bean))};
serverService.promise_setOne($scope.ob, jsonToSend).then(function (response) {
if (response.status == 200) {
if (response.data.status == 200) {
$scope.response = response;
$scope.status = "El registro " + $scope.obtitle + " se ha creado con id = " + response.data.message;
$scope.bean.id = response.data.message;
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
} else {
$scope.status = "Error en la recepción de datos del servidor";
}
}).catch(function (data) {
$scope.status = "Error en la recepción de datos del servidor";
});
;
};
$scope.back = function () {
window.history.back();
};
$scope.close = function () {
$location.path('/home');
};
$scope.plist = function () {
$location.path('/' + $scope.ob + '/plist');
};
$scope.chooseOne = function (nameForeign, foreignObjectName, contollerName) {
var modalInstance = $uibModal.open({
templateUrl: 'js/' + foreignObjectName + '/selection.html',
controller: contollerName,
size: 'lg'
}).result.then(function (modalResult) {
$scope.bean[nameForeign].id = modalResult;
});
};
$scope.$watch('bean.obj_episodio.id', function () {
if ($scope.bean) {
serverService.promise_getOne('episodio', $scope.bean.obj_episodio.id).then(function (response) {
var old_id = $scope.bean.obj_episodio.id;
$scope.bean.obj_episodio = response.data.message;
if (response.data.message.id != 0) {
$scope.outerForm.obj_episodio.$setValidity('exists', true);
} else {
$scope.outerForm.obj_episodio.$setValidity('exists', false);
$scope.bean.obj_episodio.id = old_id;
}
});
}
});
}]);
|
const u = up.util
up.Request.Queue = class Queue {
constructor(options = {}) {
this.concurrency = options.concurrency ?? (() => up.network.config.concurrency)
this.badResponseTime = options.badResponseTime ?? (() => up.network.config.badResponseTime)
this.reset()
}
reset() {
this.queuedRequests = []
this.currentRequests = []
clearTimeout(this.checkSlowTimout)
this.emittedSlow = false
}
get allRequests() {
return this.currentRequests.concat(this.queuedRequests)
}
asap(request) {
request.runQueuedCallbacks()
u.always(request, responseOrError => this.onRequestSettled(request, responseOrError))
// When considering whether a request is "slow", we're measing the duration between { queueTime }
// and the moment when the request gets settled. Note that when setSlowTimer() occurs, it will
// make its own check whether a request in the queue is considered slow.
request.queueTime = new Date()
this.setSlowTimer()
this.queueRequest(request)
u.microtask(() => this.poke())
}
// Changes a preload request to a non-preload request.
// Does not change the request's position in the queue.
// Does nothing if the given request is not a preload request.
promoteToForeground(request) {
if (request.preload) {
request.preload = false
return this.setSlowTimer()
}
}
setSlowTimer() {
const badResponseTime = u.evalOption(this.badResponseTime)
this.checkSlowTimout = u.timer(badResponseTime, () => this.checkSlow())
}
hasConcurrencyLeft() {
const maxConcurrency = u.evalOption(this.concurrency)
return (maxConcurrency === -1) || (this.currentRequests.length < maxConcurrency)
}
isBusy() {
return this.currentRequests.length > 0 || this.queuedRequests.length > 0
}
queueRequest(request) {
// Queue the request at the end of our FIFO queue.
this.queuedRequests.push(request)
}
pluckNextRequest() {
// We always prioritize foreground requests over preload requests.
// Only when there is no foreground request left in the queue we will send a preload request.
// Note that if a queued preload request is requested without { preload: true } we will
// promote it to the foreground (see @promoteToForeground()).
let request = u.find(this.queuedRequests, request => !request.preload)
request ||= this.queuedRequests[0]
return u.remove(this.queuedRequests, request)
}
sendRequestNow(request) {
if (request.emit('up:request:load', { log: ['Loading %s %s', request.method, request.url] }).defaultPrevented) {
request.abort('Prevented by event listener')
} else {
// Since up:request:load listeners may have mutated properties used in
// the request's cache key ({ url, method, params }), we need to normalize
// again. Normalizing e.g. moves the params into the URL for GET requests.
request.normalizeForCaching()
this.currentRequests.push(request)
request.load()
}
}
onRequestSettled(request, responseOrError) {
// If the request was aborted before it was sent, it still sits in @queuedRequests.
u.remove(this.currentRequests, request) || u.remove(this.queuedRequests, request)
if ((responseOrError instanceof up.Response) && responseOrError.ok) {
up.network.registerAliasForRedirect(request, responseOrError)
}
// Check if we can emit up:request:recover after a previous up:request:late event.
this.checkSlow()
u.microtask(() => this.poke())
}
poke() {
let request
if (this.hasConcurrencyLeft() && (request = this.pluckNextRequest())) {
return this.sendRequestNow(request)
}
}
// Aborting a request will cause its promise to reject, which will also uncache it
abort(conditions = true, reason) {
let tester = up.Request.tester(conditions)
for (let list of [this.currentRequests, this.queuedRequests]) {
const abortableRequests = u.filter(list, tester)
for (let abortableRequest of abortableRequests) {
abortableRequest.abort(reason)
// Avoid changing the list we're iterating over.
u.remove(list, abortableRequest)
}
}
}
abortExcept(excusedRequest, additionalConditions = true, reason) {
const excusedCacheKey = excusedRequest?.cacheKey?.()
const testFn = (queuedRequest) => (queuedRequest.cacheKey() !== excusedCacheKey) && u.evalOption(additionalConditions, queuedRequest)
this.abort(testFn, reason)
}
checkSlow() {
const currentSlow = this.isSlow()
if (this.emittedSlow !== currentSlow) {
this.emittedSlow = currentSlow
if (currentSlow) {
up.emit('up:request:late', { log: 'Server is slow to respond' })
} else {
up.emit('up:request:recover', { log: 'Slow requests were loaded' })
}
}
}
isSlow() {
const now = new Date()
const delay = u.evalOption(this.badResponseTime)
const allForegroundRequests = u.reject(this.allRequests, 'preload')
// If badResponseTime is 200, we're scheduling the checkSlow() timer after 200 ms.
// The request must be slow when checkSlow() is called, or we will never look
// at it again. Since the JavaScript setTimeout() is inaccurate, we allow a request
// to "be slow" a few ms earlier than actually configured.
const timerTolerance = 1
return u.some(allForegroundRequests, request => (now - request.queueTime) >= (delay - timerTolerance))
}
}
|
var calendar = new Calendar();
function Calendar() {
this.calObj = this;
this.mouseUpContainer = null;
this.addEventButton = null;
this.eventClickContainer = null;
this.authClickButton = null;
this.scheduleTypes = {
"schedule": "Tunniplaan",
"event": "Events",
"homework": "Homeworks"
};
this.calendarSelectedRowsArray = {
"startDate" : null,
"endDate": null
};
this.calendarEvents = {
"nextId" : 1,
"eventsCount" : 0,
"events":
[
]
};
this.eventColors = ["event-color-one", "event-color-two"];
this.colorAt;
this.getEventColorClass = function() {
return this.eventColors[this.colorAt];
}
this.rotateColorAt = function(color) {
if(color == 1)
this.colorAt = 1;
else if (color == 0){
this.colorAt=0;
console.log(color);
}
}
this.monday = new Date();
this.dayNumber = this.monday.getDay();
this.monday.setTime(this.monday.getTime() - (1000 * 3600 * 24 * (this.dayNumber - 0.5)));
this.sunday = new Date();
this.sunday.setTime(this.sunday.getTime() + (1000 * 3600 * 24 * (7 - this.dayNumber)));
this.fullMonthFromToday=new Date();
this.fullMonthFromToday.setTime(this.monday.getTime() + (1000 * 3600 * 24 * 31));
this.clientId = "267206477795-nmicslqg1i7kvt6tanp8d8208nnke05p.apps.googleusercontent.com";
this.apiKey = "AIzaSyDXoUmbATnAIXsOWk9qqWZZYHizxD_k60s";
this.scopes = "https://www.googleapis.com/auth/calendar";
};
Calendar.prototype.initialize = function() {
var calObj = this.calObj;
if(this.mouseUpContainer == null)
throw "First popup not set!";
if(this.addEventButton == null)
throw "Submit event button not set!";
if(this.eventClickContainer == null)
throw "Event onclick popup not set!";
this.onWindowsResizeEvent();
this.addAuthClickListener();
this.startDragListener();
this.createInstance();
};
Calendar.prototype.createInstance = function() {
var req = null;
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("XHR not created");
}
}
}
return req;
};
Calendar.prototype.handleAuthResult = function(authResult) {
var $authorizeButton = $("#authorize-button");
if(authResult) {
$authorizeButton.addClass("hidden");
calendar.fetchData();
}
};
Calendar.prototype.addAuthClickListener = function() {
var cal = this.calObj;
$(this.authClickButton).on("click", function() {
gapi.auth.authorize(
{
"client_id": cal.clientId,
"scope": cal.scopes,
"immediate": false
},
cal.handleAuthResult
);
return false;
});
};
Calendar.prototype.makeApiCall = function(callId, calColor) {
var cal = this;
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': callId,
'timeMin': cal.monday,
'timeMax': cal.sunday
});
request.execute(function(resp) {
try{
for (var i = 0; i < resp.items.length; i++) {
try{
var tempObj = new Object();
tempObj.id = cal.calendarEvents.nextId;
cal.calendarEvents.eventsCount++;
cal.calendarEvents.nextId++;
tempObj.subject = resp.items[i].summary;
tempObj.startDate = cal.convertDateForFeed(new Date(resp.items[i].start.dateTime), "start");
tempObj.endDate = cal.convertDateForFeed(new Date(resp.items[i].end.dateTime), "end");
tempObj.color=calColor;
cal.calendarEvents.events.push(tempObj);
}catch(e){}
}
cal.populateCalendar(cal.calendarEvents);
} catch(e){}
});
});
};
Calendar.prototype.makeEventsApiCall = function(callId) {
var cal = this;
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.events.list({
'calendarId': callId,
'timeMin': cal.monday,
'timeMax': cal.fullMonthFromToday
});
request.execute(function(resp) {
try{
var calendarEntry="";
for (var i = 0; i < resp.items.length; i++) {
var eventTime=new Date(resp.items[i].start.dateTime);
eventStartHour=eventTime.getHours();
var dateToday=$.datepicker.formatDate('DD dd MM yy ', new Date(resp.items[i].start.dateTime));
calendarEntry+='<strong>'+resp.items[i].summary+'</strong> - '+dateToday+' '+ eventStartHour+'.00 </br>';
}
var $newsContainer = $(".news-box");
$newsContainer.append(calendarEntry);
} catch(e){}
});
});
};
Calendar.prototype.convertDateForFeed = function(dateTime, type) {
var hour = parseInt(dateTime.getHours())-1 ;
if(parseInt(dateTime.getMinutes())>0)
hour++;
else
var hour = dateTime.getHours();
var day = dateTime.getDay();
return day + "h" + hour;
};
Calendar.prototype.fetchData = function() {
var cal = this;
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.calendarList.list();
request.execute(function(resp) {
for (var i = 0, length = resp.items.length; i < length; i++){
if(resp.items[i].summary == cal.scheduleTypes.schedule )
{
cal.makeApiCall(resp.items[i].id, 1);
}
else if(resp.items[i].summary == cal.scheduleTypes.homework)
{
cal.makeApiCall(resp.items[i].id, 0);
}
else if(resp.items[i].summary == "Events")
{
cal.makeEventsApiCall(resp.items[i].id);
}
}
});
});
};
Calendar.prototype.populateCalendar = function(events) {
for(var i = 0; i < events.eventsCount; i++) {
var event = events.events[i];
this.pushEventToCalendar(event.startDate, event.endDate, event.subject, event.id, event.color);
}
};
Calendar.prototype.startMoveListener = function(div, e) {
$(div).addClass("moving");
$(div).attr("x", e.pageX);
$(div).attr("y", e.pageY);
$(document).on("mousemove", function(e) {
var $moving = $(".moving");
var nX = $moving.attr("x") - e.pageX;
var nY = $moving.attr("y") - e.pageY;
$moving.attr("x", e.pageX);
$moving.attr("y", e.pageY);
$moving.css("left", $moving.position().left - nX);
$moving.css("top", $moving.position().top - nY);
});
};
Calendar.prototype.startDragListener = function() {
var cal = this.calObj;
$(".drag-listener").on("mousedown", function(e) {
cal.startMoveListener($(this).parent(), e);
$(".drag-listener").on("mouseup", function(e) {
$(this).parent().removeClass("moving");
$(document).unbind("mousemove");
});
});
};
Calendar.prototype.mouseDownListener = function(column, e) {
var cal = this.calObj;
var $popup = $(this.mouseUpContainer);
var $column = $(column);
$column.addClass("calendar-selected-row");
$column.attr("data-x-enter", e.pageY);
this.calendarSelectedRowsArray.startDate = $column;
this.calendarSelectedRowsArray.endDate = $column;
var id = this.calendarEvents.eventsCount + 1;
this.calendarEvents.eventsCount = id + 1;
this.calendarSelectedRowsArray.startDate.attr("data-event-id", id);
var dataDay = $(column).attr("data-day");
var selector = "td[data-day=" + dataDay + "]";
$(selector).on("mouseenter", function(e) {
var $this = $(this);
if(e.pageY > cal.calendarSelectedRowsArray.startDate.attr("data-x-enter")) {
$this.attr('data-x-enter', e.pageY);
$this.addClass("calendar-selected-row");
cal.calendarSelectedRowsArray.endDate = $this;
$this.on("mouseleave", function(e) {
$this = $(this);
if(e.pageY < $this.attr('data-x-enter') && e.pageY > cal.calendarSelectedRowsArray.startDate.attr("data-x-enter"))
$this.removeClass("calendar-selected-row");
$this.unbind("mouseleave");
});
}
});
$(document).on("mouseup", function(e) {
$(selector).unbind("mouseenter");
$(document).unbind("mouseup");
$popup.removeClass('hidden');
$(selector).removeAttr("data-x-enter");
cal.resolveLeftLocation($popup, e.pageX);
cal.resolveTopLocation($popup, e.pageY);
});
};
Calendar.prototype.addEventOnClickListener = function(calObj, e, column) {
var $popup = $(this.eventClickContainer);
$popup.removeClass("hidden");
$popup.attr("data-event-id", $(column).attr("data-event-id"));
calObj.resolveLeftLocation($popup, e.pageX);
calObj.resolveTopLocation($popup, e.pageY);
};
Calendar.prototype.resolveTopLocation = function(div, y) {
var $window = $(window);
var $div = $(div);
if((y + $div.width()) > $window.height())
$div.css("top", y - $div.height());
else
$div.css("top", y);
};
Calendar.prototype.resolveLeftLocation = function(div, x) {
var $window = $(window);
var $div = $(div);
if((x + $div.width()) > $window.width())
$div.css("left", x - $div.width());
else
$div.css("left", x);
};
Calendar.prototype.removeSelectedRow = function() {
$(".calendar-selected-row").removeClass("calendar-selected-row");
};
Calendar.prototype.removeEvent = function() {
};
Calendar.prototype.pushEventToCalendar = function(start, end, subject, eventId, color) {
var cal = this.calObj;
var startDates = start.split("h");
startDates[0] = parseInt(startDates[0]);
startDates[1] = parseInt(startDates[1]);
var endDates = end.split("h");
endDates[0] = parseInt(endDates[0]);
endDates[1] = parseInt(endDates[1]);
$.each($(".main-calendar").find(".event-column"), function() {
var id = $(this).attr("id");
var tdDates = id.split("h");
tdDates[0] = parseInt(tdDates[0]);
tdDates[1] = parseInt(tdDates[1]);
if(tdDates[0] == startDates[0] && tdDates[1] == startDates[1]) {
$(this).addClass("border-top");
var $div = $("<div class='calendar-event'></div>");
$div.css("position", "absolute");
$div.css("height", $(this).height() + 8);
$div.css("padding", "2px");
$div.css("z-index", "10");
$div.css("border-top-left-radius", "7px");
$div.css("border-top-right-radius", "7px");
if(tdDates[1] == endDates[1]) {
$div.css("border-bottom-left-radius", "7px");
$div.css("border-bottom-right-radius", "7px");
}
$div.css("top", $(this).position().top + 8);
$div.append("<h5><strong>" + subject + "</strong></h5>");
cal.addEventPart($div, this, eventId);
}
else if(startDates[0] == tdDates[0] && tdDates[1] > startDates[1] && tdDates[1] < endDates[1]) {
var $div = $("<div class='calendar-event'> </div>");
$div.css("position", "absolute");
$div.css("height", $(this).height() + 16);
$div.css("top", $(this).position().top);
cal.addEventPart($div, this, eventId);
}
else if(startDates[0] == tdDates[0] && tdDates[1] == endDates[1]) {
var $div = $("<div class='calendar-event'> </div>");
$div.css("position", "absolute");
$div.css("border-bottom-left-radius", "10px");
$div.css("border-bottom-right-radius", "10px");
$div.css("height", $(this).height() + 8);
$div.css("top", $(this).position().top);
cal.addEventPart($div, this, eventId);
}
if(endDates[0] == tdDates[0] && tdDates[1] == endDates[1])
$(this).addClass("border-bottom");
});
cal.rotateColorAt(color);
};
Calendar.prototype.addEvent = function(object) {
var course = $(object).attr("data-course");
this.calendarSelectedRowsArray.startDate.addClass("full");
var eventId = this.calendarSelectedRowsArray.startDate.attr("data-event-id");
var startId = this.calendarSelectedRowsArray.startDate.attr("id");
var endId = this.calendarSelectedRowsArray.endDate.attr("id");
this.calendarEvents.events.push({"id": eventId, "subject": course, "startDate": startId, "endDate": endId});
this.pushEventToCalendar(startId, endId, course, eventId);
this.removeSelectedRow();
};
Calendar.prototype.addEventPart =function(div, column, id) {
var calObj = this;
div.addClass(this.getEventColorClass());
div.css("width", $(column).width());
$(column).append(div);
$(column).removeClass("empty");
$(column).addClass("full");
$(column).unbind("mousedown");
$(column).attr("data-event-id", id);
$(column).on("click", function() {calObj.addEventOnClickListener(calObj, event, column)});
};
Calendar.prototype.onWindowsResizeEvent = function() {
$.each($(".main-calendar").find(".calendar-event"), function() {
$(this).css("width", $(this).parents("td").width());
});
};
Calendar.prototype.setMouseUpPopup = function(div) {
this.mouseUpContainer = div;
};
Calendar.prototype.setEventAddButton = function(button) {
this.addEventButton = button;
};
Calendar.prototype.setEventClickPopup = function(div) {
this.eventClickContainer = div;
};
Calendar.prototype.setAuthClick = function(button) {
this.authClickButton = button;
};
$(document).ready(function() {
$('#date-today').datepicker({dateFormat: 'DD MM yy '}).datepicker('setDate', new Date());
$(function() {
$( "#datepicker" ).datepicker({
inline: true
});
});
}); |
#!/usr/bin/env node
var garnish = require('../')
var argv = require('minimist')(process.argv.slice(2))
argv.level = argv.level || argv.l
argv.verbose = argv.verbose || argv.v
process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin
.pipe(garnish(argv))
.pipe(process.stdout) |
import React from 'react'
import Hook from 'util/hook'
import Async from 'client/components/Async'
import {client} from 'client/middleware/graphql'
import {registerTrs} from '../../util/i18n'
import {translations} from './translations/admin'
registerTrs(translations, 'Newsletter')
const SimpleDialog = (props) => <Async {...props} expose="SimpleDialog"
load={import(/* webpackChunkName: "admin" */ '../../gensrc/ui/admin')}/>
export default () => {
/*Hook.on('ApiResponse', ({data}) => {
if (data.products) {
const results = data.products.results
if (results) {
results.forEach(e => {
//e.name = 'ssss'
//console.log(e)
})
}
}
})*/
Hook.on('TypeCreateEditAction', function ({type, action, dataToEdit, createEditForm, meta}) {
if (type === 'NewsletterMailing' && action && action.key === 'send') {
const listIds = []
createEditForm.state.fields.list.forEach(list=>{
listIds.push(list._id)
})
const runOnlyScript = action.key==='run_script'
let template = createEditForm.state.fields.template
if(template.constructor === Array && template.length>0){
template = template[0]
}
client.query({
fetchPolicy: 'network-only',
query: 'query sendNewsletter($mailing: ID!, $subject: LocalizedStringInput!,$template: String!, $list:[ID], $batchSize: Float, $text: LocalizedStringInput, $html: LocalizedStringInput){sendNewsletter(mailing:$mailing,subject:$subject,template:$template,list:$list,batchSize:$batchSize, text: $text,html:$html){status}}',
variables: {
mailing: dataToEdit._id,
subject: createEditForm.state.fields.subject,
batchSize: createEditForm.state.fields.batchSize,
text: createEditForm.state.fields.text,
html: createEditForm.state.fields.html,
template: template.slug,
list: listIds
}
}).then(response => {
if( meta && meta.TypeContainer) {
meta.TypeContainer.setState({mailingResponse: response})
}
}).catch(error => {
console.log(error.message)
})
}
})
Hook.on('TypeCreateEdit', ({type, props, dataToEdit}) => {
if (type === 'NewsletterMailing' && dataToEdit && dataToEdit._id) {
props.actions.unshift({key: 'send', label: 'Send Newsletter'})
}
})
Hook.on('TypesContainerRender', function ({type, content}) {
if (type === 'NewsletterMailing') {
if (this.state.mailingResponse && this.state.mailingResponse.data.sendNewsletter && this.state.mailingResponse.data.sendNewsletter.status) {
content.push(<SimpleDialog key="mailingResponseDialog" open={true} onClose={() => {
this.setState({mailingResponse: null})
}}
actions={[{key: 'ok', label: 'Ok'}]}
title="Mailing response">
<h3 key="status">{this.state.mailingResponse.data.sendNewsletter.status}</h3>
{this.state.mailingResponse.data.sendNewsletter.result &&
<pre key="result">
{JSON.stringify(JSON.parse(this.state.mailingResponse.data.sendNewsletter.result),null,2)}
</pre>
}
</SimpleDialog>)
}
}
})
}
|
import Ember from 'ember';
import layout from '../../templates/components/table-pagination/table-toolbar';
export default Ember.Component.extend({
layout
});
|
module.exports = function(
config,
sessionStore,
fayeServer,
serversideClient,
channelRequestParser,
messageFactory,
tokenUtil,
errorUtil
){
var self = this;
let ms = require('ms');
self.createSession = function(request){
let newToken = null;
return sessionStore.reserveNickname(request.channelParams.nickname).then((isSuccess) => {
if(!isSuccess){
throw errorUtil.create('E409');
}
return tokenUtil.generateToken({
nickname: request.channelParams.nickname,
clientId: request.clientId
});
}).then((token) => {
newToken = token;
return tokenUtil.decryptToken(token);
}).then((tokenData) => {
let promise = sessionStore.updateToken(request.channelParams.nickname, request.clientId, newToken);
enqueueSessionExpiration(request.channel, request.clientId, tokenData);
return promise;
});
}
self.validateSubscription = function(request){
return self.validateMessage(request.authToken).then((tokenData) => {
enqueueSessionExpiration(request.channel, request.clientId, tokenData);
return Promise.resolve(tokenData);
});
};
self.validateMessage = function(authToken){
if(authToken){
return tokenUtil.decryptToken(authToken);
} else {
return Promise.reject(errorUtil.create('E401'));
}
};
function enqueueSessionExpiration(channel, clientId, tokenData){
let d = new Date();
let currentTimeInSeconds = Math.round(d.getTime() / 1000);
let expirationInSeconds = tokenData.exp - currentTimeInSeconds;
let nickname = channelRequestParser.parseNicknamefromUserChannelUrl(channel);
if(nickname !== null){
setTimeout(function() {
let sessionExpirationMessage = messageFactory.create('session-expiration');
sessionExpirationMessage.clientId = tokenData.clientId;
serversideClient.publish(channel, sessionExpirationMessage).then(() => {
console.log('[#SERVER][@' + nickname + '][' + channel + '] Published session-expiration');
}).catch((error) => {
console.log('[!!!ERROR][$' + nickname + '][' + channel + '] Failed to publish session-expiration due to error: ' + error.message);
}).then(() => {
setTimeout(function() {
disconnectClient(channel, clientId, nickname);
}, ms(config.server.security.idleSubscriptionExpirationWindow));
});
}, expirationInSeconds * 1000);
}
else{
setTimeout(function() {
disconnectClient(channel, clientId);
}, (expirationInSeconds * 1000) + ms(config.server.security.idleSubscriptionExpirationWindow));
}
};
function disconnectClient(channel, clientId, nickname){
if(typeof nickname === 'undefined' || nickname === null){
nickname = '';
}
else{
nickname = '[$' + nickname + ']';
}
let metaDisconnectChannel = '/meta/disconnect';
let disconnectClientMessage = messageFactory.createMeta(metaDisconnectChannel, clientId);
serversideClient.publish(metaDisconnectChannel, disconnectClientMessage).then(() => {
console.log('[#SERVER]' + nickname + '[' + channel + '] Published client disconnection');
}).catch((error) => {
console.log('[!!!ERROR]' + nickname + '[' + channel + '] Failed to publish client disconnection due to error: ' + error.message);
});
//fayeServer._server._engine.destroyClient(clientId, function() {});
}
} |
(function() {
'use strict';
angular
.module('assessoriaTorrellesApp')
.factory('LoginService', LoginService);
LoginService.$inject = ['$uibModal'];
function LoginService ($uibModal) {
var service = {
open: open
};
var modalInstance = null;
var resetModal = function () {
modalInstance = null;
};
return service;
function open () {
if (modalInstance !== null) return;
modalInstance = $uibModal.open({
animation: true,
templateUrl: 'app/components/login/login.html',
controller: 'LoginController',
controllerAs: 'vm',
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('login');
return $translate.refresh();
}]
}
});
modalInstance.result.then(
resetModal,
resetModal
);
}
}
})();
|
var test = require('tape'),
onError = require('..')
test('on-error().otherwiseWithError', function plan (t) {
var h = function errHandler () {}
t.equal(typeof onError(h).otherwiseWithError, 'function', 'should be a function')
t.throws(onError(h).otherwiseWithError, 'requires a callback')
t.end()
})
test('on-error().otherwiseWithError when passed an error', function plan (t) {
t.plan(4)
var errorCalls = [],
otherCalls = []
function errHandler () {
var args = Array.prototype.slice.call(arguments, 0)
errorCalls.push(args)
}
function otherHandler () {
var args = Array.prototype.slice.call(arguments, 0)
otherCalls.push(args)
}
var anError = new Error('error 1'),
handler = onError(errHandler).otherwiseWithError(otherHandler)
t.notOk(handler(anError), 'should return undefined')
t.equal(errorCalls.length, 1, 'should invoke error handler')
t.equal(otherCalls.length, 0, 'should not invoke otherwise handler')
t.equal(errorCalls[0][0], anError, 'should pass error to handler')
})
test('on-error().otherwiseWithError when passed no error', function plan (t) {
t.plan(4)
var errorCalls = [],
otherCalls = []
function errHandler () {
var args = Array.prototype.slice.call(arguments, 0)
errorCalls.push(args)
}
function otherHandler () {
var args = Array.prototype.slice.call(arguments, 0)
otherCalls.push(args)
return true
}
var handler = onError(errHandler).otherwiseWithError(otherHandler)
t.equal(handler(null, 5, 10), true, 'should return true')
t.equal(errorCalls.length, 0, 'should not invoke error handler')
t.equal(otherCalls.length, 1, 'should invoke otherwise handler')
t.deepEqual(otherCalls[0], [null, 5, 10], 'should pass all args to otherwise handler')
})
|
//~ name b189
alert(b189);
//~ component b190.js
|
const fs = require('fs')
const path = require('path')
const zlib = require('zlib')
const uglify = require('uglify-js')
const rollup = require('rollup')
if (!fs.existsSync('dist')) {
fs.mkdirSync('dist')
}
const configRef = require('./configs')
const builds = configRef.getAllBuilds()
build(builds)
function build (builds) {
let built = 0
const total = builds.length
const next = () => {
buildEntry(builds[built]).then(() => {
built++
if (built < total) {
next()
}
}).catch(logError)
}
next()
}
function buildEntry (config) {
const output = config.output
const { file, banner } = output
const isProd = /min\.js$/.test(file)
return rollup.rollup(config)
.then(bundle => bundle.generate(output))
.then(({ code }) => {
if (isProd) {
var minified = (banner ? banner + '\n' : '') + uglify.minify(code, {
output: {
/* eslint-disable camelcase */
ascii_only: true
},
compress: {
/* eslint-disable camelcase */
pure_funcs: ['makeMap']
}
}).code
return write(file, minified, true)
} else {
return write(file, code)
}
})
}
function write (dest, code, zip) {
return new Promise((resolve, reject) => {
function report (extra) {
console.log(blue(path.relative(process.cwd(), dest)) + ' ' + getSize(code) + (extra || ''))
resolve()
}
fs.writeFile(dest, code, err => {
if (err) return reject(err)
if (zip) {
zlib.gzip(code, (err, zipped) => {
if (err) return reject(err)
report(' (gzipped: ' + getSize(zipped) + ')')
})
} else {
report()
}
})
})
}
function getSize (code) {
return (code.length / 1024).toFixed(2) + 'kb'
}
function logError (e) {
console.log(e)
}
function blue (str) {
return '\x1b[1m\x1b[34m' + str + '\x1b[39m\x1b[22m'
}
|
/**
* Copyright 2012-2019, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Lib = require('../lib');
var extendFlat = Lib.extendFlat;
var extendDeep = Lib.extendDeep;
// Put default plotTile layouts here
function cloneLayoutOverride(tileClass) {
var override;
switch(tileClass) {
case 'themes__thumb':
override = {
autosize: true,
width: 150,
height: 150,
title: {text: ''},
showlegend: false,
margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
annotations: []
};
break;
case 'thumbnail':
override = {
title: {text: ''},
hidesources: true,
showlegend: false,
borderwidth: 0,
bordercolor: '',
margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
annotations: []
};
break;
default:
override = {};
}
return override;
}
function keyIsAxis(keyName) {
var types = ['xaxis', 'yaxis', 'zaxis'];
return (types.indexOf(keyName.slice(0, 5)) > -1);
}
module.exports = function clonePlot(graphObj, options) {
// Polar plot compatibility
if(graphObj.framework && graphObj.framework.isPolar) {
graphObj = graphObj.framework.getConfig();
}
var i;
var oldData = graphObj.data;
var oldLayout = graphObj.layout;
var newData = extendDeep([], oldData);
var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
var context = graphObj._context || {};
if(options.width) newLayout.width = options.width;
if(options.height) newLayout.height = options.height;
if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
// kill annotations
newLayout.annotations = [];
var keys = Object.keys(newLayout);
for(i = 0; i < keys.length; i++) {
if(keyIsAxis(keys[i])) {
newLayout[keys[i]].title = {text: ''};
}
}
// kill colorbar and pie labels
for(i = 0; i < newData.length; i++) {
var trace = newData[i];
trace.showscale = false;
if(trace.marker) trace.marker.showscale = false;
if(trace.type === 'pie') trace.textposition = 'none';
}
}
if(Array.isArray(options.annotations)) {
for(i = 0; i < options.annotations.length; i++) {
newLayout.annotations.push(options.annotations[i]);
}
}
// TODO: does this scene modification really belong here?
// If we still need it, can it move into the gl3d module?
var sceneIds = Object.keys(newLayout).filter(function(key) {
return key.match(/^scene\d*$/);
});
if(sceneIds.length) {
var axesImageOverride = {};
if(options.tileClass === 'thumbnail') {
axesImageOverride = {
title: {text: ''},
showaxeslabels: false,
showticklabels: false,
linetickenable: false
};
}
for(i = 0; i < sceneIds.length; i++) {
var scene = newLayout[sceneIds[i]];
if(!scene.xaxis) {
scene.xaxis = {};
}
if(!scene.yaxis) {
scene.yaxis = {};
}
if(!scene.zaxis) {
scene.zaxis = {};
}
extendFlat(scene.xaxis, axesImageOverride);
extendFlat(scene.yaxis, axesImageOverride);
extendFlat(scene.zaxis, axesImageOverride);
// TODO what does this do?
scene._scene = null;
}
}
var gd = document.createElement('div');
if(options.tileClass) gd.className = options.tileClass;
var plotTile = {
gd: gd,
td: gd, // for external (image server) compatibility
layout: newLayout,
data: newData,
config: {
staticPlot: (options.staticPlot === undefined) ?
true :
options.staticPlot,
plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
2 :
options.plotGlPixelRatio,
displaylogo: options.displaylogo || false,
showLink: options.showLink || false,
showTips: options.showTips || false,
mapboxAccessToken: context.mapboxAccessToken
}
};
if(options.setBackground !== 'transparent') {
plotTile.config.setBackground = options.setBackground || 'opaque';
}
// attaching the default Layout the gd, so you can grab it later
plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);
return plotTile;
};
|
define([], function () {
'use strict';
function configValueFilter(configuration) {
return function (configKey) {
if (configuration.hasOwnProperty(configKey)) {
return configuration[configKey];
} else {
throw new Error('Configuration key ' + configKey + ' not found.');
}
};
}
configValueFilter.$inject = ['base.config'];
return configValueFilter;
}); |
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var BUILD_DIR = path.resolve(__dirname, 'dist');
var WWW_DIR = path.resolve(BUILD_DIR, 'public/js');
var CLIENT_DIR = path.resolve(__dirname, 'frontend/js');
var SERVER_DIR = path.resolve(__dirname, 'server');
var CSS_DIR = path.resolve(__dirname, 'frontend/sass');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
var server = {
entry: SERVER_DIR + '/index.js',
target: 'node',
output: {
path: BUILD_DIR,
filename: 'backend.js'
},
externals: nodeModules,
module : {
loaders : [
{
test : /\.js?/,
include : SERVER_DIR,
loader : 'babel-loader'
}
],
},
plugins: [
new webpack.IgnorePlugin(/\.(css|less)$/),
new webpack.BannerPlugin('require("source-map-support").install();')//,
// { raw: true, entryOnly: false })
],
devtool: 'sourcemap'
};
var client = {
devtool: 'cheap-eval-source-map',
entry: {
app: CLIENT_DIR + '/client.jsx',
},
output: {
path: WWW_DIR,
filename: 'bundle.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : CLIENT_DIR,
loader : 'babel-loader'
}
],
rules: [{
test: /\.scss$/,
use: [{
loader: "style-loader" // creates style nodes from JS strings
}, {
loader: "css-loader" // translates CSS into CommonJS
}, {
loader: "sass-loader", // compiles Sass to CSS
options: {
includePaths: [CSS_DIR],
sourceMap: true
}
}]
}, {
test: /\.jsx?/,
exclude: /(node_modules|bower_components)/,
use: [{
loader: "babel-loader"
}]
}]
}
};
module.exports = client;
|
/**
* grunt-angular-translate
* https://github.com/firehist/grunt-angular-translate
*
* Copyright (c) 2013 "firehist" Benjamin Longearet, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/**/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
/**
* Increments the version number, etc.
*/
bump: {
options: {
files: [
"package.json"
],
commit: true,
commitMessage: 'chore(release): v%VERSION%',
commitFiles: [
"package.json"
],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin'
}
},
/**
* i18nextract build json lang files
*/
i18nextract: {
// Provide fr_FR language
default_options: {
prefix: '00_',
suffix: '.json',
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR'],
dest: 'tmp'
},
default_exists_i18n : {
prefix: '01_',
suffix: '.json',
nullEmpty: true,
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR'],
dest: 'tmp',
source: 'test/fixtures/default_exists_i18n.json' // Use to generate different output file
},
default_deleted_i18n : {
prefix: '02_',
suffix: '.json',
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR'],
dest: 'tmp',
source: 'test/fixtures/default_deleted_i18n.json' // Use to generate different output file
},
interpolation_bracket: {
prefix: '03_',
suffix: '.json',
interpolation: {
startDelimiter: '[[',
endDelimiter: ']]'
},
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR'],
dest: 'tmp'
},
default_language: {
prefix: '04_',
suffix: '.json',
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR', 'en_US'],
dest: 'tmp',
defaultLang: 'en_US'
},
json_extract: {
prefix: '05_',
suffix: '.json',
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
jsonSrc: [ 'test/fixtures/*.json' ],
jsonSrcName: ['label'],
lang: ['en_US'],
dest: 'tmp',
defaultLang: 'en_US'
},
sub_namespace: {
prefix: '06_',
suffix: '.json',
src: [ 'test/fixtures/index_namespace.html' ],
lang: ['fr_FR'],
namespace: true,
dest: 'tmp'
},
/**
* Test case: Feed
*/
sub_namespace_default_language: {
prefix: '07_',
suffix: '.json',
src: [ 'test/fixtures/index_namespace.html' ],
lang: ['fr_FR', 'en_US'],
defaultLang: 'fr_FR',
nullEmpty: true,
namespace: true,
dest: 'tmp'
},
/**
* Test case: Feed
*/
sub_namespace_default_language_source: {
prefix: '08_',
suffix: '.json',
src: [ 'test/fixtures/index_namespace.html' ],
lang: ['fr_FR'],
defaultLang: 'fr_FR',
safeMode: true,
nullEmpty: true,
namespace: true,
dest: 'tmp',
source: 'test/fixtures/default_exists_i18n_namespace.json' // Use to generate different output file
},
/**
* Test case: Use consistent output to be able to merge easily
*/
consistent_stringify: {
prefix: '09_A_',
suffix: '.json',
src: [ 'test/fixtures/index_namespace_consistent_output.html' ],
lang: ['fr_FR'],
defaultLang: 'fr_FR',
safeMode: true,
nullEmpty: true,
namespace: true,
stringifyOptions: true,
dest: 'tmp',
source: 'test/fixtures/default_exists_i18n_namespace.json' // Use to generate different output file
},
/**
* Test case: Use consistent output with options
*/
consistent_stringify_options: {
prefix: '09_B_',
suffix: '.json',
src: [ 'test/fixtures/index_namespace_consistent_output.html' ],
lang: ['fr_FR'],
defaultLang: 'fr_FR',
safeMode: true,
nullEmpty: true,
namespace: true,
stringifyOptions: {
space: ' '
},
dest: 'tmp',
source: 'test/fixtures/default_exists_i18n_namespace.json' // Use to generate different output file
},
/**
* Test case: Use consistent output with options
*/
extra_regexs: {
prefix: '10_',
suffix: '.json',
src: [ 'test/fixtures/*.html', 'test/fixtures/*.js' ],
lang: ['fr_FR'],
customRegex: [
'tt-default="\'((?:\\\\.|[^\'\\\\])*)\'\\|translate"'
],
dest: 'tmp'
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
},
markdox: {
all: {
files: [
{src: 'tasks/*.js', dest: 'DOCUMENTATION.md'}
]
}
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-bump');
grunt.loadNpmTasks('grunt-markdox');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'i18nextract', 'nodeunit', 'clean']);
// By default, lint and run all tests.
grunt.registerTask('default', ['test']);
}; |
var log = require('./')
var net = require('net')
function createServer () {
var server = net.createServer()
setInterval(function () {}, 1000)
server.listen(0)
}
createServer()
createServer()
setTimeout(function () {
log()
}, 100)
|
"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0;
var _AppBar = _interopRequireDefault(require("@material-ui/core/AppBar"));
var _Checkbox = _interopRequireDefault(require("@material-ui/core/Checkbox"));
var _FormGroup = _interopRequireDefault(require("@material-ui/core/FormGroup"));
var _FormControlLabel = _interopRequireDefault(require("@material-ui/core/FormControlLabel"));
var _List = _interopRequireDefault(require("@material-ui/core/List"));
var _styles = require("@material-ui/core/styles");
var _found = require("found");
var _react = _interopRequireDefault(require("react"));
var _reactRelay = require("react-relay");
var _Tabs = _interopRequireWildcard(require("@material-ui/core/Tabs"));
var _ToDoListUpdateMarkAllMutation = _interopRequireDefault(require("../../rb-example-todo-client/relay/ToDoListUpdateMarkAllMutation"));
var _ToDoItem = _interopRequireDefault(require("./ToDoItem"));function _interopRequireWildcard(obj) {if (obj && obj.__esModule) {return obj;} else {var newObj = {};if (obj != null) {for (var key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) {var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};if (desc.get || desc.set) {Object.defineProperty(newObj, key, desc);} else {newObj[key] = obj[key];}}}}newObj.default = obj;return newObj;}}function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const styles = theme => ({
root: {
width: '100%',
maxWidth: 360,
background: theme.palette.background.paper } });
class ToDoList extends _react.default.Component
{constructor(...args) {var _temp;return _temp = super(...args), this.
_handle_onClick_MarkAll = (event, checked) => {
const { relay, Viewer } = this.props;
const { variables } = this.context.relay;
const ToDo_Complete = checked;
_ToDoListUpdateMarkAllMutation.default.commit(
relay.environment,
Viewer,
Viewer.ToDos,
ToDo_Complete,
variables.status);
}, this.
_handle_onChange = (event, tabsValue) => {
const url = tabsValue === 2 ? '/todo/completed' : tabsValue === 1 ? '/todo/active' : '/todo';
this.context.router.push(url);
}, _temp;}
renderTabs() {
const status = this.context.relay.variables.status;
const tabsValue = status === 'active' ? 1 : status === 'completed' ? 2 : 0;
return (
_react.default.createElement(_AppBar.default, { position: "static" },
_react.default.createElement(_Tabs.default, { value: tabsValue, onChange: this._handle_onChange },
_react.default.createElement(_Tabs.Tab, { label: "All" }),
_react.default.createElement(_Tabs.Tab, { label: "Active" }),
_react.default.createElement(_Tabs.Tab, { label: "Completed" }))));
}
render() {
const { Viewer } = this.props;
const { ToDos, ToDo_TotalCount, ToDo_CompletedCount } = Viewer;
if (!ToDo_TotalCount) {
return null;
}
return (
_react.default.createElement("div", null,
this.renderTabs(),
_react.default.createElement(_FormGroup.default, { row: true },
_react.default.createElement(_FormControlLabel.default, {
control:
_react.default.createElement(_Checkbox.default, {
checked: ToDo_TotalCount === ToDo_CompletedCount,
onChange: this._handle_onClick_MarkAll }),
label: "Mark all as complete" })),
_react.default.createElement(_List.default, null,
ToDos.edges.map(({ node }) =>
_react.default.createElement(_ToDoItem.default, { key: node.id, Viewer: Viewer, ToDo: node })))));
}}var _default =
(0, _reactRelay.createFragmentContainer)(
(0, _styles.withStyles)(styles)((0, _found.withRouter)(ToDoList)), { Viewer: function () {return require("./__generated__/ToDoList_Viewer.graphql");} });exports.default = _default;
//# sourceMappingURL=ToDoList.js.map |
/**
* Editor package.
*
* This package is independent from the application, and represent the graph
* (canvas element) and logic part of the editor. For organization purposes,
* the editor is divided into several namespaces:
*
* - **b3e** : contains all base classes, functions and constants;
* - **b3e.draw** : contains functions to draw the block shapes and symbols;
* - **b3e.editor** : contains the editor class, editor-related managers and
* symbols;
* - **b3e.project** : contains the project class and project-related managers;
* - **b3e.tree** : contains the tree class and tree-related managers;
*
* As a general rule, an application has a single editor instance; the editor
* can handle several projects but only a single project can be active in a
* given time; a project can have several trees.
*
* Each project has a set of nodes (default fixed nodes and custom nodes). A
* block is a visual instance of a node.
*
* Also notice that, the Editor, Project, Tree, Block, Connection and
* SelectionBox are all children of `createjs.DisplayObject` or
* `createjs.Container`.
*
*/
window.b3e = window.b3e || {};
window.b3e.draw = window.b3e.draw || {};
window.b3e.editor = window.b3e.editor || {};
window.b3e.project = window.b3e.project || {};
window.b3e.tree = window.b3e.tree || {};
window.b3e.VERSION = '[BUILD_VERSION]'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.