code
stringlengths 2
1.05M
|
---|
'use strict';
angular.module('myApp.filmsView', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/filmsView', {
templateUrl: 'filmsView/filmsView.html',
controller: 'FilmsViewCtrl'
});
}])
.controller('FilmsViewCtrl', [function() {
}]);
|
/**
* @param {number[][]} rooms
* @return {boolean}
*/
const canVisitAllRooms = function (rooms) {
let visited = new Set(), queue = [0];
while (queue.length > 0) {
let nq = [];
for (let idx of queue) {
visited.add(idx);
for (let key of rooms[idx]) {
if (!visited.has(key)) {
nq.push(key);
}
}
}
queue = nq;
}
return visited.size === rooms.length;
};
module.exports = canVisitAllRooms; |
$('.upload-btn').on('click', function (){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
// add the files to formData object for the data payload
formData.append('uploads[]', file, file.name);
}
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!\n' + data);
},
xhr: function() {
// create an XMLHttpRequest
var xhr = new XMLHttpRequest();
console.log('inside upload xhr');
// listen to the 'progress' event
xhr.upload.addEventListener('progress', function(evt) {
console.log('inside upload addEventListener');
if (evt.lengthComputable) {
// calculate the percentage of upload completed
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
// update the Bootstrap progress bar with the new percentage
$('.progress-bar').text(percentComplete + '%');
$('.progress-bar').width(percentComplete + '%');
// once the upload reaches 100%, set the progress bar text to done
if (percentComplete === 100) {
$('.progress-bar').html('Done');
}
}
}, false);
return xhr;
}
});
}
});
|
!function(e){e.module("app",["resources","ui.router","gpyComponents"])}(angular),function(e){var r=e.module("app");r.config(["$resourcesProvider","$stateProvider","$urlRouterProvider",function(e,r,o){r.state("stateX",{url:"/state-x",template:"State X"})}])}(angular),function(e){var r=e.module("app");r.controller("appController",["$scope","$http","gpyComponents",function(e,r,o){e.methods=e.methods||{},e.models=e.models||{},e.methods.serverErrorPopup=function(e){o.popup.show({message:"Server error, please provide this code to the administrator: "+e.data.errorId,type:"error"})}}])}(angular),function(e){var r=e.module("app");r.directive("appContainer",function(){return{restrict:"EA",templateUrl:"/front/modules/angular-seed/dev/app/app.html",controller:"appController"}})}(angular); |
import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import {jenkinsOnly} from '@webex/test-helper-mocha';
import {createWhistlerTestUser, removeWhistlerTestUser} from '@webex/test-users';
const {assert} = chai;
chai.use(chaiAsPromised);
assert.hasAccessToken = (user) => {
assert.isDefined(user.token, 'user.token is defined');
};
assert.isTestUser = (user) => {
assert.isDefined(user, 'user is defined');
assert.isDefined(user.displayName, 'user.displayName is defined');
assert.isDefined(user.emailAddress, 'user.emailAddress is defined');
assert.isDefined(user.password, 'user.password is defined');
assert.isDefined(user.reservationUrl, 'user.reservationUrl is defined');
};
jenkinsOnly(describe)('test-users-whistler', () => {
describe('createWhistlerTestUser()', () => {
it('creates a test user', () => createWhistlerTestUser()
.then((u) => {
assert.isTestUser(u);
assert.hasAccessToken(u);
}));
});
describe('removeWhistlerTestUser()', () => {
it('removes the specified test user', () => createWhistlerTestUser()
.then(async (u) => {
const res = await removeWhistlerTestUser(u);
assert.equal(res.statusCode, 204);
}));
});
});
|
'use strict';
(function ($) {
$(document).ready(function () {
// Setup media query for enabling dynamic layouts only on
// larger screen sizes
var mq = window.matchMedia("(min-width: 320px)");
if ($(".userrole-anonymous")[0]){
$('input[type="password"]').showPassword('focus', {
});
$('.app-signin-input').jvFloat();
var $mcNote = $('#app-signin-suggestion');
Mailcheck.defaultDomains.push('lcm.ade25.de')
$('#ac-name').on('blur', function (event) {
console.log("event ", event);
console.log("this ", $(this));
$(this).mailcheck({
// domains: domains, // optional
// topLevelDomains: topLevelDomains, // optional
suggested: function (element, suggestion) {
// callback code
console.log("suggestion ", suggestion.full);
$mcNote.removeClass('hidden').addClass('fadeInDown');
$mcNote.html("Meinten Sie <i>" + suggestion.full + "</i>?");
$mcNote.on('click', function (evt) {
evt.preventDefault();
$('#ac-name').val(suggestion.full);
$mcNote.removeClass('fadeInDown').addClass('fadeOutUp').delay(2000).addClass('hidden');
});
},
empty: function (element) {
// callback code
$mcNote.html('').addClass('hidden');
}
});
});
// Enable gallery and masonry scripts based on screen size
if (mq.matches) {
var bannerflkty = new Flickity('.app-banner', {
autoPlay: true,
contain: true,
wrapAround: true,
imagesLoaded: true,
cellSelector: '.app-banner-item',
cellAlign: 'left',
autoPlay: 7500
});
//var flkty = new Flickity('.main-gallery', {
// autoPlay: true,
// contain: true,
// wrapAround: true,
// imagesLoaded: true,
// cellSelector: '.app-gallery-cell',
// cellAlign: 'left'
//});
var $isoContainer = $('#js-isotope-container');
$isoContainer.addClass('js-isotope-intialized');
$isoContainer.isotope({
itemSelector: '.js-isotope-item',
layoutMode: 'fitRows',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false
},
resizable: false,
animationEngine: 'best-available'
});
// filter items on button click
var $selectionLinks = $('[data-appui="app-list-filter"]'),
$current = '';
$('#app-list-filters').on('click', '[data-appui="app-list-filter"]', function () {
$current = $(this);
$selectionLinks.not($current).removeClass('active-filter');
$(this).addClass('active-filter');
var $filterValue = $(this).attr('data-filter');
$isoContainer.isotope({ filter: $filterValue });
});
}
};
}
);
}(jQuery));
|
import './Admin.css';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
class AdminForm extends Component {
renderField(field) {
const { meta: { touched, error } } = field;
const className = '';
return (
<div className={className}>
<input className="form-control"
type={field.type}
placeholder={field.placeholder}
{...field.input} />
<div className="text-help">
{touched ? error : ''}
</div>
</div>
);
}
onSubmit(values) {
}
render() {
const { handleSubmit } = this.props;
return (
<div className={'adminForm'}>
<h3>Cadastre um Administrador do sistema</h3>
<form onSubmit={handleSubmit(this.onSubmit.bind(this))} className={'form-inline'}>
<Field
name="name"
label="Nome"
placeholder="Nome"
type="text"
component={this.renderField}
/>
<Field
name="id"
label="ID"
placeholder="Identificação"
type="text"
component={this.renderField}
/>
<Field
name="foto"
label="Foto"
placeholder="Link para foto"
type="text"
component={this.renderField}
/>
<Field
name="phone"
label="Telefone"
placeholder="Telefone"
type="text"
component={this.renderField}
/>
<Field
name="email"
label="Email"
placeholder="Email"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Entrar</button>
<Link to="/user" className="btn btn-danger">Cancelar</Link>
</form>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
}
};
export default reduxForm({
form: 'Admin'
})(
connect(mapStateToProps, {})(AdminForm)
); |
/**
* Created by desver_f on 06/02/17.
*/
import { action, computed, observable } from 'mobx';
import bluebird from 'bluebird';
import autobind from 'autobind-decorator';
import storage from 'react-native-simple-store';
import _ from 'lodash';
import stores from './index';
import * as Intra from '../api/intra';
import medal from '../assets/medal.png';
function n(n) {
return n > 9 ? '' + n : '0' + n;
}
@autobind
class Ranking {
@observable promotion = [];
@observable rankPosition = '0th';
@observable searchField = "";
@observable studentModal = "";
@action
setStudentModal(login) {
this.studentModal = login;
}
@action
async computePromotion({ refreshCache }) {
const cachedPromotion = await this.getCachedRanking();
if (cachedPromotion && !refreshCache) {
this.promotion = cachedPromotion;
await this.selfRankPosition({ ranking: cachedPromotion });
return Promise.resolve(true);
}
// Always reset promotion to empty so that we can detect that we're loading
if (stores.ui.isConnected) {
this.promotion = [];
const { userProfile: { location, year, promo } } = stores.session;
const promotion = await Intra.fetchPromotion(location, year, promo);
const promotionWithDetails = await bluebird.map(promotion, async ({ login: email }) => {
return await Intra.fetchStudent(email);
});
const promotionSorted = _(promotionWithDetails)
.filter(({ gpa: [value] }) => value.gpa !== 'n/a')
.orderBy(({ gpa: [value] }) => value.gpa, ['desc'])
.map((student, i) => {
if (i === 0) {
student.img = medal;
}
return {
...student,
rank: n(i + 1)
}
})
.value();
this.promotion = promotionSorted;
await this.selfRankPosition({ ranking: promotionSorted });
await storage.save('ranking', promotionSorted);
}
}
getOrdinalNumber(n) {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
@action
async selfRankPosition({ ranking, fromCache = false }) {
const { login } = stores.session.userProfile;
const promotionRanks = fromCache ? await this.getCachedRanking() : ranking;
if (!promotionRanks) {
return Promise.resolve(true);
}
const position = _.findIndex(promotionRanks, (student) => student.login === login) + 1;
this.rankPosition = this.getOrdinalNumber(position);
}
@computed get renderResults() {
return this.searchField === ""
? this.promotion.slice()
: _.filter(this.promotion, (student) => new RegExp(this.searchField, 'i').test(student.login));
}
@computed get getResume() {
return _.find(this.promotion, (student) => student.login === this.studentModal);
}
selfRank() {
const { login } = stores.session.userProfile;
return _.find(this.promotion, (student) => student.login === login);
}
getCachedRanking() {
return storage.get('ranking');
}
}
const rankingStore = new Ranking();
export default rankingStore; |
import React from 'react'
import MediaQuery from 'react-responsive'
import Link from 'gatsby-link'
export default ({ data }) => {
const post = data.markdownRemark
return (
<div style={{textAlign: 'justify'}}>
<Link to='/' style={{letterSpacing: '.125em', textTransform: 'uppercase', fontSize: '1rem'}} href="">Writings »</Link>
<h1>
{post.frontmatter.title}
</h1>
<MediaQuery query="(min-width: 1024px)">
<div dangerouslySetInnerHTML={{ __html: post.html }} style={{ columns: 1}} />
</MediaQuery>
<MediaQuery query="(max-width: 1023px)">
<div dangerouslySetInnerHTML={{ __html: post.html }} style={{ columns: 1}} />
</MediaQuery>
</div>
)
}
export const query = graphql`
query BlogPostQuery($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
}
`
|
const util = require('util');
exports.run = async (client,message, args = []) => {
const suffix =args.join(' ');
try {
let evaled = await eval(suffix);
const type = typeof evaled;
const insp = util.inspect(evaled, {depth: 0});
const toSend= [];
if (evaled === null) evaled ='null';
toSend.push('**EVAL:**');
toSend.push('```js');
toSend.push(clean(suffix));
toSend.push('```');
toSend.push('**Evaluates to:**');
toSend.push('```LDIF');
toSend.push(clean(evaled.toString().replace(client.token, 'Redacted').replace(client.user.email, 'Redacted')));
toSend.push('```');
if (evaled instanceof Object) {
toSend.push('**Inspect:**');
toSend.push('```js');
toSend.push(clean(insp.toString().replace(client.token, 'Redacted').replace(client.user.email, 'Redacted')));
toSend.push('```');
} else {
toSend.push('**Type:**');
toSend.push('```js');
toSend.push(type);
toSend.push('```');
}
await message.channel.send(toSend, {split: true});
} catch (err) {
const toSend = [];
toSend.push('**EVAL:**');
toSend.push('```js');
toSend.push(clean(suffix));
toSend.push('```');
toSend.push('**Error:** ```LDIF');
toSend.push(clean(err.message));
toSend.push('```');
await message.channel.send(toSend, {split: true});
}
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['ev'],
permsLevel: 'Bot Owner'
};
exports.help = {
name: 'eval',
category: 'System',
description: 'Evaluates arbitrary Javascript.',
usage: 'eval <expression>'
};
function clean(text) {
if (typeof(text) === 'string') {
return text.replace(/`/g, '`' + String.fromCharCode(8203)).replace(/@/g, '@' + String.fromCharCode(8203));
} else {
return text;
}
}
|
function Battle() {
this.user = new User();
this.pokemon;
this.view = new View();
}
Battle.prototype.Battle_Checker = function() {
var rnd = Math.random();
if (rnd > 0.8) {
this.Initiate_Battle_Conditions();
}
}
Battle.prototype.Initiate_Battle_Conditions = function() {
inBattle = true;
this.view.ShowBattleBox();
this.Get_Random_Enemy_Sprite();
}
Battle.prototype.Get_Random_Enemy_Sprite = function() {
var random = Math.floor(Math.random() * 151) + 1;
var self = this;
$.ajax({
url: "http://pokeapi.co/api/v1/sprite/" + random,
success: function(data) {
self.pokemon = new Pokemon(data.pokemon.name, data.image, data.id);
self.view.Display_Pokemon_Details(self.pokemon);
}
});
}
Battle.prototype.Battle_Loop = function() {
this.Set_Enemy_Health_Bar_Relative_To_Health();
while (inBattle) {
//Attacking Loop
//player attack
this.pokemon.health -= this.user.Attack();
document.getElementById("enemy-health-bar").value = this.pokemon.health;
this.Check_Win_Conditions(this.pokemon);
//pokemon attack
this.user.health -= this.pokemon.Attack();
document.getElementById("user-health-bar").value = this.user.health;
this.Check_Win_Conditions(this.user);
}
}
Battle.prototype.Set_Enemy_Health_Bar_Relative_To_Health = function() {
var enemyHealthBar = document.getElementById("enemy-health-bar");
enemyHealthBar.max = this.pokemon.maxHealth;
enemyHealthBar.value = this.pokemon.health;
var userHealthBar = document.getElementById("user-health-bar");
userHealthBar.max = this.user.maxHealth;
userHealthBar.value = this.user.health;
};
Battle.prototype.Check_Win_Conditions = function(player) {
if (player.health <= 0) {
inBattle = false;
this.view.CloseBattleScreen();
};
} |
// From http://github.com/Caged/javascript-bits/tree/master/datetime/format.js
Object.extend(Date.prototype, {
/**
* @param format {String} The string used to format the date.
* Example: new Date().strftime("%A %I:%M %p")
*/
strftime: function(format) {
var day = this.getUTCDay(), month = this.getUTCMonth();
var hours = this.getUTCHours(), minutes = this.getUTCMinutes();
function pad(num) { return num.toPaddedString(2); };
return format.gsub(/\%([aAbBcdDHiImMpSwyY])/, function(part) {
switch(part[1]) {
case 'a': return $w("Sun Mon Tue Wed Thu Fri Sat")[day]; break;
case 'A': return $w("Sunday Monday Tuesday Wednesday Thursday Friday Saturday")[day]; break;
case 'b': return $w("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec")[month]; break;
case 'B': return $w("January February March April May June July August September October November December")[month]; break;
case 'c': return this.toString(); break;
case 'd': return this.getUTCDate(); break;
case 'D': return pad(this.getUTCDate()); break;
case 'H': return pad(hours); break;
case 'i': return (hours === 12 || hours === 0) ? 12 : (hours + 12) % 12; break;
case 'I': return pad((hours === 12 || hours === 0) ? 12 : (hours + 12) % 12); break;
case 'm': return pad(month + 1); break;
case 'M': return pad(minutes); break;
case 'p': return hours > 11 ? 'PM' : 'AM'; break;
case 'S': return pad(this.getUTCSeconds()); break;
case 'w': return day; break;
case 'y': return pad(this.getUTCFullYear() % 100); break;
case 'Y': return this.getUTCFullYear().toString(); break;
}
}.bind(this));
}
}); |
var gulp = require( 'gulp' ),
livingcss = require( 'gulp-livingcss' ),
sass = require( 'gulp-sass' ),
fs = require( 'fs-extra' ),
path = require( 'path' ),
runSequence = require( 'run-sequence' ),
clean = require( 'gulp-dest-clean' ),
sublime = require( './lib/gulp-sublime.js' ),
intellij = require( './lib/gulp-intellij.js' );
// Output variables
var sublimeDest = 'snippets/sublime',
intellijDest = 'snippets/intellij';
// define custom tag
var optsObj = {
preprocess: function ( context, template, Handlebars ) {
context.title = 'Cedar Snippet Docs';
return livingcss.utils.readFileGlobs( './template/partials/*.hbs', function ( data, file ) {
// make the name of the partial the name of the file
var partialName = path.basename( file, path.extname( file ) );
Handlebars.registerPartial( partialName, data );
} );
},
tags: {
modifier: function () {
var section = this.sections[ this.tag.description ];
if ( section ) {
section.modifiers = section.modifiers || [];
section.modifiers.push( {
name: this.tag.name,
value: this.tag.type
} );
}
}
},
template: './template/snipTemplate.hbs'
};
// Make the JSON from comments -- waiting to replace this is updated
gulp.task( 'livingjson', function () {
var jsonObj = optsObj;
jsonObj.preprocess = function ( context, template, Handlebars ) {
fs.outputFile( './dist/json/elements.json', JSON.stringify( context.sections, null, ' ' ), function ( err ) {
if ( err ) {
console.error( err );
}
} );
return false;
};
return gulp.src( 'src/css/main.css' )
.pipe( livingcss( '', jsonObj ) );
} );
gulp.task( 'clean-sublime', function () {
return gulp.src( sublimeDest )
.pipe( clean( sublimeDest ) );
} );
gulp.task( 'clean-intellij', function () {
return gulp.src( intellijDest )
.pipe( clean( intellijDest ) );
} );
// Create Snippets tasks
gulp.task( 'sublime-snips', function () {
return gulp.src( './dist/json/elements.json' )
.pipe( sublime() )
.pipe( gulp.dest( sublimeDest ) );
} );
gulp.task( 'intellij-snips', function () {
return gulp.src( './dist/json/elements.json' )
.pipe( intellij() )
.pipe( gulp.dest( intellijDest ) );
} );
// general stuff
gulp.task( 'livingcss', function () {
return gulp.src( 'src/css/main.css' )
.pipe( livingcss( '', optsObj ) )
.pipe( gulp.dest( 'dist' ) );
} );
gulp.task( 'sass', function () {
return gulp.src( './src/scss/**/*.scss' )
.pipe( sass().on( 'error', sass.logError ) )
.pipe( gulp.dest( 'src/css/' ) );
} );
// Parsing SCSS comments and outputting JSON
gulp.task( 'default', function ( cb ) {
runSequence(
'sass',
'livingcss',
'livingjson',
cb );
} );
// Generate all snippet types
gulp.task( 'snippets', function ( cb ) {
runSequence(
'default',
'clean-sublime',
'sublime-snips',
'clean-intellij',
'intellij-snips',
cb );
} );
// Generate sublime snippets
gulp.task( 'sublime', function ( cb ) {
runSequence(
'default',
'clean-sublime',
'sublime-snips',
cb );
} );
// Generate intellij snippets
gulp.task( 'intellij', function ( cb ) {
runSequence(
'default',
'clean-intellij',
'intellij-snips',
cb );
} );
|
this.NesDb = this.NesDb || {};
NesDb[ 'F31824D16504B44948DE2CE53FD10C0CFAD3D41C' ] = {
"$": {
"name": "Big Nose the Caveman",
"class": "Unlicensed",
"catalog": "CAM-BN",
"publisher": "Camerica",
"developer": "Codemasters",
"region": "USA",
"players": "1",
"date": "1991"
},
"cartridge": [
{
"$": {
"system": "NES-NTSC",
"crc": "BD154C3E",
"sha1": "F31824D16504B44948DE2CE53FD10C0CFAD3D41C",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2006-01-22"
},
"board": [
{
"$": {
"type": "CAMERICA-BF9093",
"pcb": "BIC-41",
"mapper": "71"
},
"prg": [
{
"$": {
"name": "COBIC 7406-BN",
"size": "256k",
"crc": "BD154C3E",
"sha1": "F31824D16504B44948DE2CE53FD10C0CFAD3D41C"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "BF9093"
}
}
],
"cic": [
{
"$": {
"type": "CIC Stun"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
],
"gameGenieCodes": [
{
"name": "1 life",
"codes": [
[
"PEUYITLA"
]
]
},
{
"name": "6 lives",
"codes": [
[
"TEUAITLA"
]
]
},
{
"name": "9 lives",
"codes": [
[
"PEUYITLE"
]
]
},
{
"name": "Infinite lives",
"codes": [
[
"SXOTPAVG"
]
]
},
{
"name": "Slower timer",
"codes": [
[
"ANENAKLL"
]
]
},
{
"name": "Faster timer",
"codes": [
[
"AXENAKLL"
]
]
},
{
"name": "Never lose bones when buying",
"codes": [
[
"AEEYYZPA"
]
]
},
{
"name": "Start on Monster Island",
"codes": [
[
"XXXYITSZ",
"VEKYAVSE",
"AOUNGTAE"
]
]
},
{
"name": "Start on Terror Island",
"codes": [
[
"XXXYITSZ",
"VEKYAVSE",
"ZOUNGTAE"
]
]
}
]
};
|
import ProjectModel from '../model/ProjectModel';
//TODO make sure *all* calls make use of the ObjectModelUtil to ensure proper project objects!
//TODO check to see if the response contains the 'error' key/value
const ProjectAPI = {
save : function (userId, project, callback) {
let url = _config.PROJECT_API_BASE + '/' + userId + "/projects";
let method = 'POST'
if (project.id) {
url += '/' + project.id;
method = 'PUT';
}
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.status == 200) {
const respData = JSON.parse(xhr.responseText);
if(respData && ! respData.error) {
callback(JSON.parse(xhr.responseText));
} else {
callback(null);
}
} else {
callback(null);
}
}
}
xhr.open(method, url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(project));
},
delete : function(userId, projectId, callback) {
const url = _config.PROJECT_API_BASE + '/' + userId + '/projects/' + projectId;
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.status == 200) {
const respData = JSON.parse(xhr.responseText);
if(respData && !respData.error) {
callback(respData);
} else {
callback(null);
}
} else {
callback(null);
}
}
}
xhr.open("DELETE", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
},
list : function(userId, filter, callback) {
// todo: add filters to request
const url = _config.PROJECT_API_BASE + '/' + userId + '/projects';
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.status == 200) {
const respData = JSON.parse(xhr.responseText);
if(respData && !respData.error) {
callback(ProjectModel.ensureProjectList(respData));
} else {
callback(null);
}
} else {
callback(null);
}
}
}
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
},
get : function(userId, projectId, callback) {
const url = _config.PROJECT_API_BASE + '/' + userId + '/projects/' + encodeURIComponent(projectId);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
if(xhr.status == 200) {
const respData = JSON.parse(xhr.responseText);
if(respData && !respData.error) {
callback(ProjectModel.ensureProject(respData));
} else {
callback(null);
}
} else {
callback(null);
}
}
}
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
}
}
export default ProjectAPI; |
class WorkRouting {
constructor(twilioClient, accountSid, twilioNumber) {
this.twilioClient = twilioClient;
this.accountSid = accountSid;
this.twilioNumber = twilioNumber;
}
createTask(workspaceSid, workflowSid, attributes) {
return new Promise((resolve, reject) => {
this.twilioClient.taskrouter.v1
.workspaces(workspaceSid)
.tasks
.create({
workflowSid,
taskChannel: 'voice',
attributes: JSON.stringify(attributes),
}).then(resolve, reject);
});
}
loadTask(workspaceSid, taskSid) {
return new Promise((resolve, reject) => {
this.twilioClient.taskrouter.v1
.workspaces(workspaceSid)
.tasks(taskSid)
.fetch()
.then(resolve, reject);
});
}
completeTask(workspaceSid, taskSid, reason) {
return new Promise((resolve, reject) => {
this.twilioClient.taskrouter.v1
.workspaces(workspaceSid)
.tasks(taskSid)
.update({ assignmentStatus: 'completed', reason })
.then(resolve, reject);
});
}
}
module.exports = WorkRouting;
|
import calculatables from '../calculations';
import getItems from '../../helpers/data/get-items';
export default function (transformedData, params) {
const calculations = Object.keys(calculatables)
.filter(calc => calculatables[calc].check(transformedData));
const items = getItems(transformedData);
const initialStats = calculations.reduce((obj, calc) => Object.assign(obj, { [calc]: 0 }), {});
const itemStats = items.reduce((obj, item) => Object.assign(obj, { [item]: Object.assign({}, initialStats) }), {});
return transformedData.map(round => {
const results = round.results.map(result => {
const calculatedResult = Object.assign({}, result);
const stats = itemStats[result.item];
calculations.filter(calc => !calculatables[calc].isPost)
.forEach(calc => {
const change = calculatables[calc].calculate(calculatedResult);
calculatedResult[calc] = {
change: change,
total: stats[calc] + change
};
stats[calc] += change;
});
calculations.filter(calc => calculatables[calc].isPost)
.forEach(calc => {
const total = calculatables[calc].calculate(calculatedResult);
calculatedResult[calc] = {
change: null,
total: total
}
});
return calculatedResult;
});
return {
name: round.name,
results: results
}
});
};
|
"use strict";
const React = require("react");
const PropTypes = require("prop-types");
class ProductHeader extends React.Component {
render() {
return <div>{this.props.children}</div>;
}
}
class Cart extends React.Component {
static propTypes = {
products: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
quantity: PropTypes.number.isRequired
})
).isRequired,
total: PropTypes.string.isRequired,
onCheckoutClicked: PropTypes.func.isRequired
};
render() {
const products = this.props.products;
const hasProducts = products.length > 0;
const nodes = !hasProducts ? (
<div>Please add some products to cart.</div>
) : (
products.map(function (p) {
return (
<ProductHeader key={p.id}>
{p.title} - €{p.price} x {p.quantity}
</ProductHeader>
);
})
);
return (
<div className="cart uk-panel uk-panel-box uk-panel-box-primary">
<div className="uk-badge uk-margin-bottom">Your Cart</div>
<div className="uk-margin-small-bottom">{nodes}</div>
<div className="uk-margin-small-bottom">Total: €{this.props.total}</div>
<button
className="uk-button uk-button-large uk-button-success uk-align-right"
onClick={this.props.onCheckoutClicked}
disabled={hasProducts ? "" : "disabled"}
>
Checkout
</button>
</div>
);
}
}
module.exports = Cart;
|
"use strict";
/**
* sliceSet.js
* @createdOn: 01-Nov-2017
* @author: SmartChartsNXT
* @version: 1.0.0
* @description:This is a parent class of slice class which create all the slices.
*/
import defaultConfig from "./../../settings/config";
import Point from "./../../core/point";
import {Component} from "./../../viewEngin/pview";
import UiCore from './../../core/ui.core';
import Slice from "./slice";
class SliceSet extends Component {
constructor(props) {
super(props);
let self = this;
this.state = {
startAngle:0,
endAngle:0,
textFontSize: defaultConfig.theme.fontSizeMedium,
showSliceMarker: true,
hideMarkerText: false,
animPercent: null
};
this.slices = {};
this.global = {
mouseDownPos: {},
set mouseDown(v) {
this._mouseDown = v;
},
get mouseDown() {
return this._mouseDown;
},
set mouseDrag(v) {
this._mouseDrag = v;
let slicePlane = self.ref.node.getElementsByClassName('slice-rotation-plane')[0];
slicePlane.style.display = (v ? 'block':'none');
},
get mouseDrag() {
return this._mouseDrag;
}
};
this.renderCounter = 0;
}
componentWillMount() {
this.state.startAngle = 0;
this.state.endAngle = 0;
this.state.showSliceMarker = true;
}
componentDidMount() {
this.renderCounter++;
let sliceSetBBox = this.ref.node.getBBox();
if(sliceSetBBox.width > this.props.areaWidth) {
switch(this.renderCounter) {
case 1: this.setState({textFontSize: defaultConfig.theme.fontSizeSmall}); break;
case 2: this.setState({hideMarkerText: true}); break;
case 3: this.setState({showSliceMarker: false}); break;
}
} else if(this.props.animated) {
if(this.state.animPercent === null) {
this.state.animPercent = 0;
}
if(this.state.animPercent <= 100){
this.doAnimation();
}
}
}
render() {
return (
<g class='slice-set'>
{this.createSlices()}
<rect class='slice-rotation-plane' x={this.props.cx-(this.props.areaWidth/2)} y={this.props.cy-(this.props.areaHeight/2)}
width={this.props.areaWidth} height={this.props.areaHeight} strokeColor='black' strokeWidth='1' fill='none' opacity='0.1' style={{display : 'none', 'pointer-events':'all'}}
events={{
touchstart: this.onMouseDown.bind(this),
mouseup: this.onMouseUp.bind(this), mousemove: this.onMouseMove.bind(this),
touchend: this.onMouseUp.bind(this), touchmove: this.onMouseMove.bind(this)
}}>
</rect>
</g>
);
}
createSlices() {
return this.props.dataSet.map((data, i) =>{
let percent = Math.min(this.state.animPercent || data.percent, data.percent);
this.state.startAngle = this.state.endAngle;
this.state.endAngle += (percent * 3.6);
return (
<Slice index={i} rootNodeId={this.props.rootNodeId}
toggleEnabled={this.props.dataSet.length > 0 ? true : false} cx ={this.props.cx} cy={this.props.cy}
width={this.props.width} height={this.props.height} innerWidth={this.props.innerWidth} innerHeight={this.props.innerHeight}
offsetWidth={this.props.offsetWidth} offsetHeight={this.props.offsetHeight}
data={data} startAngle={this.state.startAngle} endAngle={this.state.endAngle} strokeColor={this.props.strokeColor}
strokeWidth={this.props.strokeWidth} rotateChart={this.rotateChart.bind(this)} slicedOut={data.slicedOut} fontSize={this.state.textFontSize}
gradient={this.props.gradient} updateTip={this.props.updateTip} hideTip={this.props.hideTip}
onRef={ref => this.slices["s"+i] = ref} parentCtx={this.global} showSliceMarker={this.state.showSliceMarker} hideMarkerText={this.state.hideMarkerText}
/>
);
});
}
onMouseDown(e) {
this.global.mouseDown = true;
}
onMouseUp(e) {
e.stopPropagation();
e.preventDefault();
this.global.mouseDown = false;
this.global.mouseDrag = false;
}
onMouseMove(e) {
if (this.props.dataSet.length === 0) {
return;
}
let pos = {clientX : e.clientX || e.touches[0].clientX, clientY : e.clientY || e.touches[0].clientY };
if (this.global.mouseDown === true && (this.global.mouseDownPos.x !== pos.clientX && this.global.mouseDownPos.y !== pos.clientY)) {
let dragStartPoint = UiCore.cursorPoint(this.props.rootNodeId, pos);
let dragAngle = this.getAngle(new Point(this.props.cx, this.props.cy), dragStartPoint);
if (dragAngle > this.dragStartAngle) {
this.rotateChart(2);
} else {
this.rotateChart(-2);
}
this.dragStartAngle = dragAngle;
this.props.hideTip();
}
}
rotateChart(rotationIndex) {
Object.keys(this.slices).forEach((key) => {
this.slices[key].rotateSlice(rotationIndex);
});
}
doAnimation() {
setTimeout(() => {
this.setState({animPercent:this.state.animPercent + 4});
}, 50);
}
getAngle(point1, point2) {
let deltaX = point2.x - point1.x;
let deltaY = point2.y - point1.y;
let rad = Math.atan2(deltaY, deltaX);
let deg = rad * 180.0 / Math.PI;
deg = (deg < 0) ? deg + 450 : deg + 90;
return deg % 360;
}
}
export default SliceSet; |
var angular = require('angular');
var ngApp = require('ngApp');
var moment = require('moment');
var _ = require('lodash');
ngApp.directive('speciesPropForm', function () {
return {
restrict: 'C',
template: require('raw-loader!./templates/species-property-form.html'),
controller: function ($scope, $routeParams, $location, $mdDialog, $controller, speciesDataService, userService, uiService, animalDataService) {
$scope.speciesName = $routeParams.speciesName;
$scope.propName = $routeParams.propName;
$scope.propOrderValue = userService.getPropPriority($scope.propName);
$scope.addSpeciesPropertyOption = function (key, option) {
$scope.propData.options = _.uniq([option].concat($scope.propData.options));
};
$scope.isFormValid = function () {
return angular.element('.section--edit-propData .md-input-invalid').length === 0;
};
$scope.hasEditableOptions = function () {
if (!$scope.propData) {
console.warn('$scope.hasEditableOptions called without valid propData');
return false;
}
switch (animalDataService.getPropType($scope.propData)) {
case 'string':
case 'number':
return true;
default:
return false;
}
};
/**
*
* @returns {Promise}
*/
$scope.saveSpeciesProperty = function () {
if (!$scope.isFormValid()) {
var formErrMessage = "Form is invalid. Please fix.";
uiService.showError(formErrMessage);
return Promise.reject(new Error(formErrMessage));
}
if ($scope.propOrderValue) {
userService.saveUserAnimalPropertyOrder($scope.propData.key, $scope.propOrderValue);
}
if ($scope.propData.val) {
$scope.propData.defaultVal = angular.copy($scope.propData.val);
}
$scope.formatDefaultVal();
switch ($scope.propData.valType) {
case 'date':
case 'number':
$scope.propData.options = [];
break;
case 'boolean':
$scope.propData.options = [true, false];
break;
default:
break;
}
return speciesDataService.saveSpeciesProp($scope.speciesName, _.omit($scope.propData, 'val'))
.then(function(){
uiService.showMessage("Successfully saved property");
})
.catch(function (err) {
uiService.showError("Failed to save property");
console.error(err);
return Promise.reject(err);
})
};
/**
*
* @returns {Promise}
*/
$scope.deleteSpeciesProperty = function () {
return speciesDataService.deleteSpeciesProp($scope.speciesName, $scope.propName);
};
/**
*
* @param {String} [defaultValType]
*/
$scope.formatDefaultVal = function (defaultValType) {
var propType = defaultValType || $scope.propData.valType;
console.log('setting prop type to %s', propType);
switch (propType) {
case 'date':
$scope.propData.defaultVal = moment.utc($scope.propData.defaultVal).toDate();
break;
case 'number':
if (!_.isNumber($scope.propData.defaultVal)) {
$scope.propData.defaultVal = parseFloat($scope.propData.defaultVal) || 0;
}
break;
case 'boolean':
if (!_.isBoolean($scope.propData.defaultVal)) {
$scope.propData.defaultVal = true;
}
break;
case 'string':
default:
if (!_.isString($scope.propData.defaultVal)) {
$scope.propData.defaultVal = '';
}
}
};
(function init() {
var propTypeWatchHandler;
var destroyWatchHandler;
speciesDataService.getSpecies($scope.speciesName)
.then(function(species){
$scope.activeSpecies = species;
$scope.propData = speciesDataService.getSpeciesProp($scope.speciesName, $scope.propName);
$scope.valTypes = _.reduce($scope.activeSpecies.getSpeciesProps(), function(valTypes, speciesProp){
if (valTypes.indexOf(speciesProp.valType) < 0){
valTypes.push(speciesProp.valType);
}
return valTypes;
}, ['number', 'string', 'date', 'boolean']);
if (!$scope.activeSpecies.getProp($scope.propName)) {
uiService.showError("Property not valid");
console.error('invalid propName');
$location.path('/species/' + $scope.speciesName);
}
propTypeWatchHandler = $scope.$watch("propData.valType", function (valType) {
$scope.formatDefaultVal(valType);
});
destroyWatchHandler = $scope.$on('$destroy', function () {
propTypeWatchHandler();
destroyWatchHandler();
});
});
})()
}
}
});
module.exports = ngApp;
|
define([
'vehicle-licensing/collections/services'
],
function (ServicesCollection) {
describe("ServicesCollection", function () {
var response = {
"data": [
{
"volume:sum": 5,
"values": [
{
"_end_at": "2012-09-01T00:00:00+00:00",
"volume:sum": 3,
"_start_at": "2012-08-01T00:00:00+00:00"
},
{
"_end_at": "2012-10-01T00:00:00+00:00",
"volume:sum": 2,
"_start_at": "2012-09-01T00:00:00+00:00"
}
],
"service": "tax-disc"
},
{
"volume:sum": 7,
"values": [
{
"_end_at": "2012-09-01T00:00:00+00:00",
"_start_at": "2012-08-01T00:00:00+00:00"
},
{
"_end_at": "2012-10-01T00:00:00+00:00",
"volume:sum": 4,
"_start_at": "2012-09-01T00:00:00+00:00"
}
],
"service": "sorn"
}
]
};
var expected = [
{
"id": "tax-disc",
"title": "Tax disc",
"href": "/performance/tax-disc",
"values": [
{
"_end_at": "2012-09-01T00:00:00+00:00",
"volume:sum": 3,
"_start_at": "2012-08-01T00:00:00+00:00"
},
{
"_end_at": "2012-10-01T00:00:00+00:00",
"volume:sum": 2,
"_start_at": "2012-09-01T00:00:00+00:00"
}
]
},
{
"id": "sorn",
"title": "SORN",
"href": "/performance/sorn",
"values": [
{
"_end_at": "2012-09-01T00:00:00+00:00",
"_start_at": "2012-08-01T00:00:00+00:00"
},
{
"_end_at": "2012-10-01T00:00:00+00:00",
"volume:sum": 4,
"_start_at": "2012-09-01T00:00:00+00:00"
}
]
}
];
describe("parse", function () {
it("parses the response", function () {
var parsed = ServicesCollection.prototype.parse(response);
expect(parsed).toEqualProperties(expected);
});
});
});
});
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('site-header', 'Integration | Component | site header', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{site-header}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#site-header}}
template block text
{{/site-header}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({widgetLabel:"Keres\u00e9s",searchButtonTitle:"Keres\u00e9s",clearButtonTitle:"Keres\u00e9s t\u00f6rl\u00e9se",placeholder:"C\u00edm vagy hely keres\u00e9se",searchIn:"Keres\u00e9s ebben",all:"Mind",allPlaceholder:"C\u00edm vagy hely keres\u00e9se",emptyValue:"Adjon meg egy keres\u00e9si kifejez\u00e9st.",untitledResult:"C\u00edm n\u00e9lk\u00fcl",untitledSource:"C\u00edm n\u00e9lk\u00fcli forr\u00e1s",noResults:"Nincs eredm\u00e9ny",noResultsFound:"A keres\u00e9s nem j\u00e1rt eredm\u00e9nnyel.",
noResultsFoundForValue:"A(z) {value} keres\u00e9se nem j\u00e1rt eredm\u00e9nnyel.",showMoreResults:"T\u00f6bb eredm\u00e9ny megjelen\u00edt\u00e9se",hideMoreResults:"Elrejt\u00e9s",searchResult:"Keres\u00e9si eredm\u00e9ny",moreResultsHeader:"T\u00f6bb eredm\u00e9ny",useCurrentLocation:"Aktu\u00e1lis hely haszn\u00e1lata"}); |
// https://github.com/dimsemenov/PhotoSwipe
//= require photoswipe/v4.0.0/photoswipe.js |
import { customerSaveCompleted } from './customerSaveCompleted';
import { customerFormValidation } from '../components/sampleForm/validations/customerFormValidation';
export function customerSaveStart(viewModel) {
return (dispatcher) => {
customerFormValidation.validateForm(viewModel).then(
(formValidationResult) => {
if (formValidationResult.succeeded) {
// Call here the async call to save
// additional logic or actions to be added on a real case
console.log("Save Completed");
}
dispatcher(customerSaveCompleted(formValidationResult));
}
);
}
}
|
import baseConfig from './base';
const config = Object.assign({}, baseConfig, {
peerServer: {
host: 'localhost',
port: 9000,
key: 'doppelchat',
path: '/'
}
});
export default config;
|
// Search script generated by doxygen
// Copyright (C) 2009 by Dimitri van Heesch.
// The code in this file is loosly based on main.js, part of Natural Docs,
// which is Copyright (C) 2003-2008 Greg Valure
// Natural Docs is licensed under the GPL.
var indexSectionsWithContent =
{
0: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101111101001101101110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
1: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101100000001101101000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
2: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000101111101001100101110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
3: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
4: "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "functions",
3: "variables",
4: "pages"
};
function convertToId(search)
{
var result = '';
for (i=0;i<search.length;i++)
{
var c = search.charAt(i);
var cn = c.charCodeAt(0);
if (c.match(/[a-z0-9]/))
{
result+=c;
}
else if (cn<16)
{
result+="_0"+cn.toString(16);
}
else
{
result+="_"+cn.toString(16);
}
}
return result;
}
function getXPos(item)
{
var x = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
x += item.offsetLeft;
item = item.offsetParent;
}
}
return x;
}
function getYPos(item)
{
var y = 0;
if (item.offsetWidth)
{
while (item && item!=document.body)
{
y += item.offsetTop;
item = item.offsetParent;
}
}
return y;
}
/* A class handling everything associated with the search panel.
Parameters:
name - The name of the global variable that will be
storing this instance. Is needed to be able to set timeouts.
resultPath - path to use for external files
*/
function SearchBox(name, resultsPath, inFrame, label)
{
if (!name || !resultsPath) { alert("Missing parameters to SearchBox."); }
// ---------- Instance variables
this.name = name;
this.resultsPath = resultsPath;
this.keyTimeout = 0;
this.keyTimeoutLength = 500;
this.closeSelectionTimeout = 300;
this.lastSearchValue = "";
this.lastResultsPage = "";
this.hideTimeout = 0;
this.searchIndex = 0;
this.searchActive = false;
this.insideFrame = inFrame;
this.searchLabel = label;
// ----------- DOM Elements
this.DOMSearchField = function()
{ return document.getElementById("MSearchField"); }
this.DOMSearchSelect = function()
{ return document.getElementById("MSearchSelect"); }
this.DOMSearchSelectWindow = function()
{ return document.getElementById("MSearchSelectWindow"); }
this.DOMPopupSearchResults = function()
{ return document.getElementById("MSearchResults"); }
this.DOMPopupSearchResultsWindow = function()
{ return document.getElementById("MSearchResultsWindow"); }
this.DOMSearchClose = function()
{ return document.getElementById("MSearchClose"); }
this.DOMSearchBox = function()
{ return document.getElementById("MSearchBox"); }
// ------------ Event Handlers
// Called when focus is added or removed from the search field.
this.OnSearchFieldFocus = function(isActive)
{
this.Activate(isActive);
}
this.OnSearchSelectShow = function()
{
var searchSelectWindow = this.DOMSearchSelectWindow();
var searchField = this.DOMSearchSelect();
if (this.insideFrame)
{
var left = getXPos(searchField);
var top = getYPos(searchField);
left += searchField.offsetWidth + 6;
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
left -= searchSelectWindow.offsetWidth;
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
else
{
var left = getXPos(searchField);
var top = getYPos(searchField);
top += searchField.offsetHeight;
// show search selection popup
searchSelectWindow.style.display='block';
searchSelectWindow.style.left = left + 'px';
searchSelectWindow.style.top = top + 'px';
}
// stop selection hide timer
if (this.hideTimeout)
{
clearTimeout(this.hideTimeout);
this.hideTimeout=0;
}
return false; // to avoid "image drag" default event
}
this.OnSearchSelectHide = function()
{
this.hideTimeout = setTimeout(this.name +".CloseSelectionWindow()",
this.closeSelectionTimeout);
}
// Called when the content of the search field is changed.
this.OnSearchFieldChange = function(evt)
{
if (this.keyTimeout) // kill running timer
{
clearTimeout(this.keyTimeout);
this.keyTimeout = 0;
}
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 || e.keyCode==13)
{
if (e.shiftKey==1)
{
this.OnSearchSelectShow();
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
child.focus();
return;
}
}
return;
}
else if (window.frames.MSearchResults.searchResults)
{
var elem = window.frames.MSearchResults.searchResults.NavNext(0);
if (elem) elem.focus();
}
}
else if (e.keyCode==27) // Escape out of the search field
{
this.DOMSearchField().blur();
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
this.Activate(false);
return;
}
// strip whitespaces
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue != this.lastSearchValue) // search value has changed
{
if (searchValue != "") // non-empty search
{
// set timer for search update
this.keyTimeout = setTimeout(this.name + '.Search()',
this.keyTimeoutLength);
}
else // empty search field
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.lastSearchValue = '';
}
}
}
this.SelectItemCount = function(id)
{
var count=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
count++;
}
}
return count;
}
this.SelectItemSet = function(id)
{
var i,j=0;
var win=this.DOMSearchSelectWindow();
for (i=0;i<win.childNodes.length;i++)
{
var child = win.childNodes[i]; // get span within a
if (child.className=='SelectItem')
{
var node = child.firstChild;
if (j==id)
{
node.innerHTML='•';
}
else
{
node.innerHTML=' ';
}
j++;
}
}
}
// Called when an search filter selection is made.
// set item with index id as the active item
this.OnSelectItem = function(id)
{
this.searchIndex = id;
this.SelectItemSet(id);
var searchValue = this.DOMSearchField().value.replace(/ +/g, "");
if (searchValue!="" && this.searchActive) // something was found -> do a search
{
this.Search();
}
}
this.OnSearchSelectKey = function(evt)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==40 && this.searchIndex<this.SelectItemCount()) // Down
{
this.searchIndex++;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==38 && this.searchIndex>0) // Up
{
this.searchIndex--;
this.OnSelectItem(this.searchIndex);
}
else if (e.keyCode==13 || e.keyCode==27)
{
this.OnSelectItem(this.searchIndex);
this.CloseSelectionWindow();
this.DOMSearchField().focus();
}
return false;
}
// --------- Actions
// Closes the results window.
this.CloseResultsWindow = function()
{
this.DOMPopupSearchResultsWindow().style.display = 'none';
this.DOMSearchClose().style.display = 'none';
this.Activate(false);
}
this.CloseSelectionWindow = function()
{
this.DOMSearchSelectWindow().style.display = 'none';
}
// Performs a search.
this.Search = function()
{
this.keyTimeout = 0;
// strip leading whitespace
var searchValue = this.DOMSearchField().value.replace(/^ +/, "");
var code = searchValue.toLowerCase().charCodeAt(0);
var hexCode;
if (code<16)
{
hexCode="0"+code.toString(16);
}
else
{
hexCode=code.toString(16);
}
var resultsPage;
var resultsPageWithSearch;
var hasResultsPage;
if (indexSectionsWithContent[this.searchIndex].charAt(code) == '1')
{
resultsPage = this.resultsPath + '/' + indexSectionNames[this.searchIndex] + '_' + hexCode + '.html';
resultsPageWithSearch = resultsPage+'?'+escape(searchValue);
hasResultsPage = true;
}
else // nothing available for this search term
{
resultsPage = this.resultsPath + '/nomatches.html';
resultsPageWithSearch = resultsPage;
hasResultsPage = false;
}
window.frames.MSearchResults.location = resultsPageWithSearch;
var domPopupSearchResultsWindow = this.DOMPopupSearchResultsWindow();
if (domPopupSearchResultsWindow.style.display!='block')
{
var domSearchBox = this.DOMSearchBox();
this.DOMSearchClose().style.display = 'inline';
if (this.insideFrame)
{
var domPopupSearchResults = this.DOMPopupSearchResults();
domPopupSearchResultsWindow.style.position = 'relative';
domPopupSearchResultsWindow.style.display = 'block';
var width = document.body.clientWidth - 8; // the -8 is for IE :-(
domPopupSearchResultsWindow.style.width = width + 'px';
domPopupSearchResults.style.width = width + 'px';
}
else
{
var domPopupSearchResults = this.DOMPopupSearchResults();
var left = getXPos(domSearchBox) + 150; // domSearchBox.offsetWidth;
var top = getYPos(domSearchBox) + 20; // domSearchBox.offsetHeight + 1;
domPopupSearchResultsWindow.style.display = 'block';
left -= domPopupSearchResults.offsetWidth;
domPopupSearchResultsWindow.style.top = top + 'px';
domPopupSearchResultsWindow.style.left = left + 'px';
}
}
this.lastSearchValue = searchValue;
this.lastResultsPage = resultsPage;
}
// -------- Activation Functions
// Activates or deactivates the search panel, resetting things to
// their default values if necessary.
this.Activate = function(isActive)
{
if (isActive || // open it
this.DOMPopupSearchResultsWindow().style.display == 'block'
)
{
this.DOMSearchBox().className = 'MSearchBoxActive';
var searchField = this.DOMSearchField();
if (searchField.value == this.searchLabel) // clear "Search" term upon entry
{
searchField.value = '';
this.searchActive = true;
}
}
else if (!isActive) // directly remove the panel
{
this.DOMSearchBox().className = 'MSearchBoxInactive';
this.DOMSearchField().value = this.searchLabel;
this.searchActive = false;
this.lastSearchValue = ''
this.lastResultsPage = '';
}
}
}
// -----------------------------------------------------------------------
// The class that handles everything on the search results page.
function SearchResults(name)
{
// The number of matches from the last run of <Search()>.
this.lastMatchCount = 0;
this.lastKey = 0;
this.repeatOn = false;
// Toggles the visibility of the passed element ID.
this.FindChildElement = function(id)
{
var parentElement = document.getElementById(id);
var element = parentElement.firstChild;
while (element && element!=parentElement)
{
if (element.nodeName == 'DIV' && element.className == 'SRChildren')
{
return element;
}
if (element.nodeName == 'DIV' && element.hasChildNodes())
{
element = element.firstChild;
}
else if (element.nextSibling)
{
element = element.nextSibling;
}
else
{
do
{
element = element.parentNode;
}
while (element && element!=parentElement && !element.nextSibling);
if (element && element!=parentElement)
{
element = element.nextSibling;
}
}
}
}
this.Toggle = function(id)
{
var element = this.FindChildElement(id);
if (element)
{
if (element.style.display == 'block')
{
element.style.display = 'none';
}
else
{
element.style.display = 'block';
}
}
}
// Searches for the passed string. If there is no parameter,
// it takes it from the URL query.
//
// Always returns true, since other documents may try to call it
// and that may or may not be possible.
this.Search = function(search)
{
if (!search) // get search word from URL
{
search = window.location.search;
search = search.substring(1); // Remove the leading '?'
search = unescape(search);
}
search = search.replace(/^ +/, ""); // strip leading spaces
search = search.replace(/ +$/, ""); // strip trailing spaces
search = search.toLowerCase();
search = convertToId(search);
var resultRows = document.getElementsByTagName("div");
var matches = 0;
var i = 0;
while (i < resultRows.length)
{
var row = resultRows.item(i);
if (row.className == "SRResult")
{
var rowMatchName = row.id.toLowerCase();
rowMatchName = rowMatchName.replace(/^sr\d*_/, ''); // strip 'sr123_'
if (search.length<=rowMatchName.length &&
rowMatchName.substr(0, search.length)==search)
{
row.style.display = 'block';
matches++;
}
else
{
row.style.display = 'none';
}
}
i++;
}
document.getElementById("Searching").style.display='none';
if (matches == 0) // no results
{
document.getElementById("NoMatches").style.display='block';
}
else // at least one result
{
document.getElementById("NoMatches").style.display='none';
}
this.lastMatchCount = matches;
return true;
}
// return the first item with index index or higher that is visible
this.NavNext = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index++;
}
return focusItem;
}
this.NavPrev = function(index)
{
var focusItem;
while (1)
{
var focusName = 'Item'+index;
focusItem = document.getElementById(focusName);
if (focusItem && focusItem.parentNode.parentNode.style.display=='block')
{
break;
}
else if (!focusItem) // last element
{
break;
}
focusItem=null;
index--;
}
return focusItem;
}
this.ProcessKeys = function(e)
{
if (e.type == "keydown")
{
this.repeatOn = false;
this.lastKey = e.keyCode;
}
else if (e.type == "keypress")
{
if (!this.repeatOn)
{
if (this.lastKey) this.repeatOn = true;
return false; // ignore first keypress after keydown
}
}
else if (e.type == "keyup")
{
this.lastKey = 0;
this.repeatOn = false;
}
return this.lastKey!=0;
}
this.Nav = function(evt,itemIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
var newIndex = itemIndex-1;
var focusItem = this.NavPrev(newIndex);
if (focusItem)
{
var child = this.FindChildElement(focusItem.parentNode.parentNode.id);
if (child && child.style.display == 'block') // children visible
{
var n=0;
var tmpElem;
while (1) // search for last child
{
tmpElem = document.getElementById('Item'+newIndex+'_c'+n);
if (tmpElem)
{
focusItem = tmpElem;
}
else // found it!
{
break;
}
n++;
}
}
}
if (focusItem)
{
focusItem.focus();
}
else // return focus to search field
{
parent.document.getElementById("MSearchField").focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = itemIndex+1;
var focusItem;
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem && elem.style.display == 'block') // children visible
{
focusItem = document.getElementById('Item'+itemIndex+'_c0');
}
if (!focusItem) focusItem = this.NavNext(newIndex);
if (focusItem) focusItem.focus();
}
else if (this.lastKey==39) // Right
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'block';
}
else if (this.lastKey==37) // Left
{
var item = document.getElementById('Item'+itemIndex);
var elem = this.FindChildElement(item.parentNode.parentNode.id);
if (elem) elem.style.display = 'none';
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
this.NavChild = function(evt,itemIndex,childIndex)
{
var e = (evt) ? evt : window.event; // for IE
if (e.keyCode==13) return true;
if (!this.ProcessKeys(e)) return false;
if (this.lastKey==38) // Up
{
if (childIndex>0)
{
var newIndex = childIndex-1;
document.getElementById('Item'+itemIndex+'_c'+newIndex).focus();
}
else // already at first child, jump to parent
{
document.getElementById('Item'+itemIndex).focus();
}
}
else if (this.lastKey==40) // Down
{
var newIndex = childIndex+1;
var elem = document.getElementById('Item'+itemIndex+'_c'+newIndex);
if (!elem) // last child, jump to parent next parent
{
elem = this.NavNext(itemIndex+1);
}
if (elem)
{
elem.focus();
}
}
else if (this.lastKey==27) // Escape
{
parent.searchBox.CloseResultsWindow();
parent.document.getElementById("MSearchField").focus();
}
else if (this.lastKey==13) // Enter
{
return true;
}
return false;
}
}
function setKeyActions(elem,action)
{
elem.setAttribute('onkeydown',action);
elem.setAttribute('onkeypress',action);
elem.setAttribute('onkeyup',action);
}
function setClassAttr(elem,attr)
{
elem.setAttribute('class',attr);
elem.setAttribute('className',attr);
}
function createResults()
{
var results = document.getElementById("SRResults");
for (var e=0; e<searchData.length; e++)
{
var id = searchData[e][0];
var srResult = document.createElement('div');
srResult.setAttribute('id','SR_'+id);
setClassAttr(srResult,'SRResult');
var srEntry = document.createElement('div');
setClassAttr(srEntry,'SREntry');
var srLink = document.createElement('a');
srLink.setAttribute('id','Item'+e);
setKeyActions(srLink,'return searchResults.Nav(event,'+e+')');
setClassAttr(srLink,'SRSymbol');
srLink.innerHTML = searchData[e][1][0];
srEntry.appendChild(srLink);
if (searchData[e][1].length==2) // single result
{
srLink.setAttribute('href',searchData[e][1][1][0]);
if (searchData[e][1][1][1])
{
srLink.setAttribute('target','_parent');
}
var srScope = document.createElement('span');
setClassAttr(srScope,'SRScope');
srScope.innerHTML = searchData[e][1][1][2];
srEntry.appendChild(srScope);
}
else // multiple results
{
srLink.setAttribute('href','javascript:searchResults.Toggle("SR_'+id+'")');
var srChildren = document.createElement('div');
setClassAttr(srChildren,'SRChildren');
for (var c=0; c<searchData[e][1].length-1; c++)
{
var srChild = document.createElement('a');
srChild.setAttribute('id','Item'+e+'_c'+c);
setKeyActions(srChild,'return searchResults.NavChild(event,'+e+','+c+')');
setClassAttr(srChild,'SRScope');
srChild.setAttribute('href',searchData[e][1][c+1][0]);
if (searchData[e][1][c+1][1])
{
srChild.setAttribute('target','_parent');
}
srChild.innerHTML = searchData[e][1][c+1][2];
srChildren.appendChild(srChild);
}
srEntry.appendChild(srChildren);
}
srResult.appendChild(srEntry);
results.appendChild(srResult);
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button } from 'react-bootstrap';
require('../../styles/TwitterAuthentication.scss')
class TwitterAuthentication extends Component {
render() {
var isProduction = process.env.NODE_ENV === 'production';
if (isProduction) {
var url = 'https://mypinclone.herokuapp.com/auth/twitter/'
}
else {
var url = 'http://127.0.0.1:3000/auth/twitter/'
}
return (
<div className="TwitterLoginButtonDiv">
<a href = {url}>
<Button bsStyle="primary" bsSize="lg">
Sign in with Twitter
<i className="fa fa-twitter TwitterLogo"></i>
</Button>
</a>
</div>
);
}
}
export default TwitterAuthentication |
// Copyright 2017, University of Colorado Boulder
/**
* Copies a single file.
*
* @author Jonathan Olson <[email protected]>
*/
const fs = require( 'fs' );
const winston = require( 'winston' );
/**
* Copies a single file.
* @public
*
* @param {string} sourceFilename
* @param {string} destinationFilename
* @returns {Promise} - Resolves with no value
*/
module.exports = function( sourceFilename, destinationFilename ) {
return new Promise( ( resolve, reject ) => {
winston.info( `Copying ${sourceFilename} to ${destinationFilename}` );
const readStream = fs.createReadStream( sourceFilename );
const writeStream = fs.createWriteStream( destinationFilename );
readStream.pipe( writeStream );
readStream.on( 'end', () => resolve() );
readStream.on( 'error', err => reject( new Error( err ) ) );
writeStream.on( 'error', err => reject( new Error( err ) ) );
} );
};
|
$(document).ready(function () {
var chatPublishChannel = 'chat_send',
chatSubscribeChannel = 'chat_receive',
inputMessage = $('#inputMessage'),
inputMessageSubmit = $("#inputMessageSubmit"),
messageList = $("#message-list"),
onlineUsersList = $("#onlineUsers"),
ATCUserName = $("#ATCUserName"),
ATCControlLoc = $("#ATCcontrol"),
ATClogin = $("#ATClogin"),
ATCleave = $("#leave"),
LoginScreen = $(".overlay"),
ATCuserlist = [],
pub_key = 'pub-c-578b72c9-0ca2-4429-b7d4-313bbdf9b335',
sub_key = 'sub-c-471f5e36-e1ef-11e6-ac69-0619f8945a4f',
ATCusername,
ATCctrlname;
var weather_states = {
"Tornado":0,"Tropical Storm":1,"Hurricane":2,"Strong Storms":3,
"Rain to Snow Showers":5,"Rain / Sleet":6,"Wintry Mix Snow":7,
"Freezing Drizzle":8,"Drizzle":9,"Freezing Rain":10,"Light Rain":11,
"Rain":12,"Scattered Flurries":13,"Light Snow":14,"Blowing / Drifting Snow":15,
"Snow":16,"Hail":17,"Sleet":18,"Blowing Dust / Sandstorm":19,
"Foggy":20,"Haze / Windy":21,"Smoke / Windy":22,"Breezy":23,
"Blowing Spray / Windy":24,"Frigid / Ice Crystals":25,"Cloudy":26,
"Mostly Cloudy":27,"Mostly Cloudy":28,"Partly Cloudy":29,"Partly Cloudy":30,
"Clear":31,"Sunny":32,"Fair / Mostly Clear":33,"Fair / Mostly Sunny":34,
"Mixed Rain & Hail":35,"Hot":36,"Isolated Thunderstorms":37,"Thunderstorms":38,
"Scattered Showers":39,"Heavy Rain":40,"Scattered Snow Showers":41,
"Heavy Snow":42,"Blizzard":43,"Not Available (N/A)":44,
"Scattered Showers":45,"Scattered Snow Showers":46,"Scattered Thunderstorms":47,
"Fair":26,"Fair / Windy":22
}
var pubnub = PUBNUB({
publish_key : pub_key,
subscribe_key : sub_key
})
function pub_subscribe(){
pubnub.subscribe({
channel : chatSubscribeChannel,
message : function(m){
console.log(m)
message_listing(m);
},
error : function (error) {
console.log(JSON.stringify(error));
}
});
};
function message_listing(m){
if(m.command == "join"){
ATCuserlist.push(m.user);
var userData = {
ATC_UserIcon : Math.floor(Math.random() * 8) + 1,
ATC_UserName : m.user,
ATC_Location : m.ATClocation
}
if(ATCuserlist.length == 1){
var userTemplate = ['<li class="media clearList" id={{ATC_UserName}}>',
'<div class="media-body" style="background:#d5e5e1">',
'<div class="media">',
'<a class="pull-left" href="#">',
'<img class="media-object img-circle" style="max-height:40px;" src="assets/img/userImages/{{ATC_UserIcon}}.png" />',
'</a>',
'<div class="media-body" >',
'<h5>{{ATC_UserName}}</h5>',
'<small class="text-muted" style="text-transform: uppercase;">ATC-{{ATC_Location}}</small>',
'</div>',
'</div>',
'</div>',
'</li>'].join("\n");
}else{
var userTemplate = ['<li class="media clearList" id={{ATC_UserName}}>',
'<div class="media-body">',
'<div class="media">',
'<a class="pull-left" href="#">',
'<img class="media-object img-circle" style="max-height:40px;" src="assets/img/userImages/{{ATC_UserIcon}}.png" />',
'</a>',
'<div class="media-body" >',
'<h5>{{ATC_UserName}}</h5>',
'<small class="text-muted" style="text-transform: uppercase;">ATC-{{ATC_Location}}</small>',
'</div>',
'</div>',
'</div>',
'</li>'].join("\n");
}
var userList = Mustache.render(userTemplate, userData);
onlineUsersList.append(userList);
}else if(m.command == "message"){
for (var p in weather_states){
if (p == m.weatherStatus){
var weatherStatusIcon = weather_states[p];
break;
}
else{
var weatherStatusIcon = 44;
}
}
var userData = {
ATC_UserIcon : Math.floor(Math.random() * 8) + 1,
ATC_UserName : m.user,
ATC_Location : m.ATClocation
}
var count = 0;
for (var i = 0; i < ATCuserlist.length; i++) {
if (ATCuserlist[i] !== m.user){
count++;
}
else{
break;
}
};
if(count == ATCuserlist.length){
ATCuserlist.push(m.user);
var userTemplate = ['<li class="media clearList" id={{ATC_UserName}}>',
'<div class="media-body">',
'<div class="media">',
'<a class="pull-left" href="#">',
'<img class="media-object img-circle" style="max-height:40px;" src="assets/img/userImages/{{ATC_UserIcon}}.png" />',
'</a>',
'<div class="media-body" >',
'<h5>{{ATC_UserName}}</h5>',
'<small class="text-muted" style="text-transform: uppercase;">ATC-{{ATC_Location}}</small>',
'</div>',
'</div>',
'</div>',
'</li>'].join("\n");
var userList = Mustache.render(userTemplate, userData);
onlineUsersList.append(userList);
}
var messageData = {
ATC_UserIcon : Math.floor(Math.random() * 8) + 1,
userName : m.user,
userATClocation : m.ATClocation,
userMessageBody : m.userMessage,
weatherIcon : weatherStatusIcon,
weatherReport : m.weatherStatus
}
var messageTemplate = ['<li class="media clearMsgList" >',
'<div class="media-body">',
'<div class="media">',
'<a class="pull-left" href="#">',
'<img class="media-object img-circle" src="assets/img/userImages/{{ATC_UserIcon}}.png" alt="man1" height="40" width="40" />',
'<p style="text-align:center;">{{userName}}</p>',
'</a>',
'<div class="media-body" >{{userMessageBody}}',
' <br />',
'<small class="text-muted" style="text-transform: uppercase;"> ATC-{{userATClocation}} <img height="30" width="30" src="assets/img/weather/png/{{weatherIcon}}.png"> {{weatherReport}} </small>',
'<hr />',
'</div>',
'</div>',
'</div>',
'</li>'].join("\n");
var list = Mustache.render(messageTemplate, messageData);
messageList.append(list);
var height = 0;
$('div li').each(function(i, value){
height += parseInt($(this).height());
});
height += '';
$('div').animate({scrollTop: height});
}else if(m.command == "leave"){
$( "li" ).remove( "#"+m.user );
}
};
function send_message(){
inputMessageSubmit.click(function (event) {
var chatMessage = {
"command":"message",
"user":ATCusername,
"ATClocation":ATCctrlname,
"userMessage":inputMessage.val()
}
if(inputMessage.val().length != 0){
pub_publish(chatMessage);
inputMessage.val("");
}
});
};
ATClogin.on( "click", function() {
pub_subscribe();
setTimeout(function(){
var loginData = {"command":"join","user":ATCUserName.val(),"ATClocation":ATCControlLoc.val()}
ATCusername = ATCUserName.val();
ATCctrlname = ATCControlLoc.val();
pub_publish(loginData);
LoginScreen.fadeOut(1000);
setTimeout(function(){
LoginScreen.css("z-index","-10");
ATCUserName.val(""),
ATCControlLoc.val("Select Your ATC Location")
},1000);
document.getElementById('chat-header-username').innerHTML = ATCusername;
document.getElementById('chat-header-atcname').innerHTML = " - ATC-"+ATCctrlname;
},1000);
});
ATCleave.on( "click", function() {
var leaveData = {"command":"leave","user":ATCusername,"ATClocation":ATCctrlname};
pub_publish(leaveData);
$( "li" ).remove(".clearMsgList");
$( "li" ).remove(".clearList");
ATCuserlist.length = 0;
LoginScreen.css("z-index","10");
LoginScreen.fadeIn(1000);
pubnub.unsubscribe({
channel : chatSubscribeChannel,
});
});
function pub_publish(pub_msg){
pubnub.publish({
channel : chatPublishChannel,
message : pub_msg,
callback : function(m){
console.log(m)
}
});
};
send_message();
});
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm7.48 7.16l-5.01-.43-2-4.71c3.21.19 5.91 2.27 7.01 5.14zm-5.07 6.26L12 13.98l-2.39 1.44.63-2.72-2.11-1.83 2.78-.24L12 8.06l1.09 2.56 2.78.24-2.11 1.83.64 2.73zm-2.86-11.4l-2 4.72-5.02.43c1.1-2.88 3.8-4.97 7.02-5.15zM4 12c0-.64.08-1.26.23-1.86l3.79 3.28-1.11 4.75C5.13 16.7 4 14.48 4 12zm3.84 6.82L12 16.31l4.16 2.5c-1.22.75-2.64 1.19-4.17 1.19-1.52 0-2.94-.44-4.15-1.18zm9.25-.65l-1.11-4.75 3.79-3.28c.14.59.23 1.22.23 1.86 0 2.48-1.14 4.7-2.91 6.17z"
}), 'StarsOutlined'); |
// Automatically generated by scripts/createStyleInterpolations.js at Tue Jun 20 2017 00:01:09 GMT+0900 (JST)
// Imported darkula.css file from highlight.js
export default `
/*
Deprecated due to a typo in the name and left here for compatibility purpose only.
Please use darcula.css instead.
*/
@import url('darcula.css');
`
|
var app = angular.module('app', ['ngRoute','restangular','tien.clndr']);
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var edit = exports.edit = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M21.561 5.318l-2.879-2.879c-.293-.293-.677-.439-1.061-.439-.385 0-.768.146-1.061.439l-3.56 3.561h-9c-.552 0-1 .447-1 1v13c0 .553.448 1 1 1h13c.552 0 1-.447 1-1v-9l3.561-3.561c.293-.293.439-.677.439-1.061s-.146-.767-.439-1.06zm-10.061 9.354l-2.172-2.172 6.293-6.293 2.172 2.172-6.293 6.293zm-2.561-1.339l1.756 1.728-1.695-.061-.061-1.667zm7.061 5.667h-11v-11h6l-3.18 3.18c-.293.293-.478.812-.629 1.289-.16.5-.191 1.056-.191 1.47v3.061h3.061c.414 0 1.108-.1 1.571-.29.464-.19.896-.347 1.188-.64l3.18-3.07v6zm2.5-11.328l-2.172-2.172 1.293-1.293 2.171 2.172-1.292 1.293z" }, "children": [] }] }; |
var db = global.db;
module.exports = {
secure: function (req, res, next) {
var token = req.headers.token || "";
var tokenModel = db('tokens').find({token: token});
if (typeof tokenModel === "undefined") {
res.status(500).send({
error: "token_not_found"
});
} else {
var userModel = db('users').find({id: tokenModel["user_id"]});
req.user = userModel;
next();
}
},
checkFields: function (obj, arr) {
for (var i = 0; i < arr.length; i++) {
if (!obj.hasOwnProperty(arr[i])) {
return false;
} else {
if (obj[arr[i]].trim() === "") {
return false;
}
}
}
return true;
}
}; |
import { Meteor } from 'meteor/meteor';
Meteor.methods({
/**
* Meteor.methods get called by the client and the server simultaneously
* when invoked by the client. This allows us to update the client's version
* of the database immediately - latency compensation. If for whatever reason,
* the server responds with a different idea of how the database should look,
* it will take precedence and the changes the client made will be updated.
*
* For instance, if there are complex validation calculations, we can insert right
* away to the client db right away. If validation fails, the client db will be reverted.
*
* @param settingName
* @param value
*/
"updateSetting": function(settingName, value) {
var settings;
// This is for latency compensation. Let the client update the client db right away.
settings = Meteor.users.findOne({_id: this.userId}).settings || {};
settings[settingName] = value;
Meteor.users.update({_id: this.userId}, {$set: {settings: settings}});
},
"updateRoom": function(roomId) {
Meteor.users.update({_id: this.userId}, {$set: {currentRoomId: roomId}});
}
}); |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({transparency:"Transpar\u00eancia",suggested:"Sugerido",recent:"Recente",more:"Mais",moreColorsTooltip:"Visualize mais cores.",paletteTooltip:"Selecione uma cor.",noColorTooltip:"Sem",hexInputTooltip:"Uma cor personalizada na nota\u00e7\u00e3o hexadecimal (#FFFF00)."}); |
import React from 'react'
import Modal from 'react-modal'
import {connect} from 'react-redux'
import {Link} from 'react-router'
import RequestPasswordReset from './RequestPasswordReset'
import PendingAccountModal from './PendingAccountModal'
import validator from 'validator'
import {login} from '../../actions/authActions'
import 'icheck/skins/all.css'
import "../../css/third-party/bootstrap-social.css"
import {websiteTitle} from '../../conf/application.properties'
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
errors: {},
modalIsOpen: false,
pendingAccountModalIsOpen: false,
isLoading: false
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.validateInput = this.validateInput.bind(this);
this.closeModal = this.closeModal.bind(this);
this.openModal = this.openModal.bind(this);
this.openPendingAccountModal = this.openPendingAccountModal.bind(this);
this.closePendingAccountModal = this.closePendingAccountModal.bind(this);
}
componentWillMount() {
const {isAuthenticated} = this.props;
if (isAuthenticated) {
this.context.router.push('/loggedin');
}
}
componentDidUpdate() {
const {isAuthenticated} = this.props;
if (isAuthenticated) {
this.context.router.push('/loggedin');
}
}
onChange(e) {
this.setState({[e.target.name] : e.target.value});
}
validateInput(formData) {
let errors = {};
if (!validator.isEmail(formData.email)) errors.email = "Not a valid email address";
if (validator.isEmpty(formData.password)) errors.password = "Enter a password";
this.setState({errors});
return !errors.email && !errors.password;
}
onSubmit(e) {
e.preventDefault();
if (this.validateInput(this.state)) {
this.setState({errors:{}, isLoading:true});
this.props.login({...this.state, username: this.state.email}).then(
() => {},
(json) => {
if (!json)
this.setState({isLoading: false, errors: {server: 'Something went wrong while trying to call the server!'}});
else {
if (json.errorCode === 1003) {
this.setState({isLoading: false, errors: {}});
this.openPendingAccountModal();
return;
} else {
this.setState({isLoading: false, errors: {server: json.description}});
}
}
}
);
}
}
openModal() {
this.setState({modalIsOpen: true});
}
closeModal() {
this.setState({modalIsOpen: false});
}
openPendingAccountModal() {
this.setState({pendingAccountModalIsOpen: true});
}
closePendingAccountModal() {
this.setState({pendingAccountModalIsOpen: false});
}
render() {
const {errors, modalIsOpen, pendingAccountModalIsOpen} = this.state;
return (
<div className="login-box">
<div className="login-logo">
<Link to="/">{websiteTitle}</Link>
</div>
<div className="login-box-body">
<p className="login-box-msg">Sign in to start your session</p>
{
errors &&
errors.server &&
<p className="login-server-error">
{errors.server}
</p>
}
<form onSubmit={this.onSubmit} method="post">
<div className="form-group has-feedback">
<input onChange={this.onChange} type="text" className="form-control" placeholder="Email" name="email" />
<span className="glyphicon glyphicon-envelope form-control-feedback"></span>
{errors && errors.email && <span className="form-input-error-message">{errors.email}</span>}
</div>
<div className="form-group has-feedback">
<input onChange={this.onChange} type="password" className="form-control" placeholder="Password" name="password" />
<span className="glyphicon glyphicon-lock form-control-feedback"></span>
{errors && errors.password && <span className="form-input-error-message">{errors.password}</span>}
</div>
<div className="row">
<div className="col-xs-8"></div>
<div className="col-xs-4">
<button disabled={this.state.isLoading} type="submit" className="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
</div>
</form>
<div className="social-auth-links text-center">
<p>- OR -</p>
<a className="btn btn-block btn-social btn-facebook btn-flat"><i className="fa fa-facebook"></i> Sign in using
Facebook</a>
<a className="btn btn-block btn-social btn-google btn-flat"><i className="fa fa-google-plus"></i> Sign in using
Google+</a>
</div>
<a onClick={this.openModal}>I forgot my password</a>
<br/>
<Link to="/signup"><span className="text-center">Register a new membership</span></Link>
</div>
<Modal
isOpen={modalIsOpen}
contentLabel="Modal"
style={{overlay:{
backgroundColor: 'rgba(0, 0, 0, 0.3)'
},
content : {
position: 'relative',
top: '0',
right: '0',
bottom: '0',
left: '0',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '4px',
outline: 'none',
padding: '20px',
margin: '20px',
marginTop: '40px'
}
}
}
onRequestClose={this.closeModal}>
<RequestPasswordReset closeModal={this.closeModal} />
</Modal>
<Modal
isOpen={pendingAccountModalIsOpen}
contentLabel="Modal"
style={
{overlay:{
backgroundColor: 'rgba(0, 0, 0, 0.3)'
},
content : {
position: 'relative',
top: '0',
right: '0',
bottom: '0',
left: '0',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '4px',
outline: 'none',
padding: '20px',
margin: '20px',
marginTop: '40px'
}
}
}
onRequestClose={this.closePendingAccountModal}>>
<PendingAccountModal closeModal={this.closePendingAccountModal} />
</Modal>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
isAuthenticated: state.auth.isAuthenticated
};
}
Login.contextTypes = {
router: React.PropTypes.object.isRequired
}
export default connect(mapStateToProps, {login})(Login);
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var emails = require('../../app/controllers/emails.server.controller');
// Emails Routes
app.route('/api/emails')
.get(emails.list)
.post(users.requiresLogin, emails.create);
app.route('/api/emails/:emailId')
.get(emails.read)
.put(users.requiresLogin, emails.hasAuthorization, emails.update)
.delete(users.requiresLogin, emails.hasAuthorization, emails.delete);
app.route('/sendEmail').post(emails.sendEmail);
// Finish by binding the Email middleware
app.param('emailId', emails.emailByID);
};
|
var lang = {
"lang_code": "en",
"lang_name": "English",
"title": "Data retention in Switzerland",
"town_zuerich": "Zurich",
"town_bern": "Bern",
"town_basel": "Basel",
"town_genf": "Geneva",
"town_luzern": "Lucerne",
"town_lausanne": "Lausanne",
"weekday_short_mon": "Mon",
"weekday_short_tue": "Tue",
"weekday_short_wed": "Wed",
"weekday_short_thu": "Thu",
"weekday_short_fri": "Fri",
"weekday_short_sat": "Sat",
"weekday_short_sun": "Sun",
"msg_type_fb": "Facebook post",
"msg_type_tw": "Tweet",
"msg_type_sm": "SMS %",
"msg_type_ca": "Call %",
"msg_type_ma": "Email %",
"word_from": "from",
"word_to": "to",
"word_From": "From",
"word_To": "To",
"word_Content": "Content",
"word_number": "No.",
"social_info_name": "Name",
"social_info_org": "Group",
"social_info_email_out": "Emails to Balthasar",
"social_info_email_in": "Emails from Balthasar",
"social_info_email_co": "In CC of E-Mails to Balthasar",
"social_info_sms_out": "SMS to Balthasar",
"social_info_sms_in": "SMS from Balthasar",
"social_info_call_out": "Calls to Balthasar",
"social_info_call_in": "Calls from Balthasar",
"social_info_maincomtimes": "Main time of communication",
"contact_adlethorensgoumaz": "Adèle Thorens Goumaz",
"contact_arztrztin": "Doctor",
"contact_assistentin": "Assistant",
"contact_asylchmailingliste": "asyl.ch mailing list",
"contact_asylchnewsletter": "asyl.ch newsletter",
"contact_balthasarglttli": "Balthasar Glättli",
"contact_brigittemarti": "Brigitte Marti",
"contact_bundesrat": "Federal Council",
"contact_digigesmailingliste": "digiges mailing list",
"contact_diverse": "miscellaneous",
"contact_doodlenewsletter": "doodle newsletter",
"contact_facebooknewsletter": "Facebook newsletter",
"contact_factschnewsletter": "facts.ch newsletter",
"contact_familie": "Family",
"contact_gemeinderat": "Local council",
"contact_googlealerts": "Google Alerts",
"contact_googlecalendar": "Google Calendar",
"contact_googlenewsletter": "Google newsletter",
"contact_grne": "The Greens",
"contact_hyperalertsnewsletter": "hyperalerts newsletter",
"contact_journalistin": "Journalist",
"contact_kantonsrat": "Canton council",
"contact_medien": "Media",
"contact_mediendienstezuerichch": "[email protected]",
"contact_minlimartipartnerin": "Min Li Marti (partner)",
"contact_miriambehrens": "Miriam Behrens",
"contact_mutter": "Mother",
"contact_nationalrat": "National Council",
"contact_netzwochechnewsletter": "netzwoche.ch newsletter",
"contact_newsadminchnewsletter": "news.admin.ch newsletter",
"contact_newsaktuellch": "newsaktuell.ch",
"contact_ngo": "NGO",
"contact_ngomieterrecht": "NGO tenant-right",
"contact_ngomigrationasyl": "NGO migration/asylum",
"contact_nzznewsletter": "NZZ newsletter",
"contact_parlamentarierin": "Member of Parliament",
"contact_parlamentsnewsletter": "Parliament newsletter",
"contact_person": "Person",
"contact_pfarrer": "Priest",
"contact_politik": "Politics",
"contact_politnetznewsletter": "Politnetz newsletter",
"contact_rechtsanwalt": "Lawyer",
"contact_ronorpnetnewsletter": "ronorp.net newsletter",
"contact_sonstigerkontakt": "Other contact",
"contact_stadtrat": "City Council",
"contact_stnderat": "Council of States",
"contact_swissconsortiumnewsletter": "swissconsortium newsletter",
"contact_tamedianewsletter": "Tamedia newsletter",
"contact_twitter": "Twitter",
"contact_uelileuenberger": "Ueli Leuenberger",
"contact_universitt": "University",
"contact_vater": "Father",
"contact_verteiler": "Mailing list",
"contact_wordpresscomnewsletter": "wordpress.com newsletter",
"contact_xingcomnewsletter": "xing.com newsletter"
} |
"use strict";
require("./document_test");
require("./selection_test");
|
/**
* builder funciton. return jQuery object for chaining and triggering events
* @return {jQuery}
*/
ChartAPI.Build = function (settings) {
var $container;
if (typeof settings === 'string' && (/\.json$/).test(settings)) {
$container = $('<div class="mtchart-container">');
ChartAPI.Data.getData($.getJSON(settings), null, function (settings) {
settings.$container = $container;
ChartAPI.Build_(settings).trigger('APPEND');
});
} else {
$container = ChartAPI.Build_(settings).trigger('APPEND');
}
return $container;
};
/**
* internal method for building graph|slider|list objects
* @param {Object} settings
* @param {=jQuery} jQuery object to attach graph|slider|list object
*/
ChartAPI.Build_ = function (settings) {
var $container, $graphContainer, $sliderContainer, $listContainer, dataRangeTarget, sliderUpdateTarget, sliderAmountTarget;
$container = settings.$container || $('<div class="mtchart-container">');
sliderUpdateTarget = [];
if (settings.graph) {
$graphContainer = new ChartAPI.Graph(settings.graph, settings.range);
sliderUpdateTarget.push($graphContainer);
}
if (settings.list) {
$listContainer = new ChartAPI.List(settings.list, settings.range);
if (settings.list.data) {
sliderUpdateTarget.push($listContainer);
}
}
if (settings.graph && settings.graph.type !== 'donut') {
dataRangeTarget = $graphContainer;
sliderAmountTarget = [$graphContainer];
} else {
dataRangeTarget = $listContainer;
sliderAmountTarget = [$listContainer];
}
var isSmartPhone = function () {
var userAgent = window.navigator ? window.navigator.userAgent : '';
return (/android|iphone|ipod|ipad/i).test(userAgent);
};
if (settings.slider && (settings.slider.force || !isSmartPhone())) {
$sliderContainer = new ChartAPI.Slider(settings.slider, settings.range, dataRangeTarget, sliderUpdateTarget, sliderAmountTarget);
}
$container.on('APPEND', function () {
if ($graphContainer) {
$graphContainer.trigger('APPEND_TO', [$container]);
}
if ($sliderContainer) {
$sliderContainer.trigger('BUILD_SLIDER')
.trigger('APPEND_TO', [$container]);
}
if ($listContainer) {
$listContainer.trigger('APPEND_TO', [$container]);
}
});
$container.on('GET_CONTAINER', function (e, type, callback) {
callback({
'graph': $graphContainer,
'slider': $sliderContainer,
'list': $listContainer
}[type]);
});
return $container;
};
|
var assign = require('object-assign');
var isFunction = require('lodash/lang/isFunction');
var omit = require('lodash/object/omit');
var actionMixin = {
/**
* Get the entity identifier for the form loading.
* @returns {object} - The identifier of the entity.
*/
_getId: function formGetId() {
if(this.getId){
return this.getId();
}
return this.state.id;
},
/**
* Get a clean state to send data to the server.
* @returns {object} - The state json cleanded
*/
_getCleanState: function(){
return omit(this.state, ['reference', 'isLoading', 'isEdit']);
},
/**
* Compute the entity read from the html givent the keys and the definition Path, this operation is reversed from the _computeEntityFromStore operation.
* @param {object} htmlData - Data read from the html form.
*/
_computeEntityFromHtml: function(htmlData){
const DEF = `${this.definitionPath}.`;
const EMPTY = '';
let computedEntity = {};
for(let prop in htmlData){
computedEntity[prop.replace(DEF, EMPTY)] = htmlData[prop];
}
return computedEntity;
},
/**
* Get the constructed entity from the state.
* @returns {object} - the entity informations.
*/
_getEntity: function formGetEntity(){
if(this.getEntity){
return this.getEntity();
}
//Build the entity value from the ref getVaue.
var htmlData = {};
for(var r in this.refs){
//If the reference has a getValue function if is read.
if(this.refs[r] && isFunction(this.refs[r].getValue)){
htmlData[r] = this.refs[r].getValue();
}
}
//Maybe a merge cold be done if we need a deeper property merge.
return assign({}, this._getCleanState(), this._computeEntityFromHtml(htmlData));
},
/**
* Load data action call.
*/
_loadData: function formLoadData() {
this.action.load(this._getId());
}
};
module.exports = actionMixin;
|
'use strict';
var chai = require('chai');
var should = chai.should();
var Response = require('../lib/response');
var Request = require('../lib/request');
var Method = require('../lib/method');
describe('Response', function() {
var responseMock, requestMock;
beforeEach(function() {
var methodMock = new Method('GetFoo');
requestMock = new Request({method: methodMock});
responseMock = Response.create(requestMock);
});
it('instantiates from constructor', function() {
var response = new Response(requestMock);
should.exist(response);
});
it('instantiates from create', function() {
should.exist(responseMock);
});
it('sets id', function() {
responseMock.id.should.equal(requestMock.id);
});
it('sets error if response contains error', function() {
responseMock.receive({error: {message: 'bad', code: 911}});
responseMock.error.should.equal('911: bad');
});
it('sets error "Invalid response" if response ID differs from request', function() {
responseMock.receive({id: null});
responseMock.error.should.contain('Invalid response');
});
it('sets result if no error', function() {
responseMock.receive({id: responseMock.id, result: 'bar'});
responseMock.result.should.equal('bar');
});
it('sets result to null on error', function() {
responseMock.receive({id: 'not 1234', result: 'bar'});
true.should.equal(responseMock.result === null);
});
});
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var XmlElementNames_1 = require("../../../Core/XmlElementNames");
var Recurrence_IntervalPattern_1 = require("./Recurrence.IntervalPattern");
/**
* Represents a regeneration pattern, as used with recurring tasks, where each occurrence happens a specified number of weeks after the previous one is completed.
*/
var WeeklyRegenerationPattern = (function (_super) {
__extends(WeeklyRegenerationPattern, _super);
function WeeklyRegenerationPattern(startDate, interval) {
if (arguments.length === 0) {
_super.call(this);
return;
}
_super.call(this, startDate, interval);
}
Object.defineProperty(WeeklyRegenerationPattern.prototype, "XmlElementName", {
/**
* @internal Gets the name of the XML element.
*
* @value The name of the XML element.
*/
get: function () {
return XmlElementNames_1.XmlElementNames.WeeklyRegeneration;
},
enumerable: true,
configurable: true
});
Object.defineProperty(WeeklyRegenerationPattern.prototype, "IsRegenerationPattern", {
/**
* Gets a value indicating whether this instance is a regeneration pattern.
*
* @value *true* if this instance is a regeneration pattern; otherwise, *false*.</value>
*/
get: function () {
return true;
},
enumerable: true,
configurable: true
});
return WeeklyRegenerationPattern;
}(Recurrence_IntervalPattern_1.IntervalPattern));
exports.WeeklyRegenerationPattern = WeeklyRegenerationPattern;
|
const Koa = require('koa')
const request = require('koa-test')
const supertest = require('supertest')
const agent = app => supertest.agent(app.callback())
const utils = require('utility')
const test = require('ava')
supertest.Test.prototype.testJson = function (value, status = 200) {
if (typeof(value) === 'object') {
value = JSON.stringify(value)
}
return this.set('Content-Type', 'application/json')
.send(value)
.expect(status)
.expect('Content-Type', /json/)
.then(JsonMiddle)
};
supertest.Test.prototype.sendJson = function (value) {
if (typeof(value) === 'object') {
value = JSON.stringify(value)
}
return this.set('Content-Type', 'application/json')
.send(value)
};
const envir = require('../../envir')
const TEST_DB = 'pache_test'
envir.db = `mongodb://127.0.0.1:27017/${TEST_DB}`
envir.limit = 3;
envir.pass = '測試用的哦'
const Model = require('../../model')
const apiRouter = require('../../back/api')
const app = new Koa
app.use(apiRouter.routes(), apiRouter.allowedMethods())
/* 準備環境 */
let ag = null
let inserted_list = []
let delete_ids = null
let topic_article = null
let categories = []
test.before('準備環境', async t => {
ag = agent(app)
await Model.connectStatus
try {
await Model.removeCollection('articles')
} catch (_) {}
try {
await Model.removeCollection('categories')
} catch(_) {}
const category_1 = new Model.Category({name: 'cate_1'})
const category_2 = new Model.Category({name: 'cate_2'})
categories = categories.concat([
await category_1.save(),
await category_2.save()
])
const d_arts = [
{ title: '我會被刪掉的' },
{ title: '我會被刪掉的' }
];
const delete_article = [];
for (let art of d_arts) {
let inserted = await (new Model.Article({
title: '我會被刪掉的'
})).save()
delete_article.push(inserted)
}
delete_ids = delete_article.map(a => a._id.toString())
const article_list = [
{title: '標題一', category: category_1._id.toString(), tags: ['java', 'python', 'public']},
{title: '標題二', category: category_1._id.toString(), tags: ['torzo', 'public']},
{title: '標題三', category: category_1._id.toString(), tags: ['pache', 'oop', 'public']},
{title: '標題四', category: category_2._id.toString(), tags: ['durzo', 'osb', 'public']},
{title: '標題五', category: category_2._id.toString(), tags: ['魔術', 'ability', 'fff']},
{title: '標題六', category: category_2._id.toString(), tags: ['pache', 'iptp', 'fff']}
];
const p_arr = [];
for (let arts of article_list) {
let article_ins = new Model.Article(arts)
inserted_list.push(await article_ins.save())
}
topic_article = inserted_list.slice(-1)
})
/**
JSON 統一格式
@param msg 消息
@param code 返回碼,無錯誤時通常為 0
@param result 返回的結果
*/
const JsonMiddle = (res) => {
try {
res.json = JSON.parse(res.text)
} catch (e) {
console.warn('JsonMiddle fail, text:', res.text)
throw e
}
return res
}
test('GET /api/topic', async t => {
let web = await ag.get('/topic').then(JsonMiddle)
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
t.regex(result.title, /標題六/)
})
test('GET /api/articles/:pagecode', async t => {
let web = await ag.get('/articles/1').then(JsonMiddle)
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
t.is(Array.isArray(result), true) //是個數組
t.is(result.length, envir.limit) //單頁最大限制為 envir.limit
t.is(result[0].title, '標題六')
t.is(result[1].title, '標題五')
t.is(result[2].title, '標題四')
})
test('PATCH /api/article/:id', async t => {
let patch_article = inserted_list.slice(-1).pop()
let patch_id = patch_article._id.toString()
let web = await ag.patch(`/article/${patch_id}`).testJson({
$push: { tags: {$each: ['index']} }
})
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
let article = await Model.Article.findOne({ _id: patch_id })
t.is(article.title, patch_article.title)
t.is(article.tags.includes('index'), true)
})
test('PATCH /api/articles', async t => {
let patch_list = inserted_list.slice(-3)
let patch_list_ids = patch_list.map(art => art._id.toString())
let web = await ag.patch('/articles').testJson({
ids: patch_list_ids,
fields: {
$push: { tags: {$each: ['Misaka10032', 'Sisters']} }
}
})
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
const modelResult = await Model.Article.find({_id: {$in: patch_list_ids}})
modelResult.forEach(art => {
t.is(art.tags.includes('Misaka10032'), true)
t.is(art.tags.includes('Sisters'), true)
})
})
test('DELETE /api/articles', async t => {
let web = await ag.delete('/articles').send(delete_ids).then(JsonMiddle)
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
let list = await Model.Article.find()
list.forEach(a => {
t.is(delete_ids.includes(a._id.toString()), false)
})
})
test('GET /api/article/:articleid', async t => {
const inserted = inserted_list.slice(-1).pop()
const inserted_id = inserted._id.toString()
let web = await ag.get(
`/article/${inserted_id}`
).then(JsonMiddle)
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
t.is(result._id.toString(), inserted_id)
})
test('POST /api/article', async t => {
let web = await ag.post('/article').testJson({
title: '這是一篇新的文章',
content: '測試完成後就會被刪除',
date: new Date(1970),
})
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
let inserted = await Model.Article.findOne({_id: result._id})
t.is(result.title, inserted.title)
await Model.Article.find({ _id: result._id }).remove()
})
test('GET /api/categories', async t => {
let web = await ag.get('/categories').then(JsonMiddle)
t.is(web.status, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
const name_list = result.map(r => r.name)
t.is(name_list.length, 2)
t.is(name_list.includes('cate_1'), true)
t.is(name_list.includes('cate_2'), true)
})
test('POST /api/category', async t => {
const insert_cate = { name: 'new_cate'}
let web = await ag.post('/category').testJson(insert_cate, 200)
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
const new_cate = await Model.Category.findOne({ _id: result._id})
t.is(new_cate.name, result.name)
await new_cate.remove()
})
test('PATCH /api/category/:categoryid', async t => {
const categories = await Model.Category.find()
const inserted = categories.slice(-1).pop()
const inserted_id = inserted._id.toString()
let web = await ag.patch(`/category/${inserted_id}`).testJson({
color: '#233'
})
let {msg, code, result} = web.json
t.is(code, 0)
t.not(msg.length, 0)
const patched = await Model.Category.findOne({ _id: inserted_id })
t.is(patched.color, '#233')
})
test('DELETE /api/category/:categoryid', async t => {
const new_cate = await (new Model.Category({ name: '我會被刪' })).save()
const new_cate_id = new_cate._id.toString()
let web = await agent(app).delete(`/category/${new_cate_id}`)
.expect(200)
.expect('Content-Type', /json/)
.then(JsonMiddle);
const deleted_cate = await Model.Category.findOne({ _id: new_cate_id })
t.is(deleted_cate, null)
})
|
/* Grunt Task configuration */
module.exports = function(grunt) {
/* using jit-grunt for automatically loading all required plugins */
require('jit-grunt')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Compile Sass to CSS and produce SoureMaps;
sass: {
options: {
sourceMap: true,
outputStyle: 'uncompressed'
},
files: {
src: 'scss/main.scss',
dest: 'dist/css/styles.min.css',
ext: '.css'
}
},
// PostCSS for adding prefixers and setting rem to pixels;
postcss: {
dist: {
src: 'dist/css/styles.min.css'
},
options: {
// Rewrite and save sourcemap as seperate file
map: {
inline: false
},
processors: [
// add fallbacks for rem units
require('pixrem')({
atrules: true
}),
// add vendor prefixes
require('autoprefixer')({ browsers: 'iOS >= 7, last 2 versions, ie > 7' }),
// minify the result
require('cssnano')()
]
},
},
watch: {
scss: {
files: ['scss/**/*.scss', 'node_modules/**/*.scss' ],
tasks: ['sass', 'postcss'],
options: {
spawn: false,
},
},
nunjucks: {
files: 'views/**/*.html',
tasks: ['nunjucks'],
options: {
spawn: false,
},
}
},
nunjucks: {
render: {
options: {
paths: ['views'],
trimBlock: true,
lstripBlocks: true,
data: grunt.file.readJSON('templates-data.json')
},
files: [
{
expand: true,
cwd: "views/",
src: "*.html",
dest: "dist/",
ext: ".html"
}
]
}
},
browserSync: {
dev: {
bsFiles: {
src : [
'./dist/**/*.css',
'./dist/**/*.html',
]
},
options: {
watchTask: true,
server: './dist/'
}
}
}
});
grunt.loadNpmTasks('grunt-nunjucks-2-html');
/*
* Grunt tasks
* Run with grunt or grunt <command> in terminal
*/
grunt.registerTask('default', 'run');
grunt.registerTask('run',
[
'nunjucks',
'sass',
'postcss',
'browserSync',
'watch'
]
);
grunt.registerTask('create_css',
[
'sass',
'postcss'
]
);
grunt.registerTask('create_html',
[
'nunjucks'
]
);
};
|
{
a: 1,
b: 2,
}
|
/*jslint node: true, nomen: true*/
/*global describe, it*/
/**
* Developed By Carlo Bernaschina (GitHub - B3rn475)
* www.bernaschina.com
*
* Distributed under the MIT Licence
*/
"use strict";
var assert = require("assert"),
validator = require("../").validator,
field = require("../").field;
describe('validator', function () {
it('should be a function', function () {
assert.equal(typeof validator, 'function');
});
it('should return a middleware', function () {
var middleware = validator();
assert.equal(typeof middleware, 'function');
assert.equal(middleware.length, 3);
});
it('should throw with invalid arguments', function () {
assert.throws(function () {validator(undefined); });
assert.throws(function () {validator(null); });
assert.throws(function () {validator(true); });
assert.throws(function () {validator(0); });
assert.throws(function () {validator("string"); });
assert.throws(function () {validator(/a-z/); });
assert.throws(function () {validator([]); });
assert.throws(function () {validator({}); });
assert.throws(function () {validator(function () {}); });
});
it('should not throw with fields as arguments', function () {
var field1 = field.body("pippo"),
field2 = field.body("pippo");
validator(field1);
validator(field1, field2);
});
it('should create the structure', function () {
var req = {},
res = {},
done = false;
validator()(req, res, function (err) {
assert.equal(err, undefined);
assert.equal(typeof req.formwork === 'object', true);
assert.equal(typeof req.formwork.query === 'object', true);
assert.equal(typeof req.formwork.body === 'object', true);
assert.equal(typeof req.formwork.params === 'object', true);
assert.equal(typeof req.formwork.any === 'object', true);
done = true;
});
assert.equal(done, true);
});
it('should preserve structure', function () {
var query = {}, body = {}, params = {}, any = {},
formwork = {
query: query,
body: body,
params: params,
any: any
},
req = {formwork: formwork},
res = {},
done = false;
validator()(req, res, function (err) {
assert.equal(err, undefined);
assert.equal(req.formwork, formwork);
assert.equal(req.formwork.query, query);
assert.equal(req.formwork.body, body);
assert.equal(req.formwork.params, params);
assert.equal(req.formwork.any, any);
done = true;
});
assert.equal(done, true);
});
it('should forward error', function () {
var req = {},
res = {},
done = false;
validator(
field.body('name').validate(function (str, done) { done("internal error"); })
)(req, res, function (err) {
assert.equal(err, "internal error");
done = true;
});
assert.equal(done, true);
});
}); |
define(['ko', 'text!app/components/borat-flag/template.html'], function (ko, htmlString) {
function BoratFlag(model) {
var self = this;
};
return {
viewModel: BoratFlag,
template: htmlString
};
}); |
/* global define */
define([
'backbone',
'behaviors/pagination-behavior',
'templates/pagination-template'
], function (Backbone) {
'use strict';
var PaginationView = Backbone.Marionette.ItemView.extend({
template: 'pagination-template.dust',
tagName: 'div id="paginated"',
ui: {
pageNumber: '.number > a',
previousPage: '.previous > a',
nextPage: '.next > a'
},
behaviors: {
Pagination: { activeClass: 'active', disabledClass: 'disabled' }
},
initialize: function (options) {
options = options || {};
this.pages = options.pages || 1;
this.page = options.page || 1;
this.hasNumberPicker = options.include;
},
serializeData: function () {
return {
page: this.page,
pages: this.pages,
isPreviousDisabled: this.page === 1,
isNextDisabled: this.page === this.pages,
hasNumberPicker: this.hasNumberPicker
};
}
});
return PaginationView;
});
|
'use strict';
var express = require('express');
var app = express();
var path = require('path');
var cron = require('cron');
var shjs = require('shelljs');
var windData = require('./public/data/wind.json');
app.set('port', process.env.PORT || 8080);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function (req, res) {
res.sendFile('./index.html');
});
app.get('/current-wind', function (req, res) {
res.json(windData);
});
// 2AM get fs.2015042906
var cronJob1 = cron.job('00 00 06 * * 1-7', function () {
// perform operation e.g. GET request http.get() etc.
shjs.exec('bash ./scripts/getWind.sh 06');
windData = require('./public/data/wind.json');
console.info('cron job completed', new Date());
});
// 8AM get fs.2015042912
var cronJob2 = cron.job('00 00 12 * * 1-7', function () {
// perform operation e.g. GET request http.get() etc.
shjs.exec('bash ./scripts/getWind.sh 12');
windData = require('./public/data/wind.json');
console.info('cron job completed', new Date());
});
// 2PM get fs.2015042914
var cronJob3 = cron.job('00 00 18 * * 1-7', function () {
// perform operation e.g. GET request http.get() etc.
shjs.exec('bash ./scripts/getWind.sh 18');
windData = require('./public/data/wind.json');
console.info('cron job completed', new Date());
});
// 8PM get fs.2015042900
var cronJob4 = cron.job('00 00 00 * * 1-7', function () {
// perform operation e.g. GET request http.get() etc.
shjs.exec('bash ./scripts/getWind.sh 00');
windData = require('./public/data/wind.json');
console.info('cron job completed', new Date());
});
cronJob1.start();
cronJob2.start();
cronJob3.start();
cronJob4.start();
var server = app.listen(process.env.PORT || 8080, function () {
console.log('Listening on port %d', server.address().port);
}); |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var sd;
sd = require('sharify').data;
$(function() {
return $('body').append("<br><br>your email from the client-side!<br> " + sd.CURRENT_USER.email);
});
},{"sharify":2}],2:[function(require,module,exports){
// Middleware that injects the shared data and sharify script
module.exports = function(req, res, next) {
// Clone the "constant" sharify data for the request so
// request-level data isn't shared across the server potentially
// exposing sensitive data.
var data = {};
for(var key in module.exports.data) {
data[key] = module.exports.data[key];
};
// Inject a sharify object into locals for `= sharify.data` and `= sharify.script()`
res.locals.sharify = {
data: data,
script: function() {
return '<script type="text/javascript">' +
'window.__sharifyData = ' +
//There are tricky rules about safely embedding JSON within HTML
//see http://stackoverflow.com/a/4180424/266795
JSON.stringify(data)
.replace(/</g, '\\u003c')
.replace(/-->/g, '--\\>')
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029') +
';</script>';
}
};
// Alias the sharify short-hand for convience
res.locals.sd = res.locals.sharify.data;
next();
};
// The shared hash of data
module.exports.data = {};
// When required on the client via browserify, run this snippet that reads the
// sharify.script data and injects it into this module.
var bootstrapOnClient = module.exports.bootstrapOnClient = function() {
if (typeof window != 'undefined' && window.__sharifyData) {
module.exports.data = window.__sharifyData;
// Conveniently expose globals so client-side templates can access
// the `sd` and `sharify.data` just like the server.
if (!window.sharify) window.sharify = module.exports;
if (!window.sd) window.sd = window.__sharifyData;
}
};
bootstrapOnClient();
},{}]},{},[1]);
|
import React from "react";
import PACKAGE_API from "../../../../constants/packages";
import ActiveLink from "../../../links/ActiveLink";
import Container from "./Container";
import DropdownMenu from "./DropdownMenu";
import usePrefetch from "./usePrefetch";
let GroupPackages = ({ packages }) => (
<ul>
{packages.map(p => (
<li key={p.name}>
<ActiveLink
name="Package"
params={{ package: p.name, version: p.latest }}
activeClassName="font-bold"
>
{p.name}
</ActiveLink>
</li>
))}
</ul>
);
let groups = PACKAGE_API.versioned("v2");
let pkgs = PACKAGE_API.all().map(pkg => ({
name: "Package",
params: {
package: pkg.name,
version: pkg.latest
}
}));
let PackageLinks = ({ hidden }) => {
usePrefetch(pkgs, !hidden);
return (
<Container hidden={hidden}>
{Object.keys(groups).map(title => (
<li key={title}>
<DropdownMenu>
<h3>{title}</h3>
<GroupPackages packages={groups[title]} />
</DropdownMenu>
</li>
))}
</Container>
);
};
export default React.memo(PackageLinks);
|
// @flow
/* eslint-env mocha */
import assert from 'power-assert'
import plugins from './plugins'
import type {Rec} from './plugins'
import getAtom from '../getAtom'
plugins.forEach(([name, atmover]: Rec) => {
describe(`${name} get atom`, () => {
it('from constructed', () => {
class A {}
const v = atmover.value({a: 1})
const a = atmover.construct(A, [v])
const val = a.get()
assert(typeof getAtom(val) === 'object')
})
it('from factory', () => {
function A() {
return {}
}
const a = atmover.factory(A)
const val = a.get()
assert(typeof getAtom(val) === 'object')
})
it('from value', () => {
const a = atmover.value({a: 1})
const val = a.get()
assert(typeof getAtom(val) === 'object')
})
it('from value, after set', () => {
const a = atmover.value({a: 1})
const atom = getAtom(a.get())
a.set({a: 2})
assert(getAtom(a.get()) === atom)
})
it('from value after update', () => {
const a = atmover.value({a: 1})
a.get()
a.set({a: 2})
const val = a.get()
assert(typeof getAtom(val) === 'object')
})
})
})
|
import Vue from 'vue';
import VueResource from 'vue-resource';
Vue.use(VueResource);
var data = {
message: null,
list: null
};
new Vue({
el: "#app",
data: data,
methods: {
addListItem() {
this.list.push(this.message);
}
},
created: function(){
this.$http.get('data.json').then(responce => {
this.message = responce.body.message;
this.list = responce.body.list;
}, responce => {
// error
alert(responce.statusText);
});
}
});
|
(function(){
var Roles = function() {
if ($('#controller-roles').length > 0) {
this.init();
}
};
Roles.prototype.init = function() {
this.bindRemovePermissions();
this.bindAddPermission();
this.bindRemoveRole();
this.bindAddRole();
};
/**
* Bind Delete button action
*/
Roles.prototype.bindRemovePermissions = function() {
var self = this;
$('.js-role-permissions').on('click', '.js-remove-role-permission', function(e) {
e.preventDefault();
var $this = $(this),
permissionId = $this.data('permission-id'),
roleId = $this.data('role-id');
$.ajax({
data: {
role_id: roleId,
permission_id: permissionId
},
type: 'DELETE',
url: '/remove_permission_from_role',
success: self.onRemovePermissionSuccess,
error : self.onRemovePermissionFailure
});
});
};
/**
* Bind Add Permission Action
*/
Roles.prototype.bindAddPermission = function() {
var self = this;
$('.js-add-new-permission').on('click', function() {
var $this = $(this),
permissionId = $('.js-add-permission-select').val(),
roleId = $('.js-role-id').val();
$.ajax({
data: {
role_id: roleId,
permission_id: permissionId
},
dataType: 'json',
type: 'POST',
url: '/add_permission_to_role',
success: self.onAddPermissionSuccess,
error : self.onAddPermissionFailure
});
});
};
/**
* Bind Action for when User Clicks the Remove Role Button
*/
Roles.prototype.bindRemoveRole = function() {
var self = this;
$('.js-role-profiles').on('click', '.js-remove-role-profile', function(e) {
e.preventDefault();
var $this = $(this),
profileId = $this.data('profile-id'),
roleId = $this.data('role-id');
// send ajax call to remove profile
$.ajax({
data: {
role_id: roleId,
profile_id: profileId
},
dataType: 'json',
type: 'DELETE',
url: '/remove_profile_from_role',
success: self.onRemoveProfileSuccess,
error : self.onRemoveProfileFailure
});
});
};
Roles.prototype.bindAddRole = function() {
var self = this;
$('.js-add-role-profile').on('click', function() {
var $this = $(this),
profileId = $('.js-add-profile-select').val(),
roleId = $('.js-role-id').val();
// send ajax call to remove profile
$.ajax({
data: {
role_id: roleId,
profile_id: profileId
},
dataType: 'json',
type: 'POST',
url: '/add_profile_to_role',
success: self.onAddProfileSuccess,
error : self.onAddProfileFailure
});
});
};
/**
* Action when a Permission remove ajax call
* returns success from server
*/
Roles.prototype.onRemovePermissionSuccess = function(data) {
if (data && data.success) {
// remove the role from the view
$('.js-role-permission-' + data.role_id + '-' + data.permission_id).closest('.js-role-permission-item').slideUp();
} else {
this.onRemovePermissionFailure(data);
}
};
Roles.prototype.onRemovePermissionFailure = function(data) {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Removing Permission!'});
};
Roles.prototype.onAddPermissionSuccess =function(data) {
if (data && data.success) {
$.toaster({ priority : 'success', title : 'Success!', message : 'Permission Added!!'});
$('.js-role-permissions').append(data.html);
} else {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Adding Permission ' + data.message});
}
};
Roles.prototype.onAddPermissionFailure = function(data) {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Adding Permission ' + data.message});
};
Roles.prototype.onRemoveProfileSuccess = function(data) {
if (data && data.success) {
$('.js-role-profile-' + data.role_id + '-' + data.profile_id).closest('.js-role-profile-item').slideUp();
} else {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Adding Permission ' + data.message});
}
};
Roles.prototype.onRemoveProfileFailure = function(data) {
// show toast notifcation on failure
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Removing Profile: ' + data.message});
};
Roles.prototype.onAddProfileSuccess = function(data) {
if (data && data.success) {
$.toaster({ priority : 'success', title : 'Success!', message : 'New Profile Added!!'});
$('.js-role-profiles').append(data.view);
} else {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Adding Profile: ' + data.message});
}
};
Roles.prototype.onAddProfileFailure = function(data) {
$.toaster({ priority : 'danger', title : 'Error!', message : 'Issue Adding Profile: ' + data.message});
};
new Roles();
}());
|
"use strict";
const should = require("should");
const ClientSecureChannelLayer = require("..").ClientSecureChannelLayer;
const ServerSecureChannelLayer = require("..").ServerSecureChannelLayer;
const describe = require("node-opcua-leak-detector").describeWithLeakDetector;
describe("Testing ClientSecureChannel 1", function () {
this.timeout(Math.max(this._timeout, 100000));
const options = {
connectionStrategy: {
maxRetry: 1,
initialDelay:1,
maxDelay: 2,
randomisationFactor: 0.1
}
};
it("should not receive a close event with an error when attempting to connect to a non existent server", function (done) {
const secureChannel = new ClientSecureChannelLayer(options);
let client_has_received_close_event = 0;
secureChannel.on("close", function (err) {
should.not.exist(err);
client_has_received_close_event += 1;
});
secureChannel.create("opc.tcp://no_server_at_this_address.com:1234/UA/Sample", function (err) {
should(err).be.instanceOf(Error);
err.message.should.match(/getaddrinfo ENOTFOUND/);
client_has_received_close_event.should.eql(0);
setTimeout(done, 200);
});
});
it("should not receive a close event with an error when attempting to connect to a valid server on a invalid port", function (done) {
const secureChannel = new ClientSecureChannelLayer(options);
let client_has_received_close_event = 0;
secureChannel.on("close", function (err) {
should.not.exist(err);
client_has_received_close_event += 1;
});
secureChannel.create("opc.tcp://localhost:8888/UA/Sample", function (err) {
should(err).be.instanceOf(Error);
err.message.should.match(/connect ECONNREFUSED/);
client_has_received_close_event.should.eql(0);
setTimeout(done, 200);
});
});
});
function startServer(holder,callback) {
const net = require("net");
const server_socket = new net.Server();
holder.server_socket = server_socket;
//xx console.log(" max connection = ", server_socket.maxConnections);
server_socket.listen(1234);
server_socket.on("connection", function on_connection(socket) {
const serverChannel = new ServerSecureChannelLayer({});
holder.serverChannel = serverChannel;
serverChannel.timeout = 10050;
serverChannel.init(socket, function () {
//xx console.log(" server channel is initialised");
});
});
callback();
}
function simulate_server_abrupt_shutdown(holder) {
if (holder.serverChannel && holder.serverChannel.transport._socket) {
holder.serverChannel.transport._socket.end();
}
}
function stopServer(holder,callback) {
simulate_server_abrupt_shutdown(holder);
holder.server_socket.close(callback);
holder.serverChannel = null;
holder.server_socket = null;
}
describe("Testing ClientSecureChannel 2", function () {
beforeEach(function (done) {
startServer(this,done);
});
afterEach(function (done) {
stopServer(this,done);
});
it("should establish a client secure channel ", function (done) {
const secureChannel = new ClientSecureChannelLayer({});
secureChannel.protocolVersion.should.equal(0);
secureChannel.on_transaction_completed = function (transaction_stat) {
should.exist(transaction_stat.request);
should.exist(transaction_stat.response);
// xx console.log(transaction_stat);
};
secureChannel.on("close", function (err) {
should(!err).be.eql(true, "expecting no error here, as secure channel has been closed normally");
//xx console.log("secure channel has ended", err);
if (err) {
//xx console.log(" the connection was closed by an external cause such as server shutdown");
}
});
secureChannel.create("opc.tcp://localhost:1234/UA/Sample", function (err) {
should(!err).be.eql(true, "connection expected to succeed");
secureChannel.close(function () {
done();
});
});
});
});
describe("Testing ClientSecureChannel with BackOff reconnection strategy", function () {
this.timeout(Math.max(this._timeout, 100000));
it("WW2-a connectionStrategy: should retry many times and fail eventually ",function(done) {
const options = {
connectionStrategy: {
maxRetry: 3,
initialDelay:10,
maxDelay: 20,
randomisationFactor: 0.1,
}
};
const secureChannel = new ClientSecureChannelLayer(options);
const endpoint = "opc.tcp://localhost:1234/UA/Sample";
let nbRetry =0;
secureChannel.on("backoff",function(number,delay){
console.log(number + " " + delay + "ms");
nbRetry = number+1;
});
secureChannel.create(endpoint,function(err){
nbRetry.should.equal(options.connectionStrategy.maxRetry );
should.exist(err, "expecting an error here");
done();
});
});
// waiting for https://github.com/MathieuTurcotte/node-backoff/issues/15 to be fixed
it("WW2-b should be possible to interrupt the retry process ",function(done) {
const options = {
connectionStrategy: {
maxRetry: 3000,
initialDelay: 10,
maxDelay: 20,
randomisationFactor: 0
}
};
const secureChannel = new ClientSecureChannelLayer(options);
const endpoint = "opc.tcp://localhost:1234/UA/Sample";
let nbRetry =0;
secureChannel.on("backoff",function(number,delay){
console.log(number + " " + delay + "ms");
nbRetry = number+1;
if (number === 2) {
console.log("Let's abort the connection now");
secureChannel.abortConnection(function() {});
}
});
secureChannel.create(endpoint,function(err){
nbRetry.should.not.equal(options.connectionStrategy.maxRetry);
nbRetry.should.be.greaterThan(2);
nbRetry.should.be.lessThan(4);
should.exist(err,"expecting an error here");
console.log("secureChannel.create failed with message ",err.message);
secureChannel.close(function() {
setTimeout(done,100);
});
});
});
const test = this;
it("WW2-c secureChannel that starts before the server is up and running should eventually connect without error",function(done) {
const options = {
connectionStrategy: {
maxRetry: 3000,
initialDelay: 10,
maxDelay: 2000,
randomisationFactor: 0
}
};
const secureChannel = new ClientSecureChannelLayer(options);
const endpoint = "opc.tcp://localhost:1234/UA/Sample";
let nbRetry =0;
secureChannel.on("backoff",function(number,delay){
console.log(number + " " + delay + "ms");
nbRetry = number+1;
});
//
secureChannel.create(endpoint,function(err){
should(!err).be.eql(true, "expecting NO error here");
setTimeout(function() {
stopServer(test,function() {
secureChannel.close(function() {
done();
});
});
},1000);
});
setTimeout(function(){
// start the server with a delay
startServer(test,function(){
console.log("Server finally started !");
});
},5000);
});
});
|
import React, { Component } from 'react';
import { StyleSheet, Text, View, Platform, ListView, Image, Dimensions, } from 'react-native';
import styles from '../../../../app/components/Styles/shared';
import layoutStyles from '../../../../app/components/Styles/layout';
import Icons from '../../../../app/components/Icons';
import LoadingView from '../../../../app/components/LoadingIndicator/LoadingView';
import { Button, } from 'react-native-elements';
import constants from '../../constants';
import moment from 'moment';
import numeral from 'numeral';
import Table from '../../../../app/components/Table';
import { request, } from '../../../../app/util/request';
function getBlankHeader() {
return {
identification: {},
contact: {},
credit_bureau: {},
self_reported: {},
};
}
function getRenderRowData(data) {
return {
columns: [{
style: {
width:200,
},
heading: 'GUID',
label: data.identification.guid,
}, {
style: {
width: 200,
},
heading: 'Date',
label: moment(data.identification.application_submission_date).format('MM/DD/YYY | hh:mm:ssa'),
}, {
style: {
width: 300,
},
heading: 'Email',
label: data.contact.email,
}, {
style: {
width: 90,
},
heading: 'Income',
label: numeral(data.self_reported.annual_income).format('$0,0[.]00') || 'null',
}, {
style: {
width: 45,
},
heading: 'FICO',
label: data.credit_bureau.fico_score || 'null',
}],
action: {
icon: {
name:'ios-arrow-forward',
},
},
image: {
uri: 'https://facebook.github.io/react/img/logo_og.png',
},
};
}
class Applications extends Component {
constructor(props){
super(props);
this.state = {
applicationDataError: false,
applicationDataLoaded: false,
applicationData: {
applicationpages: 1,
applications: [ { title: 'title', }],
applicationscount: 1,
},
};
}
componentDidMount() {
this.getPipelineIndex();
}
// componentWillMount() {
// console.log('componentWillMount APPPLICATIONS mounted')
// }
// componentWillUpdate() {
// console.log('componentWillUpdate APPPLICATIONS mounted')
// }
getPipelineIndex() {
request(constants.pipelines.all.BASE_URL+constants.pipelines.applications.GET_INDEX, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Access-Token': this.props.user.jwt_token,
},
})
.then(responseData => {
this.setState({
applicationDataError: false,
applicationDataLoaded: true,
applicationData: {
applicationpages: responseData.applicationpages,
applications: responseData.applications,
applicationscount: responseData.applicationscount,
},
});
})
.catch(error => {
this.setState({
applicationDataError: error,
applicationDataLoaded: true,
});
});
}
// componentWillReceiveProps(nextProps) {
// console.log('componentWillReceiveProps APPPLICATIONS mounted')
// this.getPipelineIndex();
// }
render() {
let loadingView = (<LoadingView/>);
let loadedDataView = (
<Table
name="pasdata-applications-table"
pages={this.state.applicationData.applicationpages}
rows={this.state.applicationData.applications}
totalcount={this.state.applicationData.applicationscount}
getBlankHeader={getBlankHeader}
getRenderRowData={getRenderRowData}
{...this.props}
>
</Table>
);
let errorView = (
<View style={styles.container}>
<Text style={styles.welcome}>ERROR</Text>
</View>
);
if (this.state.applicationDataLoaded) {
if (this.state.applicationDataError) {
return errorView;
} else {
return loadedDataView;
}
} else {
return loadingView;
}
}
}
export default Applications; |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/* -*- js2-basic-offset: 4 -*- */
var husl = require('husl');
var codex = document.getElementById('codex');
var visCan = document.getElementById('art');
var visCtx = visCan.getContext('2d');
var hidCan = document.getElementById('hidden');
var hidCtx = hidCan.getContext('2d');
var state = {
world: [],
plants: {}
};
var spores = [];
var selected = "";
var xViewport = 0;
function worldWidth() {
if (worldHeight() == 0) return 0;
return state.world[0].length;
}
function worldHeight() {
return state.world.length;
}
var colorMap = [
husl.toHex(30, 50, 50), //dirt
husl.toHex(210, 50, 50), //sky
husl.toHex(160, 70, 70), //plant default
husl.toHex(344, 70, 70) //spore
];
var firstFrame = true;
// Render into the hidden canvas
function render() {
hidCtx.fillStyle = colorMap[0];
hidCtx.fillRect(0, 0, hidCan.width, hidCan.height);
for (var y = 0; y < state.world.length; y++) {
for (var x = 0; x < state.world[y].length; x++) {
drawTile(x, y, state.world[y][x]);
}
}
// Draw the spores
for (var s = 0; s < spores.length; s++) {
drawTile(spores[s]['location']['x'], spores[s]['location']['y'], {
tileType: 3,
plant: spores[s]['plantId']
});
// console.log(s['plantId']);
}
display();
}
function display() {
visCtx.fillStyle = colorMap[0];
visCtx.fillRect(0, 0, visCan.width, visCan.height);
visCtx.drawImage(hidCan, xViewport, 0);
visCtx.drawImage(hidCan, xViewport - worldWidth() * scale, 0);
visCtx.drawImage(hidCan, xViewport + worldWidth() * scale, 0);
visCtx.drawImage(hidCan, xViewport + worldWidth() * 2 * scale, 0);
}
function applyDelta(delta) {
delta.tileDiff.forEach(function(diff) {
state.world[diff.loc.y][diff.loc.x] = diff.tile;
});
Object.keys(delta.newPlants).forEach(function(key) {
state.plants[key] = delta.newPlants[key];
});
delta.removedPlants.forEach(function(key) {
delete state.plants[key];
});
spores = delta['spores'];
}
function drawTile(x, y, tile) {
if (tile['tileType'] == 0) {
return;
}
if (tile['tileType'] == 2) {
hidCtx.fillStyle = husl.toHex(state['plants'][tile['plant']['plantId']]['color'], 70, 70);
if (tile['plant']['plantId'] === selected) {
hidCtx.fillStyle = '#fff';
}
} else if (tile['tileType'] == 3) {
// console.log(tile['plantId']);
hidCtx.fillStyle = husl.toHex((state['plants'][tile['plant']]['color']+90)%360, 65, 75);
} else {
hidCtx.fillStyle = colorMap[tile['tileType']];
}
// XXX Do we want to do this without scaling, and scale when we copy to visctx?
hidCtx.fillRect(x * scale, y * scale, scale, scale);
}
var ws;
if (inEditMode) {
ws = new WebSocket("ws://localhost:4444/local");
} else {
ws = new WebSocket("ws://localhost:4444/global");
}
ws.onmessage = function(evt) {
console.log("EVENT!");
var reader = new FileReader();
reader.addEventListener("loadend", function() {
var json = JSON.parse(reader.result);
if (firstFrame) {
state = json;
onResize(); // We may have changed scale, so pretend we resized
render(); // Render the screen
firstFrame = false;
updateCodex();
} else {
applyDelta(json);
updateCodex();
render();
}
});
reader.readAsText(evt.data);
};
ws.onopen = function() {
console.log("Connection established");
};
ws.onclose = function() {
if (inEditMode) {
document.querySelector('#docs > iframe').contentDocument.body.innerHTML = "<h1>disconnected from server...<small style='font-size: 50%; vertical-align: top;'>(sorry)</small></h1>";
} else {
document.getElementById('logo').innerHTML = "disconnected from server...<small style='font-size: 50%; vertical-align: top;'>(sorry)</small>";
}
};
window.onbeforeunload = function() {
ws.onclose = function() {}; // disable onclose handler first
ws.close();
};
function onResize() {
visCtx = visCan.getContext('2d');
hidCtx = hidCan.getContext('2d');
if (hidCan.width != worldWidth() * scale) {
hidCan.width = worldWidth() * scale;
hidCan.height = worldHeight() * scale;
}
visCan.width = window.innerWidth;
visCan.height = worldHeight() * scale;
runningResize = false;
display();
}
var runningResize = false;
window.addEventListener("resize", function(e) {
if (runningResize) {
return;
}
runningResize = true;
requestAnimationFrame(onResize);
});
var dir = 1;
var lastX = -1;
visCan.addEventListener('mousedown', function(e) {
lastX = e.clientX;
dir = 0;
});
visCan.addEventListener('mousemove', function(e) {
if (lastX == -1) {
return;
}
xViewport -= lastX - e.clientX;
if (lastX - e.clientX < 0) {
dir = 1;
} else if (lastX - e.clientX > 0) {
dir = -1;
}
xViewport = xViewport % (worldWidth() * scale);
lastX = e.clientX;
display();
});
window.setInterval(function() {
if (lastX == -1) {
requestAnimationFrame(function() {
if (worldWidth() == 0) return;
xViewport += dir;
xViewport = xViewport % (worldWidth() * scale);
display();
});
}
}, 100);
visCan.addEventListener('mouseup', function(e) {
lastX = -1;
});
function updateCodex() {
if (inEditMode) {
return;
}
var codexString = "";
var key = 0;
codex.innerHTML = "";
Object.keys(state.plants).forEach(function(key) {
var editBtn = document.createElement('button');
editBtn.setAttribute('class', 'edit-btn');
editBtn.setAttribute('id', 'edit-' + key);
editBtn.setAttribute('style', 'background-color: ' + husl.toHex(state.plants[key].color, 50, 50));
editBtn.innerHTML = '<i class="fa fa-code-fork"></i>'; // XXX FIXME pen?
editBtn.addEventListener("mouseover", function(event) {
selected = key;
}, true);
editBtn.addEventListener("mouseout", function(event) {
selected = "";
}, true);
editBtn.addEventListener("click", function(event) {
sessionStorage.setItem('code', state.plants[key].source);
document.location = '/edit';
}, true);
codex.appendChild(editBtn);
});
}
if (inEditMode) {
document.getElementById('test').addEventListener('click', function(e) {
e.preventDefault();
var v = JSON.stringify({
kind: "+species+spawn",
color: Math.floor(Math.random() * 360),
code: editor.getValue(),
ground: true
});
console.log(v);
ws.send(v);
});
document.getElementById('publish').addEventListener('click', function(e) {
e.preventDefault();
var globws = new WebSocket("ws://localhost:4444/global");
globws.onopen = function() {
var v = JSON.stringify({
kind: "+species+spawn",
color: Math.floor(Math.random() * 360),
code: editor.getValue(),
ground: false
});
console.log(v);
globws.send(v);
globws.close();
setTimeout(function() {
document.location = '/';
}, 0);
};
});
document.getElementById('clear').addEventListener('click', function(e) {
e.preventDefault();
var v = JSON.stringify({
kind: "+clear"
});
console.log(v);
ws.send(v);
});
}
},{"husl":2}],2:[function(require,module,exports){
// Generated by CoffeeScript 1.9.3
(function() {
var L_to_Y, Y_to_L, conv, distanceFromPole, dotProduct, epsilon, fromLinear, getBounds, intersectLineLine, kappa, lengthOfRayUntilIntersect, m, m_inv, maxChromaForLH, maxSafeChromaForL, refU, refV, root, toLinear;
m = {
R: [3.2409699419045214, -1.5373831775700935, -0.49861076029300328],
G: [-0.96924363628087983, 1.8759675015077207, 0.041555057407175613],
B: [0.055630079696993609, -0.20397695888897657, 1.0569715142428786]
};
m_inv = {
X: [0.41239079926595948, 0.35758433938387796, 0.18048078840183429],
Y: [0.21263900587151036, 0.71516867876775593, 0.072192315360733715],
Z: [0.019330818715591851, 0.11919477979462599, 0.95053215224966058]
};
refU = 0.19783000664283681;
refV = 0.468319994938791;
kappa = 903.2962962962963;
epsilon = 0.0088564516790356308;
getBounds = function(L) {
var bottom, channel, j, k, len1, len2, m1, m2, m3, ref, ref1, ref2, ret, sub1, sub2, t, top1, top2;
sub1 = Math.pow(L + 16, 3) / 1560896;
sub2 = sub1 > epsilon ? sub1 : L / kappa;
ret = [];
ref = ['R', 'G', 'B'];
for (j = 0, len1 = ref.length; j < len1; j++) {
channel = ref[j];
ref1 = m[channel], m1 = ref1[0], m2 = ref1[1], m3 = ref1[2];
ref2 = [0, 1];
for (k = 0, len2 = ref2.length; k < len2; k++) {
t = ref2[k];
top1 = (284517 * m1 - 94839 * m3) * sub2;
top2 = (838422 * m3 + 769860 * m2 + 731718 * m1) * L * sub2 - 769860 * t * L;
bottom = (632260 * m3 - 126452 * m2) * sub2 + 126452 * t;
ret.push([top1 / bottom, top2 / bottom]);
}
}
return ret;
};
intersectLineLine = function(line1, line2) {
return (line1[1] - line2[1]) / (line2[0] - line1[0]);
};
distanceFromPole = function(point) {
return Math.sqrt(Math.pow(point[0], 2) + Math.pow(point[1], 2));
};
lengthOfRayUntilIntersect = function(theta, line) {
var b1, len, m1;
m1 = line[0], b1 = line[1];
len = b1 / (Math.sin(theta) - m1 * Math.cos(theta));
if (len < 0) {
return null;
}
return len;
};
maxSafeChromaForL = function(L) {
var b1, j, len1, lengths, m1, ref, ref1, x;
lengths = [];
ref = getBounds(L);
for (j = 0, len1 = ref.length; j < len1; j++) {
ref1 = ref[j], m1 = ref1[0], b1 = ref1[1];
x = intersectLineLine([m1, b1], [-1 / m1, 0]);
lengths.push(distanceFromPole([x, b1 + x * m1]));
}
return Math.min.apply(Math, lengths);
};
maxChromaForLH = function(L, H) {
var hrad, j, l, len1, lengths, line, ref;
hrad = H / 360 * Math.PI * 2;
lengths = [];
ref = getBounds(L);
for (j = 0, len1 = ref.length; j < len1; j++) {
line = ref[j];
l = lengthOfRayUntilIntersect(hrad, line);
if (l !== null) {
lengths.push(l);
}
}
return Math.min.apply(Math, lengths);
};
dotProduct = function(a, b) {
var i, j, ref, ret;
ret = 0;
for (i = j = 0, ref = a.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
ret += a[i] * b[i];
}
return ret;
};
fromLinear = function(c) {
if (c <= 0.0031308) {
return 12.92 * c;
} else {
return 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
}
};
toLinear = function(c) {
var a;
a = 0.055;
if (c > 0.04045) {
return Math.pow((c + a) / (1 + a), 2.4);
} else {
return c / 12.92;
}
};
conv = {
'xyz': {},
'luv': {},
'lch': {},
'husl': {},
'huslp': {},
'rgb': {},
'hex': {}
};
conv.xyz.rgb = function(tuple) {
var B, G, R;
R = fromLinear(dotProduct(m.R, tuple));
G = fromLinear(dotProduct(m.G, tuple));
B = fromLinear(dotProduct(m.B, tuple));
return [R, G, B];
};
conv.rgb.xyz = function(tuple) {
var B, G, R, X, Y, Z, rgbl;
R = tuple[0], G = tuple[1], B = tuple[2];
rgbl = [toLinear(R), toLinear(G), toLinear(B)];
X = dotProduct(m_inv.X, rgbl);
Y = dotProduct(m_inv.Y, rgbl);
Z = dotProduct(m_inv.Z, rgbl);
return [X, Y, Z];
};
Y_to_L = function(Y) {
if (Y <= epsilon) {
return Y * kappa;
} else {
return 116 * Math.pow(Y, 1 / 3) - 16;
}
};
L_to_Y = function(L) {
if (L <= 8) {
return L / kappa;
} else {
return Math.pow((L + 16) / 116, 3);
}
};
conv.xyz.luv = function(tuple) {
var L, U, V, X, Y, Z, varU, varV;
X = tuple[0], Y = tuple[1], Z = tuple[2];
if (Y === 0) {
return [0, 0, 0];
}
L = Y_to_L(Y);
varU = (4 * X) / (X + (15 * Y) + (3 * Z));
varV = (9 * Y) / (X + (15 * Y) + (3 * Z));
U = 13 * L * (varU - refU);
V = 13 * L * (varV - refV);
return [L, U, V];
};
conv.luv.xyz = function(tuple) {
var L, U, V, X, Y, Z, varU, varV;
L = tuple[0], U = tuple[1], V = tuple[2];
if (L === 0) {
return [0, 0, 0];
}
varU = U / (13 * L) + refU;
varV = V / (13 * L) + refV;
Y = L_to_Y(L);
X = 0 - (9 * Y * varU) / ((varU - 4) * varV - varU * varV);
Z = (9 * Y - (15 * varV * Y) - (varV * X)) / (3 * varV);
return [X, Y, Z];
};
conv.luv.lch = function(tuple) {
var C, H, Hrad, L, U, V;
L = tuple[0], U = tuple[1], V = tuple[2];
C = Math.sqrt(Math.pow(U, 2) + Math.pow(V, 2));
if (C < 0.00000001) {
H = 0;
} else {
Hrad = Math.atan2(V, U);
H = Hrad * 360 / 2 / Math.PI;
if (H < 0) {
H = 360 + H;
}
}
return [L, C, H];
};
conv.lch.luv = function(tuple) {
var C, H, Hrad, L, U, V;
L = tuple[0], C = tuple[1], H = tuple[2];
Hrad = H / 360 * 2 * Math.PI;
U = Math.cos(Hrad) * C;
V = Math.sin(Hrad) * C;
return [L, U, V];
};
conv.husl.lch = function(tuple) {
var C, H, L, S, max;
H = tuple[0], S = tuple[1], L = tuple[2];
if (L > 99.9999999 || L < 0.00000001) {
C = 0;
} else {
max = maxChromaForLH(L, H);
C = max / 100 * S;
}
return [L, C, H];
};
conv.lch.husl = function(tuple) {
var C, H, L, S, max;
L = tuple[0], C = tuple[1], H = tuple[2];
if (L > 99.9999999 || L < 0.00000001) {
S = 0;
} else {
max = maxChromaForLH(L, H);
S = C / max * 100;
}
return [H, S, L];
};
conv.huslp.lch = function(tuple) {
var C, H, L, S, max;
H = tuple[0], S = tuple[1], L = tuple[2];
if (L > 99.9999999 || L < 0.00000001) {
C = 0;
} else {
max = maxSafeChromaForL(L);
C = max / 100 * S;
}
return [L, C, H];
};
conv.lch.huslp = function(tuple) {
var C, H, L, S, max;
L = tuple[0], C = tuple[1], H = tuple[2];
if (L > 99.9999999 || L < 0.00000001) {
S = 0;
} else {
max = maxSafeChromaForL(L);
S = C / max * 100;
}
return [H, S, L];
};
conv.rgb.hex = function(tuple) {
var ch, hex, j, len1;
hex = "#";
for (j = 0, len1 = tuple.length; j < len1; j++) {
ch = tuple[j];
ch = Math.round(ch * 1e6) / 1e6;
if (ch < 0 || ch > 1) {
throw new Error("Illegal rgb value: " + ch);
}
ch = Math.round(ch * 255).toString(16);
if (ch.length === 1) {
ch = "0" + ch;
}
hex += ch;
}
return hex;
};
conv.hex.rgb = function(hex) {
var b, g, j, len1, n, r, ref, results;
if (hex.charAt(0) === "#") {
hex = hex.substring(1, 7);
}
r = hex.substring(0, 2);
g = hex.substring(2, 4);
b = hex.substring(4, 6);
ref = [r, g, b];
results = [];
for (j = 0, len1 = ref.length; j < len1; j++) {
n = ref[j];
results.push(parseInt(n, 16) / 255);
}
return results;
};
conv.lch.rgb = function(tuple) {
return conv.xyz.rgb(conv.luv.xyz(conv.lch.luv(tuple)));
};
conv.rgb.lch = function(tuple) {
return conv.luv.lch(conv.xyz.luv(conv.rgb.xyz(tuple)));
};
conv.husl.rgb = function(tuple) {
return conv.lch.rgb(conv.husl.lch(tuple));
};
conv.rgb.husl = function(tuple) {
return conv.lch.husl(conv.rgb.lch(tuple));
};
conv.huslp.rgb = function(tuple) {
return conv.lch.rgb(conv.huslp.lch(tuple));
};
conv.rgb.huslp = function(tuple) {
return conv.lch.huslp(conv.rgb.lch(tuple));
};
root = {};
root.fromRGB = function(R, G, B) {
return conv.rgb.husl([R, G, B]);
};
root.fromHex = function(hex) {
return conv.rgb.husl(conv.hex.rgb(hex));
};
root.toRGB = function(H, S, L) {
return conv.husl.rgb([H, S, L]);
};
root.toHex = function(H, S, L) {
return conv.rgb.hex(conv.husl.rgb([H, S, L]));
};
root.p = {};
root.p.toRGB = function(H, S, L) {
return conv.xyz.rgb(conv.luv.xyz(conv.lch.luv(conv.huslp.lch([H, S, L]))));
};
root.p.toHex = function(H, S, L) {
return conv.rgb.hex(conv.xyz.rgb(conv.luv.xyz(conv.lch.luv(conv.huslp.lch([H, S, L])))));
};
root.p.fromRGB = function(R, G, B) {
return conv.lch.huslp(conv.luv.lch(conv.xyz.luv(conv.rgb.xyz([R, G, B]))));
};
root.p.fromHex = function(hex) {
return conv.lch.huslp(conv.luv.lch(conv.xyz.luv(conv.rgb.xyz(conv.hex.rgb(hex)))));
};
root._conv = conv;
root._getBounds = getBounds;
root._maxChromaForLH = maxChromaForLH;
root._maxSafeChromaForL = maxSafeChromaForL;
if (!((typeof module !== "undefined" && module !== null) || (typeof jQuery !== "undefined" && jQuery !== null) || (typeof requirejs !== "undefined" && requirejs !== null))) {
this.HUSL = root;
}
if (typeof module !== "undefined" && module !== null) {
module.exports = root;
}
if (typeof jQuery !== "undefined" && jQuery !== null) {
jQuery.husl = root;
}
if ((typeof requirejs !== "undefined" && requirejs !== null) && (typeof define !== "undefined" && define !== null)) {
define(root);
}
}).call(this);
},{}]},{},[1]);
|
import { createStore, applyMiddleware } from 'redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import { AsyncStorage } from 'react-native'
import createLogger from 'redux-logger'
import rootReducer, { persistentStoreBlacklist } from '../Reducers/'
import Config from '../Config/DebugSettings'
import sagaMiddleware from 'redux-saga'
import sagas from '../Sagas/'
import R from 'ramda'
// the logger master switch
const USE_LOGGING = Config.reduxLogging
// silence these saga-based messages
const BLACKLIST = ['EFFECT_TRIGGERED', 'EFFECT_RESOLVED', 'EFFECT_REJECTED']
// creat the logger
const logger = createLogger({
predicate: (getState, { type }) => USE_LOGGING && R.not(R.contains(type, BLACKLIST))
})
// a function which can create our store and auto-persist the data
export default () => {
const store = createStore(
rootReducer,
applyMiddleware(
logger,
sagaMiddleware(...sagas)
),
(Config.reduxPersist) ? autoRehydrate() : null
)
if (Config.reduxPersist) {
persistStore(store, {
storage: AsyncStorage,
blacklist: persistentStoreBlacklist
})
}
return store
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="9" cy="13" r="1.25" /><path d="M17.5 10c.75 0 1.47-.09 2.17-.24.21.71.33 1.46.33 2.24 0 1.22-.28 2.37-.77 3.4l1.49 1.49C21.53 15.44 22 13.78 22 12c0-5.52-4.48-10-10-10-1.78 0-3.44.47-4.89 1.28l5.33 5.33c1.49.88 3.21 1.39 5.06 1.39zm-6.84-5.88c.43-.07.88-.12 1.34-.12 2.9 0 5.44 1.56 6.84 3.88-.43.07-.88.12-1.34.12-2.9 0-5.44-1.56-6.84-3.88zm-8.77-.4l2.19 2.19C2.78 7.6 2 9.71 2 12c0 5.52 4.48 10 10 10 2.29 0 4.4-.78 6.09-2.08l2.19 2.19 1.41-1.41L3.31 2.31 1.89 3.72zm14.77 14.77C15.35 19.44 13.74 20 12 20c-4.41 0-8-3.59-8-8 0-.05.01-.1 0-.14 1.39-.52 2.63-1.35 3.64-2.39l9.02 9.02zM6.23 8.06c-.53.55-1.14 1.03-1.81 1.41.26-.77.63-1.48 1.09-2.13l.72.72z" /></React.Fragment>
, 'FaceRetouchingOffOutlined');
|
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
//= require_tree ./jquery
//= require_tree ./layout
//= require_tree ./templ
|
import { connect } from 'react-redux';
import {
makeSelectFileInfoForUri,
makeSelectDownloadingForUri,
makeSelectLoadingForUri,
makeSelectClaimIsMine,
makeSelectClaimForUri,
makeSelectClaimWasPurchased,
makeSelectStreamingUrlForUri,
} from 'lbry-redux';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { doOpenModal, doAnalyticsView } from 'redux/actions/app';
import { doSetPlayingUri, doPlayUri } from 'redux/actions/content';
import FileDownloadLink from './view';
const select = (state, props) => ({
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
downloading: makeSelectDownloadingForUri(props.uri)(state),
loading: makeSelectLoadingForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
});
const perform = dispatch => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
pause: () => dispatch(doSetPlayingUri(null)),
download: uri => dispatch(doPlayUri(uri, false, true, () => dispatch(doAnalyticsView(uri)))),
});
export default connect(select, perform)(FileDownloadLink);
|
(function () {
'use strict';
angular
.module('split', [])
.factory('split', split);
/* @ngInject */
function split () {
return {
0: {
rose: 1,
white: 3,
red: 2
},
17: {
rose: 1,
white: 1,
red: 4
},
19: {
rose: 1,
white: 4,
red: 1
},
23: {
rose: 2,
white: 2,
red: 2
},
34: {
rose: 0,
white: 0,
red: 6
},
36: {
rose: 0,
white: 3,
red: 3
},
38: {
rose: 0,
white: 6,
red: 0
},
40: {
rose: 2,
white: 0,
red: 4
},
42: {
rose: 3,
white: 3,
red: 0
},
46: {
rose: 4,
white: 1,
red: 1
},
53: {
rose: 0,
white: 2,
red: 4
},
55: {
rose: 0,
white: 4,
red: 2
},
57: {
rose: 2,
white: 0,
red: 4
},
59: {
rose: 2,
white: 2,
red: 2
},
61: {
rose: 2,
white: 4,
red: 0
},
63: {
rose: 4,
white: 0,
red: 2
},
65: {
rose: 4,
white: 2,
red: 0
},
72: {
rose: 0,
white: 3,
red: 3
},
76: {
rose: 1,
white: 2,
red: 3
},
78: {
rose: 1,
white: 4,
red: 1
},
80: {
rose: 3,
white: 0,
red: 3
},
82: {
rose: 3,
white: 1,
red: 2
},
84: {
rose: 3,
white: 3,
red: 0
},
95: {
rose: 1,
white: 2,
red: 3
},
99: {
rose: 2,
white: 1,
red: 3
},
101: {
rose: 2,
white: 3,
red: 1
},
118: {
rose: 2,
white: 2,
red: 2
}
};
}
})(); |
(function(angular,JSON, undefined) {
"use strict";
var login = angular.module("login",[]);
login.controller("loginCtrl",["$http", "$scope", function($http,$scope){
$scope.logar = function(){
$http.post(Routing.generate("logar"),{cpf:$scope.cpf,senha:$scope.senha}).success(function(data){
if(data.success) {
window.location = Routing.generate("start");
} else {
alert("login ou senha errada");
}
});
}
}]);
})(angular); |
'use strict';
// this file is not automatically re-loaded during watched build because it's
// slow to do so. if you make changes, you should re-launch the build process.
// globally expose jQuery for other vendor scripts
window.jQuery = window.$ = require('../bower_components/jquery/dist/jquery.js');
// include all of bootstrap, or optionally choose specific components below.
require('../bower_components/bootstrap-sass/dist/js/bootstrap.js'); /*
require('../bower_components/bootstrap-sass/js/affix');
require('../bower_components/bootstrap-sass/js/alert');
require('../bower_components/bootstrap-sass/js/dropdown');
require('../bower_components/bootstrap-sass/js/tooltip');
require('../bower_components/bootstrap-sass/js/modal');
require('../bower_components/bootstrap-sass/js/transition');
require('../bower_components/bootstrap-sass/js/button');
require('../bower_components/bootstrap-sass/js/popover');
require('../bower_components/bootstrap-sass/js/carousel');
require('../bower_components/bootstrap-sass/js/scrollspy');
require('../bower_components/bootstrap-sass/js/collapse');
require('../bower_components/bootstrap-sass/js/tab'); */
|
var cli = require('../lib')
, nitrogen = require('nitrogen');
var passthrough = function(value) {
return function(callback) {
return callback(null, value);
};
};
// TODO: store away session details and just return those if email/password haven't been changed.
var startSession = function(callback) {
cli.service.getService(function(err, service) {
if (err) return callback(err);
cli.store.get('email', function(err, email) {
if (err) return callback(err);
cli.store.get('password', function(err, password) {
if (err) return callback(err);
var user = new nitrogen.User({
nickname: 'current',
email: email,
password: password
});
service.authenticate(user, callback);
});
});
});
};
module.exports = {
passthrough: passthrough,
startSession: startSession
}; |
#!/usr/bin/env node
var fs = require('fs')
var http = require('http')
var path = require('path')
var ecstatic = require('ecstatic')
var util = require('util')
var mime = require('mime')
var filename = process.argv[2] || '.'
var port = process.argv[3] || 12345
var realFilename = path.resolve(process.cwd(), filename)
var stat = fs.statSync(realFilename)
var app
if (stat.isFile()) {
var contentType = mime.getType(realFilename)
var contentDisposition = util.format('attachment; filename="%s"', path.basename(realFilename))
app = function(request, response) {
response.setHeader('content-disposition', contentDisposition)
response.setHeader('content-type', contentType)
fs.createReadStream(realFilename).pipe(response)
}
} else if (stat.isDirectory()) {
app = ecstatic({ root: realFilename })
} else {
throw new Error('unsupported ' + realFilename)
}
var server = http.createServer(app).listen(port, function(err) {
if (err) return console.error(err)
console.log('serving %s on http://localhost:%s', realFilename, port)
})
|
var blessed = require('../')
, screen;
var auto = true;
screen = blessed.screen({
dump: __dirname + '/logs/listbar.log',
autoPadding: auto
});
var box = blessed.box({
parent: screen,
top: 0,
right: 0,
width: 'shrink',
height: 'shrink',
content: '...'
});
var bar = blessed.listbar({
parent: screen,
bottom: 0,
left: 3,
right: 3,
height: auto ? 'shrink' : 3,
mouse: true,
keys: true,
autoCommandKeys: true,
border: {
type: 'line'
},
vi: true,
style: {
bg: 'green',
item: {
bg: 'red',
hover: {
bg: 'blue'
},
//focus: {
// bg: 'blue'
//}
},
selected: {
bg: 'blue'
}
},
commands: {
'one': {
keys: ['a'],
callback: function() {
box.setContent('Pressed one.');
screen.render();
}
},
'two': function() {
box.setContent('Pressed two.');
screen.render();
},
'three': function() {
box.setContent('Pressed three.');
screen.render();
},
'four': function() {
box.setContent('Pressed four.');
screen.render();
},
'five': function() {
box.setContent('Pressed five.');
screen.render();
},
'six': function() {
box.setContent('Pressed six.');
screen.render();
},
'seven': function() {
box.setContent('Pressed seven.');
screen.render();
},
'eight': function() {
box.setContent('Pressed eight.');
screen.render();
},
'nine': function() {
box.setContent('Pressed nine.');
screen.render();
},
'ten': function() {
box.setContent('Pressed ten.');
screen.render();
},
'eleven': function() {
box.setContent('Pressed eleven.');
screen.render();
},
'twelve': function() {
box.setContent('Pressed twelve.');
screen.render();
},
'thirteen': function() {
box.setContent('Pressed thirteen.');
screen.render();
},
'fourteen': function() {
box.setContent('Pressed fourteen.');
screen.render();
},
'fifteen': function() {
box.setContent('Pressed fifteen.');
screen.render();
}
}
});
bar.focus();
screen.key('q', function() {
return process.exit(0);
});
screen.render();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 9h-2V5h2v6zm0 4h-2v-2h2v2z" /></g>
, 'Announcement');
|
/* https://github.com/tlseabra */
function breakInHalf(input){
var top = [], length = input.length;
for(var i=0; i < Math.floor(length/2); i++){
top.push(input.shift());
}
return [top, input];
}
|
var utils = require('./utils');
// Get a reference to the global scope. We do this instead of using {global}
// in case someone decides to bundle this up and use it in the browser
var _global = (function() { return this; }).call();
//
// Install the Promise constructor into the global scope, if and only if a
// native promise constructor does not exist.
//
exports.install = function() {
if (! _global.Promise) {
_global.Promise = Promise;
}
};
//
// Remove global.Promise, but only if it is our version
//
exports.uninstall = function() {
if (_global.Promise && _global.Promise === Promise) {
_global.Promise = void(0);
delete _global.Promise;
}
};
//
// State constants
//
var PENDING = void(0);
var UNFULFILLED = 0;
var FULFILLED = 1;
var FAILED = 2;
//
// The Promise constructor
//
// @param {callback} the callback that defines the process to occur
//
var Promise = exports.Promise = function(callback) {
// Check that a function argument was given
if (typeof callback !== 'function') {
throw new TypeError('Promise constructor takes a function argument');
}
// Check that a new instance was created, and not just a function call was made
if (! (this instanceof Promise)) {
throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.');
}
var self = this;
// The queue of functions waiting for the promise to resolve/reject
utils.defineProperty(this, 'funcs', {
enumerable: false,
configurable: false,
writable: false,
value: [ ]
});
// The queue of functions waiting for the promise to resolve/reject
utils.defineProperty(this, 'value', {
enumerable: false,
configurable: true,
writable: false,
value: void(0)
});
// Call the function, passing in the resolve and reject functions
try {
callback(resolve, reject);
} catch (err) {
reject(err);
}
// The {resolve} callback given to the handler function
function resolve(value) {
resolvePromise(self, value);
}
// The {reject} callback given to the handler function
function reject(value) {
rejectPromise(self, value);
}
};
// --------------------------------------------------------
//
// Assigns handler function(s) for the resolve/reject events
//
// @param {onResolve} optional; a function called when the promise resolves
// @param {onReject} optional; a function called when the promise rejects
// @return Promise
//
Promise.prototype.then = function(onResolve, onReject) {
var self = this;
// Create the new promise that will be returned
var promise = new Promise(function( ) { });
// If the promise is already completed, call the callback immediately
if (this.state) {
setImmediate(function() {
invokeFunction(self, promise, (self.state === FULFILLED ? onResolve : onReject));
});
}
// Otherwise, add the functions to the list
else {
this.funcs.push(promise, onResolve, onReject);
}
return promise;
};
//
// Assigns a handler function for the reject event
//
// @param {onReject} a function called when the promise rejects
// @return Promise
//
Promise.prototype.catch = function(onReject) {
return this.then(null, onReject);
};
// --------------------------------------------------------
//
// Returns an immediately resolving promise which resolves with {value}. If {value} is
// a thenable, the new promise will instead follow the given thenable.
//
// @param {value} the value to resolve with
// @return Promise
//
Promise.resolve = function(value) {
try {
var then = utils.thenable(value);
} catch (err) {
return new Promise(autoResolve);
}
var callback = then
? function(resolve, reject) {
then.call(value, resolve, reject);
}
: autoResolve;
function autoResolve(resolve) {
resolve(value);
}
return new Promise(callback);
};
//
// Returns an immediately rejected promise
//
// @param {reason} the reason for the rejection
// @return Promise
//
Promise.reject = function(reason) {
return new Promise(function(resolve, reject) {
reject(reason);
});
};
//
// Returns a new promise which resolves/rejects based on an array of given promises
//
// @param {promises} the promises to handle
// @return Promise
//
Promise.all = function(promises) {
return new Promise(function(resolve, reject) {
if (! Array.isArray(promises)) {
resolve([ ]);
return;
}
var values = [ ];
var finished = false;
var remaining = promises.length;
promises.forEach(function(promise, index) {
var then = utils.thenable(promise);
if (! then) {
onResolve(promise);
return;
}
then.call(promise,
function onResolve(value) {
remaining--;
values[index] = value;
checkIfFinished();
},
function onReject(reason) {
finished = true;
reject(reason);
}
);
});
function checkIfFinished() {
if (! finished && ! remaining) {
finished = true;
resolve(values);
}
}
});
};
//
// Returns a new promise which resolve/rejects as soon as the first given promise resolves
// or rejects
//
// @param {promises} an array of promises
// @return Promise
//
Promise.race = function(promises) {
var promise = new Promise(function() { });
promises.forEach(function(childPromise) {
childPromise.then(
function(value) {
resolvePromise(promise, value);
},
function(value) {
rejectPromise(promise, value);
}
);
});
return promise;
};
// --------------------------------------------------------
//
// Determines how to properly resolve the promise
//
// @param {promise} the promise
// @param {value} the value to give the promise
// @return void
//
function resolvePromise(promise, value) {
if (! handleThenable(promise, value)) {
fulfillPromise(promise, value);
}
}
//
// When a promise resolves with another thenable, this function handles delegating control
// and passing around values
//
// @param {child} the child promise that values will be passed to
// @param {value} the thenable value from the previous promise
// @return boolean
//
function handleThenable(promise, value) {
var done, then;
// Attempt to get the `then` method from the thenable (if it is a thenable)
try {
if (! (then = utils.thenable(value))) {
return false;
}
} catch (err) {
rejectPromise(promise, err);
return true;
}
// Ensure that the promise did not attempt to fulfill with itself
if (promise === value) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return true;
}
try {
// Wait for the thenable to fulfill/reject before moving on
then.call(value,
function(subValue) {
if (! done) {
done = true;
// Once again look for circular promise resolution
if (value === subValue) {
rejectPromise(promise, new TypeError('Circular resolution of promises'));
return;
}
resolvePromise(promise, subValue);
}
},
function(subValue) {
if (! done) {
done = true;
rejectPromise(promise, subValue);
}
}
);
} catch (err) {
if (! done) {
done = true;
rejectPromise(promise, err);
}
}
return true;
}
//
// Fulfill the given promise
//
// @param {promise} the promise to resolve
// @param {value} the value of the promise
// @return void
//
function fulfillPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FULFILLED);
invokeFunctions(promise);
});
}
//
// Reject the given promise
//
// @param {promise} the promise to reject
// @param {value} the value of the promise
// @return void
//
function rejectPromise(promise, value) {
if (promise.state !== PENDING) {return;}
setValue(promise, value);
setState(promise, UNFULFILLED);
setImmediate(function() {
setState(promise, FAILED);
invokeFunctions(promise);
});
}
//
// Set the state of a promise
//
// @param {promise} the promise to modify
// @param {state} the new state
// @return void
//
function setState(promise, state) {
utils.defineProperty(promise, 'state', {
enumerable: false,
// According to the spec: If the state is UNFULFILLED (0), the state can be changed;
// If the state is FULFILLED (1) or FAILED (2), the state cannot be changed, and therefore we
// lock the property
configurable: (! state),
writable: false,
value: state
});
}
//
// Set the value of a promise
//
// @param {promise} the promise to modify
// @param {value} the value to store
// @return void
//
function setValue(promise, value) {
utils.defineProperty(promise, 'value', {
enumerable: false,
configurable: false,
writable: false,
value: value
});
}
//
// Invoke all existing functions queued up on the promise
//
// @param {promise} the promise to run functions for
// @return void
//
function invokeFunctions(promise) {
var funcs = promise.funcs;
for (var i = 0, c = funcs.length; i < c; i += 3) {
invokeFunction(promise, funcs[i], funcs[i + promise.state]);
}
// Empty out this list of functions as no one function will be called
// more than once, and we don't want to hold them in memory longer than needed
promise.funcs.length = 0;
}
//
// Invoke one specific function for the promise
//
// @param {promise} the promise the function belongs too (that .then was called on)
// @param {child} the promise return from the .then call; the next in line
// @param {func} the function to call
// @return void
//
function invokeFunction(promise, child, func) {
var value = promise.value;
var state = promise.state;
// If we have a function to run, run it
if (typeof func === 'function') {
try {
value = func(value);
} catch (err) {
rejectPromise(child, err);
return;
}
resolvePromise(child, value);
}
else if (state === FULFILLED) {
resolvePromise(child, value);
}
else if (state === FAILED) {
rejectPromise(child, value);
}
}
|
/** @jsx React.DOM */
var DataBox = React.createClass({
render() {
return <div>
<textarea className="data" id="data1" onChange={this.onChange} onPaste={this.onPaste} defaultValue={this.props.defaultValue.join('\n')}></textarea>
</div>;
},
onChange(ev) {
var values = _.chain($(ev.nativeEvent.target).val().split('\n')).map((s) => parseFloat(s)).compact().value();
this.props.onChange(this.props.id, values);
}
//onPaste(ev){
// console.log('onPaste',ev);
// const el = $(ev.nativeEvent.target);
// var values = _.chain(el.val().split('\n')).map((s) => parseFloat(s)).compact().value();
// el.val(values.join('\n'));
//}
});
var App = React.createClass({
getInitialState() {
const cs = d3.scale.category10();
const str = localStorage['HistogramD3-values'];
const vs = str ? JSON.parse(str) : {};
console.log(vs);
return {values: vs,
colors: {dat1: cs(0), dat2: cs(1), dat3: cs(2), dat4: cs(3)}
, totalWidth: 600, totalHeight: 500, margin: {top: 10, right: 30, bottom: 30, left: 30}};
},
render() {
return <div className="row">
<div className="col-md-7">
<svg id='graph'></svg>
</div>
<div className="col-md-5" id="data-div">
<DataBox id="dat1" onChange={this.valuesChanged} defaultValue={this.state.values['dat1'] || []}></DataBox>
<DataBox id="dat2" onChange={this.valuesChanged} defaultValue={this.state.values['dat2'] || []}></DataBox>
<DataBox id="dat3" onChange={this.valuesChanged} defaultValue={this.state.values['dat3'] || []}></DataBox>
<DataBox id="dat4" onChange={this.valuesChanged} defaultValue={this.state.values['dat4'] || []}></DataBox>
</div>
</div>;
},
valuesChanged(id,values) {
var vs = _.extend({}, this.state.values);
vs[id] = values;
localStorage.setItem('HistogramD3-values',JSON.stringify(vs));
this.setState({values: vs});
},
width(){
return this.state.totalWidth - this.state.margin.left - this.state.margin.right;
},
height(){
return this.state.totalHeight - this.state.margin.top - this.state.margin.bottom;
},
componentDidMount() {
var self = this;
// Generate a Bates distribution of 10 random variables.
var values = d3.range(1000).map(d3.random.bates(10));
// A formatter for counts.
var formatCount = d3.format(",.0f");
var x = d3.scale.linear()
.domain([0, 1])
.range([0, this.width()]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
var y = d3.scale.linear()
.domain([0, d3.max(data, function (d) {
return d.y;
})])
.range([this.height(), 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var svg = d3.select('#graph')
.attr("width", this.state.totalWidth)
.attr("height", this.state.totalHeight);
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function (d) {
return "translate(" + x(d.x) + "," + y(d.y) + ")";
});
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 1)
.attr("height", function (d) {
return self.height() - y(d.y);
});
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx) / 2)
.attr("text-anchor", "middle")
.text(function (d) {
return formatCount(d.y);
});
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + this.height() + ")")
.call(xAxis);
this.updateGraph();
},
componentDidUpdate() {
this.updateGraph();
},
updateGraph() {
var self = this;
var svg = d3.select('#graph');
svg.selectAll('*').remove();
const series = _.filter(Object.keys(this.state.values),(k) => k && this.state.values[k].length > 1);
const ignore = 0.01;
//const xmax = vals[Math.floor(vals.length *(1-ignore))];
//const xmin = vals[Math.floor(vals.length *ignore)];
const xmax = 10000;
const xmin = 0;
var x = d3.scale.linear()
.domain([xmin, xmax])
.range([0, this.width()]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + this.height() + ")")
.call(xAxis);
_.map(series,(id,i) =>{
const vals = _.sortBy(this.state.values[id],(v) => v);
if(vals.length > 0){
const vals_filtered = _.filter(vals, (v) => xmin < v < xmax);
var data = d3.layout.histogram()
.bins(x.ticks(20))(vals_filtered);
const ymax = d3.max(data,(d) => d.y);
this.drawSeries(series.length,i,id,x,xmin,xmax,data,ymax);
}
});
}
,drawSeries(numSeries,idx,id,x,xmin,xmax,data,ymax){
const self = this;
const widthFactor = 0.8;
var svg = d3.select('#graph');
var y = d3.scale.linear()
.domain([0, ymax])
.range([this.height(), 0]);
console.log(data);
var bar = svg.selectAll(".bar-"+idx)
.data(data)
.enter().append("g")
.attr("class", "bar bar-"+idx)
.attr("transform", function (d) {
return "translate(" + (x(d.x)+ (x(data[0].dx) - x(0))/numSeries*idx*widthFactor) + "," + y(d.y) + ")";
});
bar.append("rect")
.attr("x", 1)
.attr("width", (x(data[0].dx) - x(0))/numSeries*widthFactor)
.attr("height", function (d) {
return self.height() - y(d.y);
})
.style('fill',self.state.colors[id]);
var formatCount = d3.format(",.0f");
console.log(self.state.colors);
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx) /numSeries*idx*widthFactor/ 2)
.attr("text-anchor", "middle")
.text( (d)=> d.y > 0 ? formatCount(d.y) : '');
var svg = d3.select('#graph');
}
});
React.render(<App/>, document.getElementById('app-container'));
$(() => {
}); |
function songDecoder(song){
var unWubbed = song.replace(/WUB/g,' ').replace(/\s{2,}/g, ' ').trim();
return unWubbed;
}
|
const argv = require('yargs').argv
const webpackConfig = require('./webpack.config')
const sauceLabsIdentity = process.env.SAUCE_USERNAME
? {username: process.env.SAUCE_USERNAME, accessKey: process.env.SAUCE_ACCESS_KEY}
: require('./saucelabs.identity')
const TEST_BUNDLER = './tests/test-bundler.sauce.js'
const browsers = [
{ base: 'SauceLabs', browserName: 'android', version: '4.4', platform: 'Linux' },
{ base: 'SauceLabs', browserName: 'android', version: '6.0', platform: 'Linux' },
{ base: 'SauceLabs', browserName: 'chrome', version: '26', platform: 'Windows 2008' },
{ base: 'SauceLabs', browserName: 'chrome', version: '60', platform: 'Windows 2008' },
{ base: 'SauceLabs', browserName: 'firefox', version: '4', platform: 'Windows 10' },
{ base: 'SauceLabs', browserName: 'firefox', version: '55', platform: 'Mac 10.9' },
// { base: 'SauceLabs', browserName: 'internet explorer',
// version: '6',
// platform: 'Windows 2003' },
// { base: 'SauceLabs', browserName: 'internet explorer',
// version: '7',
// platform: 'Windows 2003' },
// { base: 'SauceLabs', browserName: 'internet explorer',
// version: '8',
// platform: 'Windows 2008' },
{ base: 'SauceLabs', browserName: 'internet explorer', version: '9', platform: 'Windows 2008' },
{ base: 'SauceLabs', browserName: 'internet explorer', version: '10', platform: 'Windows 2012' },
{ base: 'SauceLabs', browserName: 'internet explorer', version: '11', platform: 'Windows 10' },
{ base: 'SauceLabs', browserName: 'iphone', version: '9.3', platform: 'Mac 10.10' },
{ base: 'SauceLabs', browserName: 'iphone', version: '10.3', platform: 'Mac 10.12' },
{ base: 'SauceLabs', browserName: 'safari', version: '7', platform: 'Mac 10.9' },
{ base: 'SauceLabs', browserName: 'safari', version: '8', platform: 'Mac 10.10' },
{ base: 'SauceLabs', browserName: 'safari', version: '9', platform: 'Mac 10.11' },
{ base: 'SauceLabs', browserName: 'safari', version: '10', platform: 'Mac 10.12' },
{ base: 'SauceLabs', browserName: 'microsoftedge', version: '13', platform: 'Windows 10' },
{ base: 'SauceLabs', browserName: 'microsoftedge', version: '14', platform: 'Windows 10' },
{ base: 'SauceLabs', browserName: 'microsoftedge', version: '15', platform: 'Windows 10' }
]
var karmaBrowsers = {};
browsers.forEach((item) => {
karmaBrowsers[item.browserName + ' ' + item.version + ' ' + item.platform] = item
})
const karmaConfig = {
sauceLabs: {
testName: 'Test RedPanda on Saucelabs',
recordScreenshots: false,
username: sauceLabsIdentity.username,
accessKey: sauceLabsIdentity.accessKey,
connectOptions: {
logfile: 'sauce_connect.log',
'no-ssl-bump-domains': 'all', // ignore android 4 emulator SSL error
},
public: 'public'
},
basePath: '../',
browsers: Object.keys(karmaBrowsers),
customLaunchers: karmaBrowsers,
singleRun: !argv.watch,
coverageReporter: {
reporters: [
{ type: 'text-summary' },
],
},
files: [{
pattern : TEST_BUNDLER,
watched : false,
served : true,
included : true
}],
frameworks: ['mocha'],
reporters: ['mocha', 'saucelabs'],
preprocessors: {
[TEST_BUNDLER]: ['webpack'],
},
logLevel: 'WARN',
browserConsoleLogOptions: {
terminal: true,
format: '%b %T: %m',
level: '',
},
webpack: {
entry: TEST_BUNDLER,
devtool: 'cheap-module-source-map',
module: webpackConfig.module,
plugins: webpackConfig.plugins,
resolve: webpackConfig.resolve,
externals: {
'react/addons': 'react',
'react/lib/ExecutionEnvironment': 'react',
'react/lib/ReactContext': 'react',
},
},
webpackMiddleware: {
stats: 'errors-only',
noInfo: true,
},
concurrency: 5,
// Increase timeout in case connection in CI is slow
// Increase timeout for iPhone 8.1
captureTimeout: 240000,
// web server port
// port: 11001,
}
module.exports = (cfg) => cfg.set(karmaConfig)
|
import assert from 'assert';
import { Recurly } from '../../lib/recurly';
import { initRecurly, apiTest } from './support/helpers';
const sinon = window.sinon;
apiTest(function (requestMethod) {
describe('Recurly.tax (' + requestMethod + ')', function () {
let recurly;
const us = {
country: 'US',
postal_code: '94110'
};
const vat = {
country: 'DE'
};
const none = {
country: 'CA',
postal_code: 'A1A 1A1'
};
beforeEach(() => recurly = initRecurly({ cors: requestMethod === 'cors' }));
it('requires a callback', function () {
try {
recurly.tax(us);
} catch (e) {
assert(~e.message.indexOf('callback'));
}
});
it('requires Recurly.configure', function () {
try {
recurly = new Recurly();
recurly.tax(us, () => {});
} catch (e) {
assert(~e.message.indexOf('configure'));
}
});
describe('when given a taxable US postal code', function () {
it('yields a tax type and rate', function (done) {
recurly.tax(us, function (err, taxes) {
var tax = taxes[0];
assert(!err);
assert(taxes.length === 1);
assert(tax.type === 'us');
assert(tax.rate === '0.0875');
done();
});
});
});
describe('when given a taxable VAT country', function () {
it('yields a tax type and rate', function (done) {
recurly.tax(vat, function (err, taxes) {
var tax = taxes[0];
assert(!err);
assert(taxes.length === 1);
assert(tax.type === 'vat');
assert(tax.rate === '0.015');
done();
});
});
});
describe('when given a non-taxable country', function () {
it('yields an empty array', function (done) {
recurly.tax(none, function (err, taxes) {
assert(!err);
assert(taxes.length === 0);
done();
});
});
});
describe('when given a non-taxable US postal code', function () {
it('yields an empty array', function (done) {
recurly.tax({
country: 'US',
postal_code: '70118'
}, function (err, taxes) {
assert(!err);
assert(taxes.length === 0);
done();
});
});
});
describe('when given a tax_code', function () {
it('sends the tax_code', function (done) {
var spy = sinon.spy(recurly.request, 'request');
recurly.tax({
country: 'US',
postal_code: '70118',
tax_code: 'digital'
}, function (err, taxes) {
assert(!err);
assert(spy.calledOnce);
assert(spy.calledWithMatch(sinon.match({ data: { tax_code: 'digital' } })));
spy.restore();
done();
});
});
});
describe('when given a vat_number', function () {
it('sends the vat_number', function (done) {
var spy = sinon.spy(recurly.request, 'request');
recurly.tax({
country: 'GB',
vat_number: 'GB0000'
}, function (err, taxes) {
assert(!err);
assert(spy.calledOnce);
assert(spy.calledWithMatch(sinon.match({ data: { vat_number: 'GB0000' } })));
spy.restore();
done();
});
});
});
});
});
|
'use strict';
const { execFile } = require('child_process');
module.exports = {
friendlyName: 'File size',
description: 'Get size of a file in KB',
inputs: {
filename: {
type: 'string',
required: true,
description: 'Path to the file',
},
},
exits: {
},
fn: async function (inputs, exits) {
execFile('du', ['-sk', inputs.filename], (error, stdout) => {
if (error)
return exits.error(error);
exits.success(parseInt(_.trim(_.split(stdout, ' ')[0])));
});
}
};
|
/* eslint no-var: 0 */
var main = require('./dist/cjs/i18nextXHRBackend.js').default;
module.exports = main;
module.exports.default = main;
|
(function (factory) {
typeof define === 'function' && define.amd ? define(factory) :
factory();
}((function () { 'use strict';
/**
* The code was extracted from:
* https://github.com/davidchambers/Base64.js
*/
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error();
InvalidCharacterError.prototype.name = "InvalidCharacterError";
function polyfill(input) {
var str = String(input).replace(/=+$/, "");
if (str.length % 4 == 1) {
throw new InvalidCharacterError(
"'atob' failed: The string to be decoded is not correctly encoded."
);
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = "";
// get next character
(buffer = str.charAt(idx++));
// character found in table? initialize bit storage and add its ascii value;
~buffer &&
((bs = bc % 4 ? bs * 64 + buffer : buffer),
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ?
(output += String.fromCharCode(255 & (bs >> ((-2 * bc) & 6)))) :
0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
}
var atob = (typeof window !== "undefined" &&
window.atob &&
window.atob.bind(window)) ||
polyfill;
function b64DecodeUnicode(str) {
return decodeURIComponent(
atob(str).replace(/(.)/g, function(m, p) {
var code = p.charCodeAt(0).toString(16).toUpperCase();
if (code.length < 2) {
code = "0" + code;
}
return "%" + code;
})
);
}
function base64_url_decode(str) {
var output = str.replace(/-/g, "+").replace(/_/g, "/");
switch (output.length % 4) {
case 0:
break;
case 2:
output += "==";
break;
case 3:
output += "=";
break;
default:
throw "Illegal base64url string!";
}
try {
return b64DecodeUnicode(output);
} catch (err) {
return atob(output);
}
}
function InvalidTokenError(message) {
this.message = message;
}
InvalidTokenError.prototype = new Error();
InvalidTokenError.prototype.name = "InvalidTokenError";
function jwtDecode(token, options) {
if (typeof token !== "string") {
throw new InvalidTokenError("Invalid token specified");
}
options = options || {};
var pos = options.header === true ? 0 : 1;
try {
return JSON.parse(base64_url_decode(token.split(".")[pos]));
} catch (e) {
throw new InvalidTokenError("Invalid token specified: " + e.message);
}
}
/*
* Expose the function on the window object
*/
//use amd or just through the window object.
if (window) {
if (typeof window.define == "function" && window.define.amd) {
window.define("jwt_decode", function() {
return jwtDecode;
});
} else if (window) {
window.jwt_decode = jwtDecode;
}
}
})));
//# sourceMappingURL=jwt-decode.js.map
|
// Convert our unix timestamps to human-readable string using Moment.js library
import moment from 'moment'
import _ from 'lodash'
import GoogleMapsLoader from 'google-maps'
import MarkerGenerator from './marker-generator'
module.exports = {
/***************************************************************
* Create a map instance to render on the page
****************************************************************/
createMap: function (googleMaps, callback) {
// Secure the key by restricting access on Google API manager
GoogleMapsLoader.KEY = 'AIzaSyAmXZa39VvogISSdytzFY-DGxxNZsu4Pj4'
GoogleMapsLoader.REGION = 'CA'
GoogleMapsLoader.load(google => {
googleMaps.window = google
googleMaps.map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: {lat: 49.26256765463452, lng: -123.25080871582031},
mapTypeControl: false, // disable toggle between MAP/SATELLITE
streetViewControl: false // disable STREETVIEW
})
// Execute CALLBACK function when the Google Maps has finished loading
if (callback) {
google.maps.event.addListenerOnce(googleMaps.map, 'idle', callback)
}
})
},
/***************************************************************
* Create a marker on the google map (based on the provided lat, lng)
****************************************************************/
createMarker: function (googleMaps, dataId, lat, lng, timestamp, color, image) {
const google = googleMaps.window
const map = googleMaps.map
const marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
title: `${lat}, ${lng}`,
animation: google.maps.Animation.DROP,
icon: {
url: MarkerGenerator.createSVGMarker(color),
size: new google.maps.Size(32, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(16, 32)
},
// Shapes define the clickable region of the icon
shape: {
coords: [15.5, 0, 5, 20, 32, 32, 27, 20],
type: 'poly'
},
optimized: false,
map: map
})
// Append newly created marker into an array for tracking purposes
googleMaps.markers[dataId] = marker
// Create a corresponding infoWindow for marker
const infoWindow = this.createInfoWindow(googleMaps, marker, timestamp, image)
googleMaps.infoWindows[dataId] = infoWindow
return marker
},
// Remove all markers
clearMarkers: function (googleMaps) {
for (let key in googleMaps.markers) {
googleMaps.infoWindows[key].close(googleMaps.map, googleMaps.markers[key])
googleMaps.infoWindows[key] = null
googleMaps.markers[key].setMap(null)
}
googleMaps.markers = {}
googleMaps.infoWindows = {}
},
/***************************************************************
* Create a marker on the google map (based on the provided lat, lng)
****************************************************************/
createInfoWindow: function (googleMaps, marker, timestamp, image) {
const google = googleMaps.window
const map = googleMaps.map
let infoWindow
if (image === undefined) {
infoWindow = new google.maps.InfoWindow({
content: `<div class="infoWindow">
<p>Checked in at ${moment.unix(timestamp).format('Do MMM YY (ddd), HH:mm:ss')}</p>
</div>`
})
} else {
infoWindow = new google.maps.InfoWindow({
content: `<div class="infoWindow infoImageWindow">
<p>Uploaded at ${moment.unix(timestamp).format('Do MMM YY (ddd), HH:mm:ss')}</p>
<div>
<img class="image" src=${image}>
</div>
</div>`
})
}
// marker.addListener('click', function () { infoWindow.open(map, marker) })
marker.addListener('mouseover', function () { infoWindow.open(map, marker) })
marker.addListener('mouseout', function () { infoWindow.close(map, marker) })
return infoWindow
},
/***************************************************************
* Draws a polyline on the google map (based on the provided array of coordinates)
****************************************************************/
drawRoute: function (googleMaps, coordinatesArray, color) {
const google = googleMaps.window
const map = googleMaps.map
// Appends the first checkpoint to the array so our route will have a polyline
// drawn from the last checkpoint to the first checkpoint (forming a loop)
if (coordinatesArray.length > 0) {
const startingPoint = _.clone(coordinatesArray[0], false)
coordinatesArray.push(startingPoint)
}
const thisRoute = new google.maps.Polyline({
path: coordinatesArray,
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 5
})
thisRoute.setMap(map)
// Append newly created route into an array for tracking purposes
googleMaps.routes.push(thisRoute)
return thisRoute
},
panTo: function (googleMaps, lat, lng) {
const google = googleMaps.window
const map = googleMaps.map
const latLng = new google.maps.LatLng(lat, lng)
map.panTo(latLng)
map.setZoom(19)
}
}
|
const {User} = require('../models')
const jwt = require('jsonwebtoken')
const config = require('../config/config')
function jwtSingUser(user) {
const ONE_WEEK = 60 * 60 * 24* 7;
return jwt.sign(user, config.authentication.jwtSecret, {
expiresIn: ONE_WEEK
})
}
module.exports = {
async register (req, res) {
try {
const user = await User.create(req.body)
const userJson = user.toJSON();
res.send({
user: userJson,
token: jwtSingUser(userJson)
})
} catch (err) {
res.status(400).send({
error: 'This email already exists.'
})
console.log(err)
}
},
async login (req, res) {
try {
const {email, password} = req.body
const user = await User.findOne({
where: {
email: email
}
})
if(!user){
return res.status(403).send({
error: 'Invalid credentials'
})
}
const isPasswordValid = await user.comparePassword(password)
if(!isPasswordValid){
return res.status(403).send({
error: 'Invalid credentials'
})
}
const userJson = user.toJSON();
res.send({
user: userJson,
token: jwtSingUser(userJson)
})
} catch (err) {
res.status(500).send({
error: 'Error in Login'
})
console.log(err)
}
}
}
|
var SOAPFault = BaseClass.extend({
LOG_SOURCE: "soapfault.js: ",
/**
* Constructor
* @param fault XML response body containing the SOAP Fault
* @param version SOAP version to determine the initialization of the class
*/
init: function(fault, version)
{
this.log = new Logger(this.LOG_SOURCE);
// Initialize the fault variables
this.faultcode = null;
this.faultstring = null;
this.faultactor = null;
this.detail = null;
this.code = null;
this.node = null;
this.role = null;
this.reason = null;
this.message = fault;
try
{
if ("1_1".equals(version))
{
var soap = new Namespace("http://schemas.xmlsoap.org/soap/envelope/");
var faultXml = new XML(this.formatStringForE4X(fault)).soap::Body.soap::Fault;
this.faultcode = faultXml.faultcode;
this.faultstring = faultXml.faultstring;
this.faultactor = faultXml.faultactor;
this.detail = faultXml.detail;
}
else if ("1_2".equals(version))
{
var soap = new Namespace("http://www.w3.org/2003/05/soap-envelope");
var faultXml = new XML(this.formatStringForE4X(fault)).soap::Body.soap::Fault;
this.code = new Object();
this.code.value = faultXml.soap::Code.soap::Value;
this.code.subcode = faultXml.soap::Code.soap::Subcode;
this.detail = faultXml.soap::Detail;
this.node = faultXml.soap::Node;
this.role = faultXml.soap::Role;
this.reason = new ArrayList();
var reasonList = faultXml.soap::Reason.soap::Text;
for each (item in reasonList)
{
this.reason.add(item.toString());
}
}
}
catch (e)
{
this.message = fault;
}
},
/**
* At implementation time it was found that Mozilla's implementation of E4X
* does not support XML declarations (<? ... ?>), therefore if it exists in
* the payload returned from a webservice call, it needs to be stripped out.
* http://www.xml.com/pub/a/2007/11/28/introducing-e4x.html?page=4
*
* This method takes a parameter:
* 1. Ensures it is a string
* 2. Removes any XML declarations
* 3. returns a string which can be used to create E4X objects such as
* XML or XMLList.
*/
formatStringForE4X: function(string)
{
this.log.debug("XML string that needs XML declarations removed: " + string);
string = string.toString();
string = string.replace(/<\?(.*?)\?>/g,'');
this.log.debug("XML declarations should be removed: " + string);
return string;
}
}); |
angular.module('parrotPollApp')
.service('pollService', ['dataFactory', function(dataFactory) {
this.getMaxPaginas = function functionName(pollsPorPagina, callBack) {
dataFactory.getCountPolls()
.then(function(res) {
callBack(Math.floor(res.data / pollsPorPagina));
});
};
this.getPoll = function(idPoll, callBack) {
dataFactory.getPoll(idPoll)
.then(function(res) {
callBack(res.data);
});
};
this.getPolls = function(limit, skip, callBack) {
dataFactory.getPolls(limit, skip)
.then(function(res) {
callBack(res.data);
});
};
this.ResultsCount = function(reference, callBack) {
dataFactory.getResultsCount(reference)
.then(function(res) {
callBack(res.data);
});
};
this.getResults = function(reference, callBack) {
dataFactory.getResults(reference)
.then(function(res) {
callBack(res.data);
});
};
this.validatePoll = function(poll) {
var result = true;
poll.questions.forEach(function(element, index) {
var r = false;
element.answers.forEach(function(item, i) {
r = r || item.selected || (item.selected !== undefined);
});
if (!r) result = false;
});
return result;
};
this.savePollResult = function(poll, callBack) {
dataFactory.getUser()
.then(function(res) {
poll.userResult = res.data;
dataFactory.postPollResult(poll)
.then(function(res) {
callBack();
});
}, function(res) {
dataFactory.postPollResult(poll)
.then(function(res) {
callBack();
});
});
};
}]);
|
const schema = {
_id: {
type: String,
},
createdAt: {
type: Date,
optional: true,
},
userId: {
type: String,
optional: true,
},
scheduledAt: {
type: Date,
optional: true,
},
subject: {
type: String,
optional: true,
},
data: {
type: String,
optional: true,
},
html: {
type: String,
optional: true,
},
provider: {
type: String,
optional: true,
},
};
export default schema; |
import $ from 'jquery';
$(() => {
const template = $('#new-prof-template').html();
const select = $('#std_information');
select.prepend(template);
});
|
const path = require('path');
const webpack = require('webpack');
const deepAssign = require('deep-assign');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const excludes = ['/node_modules/', '/elm-stuff/'];
const config = {
entry: {
bundle: path.resolve(__dirname, 'src', 'index.js')
},
output: {
path: path.resolve(__dirname),
filename: '[name].min.js',
publicPath: '/'
},
resolve: {
alias: {
hljs: path.resolve(__dirname, 'node_modules/highlight.js')
}
},
module: {
rules: [
{
test: /\.json/,
exclude: excludes,
use: 'json-loader'
},
{
test: /\.html$/,
exclude: excludes,
use: 'html-loader'
},
{
test: /\.elm$/,
exclude: excludes,
use: [
{ loader: 'elm-hot-loader' },
{
loader: 'elm-webpack-loader',
options: {
verbose: true,
warn: true
}
}
]
},
{
test: /\.js/,
exclude: excludes,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015']
}
}
},
{
test: /\.css$/,
exclude: excludes,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
plugins: () => [ require('autoprefixer'), require('precss') ]
}
}
]
},
{
test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: 'url-loader?limit=10000&mimetype=application/font-woff'
},
{
test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
use: 'file-loader'
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.ejs',
inlineSource: '.(js|css)$',
minify: {
removeComments: true,
}
}),
new HtmlWebpackInlineSourcePlugin()
]
};
const devConfig = {
plugins: (config.plugins || [])
.concat([new webpack.HotModuleReplacementPlugin()]),
devServer: {
inline: true,
hot: true,
noInfo: true,
stats: {
colors: true
}
}
};
const prodConfig = {
plugins: (config.plugins || []).concat([
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
screw_ie8: true,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true
}
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
})
])
};
function makeConfig(config) {
switch (process.env.NODE_ENV) {
case 'dev':
default:
return deepAssign({}, config, devConfig);
case 'prod':
return deepAssign({}, config, prodConfig);
}
}
module.exports = makeConfig(config);
|
import Vue from 'vue'
import Vuelidate from 'vuelidate'
import { shallowMount } from '@vue/test-utils'
import useI18nGlobally from '../../__utils__/i18n'
import { ModalAdditionalLedgers } from '@/components/Modal'
Vue.use(Vuelidate)
const i18n = useI18nGlobally()
let wrapper
beforeEach(() => {
wrapper = shallowMount(ModalAdditionalLedgers, {
i18n,
mocks: {
$store: {
getters: {
'ledger/wallets' () {
return []
}
}
}
}
})
})
describe('ModalAdditionalLedgers', () => {
it('should render modal', () => {
expect(wrapper.isVueInstance()).toBeTrue()
})
})
|
// Find all bytes in current directory
const req = require.context('./', true, /^\.\/.*\/index.js/);
// Export each byte
req.keys().forEach(modulePath => {
// Export name is based on byte directory
const moduleName = modulePath.match(/\.\/(.*)\//)[1];
// Export default module
module.exports[moduleName] = req(modulePath).default;
});
// Export vendor bytes
// ...
|
const _ = require('underscore');
const DrawCard = require('../../drawcard.js');
class StayYourHand extends DrawCard {
setupCardAbilities() {
this.wouldInterrupt({
title: 'Cancel a duel',
when: {
onDuelInitiated: (event, context) =>
event.context.player === context.player.opponent &&
(_.some(event.context.targets, (card) => card.controller === context.player) ||
(event.context.targets.target && _.some(event.context.targets.target, (card) => card.controller === context.player)))
},
cannotBeMirrored: true,
effect: 'cancel the duel originating from {1}',
effectArgs: context => context.event.context.source,
handler: context => context.cancel()
});
}
}
StayYourHand.id = 'stay-your-hand';
module.exports = StayYourHand;
|
var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var imageResize = require('gulp-image-resize');
var rename= require('gulp-rename')
var path = require('path');
var mime = require('mime-types')
const fs = require('fs');
var lwip = require('pajk-lwip');
function processImg(file)
{
var filesrc= file.path
var fileparts= path.parse(filesrc);
var fileext= mime.extension(file.mimetype) || 'jpg';
var filehead= fileparts.dir + '/' + fileparts.name;
console.log('handling file ' + filehead + '_min.' + fileext + ' from ' + filesrc );
return gulp.src(filesrc)
.pipe( imagemin( { optimizationLevel : 5 } ) ).pipe(rename({basename: fileparts.name + '_min.' , extname:fileext }) ).pipe( gulp.dest('/files') )
.pipe( imageResize({width : 500, height : 500, crop : true, imageMagick : true }) ).pipe(rename({basename: fileparts.name + '_500.' , extname:fileext }) ).pipe( gulp.dest('/files') )
.pipe( imageResize({width : 200, height : 200, crop : true, imageMagick : true }) ).pipe(rename({basename: fileparts.name + '_200.' , extname:fileext }) ).pipe( gulp.dest('/files') )
.pipe( imageResize({width : 100, height : 100, crop : true, imageMagick : true }) ).pipe(rename({basename: fileparts.name + '_100.' , extname:fileext }) ).pipe( gulp.dest('/files') );
}
process.on('message', function(images)
{
console.log('INFO: image processing started');
var stream = processImg(images);
stream.on('end', function()
{
console.log('INFO: image processing completed');
process.send('INFO: image processing completed');
process.exit();
});
stream.on('error', function(err)
{
console.log('ERROR: image processing failed ' + err );
process.send(err);
process.exit(1);
});
});
module.exports = {}; |
'use strict';
const http = require('http');
const https = require('https');
const fs = require('fs');
const debug = require('debug')('grm:init');
const koa = require('koa');
const config = require('./config.json');
const app = koa();
debug('configuring app');
require('./src/server/load')(app);
const httpServer = http.createServer(app.callback());
const httpPort = config.port || 3000;
httpServer.listen(httpPort, function() {
debug(`app listening on HTTP port ${httpPort}`);
});
if (config.ssl) {
const httpsServer = https.createServer(
{
key: fs.readFileSync(config.ssl.key),
cert: fs.readFileSync(config.ssl.cert),
},
app.callback(),
);
const httpsPort = config.ssl.port || 3001;
httpsServer.listen(httpsPort, function() {
debug(`app listening on HTTPS port ${httpsPort}`);
});
}
|
// This library started as an experiment to see how small I could make
// a functional router. It has since been optimized (and thus grown).
// The redundancy and inelegance here is for the sake of either size
// or speed.
function Rlite() {
var routes = {},
decode = decodeURIComponent;
function noop(s) { return s; }
function sanitize(url) {
~url.indexOf('/?') && (url = url.replace('/?', '?'));
url[0] == '/' && (url = url.slice(1));
url[url.length - 1] == '/' && (url = url.slice(0, -1));
return url;
}
function processUrl(url, esc) {
var pieces = url.split('/'),
rules = routes,
params = {};
for (var i = 0; i < pieces.length && rules; ++i) {
var piece = esc(pieces[i]);
rules = rules[piece.toLowerCase()] || rules[':'];
rules && rules[':'] && (params[rules[':']] = piece);
}
return rules && {
cb: rules['@'],
params: params
};
}
function processQuery(url, ctx, esc) {
if (url && ctx.cb) {
var hash = url.indexOf('#'),
query = (hash < 0 ? url : url.slice(0, hash)).split('&');
for (var i = 0; i < query.length; ++i) {
var nameValue = query[i].split('=');
ctx.params[nameValue[0]] = esc(nameValue[1]);
}
}
return ctx;
}
function lookup(url) {
var querySplit = sanitize(url).split('?'),
esc = ~url.indexOf('%') ? decode : noop;
return processQuery(querySplit[1], processUrl(querySplit[0], esc) || {}, esc);
}
return {
add: function(route, handler) {
var pieces = route.toLowerCase().split('/'),
rules = routes;
for (var i = 0; i < pieces.length; ++i) {
var piece = pieces[i],
name = piece[0] == ':' ? ':' : piece;
rules = rules[name] || (rules[name] = {});
name == ':' && (rules[':'] = piece.slice(1));
}
rules['@'] = handler;
},
exists: function (url) {
return !!lookup(url).cb;
},
lookup: lookup,
run: function(url) {
var result = lookup(url);
result.cb && result.cb({
url: url,
params: result.params
});
return !!result.cb;
}
};
}
(function (root, factory) {
var define = root.define;
if (define && define.amd) {
define([], factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
}
}(this, function () { return Rlite; }));
/*!
* cookie-monster - a simple cookie library
* v0.3.0
* https://github.com/jgallen23/cookie-monster
* copyright Greg Allen 2014
* MIT License
*/
var monster = {
set: function(name, value, days, path, secure) {
var date = new Date(),
expires = '',
type = typeof(value),
valueToUse = '',
secureFlag = '';
path = path || "/";
if (days) {
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
if (type === "object" && type !== "undefined") {
if(!("JSON" in window)) throw "Bummer, your browser doesn't support JSON parsing.";
valueToUse = encodeURIComponent(JSON.stringify({v:value}));
} else {
valueToUse = encodeURIComponent(value);
}
if (secure){
secureFlag = "; secure";
}
document.cookie = name + "=" + valueToUse + expires + "; path=" + path + secureFlag;
},
get: function(name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
value = '',
firstChar = '',
parsed={};
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) {
value = decodeURIComponent(c.substring(nameEQ.length, c.length));
firstChar = value.substring(0, 1);
if(firstChar=="{"){
try {
parsed = JSON.parse(value);
if("v" in parsed) return parsed.v;
} catch(e) {
return value;
}
}
if (value=="undefined") return undefined;
return value;
}
}
return null;
},
remove: function(name) {
this.set(name, "", -1);
},
increment: function(name, days) {
var value = this.get(name) || 0;
this.set(name, (parseInt(value, 10) + 1), days);
},
decrement: function(name, days) {
var value = this.get(name) || 0;
this.set(name, (parseInt(value, 10) - 1), days);
}
};
(function(){
var d = document,
w = window,
templates = {},
models = {},
store = {},
readyCbs = [],
ready = false,
router = new Rlite(),
$ = d.querySelector.bind(d),
Base = function() {};
function ikon(e) {
if (typeof e === 'string') {
return ikon.select(e);
} else if (typeof e === 'function') {
if (!!ready) {
func();
} else if (typeof func === 'function') {
readyCbs.push(func);
}
} else if (e instanceof w.Element || e instanceof w.Window) {
return new ikon.Element(e);
}
return ikon;
};
ikon.ajax = function(method, url, data, headers, cb, contentType) {
var xhr = new XMLHttpRequest(),
hasBody = (method === 'PUT' || method === 'POST'),
responded = false, k;
contentType = contentType || 'application/json';
headers = headers || {};
xhr.onreadystatechange = function() {
if (!!responded || xhr.readyState < 4) {
return;
}
if(xhr.status < 200 || xhr.status > 204) {
responded = true;
cb({}, null, xhr.status);
return;
}
if(xhr.readyState === 4) {
responded = true;
cb(null, xhr.responseText, xhr.status);
}
};
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', contentType);
for (k in headers) {
if (headers.hasOwnProperty(k)) {
xhr.setRequestHeader(k, headers[k]);
}
}
if (hasBody) {
if (contentType === 'application/json' && typeof data !== 'string') {
data = JSON.stringify(data || {});
} else if (!data) {
data = '';
}
xhr.send(data);
} else {
xhr.send();
}
return ikon;
};
ikon.solve = function(url, object) {
var a = url.split('/'),
i, l = a.length, key;
for (i = 0; i < l; i += 1) {
if (a[i].indexOf(':') === 0) {
key = a[i].slice(1);
if (object.hasOwnProperty(key)) {
if (typeof object[key] === 'function') {
a[i] = object[key]();
} else {
a[i] = object[key];
}
}
}
}
return a.join('/');
};
ikon.bulk = function(urls, cb) {
var k,
l = 0,
url,
allDone = false,
hasError,
res = {};
for(k in urls) {
l += 1;
url = urls[k];
// Url is array: we load a model
// (either a unique one or an array of them)
if (Array.isArray(url)) {
(function bulk_load(k){
ikon.load(url[0], url[1], function(err, data) {
hasError = !!err || hasError;
res[k] = data;
l -= 1;
if (l === 0 && allDone) {
cb(hasError, res);
}
});
}(k));
// Otherwise if string we only get
// the URL if it's a string
} else if (typeof url === 'string') {
(function bulk_get(k){
ikon.get(url, function(err, data) {
hasError = !!err || hasError;
res[k] = data;
l -= 1;
if (l === 0 && allDone) {
cb(hasError, res);
}
});
}(k));
}
}
allDone = true;
if (l === 0) {
cb(null, res);
}
return ikon;
};
ikon.get = function(url, cb) {
return ikon.ajax('GET', url, null, {}, function(err, data) {
cb(err, data);
});
};
ikon.post = function(url, data, cb, parseJSON) {
var cb2 = cb;
if (parseJSON) {
cb2 = function(err, data) {
cb(err, typeof data === 'string' ? JSON.parse(data) : data);
};
}
return ikon.ajax('POST', url, data, {}, cb2);
};
ikon.put = function(url, data, cb, parseJSON) {
var cb2 = cb;
if (parseJSON) {
cb2 = function(err, data) {
cb(err, typeof data === 'string' ? JSON.parse(data) : data);
};
}
return ikon.ajax('PUT', url, data, {}, cb2);
};
ikon.delete = function(url, cb) {
return ikon.ajax('DELETE', url, null, {}, cb);
};
ikon.load = function(url, modelName, cb) {
return ikon.get(url, function(err, data) {
if (!!err) {
cb(err, null);
return;
}
cb(null, ikon.materialize(modelName, JSON.parse(data)));
});
};
ikon.materialize = function(modelName, data) {
var i, l, res;
if (Array.isArray(data)) {
for (i = 0, l = data.length; i < l; i += 1) {
data[i] = ikon.materialize(modelName, data[i]);
}
return data;
}
res = new Base();
models[modelName](res);
if (typeof data !== 'undefined') {
if (typeof data === 'object' && typeof res.fromJSON === 'function') {
res.fromJSON(data);
}
if (data.hasOwnProperty('id') && !!data.id) {
store[modelName][data.id] = data;
}
}
return res;
};
ikon.model = function(modelName, constructor, prototype) {
for (var k in prototype) {
if (prototype.hasOwnProperty(k)) {
constructor.prototype[k] = prototype[k];
}
}
store[modelName] = {};
models[modelName] = constructor;
return ikon;
};
ikon.template = function(template, cb) {
if (templates.hasOwnProperty(template)) {
cb(templates[template]);
return ikon;
}
ikon.get(template + '.html', function(err, tpl) {
if (!!err) {
console.warn('Template not loaded: ' + template, err);
tpl = '';
} else {
templates[template] = tpl;
}
cb(tpl);
});
return ikon;
};
ikon.view = function(selector, template, cb) {
var el = $(selector),
view;
if (el === null) {
console.warn('No element found for selector ' + selector);
return;
}
el.innerHTML = '';
ko.cleanNode(el);
ikon.template(template, function(tpl) {
cb(function(vm) {
el.innerHTML = tpl;
if (!!vm && typeof ko !== 'undefined') {
ko.applyBindings(vm, el);
}
});
});
return ikon;
};
ikon.route = function (hash, cb) {
router.add(ikon.cleanHash(hash), cb);
return ikon;
};
ikon.redirect = function (hash) {
if (hash.indexOf('#') !== 0) {
hash = '#' + hash;
}
w.location.hash = hash;
return ikon;
};
ikon.cleanHash = function(hash) {
while (hash[0] === '#' || hash[0] === '!' || hash[0] === '/') {
hash = hash.slice(1);
}
return hash;
};
ikon.extend = function(from, to) {
var k;
to = to || {};
for (k in from) {
if (from.hasOwnProperty(k)) {
to[k] = from[k];
}
}
return to;
};
ikon.hasClass = function(node, className) {
return node.className && new RegExp("(\\s|^)" + className + "(\\s|$)").test(node.className);
};
ikon.addClass = function(node, className) {
if (className && !ikon.hasClass(node, className)) {
node.className += ' ' + className;
}
return ikon;
};
ikon.removeClass = function(node, className) {
if (className && ikon.hasClass(node, className)) {
node.className = node.className.replace(new RegExp('(^| )(' + className +')($| )', 'gi'), ' ');
}
return ikon;
};
ikon.Element = function(el, parent) {
this.el_ = el;
this.parent_ = parent || null;
};
ikon.Element.prototype = {
create: function(type) {
var child = new ikon.Element(d.createElement(type), this);
child.appendTo(this);
return child;
},
parent: function() {
return this.parent_;
},
root: function() {
var p = this;
while (p.parent_) {
p = p.parent_;
}
return p;
},
attr: function(key, value) {
if (arguments.length === 2) {
this.el_.setAttribute(key, value);
return this;
}
return this.el_.getAttribute(key);
},
style: function(key, value) {
if (arguments.length === 2) {
this.el_.style[key] = value;
return this;
}
return this.el_.style[key];
},
addClass: function(className) {
ikon.addClass.call(ikon, this.el_, className);
return this;
},
removeClass: function(className) {
ikon.removeClass.call(ikon, this.el_, className);
return this;
},
hasClass: function(className) {
return ikon.hasClass.call(ikon, this.el_, className);
},
text: function(text) {
this.el_.innerText = text;
return this;
},
html: function(html) {
this.el_.innerHTML = html;
return this;
},
remove: function() {
if (this.el_.parentNode) {
this.el_.parentNode.removeChild(this.el_);
}
return this;
},
empty: function() {
this.html('');
return this;
},
on: function(evt, cb) {
this.el_.addEventListener(evt, cb);
return this;
},
off: function(evt, cb) {
this.el_.removeEventListener(evt, cb);
return this;
},
height: function(v) {
if (arguments.length) {
this.style('height', v + 'px');
return this;
}
return this.el_.offsetHeight;
},
width: function(v) {
if (arguments.length) {
this.style('width', v + 'px');
return this;
}
return this.el_.offsetWidth;
},
left: function(v) {
if (arguments.length) {
this.style('left', v + 'px');
return this;
}
return this.el_.offsetLeft;
},
top: function(v) {
if (arguments.length) {
this.style('top', v + 'px');
return this;
}
return this.el_.offsetTop;
},
appendTo: function(parent) {
var p = parent;
if (p instanceof ikon.Element) {
p = p.el();
}
p.appendChild(this.el_);
return this;
},
el: function() {
return this.el_;
}
};
ikon.select = function(selector) {
return new ikon.Element($(selector));
};
ikon.create = function(type) {
return new ikon.Element(d.createElement(type));
};
ikon.fn = function(name, handler) {
// To be replaced by prototype based
ikon.fn[name] = handler;
};
ikon.cookie = {
get: function() {
return monster.get.apply(w, arguments);
},
set: function() {
return monster.set.apply(w, arguments);
},
remove: function() {
return monster.remove.apply(w, arguments);
}
};
var route = function() {
router.run(ikon.cleanHash(w.location.hash || ''));
};
w.addEventListener('hashchange', route);
d.addEventListener('DOMContentLoaded', function() {
ready = true;
readyCbs.forEach(function(f) {
f();
});
route();
});
w.ikon = ikon;
}());
|
const anymatch = require('anymatch')
const {createVariableRule} = require('./lib/variable-rules')
const spacerVarPatterns = ['$spacer-*', '$em-spacer-*']
const values = [...spacerVarPatterns, '0', 'auto', 'inherit']
module.exports = createVariableRule(
'primer/spacing',
({variables}) => {
const spacerVars = Object.keys(variables).filter(anymatch(spacerVarPatterns))
const negativeValues = spacerVarPatterns.map(p => `-${p}`)
const replacements = {}
for (const name of spacerVars) {
replacements[`-${variables[name].computed}`] = `-${name}`
}
return {
margin: {
expects: 'a spacer variable',
props: 'margin{,-top,-right,-bottom,-left}',
values: values.concat(negativeValues),
replacements
},
padding: {
expects: 'a non-negative spacer variable',
props: 'padding{,-top,-right,-bottom,-left}',
values
}
}
},
'https://primer.style/css/support/spacing'
)
|
'use strict';
var fs = require('fs');
var jsStringEscape = require('js-string-escape');
var uglifyJs = require("uglify-js");
var PACKAGE_FILE = './distribution/es6pack.js';
var minified = uglifyJs.minify('./source/es6pack.js');
console.info(Buffer.byteLength(minified.code, 'utf8') + ' bytes');
var distributionString = jsStringEscape(minified.code);
var packageScript = 'module.exports = "' + distributionString + '";\n';
fs.writeFileSync(PACKAGE_FILE, packageScript);
|
var HashTable = function(limit) {
this._storage = [];
this._storageLimit = limit || 128;
this.insert = function(key, value) {
var index = getIndexBelowMaxForKey(key, this._storageLimit);
var bucket = this._storage[index];
var found = false;
if (!bucket) {
bucket = [];
}
bucket.forEach(function(tuple) {
if (tuple[0] === key) {
tuple[1] = value;
found = true;
}
});
if (!found) {
bucket.push[key, value];
}
};
this.retrieve = function(key) {
var index = getIndexBelowMaxForKey(key, this._storageLimit);
var bucket = this._storage[index];
var value = null;
bucket.forEach(function(tuple) {
if (tuple[0] === key) {
value = tuple[1];
}
});
return value;
};
this.remove = function(key) {
var index = getIndexBelowMaxForKey(key, this._storageLimit);
var bucket = this._storage[index];
bucket.forEach(function(tuple, i) {
if (tuple[0] === key) {
bucket.splice(i, 1);
}
});
};
};
// Hashing function
function getIndexBelowMaxForKey(str, max) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash += str.charCodeAt(i);
}
return hash % max;
}
|
import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet, injectGlobal } from 'styled-components'
injectGlobal`
html {
box-sizing: border-box;
background-color: #141518;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
font-family: 'Open Sans', sans-serif;
color: #f2f2f2;
}
.root {
min-height: 100%;
}
`
export default class extends Document {
render() {
const sheet = new ServerStyleSheet()
const main = sheet.collectStyles(<Main/>)
const styleTags = sheet.getStyleElement()
return (
<html>
<Head>
<meta name='viewport' content='width=device-width, initial-scale=1'/>
<link rel='apple-touch-icon' sizes='180x180' href='/images/apple-touch-icon.png'/>
<link rel='icon' type='image/png' sizes='32x32' href='/images/favicon-32x32.png'/>
<link rel='icon' type='image/png' sizes='16x16' href='/images/favicon-16x16.png'/>
<link rel='manifest' href='/manifest.json'/>
<link rel='mask-icon' href='/images/safari-pinned-tab.svg' color='#2c2f34'/>
<meta name='theme-color' content='#2c2f34'/>
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css'/>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i'/>
{ styleTags }
<title>Inqur</title>
</Head>
<body>
<div className='root'>{ main }</div>
<NextScript />
</body>
</html>
)
}
}
|
var pacbot = require('../../lib/pacbot');
var fss = require('../../lib/fss');
exports.setUp = function (callback) {
pacbot.config({
appdir: 'spec/cases/tmpl',
pubdir: 'spec/out/tmpl',
packed: 'assets',
config: 'spec/cases/tmpl/config.js'
});
callback();
};
var js = function (path) {
return '<script src="' + path;
};
var assertSubstr = function (test, supstr, substr) {
test.ok(supstr.indexOf(substr) > -1);
};
exports.canCompileAssetTemplates = function (test) {
pacbot.build(function () {
test.ok(fss.exists('spec/out/tmpl/index.html'));
assertSubstr(test, fss.readFile('spec/out/tmpl/index.html'), js('/assets/common.tmpl'));
assertSubstr(test, fss.readFile('spec/out/tmpl/assets/common.tmpl'), 'window.templates["assets/templates/1.tmpl"]');
test.done();
});
};
|
/* */
(function(process) {
module.exports = DirReader;
var fs = require('graceful-fs');
var inherits = require('inherits');
var path = require('path');
var Reader = require('./reader');
var assert = require('assert').ok;
inherits(DirReader, Reader);
function DirReader(props) {
var self = this;
if (!(self instanceof DirReader)) {
throw new Error('DirReader must be called as constructor.');
}
if (props.type !== 'Directory' || !props.Directory) {
throw new Error('Non-directory type ' + props.type);
}
self.entries = null;
self._index = -1;
self._paused = false;
self._length = -1;
if (props.sort) {
this.sort = props.sort;
}
Reader.call(this, props);
}
DirReader.prototype._getEntries = function() {
var self = this;
if (self._gotEntries)
return;
self._gotEntries = true;
fs.readdir(self._path, function(er, entries) {
if (er)
return self.error(er);
self.entries = entries;
self.emit('entries', entries);
if (self._paused)
self.once('resume', processEntries);
else
processEntries();
function processEntries() {
self._length = self.entries.length;
if (typeof self.sort === 'function') {
self.entries = self.entries.sort(self.sort.bind(self));
}
self._read();
}
});
};
DirReader.prototype._read = function() {
var self = this;
if (!self.entries)
return self._getEntries();
if (self._paused || self._currentEntry || self._aborted) {
return;
}
self._index++;
if (self._index >= self.entries.length) {
if (!self._ended) {
self._ended = true;
self.emit('end');
self.emit('close');
}
return;
}
var p = path.resolve(self._path, self.entries[self._index]);
assert(p !== self._path);
assert(self.entries[self._index]);
self._currentEntry = p;
fs[self.props.follow ? 'stat' : 'lstat'](p, function(er, stat) {
if (er)
return self.error(er);
var who = self._proxy || self;
stat.path = p;
stat.basename = path.basename(p);
stat.dirname = path.dirname(p);
var childProps = self.getChildProps.call(who, stat);
childProps.path = p;
childProps.basename = path.basename(p);
childProps.dirname = path.dirname(p);
var entry = Reader(childProps, stat);
self._currentEntry = entry;
entry.on('pause', function(who) {
if (!self._paused && !entry._disowned) {
self.pause(who);
}
});
entry.on('resume', function(who) {
if (self._paused && !entry._disowned) {
self.resume(who);
}
});
entry.on('stat', function(props) {
self.emit('_entryStat', entry, props);
if (entry._aborted)
return;
if (entry._paused) {
entry.once('resume', function() {
self.emit('entryStat', entry, props);
});
} else
self.emit('entryStat', entry, props);
});
entry.on('ready', function EMITCHILD() {
if (self._paused) {
entry.pause(self);
return self.once('resume', EMITCHILD);
}
if (entry.type === 'Socket') {
self.emit('socket', entry);
} else {
self.emitEntry(entry);
}
});
var ended = false;
entry.on('close', onend);
entry.on('disown', onend);
function onend() {
if (ended)
return;
ended = true;
self.emit('childEnd', entry);
self.emit('entryEnd', entry);
self._currentEntry = null;
if (!self._paused) {
self._read();
}
}
entry.on('error', function(er) {
if (entry._swallowErrors) {
self.warn(er);
entry.emit('end');
entry.emit('close');
} else {
self.emit('error', er);
}
});
;
['child', 'childEnd', 'warn'].forEach(function(ev) {
entry.on(ev, self.emit.bind(self, ev));
});
});
};
DirReader.prototype.disown = function(entry) {
entry.emit('beforeDisown');
entry._disowned = true;
entry.parent = entry.root = null;
if (entry === this._currentEntry) {
this._currentEntry = null;
}
entry.emit('disown');
};
DirReader.prototype.getChildProps = function() {
return {
depth: this.depth + 1,
root: this.root || this,
parent: this,
follow: this.follow,
filter: this.filter,
sort: this.props.sort,
hardlinks: this.props.hardlinks
};
};
DirReader.prototype.pause = function(who) {
var self = this;
if (self._paused)
return;
who = who || self;
self._paused = true;
if (self._currentEntry && self._currentEntry.pause) {
self._currentEntry.pause(who);
}
self.emit('pause', who);
};
DirReader.prototype.resume = function(who) {
var self = this;
if (!self._paused)
return;
who = who || self;
self._paused = false;
self.emit('resume', who);
if (self._paused) {
return;
}
if (self._currentEntry) {
if (self._currentEntry.resume)
self._currentEntry.resume(who);
} else
self._read();
};
DirReader.prototype.emitEntry = function(entry) {
this.emit('entry', entry);
this.emit('child', entry);
};
})(require('process'));
|
(function (FunnyRain) {
"use strict";
function BlocksFactory (game) {
var _game = game;
var _isEnabled;
var _blockClassList = [
{
blockCategory: "fruit",
blockClass: FunnyRain.Plugins.Blocks.FruitBlock,
blockTypes: ["apple","peach","orange"]
},
{
blockCategory: "bomb",
blockClass: FunnyRain.Plugins.Blocks.BombBlock,
blockTypes: ["bomb"]
}
];
var _nextId;
var _blockList = [];
init();
function init () {
_nextId = 0;
}
function findBlockCategory (blockCategory) {
for(var i = 0; i < _blockClassList.length; i++) {
var blockClassRecord = _blockClassList[i];
if(blockClassRecord.blockCategory === blockCategory) {
return blockClassRecord;
}
}
return null;
}
function createBlock (blockCategoryRecord, blockTypeIndex) {
var blockId = ++_nextId;
var block = new blockCategoryRecord.blockClass(blockId,
_game,
blockCategoryRecord.blockTypes[blockTypeIndex],
blockCategoryRecord.blockCategory, function(context, block){
destroyBlock(block);
});
_blockList.push(block);
return block;
}
function createRandomBlock (blockCategoryRecord) {
var blockTypeIndex = Boplex.random(0,
blockCategoryRecord.blockTypes.length-1);
return createBlock(blockCategoryRecord, blockTypeIndex);
}
function createBlockByCategory (blockCategory) {
var blockCategoryRecord = findBlockCategory(blockCategory);
if (!blockCategoryRecord) {
throw new RangeError(blockCategory + " - unknown block category");
}
return createRandomBlock(blockCategoryRecord);
}
function destroyBlock (block) {
for(var i = 0; i < _blockList.length; i++){
if (block === _blockList[i]) {
_blockList.splice(i,1);
break;
}
}
}
function enable (t, isEnabled) {
if (isEnabled === _isEnabled) {
return;
}
_isEnabled = isEnabled;
if (_isEnabled) {
removeAllBlocks(t);
}
}
function removeAllBlocks (t) {
while(_blockList.length) {
_blockList[0].destroy();
}
}
BlocksFactory.prototype.createBlockByCategory = function (blockCategory) {
return createBlockByCategory.call(this, blockCategory);
};
BlocksFactory.prototype.forEach = function (handler) {
_blockList.forEach(handler);
};
BlocksFactory.prototype.destroyBlock = function (block) {
destroyBlock.call(this, block);
};
BlocksFactory.prototype.enable = function (isEnabled) {
enable.call(this, this, isEnabled);
};
}
FunnyRain.Plugins.Blocks.BlocksFactory = BlocksFactory;
})(FunnyRain);
|
Subsets and Splits