text
stringlengths 2
6.14k
|
|---|
{
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function HTMLImageElement(node) {
HTMLElement.call(this, node);
}
HTMLImageElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(
OriginalHTMLImageElement,
HTMLImageElement,
document.createElement("img")
);
function Image(width, height) {
if (!(this instanceof Image)) {
throw new TypeError(
"DOM object constructor cannot be called as a function."
);
}
var node = unwrap(document.createElement("img"));
HTMLElement.call(this, node);
rewrap(node, this);
if (width !== undefined) node.width = width;
if (height !== undefined) node.height = height;
}
Image.prototype = HTMLImageElement.prototype;
scope.wrappers.HTMLImageElement = HTMLImageElement;
scope.wrappers.Image = Image;
}
|
'use strict';
import Immutable from 'immutable';
export default {
DEFAULT_STATE: Immutable.fromJS({
channels: [],
activeChannel: null,
users: [],
user: null,
messages: []
})
/*
DEFAULT_STATE: Immutable.fromJS({
channels: [
{id: 1, name: 'channel 1'},
{id: 2, name: 'channel 2'},
{id: 3, name: 'channel 3'},
{id: 4, name: 'channel 4'}
],
activeChannel: 1,
users: [
{id: 1, name: 'Jiri Vopolka'},
{id: 2, name: 'Vladimir Gorej'},
{id: 3, name: 'Dmitry Druganov'}
],
user: 3,
messages: [
{
id: '6c84fb90-12c4-11e1-840d-7b25c5ee775a',
channel: 1,
user: 1,
body: 'message body 1, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'cd278f50-cb8c-11e5-b5a4-f1075ef8465d',
channel: 1,
user: 2,
body: 'message body 2, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'fee79d00-cb8c-11e5-b5a4-f1075ef8465d',
channel: 1,
user: 1,
body: 'message body 3, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'dcfdaae0-cb8c-11e5-b5a4-f1075ef8465d',
channel: 2,
user: 2,
body: 'message body 4, channel 2',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'f4f9a6d0-cb8c-11e5-b5a4-f1075ef8465d',
channel: 2,
user: 3,
body: 'message body 5, channel 2',
created: '2016-02-03T14:03:02.782Z'
}
]
})
*/
};
|
var should = require('should')
var Store = require('../../../store/postgres')
describe('Postgres: UUID Key', function() {
var store
var database = 'uuid_key_test'
before(function(next) {
this.timeout(5000)
beforePG(
database,
[
'CREATE EXTENSION IF NOT EXISTS \\"uuid-ossp\\"',
'CREATE TABLE uuid_tests (id uuid not null primary key default uuid_generate_v1(), another_column varchar(255))'
],
next
)
})
before(function() {
store = new Store({
host: 'localhost',
type: 'postgres',
database: database,
user: 'postgres',
password: ''
})
store.Model('UuidTest', function() {})
})
after(function(next) {
afterPG(database, next)
})
it('attribute id is type uuid', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
UuidTest.definition.attributes.id.type.name.should.be.equal('uuid')
})
})
it('new() returns a null id (uuid)', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
var test = new UuidTest({ another_column: 'i am setting uuid' })
should.not.exist(test.id)
})
})
it('create() returns a new id (uuid)', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
var test = new UuidTest({ another_column: 'i am setting uuid' })
return test.save().then(function() {
should.exist(test.id)
})
})
})
})
|
var searchData=
[
['root_279',['root',['../structbwRTree__t.html#ad4566d3fdd23ac4918104d23c77a7ddb',1,'bwRTree_t']]],
['rootoffset_280',['rootOffset',['../structbwRTree__t.html#aa3e57a494e0c45d56dca1de0939e8197',1,'bwRTree_t']]],
['runningwidthsum_281',['runningWidthSum',['../structbwWriteBuffer__t.html#a395634c6f60756abb87013a11f68b293',1,'bwWriteBuffer_t']]]
];
|
const fp = require('lodash/fp')
const { handleActions } = require('redux-fp')
module.exports = handleActions({
SET_SOCKET_CLIENT: ({ payload: { socket } }) =>
fp.set(['socketClients', socket.id], socket),
UNSET_SOCKET_CLIENT: ({ payload: { socket } }) =>
fp.unset(['socketClients', socket.id]),
SET_SOCKET_SESSION: ({ payload: { socket, session } }) =>
fp.set(['socketSessions', socket.id], session),
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:ceb6c3cd7166befa772ac603351dea546ba4ae40384834f19111fac325627715
size 24214
|
(function(){
angular
.module('app.answer')
.controller('answerController', answerController);
answerController.$inject = ['$stateParams','$firebaseObject'];
function answerController($stateParams, $firebaseObject){
var vm = this;
vm.id = $stateParams.id;
vm.addVote = addVote;
vm.options = {
responsive: true,
maintainAspectRatio: true
};
var fireQuestions = new Firebase('https://quizpoll-d8e4a.firebaseio.com/question/' + vm.id);
vm.Answer = $firebaseObject(fireQuestions);
$firebaseObject(fireQuestions).$watch(function(){
vm.Answer.$loaded().then(function(){
vm.data = [vm.Answer.option1.vote, vm.Answer.option2.vote, vm.Answer.option3.vote, vm.Answer.option4.vote];
vm.labels = [vm.Answer.option1.option,vm.Answer.option2.option, vm.Answer.option3.option, vm.Answer.option4.option];
vm.sum = vm.Answer.option1.vote + vm.Answer.option2.vote + vm.Answer.option3.vote + vm.Answer.option4.vote;
});
});
function addVote(vote){
vote.vote++;
console.log(vote.vote);
vm.Answer.$save();
alert('Thank you for voting! Your vote has been added');
vm.Answer.$loaded().then(function(){
vm.data = [vm.Answer.option1.vote, vm.Answer.option2.vote, vm.Answer.option3.vote, vm.Answer.option4.vote];
vm.labels = [vm.Answer.option1.option,vm.Answer.option2.option, vm.Answer.option3.option, vm.Answer.option4.option];
});
vm.hide=true;
}
}
})();
|
var gulp = require('gulp');
var revOrig = require('./../index.js');
gulp.task('revOrig-default', function (argument) {
gulp.src('test.html')
.pipe(revOrig())
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withBase', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
base: 'assets/'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-byDate', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'date'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withDateFormat', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'date',
dateFormat: 'yymmddHHmm'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withHashLength', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'hash',
hashLength: 5
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withHashKey', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
suffix: 'hashkey'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withFileTypes', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['js']
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withElementAttributes', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['img1'],
elementAttributes: {
img1: {
tagRegStr: '(<img [^>]+/?>)',
pathRegStr: '(?:(\\s+data-src=")([^"]+)("))'
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withTransformPath', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
transformPath: function (orgpath, ver) {
var newpath = 'http://s1.cdn.com/' + orgpath + (orgpath.indexOf('?') > -1 ? '&' : '?') + 'v=' + ver;
return newpath;
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withDefaultAddElementRev', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
defaultAddElementRev: function (segment, addSrcRev, elementSetting) {
elementSetting.pathReg.lastIndex = 0;
var match = elementSetting.pathReg.exec(segment);
if(match) {
var src = match[2];
var revSrc = addSrcRev(src);
if(revSrc !== src) {
var base = './xxx' + (revSrc[0] === '/' ? '' : '/');
return segment.replace(elementSetting.pathReg, '$1' + base + revSrc + '$3');
} else {
return segment;
}
} else {
return segment;
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withAddElementRev', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['js', 'img1'],
elementAttributes: {
js: {
tagRegStr: '(<script [^>]+/?>)',
pathRegStr: '(?:(\\s+src=")([^"]+)("))'
},
img1: {
tagRegStr: '(<img [^>]+/?>)',
pathRegStr: '(?:(\\s+data-src=")([^"]+)("))',
addElementRev: function (segment, addSrcRev, elementSetting) {
elementSetting.pathReg.lastIndex = 0;
var match = elementSetting.pathReg.exec(segment);
if(match) {
var src = match[2];
var revSrc = addSrcRev(src);
return segment.replace(elementSetting.pathReg, '$1[' + revSrc + ']$3');
} else {
return segment;
}
}
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-createDefaultOptions', function () {
var options = revOrig.createDefaultOptions();
options.elementAttributes.loadJs = {
tagRegStr: '(<js [^>]+/?>)',
pathRegStr: '(?:(\\s+src=")([^"]+)("))'
};
options.fileTypes.push('loadJs');
gulp.src('test.html')
.pipe(revOrig(options))
.pipe(gulp.dest('./dist'));
});
|
import React from 'react';
const ReactComponenta1 = () => <h2> Hello </h2>;
const ReactComponenta2 = () => <input />;
const ReactComponenta3 = () => <button>Add Me</button>;
const allBox = [
{
uid: 'a1',
title: 'Box-1',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta1,
},
{
uid: 'a2',
title: 'Box-2',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta2,
},
{
uid: 'a3',
title: 'Box-3',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta3,
},
{
uid: 'a4',
title: 'Box-4',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta3,
},
];
export default allBox;
/*
size: {
lg: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
md: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
sm: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
xs: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
xxs: {x: 0, y: 4, h: 2, w: 12,i: 'a3'},
},
*/
|
require("coffee-script/register");
module.exports = require("./machina.coffee");
|
import React, { Component, PropTypes } from 'react';
import styles from '../../build/styles';
import { getCallbacks } from '../helper/helper';
export default class Column extends Component {
static propTypes = {
children: PropTypes.any,
style: PropTypes.object,
className: PropTypes.string,
isMultiline: PropTypes.bool,
size: PropTypes.oneOf([
'is1',
'is2',
'is3',
'is4',
'is5',
'is6',
'is7',
'is8',
'is9',
'is10',
'is11',
'is12',
'isThreeQuarters',
'isTwoThirds',
'isHalf',
'isOneThird',
'isOneQuarter',
'isThreeQuartersMobile',
'isTwoThirdsMobile',
'isHalfMobile',
'isOneThirdMobile',
'isOneQuarterMobile',
'isThreeQuartersTablet',
'isTwoThirdsTablet',
'isHalfTablet',
'isOneThirdTablet',
'isOneQuarterTablet',
'isThreeQuartersDesktop',
'isTwoThirdsDesktop',
'isHalfDesktop',
'isOneThirdDesktop',
'isOneQuarterDesktop',
'isThreeQuartersWidescreen',
'isTwoThirdsWidescreen',
'isHalfWidescreen',
'isOneThirdWidescreen',
'isOneQuarterWidescreen',
'isNarrow',
'isNarrowMobile',
'isNarrowTablet',
'isNarrowDesktop',
'isNarrowWidescreen',
'isFull',
'isFullMobile',
'isFullTablet',
'isFullDesktop',
'isFullWidescreen',
]),
offset: PropTypes.oneOf([
'isOffsetThreeQuarters',
'isOffsetTwoThirds',
'isOffsetHalf',
'isOffsetOneThird',
'isOffsetOneQuarter',
'isOffset1',
'isOffset2',
'isOffset3',
'isOffset4',
'isOffset5',
'isOffset6',
'isOffset7',
'isOffset8',
'isOffset9',
'isOffset10',
'isOffset11',
'isOffset12',
'isOffset1Mobile',
'isOffset2Mobile',
'isOffset3Mobile',
'isOffset4Mobile',
'isOffset5Mobile',
'isOffset6Mobile',
'isOffset7Mobile',
'isOffset8Mobile',
'isOffset9Mobile',
'isOffset10Mobile',
'isOffset11Mobile',
'isOffset12Mobile',
'isOffset1Tablet',
'isOffset2Tablet',
'isOffset3Tablet',
'isOffset4Tablet',
'isOffset5Tablet',
'isOffset6Tablet',
'isOffset7Tablet',
'isOffset8Tablet',
'isOffset9Tablet',
'isOffset10Tablet',
'isOffset11Tablet',
'isOffset12Tablet',
'isOffset1Desktop',
'isOffset2Desktop',
'isOffset3Desktop',
'isOffset4Desktop',
'isOffset5Desktop',
'isOffset6Desktop',
'isOffset7Desktop',
'isOffset8Desktop',
'isOffset9Desktop',
'isOffset10Desktop',
'isOffset11Desktop',
'isOffset12Desktop',
'isOffset1Widescreen',
'isOffset2Widescreen',
'isOffset3Widescreen',
'isOffset4Widescreen',
'isOffset5Widescreen',
'isOffset6Widescreen',
'isOffset7Widescreen',
'isOffset8Widescreen',
'isOffset9Widescreen',
'isOffset10Widescreen',
'isOffset11Widescreen',
'isOffset12Widescreen',
]),
};
createClassName() {
return [
styles.column,
styles[this.props.size],
styles[this.props.offset],
this.props.className,
].join(' ').trim();
}
render() {
return (
<div
{...getCallbacks(this.props)}
className={this.createClassName()}
style={this.props.style}
>
{this.props.children}
</div>
);
}
}
|
import { createAction } from 'redux-actions'
import { NAME } from './constants'
import shop from 'api/shop'
const RECEIVE_PRODUCTS = `${NAME}/RECEIVE_PRODUCTS`
const receiveProducts = createAction(RECEIVE_PRODUCTS)
const getAllProductsAsync = () => (dispatch) =>
shop.getProducts(products => {
dispatch(receiveProducts(products))
})
export {
RECEIVE_PRODUCTS,
receiveProducts,
getAllProductsAsync,
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WorkSchema = Schema({
name: {
type: String,
required: true
},
desc: {
type: String,
required: true
},
photo: [String],
tag: [String],
pubDate: {
type: Date,
default: Date.now,
required: true
},
id: Schema.Types.ObjectId
});
module.exports = mongoose.model('Work', WorkSchema);
|
class LocalstorageController {
/*@ngInject*/
constructor($location, persistenceService) {
this.$location = $location;
this.persistenceService = persistenceService;
this.initData();
}
initData() {
this.localStorageAsText = this.persistenceService.export();
}
import() {
if (!!importData) {
this.persistenceService.import(this.importData);
}
}
clear() {
localStorage.clear();
this.initData();
}
displayAsList() {
this.listDisplayed = true;
}
back() {
this.$location.url('/stack');
}
}
export default LocalstorageController;
|
describe('Optimistic Cache', function () {
var $q = null;
var $rootScope = null;
var optimisticCache = null;
beforeEach(module('rt.optimisticcache'));
beforeEach(inject(function ($injector) {
$q = $injector.get('$q');
$rootScope = $injector.get('$rootScope');
optimisticCache = $injector.get('optimisticCache');
}));
it('Adds a toScope method', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
assert.isFunction(promise.toScope);
});
it('Scope gets pre-filled if we already have a cached copy', function () {
// Fill cache
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve({
id: 123
});
$rootScope.$digest();
// Request it again somewhere else
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
// Should be on scope now
var scope = {};
promise.toScope(scope, 'test');
assert.equal(scope.test.id, 123);
// Scope gets updated when results come in
deferred.resolve({
id: 124
});
$rootScope.$digest();
assert.equal(scope.test.id, 124);
});
it('Updates scope objects in place', function () {
var result = null;
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
promise.then(function (obj) {
result = obj;
});
deferred.resolve({
id: 1,
name: 'Ruben'
});
var scope = {};
var result2 = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
promise.toScope(scope, 'person').then(function (obj) {
result2 = obj;
assert.equal(result2, result);
});
assert.equal(scope.person, result);
deferred.resolve({ id: 1, name: 'Ruben' });
assert.equal(result2, result);
assert.equal(scope.person, result);
});
it('Updates scope arrays in place', function () {
var result = null;
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
promise.then(function (obj) {
result = obj;
});
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
var scope = {};
var result2 = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
promise.toScope(scope, 'people').then(function (obj) {
result2 = obj;
assert.equal(result2, result);
});
assert.equal(scope.people, result);
deferred.resolve([
{ id: 1, name: 'Test 2' },
{ id: 2, name: 'Test 3' }
]);
assert.equal(result2, result);
assert.equal(scope.people, result);
});
it('Uses results from getAll to pre-populate get', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
$rootScope.$digest();
var scope = {};
var result = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test/1');
promise.toScope(scope, 'person').then(function (obj) {
result = obj;
});
assert.equal(scope.person.name, 'Ruben');
deferred.resolve({ id: 1, name: 'New' });
$rootScope.$digest();
assert.equal(result.name, 'New');
assert.equal(scope.person, result);
});
it('Can disable pre-populate', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test', {
populateChildren: false
});
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
$rootScope.$digest();
var scope = {};
var result = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test/1');
promise.toScope(scope, 'person').then(function (obj) {
result = obj;
});
// Expect a cache miss
assert.equal(scope.person, undefined);
deferred.resolve({ id: 1, name: 'New' });
$rootScope.$digest();
assert.equal(result.name, 'New');
assert.equal(scope.person, result);
});
it('Can expire caches', function () {
// Fill cache
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve({
id: 123
});
$rootScope.$digest();
// Clear cache
optimisticCache.clear();
// Request it again somewhere else
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
// Should not be on the scope, it's not cached anymore
var scope = {};
promise.toScope(scope, 'test');
assert.equal(scope.test, undefined);
// Scope gets updated when results come in
deferred.resolve({
id: 124
});
$rootScope.$digest();
assert.equal(scope.test.id, 124);
});
it('Can use different ID field');
});
|
const fs = require("fs");
const path = require("path");
const https = require("https");
const url = require("url");
const replace = require("replace-in-file");
module.exports = () => {
let cssPath = path.join(process.cwd(), "./node_modules/antd/dist/antd.css");
const options = {
files: ["node_modules/antd/dist/*.css"],
from: /https:\/\/at\.alicdn\.com\/t\//g,
to: "./"
};
console.log("download antd's font file...");
let cssContent = fs.readFileSync(cssPath, {
encoding: "utf8"
});
const distDir = path.join(process.cwd(), "./node_modules/antd/dist");
let urlRegex = /https:\/\/at\.alicdn\.com\/t\/font_[_a-zA-Z0-9]+\.(eot|woff|ttf|svg)\b/g;
let fonts = new Set(cssContent.match(urlRegex));
let downloadAll = [];
for (let f of fonts) {
downloadAll.push(
new Promise((resolve, reject) => {
download(
f,
path.join(distDir, path.parse(url.parse(f).path).base),
err => {
if (err) {
reject(err);
}
resolve();
}
);
})
);
}
return Promise.all(downloadAll)
.then(() => replace(options))
.then(changedfiles => {
console.log("modified files:", changedfiles.join(", "));
})
.catch(err => {
console.error(err);
throw err;
});
};
function download(url, dist, callback) {
let file = fs.createWriteStream(dist);
https
.get(url, function(response) {
response.pipe(file);
file.on("finish", function() {
file.close(); // close() is async, call cb after close completes.
callback();
});
})
.on("error", function(err) {
// Handle errors
fs.unlink(dist); // Delete the file async. (But we don't check the result)
if (callback) callback(err);
});
}
|
const webpack = require('webpack');
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
module.exports = {
entry: {
app: './src/js/main.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_module/],
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-sprite-loader',
options: {
extract: true,
spriteFilename: 'icons.svg'
}
},
'svgo-loader'
]
}
]
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
]),
new SpriteLoaderPlugin()
]
};
|
module.exports = function(mongoose) {
var Comment = new mongoose.Schema({
userId: { type: String },
firstName: { type: String },
lastName: { type: String },
comment: { type: String },
date: { type: Date } // When the comment was added
});
var Like = new mongoose.Schema({
userId: { type: String },
firstName: { type: String },
lastName: { type: String },
date: { type: Date } // When the like was added
});
var PhotoSchema = new mongoose.Schema({
userId: { type: String },
firstName: { type: String }, //
lastName: { type: String }, //
photoUrl: { type: String },
caption: { type: String },
dateTaken: { type: Date },
removed: {type: String}, //0-not removed, 1-removed
photoWidth: { type: String },
photoHeight: { type: String },
comments: [Comment],
likes: [Like]
});
var Photo = mongoose.model('Photo', PhotoSchema);
//OK
var addPhoto = function(userId, firstName, lastName, photoUrl, caption,photoWidth,photoHeight, callback) {
var photo = new Photo({
userId: userId,
firstName: firstName,
lastName: lastName,
photoUrl: photoUrl,
caption: caption,
dateTaken: new Date(),
photoWidth: photoWidth,
photoHeight: photoHeight,
removed: 0
});
photo.save(function(err) {
if (err) {
callback(false);
console.log('Error adding the photo: ' + err);
}else{
callback(true);
console.log('Photo was added');
}
});
}
//OK (photo is not deleted from db.. only the flag 'removed' is set to '1' (1 means deleted)
var removePhoto = function(photo, callback) {
if ( null == photo ) return;
photo.removed ="1";
photo.save(function(err) {
if (err) {
callback(false);
console.log('Error deleting the photo: ' + err);
}else{
callback(true);
console.log('Photo was deleted');
}
});
}
//OK
var findById = function(photoId, callback) {
Photo.findOne({_id:photoId}, function(err,doc) {
callback(doc);
});
}
//OK
var getUserPhotos = function(userId, callback) {
Photo.find({userId:userId, removed: "0"}, {}, {sort: {dateTaken: -1}}, function(err,doc) { //check
callback(doc);
});
}
//returns:
/*
[
{
"_id": "53ff492d49aa9e681b000004",
"photoUrl": "urllllllllllllllll",
"caption": "captionnnnnnnnnn",
"dateTaken": "2014-08-28T15:22:21.220Z",
"removed": "0",
"__v": 0,
"likes": [],
"comments": []
},
...
]
*/
//OK
var getAllPhotos = function(callback) {
Photo.find({}, {}, {sort: {dateTaken: -1}}, function(err,doc) { //check
callback(doc);
});
}
//OK
var getPhotosByUsers = function(usersIdArray, callback) { //users = id1 id2 ...
Photo.find( {userId : {$in : usersIdArray }, removed: 0}, {} , {sort: {dateTaken: -1}} , function(err,result) {
callback(result);
});
}
//OK
var addComment = function( photo, userId, firstName, lastName, comment, callback ) {
var newComment = {
userId: userId,
firstName: firstName,
lastName: lastName,
comment: comment,
date: new Date()
};
photo.comments.push(newComment);
photo.save(function (err) {
if (err) {
console.log('Error adding a comment: ' + err);
callback(false);
}else{
console.log('Comment was added');
callback(true);
}
});
};
//OK
var addOrRemoveLike = function( photo, userId, firstName, lastName, callback ) {
var newLike = {
userId: userId,
firstName: firstName,
lastName: lastName,
date: new Date()
};
var hasLikeFromUser = false;
if ( null != photo.likes ){
photo.likes.forEach(function(like) {
if ( like.userId == userId ) {
hasLikeFromUser = true;
photo.likes.remove(like);
console.log('Like was removed');
photo.save();
}
});
}
if(!hasLikeFromUser){
photo.likes.push(newLike);
photo.save(function (err) {
if (err) {
console.log('Error adding like: ' + err);
callback(false);
}else{
console.log('Like was added');
callback(true);
}
});
}else{
callback(true);
}
};
return {
findById: findById,
addPhoto: addPhoto,
removePhoto: removePhoto,
getUserPhotos: getUserPhotos,
getPhotosByUsers: getPhotosByUsers,
addComment: addComment,
addOrRemoveLike: addOrRemoveLike,
getAllPhotos: getAllPhotos,
Photo: Photo
}
}
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "keyserv_solutions");
|
"use strict";
(function (socket_path, thread_id) {
var socket = io(socket_path)
, thread_id = 6
, commentLists = []
, commentBox;
socket.emit('comment/list', {thread_id: thread_id});
socket.on('user', function (user) {
var comments = [];
var submitCallback = function (replyTo, body) {
socket.emit('comment/post', {body: body, thread_id: thread_id, replyTo: replyTo});
};
var likeCallback = function (id) {
socket.emit('comment/like', {comment_id: id});
};
/**
* @param integer commentId
* @param integer commentReplyId The replyId of commentId
*/
var getRepliesCallback = function (commentId, commentReplyId) {
var reset = false;
// If the trail is already open then we want to close it
if (commentLists[commentId] !== undefined) {
reset = true;
}
// Delete all list after the list matching commentReplyId
for (var id in commentLists) {
// If the id matches the commentReplyId then all loops going
// forward will delete the lists
if (id === commentReplyId) {
commentLists.length = parseInt(id) + 1;
break;
}
}
if (reset === false) {
socket.emit('comment/list', {commentId: commentId});
} else {
commentBox.setState({commentLists: commentLists});
}
};
var renderList = function (list) {
commentBox = React.renderComponent(
CommentBox({
key: 'CommentBox',
user: user,
getRepliesCallback: getRepliesCallback,
likeCallback: likeCallback,
submitCallback: submitCallback,
initialCommentLists: list
}),
document.getElementById('CommentListContainer')
);
};
socket.on('comment/list', function (data) {
commentLists[data.commentId] = data.comments;
renderList(commentLists);
});
socket.on('comment/replies', function (data) {
commentLists[data.commentId] = data.comments;
commentBox.setState({commentLists: commentLists});
});
socket.on('comment/post/confirmation', function (data) {
commentLists[data.replyTo].unshift(data.comment);
commentBox.setState({commentLists: commentLists});
});
});
window.socket;
})(socket_path, thread_id);
|
/**
* <http://stackoverflow.com/a/5158301>
*/
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
|
var path = require('path');
var webpack = require('webpack');
var writeStats = require('./utils/writeStats');
var notifyStats = require('./utils/notifyStats');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = 'localhost';
var port = parseInt(process.env.PORT) + 1 || 3001;
module.exports = {
devtool: 'eval-source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'webpack-dev-server/client?http://' + host + ':' + port,
'webpack/hot/only-dev-server',
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[hash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: 'http://' + host + ':' + port + '/dist/'
},
module: {
loaders: [
{ test: /\.(jpe?g|png|gif|svg)$/, loader: 'url', query: {limit: 10240} },
{ test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel?stage=0&optional=runtime&plugins=typecheck']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true' }
]
},
progress: true,
resolve: {
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js']
},
plugins: [
// hot reload
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin([/\.json$/]),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: true,
__DEVTOOLS__: true // <-------- DISABLE redux-devtools HERE
}),
// stats
function () {
this.plugin('done', notifyStats);
},
function () {
this.plugin('done', function(stats) {
writeStats.call(this, stats, 'dev');
});
}
]
};
|
'use strict';
const _ = require('lodash');
const EntityHelper = require('../entity_helper');
const ExpenseClaim = require('../../entities/accounting/expenseclaim')
.ExpenseClaim;
const ExpenseClaims = EntityHelper.extend({
constructor: function(application, options) {
EntityHelper.call(
this,
application,
Object.assign({ entityPlural: 'ExpenseClaims' }, options)
);
},
newExpenseClaim: function(data, options) {
return new ExpenseClaim(this.application, data, options);
},
getExpenseClaims: function(options) {
return this.getEntities(this.setUpOptions(options));
},
getExpenseClaim: function(id) {
return this.getExpenseClaims({ id }).then(expenseClaims =>
_.first(expenseClaims)
);
},
saveExpenseClaims: function(expenseClaims, options) {
return this.saveEntities(expenseClaims, this.setUpOptions(options));
},
setUpOptions: function(options) {
const self = this;
const clonedOptions = _.clone(options || {});
clonedOptions.entityPath = 'ExpenseClaims';
clonedOptions.entityConstructor = data => self.newExpenseClaim(data);
return clonedOptions;
},
});
module.exports = ExpenseClaims;
|
// ==UserScript==
// @name SteamGifts GA input
// @description Adds input on top menu where you can enter 5characters of GA id and it will open the GA page for you.
// @author Bladito
// @version 1.0.0
// @homepageURL https://greasyfork.org/en/users/55159-bladito
// @match https://www.steamgifts.com/*
// @namespace Bladito/sg-ga-input
// @require http://code.jquery.com/jquery-latest.js
// @grant GM_addStyle
// ==/UserScript==
(function($) {
'use strict';
var $input = $('<input id="bsg-ga-input">');
$input.on('input', function(event) {
var value = event.target.value;
if (value.length === 5) {
var url = 'https://www.steamgifts.com/giveaway/' + value + '/';
$.get(url, function(data) {
if ($(data).find('.sidebar__navigation__item__name').text().indexOf('Entries') > -1) { // it is a giveaway page
window.open(url, '_blank');
$('#bsg-ga-input').removeClass('bsg-invalid');
} else {
$('#bsg-ga-input').addClass('bsg-invalid');
}
});
}
});
$('.nav__left-container').append($input);
addStyles();
//---------------------------------------------------------------------------------
function addStyles() {
GM_addStyle('#bsg-ga-input { ' +
'width: 100px;' +
'color: white;' +
'background-color: #3d434f;' +
'border: 1px solid #6e7788;' +
'}');
GM_addStyle('#bsg-ga-input:focus { ' +
'color: black;' +
'background-color: white;' +
'}');
GM_addStyle('#bsg-ga-input.bsg-invalid { ' +
'border: 1px solid red;' +
'}');
GM_addStyle('#bsg-ga-input.bsg-invalid:focus { ' +
'background-color: #ffd2d2;' +
'border: 1px solid red;' +
'}');
}
})(jQuery);
|
'use strict';
(function(module) {
function MyProject (proj) {
for (let keys in proj) {
this[keys] = proj[keys]
}
}
MyProject.allProjects = [];
MyProject.prototype.toHtml = function() {
var htmlTemplate = $('#template').html();
var template = Handlebars.compile(htmlTemplate);
return template(this);
};
MyProject.loadAll = function(project) {
project.forEach(function(ele) {
MyProject.allProjects.push(new MyProject(ele))
});
}
MyProject.getAll = function() {
if (localStorage.projects) {
var lStorageMyProjects = JSON.parse(localStorage.getItem('projects'));
MyProject.loadAll(lStorageMyProjects)
MyProject.showProjects(lStorageMyProjects)
} else {
$.getJSON('./data/projects.json').then(
function(data) {
localStorage.setItem('projects', JSON.stringify(data))
var lData = JSON.parse(localStorage.getItem('projects'));
MyProject.loadAll(lData);
MyProject.showProjects(lData)
}
);
}
};
MyProject.displayTheGroupProjects = function() {
return MyProject.allProjects.map(function(projects2) {
return projects2
})
.reduce(function(acc, curr) {
if (acc.indexOf(curr) === -1) {
acc.push(curr)
}
return acc;
}, []);
}
//MyProject.displayTheGroupProjects();
module.MyProject = MyProject;
})(window);
|
var dir_647e010a77631e7624f52ccf2ba3318e =
[
[ "html", "dir_04014538701d9c618e4a0af4f034e730.html", "dir_04014538701d9c618e4a0af4f034e730" ]
];
|
import React from 'react';
import Comment from './comment';
export default class CommentList extends React.Component {
render() {
var commentNodes = this.props.data.map(function(comment){
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
}
|
import HalAdapter from "ember-data-hal-9000/adapter";
import DS from "ember-data";
import Ember from "ember";
import config from "../config/environment";
let accessToken;
export function setAccessToken(token) {
accessToken = token;
}
export function getAccessToken() {
return accessToken;
}
export default HalAdapter.extend({
host: config.apiBaseUri,
headers: Ember.computed(function(){
if (!getAccessToken()) {
return {};
}
return {
'Authorization': 'Bearer ' + getAccessToken()
};
}).volatile(),
pathForType: function(type){
if (type === 'stack') {
type = 'account';
}
if(type === 'criterion') {
return 'criteria';
}
return this._super(type);
},
ajaxError: function(jqXHR){
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var payload = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError({
message: payload.message
});
} else {
return error;
}
}
});
|
export default {
el: {
colorpicker: {
confirm: 'Qabul qilish',
clear: 'Tozalash'
},
datepicker: {
now: 'Hozir',
today: 'Bugun',
cancel: 'Bekor qilish',
clear: 'Tozalash',
confirm: 'Qabul qilish',
selectDate: 'Kunni tanlash',
selectTime: 'Soatni tanlash',
startDate: 'Boshlanish sanasi',
startTime: 'Boshlanish vaqti',
endDate: 'Tugash sanasi',
endTime: 'Tugash vaqti',
prevYear: 'Oʻtgan yil',
nextYear: 'Kelgusi yil',
prevMonth: 'Oʻtgan oy',
nextMonth: 'Kelgusi oy',
year: 'Yil',
month1: 'Yanvar',
month2: 'Fevral',
month3: 'Mart',
month4: 'Aprel',
month5: 'May',
month6: 'Iyun',
month7: 'Iyul',
month8: 'Avgust',
month9: 'Sentabr',
month10: 'Oktabr',
month11: 'Noyabr',
month12: 'Dekabr',
week: 'Hafta',
weeks: {
sun: 'Yak',
mon: 'Dush',
tue: 'Sesh',
wed: 'Chor',
thu: 'Pay',
fri: 'Jum',
sat: 'Shan'
},
months: {
jan: 'Yan',
feb: 'Fev',
mar: 'Mar',
apr: 'Apr',
may: 'May',
jun: 'Iyun',
jul: 'Iyul',
aug: 'Avg',
sep: 'Sen',
oct: 'Okt',
nov: 'Noy',
dec: 'Dek'
}
},
select: {
loading: 'Yuklanmoqda',
noMatch: 'Mos maʼlumot yoʻq',
noData: 'Maʼlumot yoʻq',
placeholder: 'Tanladizngiz'
},
cascader: {
noMatch: 'Mos maʼlumot topilmadi',
loading: 'Yuklanmoqda',
placeholder: 'Tanlash',
noData: 'Maʼlumot yoʻq'
},
pagination: {
goto: 'Oʻtish',
pagesize: '/sahifa',
total: 'Barchasi {total} ta',
pageClassifier: ''
},
messagebox: {
title: 'Xabar',
confirm: 'Qabul qilish',
cancel: 'Bekor qilish',
error: 'Xatolik'
},
upload: {
deleteTip: 'Oʻchirish tugmasini bosib oʻchiring',
delete: 'Oʻchirish',
preview: 'Oldin koʻrish',
continue: 'Davom qilish'
},
table: {
emptyText: 'Boʻsh',
confirmFilter: 'Qabul qilish',
resetFilter: 'Oldingi holatga qaytarish',
clearFilter: 'Jami',
sumText: 'Summasi'
},
tree: {
emptyText: 'Maʼlumot yoʻq'
},
transfer: {
noMatch: 'Mos maʼlumot topilmadi',
noData: 'Maʼlumot yoʻq',
titles: ['1-jadval', '2-jadval'],
filterPlaceholder: 'Kalit soʻzni kiriting',
noCheckedFormat: '{total} ta element',
hasCheckedFormat: '{checked}/{total} ta belgilandi'
},
image: {
error: 'Xatolik'
},
pageHeader: {
title: 'Orqaga'
},
popconfirm: {
confirmButtonText: 'Yes', // to be translated
cancelButtonText: 'No' // to be translated
},
empty: {
description: 'Boʻsh'
}
}
};
|
$(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
}
updateWidgets();
function iterate() {
console.log("Currentwidget:", currentWidget)
var widget_name = widgets[currentWidget];
console.log("Name:", widget_name)
$.ajax({
url: '/widgets-' + widget_name + '.html',
}).success(function(result) {
var template = Handlebars.compile(result);
$.ajax({
url: '/widgets-' + widget_name + '.json',
}).success(function(result) {
context = result;
var html = template(context);
$(".view").empty().append(html);
}).always(function(result) {
// setTimeout(iterate, 2000);
});
});
// setTimeout(iterate, 2000);
currentWidget += 1;
if(currentWidget >= widgets.length) {
currentWidget = 0;
}
}
});
|
const path = require('path')
const execa = require('execa')
const logger = require('./lib/logger')
const { exampleAppsToRun } = require('./lib/paths')
const { createBundle } = require('./lib/bundle')
const bundle = createBundle()
const executeTest = (projectPath) => {
// we change current directory
process.chdir(projectPath)
// reading package.json
const projectPkg = require(path.join(projectPath, 'package.json'))
if (!projectPkg.name) projectPkg.name = 'unknown'
if (!projectPkg.version) projectPkg.version = 'unknown'
logger.log()
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
logger.log('='.repeat(20), `${projectPkg.name}@${projectPkg.version}`, 'in', projectPath, '='.repeat(20))
logger.log()
// then we install it in the repo
logger.log('ensuring all dependencies of target project are installed')
logger.log()
execa.sync('npm', ['ci'], { cwd: projectPath })
logger.log()
logger.log('installing bundled version of ts-jest')
logger.log()
execa.sync('npm', ['install', '--no-package-lock', '--no-shrinkwrap', '--no-save', bundle], { cwd: projectPath })
logger.log()
// then we can run the tests
const cmdLine = ['npm', 'run', 'test']
const cmdIsolatedLine = ['npm', 'run', 'test-isolated']
const cmdESMLine = ['npm', 'run', 'test-esm']
const cmdESMIsolatedLine = ['npm', 'run', 'test-esm-isolated']
logger.log('starting the CommonJS tests with `isolatedModules: false` using:', ...cmdLine)
logger.log()
execa.sync(cmdLine.shift(), cmdLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the CommonJS tests with `isolatedModules: true` using:', ...cmdIsolatedLine)
logger.log()
execa.sync(cmdIsolatedLine.shift(), cmdIsolatedLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the ESM tests with `isolatedModules: false` using:', ...cmdESMLine)
logger.log()
execa.sync(cmdESMLine.shift(), cmdESMLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the ESM tests with `isolatedModules: true` using:', ...cmdESMIsolatedLine)
logger.log()
execa.sync(cmdESMIsolatedLine.shift(), cmdESMIsolatedLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
}
exampleAppsToRun.forEach((projectPath) => {
executeTest(projectPath)
})
|
/* global phantom, exports, require, console */
(function () {
'use strict';
exports.resolveUrl = function (url, verbose) {
var fs = require('fs');
// assume http if no protocol is specified
// and we're not looking at a local file
if (!url.match(/:\/\//)) {
if (!fs.exists(url)) {
url = 'http://' + url;
if (verbose) {
console.log('Missing protocol, assuming http');
}
} else if (verbose) {
console.log('"' + url + '" exists locally, using that.');
console.log('Prepend a protocol (e.g. http:// or https://) to override this behavior');
}
}
return url;
};
exports.loadWithLibs = function (url, verbose, onload, width) {
var page = require('webpage').create();
if (width) {
page.viewportSize = { width: width, height: 800 };
}
page.open(url, function (status) {
if (status !== 'success' && verbose) {
console.log('Failed to load "' + url + '"');
phantom.exit();
} else {
if(page.evaluate(function () { return typeof jQuery; }) !== 'function') {
page.injectJs('vendor/jquery-1.8.2.js');
}
if(page.evaluate(function () { return typeof _; }) !== 'function') {
page.injectJs('vendor/underscore-1.4.2.js');
}
page.injectJs('lib/obj.js');
page.injectJs('lib/css.js');
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.evaluate(function () {
/* global $ */
if(window.fullyLoaded !== true) { // do not check twice
window.fullyLoaded = false;
$(function () { window.fullyLoaded = true; });
}
});
politelyWait(
function () {
return page.evaluate(function () { return window.fullyLoaded; }) === true;
},
function () { // aka _.partial(onload, page)
// Their page got to load so now blast the newest vanilla jquery in there
page.injectJs('vendor/jquery-1.8.2.js');
page.injectJs('vendor/underscore-1.4.2.js');
onload(page);
}
);
}
});
};
function politelyWait(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = testFx(); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
// then just go ahead, we gave it some time
onReady(); //< Do what it's supposed to do once the condition is fulfilled
} else {
// Condition fulfilled (timeout and/or condition is 'true')
onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
}
}());
|
'use strict';
var gaModule = require('./gaModule'),
gaConfig = require('./gaConfig'),
gaSettingsConstant = require('./gaSettingsConstant'),
gaProvider = require('./gaProvider');
gaModule
.config(gaConfig)
.constant('$gaSettings', gaSettingsConstant)
.provider('$ga', gaProvider);
module.exports = gaModule;
|
/**
* Easy reference for key codes
*/
var KEYS = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
W: 87,
A: 65,
S: 83,
D: 68,
R: 82
};
|
(function() {
'use strict';
/**
* [BetService Serves the application with resources data and calculate result]
*
*/
function BetService($http, betHelper) {
var _self = this;
/*
* Public function
* Gets resource file data.txt to be processed
* Returns promise
*/
_self.getResourceFile = function() {
return $http.get('/resources/data.txt').then(function(response) {
return response.data;
});
};
/*
* Public function
* Returns the result for the bets
*/
_self.calculateResult = function(formattedBets) {
return betHelper.buildResultOutput(formattedBets);
};
}
BetService.$inject = ['$http', 'betHelper'];
angular.module('bettingHost')
.service('betService', BetService);
})();
|
export default function($scope, Seasons, $state){
"ngInject";
$scope.Seasons = Seasons;
$scope.selectSeason = function(season){
Seasons.setSelectedSeason(season)
$state.reload();
}
}
|
/*
* The MIT License (MIT)
* Copyright (c) 2020 Karl STEIN
*/
import { ERROR_FIELD_FORMAT } from '../errors';
import FieldError from './FieldError';
class FieldFormatError extends FieldError {
constructor(field, format, path) {
super(field, path, ERROR_FIELD_FORMAT);
this.format = format;
this.message = `"${field}" does not matches format (${format}).`;
}
}
export default FieldFormatError;
|
var Popover = ReactBootstrap.Popover;
var ButtonToolbar = ReactBootstrap.ButtonToolbar;
var OverlayTrigger = ReactBootstrap.OverlayTrigger;
var Button = ReactBootstrap.Button
var popoverInstance = (
<div style={{ height: 180 }}>
<ButtonToolbar>
<OverlayTrigger trigger="click" placement="left" overlay={<Popover title="Popover left"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="top" overlay={<Popover title="Popover top"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="bottom" overlay={<Popover title="Popover bottom"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="right" overlay={<Popover title="Popover right"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
</ButtonToolbar>
<Popover placement="right" positionLeft={200} positionTop={50} title="Popover right">
And here's some <strong>amazing</strong> content. It's very engaging. right?
</Popover>
</div>
);
ReactDOM.render(popoverInstance, mountNode);
|
/*
* Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint node: true */
module.exports = function (grunt) {
"use strict";
var common = require("./lib/common")(grunt),
build = require("./build")(grunt);
// task: write-config
grunt.registerTask("npm-install", "Install node_modules to the dist folder so it gets bundled with release", function () {
var packageJSON = grunt.file.readJSON("package.json");
delete packageJSON.devDependencies;
delete packageJSON.scripts; // we don't want to run post-install scripts in dist folder
common.writeJSON(grunt, "dist/package.json", packageJSON);
var exec = require('child_process').exec;
var done = this.async();
exec('npm install --production', { cwd: './dist' }, function(err, stdout, stderr) {
if (err) {
grunt.log.error(stderr);
done(false);
} else {
grunt.log.writeln(stdout);
done();
}
});
});
};
|
/* ========================================================================
* MZUI: doc.js
* https://github.com/easysoft/mzui
* ========================================================================
* Copyright (c) 2016 cnezsoft.com; Licensed MIT
* ======================================================================== */
$(function() {
var $fabNav = $('#fabNav'),
$partial = $('#partial'),
$tocList = $('#tocList'),
$navs = $('#navs'),
$modalHeading = $('#tocHeading'),
$headNav = $('#headNav'),
scrollTopOffset = $headNav.height() * 2 + 10;
$headNav.display({
selector: 'a:not(.brand-name)',
activeClass: 'active',
target: '#navs',
trigger: 'click',
name: 'headNav',
animate: false,
show: function() {
$partial.empty();
$('body').removeClass('has-index-content');
},
displayed: function(options) {
$('#navs > a[data-display-auto]').trigger('click');
}
});
$navs.display({
selector: 'a',
activeClass: 'active',
target: '#partial',
trigger: 'click',
targetZIndex: 'none',
name: 'navs',
show: function() {
$fabNav.addClass('disabled');
},
shown: function() {
$fabNav.removeClass('disabled');
$tocList.empty();
},
displayed: function(options) {
var $parent = $headNav.children('.active');
var parentName = $parent.data('pageName');
var parentTitle = $parent.text();
var $element = $(options.element);
var elementName = $element.attr('href').replace('doc/part/', '').replace('examples/', '');
var gaOptions = {
hitType: 'pageview',
page: window.location.pathname + '#' + parentName + '/' + elementName,
title: parentTitle + ' > ' + $element.text()
};
ga('send', gaOptions);
$fabNav.toggleClass('hidden', !$partial.find('.section').children('.heading').children('.title').length);
}
});
$('#tocBtn').display({
triggerMethod: 'toggle',
target: '#tocModal',
backdrop: true,
targetDismiss: true,
name: 'tocModal',
show: function() {
$fabNav.addClass('open').find('.btn').removeClass('primary');
if($tocList.children().length) return;
$partial.children('.section').each(function(idx) {
var $section = $(this);
var sectionId = 'section-' + idx;
$section.attr('id', sectionId);
$tocList.append('<a class="item" data-target="#' + sectionId + '">' + $section.children('.heading').find('.title').text() + '</a>')
});
$modalHeading.text($('#navs > .active').text());
},
hide: function() {
$fabNav.removeClass('open').find('.btn').addClass('primary');
}
});
$tocList.on('click', 'a', function(e) {
var $section = $($(this).data('target'));
$(window).scrollTop($section.offset().top - scrollTopOffset);
e.preventDefault();
});
$(document).on('display.displayed', function(e, display, $trigger, options) {
if(window.prettyPrint && options.$target && options.$target.find('.prettyprint').length) {
window.prettyPrint();
}
});
$('body').on($.TapName, '.btn-begin', function() {
$('#beginLink').trigger('click');
});
if(!window.localStorage.getItem('mzuiTip') && $(window).width() > 1200) {
$.messager.warning("MZUI 专为移动端设计,在移动设备上访问效果更佳。", {placement: 'top-center', targetZIndex: 3000});
window.localStorage.setItem('mzuiTip', new Date().toLocaleString());
}
});
|
export const error = (msg) => ({ error: msg })
export const success = (data) => ({ response: data })
|
define([
'./script/dbpediaQuery',
'./script/dbpediaQueryArea',
'./script/dbpediaQueryDump',
'./script/dbpediaSvc',
'./script/dbpImgHistory',
'./script/dbpImgSearch',
'./script/dbpKey',
'./script/dbpSpecies',
'./script/dbpFungi'
],
function(){})
|
import React from 'react';
import { Link } from 'react-router';
import Breadcrumbs from 'components/Breadcrumbs';
class FilesPage extends React.Component {
constructor(props) {
super(props);
}
renderBreadcrumbs(breadcrumbs) {
//console.log(breadcrumbs);
if (Array.isArray(breadcrumbs)) {
return <div style={{'paddingTop': '20px', 'paddingBottom': '20px'}}>
{breadcrumbs.map((el, i) => (
<span key={i}>{el}</span>
))}
</div>
} else {
return <div></div>;
}
}
render() {
const breadcrumbs = [
<Link to='/files'>Файловый архив</Link>,
'123'
];
return (
<div>
<Breadcrumbs items={breadcrumbs} />
<span>тут будет страница файлов</span>
</div>
);
}
}
//LoginPage.propTypes = { initialCount: React.PropTypes.number };
//LoginPage.defaultProps = { initialCount: 0 };
export default FilesPage;
|
const mongoose = require('mongoose');
const childSchema = new mongoose.Schema({ subName: String });
module.exports = childSchema;
|
// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Button, Header, Icon, Menu, Modal, Segment, Table } from 'semantic-ui-react';
import AccountsCustomJson from '../components/Accounts/CustomJSON.js';
import * as AccountActions from '../actions/account';
import * as KeyActions from '../actions/keys';
import * as ProcessingActions from '../actions/processing';
import MenuBar from './MenuBar';
import ContentBar from '../components/ContentBar';
class AccountsPage extends Component {
state = {
activeItem: 'custom_json'
};
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
if (!this.props.keys.isUser) {
return <Redirect to="/" />;
}
const { activeItem } = this.state;
let activeTab = <AccountsCustomJson {...this.props} />;
switch (activeItem) {
default: {
activeTab = <AccountsCustomJson {...this.props} />;
break;
}
}
return (
<ContentBar>
<Segment basic padded attached secondary>
<Header>
<Icon name="lab" />
<Header.Content>
Advanced Operations
<Header.Subheader>
This section can be used to perform more advanced operations using the loaded accounts.
</Header.Subheader>
</Header.Content>
</Header>
</Segment>
<Menu tabular attached>
<Menu.Item
name="custom_json"
icon="lock"
content="Custom JSON"
active={activeItem === 'custom_json'}
onClick={this.handleItemClick}
/>
</Menu>
{activeTab}
<MenuBar />
</ContentBar>
);
}
}
function mapStateToProps(state) {
return {
account: state.account,
keys: state.keys,
processing: state.processing,
hive: state.hive
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...AccountActions,
...KeyActions,
...ProcessingActions,
}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AccountsPage);
|
const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const msx = require('gulp-msx');
const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function bundle() {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8000/samples/1000box.html"
}));
bundle();
gulp.watch('./components/*.js', ['msx']);
});
gulp.task('compress', function() {
return gulp.src('static/js/Solufa.js')
.pipe(uglify({
preserveComments: 'some' // ! から始まるコメントを残すオプションを追加
}))
.pipe(rename('Solufa.min.js'))
.pipe(gulp.dest('static/js'));
});
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var lastName = root,
namespace = 'allColors.ideaColorThemes.netbeans8'.split('.');
for (var i = 0; i < namespace.length; i++) {
if (lastName[namespace[i]] === undefined) {
lastName = lastName[namespace[i]] = {};
}
}
root.allColors.ideaColorThemes.netbeans8 = factory();
}
}(this, function() {
return [
'#a1f2ac',
'#eeeeee',
'#ffffff',
'#cccccc',
'#a0a9f9',
'#ffc8c8',
'#b7b7b7',
'#ce7b00',
'#d25252',
'#868686',
'#808080',
'#ffded8',
'#ffc8bd',
'#d6d6d6',
'#cbcbcb',
'#c8f2c8',
'#baeeba',
'#bccff9',
'#f5f7f0',
'#ff0000',
'#e9e9e9',
'#f4e803',
'#eceba3',
'#ffffcc',
'#660e7a',
'#ccffcc',
'#ffcccc',
'#99ccff',
'#f49810',
'#d8d8d8',
'#ffdcdc',
'#f6ebbc',
'#ffff00'
];
}));
|
var searchData=
[
['paperfigures',['PaperFigures',['../class_paper_figures.html',1,'']]],
['parameter',['Parameter',['../class_parameter.html',1,'']]],
['pathway',['Pathway',['../class_pathway.html',1,'']]],
['pdfutil',['PdfUtil',['../class_pdf_util.html',1,'']]],
['physicalobject',['PhysicalObject',['../class_physical_object.html',1,'']]],
['polymer',['Polymer',['../class_polymer.html',1,'']]],
['population',['Population',['../class_population.html',1,'']]],
['posterfigures',['PosterFigures',['../class_poster_figures.html',1,'']]],
['process',['Process',['../class_process.html',1,'']]],
['processmetaboliteusage',['ProcessMetaboliteUsage',['../class_process_metabolite_usage.html',1,'']]],
['protein',['Protein',['../class_protein.html',1,'']]],
['proteincomplex',['ProteinComplex',['../class_protein_complex.html',1,'']]],
['proteinmonomer',['ProteinMonomer',['../class_protein_monomer.html',1,'']]]
];
|
(function() {
window.Glow = {
flash: function(type, message) {
return $(document).trigger('glow:flash', {
type: type,
message: message
});
}
};
$(document).ajaxComplete(function(evt, xhr, options) {
var message, type;
type = xhr.getResponseHeader('X-Message-Type');
message = xhr.getResponseHeader('X-Message');
if (type && message) {
return Glow.flash(type, $('<div/>').html(message).text());
}
});
window.Flash = {
fire: Glow.flash,
// convenience methods
success: function(message) {
return Glow.flash('success', message);
},
notice: function(message) {
return Glow.flash('notice', message);
},
error: function(message) {
return Glow.flash('error', message);
}
};
}).call(this);
|
export default {
uiv: {
datePicker: {
clear: 'Törlés',
today: 'Ma',
month: 'Hónap',
month1: 'január',
month2: 'február',
month3: 'március',
month4: 'április',
month5: 'május',
month6: 'június',
month7: 'július',
month8: 'augusztus',
month9: 'szeptember',
month10: 'október',
month11: 'november',
month12: 'december',
year: 'Év',
week1: 'H.',
week2: 'K.',
week3: 'Sze.',
week4: 'Cs.',
week5: 'P.',
week6: 'Szo.',
week7: 'V.'
},
timePicker: {
am: 'AM',
pm: 'PM'
},
modal: {
cancel: 'Mégse',
ok: 'OK'
},
multiSelect: {
placeholder: 'Válassz...',
filterPlaceholder: 'Keresés...'
}
}
}
|
// @flow
export default ( siteInformation: Object ) => '/graphql'
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
//Añadir el módulo de MongoDB
var mongodb = require('mongodb');
var database;
//Crea la conexión a la base de datos ColScript mediante el puerto por defecto.
var connection = mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/colscript', function(err, db){
database = db; //Almacena la información de la base de datos.
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//Con este código podemos acceder a la base de datos desde cualquier objeto req de las rutas.
app.use(function(req,res,next){
req.db = database;
next();
});
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000);
console.log("Listening on port 3000.");
module.exports = app;
|
var ConfigManager = require('./components/config_manager');
var RenderEngine = require('./components/render_engine');
var OrientationManager = require('./components/orientation_manager');
var Network = require('./components/network');
var LocalStream = require('./components/local_stream');
var DepthRender = require('./components/depth_render');
var ForwardStream = require('./components/forward_stream');
var RemoteStream = require('./components/remote_stream');
var Utils = require('./components/utils');
var Logger = require('./components/logger');
var REDUCE = 4;
var SKIP = 60;
var cm = new ConfigManager();
var re = new RenderEngine(cm);
var om = new OrientationManager();
var n = new Network(cm);
var ls = new LocalStream('ws://0.0.0.0:9090');
new DepthRender(ls, REDUCE, re, om.obtain(ls), 0);
new ForwardStream(ls, n, SKIP);
var l = new Logger(n, re, cm);
n.on('found', function(node){
node.render = new DepthRender(new RemoteStream(node), REDUCE, re, om.obtain(node), RenderEngine.SENSOR_DISTANCE);
});
n.on('lost', function(node){
node.render.stop();
om.free(node);
});
cm.initialize();
Utils.hideInactiveCursor();
n.connect();
re.start();
|
(function() {
'use strict';
var bowerFiles = require('bower-files')();
var config = require('./gulp/config');
function listFiles() {
var files = []
.concat(bowerFiles.dev().ext('js').files)
.concat([
config.sourceDir + 'app/**/*.html',
config.sourceDir + 'app/**/*.js',
]);
return files;
}
function listPreprocessors() {
var preprocessors = {};
preprocessors[config.sourceDir + 'app/**/*.html'] = ['ng-html2js'];
preprocessors[config.sourceDir + 'app/**/!(*.spec|*.mock).js'] = ['coverage'];
return preprocessors;
}
module.exports = function(karmaConfig) {
karmaConfig.set({
files: listFiles(),
browsers: ['PhantomJS'],
frameworks: ['jasmine', 'angular-filesort'],
preprocessors: listPreprocessors(),
ngHtml2JsPreprocessor: {
stripPrefix: config.sourceDir,
moduleName: 'templateCache'
},
angularFilesort: {
whitelist: [
config.sourceDir + 'app/**/!*.html',
config.sourceDir + 'app/**/!(*.spec|*.mock).js'
]
},
reporters: ['progress', 'coverage', 'html'],
coverageReporter: {
dir: config.coverageDir,
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
}
});
};
})();
|
var http = require("http");
var https = require("https");
var url = require("url");
var log = require("./logger");
var headerRE = /(.*):(.*)/
// Runs a single step within a given context
exports.run = function(context, step, callback) {
if (step.variables) {
context.updateVariables(step.variables);
}
log.debugi("step ", step);
var fullURL = context.substituteVariables(step.fullURL || step.url);
var opts = url.parse(fullURL);
opts.method = step.request || "GET";
if (step.headers) {
opts.headers = {};
for(var ix=0; ix<step.headers.length; ix++) {
var v = step.headers[ix];
var hdr = headerRE.exec(v);
opts.headers[ context.substituteVariables(hdr[1]) ] = context.substituteVariables(hdr[2]);
}
}
// So it can add cookies and the like
context.preflight(opts);
// Update content length
if (step.content && step.content.data) {
var toSend = [];
var len = 0;
for(var ix=0; ix<step.content.data.length; ix++) {
var el = step.content.data[ix];
el = context.substituteVariables(el);
len += el.length;
toSend.push(el);
}
if (!opts.headers) opts.headers = {};
opts.headers["content-length"] = len;
}
if (opts.protocol == "https") {
var proto = https;
} else {
var proto = http;
}
log.debugi("Request options ", opts);
var req = proto.request(opts);
var result = {
timing: {
created: Date.now()
}
, errors: []
};
req.on("response", function(response) {
log.debug("response");
result.statusCode = response.statusCode;
result.headers = response.headers;
result.timing.responseBegins = Date.now();
result.data = [];
response.on("data", function(data) {
log.debug("response data");
result.data.push(data);
});
response.on("error", function(err) {
errors.push("response error: "+err);
});
response.on("end", function() {
log.debug("response end");
result.timing.end = Date.now();
// Finishing processing
if (step.xtracts) {
context.xtract(step.xtracts, result);
}
callback(null, result);
});
// Set timeout on response???
});
req.on("socket", function(socket) {
socket.setMaxListeners(0);
socket.on("error", function(e) {
console.log("Socket thing "+e);
});
});
req.on("error", function(err) {
log.warning("request error ", err);
result.timing.error = Date.now();
result.errors.push(err);
//callback(err);
console.trace();
return false;
});
req.setTimeout(step.timeout, function() {
result.timing.requestTimeout = Date.now();
});
// Send any data if we have that to do
if (toSend) {
sent = [];
for(var ix=0; ix<toSend.length; ix++) {
var el = toSend[ix];
sent.push(el);
req.write( el );
}
result.sent = sent;
}
req.end();
// Return a canceler
return function() {
log.debugi("req abort function");
req.setTimeout(0, function() { });
}
}
|
// @flow
/**
* Copyright (c) 2017, Dirk-Jan Rutten
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
export {
serializeTime,
serializeTimeString,
serializeDate,
serializeDateTime,
serializeDateTimeString,
serializeUnixTimestamp,
parseTime,
parseDate,
parseDateTime
} from './formatter'
export {
validateTime,
validateDate,
validateDateTime,
validateUnixTimestamp,
validateJSDate
} from './validator'
|
'use strict'
var website = angular.module('website',['ngRoute']);
website.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: '/website/partials/home.html',
controller: 'mainCtrl'
})
});
|
/**
* The MIT License (MIT)
* Copyright (c) 2016 Krypto Fin ry and the FIMK Developers
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* */
(function () {
'use strict';
var module = angular.module('fim.base');
module.directive('fileSelect', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('change', function () {
var input = element,
numFiles = input.files ? input.files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
var event;
if (document.createEvent) {
event = document.createEvent("HTMLEvents");
event.initEvent("fileselect", true, true);
} else {
event = document.createEventObject();
event.eventType = "fileselect";
}
event.eventName = "fileselect";
if (document.createEvent) {
element[0].dispatchEvent(event);
}
else {
element[0].fireEvent("on" + event.eventType, event);
}
// input.trigger('fileselect', [numFiles, label]);
});
}
};
});
})();
|
/*
let fs = require('fs');
fs.readFile('./files/a.json','utf8',(error1,data1)=>{
console.log(data1);
fs.readFile('./files/b.json','utf8',(error2,data2)=>{
console.log(data2);
fs.readFile('./files/c.json','utf8',(error3,data3)=>{
console.log(data3);
fs.readFile('./files/d.json','utf8',(error4,data4)=>{
console.log(data4);
});
});
});
});
*/
let fs = require('fs');
let co = require('co');
let readFile = url => {
return cb => fs.readFile(url,'utf8',cb);
}
/*
yield 与 yield* 的区别在于:yield 只是返回右值,而 yield* 则将函数委托
(delegate)到另一个生成器( Generator)或可迭代的对象(如字符串、数组和类数组 arguments,以及 ES6 中的 Map、Set 等)。
*/
function(cb){
return fs.readFile('./files/a.json','utf8',cb);
}
co(function*(){
let data1 = yield readFile('./files/a.json');
console.log(data1);
let data2 = yield readFile('./files/b.json');
console.log(data2);
let data3 = yield readFile('./files/c.json');
console.log(data3);
let data4 = yield readFile('./files/d.json');
console.log(data4);
}).catch(error => console.log(error) )
|
const _ = require('lodash');
const Promise = require('bluebird');
const fs = require('fs');
const _path = require('path');
/**
* @memberOf FileUtil
* @function symlink
*
* Asynchronous {@link http://man7.org/linux/man-pages/man2/symlink.2.html|symlink(2)}.
*
* @param {Object} options
* @param {String|Buffer} options.target
* @param {String|Buffer} options.path
* @param {String} [options.type=file] The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms).
*
* Note that Windows junction points require the destination path to be absolute. When using 'junction', the target argument will automatically be normalized to absolute path.
*
* @returns {Promise<undefined>}
* @see {@link https://nodejs.org/api/fs.html#fs_fs_symlink_target_path_type_callback}
*/
var symlink = function (options) {
return new Promise(function (resolve, reject) {
try {
var target = _.get(options, 'target');
var path = _.get(options, 'path');
if (_.isString(target) || _.isBuffer(target)) {
target = _path.resolve(process.cwd(), target);
}
if (_.isString(path) || _.isBuffer(path)) {
path = _path.resolve(process.cwd(), path);
}
var symlinkArgs = [target, path];
var type = _.get(options, 'type');
if (!_.isNil(type)) {
symlinkArgs.push(type);
}
var callback = function (err) {
if (!_.isNil(err)) {
return reject(err);
}
return resolve();
};
symlinkArgs.push(callback);
return fs.symlink.apply(fs, symlinkArgs);
} catch (err) {
return reject(err);
}
});
};
module.exports = symlink;
|
import React, { PureComponent } from 'react';
import { connect } from 'react-redux';
import isFunction from 'lodash/isFunction';
import noop from 'lodash/noop';
import withTheme from 'hoc/withTheme';
import { actions } from 'modules/modal';
import Button from 'components/Button';
import { propTypes, defaultProps } from './ModalWrapper.statics';
import StyledModal, { ModalActions, ModalBackdrop } from './ModalWrapper.styled';
@withTheme
@connect(null, {
close: actions.closeModal,
})
class ModalWrapper extends PureComponent {
static defaultProps = defaultProps;
static propTypes = propTypes;
// Wrap Action with close event
withClose = (action, useReduxCloseAction = false) => () => {
const { id, close } = this.props;
const modalAction = isFunction(action) ? action : noop;
if (useReduxCloseAction) {
modalAction();
} else {
modalAction();
close(id);
}
};
getCloseEvent = () => {
const { cancelButton, onClose, onCancel, useCloseAction, useCancelAction } = this.props;
return cancelButton ? this.withClose(onCancel, useCloseAction) : this.withClose(onClose, useCancelAction);
};
handleBackgroundClick = e => {
if (e.target === e.currentTarget) {
const closeEvent = this.getCloseEvent();
closeEvent();
}
};
handleKeyPress = ({ keyCode }) => {
if (keyCode === 27) {
const closeEvent = this.getCloseEvent();
closeEvent();
}
};
getButtonType = (type = '') => ({
alert: type === 'alert',
info: type === 'info',
success: type === 'success',
noAccent: type === 'noAccent',
});
componentDidMount() {
document.addEventListener('keyup', this.handleKeyPress);
}
componentWillUnmount() {
document.removeEventListener('keyup', this.handleKeyPress);
}
render() {
const {
id,
buttons,
children,
collapse,
cancelText,
closeText,
cancelButton,
closeButton,
footNote,
useCloseAction,
useCancelAction,
locked,
theme,
title,
type,
width,
valid,
onCancel,
onClose,
transitionEnter,
transitionLeave,
} = this.props;
const modalButtons = [];
if (closeButton) {
modalButtons.push({
action: onClose,
useReduxAction: useCloseAction,
text: closeText,
type: type || 'info',
disabled: !valid,
});
}
if (cancelButton) {
modalButtons.push({
action: onCancel,
useReduxAction: useCancelAction,
type: 'noAccent',
text: cancelText,
});
}
const modalActions = [...buttons, ...modalButtons];
return (
<ModalBackdrop
key={id}
onClick={!locked ? this.handleBackgroundClick : noop}
theme={theme}
transitionEnter={transitionEnter}
transitionLeave={transitionLeave}
>
<StyledModal
className="Modal"
style={{ width: width ? `${width}px` : '100%' }}
type={type}
collapse={collapse}
theme={theme}
transitionEnter={transitionEnter}
transitionLeave={transitionLeave}
>
{title && <div className="Modal__header">{title}</div>}
<div className="Modal__content">{children}</div>
{modalActions.length > 0 && (
<div className="Modal__footer">
<ModalActions className="Modal__actions" length={modalActions.length}>
{modalActions.map(({ action, type, text, useReduxAction, ...props }, i) => (
<Button
className="Modal__action"
key={i}
onClick={this.withClose(action, useReduxAction)}
{...this.getButtonType(type)}
{...props}
>
{text}
</Button>
))}
</ModalActions>
</div>
)}
{footNote && <div className="Modal__footNote">{footNote}</div>}
</StyledModal>
</ModalBackdrop>
);
}
}
export default ModalWrapper;
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.15-3-16
description: >
Array.prototype.lastIndexOf - value of 'length' is a string which
is able to be converted into hex number
includes: [runTestCase.js]
---*/
function testcase() {
var obj = { 2573: 2573, 2574: 0x000A0E, length: "0x000A0E" };
return Array.prototype.lastIndexOf.call(obj, 2573) === 2573 &&
Array.prototype.lastIndexOf.call(obj, 0x000A0E) === -1;
}
runTestCase(testcase);
|
var tool = require('../tool');
var mapping = require('../mapping');
var factory = require('../io/factory');
//protobuf映射
function callbackMapping(entity, tag) {
switch (tag) {
case "GetUserInfoOutput":
var userInfo = new RongIMClient.UserInfo();
userInfo.setUserId(entity.userId);
userInfo.setUserName(entity.userName);
userInfo.setPortraitUri(entity.userPortrait);
return userInfo;
case "GetQNupTokenOutput":
return {
deadline: util.int64ToTimestamp(entity.deadline),
token: entity.token
};
case "GetQNdownloadUrlOutput":
return {
downloadUrl: entity.downloadUrl
};
case "CreateDiscussionOutput":
return entity.id;
case "ChannelInfoOutput":
var disInfo = new RongIMClient.Discussion();
disInfo.setCreatorId(entity.adminUserId);
disInfo.setId(entity.channelId);
disInfo.setMemberIdList(entity.firstTenUserIds);
disInfo.setName(entity.channelName);
disInfo.setOpen(RongIMClient.DiscussionInviteStatus.setValue(entity.openStatus));
return disInfo;
case "GroupHashOutput":
return entity.result;
case "QueryBlackListOutput":
return entity.userIds;
default:
return entity;
}
}
function MessageCallback(error) {
var timeoutMillis, me = this;
this.timeout = null;
this.onError = null;
if (error && typeof error == "number") {
timeoutMillis = error
} else {
timeoutMillis = 6000;
this.onError = error;
}
this.resumeTimer = function () {
if (timeoutMillis > 0 && !this.timeout) {
this.timeout = setTimeout(function () {
me.readTimeOut(true);
}, timeoutMillis)
}
}
}
MessageCallback.prototype = {
pauseTimer: function () {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null
}
}, readTimeOut: function (isTimeout) {
if (isTimeout && this.onError) {
this.onError(RongIMClient.callback.ErrorCode.TIMEOUT)
} else {
this.pauseTimer()
}
}
};
//发送PublishMessage消息回调类
function PublishCallback(cb, _timeout) {
MessageCallback.call(this, _timeout);
this.done = cb || function () {
};
this.fail = _timeout || function () {
};
}
tool.inherit(PublishCallback, MessageCallback);
PublishCallback.prototype.process = function (_staus, _serverTime, _msg) {
this.readTimeOut();
if (_staus == 0) {
if (_msg) {
//把发送的消息发送状态改为已接收
_msg.setSentStatus(RongIMClient.SentStatus.RECEIVED)
}
this.done();
} else {
this.fail(RongIMClient.SendErrorStatus.setValue(_staus));
}
};
PublishCallback.prototype.readTimeOut = function (x) {
PublishCallback.super_.prototype.readTimeOut.call(this, x)
};
//发送QueryMessage消息回调类
function QueryCallback(cb, _timeout) {
MessageCallback.call(this, _timeout);
this.done = cb || function () {
};
this.fail = _timeout || function () {
};
}
tool.inherit(QueryCallback, MessageCallback);
QueryCallback.prototype.process = function (status, data, serverTime, pbtype) {
this.readTimeOut();
if (pbtype && data && status == 0) {
try {
data = callbackMapping(Modules[pbtype].decode(data), pbtype);
} catch (e) {
this.fail(RongIMClient.callback.ErrorCode.UNKNOWN_ERROR);
return;
}
if ("GetUserInfoOutput" == pbtype) {
//pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列
mapping.userInfoMapping[data.getUserId()] = data;
}
this.done(data);
} else {
status > 0 ? this.fail(status) : this.done(status)
}
};
QueryCallback.prototype.readTimeOut = function (x) {
QueryCallback.super_.prototype.readTimeOut.call(this, x)
};
//连接回调类
function ConnectAck(cb, _timeout, context) {
MessageCallback.call(this, _timeout);
this.context = context;
this.done = cb || function () {
};
this.fail = _timeout || function () {
};
}
tool.inherit(ConnectAck, MessageCallback);
ConnectAck.prototype.process = function (status, userId) {
this.readTimeOut();
if (status == 0) {
mapping.userId = this.context.userId = userId;
if (!RongIMClient.isNotPullMsg) {
this.context.syncTime();
}
if (mapping.reconnectSet.onSuccess) {
mapping.reconnectSet.onSuccess(userId);
try {
delete mapping.reconnectSet.onSuccess;
} catch (e) {
}
} else {
this.done(userId);
}
factory.getInstance().fire("StatusChanged", 0);
factory.getInstance()._doQueue()
} else if (status == 6) {
var that = this;
ConnectAck.redirect(this.context.token, this.context.appId, function () {
that.context.clearHeartbeat();
ConnectAck.redirect();
that.context.channel.socket.fire("StatusChanged", 2);
}, function () {
that.fail();
}, false);
} else {
if (mapping.reconnectSet.onError) {
mapping.reconnectSet.onError(RongIMClient.ConnectErrorStatus.setValue(status));
delete mapping.reconnectSet.onError;
} else {
this.fail(RongIMClient.ConnectErrorStatus.setValue(status))
}
}
};
ConnectAck.prototype.readTimeOut = function (x) {
ConnectAck.super_.prototype.readTimeOut.call(this, x)
};
ConnectAck.redirect = function () {
};
module.exports = {
MessageCallback: MessageCallback,
PublishCallback: PublishCallback,
QueryCallback: QueryCallback,
ConnectAck: ConnectAck
};
|
import { $, ensureEventExists } from "../api/jquery.js";
import { TD } from "../api/td.js";
import { ensurePropertyExists } from "../api/utils.js";
function reloadScheduledColumn() {
const column = Object.values(TD.controller.columnManager.getAll()).find(column => column.model.state.type === "scheduled");
if (column) {
setTimeout(function() {
column.reloadTweets();
}, 1000);
}
}
/**
* Works around scheduled tweets not showing up sometimes after being sent.
*/
export default function() {
ensurePropertyExists(TD, "controller", "columnManager", "getAll");
ensureEventExists(document, "dataTweetSent");
$(document).on("dataTweetSent", function(e, data) {
if ("request" in data && "scheduledDate" in data.request) {
reloadScheduledColumn();
}
});
};
|
import gulp from 'gulp';
import path from 'path';
import runSequence from 'run-sequence';
import { spawn } from 'child_process';
const pkg = require('../package.json');
function zip(src, dest) {
const current_process = spawn('7z', ['a', '-tzip', dest, src], {cwd: './tmp'});
let is_error = false;
return new Promise((resolve, reject) => {
current_process.stdout.on('data', function(msg) {
console.log(msg.toString());
});
current_process.stderr.on('data', function(msg) {
console.error(msg.toString());
is_error = true;
});
current_process.on('close', function(code) {
if (is_error) return reject();
return resolve();
});
});
}
function releaseFile(platform) {
return `Championify-${platform}-${pkg.version}.zip`;
}
gulp.task('zip:osx', function(cb) {
const src = `${pkg.name}.app`;
const dest = path.join('../releases', releaseFile('OSX'));
return zip(src, dest, cb);
});
gulp.task('zip:win', function(cb) {
const src = pkg.name;
const dest = path.join('../releases', releaseFile('WIN'));
return zip(src, dest, cb);
});
gulp.task('zip:all', function(cb) {
return runSequence(['zip:osx', 'zip:win'], cb);
});
|
import logger from '../../logging';
export default logger.child({module: 'resources', resource: 'account'});
|
/* eslint-disable max-len, camelcase */
'use strict';
exports.seed = function(knex) {
return knex('tasks').del()
.then(() => {
return knex('tasks').insert([{
id: 1,
column_index: 1,
short_description: 'Prepare Day 1 of Angular Curriculum',
long_description: 'Focus on getting students with the purpose of ' +
'frontend development in a goal to fully understand the importance ' +
'of planning your UI before implementation.',
column_id: 2,
is_archived: false,
created_at: new Date('2016-10-25 14:26:16 UTC'),
updated_at: new Date('2016-10-25 14:26:16 UTC')
}, {
id: 2,
column_index: 1,
short_description: 'Prepare Day 2 of Angular Curriculum',
long_description: 'Focus on taking students to understand and build ' +
'the initial view based on the UI plan.',
column_id: 1,
is_archived: false,
created_at: new Date('2016-10-25 14:26:16 UTC'),
updated_at: new Date('2016-10-25 14:26:16 UTC')
}]);
})
.then(() => {
return knex.raw(
"SELECT setval('tasks_id_seq', (SELECT MAX(id) FROM tasks));"
);
});
};
|
var class_property_two =
[
[ "SetUp", "class_property_two.html#aa3ab39cf4e6c751cb0788c575bf92ca2", null ],
[ "TearDown", "class_property_two.html#aa4ffb2b9dddeba69f0f9baf133f06ef2", null ]
];
|
var base = require('../base')
var ERROR_LEVEL = base.ERROR_LEVEL
var Class = base.Class
var RuleChecker = base.RuleChecker
var helper = require('./helper');
module.exports = global.FEDUseSingleQuotation = new Class(RuleChecker, function() {
this.__init__ = function(self) {
self.id = 'single-quotation'
self.errorLevel = ERROR_LEVEL.WARNING
self.errorMsg = 'replace " with \' in "${selector}"'
}
this.check = function(self, rule, config) {
if (self._findDouble(rule.value))
return false
return true
}
this.fix = function(self, rule, config) {
if (self._findDouble(rule.value))
rule.fixedValue = rule.fixedValue.replace(/"/g, "'")
}
this._findDouble = function(self, value) {
return value.indexOf('"') != -1
}
this.__doc__ = {
"summary":"使用单引号",
"desc":"CSS的属性取值一律使用单引号<code>'</code>, 不允许使用双引号"
}
})
|
var https = require('https');
var url = require('url');
module.exports = function (options) {
options = options || {};
var agent = new https.Agent(options);
return agent;
};
|
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Breadcrumbs from '@material-ui/core/Breadcrumbs';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
const useStyles = makeStyles(theme => ({
root: {
justifyContent: 'center',
flexWrap: 'wrap',
},
paper: {
padding: theme.spacing(1, 2),
},
}));
function handleClick(event) {
event.preventDefault();
alert('You clicked a breadcrumb.');
}
export default function CollapsedBreadcrumbs() {
const classes = useStyles();
return (
<Paper elevation={0} className={classes.paper}>
<Breadcrumbs maxItems={2} aria-label="breadcrumb">
<Link color="inherit" href="#" onClick={handleClick}>
Home
</Link>
<Link color="inherit" href="#" onClick={handleClick}>
Catalog
</Link>
<Link color="inherit" href="#" onClick={handleClick}>
Accessories
</Link>
<Link color="inherit" href="#" onClick={handleClick}>
New Collection
</Link>
<Typography color="textPrimary">Belts</Typography>
</Breadcrumbs>
</Paper>
);
}
|
/**
* This behavior adds a class of 'js' to the element.
*
* Although simple, this technique is useful when applied to the BODY element in the DOM.
* Stylesheets can then target the page if the page has Javascript enabled (as the new class
* will be applied), or target a Javascript less environment where the class will not be applied.
*/
Elemental.JavascriptEnabled = function(el){
el.addClass('js');
};
|
'use strict';
/* https://github.com/angular/protractor/blob/master/docs/toc.md */
// describe('my app', function() {
//
// browser.get('index.html');
//
// it('should automatically redirect to /view1 when location hash/fragment is empty', function() {
// expect(browser.getLocationAbsUrl()).toMatch("/view1");
// });
//
//
// describe('view1', function() {
//
// beforeEach(function() {
// browser.get('index.html#/view1');
// });
//
//
// it('should render view1 when user navigates to /view1', function() {
// expect(element.all(by.css('[ng-view] p')).first().getText()).
// toMatch(/partial for view 1/);
// });
//
// });
//
//
// describe('view2', function() {
//
// beforeEach(function() {
// browser.get('index.html#/view2');
// });
//
//
// it('should render view2 when user navigates to /view2', function() {
// expect(element.all(by.css('[ng-view] p')).first().getText()).
// toMatch(/partial for view 2/);
// });
//
// });
// });
|
const Shader = require('../')
const test = require('tape')
const GL = require('gl')
const gl = GL(256, 256)
test('kindred-shader: compiler errors', function (t) {
const valid = Shader`
attribute vec2 position;
void vert() {
gl_Position = vec4(position, 1, 1);
}
void frag() {
gl_FragColor = vec4(1);
}
`
const invalid = Shader`
attribute vec2 position;
void vert() {
unused_reference;
gl_Position = vec4(position, 1, 1);
}
void frag() {
gl_FragColor = vec4(1);
}
`
t.throws(function () {
invalid.bind(gl)
}, 'invalid shaders throw on binding')
t.throws(function () {
invalid.bind(gl)
}, 'invalid shaders throw every binding')
t.doesNotThrow(function () {
valid.bind(gl)
}, 'valid shaders do not throw on binding')
t.equal(valid.compiled, true, 'valid shader considered "compiled"')
t.equal(invalid.compiled, false, 'invalid shader not considered "compiled"')
try {
invalid.bind(gl)
} catch (e) {
t.ok(
e.message.indexOf('1:') !== -1 &&
e.message.indexOf('2:') !== -1 &&
e.message.indexOf('3:') !== -1
, 'line numbers included in error output')
}
t.end()
})
test('kindred-shader: invalid context errors', function (t) {
const secondary = GL(64, 64)
const shader = Shader`
attribute vec2 position;
void vert() {
gl_Position = vec4(position, 1, 1);
}
void frag() {
gl_FragColor = vec4(1);
}
`
t.throws(function () {
shader.bind()
}, 'binding without a context causes an error')
t.doesNotThrow(function () {
shader.bind(gl)
}, 'can be attempted again successfully')
t.throws(function () {
shader.bind(secondary)
}, 'errors when handed a fresh context')
t.doesNotThrow(function () {
shader.dispose()
shader.bind(secondary)
}, 'can use .dispose() to set a fresh context safely')
t.ok(shader.compiled, 'shader.compiled === true')
t.end()
})
test('kindred-shader: glslify error (without transform)', function (t) {
try {
Shader`
attribute vec2 position;
#pragma glslify: square = require('glsl-square-frame')
void vert() {
gl_Position = vec4(position, 1, 1);
}
void frag() {
gl_FragColor = vec4(1);
}
`
} catch (e) {
t.ok(e.message.indexOf('glslify') !== -1, 'error on using glslify, referring as such')
t.end()
return
}
t.fail('Shader did not throw error on creation')
})
|
// Add residence data
if (Residences.find().count() === 0) {
Residences.insert({
building: 'Sibley',
type: 'Residence Hall',
beds: 'Single',
tenantNames: [],
tenants: 0 // use $inc
});
Residences.insert({
building: 'Shuniah',
type: 'Residence Hall',
beds: 'Double',
tenantNames: [],
tenants: 0 // use $inc
});
Residences.insert({
building: 'Bartley',
type: 'Townhouse',
beds: 'Double',
tenantNames: [],
tenants: 0 // use $inc
});
Residences.insert({
building: 'Chicago',
type: 'Apartment',
beds: 'Double',
tenantNames: [],
tenants: 0 // use $inc
});
Residences.insert({
building: 'Ripley',
type: 'Townhouse',
beds: 'Single',
tenantNames: [],
tenants: 0 // use $inc
});
Residences.insert({
building: 'Ridgemont',
type: 'Residence Hall',
beds: 'Single Basic',
tenantNames: [],
tenants: 0 // use $inc
});
}
|
var AboutMeEditEntryView = Backbone.View.extend({
events: {
"click #save": "saveEntry",
"click #delete": "deleteEntry",
"click #close-success": "closeSuccess"
},
render: function() {
$(this.el).html(template.preferencesView.aboutMeEditEntry({title: this.model.get("title"), body:this.model.get("body")}));
this.notificationSuccess = $(this.el).find("#notif-success");
return this;
},
deleteEntry: function(){
this.model.destroy();
$(this.el).fadeOut(function(){
$(this).remove();
});
},
saveEntry: function(){
var html = $(this.el);
var notif = this.notificationSuccess;
this.model.save({title: html.find("#title").val(), body: html.find("#body").val()},{
success:function(){
notif.show();
}
});
},
closeSuccess: function(){
this.notificationSuccess.hide();
}
});
|
module.exports = function getTaxRate(income) {
if (income <= 18200)
return 0;
if (income <= 37000)
return 0.19 - 3458/income;
if (income <= 80000)
return 0.325 - 8453/income;
if (income <= 180000)
return 0.37 - 12053/income;
return 0.45 - 26453/income;
};
|
module.exports = {
favicon: {
src: '<%= src %>/favicon.ico',
dest: '<%= build %>/favicon.ico'
},
bower_components: {
files: {
'<%= build %>/css/codemirror.css':'bower_components/codemirror/lib/codemirror.css'
}
},
'wri-skeleton': {
files: {
'<%= build %>/css/wri-skeleton.css':'<%= tmp %>/css/wri-skeleton.css',
'<%= dist %>/wri-skeleton.css':'<%= tmp %>/css/wri-skeleton.css',
'<%= build %>/js/wri-skeleton.min.js':'<%= dist %>/js/wri-skeleton.min.js'
}
}
};
|
'use strict'
const apemandb = require('apemandb')
let db = apemandb({
env: require('../env')('database'),
models: `${__dirname}/models/*.json`,
addons: `${__dirname}/addons/*.addon.js`,
seeds: `/seeds/${process.env.NODE_ENV}/*.seed.js`
})
// Models are exposed as db.models.<ModelName> (like db.models.User)
module.exports = db
|
angular.module('Atarnia.utils').factory('_uploader', ['$upload', '_apiAdapter', _uploader]);
function _uploader($upload, _apiAdapter) {
return {
setUp: setUpUploader
};
function setUpUploader(scope, fileFieldLabel, tokenFieldLabel, progressFieldLabel) {
var url = _apiAdapter.getApiUrl() + 'upload/',
uploader;
scope.$watch(fileFieldLabel, function() {
var file = scope[fileFieldLabel] && scope[fileFieldLabel][0];
if (file){
if (uploader) { uploader.abort(); }
uploader = $upload.upload({
url: url,
method: 'POST',
file: file
})
.progress(function(evt) {
scope[progressFieldLabel] = scope[progressFieldLabel] || {};
scope[progressFieldLabel][fileFieldLabel] = {
progress: parseInt(100.0 * evt.loaded / evt.total),
loaded: evt.loaded,
total: evt.total
};
})
.success(function(data, status, headers, config) {
scope[tokenFieldLabel] = data.token;
delete scope[progressFieldLabel][fileFieldLabel];
})
.error(function(reason){
scope[progressFieldLabel][fileFieldLabel] = { error: reason };
});
}
});
}
}
|
// Dependencies
var express = require('express');
var path = require('path');
// Args
var port = process.argv[2];
var template = process.argv[3];
// App
var app = express();
// App settings
app.set('views', template || path.join(__dirname, 'templates'));
app.set('view engine', 'jade');
// URL
app.get('/home', function(request, response){
var tplData = {
'date': new Date().toDateString()
}
response.render('index', tplData);
});
app.listen(port || 8080);
|
'use strict';
const UserHandler = require('../handlers/user');
const user = new UserHandler(require('../services/user'));
const middleware = require('../../../middleware');
module.exports = function (app) {
app.route('/users')
.post(user.create.bind(user));
app.route('/users/likes')
.put(middleware.getClubData, user.editLikes.bind(user));
app.route('/users/dislikes')
.put(middleware.getClubData, user.editDisLikes.bind(user));
app.route('users/exists')
.get(user.isUserExists.bind(this));
app.route('/users/:user')
.get(user.getOne.bind(user));
};
|
import { StyleSheet } from 'aphrodite';
import * as fonts from '../../style/fonts';
import * as colors from '../../style/colors';
export default StyleSheet.create({
quiz: {
marginTop: '3em'
},
flower: {
marginTop: '1rem',
},
img: {
maxWidth: '100%',
height: 'auto',
marginBottom: '20px'
},
rsvpButton: {
fontSize: fonts.medium
},
rsvpButtonText: {
fontSize: fonts.smallerer,
fontWeight: 200
},
score: {
marginBottom: '2em'
},
retake: {
marginBottom: '2em',
fontSize: '2em',
},
retakeLink: {
textDecoration: 'underline',
cursor: 'pointer',
color: colors.blue,
':hover': {
color: colors.aquaMarine
}
}
});
|
import { __decorate } from "tslib";
import { customAttribute, inject } from "aurelia-framework";
let AttachFocusAttribute = /** @class */ (() => {
let AttachFocusAttribute = class AttachFocusAttribute {
constructor(element) {
this.element = element;
}
attached() {
if (this.value === '' || (this.value && this.value !== 'false')) {
this.element.focus();
}
}
};
AttachFocusAttribute = __decorate([
inject(Element),
customAttribute('ux-attach-focus')
], AttachFocusAttribute);
return AttachFocusAttribute;
})();
export { AttachFocusAttribute };
//# sourceMappingURL=attach-focus-attribute.js.map
|
'use strict';
module.exports = function (verificationToken, onSlackEvent) {
return function (req, res, next) {
if (req.method !== 'POST') return next();
if (!req.body) {
res.stausCode = 400;
res.end('bad request - no body found');
return;
}
var body = req.body.payload ? JSON.parse(req.body.payload) : req.body;
if (verificationToken && body.token !== verificationToken) {
res.statusCode = 403;
res.end('could not verify slack token');
return;
}
if (body.type === 'url_verification') return res.end(body.challenge);
if (body.type === 'event_callback') {
onSlackEvent(body, function (err) {
if (!err) return res.end('ok');
res.statusCode = 400;
res.end('please retry');
});
return;
}
res.statusCode = 400;
res.end('bad request - not slack event api');
};
};
|
/* the root getters */
|
/**
* reply代理
*/
var Reply=require('../models').Reply;
var EventProxy=require('eventproxy');
var tools=require('../common/tools');
var User=require('./user');
var at=require('../common/at');
/**
* 获取一条回复信息
* @param {String} id 回复ID
* @param {Function} callback 回调函数
*/
exports.getReply=function(id,callback){
Reply.findOne()
};
/**
* 根据回复ID,获取回复
* Callback:
* - err, 数据库异常
* - reply, 回复内容
* @param {String} id 回复ID
* @param {Function} callback 回调函数
*/
exports.getReplyById=function(id,callback){
if(!id){
return callback(null,null);
}
Reply.findOne({_id:id},function(err,reply){
if(err){
return callback(err);
}
if(!reply){
return callback(err,null);
}
var user_id=reply.user_id;
User.getUserById(user_id,function(err,user){
if(err){
return callback(err);
}
reply.user=user;
at.linkUsers(reply.content,function(err,str){
if(err){
return callback(err);
}
reply.content=str;
return callback(err,reply);
});
});
});
};
/**
* 根据objId,获取回复列表
* Callback:
* - err, 数据库异常
* - replies, 回复列表
* @param {String} id objId
* @param {Function} callback 回调函数
*/
exports.getRepliesByObjectId = function (id, cb) {
Reply.find({object_id: id, deleted: false}, '', {sort: 'create_at'}, function (err, replies) {
if (err) {
return cb(err);
}
if (replies.length === 0) {
return cb(null, []);
}
var proxy = new EventProxy();
proxy.after('reply_find', replies.length, function () {
cb(null, replies);
});
for (var j = 0; j < replies.length; j++) {
(function (i) {
var user_id = replies[i].user_id;
User.getUserById(user_id, function (err, user) {
if (err) {
return cb(err);
}
replies[i].user = user || { _id: '' };
if (replies[i].content_is_html) {
return proxy.emit('reply_find');
}
at.linkUsers(replies[i].content, function (err, str) {
if (err) {
return cb(err);
}
replies[i].content = str;
proxy.emit('reply_find');
});
});
})(j);
}
});
};
/**
* 创建并保存一条回复信息
* @param {String} content 回复内容
* @param {String} objectId 回复对象ID mongoose.Types.ObjectId.toString()
* @param {String} userId 回复用户
* @param {String} [replyId] 回复ID,当二级回复时设定该值
* @param {Function} callback 回调函数
*/
exports.newAndSave=function(content,objectId,userId,replyId,callback){
if(typeof replyId==='function'){
callback=replyId;
replyId=null;
}
var reply=new Reply();
reply.content=content;
reply.object_id=objectId;
reply.user_id=userId;
if(replyId){
reply.reply_id=replyId;
}
reply.save(function(err){
callback(err,reply);
});
};
/**
* 根据objId查询到最新的一条未删除回复
* @param objId 回复对象ID
* @param callback 回调函数
*/
exports.getLastReplyByObjId=function(objId,callback){
Reply.find({object_id:objId},{},{},callback);
// Reply.find({object_id:objId,delete:false},'_id',{sort:{create_at:-1},limit:1},callback);
};
/**
* 根据用户id获取所有回复
*/
exports.getRepliesByUserId=function(userId,opt,callback){
if(callback){
callback=opt;
opt=null;
}
Reply.find({user_id:userId},{},opt,callback);
};
/**
* 通过userId获取回复总数
*/
exports.getCountByUserId=function(userId,callback){
Reply.count({user_id:userId},callback);
}
|
const winston = require("winston");
require("winston-daily-rotate-file");
const beautify = require('js-beautify').js_beautify
const embedBuilder = require("./embedBuilder.js");
const util = require("./util.js");
const config = require('./../config.json');
const winstonLogger = new (winston.Logger)({
exitOnError: false,
transports: [
new winston.transports.DailyRotateFile({
name: 'info-log',
filename: 'logs/info-',
datePattern: 'yyyy-MM-dd.log',
level: 'info',
json: false,
prettyPrint: false
}),
new winston.transports.DailyRotateFile({
name: 'warning-log',
filename: 'logs/warning-',
datePattern: 'yyyy-MM-dd.log',
level: 'warn',
json: false,
prettyPrint: false
}),
new winston.transports.DailyRotateFile({
name: 'error-log',
filename: 'logs/error-',
datePattern: 'yyyy-MM-dd.log',
level: 'error',
json: false,
prettyPrint: false,
handleExceptions: true,
humanReadableUnhandledException: true
})
]
});
const logger = {
generic: function (logParams, client, message, log) {
if (util.loggable(logParams)) {
const level = "info";
if (message) {
logger.winstonLogger(level, client, logParams, message, log);
logger.embedLogger(logParams, client, level, embedBuilder.message(message, level).embed, log);
} else {
logger.winstonLogger(level, client, logParams, message, log);
logger.embedLogger(logParams, client, level, embedBuilder.empty(level).embed, log);
}
}
},
log: function (logParams, client, data, event, wrapper) {
if (util.loggable(logParams)) {
const level = "info";
const logMessage = embedBuilder[wrapper](data, level, event);
logger.winstonLogger(level, client, logParams, event, data);
logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message);
}
},
warn: function (logParams, client, data, event, wrapper) {
if (util.loggable(logParams)) {
const level = "warning";
const logMessage = embedBuilder[wrapper](data, level, event);
logger.winstonLogger(level, client, logParams, event, data);
logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message);
}
},
error: function (logParams, client, data, event, wrapper) {
if (util.loggable(logParams)) {
const level = "error";
const logMessage = embedBuilder[wrapper](data, level, event);
logger.winstonLogger(level, client, logParams, event, data);
logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message);
}
},
imgError: function (logParams, client, data, error, wrapper, embedImage) {
if (util.loggable(logParams)) {
const level = "error";
const logMessage = embedBuilder[wrapper](data, level, error, embedImage);
logger.winstonLogger(level, client, logParams, error, data, embedImage);
logger.embedLogger(logParams, client, level, logMessage.embed, logMessage.message);
}
},
embedLogger: function (logParams, client, level, embed, message = "") {
//TODO message length
if (util.loggable({level: level})) {
const logChannelId = util.getData("/config/logChannels/default");
if (logChannelId) {
const logChannel = client.channels.filter(channel => logChannelId == channel.id).first();
if (logChannel) {
logChannel.sendMessage(message, {
embed: embed
});
} else {
console.log("Log channel " + logChannelId + " does not exist");
}
} else {
console.log("Log channel not configured");
}
}
const levelLogChannelId = util.getData("/config/logChannels/" + level);
if (levelLogChannelId) {
const levelLogChannel = client.channels.filter(channel => levelLogChannelId == channel.id).first();
if (levelLogChannel) {
levelLogChannel.sendMessage(message, {
embed: embed
});
} else {
console.log("Level log channel " + levelLogChannelId + " does not exist for " + level);
}
} else {
console.log("Level log channel not configured for " + level);
}
},
winstonLogger: function (level, client, ...logData) {
const levels = {
"info": "info",
"warning": "warn",
"error": "error"
};
logData = require('util').inspect(logData, {
depth: null
});
winstonLogger.log(levels[level], util.scrubOutput(client, JSON.stringify(logData, null, 4)).replace(new RegExp("\\\\n", 'g'), "\n"));
}
};
module.exports = logger;
|
// for tests need to install mocha:
// npm install -g mocha
//
// then to run a test
//
// mocha test.js
//
var assert = require("assert");
require('./index')
// the values are arrays of elements.
describe('groupby',function(){
it("should sort items into buckets. return an object - put each item of an array into an object property, according to value of a specified field",function(){
var arr=[
{n:1,v:'a'},
{n:2,v:'b'},
{n:3,v:'b'}
];
var result={
a:[ {n:1,v:'a'} ],
b:[ {n:2,v:'b'}, {n:3,v:'b'} ]
};
assert.deepEqual(groupby(arr,'v'),result);
})
})
describe('objeach',function(){
it("should be iterate for each on object's properties",function(){
var obj={aa:2,bb:1,cc:3};
var gotvalues=[],gotkeys=[],gotindexes=[]
var indexes=[0,1,2]
var keys=["aa","bb","cc"]
var values=[2,1,3]
objeach(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i)})
assert.deepEqual(gotvalues,values);
assert.deepEqual(gotkeys,keys);
assert.deepEqual(gotindexes,indexes);
})
})
describe('objmap',function(){
it("should be return a new object with same names and values updated by map function",function(){
var obj={aa:2,bb:1,cc:3};
var mapped={aa:3,bb:2,cc:4};
var gotvalues=[],gotkeys=[],gotindexes=[]
var indexes=[0,1,2]
var keys=["aa","bb","cc"]
var values=[2,1,3]
assert.deepEqual(objmap(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i);return v+1}),mapped);
assert.deepEqual(gotvalues,values);
assert.deepEqual(gotkeys,keys);
assert.deepEqual(gotindexes,indexes);
})
})
//var obj=objmap(obj, function(value,key,index){ return value.field ; } )
describe('objfilter',function(){
it("should be return a new object with properties filtered by their value",function(){
var obj={aa:2,bb:1,cc:3};
var filtered={aa:2};
var gotvalues=[],gotkeys=[],gotindexes=[]
var indexes=[0,1,2]
var keys=["aa","bb","cc"]
var values=[2,1,3]
assert.deepEqual(objfilter(obj,function(v,k,i){gotvalues.push(v);gotkeys.push(k);gotindexes.push(i);return v==2}),filtered);
assert.deepEqual(gotvalues,values);
assert.deepEqual(gotkeys,keys);
assert.deepEqual(gotindexes,indexes);
})
})
describe('sortobj',function(){
it("should sort object's keys by their names",function(){
var obj={aa:2,bb:1,cc:3};
var sorted={cc:3,aa:2,bb:1};
assert.deepEqual(sortobj(obj),sorted);
})
it("should be able to use optional comparator",function(){
var obj={aa:2,bb:1,cc:3};
var sorted_asc={cc:3,aa:2,bb:1};
function comparator_asc(a,b) {return a==b?0:(a>b?1:-1)};
assert.deepEqual(sortobj(obj,comparator_asc),sorted_asc);
})
})
describe('sortobjkey',function(){
it("should sort object's keys by value is desc order",function(){
var obj={aa:{f:2},bb:{f:1},cc:{f:3}};
var sorted={cc:{f:3},aa:{f:2},bb:{f:1}};
assert.deepEqual(sortobjkey(obj,'f'),sorted);
})
})
describe('sortkeys',function(){
it("should sort object's keys by their names",function(){
var obj={bb:1,aa:1};
var sorted={aa:1,bb:1};
assert.deepEqual(sortkeys(obj),sorted);
})
it("should be able to use optional comparator",function(){
var obj={bb:1,aa:1,cc:1};
var sorteddesc={cc:1,bb:1,aa:1};
function comparator_desc(a,b) {return a==b?0:(a>b?-1:1)};
assert.deepEqual(sortkeys(obj,comparator_desc),sorteddesc);
})
})
describe('objtokvarr',function(){
it("should convert object to array of objects of key and value",function(){
var obj={aa:123};
var kva=[ {k:'aa',v:123} ];
assert.deepEqual(objtokvarr(obj),kva);
})
it("should be able to use defined names",function(){
var obj={aa:123};
var kva=[ {name:'aa',value:123} ];
assert.deepEqual(objtokvarr(obj,"name","value"),kva);
})
})
describe('objtsv',function(){
it("should convert array of objects to tab seperated values string",function(){
var tsv='id\tname\r\n'+
'1\taaa\r\n'+
'2\tbbb';
var objarr=[ {id:1,name:"aaa"}, {id:2,name:"bbb"} ]
assert.deepEqual(objtsv(objarr),tsv);
})
})
|
'use strict';
describe('rgiResourcesCtrl', function () {
beforeEach(module('app'));
var $scope, $location, actualErrorHandler, locationPathBackup, RESOURCES = 'RESOURCES', spies = {}, stubs = {},
initializeController = function(resourceType) {
beforeEach(inject(
function ($rootScope, $controller, _$location_, rgiHttpResponseProcessorSrvc, rgiResourcesSrvc) {
$location = _$location_;
locationPathBackup = $location.$$path;
$location.$$path = '/' + resourceType;
spies.resourcesQuery = sinon.spy(function(criteria, callback, errorHandler) {
actualErrorHandler = errorHandler;
callback(RESOURCES);
});
stubs.resourcesQuery = sinon.stub(rgiResourcesSrvc, 'query', spies.resourcesQuery);
stubs.httpResponseProcessorGetDefaultHandler = sinon.stub(rgiHttpResponseProcessorSrvc, 'getDefaultHandler',
function(errorMessage) {return errorMessage;});
$scope = $rootScope.$new();
$controller('rgiResourcesCtrl', {$scope: $scope});
}
));
},
checkTypeSpecificProperties = function(resourceType, title, errorHandler) {
it('sets the resource type', function () {
$scope.resource_type.should.be.equal(resourceType);
});
it('sets the title', function () {
$scope.title.should.be.equal(title);
});
it('processes HTTP failures', function () {
actualErrorHandler.should.be.equal(errorHandler);
});
it('requires resources', function () {
spies.resourcesQuery.withArgs({type: resourceType}).called.should.be.equal(true);
});
};
describe('FAQ', function() {
initializeController('faq');
checkTypeSpecificProperties('faq', 'Frequently Asked Questions', 'Load FAQ data failure');
});
describe('Resources', function() {
initializeController('resource');
checkTypeSpecificProperties('resource', 'Other Resources', 'Load resource data failure');
it('sets the resources', function () {
$scope.resources.should.be.equal(RESOURCES);
});
});
afterEach(function () {
Object.keys(stubs).forEach(function(stubName) {
stubs[stubName].restore();
});
$location.$$path = locationPathBackup;
});
});
|
/*eslint-env node*/
var fs = require('fs');
module.exports = (function (fileName) {
var fileObj = JSON.parse(fs.readFileSync(fileName, 'utf8'))
return fileObj.token;
});
|
import React from 'react';
import {State, History} from 'react-router';
import { Menu, Mixins, Styles } from 'material-ui';
import Content from '../../components/layout/Content';
import ContentHeader from '../../components/layout/ContentHeader';
import Tabela from '../../components/Tabela';
class StudentiLista extends React.Component {
render() {
var menu = [];
return (
<Content>
<ContentHeader title='Lista Studenata' menu={menu}/>
<Tabela/>
</Content>
);
}
}
export default StudentiLista;
|
const Chromy = require('../src')
const path = require('path')
let chromy = new Chromy()
chromy.chain()
.goto('file://' + path.join(__dirname, '/pages/index.html'))
.evaluate(() => {
return document.querySelectorAll('*').length
})
.result((r) => console.log(r))
.end()
.then(_ => chromy.close())
|
/**
* File to check duration selection and pass selected duration to modules.
* Will trigger on event on every duration change.
*/
"use strict";
var myDur = (function () {
var myDur = {};
var startDate,
endDate;
var EVENT_DURATION_CHANGE = jQuery.Event(myConfig.EVENT_DURATION_CHANGE_NAME);
function addDatePicker() {
if ($(".date-picker").length > 0) {
$("#date-picker-1").datepicker({});
$("#date-picker-2").datepicker({});
$(".date-picker").on("click", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
event.stopPropagation();
})
}
}
function checkAndUpdateDuration(days) {
endDate = moment().utc().format(myConfig.API_DATE_FORMAT);
startDate = moment().subtract(days, 'days').utc().format(myConfig.API_DATE_FORMAT);
EVENT_DURATION_CHANGE.startDate = startDate;
EVENT_DURATION_CHANGE.endDate = endDate;
jQuery('body').trigger(EVENT_DURATION_CHANGE);
}
function init() {
/**
* TODO will consider after 3 months.
*addDatePicker();
*/
jQuery('.time-selection-controls button[data-days]').on('click', function () {
console.log(this);
var _button = jQuery(this);
_button.siblings().removeClass('btn-primary');
_button.siblings().addClass('btn-outline-primary');
_button.removeClass("btn-outline-primary");
_button.addClass("btn-primary");
checkAndUpdateDuration(_button.data('days'));
});
}
myDur.init = init;
jQuery('body').on(myConfig.EVENT_APPLICATION_LOADED_NAME, function () {
if (jQuery('#my-chart,.reporting').length > 0) {
init();
}
});
return myDur;
}());
|
import Vue from 'vue'
import CButton from 'components/c-button'
describe('button.vue', () => {
let el
beforeEach(() => {
el = document.createElement('div')
document.body.appendChild(el)
})
afterEach(() => {
document.body.removeChild(el)
})
it('should render correct contents', () => {
const vm = new Vue({
el,
replace: false,
template: '<c-button>PLATO</c-button>',
components: {
CButton
}
})
expect(vm.$children.length).to.equal(1)
const el0 = vm.$children[0].$el
expect(el0.textContent).to.equal('PLATO')
expect(el0.type).to.equal('button')
})
it('type', () => {
const vm = new Vue({
el,
replace: false,
template: '<c-button type="submit">PLATO</c-button>',
components: {
CButton
}
})
expect(vm.$children[0].$el.type).to.equal('submit')
})
})
|
'use strict';
import angular from 'angular';
import OnboardingController from './design-onboarding-controller';
var stateConfig = ($stateProvider) => {
$stateProvider
.state('app.design.onboarding', {
url: '/onboarding',
controller: OnboardingController,
controllerAs: 'onboarding',
templateProvider: ($templateCache) => $templateCache.get('design/onboarding/design-onboarding.html')
});
};
export default angular.module('app.design.onboarding', [])
.config(['$stateProvider', stateConfig]);
|
/**
* editor_plugin_src.js
*
* Copyright 2010, Moxiecode Systems AB
* Released under LGPL License.
*
* License: http://tinymce.moxiecode.com/license
* Contributing: http://tinymce.moxiecode.com/contributing
*/
(function() {
tinymce.create('tinymce.plugins.Save', {
init : function(ed, url) {
var t = this;
t.editor = ed;
// Register commands
ed.addCommand('mceSave', t._save, t);
ed.addCommand('mceCancel', t._cancel, t);
// Register buttons
ed.addButton('save', {title : 'save.save_desc', cmd : 'mceSave'});
ed.addButton('cancel', {title : 'save.cancel_desc', cmd : 'mceCancel'});
ed.onNodeChange.add(t._nodeChange, t);
ed.addShortcut('ctrl+s', ed.getLang('save.save_desc'), 'mceSave');
},
getInfo : function() {
return {
longname : 'Save',
author : 'Moxiecode Systems AB',
authorurl : 'http://tinymce.moxiecode.com',
infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/save',
version : tinymce.majorVersion + "." + tinymce.minorVersion
};
},
// Private methods
_nodeChange : function(ed, cm, n) {
var ed = this.editor;
if (ed.getParam('save_enablewhendirty')) {
cm.setDisabled('save', !ed.isDirty());
cm.setDisabled('cancel', !ed.isDirty());
}
},
// Private methods
_save : function() {
var ed = this.editor, formObj, os, i, elementId;
formObj = tinymce.DOM.get(ed.id).form || tinymce.DOM.getParent(ed.id, 'form');
if (ed.getParam("save_enablewhendirty") && !ed.isDirty())
return;
tinyMCE.triggerSave();
// Use callback instead
if (os = ed.getParam("save_onsavecallback")) {
if (ed.execCallback('save_onsavecallback', ed)) {
ed.startContent = tinymce.trim(ed.getContent({format : 'raw'}));
ed.nodeChanged();
}
return;
}
if (formObj) {
ed.isNotDirty = true;
if (formObj.onsubmit == null || formObj.onsubmit() != false)
formObj.submit();
ed.nodeChanged();
} else
ed.windowManager.alert("Error: No form element found.");
},
_cancel : function() {
var ed = this.editor, os, h = tinymce.trim(ed.startContent);
// Use callback instead
if (os = ed.getParam("save_oncancelcallback")) {
ed.execCallback('save_oncancelcallback', ed);
return;
}
ed.setContent(h);
ed.undoManager.clear();
ed.nodeChanged();
}
});
// Register plugin
tinymce.PluginManager.add('save', tinymce.plugins.Save);
})();
|
import get from 'lodash/get'
/**
* parseConnectionString - Parse a BTCPay Server style connection string.
*
* @param {string} value Connection string
* @param {string} network Network code of config to extract
* @returns {{ host, port, macaroon, cert }} Parsed connection string
*/
const parseConnectionString = (value, network = 'BTC') => {
let config = {}
try {
config = JSON.parse(value)
} catch (e) {
throw new Error('Invalid connection string')
}
const allConfigs = get(config, 'configurations', [])
const params = allConfigs.find(c => c.type === 'grpc' && c.cryptoCode === network) || {}
const { host, port, macaroon, cert } = params
if (!host || !port || !macaroon) {
throw new Error('Invalid connection string')
}
return { host, port, macaroon, cert }
}
export default parseConnectionString
|
//~ name a481
alert(a481);
//~ component a482.js
|
$(function () {
$(".submit-on-checked").change(function (ev) {
var that = $(this);
if (that.attr("type") == "radio" && !that.is(":checked")) {
return;
}
$("#search-form").submit();
})
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.