text
stringlengths 2
6.14k
|
|---|
module.exports = {
__esModule: true,
default: {
plugins: ['esm-object']
}
}
|
$(document).ready(function() {
var loading = $('#loading');
['ceneo', 'allegro'].forEach(function(service) {
$('#' + service + '-form').submit(function(e) {
e.preventDefault();
var self = $(this);
var resultsUl = $('#' + service + '-results');
resultsUl.empty().hide();
loading.show();
$.post('/' + service, self.serialize(), function(data){
loading.hide();
resultsUl.show();
console.log(data.result);
data.result.forEach(function(row) {
products = [];
row.products.forEach(function(product) {
products.push(
'<a href="' + product.url + '">' + product.name + '</a> ' + product.price.toFixed(2)
);
});
$('<li><b><a href="' + row.url + '">' + row.shop + '</a> ' + row.price.toFixed(2) + ' ' + row.products.length + ' prod.</b> (' + products.join(', ') + ')</li>').appendTo(resultsUl);
});
}).fail(function(data){
loading.hide();
resultsUl.show();
$('<li class=\'error\'>Error occured!</li>').appendTo(resultsUl);
});
});
});
});
|
// Generated by CoffeeScript 1.4.0-beerscript
(function() {
var CoffeeScript, cakefileDirectory, existsSync, fatalError, fs, helpers, missingTask, oparse, options, optparse, path, printTasks, switches, tasks;
fs = require('fs');
path = require('path');
helpers = require('./helpers');
optparse = require('./optparse');
CoffeeScript = require('./coffee-script');
existsSync = fs.existsSync || path.existsSync;
tasks = {};
options = {};
switches = [];
oparse = null;
helpers.extend(global, {
task: function(name, description, action) {
var _ref;
if (!action) {
_ref = [description, action], action = _ref[0], description = _ref[1];
}
return tasks[name] = {
name: name,
description: description,
action: action
};
},
option: function(letter, flag, description) {
return switches.push([letter, flag, description]);
},
invoke: function(name) {
if (!tasks[name]) {
missingTask(name);
}
return tasks[name].action(options);
}
});
exports.run = function() {
var arg, args, _i, _len, _ref, _results;
global.__originalDirname = fs.realpathSync('.');
process.chdir(cakefileDirectory(__originalDirname));
args = process.argv.slice(2);
CoffeeScript.run(fs.readFileSync('Cakefile').toString(), {
filename: 'Cakefile'
});
oparse = new optparse.OptionParser(switches);
if (!args.length) {
return printTasks();
}
try {
options = oparse.parse(args);
} catch (e) {
return fatalError("" + e);
}
_ref = options["arguments"];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
_results.push(invoke(arg));
}
return _results;
};
printTasks = function() {
var cakefilePath, desc, name, relative, spaces, task;
relative = path.relative || path.resolve;
cakefilePath = path.join(relative(__originalDirname, process.cwd()), 'Cakefile');
console.log("" + cakefilePath + " defines the following tasks:\n");
for (name in tasks) {
task = tasks[name];
spaces = 20 - name.length;
spaces = spaces > 0 ? Array(spaces + 1).join(' ') : '';
desc = task.description ? "# " + task.description : '';
console.log("cake " + name + spaces + " " + desc);
}
if (switches.length) {
return console.log(oparse.help());
}
};
fatalError = function(message) {
console.error(message + '\n');
console.log('To see a list of all tasks/options, run "cake"');
return process.exit(1);
};
missingTask = function(task) {
return fatalError("No such task: " + task);
};
cakefileDirectory = function(dir) {
var parent;
if (existsSync(path.join(dir, 'Cakefile'))) {
return dir;
}
parent = path.normalize(path.join(dir, '..'));
if (parent !== dir) {
return cakefileDirectory(parent);
}
throw new Error("Cakefile not found in " + (process.cwd()));
};
}).call(this);
|
import App from './container';
export default App;
|
const path = require('path');
const { CheckerPlugin } = require('awesome-typescript-loader');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const baseConfig = require('./webpack.base');
const baseDevConfig = {
...baseConfig,
devtool: 'source-map',
mode: 'development',
devServer: {
contentBase: baseConfig.output.path,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
},
compress: true,
port: 3000,
},
};
const viewerConfig = {
...baseDevConfig,
entry: {
index: path.join(__dirname, 'src', 'viewer', 'viewer.tsx'),
},
plugins: [
new CheckerPlugin(),
new HtmlWebpackPlugin({
title: 'CSpell Settings Viewer',
hash: true,
template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'),
inject: 'body',
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
const testConfig = {
...baseDevConfig,
entry: {
test: path.join(__dirname, 'src', 'viewer', 'vsCodeTestWrapper.tsx'),
},
plugins: [
new HtmlWebpackPlugin({
title: 'Tester CSpell Settings Viewer',
hash: true,
template: path.join('!!handlebars-loader!src', 'viewer', 'index.hbs'),
inject: 'body',
filename: 'test.html',
}),
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
};
module.exports = [viewerConfig, testConfig];
|
/*global describe: false, it: false, expect: false */
'use strict';
var apiFactory = require('../controller/apiFactory.js');
describe('will this work', function () {
var method = apiFactory.get('session');
it('Default test case', function apiFactory1() {
expect(method.create).toBe(require('../controller/sessionManager.js').create);
});
});
|
import { randomInt32 } from '@provably-fair/core';
/**
* Shuffles an array based on the given seeds, using the given HMAC algorithm.
* @param {[]} arr Array to be shuffled.
* @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair.
* @param {string|Buffer} secretSeed Secret seed used as HMAC key.
* @param {string|Buffer} [publicSeed] Public seed used as HMAC data. To prove fairness of random
* outputs, the hash of `secretSeed` shall be known before revealing `publicSeed`.
* @param {function} [hmacBufferUIntParser] Function to be used for parsing a UInt from the
* generated HMAC buffer.
* @param {function} [fallbackProvider] Function to provide a fallback value in a given range
* whether no appropriate number can be parsed from the generated HMAC buffer.
* @returns {[]} A new array instance containing every element of the input.
*/
export const shuffle = (
arr,
hmacAlgorithm,
secretSeed,
publicSeed,
hmacBufferUIntParser,
fallbackProvider,
) => {
const result = [...arr];
for (let i = arr.length - 1; i > 0; i -= 1) {
// Generate a random integer within [0, i]
const j = randomInt32(
hmacAlgorithm,
secretSeed,
`${publicSeed}-${i}`,
0,
i + 1,
hmacBufferUIntParser,
fallbackProvider,
);
// Exchange `result[i]` and `result[j]`
[result[i], result[j]] = [result[j], result[i]];
}
return result;
};
export default shuffle;
|
'use strict';
const Flag = require('../src/Flag');
const expect = require('chai').expect;
describe('flag.isShort', function () {
it('(empty)', function () {
const input = '';
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-f', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('--', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('-F', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.true;
});
it('---', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('aa', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('a', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-1', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
it('-2', function () {
const input = this.test.title;
const output = Flag.isShort(input);
expect(output).to.be.false;
});
});
|
/**
* Created by Jairo Martinez on 8/15/15.
*/
var five = require("johnny-five");
var board = {};
var lcd = {};
var rly1 = {};
var rly2 = {};
var btnBack = {};
var btnMenu = {};
var btnHome = {};
var btnEntr = {};
var btnNvUp = {};
var btnNvDn = {};
var btnNvLt = {};
var btnNvRt = {};
function _btnsSetup() {
btnEntr = new five.Button({
pin: 2,
isPullup: true
});
btnHome = new five.Button({
pin: 3,
isPullup: true
});
btnBack = new five.Button({
pin: 8,
isPullup: true
});
btnMenu = new five.Button({
pin: 9,
isPullup: true
});
btnNvRt = new five.Button({
pin: 5, //
isPullup: true
});
btnNvDn = new five.Button({
pin: 4, //
isPullup: true
});
btnNvUp = new five.Button({
pin: 7, //
isPullup: true
});
btnNvLt = new five.Button({
pin: 6,
isPullup: true
});
}
function _btns() {
_btnsSetup();
btnMenu.on("down", function () {
console.log("Btn Menu");
lcd.print("Menu");
});
btnHome.on("down", function () {
console.log("Btn Home");
});
btnEntr.on("down", function () {
console.log("Btn Enter");
});
btnBack.on("down", function () {
console.log("Btn Back");
});
btnNvUp.on("down", function () {
console.log("Btn Up");
});
btnNvDn.on("down", function () {
console.log("Btn Down");
});
btnNvLt.on("down", function () {
console.log("Btn Left");
});
btnNvRt.on("down", function () {
console.log("Btn Right");
});
}
function _lcd() {
lcd = new five.LCD({
controller: "PCF8574",
address: 0x20,
rows: 4,
cols: 20
});
lcd.clear();
lcd.home();
}
/**
* Setup Relays
* @private
*/
function _relays() {
rly1 = new five.Relay(10);
rly2 = new five.Relay(11);
setTimeout(function () {
rly1.on();
rly2.on();
}, 1000);
}
/**
* Initialize
* @private
*/
function _init() {
_btns();
_lcd();
_relays();
}
///////////////////////////////////////////////////
//
var j5 = function (){
};
/**
* Initialize Module
* @param opts
* @param cb
*/
j5.prototype.init = function (opts, cb) {
cb = (typeof cb === 'function') ? cb : function () {};
opts = opts || { port: "/dev/ttyAMA0" };
board = new five.Board(opts);
try {
board.on("ready", function () {
_init();
this.repl.inject({
lcd: lcd
});
cb(null);
});
}
catch(ex){
cb(ex,null);
}
};
/**
* Send Message To The LCD
* @param msg
* @param row
* @param col
*/
j5.prototype.message = function(msg,row,col){
row = row || 0;
col = col || 0;
lcd.cursor(row, col).print(msg);
};
module.exports = new j5();
|
// Dependencies
var Enny = require("enny")
, Deffy = require("deffy")
;
/**
* lineType
* Returns the line type for given input.
*
* @name lineType
* @function
* @param {Element|SubElement} source The source (sub)element.
* @param {Element|SubElement} target The target (sub)element.
* @param {} target
* @return {String} The line type.
*/
module.exports = function (source, target) {
if (!Deffy(source.id.parentId, {}, true).isServer && Deffy(target.id.parentId, {}, true).isServer) {
return "link-in";
}
// * -> error
if (Enny.TYPES(target.type, Enny.TYPES.errorHandler)) {
// "line-"
// <path class="line-error-in"...>
return "error-in";
}
// error -> *
if (Enny.TYPES(source.type, Enny.TYPES.errorHandler)) {
return "error-out";
}
// data -> *
if (Enny.TYPES(source.type, Enny.TYPES.dataHandler)) {
return "data-out";
}
return "normal";
};
|
var decode = require('base64-decode');
var crypto = require('crypto');
var ANTI_CHEAT_CODE = 'Fe12NAfA3R6z4k0z';
var SALT = 'af0ik392jrmt0nsfdghy0';
function parse(save) {
if (save.indexOf(ANTI_CHEAT_CODE) > -1) {
var result = save.split(ANTI_CHEAT_CODE);
save = '';
for (var i = 0; i < result[0].length; i += 2) {
save += result[0].charAt(i);
}
var md5 = crypto.createHash('md5');
md5.update(save + SALT, 'ascii');
if (md5.digest('hex') !== result[1]) {
throw new Error('Bad hash');
}
}
else {
throw new Error('Anti-cheat code not found');
}
var data = JSON.parse(decode(save));
return data;
}
module.exports = parse;
|
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
///
/// LOGIN WITHOUT PASSWORD
///
// Method called by a user to request a password reset email. This is
// the start of the reset process.
Meteor.methods({
loginWithoutPassword: function ({ email, username = null }) {
if (username !== null) {
check(username, String);
var user = Meteor.users.findOne({ $or: [{
"username": username, "emails.address": { $exists: 1 }
}, {
"emails.address": email
}]
});
if (!user)
throw new Meteor.Error(403, "User not found");
email = user.emails[0].address;
}
else {
check(email, String);
var user = Meteor.users.findOne({ "emails.address": email });
if (!user)
throw new Meteor.Error(403, "User not found");
}
if (Accounts.ui._options.requireEmailVerification) {
if (!user.emails[0].verified) {
throw new Meteor.Error(403, "Email not verified");
}
}
Accounts.sendLoginEmail(user._id, email);
},
});
/**
* @summary Send an email with a link the user can use verify their email address.
* @locus Server
* @param {String} userId The id of the user to send email to.
* @param {String} [email] Optional. Which address of the user's to send the email to. This address must be in the user's `emails` list. Defaults to the first unverified email in the list.
*/
Accounts.sendLoginEmail = function (userId, address) {
// XXX Also generate a link using which someone can delete this
// account if they own said address but weren't those who created
// this account.
// Make sure the user exists, and address is one of their addresses.
var user = Meteor.users.findOne(userId);
if (!user)
throw new Error("Can't find user");
// pick the first unverified address if we weren't passed an address.
if (!address) {
var email = (user.emails || []).find(({ verified }) => !verified);
address = (email || {}).address;
}
// make sure we have a valid address
if (!address || !(user.emails || []).map(({ address }) => address).includes(address))
throw new Error("No such email address for user.");
var tokenRecord = {
token: Random.secret(),
address: address,
when: new Date()};
Meteor.users.update(
{_id: userId},
{$push: {'services.email.verificationTokens': tokenRecord}});
// before passing to template, update user object with new token
Meteor._ensure(user, 'services', 'email');
if (!user.services.email.verificationTokens) {
user.services.email.verificationTokens = [];
}
user.services.email.verificationTokens.push(tokenRecord);
var loginUrl = Accounts.urls.verifyEmail(tokenRecord.token);
var options = {
to: address,
from: Accounts.emailTemplates.loginNoPassword.from
? Accounts.emailTemplates.loginNoPassword.from(user)
: Accounts.emailTemplates.from,
subject: Accounts.emailTemplates.loginNoPassword.subject(user)
};
if (typeof Accounts.emailTemplates.loginNoPassword.text === 'function') {
options.text =
Accounts.emailTemplates.loginNoPassword.text(user, loginUrl);
}
if (typeof Accounts.emailTemplates.loginNoPassword.html === 'function')
options.html =
Accounts.emailTemplates.loginNoPassword.html(user, loginUrl);
if (typeof Accounts.emailTemplates.headers === 'object') {
options.headers = Accounts.emailTemplates.headers;
}
Email.send(options);
};
// Check for installed accounts-password dependency.
if (Accounts.emailTemplates) {
Accounts.emailTemplates.loginNoPassword = {
subject: function(user) {
return "Login on " + Accounts.emailTemplates.siteName;
},
text: function(user, url) {
var greeting = (user.profile && user.profile.name) ?
("Hello " + user.profile.name + ",") : "Hello,";
return `${greeting}
To login, simply click the link below.
${url}
Thanks.
`;
}
};
}
|
//@flow
import EventEmitter from 'eventemitter2'
import { ApiManager } from '../api-manager'
import NetworkerFabric from '../networker'
import { PureStorage } from '../../store'
import TL from '../../tl'
import configValidator from './config-validation'
import generateInvokeLayer from './invoke-layer-generator'
import type { TLFabric } from '../../tl'
import type { ApiConfig, ConfigType, StrictConfig, Emit, On, PublicKey } from './index.h'
import type { ApiManagerInstance } from '../api-manager/index.h'
const api57 = require('../../../schema/api-57.json')
const mtproto57 = require('../../../schema/mtproto-57.json')
const apiConfig: ApiConfig = {
invokeWithLayer: 0xda9b0d0d,
layer : 57,
initConnection : 0x69796de9,
api_id : 49631,
device_model : 'Unknown UserAgent',
system_version : 'Unknown Platform',
app_version : '1.0.1',
lang_code : 'en'
}
class MTProto {
config: StrictConfig
tls: TLFabric
emitter = new EventEmitter({
wildcard: true
})
api: ApiManagerInstance
on: On = this.emitter.on.bind(this.emitter)
emit: Emit = this.emitter.emit.bind(this.emitter)
constructor(config: ConfigType) {
this.config = configNormalization(config)
this.tls = TL(this.config.schema, this.config.mtSchema)
const netFabric = NetworkerFabric(this.config.api, this.tls, this.config.app.storage, this.emit)
this.api = new ApiManager(this.config, this.tls, netFabric, { on: this.on, emit: this.emit })
}
}
export default MTProto
const configNormalization = (config: ConfigType): StrictConfig => {
const {
server = {},
api = {},
app: {
storage = PureStorage,
publicKeys = publicKeysHex
} = {},
schema = api57,
mtSchema = mtproto57,
} = config
const apiNormalized = { ...apiConfig, ...api }
const invokeLayer = generateInvokeLayer(apiNormalized.layer)
apiNormalized.invokeWithLayer = invokeLayer
const fullCfg = {
server,
api: apiNormalized,
app: { storage, publicKeys },
schema,
mtSchema
}
configValidator(fullCfg)
return fullCfg
}
/**
* Server public key, obtained from here: https://core.telegram.org/api/obtaining_api_id
*
* -----BEGIN RSA PUBLIC KEY-----
* MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6
* lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS
* an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw
* Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+
* 8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n
* Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB
* -----END RSA PUBLIC KEY-----
*/
const publicKeysHex: PublicKey[] = [{
modulus:
'c150023e2f70db7985ded064759cfecf0af328e69a41daf4d6f01b538135a6f91f' +
'8f8b2a0ec9ba9720ce352efcf6c5680ffc424bd634864902de0b4bd6d49f4e5802' +
'30e3ae97d95c8b19442b3c0a10d8f5633fecedd6926a7f6dab0ddb7d457f9ea81b' +
'8465fcd6fffeed114011df91c059caedaf97625f6c96ecc74725556934ef781d86' +
'6b34f011fce4d835a090196e9a5f0e4449af7eb697ddb9076494ca5f81104a305b' +
'6dd27665722c46b60e5df680fb16b210607ef217652e60236c255f6a28315f4083' +
'a96791d7214bf64c1df4fd0db1944fb26a2a57031b32eee64ad15a8ba68885cde7' +
'4a5bfc920f6abf59ba5c75506373e7130f9042da922179251f',
exponent: '010001'
}]
|
var pieceJson = {
type: 'pawn',
color: Chess.Piece.Color.WHITE,
'displacementsNumber': 10
};
var getPieceObject = function() {
var factory = new Chess.Piece.PieceFactory();
return factory.create('pawn', Chess.Piece.Color.WHITE, 10);
};
test("importFromJson", function() {
var jsonifier = new Chess.Piece.PieceJsonifier();
deepEqual(jsonifier.importFromJson(pieceJson), getPieceObject());
});
test("exportToJson", function() {
var jsonifier = new Chess.Piece.PieceJsonifier();
deepEqual(jsonifier.exportToJson(getPieceObject()), pieceJson);
});
|
import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import 'styled-components-test-utils/lib/jest';
import getTheme from '../src/getTheme';
import Link from '../src/Link';
import * as utils from '../src/utils/';
const theme = getTheme({
font: {
size: '16px',
},
});
describe('Link', () => {
test('should render a Link', () => {
const component = ReactTestRenderer.create(<Link theme={theme} />);
expect(component).toBeDefined();
expect(component.toJSON()).toMatchSnapshot();
});
test('should have an a tag', () => {
const component = ReactTestRenderer.create(<Link theme={theme} />).toJSON();
expect(component.type).toEqual('a');
});
test('should have a color', () => {
const spy = jest.spyOn(utils, 'getTextColor');
const component = ReactTestRenderer.create(
<Link
theme={theme}
textColor="white"
/>,
);
expect(component).toHaveStyleRule('color', 'white');
expect(spy).toHaveBeenCalled();
});
test('should have opacity', () => {
const spy = jest.spyOn(utils, 'getOpacity');
const component = ReactTestRenderer.create(
<Link
theme={theme}
opacity={0.75}
/>,
);
expect(component).toHaveStyleRule('opacity', '0.75');
expect(spy).toHaveBeenCalled();
});
test('should have a color hover', () => {
const spy = jest.spyOn(utils, 'getHover');
const component = ReactTestRenderer.create(
<Link
theme={theme}
hoverColor="white"
/>,
);
expect({
component,
modifier: '&:hover',
}).toHaveStyleRule('color', 'white');
expect(spy).toHaveBeenCalled();
});
test('should have the correct font size', () => {
const component = ReactTestRenderer.create(
<Link
theme={theme}
/>,
);
expect(component).toHaveStyleRule('font-size', '16px');
});
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var HotUpdateChunkTemplate = require("../HotUpdateChunkTemplate");
function NodeHotUpdateChunkTemplate(outputOptions) {
HotUpdateChunkTemplate.call(this, outputOptions);
}
module.exports = NodeHotUpdateChunkTemplate;
NodeHotUpdateChunkTemplate.prototype = Object.create(HotUpdateChunkTemplate.prototype);
NodeHotUpdateChunkTemplate.prototype.renderHeader = function(id, modules, hash) {
var buf = HotUpdateChunkTemplate.prototype.renderHeader.call(this, id, modules, hash);
buf.unshift(
"exports.id = " + JSON.stringify(id) + ";\n",
"exports.modules = "
);
return buf;
};
NodeHotUpdateChunkTemplate.prototype.updateHash = function(hash) {
HotUpdateChunkTemplate.prototype.updateHash.call(this, hash);
hash.update("NodeHotUpdateChunkTemplate");
hash.update("3");
hash.update(this.outputOptions.hotUpdateFunction + "");
hash.update(this.outputOptions.library + "");
};
|
export default {
"hljs-comment": {
"color": "#969896"
},
"hljs-quote": {
"color": "#969896"
},
"hljs-variable": {
"color": "#d54e53"
},
"hljs-template-variable": {
"color": "#d54e53"
},
"hljs-tag": {
"color": "#d54e53"
},
"hljs-name": {
"color": "#d54e53"
},
"hljs-selector-id": {
"color": "#d54e53"
},
"hljs-selector-class": {
"color": "#d54e53"
},
"hljs-regexp": {
"color": "#d54e53"
},
"hljs-deletion": {
"color": "#d54e53"
},
"hljs-number": {
"color": "#e78c45"
},
"hljs-built_in": {
"color": "#e78c45"
},
"hljs-builtin-name": {
"color": "#e78c45"
},
"hljs-literal": {
"color": "#e78c45"
},
"hljs-type": {
"color": "#e78c45"
},
"hljs-params": {
"color": "#e78c45"
},
"hljs-meta": {
"color": "#e78c45"
},
"hljs-link": {
"color": "#e78c45"
},
"hljs-attribute": {
"color": "#e7c547"
},
"hljs-string": {
"color": "#b9ca4a"
},
"hljs-symbol": {
"color": "#b9ca4a"
},
"hljs-bullet": {
"color": "#b9ca4a"
},
"hljs-addition": {
"color": "#b9ca4a"
},
"hljs-title": {
"color": "#7aa6da"
},
"hljs-section": {
"color": "#7aa6da"
},
"hljs-keyword": {
"color": "#c397d8"
},
"hljs-selector-tag": {
"color": "#c397d8"
},
"hljs": {
"display": "block",
"overflowX": "auto",
"background": "black",
"color": "#eaeaea",
"padding": "0.5em"
},
"hljs-emphasis": {
"fontStyle": "italic"
},
"hljs-strong": {
"fontWeight": "bold"
}
}
|
(function()
{
"use strict";
// no longer used
// just serves up one particular file
// should always be running
// nohup node server&
var fs = require('fs');
var http = require('http');
var url = require('url');
http.createServer(function(req, res)
{
var request = url.parse(req.url, true);
var action = request.pathname;
if (action == '/functal.png')
{
var img = fs.readFileSync('./functal.png');
res.writeHead(200,
{
'Content-Type': 'image/png'
});
res.end(img, 'binary');
}
else
{
res.writeHead(200,
{
'Content-Type': 'text/plain'
});
res.end('Functal\n');
}
}).listen(8081);
})();
|
import React from 'react';
import CalculatorInput from './CalculatorInput.js';
import CalculatoResult from './CalculatoResult.js';
import styles from './Calculator.scss';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Calculator {
static propTypes = {
};
render() {
return (
<div className="Calculator" id="calculator">
<CalculatoResult />
<CalculatorInput />
</div>
);
}
}
export default Calculator;
|
// --------- Dependencies ---------
let mongoose = require('mongoose');
/**
* Saves the update for the user into the database or returns a general error
* on failure.
* @param {Object} user The user object
* @param {Object} obj The object to return to the user
* @param {string} message The message to display on an error
* @param {Function} done The callback function to execute upon completion
* @return {Function} Execute the callback function
*/
function saveUpdate(user, obj, message, done) {
return user.save(function(err) {
// An error occurred
if (err) {
return done(new Error(message));
}
// Saved object to user
return done(null, obj);
});
}
module.exports = function(UserSchema, messages) {
['Facebook', 'YouTube'].forEach(function(serviceName) {
/**
* Populate service identifiers and tokens.
* @param {ObjectId} id The current user's id in MongoDB
* @param {Object} service User-specific details for the service
* @param {Function} done The callback function to execute upon
* completion
*/
UserSchema.statics['add' + serviceName] = function(id, service, done) {
mongoose.models.User.findById(id, function(err, user) {
// Database Error
if (err) {
return done(new Error(messages.ERROR.GENERAL));
}
// Unexpected Error: User not found
if (!user) {
return done(new Error(messages.ERROR.GENERAL));
}
if (service.reauth) {
return done(messages.STATUS[serviceName.toUpperCase()]
.MISSING_PERMISSIONS);
} else if (service.refreshAccessToken) {
delete service.refreshAccessToken;
user[serviceName.toLowerCase()] = service;
user.save(function(err) {
// Database Error
if (err) {
return done(new Error(messages.ERROR.GENERAL));
}
// Success: Refreshed access token for service
return done(messages.STATUS[serviceName.toUpperCase()].RENEWED);
});
} else if (user['has' + serviceName]) {
// Defined Error: Service already exists
return done(new Error(messages.STATUS[serviceName.toUpperCase()]
.ALREADY_CONNECTED));
} else {
// Save service information (excluding other states) to account
delete service.reauth;
delete service.refreshAccessToken;
user[serviceName.toLowerCase()] = service;
return saveUpdate(user, user, messages.ERROR.GENERAL, done);
}
});
};
/**
* Check if the user is connected to the service.
* @return {Boolean} A status of whether the user has added this service
*/
UserSchema.virtual('has' + serviceName).get(function() {
return Boolean(this[serviceName.toLowerCase()].profileId);
});
/**
* Enable or disable updates for a service.
* @param {Function} done The callback function to execute upon completion
*/
UserSchema.methods['toggle' + serviceName] = function(done) {
mongoose.models.User.findById(this._id, function(err, user) {
// Database Error
if (err) {
return done(new Error(messages.ERROR.GENERAL));
}
let message = messages.STATUS[serviceName.toUpperCase()].NOT_CONFIGURED;
if (user['has' + serviceName]) {
message = user[serviceName.toLowerCase()].acceptUpdates ?
messages.STATUS[serviceName.toUpperCase()].UPDATES_DISABLED :
messages.STATUS[serviceName.toUpperCase()].UPDATES_ENABLED;
user[serviceName.toLowerCase()].acceptUpdates =
!user[serviceName.toLowerCase()].acceptUpdates;
}
return saveUpdate(user, message, messages.ERROR.GENERAL, done);
});
};
});
};
|
import React from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import App from './App';
import CurrentStatus from './CurrentStatus';
import History from './History';
import store from '../store';
const history = syncHistoryWithStore(browserHistory, store);
class AppRouter extends React.Component {
render() {
return (
<div>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={CurrentStatus} />
<Route path="history" component={History} />
</Route>
</Router>
</div>
);
}
}
export default AppRouter;
|
netjs.collections.CollectionBase = (function (netjs, ListEnumerator) {
'use strict';
var CollectionBase = function CollectionBase() {
// use _isBase to determine if this constructor is being invoked via chain or new
if(!CollectionBase._isBase){
throw new Error("Can't instantiate abstract classes");
} else {
/**
* Call the parent constructor
*/
var _args = Array.prototype.slice.call(arguments);
CollectionBase._parent.constructor.apply(this, _args);
this._list = new netjs.collections.ArrayList();
}
if(!CollectionBase._isBase){
return netjs.Util.proxy(this);
} else {
return this;
}
};
CollectionBase.inheritsFrom(netjs.Class).isType('CollectionBase');
/**
* Implementation of IEnumerable
* 'enumerator'
*/
CollectionBase.prototype.enumerator = function (){
var self = this;
return self._list.enumerator();
};
/**
* Implementation of ICollection
* 'copyTo', 'count'
*/
CollectionBase.prototype.copyTo = function (array, index) {
var self = this;
self._list.copyTo(array, index);
};
CollectionBase.prototype.count = function () {
var self = this;
return self._list.count();
};
/**
* Implementation of IList
* 'add', 'clear', 'contains', 'get', 'indexOf', 'insert', 'remove', 'removeAt', 'set'
*/
CollectionBase.prototype.add = function (value) {
var self = this, index = self.count();
self.insert(index, value);
return index;
};
CollectionBase.prototype.clear = function () {
var self = this;
self.onClear();
self._list.clear();
self.onClearComplete();
};
CollectionBase.prototype.contains = function (value) {
var self = this;
return self._list.contains(value);
};
CollectionBase.prototype.getItem = function (index) {
var self = this;
return self._list.getItem(index);
};
CollectionBase.prototype.indexOf = function (value) {
var self = this;
return self._list.indexOf(value);
};
CollectionBase.prototype.insert = function (index, value) {
var self = this;
self.onValidate(value);
self.onInsert(index, value);
self._list.insert(index, value);
self.onInsertComplete(index, value);
};
CollectionBase.prototype.remove = function (value) {
var self = this, index;
index = self.indexOf(value);
self.onValidate(value);
self.onRemove(index, value);
self._list.remove(value);
self.onRemoveComplete(index, value);
};
CollectionBase.prototype.removeAt = function (index) {
var self = this, value;
value = self.getItem(index);
self.onValidate(value);
self.onRemove(index, value);
self._list.removeAt(index);
self.onRemoveComplete(index, value);
};
CollectionBase.prototype.setItem = function (index, value) {
var self = this, oldValue;
oldValue = self.getItem(index);
self.onValidate(value);
self.onSet(index, oldValue, value);
self._list.setItem(index, value);
self.onSetComplete(index, oldValue, value);
};
CollectionBase.prototype.onClear = function () {};
CollectionBase.prototype.onClearComplete = function () {};
CollectionBase.prototype.onInsert = function (index, value) {};
CollectionBase.prototype.onInsertComplete = function (index, value) {};
CollectionBase.prototype.onRemove = function (index, value) {};
CollectionBase.prototype.onRemoveComplete = function (index, value) {};
CollectionBase.prototype.onSet = function (index, oldValue, newValue) {};
CollectionBase.prototype.onSetComplete = function (index, oldValue, newValue) {};
CollectionBase.prototype.onValidate = function (value) {};
CollectionBase.ensureImplements(netjs.collections.IList, netjs.collections.ICollection, netjs.collections.IEnumerable);
return CollectionBase;
} (netjs));
|
var Adapter = require('../factory-girl').Adapter;
var tests = require('./adapter-tests');
var should = require('should');
var context = describe;
var TestModel = function(props) {
this.props = props;
};
var TestAdapter = function() {
this.db = [];
};
TestAdapter.prototype = new Adapter();
TestAdapter.prototype.save = function(doc, Model, cb) {
this.db.push(doc);
process.nextTick(function() {
cb(null, doc);
});
};
TestAdapter.prototype.destroy = function(doc, Model, cb) {
var db = this.db;
var i = db.indexOf(doc);
if (i != -1) this.db = db.slice(0, i).concat(db.slice(i + 1));
process.nextTick(cb);
};
describe('test adapter', function() {
var adapter = new TestAdapter();
tests(adapter, TestModel, countModels);
function countModels(cb) {
process.nextTick(function() {
cb(null, adapter.db.length);
});
}
});
|
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var fs = require('fs');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'File from renamer' });
});
router.get('/#/Users', function(req, res) {
res.send({"res":"gogo"});
});
//To have launchd start mongodb at login:
// ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
//Then to load mongodb now:
// launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
//Or, if you don't want/need launchctl, you can just run:
// mongod --config /usr/local/etc/mongod.conf
// >mongod --dbpath
mongoose.connect("mongodb://localhost/files");
// See files.js
mongoose.model('files', {
path: String,
filename: String,
size: Number,
owner: String,
created: Date,
modified: Date
});
router.get("/files", function(req,res){
console.log("Entering in REST api");
mongoose.model('files').find(function(err,files){
res.send(files);
});
});
router.get("/ls/:node/:dir(*)", function(req,res){
console.log("Entering in REST api");
var out = {};
console.log("Dir=" + req.params.dir);
console.log("Node=" + req.params.node);
//out.network = req.params.node;
out.directoryListing = [];
try {
var counter=0;
fs.readdirSync("/" + req.params.dir).forEach(function(filename){
out.directoryListing.push({
"index": counter++,
"filename": filename,
"Owner": "alainlavoie",
"lastModification": 4332,
"fileSize": 142
});
});
res.send(out.directoryListing);
} catch (dirError){
if (dirError instanceof Error && dirError.code === 'ENOENT'){
res.send(404);
} else {
res.send({Error: dirError});
}
}
});
module.exports = router;
|
module.exports = function (grunt) {
grunt.initConfig({
karma: {
options: {
configFile: 'tests/config/karma.conf.js'
},
watch: {
autoWatch: true
},
singleRun: {
singleRun: true
},
travis: {
singleRun: true,
browsers: ['PhantomJS']
}
}
});
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('testRun', ['karma:singleRun']);
grunt.registerTask('testWatch', ['karma:watch']);
grunt.registerTask('test', ['karma:travis']);
};
|
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'umi'
import { Page } from 'components'
import styles from './index.less'
@connect(({ userDetail }) => ({ userDetail }))
class UserDetail extends PureComponent {
render() {
const { userDetail } = this.props
const { data } = userDetail
const content = []
for (let key in data) {
if ({}.hasOwnProperty.call(data, key)) {
content.push(
<div key={key} className={styles.item}>
<div>{key}</div>
<div>{String(data[key])}</div>
</div>
)
}
}
return (
<Page inner>
<div className={styles.content}>{content}</div>
</Page>
)
}
}
UserDetail.propTypes = {
userDetail: PropTypes.object,
}
export default UserDetail
|
/*!
* CanJS - 2.2.5
* http://canjs.com/
* Copyright (c) 2015 Bitovi
* Wed, 22 Apr 2015 15:03:29 GMT
* Licensed MIT
*/
/*can@2.2.5#control/route/route*/
steal('can/util', 'can/route', 'can/control', function (can) {
// ## control/route.js
// _Controller route integration._
can.Control.processors.route = function (el, event, selector, funcName, controller) {
selector = selector || "";
if (!can.route.routes[selector]) {
if (selector[0] === '/') {
selector = selector.substring(1);
}
can.route(selector);
}
var batchNum,
check = function (ev, attr, how) {
if (can.route.attr('route') === (selector) &&
(ev.batchNum === undefined || ev.batchNum !== batchNum)) {
batchNum = ev.batchNum;
var d = can.route.attr();
delete d.route;
if (can.isFunction(controller[funcName])) {
controller[funcName](d);
} else {
controller[controller[funcName]](d);
}
}
};
can.route.bind('change', check);
return function () {
can.route.unbind('change', check);
};
};
return can;
});
|
exports.pathResolver = function pathResolver(base, path) {
base = base.slice();
path = path.slice();
while (base.length && path[0] === '..') {
path.shift();
base.pop();
}
return base.concat(path);
};
exports.pathSpliter = function pathSpliter(path) {
var splitPath;
if (path instanceof Array) {
splitPath = path;
} else if (typeof path === 'string') {
if (path.match(/[/]|[.][.]/)) {
splitPath = path.split('/');
} else {
splitPath = path.split('.');
}
if (!splitPath[0] && !splitPath[1]) {
splitPath = ['.'];
}
var barsProp = splitPath.pop()
.split('@');
if (barsProp[0]) {
splitPath.push(barsProp[0]);
}
if (barsProp[1]) {
splitPath.push('@' + barsProp[1]);
}
} else {
throw 'bad arrgument: expected String | Array<String>.';
}
return splitPath;
};
function findPath(arg) {
if (arg) {
if (arg.type === 'insert') {
return arg.path;
} else if (
arg.type === 'operator' ||
arg.type === 'transform'
) {
for (var i = 0; i < arg.arguments.length; i++) {
var argI = findPath(arg.arguments[i]);
if (argI.type === 'insert') {
return argI.argument;
}
}
}
}
return '';
}
exports.findPath = findPath;
|
"use strict";
var logger = require('./misc/debug.js');
var TPDU_Client = require('./tpdu_client.js');
var PDU_TYPE = require('./types.js').PDU_TYPE;
var S7_Req_Header = require('./types.js').S7_Req_Header;
var S7_ReqFun_PlcStop = require('./types.js').S7_ReqFun_PlcStop;
var S7_Client = function(host, rack, slot, callback) {
var self = this;
host = host || '127.0.0.1';
rack = rack || 0x01;
slot = slot || 0x02;
self.host = host;
self.tsap_client = 0x0100;
self.tsap_server = 0x0104;
logger.debug('TSAP Client: ' + self.tsap_client);
logger.debug('TSAP Server: ' + self.tsap_server);
self.tpdu_client = new TPDU_Client({
host: self.host,
tsap_client: self.tsap_client,
tsap_server: self.tsap_server
});
};
S7_Client.prototype.ReadArea = function() {
};
S7_Client.prototype.WriteArea = function() {
};
S7_Client.prototype.DBRead = function() {
};
S7_Client.prototype.DBWrite = function() {
};
S7_Client.prototype.MBRead = function() {
};
S7_Client.prototype.MBWrite = function() {
};
S7_Client.prototype.IBRead = function() {
};
S7_Client.prototype.IBWrite = function() {
};
S7_Client.prototype.QBRead = function() {
};
S7_Client.prototype.QBWrite = function() {
};
// Control functions
S7_Client.prototype.PlcHotStart = function() {
};
S7_Client.prototype.PlcColdStart = function() {
};
S7_Client.prototype.PlcStop = function() {
var s7_pdu = Buffer(0);
var header = new S7_Req_Header();
var para = new S7_ReqFun_PlcStop();
header.PDUType = PDU_TYPE.Request;
header.ParLen.value = para.length();
s7_pdu = Buffer.concat([s7_pdu, header.toBytes()]);
s7_pdu = Buffer.concat([s7_pdu, para.toBytes()]);
logger.debug('S7 PDU - PlcStop: \n' + s7_pdu.toString('hex'));
this.tpdu_client.send(s7_pdu);
};
S7_Client.prototype.CopyRamToRom = function() {
};
S7_Client.prototype.Compress = function() {
};
S7_Client.prototype.GetPlcStatus = function() {
};
module.exports = S7_Client;
|
version https://git-lfs.github.com/spec/v1
oid sha256:9a780e07e8e76443bb024c3b81e3f0fd6b43faa74024bd26a78ac61292bc0c06
size 21167
|
/**
* Created by NGUYENVU on 2/6/2016.
*/
var currentDir = window.location.origin + window.location.pathname + "#";
var urlUser = 'user';
var urlSearch = 'user/search';
var urlCreateUser = 'user/create';
var urlEditUser = 'user/edit';
var urlDeleteUser = 'user/delete';
var urlProject = 'project';
var urlProjectSearch = 'project/search';
var urlCreateProject = 'project/create';
var urlEditProject = 'project/edit';
var urlDeleteProject = 'project/delete';
var urlStakeholderProject = 'project/stakeholders';
|
'use strict';
var genBase = require('../genBase')
, Generator;
Generator = module.exports = genBase.extend();
Generator.prototype.prompting = function prompting() {
this.askForModuleName();
};
Generator.prototype.writing = function writing() {
var config = this.getConfig();
this.fs.copyTpl(
this.templatePath('_constant.' + config.appScript),
this.destinationPath(config.appDir + '/' + config.modulePath + '/' + config.hyphenName +
'-constant.' + config.appScript),
config
);
this.fs.copyTpl(
this.templatePath('_spec.' + config.testScript),
this.destinationPath(config.testDir + '/' + config.modulePath + '/' + config.hyphenName +
'-constant_test.' + config.testScript),
config
);
};
|
'use strict';
angular.module('myApp.unit7', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/unit7', {
templateUrl: 'unit7/unit7.html',
controller: 'Unit7Ctrl'
});
}]).controller('Unit7Ctrl', ['Unit7', '$scope',
function(Unit7, $scope) {
$scope.ex = Unit7.ex;
Unit7.refreshPage();
}]);
|
'use strict';
/* Controllers */
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
});
}]);
|
exports.config = {
namespace: "better-img-stencil",
outputTargets: [
{
type: "dist"
},
{
type: "www",
serviceWorker: false
}
]
};
exports.devServer = {
root: "www",
watchGlob: "**/**"
};
|
Blockly.Language.message = {
helpUrl: 'http://www.example.com/',
init: function() {
this.setColour(190);
this.appendDummyInput("").appendTitle(new Blockly.FieldImage("img/message.png", 16, 16)).appendTitle("Message")
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.appendValueInput("value", Text)
this.setTooltip('message');
}
};
Blockly.JavaScript.message = function() {
var argument0 = Blockly.JavaScript.valueToCode(this, 'value', Blockly.JavaScript.ORDER_COMMA) || 'false';
if (!Blockly.JavaScript.definitions_['message']) {
var functionName = Blockly.JavaScript.variableDB_.getDistinctName('message', Blockly.Generator.NAME_TYPE);
Blockly.JavaScript.message.functionName = functionName;
var func = [];
func.push('function ' + functionName + '(message) {');
func.push(' console.log(message);');
func.push('}');
Blockly.JavaScript.definitions_['message'] = func.join('\n');
}
var code = Blockly.JavaScript.message.functionName +
'(' + argument0 + ');\n';
return code;
};
|
declare export type class A {}
|
import { fork, join } from 'redux-saga/effects';
// This utility takes the array of sagas as a param, and maps it to an array of runnable tasks.
export default sagas =>
function* waitAll() {
const tasks = yield sagas.map(([saga, ...params]) => fork(saga, ...params));
yield join(...tasks);
};
|
/*
Name: Mag-register v0.1.1
Description: run mag.module for by tagName(s)
Example:
var instances = mag.register(
'my-tag',
component,
props);
Author: Michael Glazer
License: MIT
Homepage: https://github.com/magnumjs/mag.js
@requires mag.js & mag addons
(c) 2017
*/
(function(mag, document) {
'use strict';
var nodeCache = [];
//Allow for by TagName?
//wrapper for mag.module for tagNames - returns multiple instances
mag.register = function(tagName, mod, props) {
//Are we in a parent run?
// mag.mod.runningViewInstance
var cacheId =
tagName + (mag.mod.runningViewInstance ? mag.mod.runningViewInstance : 0);
//Check if in cache?
if (nodeCache[cacheId]) {
//console.log('cached', cacheId, nodeCache[cacheId]);
}
var nodes = setIdByTagName(tagName);
var instances = [];
if (nodes.length) {
for (var item of nodes) {
var instance = mag.module(item, mod, props);
instances.push(instance);
}
}
return instances;
};
function setIdByTagName(id) {
var parentNode;
if (typeof mag.mod.runningViewInstance != 'undefined') {
var parentID = mag.utils.items.getItemVal(mag.mod.runningViewInstance);
parentNode = getNode(parentID);
}
var nodes = (parentNode || mag.doc).getElementsByTagName(id);
if (nodes.length) {
for (var node of nodes) {
if (!node.id) node.id = performance.now();
nodeCache[node.id] = node;
}
}
return nodes;
}
})(mag, document);
|
import React from 'react';
import "./styles.css";
import logo from '../../../assets/logo.png'
const PersluLogo = (props) => <img src={logo} alt="logo" className="PersluLogo" />;
export default PersluLogo
|
var VERSION = '0.0.0',
http = require('http'),
querystring = require('querystring'),
oauth = require('oauth');
function merge(defaults, options) {
defaults = defaults || {};
if (options && typeof options === 'object') {
var keys = Object.keys(options);
for (var i = 0, len = keys.length; i < len; i++) {
var k = keys[i];
if (options[k] !== undefined) defaults[k] = options[k];
}
}
return defaults;
}
function Withings(options) {
if (!(this instanceof Withings)) return new Withings(options);
var defaults = {
consumer_key: null,
consumer_secret: null,
access_token_key: null,
access_token_secret: null,
headers: {
'Accept': '*/*',
'Connection': 'close',
'User-Agent': 'node-withings/' + VERSION
},
callback_url: null,
rest_base: 'http://wbsapi.withings.net',
};
this.options = merge(defaults, options);
this.oauth = new oauth.OAuth(
this.options.request_token_url,
this.options.access_token_url,
this.options.consumer_key,
this.options.consumer_secret,
'1.0',
this.options.callback_url,
'HMAC-SHA1', null,
this.options.headers
);
}
Withings.prototype.get = function(url, params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
if (url.charAt(0) == '/')
url = this.options.rest_base + url;
this.oauth.get(
url + '?' + querystring.stringify(params),
this.options.access_token_key,
this.options.access_token_secret,
function(error, data, response) {
if (error) {
var err = new Error(
'HTTP Error ' + error.statusCode + ': ' + http.STATUS_CODES[error.statusCode]
);
err.statusCode = error.statusCode;
err.data = error.data;
callback(err);
} else {
try {
var json = JSON.parse(data);
callback(json);
} catch(err) {
callback(err);
}
}
}
);
return this;
}
// CONVENIENCE METHODS
// USER
/*
* User: Get by id
*/
Withings.prototype.user_getbyuserid = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'getbyuserid';
this.get('/user', params, callback);
return this;
}
// MEASURE
/*
* Measure: Get measurement
*/
Withings.prototype.measure_getmeas = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'getmeas';
this.get('/measure', params, callback);
return this;
}
/*
* Measure: Get Activity
*/
Withings.prototype.measure_getactivity = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'getactivity';
this.get('/v2/measure', params, callback);
return this;
}
// NOTIFY
/*
* Notify: Subscribe
*/
Withings.prototype.notify_subscribe = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'subscribe';
this.get('/notify', params, callback);
return this;
}
/*
* Notify: Get
*/
Withings.prototype.notify_get = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'subscribe';
this.get('/notify', params, callback);
return this;
}
/*
* Notify: List
*/
Withings.prototype.notify_list = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'subscribe';
this.get('/notify', params, callback);
return this;
}
/*
* Notify: Revoke
*/
Withings.prototype.notify_revoke = function(params, callback) {
if (typeof params === 'function') {
callback = params;
params = null;
}
if ( typeof callback !== 'function' ) {
throw "FAIL: INVALID CALLBACK.";
return this;
}
params.action = 'subscribe';
this.get('/notify', params, callback);
return this;
}
module.version = VERSION
module.exports = Withings;
|
const express = require('express');
const router = express.Router();
const authHelpers = require('../controllers/signin');
const gameBoard = require('../controllers/gameBoard.js');
const players = require('../controllers/players.js');
const indexController = require('../controllers/index');
router.get('/', authHelpers.loginRequired, (req, res, next) => {
const renderObject = {};
authHelpers.logCheck(renderObject, req);
renderObject.sessionID = req.sessionID;
renderObject.name = req.session.user.username;
res.render('./pages/findGame', renderObject);
});
router.post('/gameBoard', authHelpers.loginRequired, (req, res, next) => {
gameBoard.setUpBoard(req.body.random).then((result) => {
res.json(result[0].board);
}).catch((err) => {
console.log(err);
});
});
router.get('/findGame', authHelpers.loginRequired, (req, res, next) => {
gameBoard.findGame().then((results) => {
res.json(results);
}).catch((err) => {
console.log(err);
});
});
router.get('/:gameID', authHelpers.loginRequired, (req, res, next) => {
const renderObject = {};
authHelpers.logCheck(renderObject, req);
renderObject.title = 'Play!';
renderObject.sessionID = req.sessionID;
renderObject.name = req.session.user.username;
renderObject.first = true;
res.render('./pages/play', renderObject);
});
router.get('/:gameID/notFirst', authHelpers.loginRequired, (req, res, next) => {
const renderObject = {};
authHelpers.logCheck(renderObject, req);
renderObject.title = 'Play!';
renderObject.sessionID = req.sessionID;
renderObject.name = req.session.user.username;
renderObject.first = false;
res.render('./pages/play', renderObject);
});
router.get('/:gameID/join', authHelpers.loginRequired, (req, res, next) => {
gameBoard.getBoard(req.params.gameID).then((result) => {
console.log(result);
res.json(result[0].board);
});
});
router.get('/:gameID/player', authHelpers.loginRequired, (req, res, next) => {
gameBoard.getPlayerBoard(req.params.gameID, req.session.user.user_id).then((result) => {
res.json(result[0]);
});
});
router.post('/player/new', authHelpers.loginRequired, (req, res, next) => {
const playerObject = {
color: req.body.color,
avatar_url: req.body.avatar_url,
user_id: req.session.user.user_id,
game_id: req.body.game_id
};
players.setUpPlayer(playerObject).then((result) => {
res.json(result[0]);
}).catch((err) => {
console.log(err);
return next();
});
});
router.get('/:gameID/yourPlace', authHelpers.loginRequired, (req, res, next) => {
const playerPromise = gameBoard.getPlayerBoard(req.params.gameID, req.session.user.user_id);
const boardPromise = gameBoard.getBoard(req.params.gameID);
});
module.exports = router;
|
import { TreeView } from "@bosket/vue"
import { dragndrop } from "@bosket/core"
/* Model */
const dragModel = [
{ name: "< Drag these items >" },
{ name: 1, children: [{ name: 11 }, { name: 12 }, { name: 13 }]},
{ name: 2, children: [{ name: 21 }, { name: 22 }]},
{ name: 3 },
{ name: 4 }
]
/* Common conf. */
const conf = {
category: "children",
onSelect: function(_) { this.selection = _ },
display: i => i.name,
strategies: { fold: [() => false]}
}
/* Drag only tree */
export const DragTree = {
name: "DragTree",
data: () => ({
selection: [],
model: dragModel,
...conf
}),
render: function(h) {
const props = { props: { ...this.$data }}
return <div class="tree-sample">
<TreeView
{ ...props }
// Pluck preset
dragndrop={{ ...dragndrop.pluck(() => this.model, m => this.model = m) }}
/>
</div>
}
}
/* Drop only tree */
export const DropTree = {
name: "DropTree",
data: () => ({
selection: [],
model: [{ name: "< Drop items here >", children: []}],
...conf
}),
render: function(h) {
const props = {
props: { ...this.$data }
}
return <div class="tree-sample">
<TreeView
{ ...props }
// Paste preset + only drop on items with children
dragndrop={{
...dragndrop.paste(() => this.model, m => this.model = m),
droppable: item => item && item.children
}}
/>
</div>
}
}
|
import React from 'react'
import PropTypes from 'prop-types'
import { EditorialOverlay } from '../editorials/EditorialParts'
import { css, media } from '../../styles/jss'
import * as s from '../../styles/jso'
import * as ENV from '../../../env'
const spinGif = '/static/images/support/ello-spin.gif'
const imageStyle = css(s.block, { margin: '0 auto 75px' })
const errorStyle = css(
{ maxWidth: 780 },
s.px10,
s.mb30,
s.fontSize14,
media(s.minBreak2, s.px0),
)
export const ErrorStateImage = () =>
<img className={imageStyle} src={spinGif} alt="Ello" width="130" height="130" />
export const ErrorState = ({ children = 'Something went wrong.' }) =>
(<div className={errorStyle}>
{children}
</div>)
ErrorState.propTypes = {
children: PropTypes.node,
}
export const ErrorState4xx = ({ withImage = true }) =>
(<ErrorState>
{withImage ? <ErrorStateImage /> : null}
<p>This doesn’t happen often, but it looks like something is broken. Hitting the back button and trying again might be your best bet. If that doesn’t work you can <a href="http://ello.co/">head back to the homepage.</a></p>
<p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p>
<p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p>
</ErrorState>)
ErrorState4xx.propTypes = {
withImage: PropTypes.bool,
}
export const ErrorState5xx = ({ withImage = true }) =>
(<ErrorState>
{withImage ? <ErrorStateImage /> : null}
<p>It looks like something is broken and we couldn’t complete your request. Please try again in a few minutes. If that doesn’t work you can <a href="http://ello.co/">head back to the homepage.</a></p>
<p>There might be more information on our <a href="http://status.ello.co/">status page</a>.</p>
<p>If all else fails you can try checking out our <a href="http://ello.threadless.com/" target="_blank" rel="noopener noreferrer">Store</a> or the <a href={`${ENV.AUTH_DOMAIN}/wtf/post/communitydirectory`}>Community Directory</a>.</p>
</ErrorState>)
ErrorState5xx.propTypes = {
withImage: PropTypes.bool,
}
// -------------------------------------
const errorEditorialStyle = css(
s.absolute,
s.flood,
s.flex,
s.justifyCenter,
s.itemsCenter,
s.fontSize14,
s.colorWhite,
s.bgcRed,
s.pointerNone,
)
const errorEditorialTextStyle = css(
s.relative,
s.zIndex2,
s.colorWhite,
)
export const ErrorStateEditorial = () => (
<div className={errorEditorialStyle}>
<span className={errorEditorialTextStyle}>Something went wrong.</span>
<EditorialOverlay />
</div>
)
|
var framework = require('framework');
exports.info = function() {
return 'fooPlugin (in Framework v' + framework.version + ')';
};
|
$('document').ready(function() {
initTooltips();
});
$(window).on('action:posts.loaded action:topic.loaded action:posts.edited', function() {
initTooltips();
});
$(window).on('action:ajaxify.contentLoaded', function(){
$('.item-tooltip').hide();
});
function initTooltips() {
$('.vanilla-tooltip').each(function(tooltip){
var name = $(this).attr('data-name');
var $this = $(this);
$.getJSON('http://api.theorycraft.fi/v1/item', {name: name}, function(response){
$this.text('['+response.data[0].name+']').attr('rel', 'item='+response.data[0].entry).addClass('q'+response.data[0].quality);
ajaxify('http://db.vanillagaming.org/ajax.php?item='+response.data[0].entry+'&power');
});
$this.mouseenter(function(){
showTooltip($this.data('id'), $this.data('tooltip'));
}).mouseleave(function(){
$('.item-tooltip').hide();
});
});
$(document).mousemove(function(event) {
$('.item-tooltip').css({
left: event.pageX+10,
top: event.pageY+10
});
});
}
function showTooltip(id, data) {
if(!$('.item-tooltip#'+id).length) {
var iconUrl = typeof data.icon == 'undefined' ? '' : 'http://db.vanillagaming.org/images/icons/medium/'+data.icon.toLowerCase()+'.jpg';
var $tooltip = $('<div id="'+id+'" class="item-tooltip"><p style="background-image: url('+iconUrl+');"><span></span></p><table><tr><td>'+data.tooltip_enus+'</td><th style="background-position: 100% 0%;"></th></tr><tr><th style="background-position: 0% 100%;"></th><th style="background-position: 100% 100%;"></th></tr></div>');
$tooltip.css('visibility', 'visible').appendTo('body').show();
} else $('.item-tooltip#'+id).show();
}
function ajaxify(url) {
$('<script type="text/javascript" src="'+url+'"></script>').appendTo('body');
}
$WowheadPower = {
registerItem: function(a,b,item) {
$('a.vanilla-tooltip[rel="item='+a+'"]').data('tooltip', item).data('id', a);
}
}
|
var fs = require("fs");
var glob = require("glob");
var IOUtils = require("./IOUtils");
var DirectiveHandler = require("./DirectiveHandler");
var DIRECTIVE_MATCHER = /<!--#([a-z]+)([ ]+([a-z]+)="(.+?)")* -->/g;
(function() {
"use strict";
var ssi = function(inputDirectory, outputDirectory, matcher) {
this.inputDirectory = inputDirectory;
this.documentRoot = inputDirectory;
this.outputDirectory = outputDirectory;
this.matcher = matcher;
this.ioUtils = new IOUtils(this.documentRoot);
this.directiveHandler = new DirectiveHandler(this.ioUtils);
this.directiveHandler.parser = this;
};
ssi.prototype = {
compile: function() {
//noinspection JSUnresolvedFunction
var files = glob.sync(this.inputDirectory + this.matcher);
for (var i = 0; i < files.length; i++) {
var input = files[i];
var contents = fs.readFileSync(input, {encoding: "utf8"});
var data = this.parse(input, contents);
var output = input.replace(this.inputDirectory, this.outputDirectory);
this.ioUtils.writeFileSync(output, data.contents);
}
},
parse: function(filename, contents, variables) {
var instance = this;
variables = variables || {};
contents = contents.replace(new RegExp(DIRECTIVE_MATCHER), function(directive, directiveName) {
var data = instance.directiveHandler.handleDirective(directive, directiveName, filename, variables);
if (data.error) {
throw data.error;
}
for (var key in data.variables) {
if (data.variables.hasOwnProperty(key)) {
variables[data.variables[key].name] = data.variables[key].value;
}
}
return (data && data.output) || "";
});
return {contents: contents, variables: variables};
}
};
module.exports = ssi;
})();
|
function changeOfBaseQuestion(randomStream, params)
{
var number = randomStream.nextIntRange(240)+15;
var baseArray = [ {base: "decimal", value: number.toString(10), radix: 10}, {base: "hexadecimal", value: number.toString(16), radix: 16}, {base: "binary", value: number.toString(2), radix: 2} ];
randomStream.shuffle(baseArray);
this.a = baseArray[0];
this.b = baseArray[1];
//Array of {String, bool} pairs: the string representation of a number in a particular base
//and a flag indicating whether or not it is the correct answer.
this.answerChoices = [ {value: this.b.value, flag: true},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false},
{value: (randomStream.nextIntRange(240)+15).toString(this.b.radix), flag: false} ]
randomStream.shuffle(this.answerChoices);
//Find the correct answer
this.correctIndex = 0;
for(var i=0; i<this.answerChoices.length; i++)
{
if(this.answerChoices[i].flag == true)
this.correctIndex = i;
}
this.formatQuestion = function(format) {
switch (format) {
case "HTML": return this.formatQuestionHTML();
}
return "unknown format";
};
this.formatQuestionHTML = function () {
var questionText = "<p>Convert " + this.a.value + " from " + this.a.base + " to " + this.b.base + ".</p>";
questionText += "<p><strong>a) </strong>"
+ this.answerChoices[0].value + "<br><strong>b) </strong>"
+ this.answerChoices[1].value + "<br><strong>c) </strong>"
+ this.answerChoices[2].value + "<br><strong>d) </strong>"
+ this.answerChoices[3].value + "</p>";
return questionText;
};
this.formatAnswer = function(format) {
switch (format) {
case "HTML": return this.formatAnswerHTML();
}
return "unknown format"; // TODO: consider exception
};
this.formatAnswerHTML = function () {
var text = String.fromCharCode(this.correctIndex + 97); //0 = 'a', 1 = 'b', 2 = 'c', etc...
return text;
};
};
|
angular.module('inviteFactory', ['firebase'])
.factory('invite', ['$firebaseObject', '$http' , function ($firebaseObject, $http) {
var inviteFactory = {};
// mandrill API key ** free version API key only for production **
// in real use case, should store this securely
var mandrillKey = 'ul35c_Y39BxIZUIUa_HIog';
inviteFactory.sendEmailInvitation = function (sender, orgName, recipient, recipientEmail) {
// in production: use localhost for testing
// change link when deployed
var link = 'http://'+window.host+':3000/#/'+orgName+'/signup';
var orgId;
var orgRef = new Firebase('https://bizgramer.firebaseio.com/'+orgName);
var orgObj = $firebaseObject(orgRef);
orgObj.$loaded()
.then(function() {
// query firebase db to get the orgId for the logged in user's org
orgId = orgObj.orgKey;
var params = {
"key": mandrillKey,
"message": {
"from_email": sender+"."+orgName+"@Hiver.com",
"to":[{"email":recipientEmail}],
"subject": "Hey "+recipient+" go signup at Hive!",
"html":
"<h1>"+sender+" invited you to sign up for "+orgName+" at Hive</h1><h2>Your OrgID is "+orgId+"</h2><h3><a href='"+link+"''>"+link+"</a></h3>",
"autotext": true,
"track_opens": true,
"track_clicks": true
}
}; // end params
// send ajax request to Mandrill api for email invite
$http.post('https://mandrillapp.com/api/1.0/messages/send.json', params)
.success(function() {
console.log('email invite sent successfully');
})
.error(function() {
console.log('error sending email invite');
});
})
.catch(function (error) {
console.log('error', error);
});
}; //end .sendEmailInvitation
return inviteFactory;
}]);
|
/**
* Created by DOCer on 2017/7/11.
*/
import {connect} from 'app';
import UI from './UI/';
export default connect(
({test}) => (test),
{
onStart({dispatch, getState}){
dispatch({
type: "test/showTableLoading"
});
// ajax request after empty completing
setTimeout(() => {
dispatch({
type: "test/hideTableLoading",
});
dispatch({
type: "test/setSelectedRowKeys",
payload: [2]
});
}, 800);
},
onChange({dispatch, getState}, selectedRowKeys){
dispatch({
type: "test/setSelectedRowKeys",
payload: selectedRowKeys
});
},
onPanelChange({dispatch, getState}, {mode, data}){
console.log(data, mode);
},
onCascaderChange({dispatch, getState}, value){
console.log(value);
},
onCollapseChange({dispatch, getState}, key){
console.log(key);
},
onDecline ({dispatch, getState}){
let percent = getState().test.progressData.percent - 10;
if (percent < 0) {
percent = 0;
}
dispatch({
type: "test/decline",
payload: percent
});
},
onIncrease ({dispatch, getState}){
let percent = getState().test.progressData.percent + 10;
if (percent > 100) {
percent = 100;
}
dispatch({
type: "test/increase",
payload: percent
});
},
}
)(UI);
|
function AddressBook () {
this.contacts=[];
this.initialComplete = false;
AddressBook.prototype.addContact= function(newContact) {
this.contacts.push(newContact);
};
AddressBook.prototype.getContact = function(index) {
return this.contacts[index];
};
AddressBook.prototype.deleteContact = function(index) {
this.contacts.splice(index, 1);
};
AddressBook.prototype.getInitialContacts = function(cb) {
var self = this;
setTimeout(function() {
self.initialComplete = true;
if (cb) {
return cb();
}
}, 3);
};
}
|
import ListaDeNotas from "./ListaDeNotas"
export default ListaDeNotas
|
'use strict';
const {BrowserWindow, app} = require('electron');
const test = require('tape-async');
const delay = require('delay');
const {
appReady,
focusWindow,
minimizeWindow,
restoreWindow,
windowVisible
} = require('.');
let win;
test('exports an appReady function', async t => {
t.is(typeof appReady, 'function');
});
test('appReady return a promise that resolve when electron app is ready', async t => {
await appReady();
// We could create a window, because the app is ready
win = new BrowserWindow({show: false});
await delay(400);
t.is(typeof win, 'object');
});
test('focusWindow return a promise that resolve when window is focused', async t => {
const browser = new BrowserWindow();
// browser.loadURL(`file://${__dirname}/index.html`);
await windowVisible(browser);
t.true(await focusWindow(browser));
t.true(browser.isFocused());
browser.close();
});
test('minimizeWindow return a promise that resolve when window is minimized', async t => {
const browser = new BrowserWindow();
await windowVisible(browser);
t.false(browser.isMinimized());
t.true(await minimizeWindow(browser));
t.true(browser.isMinimized());
browser.close();
});
test('restoreWindow return a promise that resolve when window is restored', async t => {
const browser = new BrowserWindow();
await windowVisible(browser);
t.true(await minimizeWindow(browser));
t.true(browser.isMinimized());
t.true(await restoreWindow(browser));
await delay(100);
t.false(browser.isMinimized());
browser.close();
});
test('app quit', t => {
app.on('window-all-closed', () => app.quit());
t.end();
win.close();
});
|
import Instruction from './Instruction';
import Container from './Container';
import Share from './Share';
import React from 'react';
import request from 'superagent';
var Mememe = React.createClass({
getInitialState (){
var memesGenerated = false;
return{
memesGenerated: memesGenerated
};
},
generateMemes (descriptions){
for(var key in descriptions) {
var VALUE = descriptions[key];
var YOUR_API_KEY = "xxx";
var YOUR_CSE_ID = "yyy";
var searchQuery = `https://www.googleapis.com/customsearch/v1?key=${YOUR_API_KEY}&cx=${YOUR_CSE_ID}&q=${VALUE}&searchType=image&fileType=jpg&imgSize=small&alt=json`
request
.get(searchQuery)
.end((err, results) => {
debugger
})
debugger
}
var memesGenerated = true;
this.setState({memesGenerated: memesGenerated});
},
render (){
var generateMemes = this.generateMemes;
var memesGenerated = this.state.memesGenerated;
return (
<div className="mememe">
<Instruction/>
<Container
memesGenerated={memesGenerated}
generateMemes={generateMemes}/>
<Share/>
</div>
)
}
});
module.exports = Mememe;
|
var Deferred = require('stupid-deferred')
var Imageloader = require('stupid-imageloader');
/**
* Image collection loader
* @constructor
*/
function Imagesloader(opts){
/**
* @define {object} Collection of public methods.
*/
var self = {};
/**
* @define {object} Options for the constructor
*/
var opts = opts || {};
/**
* @define {object} A image loader object
*/
var imageloader = Imageloader();
/**
* @define {array} A holder for when an image is loaded
*/
var imgs = [];
/**
* @define {array} A holder for the image src that should be loaded
*/
var srcs = [];
/**
* @define {object} A promise container for promises
*/
var def;
/**
* Load a collection of images
* @example imageloader.load(['img1.jpg', 'img2.jpg', 'img3.jpg']).success(function(){ // Do something });
* @param {array} images A collection of img object or img.src (paths)
* @config {object} def Create a promise object
* @return {object} Return the promise object
*/
function load(images){
def = Deferred();
/**
* Check if the images is img objects or image src
* return string of src
*/
srcs = convertImagesToSrc(images);
/**
* Loop through src's and load image
*/
for (var i = 0; i < srcs.length; i++) {
imageloader.load(srcs[i])
.success(function(img){
/** call imageloaded a pass the img that is loaded */
imageLoaded(img);
})
.error(function(msg){
def.reject(msg + ' couldn\'t be loaded');
});
};
return def.promise;
}
/**
* Image loaded checker
* @param {img} img The loaded image
*/
function imageLoaded(img){
/** Notify the promise */
def.notify("notify");
/** Add the image to the imgs array */
imgs.push(img);
/** If the imgs array size is the same as the src's */
if(imgs.length == srcs.length){
/** First sort images, to have the same order as src's */
sortImages();
/** Resolve the promise with the images */
def.resolve(imgs);
}
}
/**
* Convert img to src
* @param {array} imgs A collection og img/img paths
* @config {array} src A temporally array for storing img path/src
* @return {array} Return an array of img src's
*/
function convertImagesToSrc(imgs){
var src = [];
for (var i = 0; i < imgs.length; i++) {
/** If the img is an object (img) get the src */
if(typeof imgs[i] == 'object'){
src.push(imgs[i].src);
}
};
/** If the src array is null return the original imgs array */
return src.length ? src : imgs;
}
/**
* Sort images after the originally order
* @config {array} arr A temporally array for sorting images
*/
function sortImages(){
var arr = [];
/**
* Create a double loop
* And match the order of the srcs array
*/
for (var i = 0; i < srcs.length; i++) {
for (var j = 0; j < imgs.length; j++) {
var str = imgs[j].src.toString();
var reg = new RegExp(srcs[i])
/** If srcs matches the imgs add it the the new array */
if(str.match(reg)) arr.push(imgs[j]);
};
};
/** Override imgs array with the new sorted arr */
imgs = arr;
}
/**
* Public methods
* @public {function}
*/
self.load = load;
/**
* @return {object} Public methods
*/
return self;
}
/** @export */
module.exports = Imagesloader;
|
var reactTools = require('react-tools');
var path = require('path');
var mkdirp = require('mkdirp');
var fs = require('fs');
module.exports = function(root, options) {
var dest = options && options.dest || root;
return function(req, res, next) {
if (!req.path.match(/\.js$/)) {
return next();
}
var jsPath = path.join(dest, req.path);
var jsxPath = path.join(root, req.path + 'x');
function transform() {
fs.readFile(jsxPath, 'utf8', function (err, jsx) {
var annotationAdded = false;
if (!jsx.match(/\/[\*\s]*\@jsx/)) {
jsx = "/** @jsx React.DOM */\n\n" + jsx;
annotationAdded = true;
}
try {
var js = reactTools.transform(jsx)
if (annotationAdded) {
js = js.split("\n").slice(1).join("\n");
}
} catch (err) {
return next(err);
}
mkdirp(path.dirname(jsPath), 511, function() {
fs.writeFile(jsPath, js, 'utf8', next);
});
});
}
fs.stat(jsxPath, function(err, jsxStats) {
if (err) {
return next('ENOENT' == err.code ? null : err);
}
fs.stat(jsPath, function(err, jsStats) {
if (err) {
return 'ENOENT' == err.code ? transform() : next(err);
}
if (jsxStats.mtime > jsStats.mtime) {
return transform();
} else {
next();
}
});
});
}
};
|
var is = function(x) {
return (elem) => elem && elem.nodeType === x;
};
// commented-out methods are not being used
module.exports = {
elem: is(1),
attr: is(2),
text: is(3),
// cdata: is(4),
// entity_reference: is(5),
// entity: is(6),
// processing_instruction: is(7),
comment: is(8),
doc: is(9),
// document_type: is(10),
doc_frag: is(11)
// notation: is(12),
};
|
const katex = require('katex')
const renderKatexFormula = function(text, displayMode) {
try {
return katex.renderToString(text, { displayMode: displayMode })
} catch (err) {
console.log(
'Katex error trying to parse: "' + text + '". Description: ' + err
)
}
}
module.exports = function(inlineMathSelector, displayMathSelector) {
const inlineVsDisplayLogic =
typeof displayMathSelector !== 'undefined'
? 'separateSelector'
: 'spanIsInline'
inlineMathSelector = arguments.length > 0 ? inlineMathSelector : '.math'
return function(deck) {
let foundMath = false
let mathElements
switch (inlineVsDisplayLogic) {
case 'separateSelector':
mathElements = deck.parent.querySelectorAll(inlineMathSelector)
Array.from(mathElements).forEach(el => {
el.innerHTML = renderKatexFormula(el.innerHTML, false)
foundMath = true
})
mathElements = deck.parent.querySelectorAll(displayMathSelector)
Array.from(mathElements).forEach(el => {
el.innerHTML = renderKatexFormula(el.innerHTML, true)
foundMath = true
})
break
case 'spanIsInline':
mathElements = deck.parent.querySelectorAll(inlineMathSelector)
Array.from(mathElements).forEach(el => {
el.innerHTML = renderKatexFormula(
el.textContent,
el.tagName.toLowerCase() !== 'span'
)
foundMath = true
})
break
}
if (foundMath) {
try {
require('katex/dist/katex.min.css')
} catch (e) {
console.log(
'It was not possible to load the CSS from KaTeX. Details: ' + e
)
}
}
}
}
|
import React from "react";
import PropTypes from "prop-types";
import styled from "styled-components";
import Image, { thumbnailSizes } from "@crave/farmblocks-image";
import { fontTypes } from "@crave/farmblocks-text";
const Icon = styled.div`
font-size: ${({ iconFontSize }) => iconFontSize || "72px"};
color: ${fontTypes.SUBTLE};
`;
const Thumbnail = ({ imageSrc, icon, iconFontSize }) => {
if (imageSrc) {
return (
<Image className="thumbnail" size={thumbnailSizes.LARGE} src={imageSrc} />
);
}
if (icon) {
return (
<Icon className="icon-wrapper" iconFontSize={iconFontSize}>
{icon}
</Icon>
);
}
return null;
};
Thumbnail.propTypes = {
imageSrc: PropTypes.string,
iconFontSize: PropTypes.string,
icon: PropTypes.node,
};
export default Thumbnail;
|
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');
// Connect to DB
var dbConfig = require('./config/db');
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url,function(res,err){
if(err){ console.log('ERROR connecting to : ' + dbConfig.url + '. ' + err); process.exit(0);}
else {
if ( res === undefined ) console.log('connected to ' + dbConfig.url );
else { console.log('ERROR connecting to : ' + dbConfig.url + '. ' + res.errmsg); process.exit(0);}
}
});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.locals.moment = require('moment');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'mySecretKey',
resave: true,
saveUninitialized: true})
);
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize Passport
var initPassport = require('./passport/init');
initPassport(passport);
var routes = require('./routes/index');
var auth = require('./routes/auth')(passport);
var agenda = require('./routes/agenda');
app.use('/', routes);
app.use('/auth', auth);
app.use('/agenda', agenda);
// 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: {}
});
});
module.exports = app;
|
/**
* @jest-environment ./__tests__/html/__jest__/WebChatEnvironment.js
*/
describe('deprecated <Localize>', () => {
test('should localize text in navigator language', () => runHTMLTest('deprecated.localize.html'));
test('should localize text in "en"', () => runHTMLTest('deprecated.localize.html#l=en'));
test('should localize text in "yue"', () => runHTMLTest('deprecated.localize.html#l=yue'));
});
|
/**
* Created by twi18192 on 25/08/15.
*/
var React = require('react');
var mainPaneStore = require('../stores/mainPaneStore');
var mainPaneActions = require('../actions/mainPaneActions');
var ButtonStyle = {
backgroundColor: 'grey',
height: 25,
width: 70,
borderRadius: 8,
borderStyle:'solid',
borderWidth: 1,
borderColor: 'black',
fontFamily: 'Verdana',
// color: 'white',
textAlign: 'center',
display: 'inline-block',
cursor: 'pointer',
MozUserSelect: 'none'
};
var ButtonTitlePadding = {
position: 'relative',
top: -6
};
function getConfigButtonState(){
return {
configPanelOpen:mainPaneStore.getConfigPanelState()
}
}
var ConfigButton = React.createClass({
getInitialState: function(){
return {
configPanelOpen: mainPaneStore.getConfigPanelState()
}
},
_onChange: function(){
this.setState(getConfigButtonState)
},
handleActionConfigToggle:function(){
mainPaneActions.toggleConfigPanel("this is the item")
},
componentDidMount: function(){
mainPaneStore.addChangeListener(this._onChange)
},
componentWillUnmount: function(){
mainPaneStore.removeChangeListener(this._onChange)
},
render: function() {
return(
<div>
<div id="config" style={ButtonStyle} onClick={this.handleActionConfigToggle} ><span style={ButtonTitlePadding}>Config</span>
</div>
</div>
)}
});
module.exports = ConfigButton;
|
'use strict';
/**
* Profile class that normalizes profile data fetched from authentication provider
*/
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function formatAddress(address) {
var result = address;
if (result) {
result.formatted = result.street_address + '\n' + result.postal_code + ' ' + result.locality + '\n' + result.country;
return result;
}
return null;
}
var Profile =
/**
* @param data {object}
*/
exports.Profile = function Profile(data) {
_classCallCheck(this, Profile);
var fields = ['_raw', 'address', 'at_hash', 'birthdate', 'email_verified', 'email', 'family_name', 'gender', 'given_name', 'id', 'locale', 'middle_name', 'name', 'nickname', 'phone_number_verified', 'phone_number', 'picture', 'preferred_username', 'profile', 'provider', 'sub', 'updated_at', 'website', 'zoneinfo'];
this._raw = data;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var field = _step.value;
if (data.hasOwnProperty(field)) {
var value = data[field];
if (field === 'address') {
this.address = formatAddress(data.address);
} else {
this[field] = value || null;
}
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
};
|
import React from 'react';
import PureComponent from 'react-pure-render/component';
class Description extends PureComponent {
render() {
return (
<div><input type="text" value="" placeholder="I am description" /></div>
);
}
}
export default Description;
|
'use strict';
const fs = require('fs');
const exec = require('child_process').exec;
const helpers = require('yeoman-test');
const assert = require('yeoman-assert');
const util = require('./support/util');
const defaultAnswers = require('./support/defaultPromptAnswers');
const promptOptions = require("../generators/app/promptOptions");
const defaultInit = require('./support/defaultInit');
const initTest = require('./support/initTest');
const answers = Object.assign({},defaultAnswers, {
"moduleType": promptOptions.moduleType.ES6_MODULES,
"language": promptOptions.language.ES6,
"advancedOptions": [
promptOptions.advanced.DEVLIB,
promptOptions.advanced.WEBSTORM
]
});
describe('ES Modules + ES6 + WebStorm', function () {
this.timeout(125000)
before(initTest(answers))
before(function(done) {
const that = this;
this.app = helpers
.run(require.resolve('../generators/app'))
.withGenerators([[helpers.createDummyGenerator(),require.resolve('../generators/class')]])
.withOptions({
'skip-welcome-message': true,
'skip-message': true,
'skip-install': false
})
.withPrompts(answers).then(function(dir) {return defaultInit(__filename, dir)}).then(function(dir) {
that.dir = dir;
done();
})
});
describe('check files', function() {
it('generates base files', function () {
assert.file([
'app/index.html',
'app/scripts/app.js',
'app/typings/yfiles-api-modules-ts43-webstorm.d.ts',
'package.json',
'webpack.config.js',
'app/lib/yfiles/yfiles.js',
'.idea/libraries/yFiles_for_HTML.xml',
'.idea/jsLibraryMappings.xml',
'.idea/testApp.iml',
'.idea/modules.xml',
'.idea/misc.xml',
'.idea/webResources.xml'
]);
assert.noFile([
'app/lib/es2015-shim.js',
'app/styles/yfiles.css',
'jsconfig.json',
'bower.json',
'tsconfig.json',
'app/scripts/license.json',
'app/typings/yfiles-api-umd-ts43-vscode.d.ts',
'app/typings/yfiles-api-umd-ts43-webstorm.d.ts',
'Gruntfile.js'
]);
});
});
describe('build result', function() {
it('created the bundles and sourcemaps', function() {
assert.file([
'app/dist/app.js',
'app/dist/app.js.map',
'app/dist/lib.js'
]);
});
it('uses webpack 4', function() {
assert.fileContent('package.json', /"webpack": "\^?4/)
})
it('runs', function (done) {
util.maybeOpenInBrowser(this.dir,done);
});
it('succeeds to run production build', function (done) {
const dir = this.dir;
const child = exec('npm run production', {cwd: dir.cwd}, function(error, stdout, stderr) {
console.log("\nbuild done!")
assert.ok(error === null, "Production build failed: "+error);
util.maybeOpenInBrowser(dir,done);
});
child.stdout.on('data', function(data) {
console.log(data.toString());
});
});
});
});
|
import { expect } from 'chai';
import { createTheme } from '@mui/material/styles';
import defaultTheme from './defaultTheme';
import responsiveFontSizes from './responsiveFontSizes';
describe('responsiveFontSizes', () => {
it('should support unitless line height', () => {
const defaultVariant = {
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
fontSize: '6rem',
fontWeight: 300,
letterSpacing: '-0.01562em',
lineHeight: 1,
};
const theme = createTheme({
typography: {
h1: defaultVariant,
},
});
const { typography } = responsiveFontSizes(theme);
expect(typography.h1).to.deep.equal({
...defaultVariant,
fontSize: '3.5rem',
[`@media (min-width:${defaultTheme.breakpoints.values.sm}px)`]: { fontSize: '4.75rem' },
[`@media (min-width:${defaultTheme.breakpoints.values.md}px)`]: { fontSize: '5.5rem' },
[`@media (min-width:${defaultTheme.breakpoints.values.lg}px)`]: {
fontSize: defaultVariant.fontSize,
},
});
});
it('should disable vertical alignment', () => {
const defaultVariant = {
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
fontSize: '6rem',
fontWeight: 300,
letterSpacing: '-0.01562em',
lineHeight: '6rem',
};
const theme = createTheme({
typography: {
h1: defaultVariant,
},
});
const { typography } = responsiveFontSizes(theme, {
disableAlign: true,
});
expect(typography.h1).to.deep.equal({
...defaultVariant,
fontSize: '3.5rem',
[`@media (min-width:${defaultTheme.breakpoints.values.sm}px)`]: { fontSize: '4.75rem' },
[`@media (min-width:${defaultTheme.breakpoints.values.md}px)`]: { fontSize: '5.375rem' },
[`@media (min-width:${defaultTheme.breakpoints.values.lg}px)`]: {
fontSize: defaultVariant.fontSize,
},
});
});
describe('when requesting a responsive typography with non unitless line height and alignment', () => {
it('should throw an error, as this is not supported', () => {
const theme = createTheme({
typography: {
h1: {
lineHeight: '6rem',
},
},
});
expect(() => {
responsiveFontSizes(theme);
}).toThrowMinified(
'MUI: Unsupported non-unitless line height with grid alignment.\n' +
'Use unitless line heights instead.',
);
});
});
});
|
import * as THREE from 'three';
import PropTypes from 'prop-types';
import MaterialDescriptorBase from './MaterialDescriptorBase';
class LineBasicMaterialDescriptor extends MaterialDescriptorBase {
constructor(react3RendererInstance) {
super(react3RendererInstance);
this.hasColor();
this.hasProp('linewidth', {
type: PropTypes.number,
simple: true,
default: 1,
});
// what are these properties used for?
[
'linecap',
'linejoin',
].forEach((propName) => {
this.hasProp(propName, {
type: PropTypes.oneOf([
'round',
]),
simple: true,
default: 'round',
});
});
this.hasProp('fog', {
type: PropTypes.bool,
update(threeObject, fog, existsInProps) {
if (existsInProps) {
threeObject.fog = fog;
}
threeObject.needsUpdate = true;
},
updateInitial: true,
default: true,
});
}
construct(props) {
const materialDescription = this.getMaterialDescription(props);
return new THREE.LineBasicMaterial(materialDescription);
}
}
module.exports = LineBasicMaterialDescriptor;
|
/* eslint-env mocha */
const path = require('path');
const should = require('should');
const { openDb, closeDb } = require('../../lib/db');
const gtfs = require('../..');
const config = {
agencies: [{
agency_key: 'caltrain',
path: path.join(__dirname, '../fixture/caltrain_20160406.zip')
}],
verbose: false
};
describe('gtfs.getLevels():', () => {
before(async () => {
await openDb(config);
await gtfs.import(config);
});
after(async () => {
await closeDb();
});
it('should return empty array if no levels', async () => {
const levelId = 'not_real';
const results = await gtfs.getLevels({
level_id: levelId
});
should.exists(results);
results.should.have.length(0);
});
});
|
(function($) {
var UserInputView = Backbone.View.extend({
el : '#UserInput',
initialize : function() {
this.helloListView = new HelloListView();
},
events : {
'click button' : 'addToHelloCollection'
},
addToHelloCollection : function(e) {
var hello = new Hello({
name : this.$('input').val()
});
this.helloListView.collection.add(hello);
}
});
var Hello = Backbone.Model.extend({
initialize : function() {
this.name = 'name'
}
});
var HelloView = Backbone.View.extend({
tagName : 'li',
render : function() {
$(this.el).html('Hello ' + this.model.get('name'));
return this;
}
});
var HelloList = Backbone.Collection.extend({
model : Hello
});
var HelloListView = Backbone.View.extend({
el : '#HelloList',
initialize : function() {
_.bindAll(this, 'render', 'appendToHelloUL');
this.collection = new HelloList();
this.collection.bind('add', this.appendToHelloUL);
},
render:function(){
$.each(this.collection.models, function(i, helloModel){
self.appendToHelloUL(helloModel);
});
},
appendToHelloUL : function(helloModel) {
var helloView = new HelloView({
model : helloModel
});
$(this.el).append(helloView.render().el);
}
});
new UserInputView();
})(jQuery);
|
// This file defines an API that would be nice, but it's not required
// Initialize the editor
var editor = new Editor("");
// Activate/deactivate the editor
editor.active(true || false);
// Set a new action
editor.add("", {
shortcut: {} || "" || false, // The key for Ctrl+key or { key: "esc" }
menu: {} || "" || false, // The html or icon to show
init: function(){} || false, // Called when activating an editor
action: function(){} || false, // Click or shortcut for that action
destroy: function(){} || false // Deactivating an editor
});
// The editor is initialized or re-activated
editor.on("init", function(){});
// Some action is triggered for any reason
editor.on("action", function(){});
// Registered action
editor.on("action:save", function(){});
// The editor is destroyed or de-activated
editor.on("destroy", function(){});
// The editor re-reads its data
editor.on("refresh", function(){});
// Some part of the editor is clicked or touched
editor.on("click", function(){});
// Some key is introduced (for example, "tab")
editor.on("key", function(){});
editor.on("select", function(){});
// Special events
editor.on("<event>:before", function(){});
editor.on("<event>:pre", function(){});
editor.on("<event>:post", function(){});
editor.on("<event>:after", function(){});
editor.on("<event>:none", function(){});
// Example (not part of the API)
editor.action.list = { actionname1: function(){}, actionname2: function(){} };
editor.menu.inline.list = { actionname1: "html1", actionname2: "html2" };
editor.menu.block.list = { actionname1: "html1", actionname2: "html2" };
editor.menu.list = {};
editor.shortcuts.list = { actionname1: { control: true, keyCode: 16 }, actionname2: { control: false, keyCode: 27 } };
editor.shortcuts.get(e);
|
var quizQuistions = {
name:"Super Hero Name Quiz",
description:"How many super heroes can you name?",
headline:"What is the real name of ",
mainquestionList: [
{ "questionName": "Superman", "answer": "Clarke" },
{ "questionName": "Batman", "answer": "Bruce" },
{ "question": "Wonder Woman", "answer": "Dianna" }
]
}
// dom element grab
var $finalScore = document.getElementById("score");
var $ListOfquestions = document.getElementById('displayQuestion');
var $ListOfFeedback = document.getElementById('feedback')
var $startButton = document.getElementById('button');
var $mainForm = document.getElementById('mainform');
var $clockTimer = document.getElementById('clocktimer');
function updateDom(element, content, klass){
var p = element.firstChild || document.createElement("p");
p.textContent = content;
element.appendChild(p);
if(klass){
p.className = klass;
}
}
//hide function
function hide(element){
element.style.display = "none";
}
//hide show button
function show(element){
element.style.display = "block";
}
// event listener for click button
$startButton.addEventListener('click', function (){
play(quizQuistions);
}, false);
// Initial hide main form
hide($mainForm);
function play(quizQuistions){
var score = 0;
updateDom($finalScore, score);
// initialize time and set up an interval that counts down every second
var time = 20;
updateDom($clockTimer, time);
var interval = window.setInterval(timeCoutdown, 1000)
//hide button but show form
hide($startButton);
show($mainForm);
// main form event listener
$mainForm.addEventListener('submit', function(event){
event.preventDefault();
check($mainForm[0].value);
}, false);
var i = 0;
chooseQuestion();
function chooseQuestion(){
var questionVal = quizQuistions.mainquestionList[i].questionName;
ask(questionVal);
}
function ask(questionAskParamater) {
updateDom($ListOfquestions, quizQuistions.headline + questionAskParamater )
$mainForm[0].value = "";
$mainForm[0].focus();
}
function check(answer) {
if(answer === quizQuistions.mainquestionList[i].answer){
updateDom($ListOfFeedback, "Answer Correct", "right");
score++;
updateDom($finalScore, score);
} else {
updateDom($ListOfFeedback, "Answer Wrong", "wrong");
}
// check if any quistion available
i++
if(i === quizQuistions.mainquestionList.length){
finalGameOver()
} else {
chooseQuestion();
}
}
// time countdown and decrease the time
function timeCoutdown(){
time --;
updateDom($clockTimer, time);
if(time <= 0){
finalGameOver();
}
}
// game over
function finalGameOver(){
updateDom($ListOfquestions, "Gameover, Your scored is " +score+ " points");
window.clearInterval(interval);
hide($mainForm);
show($startButton);
}
}
|
#!/usr/bin/env node
/**
* @file stream.js
*
* Custom object to inherit from EventEmitter, with the help of `util'
*
*/
var events = require('events');
function Stream() {
events.EventEmitter.call(this);
}
util.inherits(Stream, events,EventEmitter);
|
/**
* Created by admin on 14.09.2015.
*/
var gulp = require('gulp');
var less = require('gulp-less');
var csso = require('gulp-csso');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var ngAnnotate = require('gulp-ng-annotate');
gulp.task('js', function () {
gulp.src(['js/**/*.js'])
.pipe(sourcemaps.init())
.pipe(concat('app.js'))
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('./dist/js'));
});
gulp.task('css', function () {
gulp.src('./less/**/*.less')
.pipe(concat('styles.less'))
.pipe(less())
.pipe(gulp.dest('./css'))
.pipe(csso())
.pipe(gulp.dest('./dist/css'));
});
gulp.task('images', function () {
gulp.src('./img/**/*')
.pipe(imagemin())
.pipe(gulp.dest('./dist/img'));
});
gulp.task('watch', function () {
gulp.watch('./less/**/*.less', function() {
gulp.run('css');
});
gulp.watch('./img/**/*', function() {
gulp.run('images');
});
gulp.watch('./js/**/*', function() {
gulp.run('js');
});
});
gulp.task('build', function () {
gulp.run('js');
gulp.run('css');
gulp.run('images');
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _webpackDevServer = __webpack_require__(1);
var _webpackDevServer2 = _interopRequireDefault(_webpackDevServer);
var _webpack = __webpack_require__(2);
var _webpack2 = _interopRequireDefault(_webpack);
var _webpackConfigDev = __webpack_require__(3);
var _webpackConfigDev2 = _interopRequireDefault(_webpackConfigDev);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var server = new _webpackDevServer2.default((0, _webpack2.default)(_webpackConfigDev2.default), {
publicPath: _webpackConfigDev2.default.output.publicPath,
hot: true
});
server.listen(8080, 'localhost', function () {
console.log("Dev-Server with Hot Reloading");
});
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = require("webpack-dev-server");
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = require("webpack");
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var webpack = __webpack_require__(2);
module.exports = {
entry: ['webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/client/main'],
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'react-hot!babel-loader?presets[]=es2015&presets[]=es2016&presets[]=react'
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
output: {
path: __dirname + '/public/js',
publicPath: 'http://localhost:8080/js/',
filename: 'application.js'
},
plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin()]
};
/***/ }
/******/ ]);
|
/*** @jsx React.DOM */
var React = require('react');
var JigsawStore = require('../stores/JigsawStore');
var JigsawActions = require('../actions/JigsawActions');
/**
* A button to update the random number generator seed.
* @type {*|Function}
*/
var Randomizer = React.createClass({
getInitialState: function() {
return {seed: JigsawStore.getRandSeed()};
},
componentDidMount: function() {
JigsawStore.addChangeListener(this._onChange);
},
componentWillUnmount: function() {
JigsawStore.removeChangeListener(this._onChange);
},
render: function() {
var disabled = ! this.state.canRedo;
return (
<button className="btn btn-default" onClick={this._randomize}>Randomize</button>
);
},
_randomize: function() {
JigsawActions.randomize();
return false;
},
_onChange: function() {
this.setState({seed: JigsawStore.getRandSeed()})
}
});
module.exports = Randomizer;
|
lychee.define('fertilizer.Main').requires([
'lychee.Input',
'lychee.data.JSON',
'fertilizer.data.Filesystem',
'fertilizer.data.Shell',
'fertilizer.template.html.Application',
'fertilizer.template.html.Library',
'fertilizer.template.html-nwjs.Application',
'fertilizer.template.html-nwjs.Library',
'fertilizer.template.html-webview.Application',
'fertilizer.template.html-webview.Library',
'fertilizer.template.node.Application',
'fertilizer.template.node.Library'
]).includes([
'lychee.event.Emitter'
]).exports(function(lychee, fertilizer, global, attachments) {
var _lychee = lychee;
var _path = require('path');
var _JSON = lychee.data.JSON;
/*
* FEATURE DETECTION
*/
var _defaults = {
project: null,
identifier: null,
settings: null
};
/*
* IMPLEMENTATION
*/
var Class = function(settings) {
this.settings = lychee.extendunlink({}, _defaults, settings);
this.defaults = lychee.extendunlink({}, this.settings);
lychee.event.Emitter.call(this);
/*
* INITIALIZATION
*/
var that = this;
this.bind('load', function() {
var identifier = this.settings.identifier || null;
var project = this.settings.project || null;
var data = this.settings.settings || null;
if (identifier !== null && project !== null && data !== null) {
var platform = data.tags.platform[0] || null;
var variant = data.variant || null;
var settings = _JSON.decode(_JSON.encode(lychee.extend({}, data, {
debug: false,
sandbox: true,
type: 'export'
})));
var profile = {};
if (settings.profile instanceof Object) {
profile = settings.profile;
}
if (platform !== null && variant.match(/application|library/)) {
if (settings.packages instanceof Array) {
settings.packages = settings.packages.map(function(pkg) {
var id = pkg[0];
var path = _path.resolve(project, pkg[1]);
return [ id, path ];
});
}
var that = this;
var environment = new lychee.Environment(settings);
_lychee.setEnvironment(environment);
environment.debug = true;
environment.init(function(sandbox) {
if (sandbox !== null) {
// IMPORTANT: Don't use Environment's imperative API here!
// Environment identifier is /libraries/lychee/main instead of /libraries/lychee/html/main
environment.id = project + '/' + identifier.split('/').pop();
environment.type = 'build';
environment.debug = that.defaults.settings.debug;
environment.sandbox = that.defaults.settings.sandbox;
_lychee.setEnvironment(null);
that.trigger('init', [ project, identifier, platform, variant, environment, profile ]);
} else {
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "load" event');
if (typeof environment.global.console.serialize === 'function') {
var debug = environment.global.console.serialize();
if (debug.blob !== null) {
(debug.blob.stderr || '').trim().split('\n').map(function(line) {
return (line.indexOf(':') !== -1 ? line.split(':')[1].trim() : '');
}).forEach(function(line) {
console.error('fertilizer: ' + line);
});
}
}
that.destroy();
}
});
return true;
}
}
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "load" event');
this.destroy();
return false;
}, this, true);
this.bind('init', function(project, identifier, platform, variant, environment, profile) {
if (typeof fertilizer.template[platform] === 'object') {
var construct = fertilizer.template[platform][variant.charAt(0).toUpperCase() + variant.substr(1).toLowerCase()] || null;
if (construct !== null) {
var template = new construct({
environment: environment,
profile: profile,
filesystem: new fertilizer.data.Filesystem(project + '/build/' + identifier),
shell: new fertilizer.data.Shell(project + '/build/' + identifier)
});
template.then('configure');
template.then('build');
template.then('package');
template.bind('complete', function() {
console.info('fertilizer: SUCCESS ("' + project + ' | ' + identifier + '")');
this.destroy();
}, this);
template.bind('error', function(event) {
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "' + event + '" event');
this.destroy();
}, this);
template.init();
return true;
}
}
console.error('fertilizer: FAILURE ("' + project + ' | ' + identifier + '") at "init" event');
this.destroy();
return false;
}, this, true);
};
Class.prototype = {
/*
* MAIN API
*/
init: function() {
this.trigger('load', []);
},
destroy: function() {
this.trigger('destroy', []);
}
};
return Class;
});
|
(function () {
'use strict';
angular
.module('templateApp')
.controller('Page2Detail', Page2Detail);
Page2Detail.$inject = ['$routeParams', '$firebaseObject', 'FIREBASE_URL'];
/* @ngInject */
function Page2Detail($routeParams, $firebaseObject, FIREBASE_URL) {
/* jshint validthis: true */
var vm = this;
vm.title = 'Meeting Detail';
var ref = new Firebase(FIREBASE_URL + '/users/' + $routeParams.uid + '/meetings/' + $routeParams.meetingId);
vm.meeting = $firebaseObject(ref);
vm.meeting.$loaded(function(){
vm.dateTime = new Date(vm.meeting.date);
});
}
})();
|
import Discover from 'node-discover';
import EventEmitter from 'events';
export default class Discovery extends EventEmitter {
constructor(channel = 'handover') {
super();
this.channel = channel;
this.d = Discover();
this.d.join(this.channel, this.handleReceive.bind(this));
}
stop() {
this.d.leave(this.channel);
this.d.stop();
}
send(data) {
this.d.send(this.channel, data);
}
handleReceive(data, obj) {
this.emit('receive', {
address: this.findNodeById(obj.iid).address,
data: data,
obj: obj
});
}
findNodeById(id) {
var node;
this.d.eachNode((n) => {
if (n.id === id) {
node = n;
}
});
return node;
}
}
|
import {NotFound} from '.'
import {shallowRender} from '../../utils/testUtils'
import {expect} from 'chai'
import {findWithType, findAllWithType} from 'react-shallow-testutils'
describe('frontend not found view', () => {
it('renders not found', () => {
const component = shallowRender(NotFound, { className: 'MyComponent' })
expect(findWithType(component, 'h1').props.children).to.equal('Not found')
})
})
|
/* Requirements */
var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, mongoose = require('mongoose');
/* Initialization */
server.listen(3333);
mongoose.connect('mongodb://localhost/test');
/* Global variable setup */
var serverRoot = __dirname;
var Schema = mongoose.Schema;
/* DB Schemas */
var adminSchema = new Schema({
first_name: String,
last_name: String,
email: {type: [String], index: true},
password: String,
session_key: String
});
var userSchema = new Schema({
first_name: String,
last_name: String,
email: {type: [String], index: true},
secret_key: String,
has_voted: Boolean
});
/* Models */
var Admin = mongoose.model('Admin', adminSchema);
var User = mongoose.model('User', userSchema);
/* Get the server up and running */
app.use(express.static(serverRoot));
app.use(express.bodyParser());
app.get('/', function (req, res) {
res.sendfile(serverRoot + '/index.html');
});
app.post('/authenticate', function(req, res) {
var date = new Date();
console.log("Authentication request received at " + date);
Admin.findOne({email: req.body.email}, function(err, result) {
if(err) {
console.log("Error: " + err);
throw(err);
}
if(!result) {
//response to client for user not found/invalid email address
res.send(401, {invalid_email: true});
}
else {
if(req.body.password !== result.password) {
//response to client for invalid password
res.send(401, {invalid_password: true});
}
else {
//res.cookie('admin_id', )
res.send({we: "fuckingdidit"});
}
}
});
});
|
/*Problem 8. Number as words
Write a script that converts a number in the range [0
999]
to words, corresponding to its English pronunciation.*/
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
var numbers = [0, 9, 10, 12, 19, 25, 98, 98, 273, 400, 501, 617, 711, 999];
for(var ind = 0; ind < numbers.length; ind++){
console.log(numbers[ind] + '\t' + getString(numbers[ind]));
}
function getString(number){
var text = '',
hundreds = Math.floor(number / 100) % 10,
tens = Math.floor(number / 10) % 10,
ones = number % 10;
if(!hundreds && !tens && !ones){
text = 'zero';
}
if (hundreds) {
text += getDigit(hundreds) + ' hundred';
}
if (tens || ones) {
if (text.length) {
text += ' and ';
}
if (tens) {
if (tens === 1) {
return (text + getTeens(tens * 10 + ones)).capitalize();
}
text += getTens(tens);
}
if (ones) {
if(tens){
text += ' ';
}
text += getDigit(ones);
}
}
return text.capitalize();
}
function getDigit (digit) {
switch(digit){
case 0: return 'zero';
case 1: return 'one';
case 2: return 'two';
case 3: return 'three';
case 4: return 'four';
case 5: return 'five';
case 6: return 'six';
case 7: return 'seven';
case 8: return 'eight';
case 9: return 'nine';
default: return '';
}
}
function getTens (digit) {
switch(digit){
case 2: return 'twenty';
case 3: return 'thirty';
case 4: return 'forty';
case 5: return 'fifty';
case 6: return 'sixty';
case 7: return 'seventy';
case 8: return 'eighty';
case 9: return 'ninety';
default: return '';
}
}
function getTeens (digit) {
switch(digit){
case 10: return 'ten';
case 11: return 'eleven';
case 12: return 'twelve';
case 13: return 'thirteen';
case 14: return 'fourteen';
case 15: return 'fifteen';
case 16: return 'sixteen';
case 17: return 'seventeen';
case 18: return 'eighteen';
case 19: return 'nineteen';
default: return '';
}
}
|
class UserInput {
constructor(game) {
this.game = game;
this.keyCodeMapper = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
}
getUserInput(){
window.addEventListener("keydown", this.sendUserInput.bind(this));
}
sendUserInput(event) {
var input = this.keyCodeMapper[event.keyCode];
var previousDirection = this.game.snake.direction;
this.game.snake.setDirection(input, previousDirection);
}
}
module.exports = UserInput;
|
import { describe, it } from 'mocha';
import Immutable from 'immutable';
import deepFreeze from 'deep-freeze';
import { createStore } from 'redux';
import { createReducerTest, executeCbs } from './helpers';
import { defaultState as objDefaultState, actions as objActions } from './objectState/index';
import { defaultState as arrDefaultState, actions as arrActions } from './arrayState/index';
import { pathReducer } from '../';
const subscribedCbs = [];
const immObjDefaultState = Immutable.fromJS(objDefaultState); // Immutable state
const immArrDefaultState = Immutable.fromJS(arrDefaultState); // Immutable state
const objReducer = (state = immObjDefaultState, action = {}) => {
executeCbs(subscribedCbs, state, action);
// We return original state in order to not mutate it,
// So every test is done over the same initial state
return state;
};
const arrReducer = (state = immArrDefaultState, action = {}) => {
executeCbs(subscribedCbs, state, action);
// We return original state in order to not mutate it,
// So every test is done over the same initial state
return state;
};
deepFreeze(immObjDefaultState);
deepFreeze(immArrDefaultState);
deepFreeze(objActions);
deepFreeze(arrActions);
export default function executeTest() {
describe('Immutable object state store', () => {
const store = createStore(objReducer);
const test = createReducerTest(store, subscribedCbs, immObjDefaultState);
let action;
for (action in objActions) {
// test(..) ensures the state is defaultState before each dispatch
if (objActions.hasOwnProperty(action)) {
it(`dispatch ${objActions[action].type} action`, test(objActions[action]));
}
}
});
describe('Immutable array state store', () => {
const store = createStore(arrReducer);
const test = createReducerTest(store, subscribedCbs, immArrDefaultState);
let action;
for (action in arrActions) {
// test(..) ensures the state is defaultState before each dispatch
if (arrActions.hasOwnProperty(action)) {
it(`dispatch ${arrActions[action].type} action`, test(arrActions[action]));
}
}
});
describe('Immutable object state store with pathReducer wrapper', () => {
let action;
it('store should be correctly created with pathReducer wrapper', () => {
createStore(pathReducer(objReducer));
});
for (action in objActions) {
if (objActions.hasOwnProperty(action)) {
// We need to recreate store as the state is being modified after each dispatch
const store = createStore(pathReducer(objReducer));
const test = createReducerTest(store, subscribedCbs, immObjDefaultState, false);
it(`dispatch ${objActions[action].type} action`, test(objActions[action]));
}
}
});
describe('Immutable array state store with pathReducer wrapper', () => {
let action;
it('store should be correctly created with pathReducer wrapper', () => {
createStore(pathReducer(objReducer));
});
for (action in arrActions) {
if (arrActions.hasOwnProperty(action)) {
// We need to recreate store as the state is being modified after each dispatch
const store = createStore(pathReducer(arrReducer));
const test = createReducerTest(store, subscribedCbs, immArrDefaultState, false);
it(`dispatch ${arrActions[action].type} action`, test(arrActions[action]));
}
}
});
}
|
import Washi from '../washi'
describe('Chain', function() {
it('can chain objects', function() {
var obj = {}
var mock = jest.fn()
Washi.$.chain(obj).tap(mock)
expect(mock.mock.calls[0][0]).toEqual(obj)
})
it('can chain arrays', function() {
var arr = [1]
var result = Washi.$
.chain(arr)
.map(function(i) {
return i + 1
})
.valueOf()
expect(result).toEqual([2])
})
it('has access to the element on calls', function() {
var el = document.createElement('button')
var mock = jest.fn()
Washi.$
.chain(el)
.tap(mock)
.tap(mock)
expect(mock.mock.calls[0][0]).toEqual(el)
})
it('can chain multiple times', function() {
var el = document.createElement('button')
var mock = jest.fn()
Washi.$
.chain(el)
.tap(mock)
.tap(mock)
expect(mock.mock.calls.length).toEqual(2)
})
it('returns the result of a previous chain to the next if provided', function() {
var el = document.createElement('button')
var mock = jest.fn()
var result = Washi.$([el, el])
.map(function(el) {
return el.tagName
})
.reduce(function(a, b) {
return [a, b].join(' ')
}, '')
.valueOf()
.trim()
expect(result).toEqual('BUTTON BUTTON')
})
})
|
/*
* Kendo UI Complete v2013.2.918 (http://kendoui.com)
* Copyright 2013 Telerik AD. All rights reserved.
*
* Kendo UI Complete commercial licenses may be obtained at
* https://www.kendoui.com/purchase/license-agreement/kendo-ui-complete-commercial.aspx
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
kendo_module({
id: "mobile.shim",
name: "Shim",
category: "mobile",
description: "Mobile Shim",
depends: [ "popup" ],
hidden: true
});
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.mobile.ui,
Popup = kendo.ui.Popup,
SHIM = '<div class="km-shim"/>',
Widget = ui.Widget;
var Shim = Widget.extend({
init: function(element, options) {
var that = this,
app = kendo.mobile.application,
osname = app ? app.os.name : kendo.support.mobileOS.name,
ioswp = osname === "ios" || osname === "wp" || app.os.skin,
bb = osname === "blackberry",
align = options.align || (ioswp ? "bottom center" : bb ? "center right" : "center center"),
position = options.position || (ioswp ? "bottom center" : bb ? "center right" : "center center"),
effect = options.effect || (ioswp ? "slideIn:up" : bb ? "slideIn:left" : "fade:in"),
shim = $(SHIM).handler(that).hide();
Widget.fn.init.call(that, element, options);
that.shim = shim;
that.element = element;
if (!that.options.modal) {
that.shim.on("up", "hide");
}
(app ? app.element : $(document.body)).append(shim);
that.popup = new Popup(that.element, {
anchor: shim,
modal: true,
appendTo: shim,
origin: align,
position: position,
animation: {
open: {
effects: effect,
duration: that.options.duration
},
close: {
duration: that.options.duration
}
},
deactivate: function() {
shim.hide();
},
open: function() {
shim.show();
}
});
kendo.notify(that);
},
options: {
name: "Shim",
modal: true,
align: undefined,
position: undefined,
effect: undefined,
duration: 200
},
show: function() {
this.shim.css("height", this.shim.parent()[0].scrollHeight);
this.popup.open();
},
hide: function(e) {
if (!e || !$.contains(this.shim[0], e.target)) {
this.popup.close();
}
},
destroy: function() {
Widget.fn.destroy.call(this);
this.shim.kendoDestroy();
this.popup.destroy();
this.shim.remove();
}
});
ui.plugin(Shim);
})(window.kendo.jQuery);
|
import { StyleSheet } from 'react-native';
import { PRIMARY_COLOR, COLOR_WHITE } from '../../styles/colors';
const styles = StyleSheet.create({
toolbar: {
height: 56,
backgroundColor: PRIMARY_COLOR
},
container: {
flex: 1,
backgroundColor: PRIMARY_COLOR,
},
contentContaier: {
padding: 30,
},
registerButton: {
backgroundColor: COLOR_WHITE,
padding: 20,
borderRadius: 6,
marginBottom: 20,
alignItems: 'center'
},
registerButtonTitle: {
fontSize: 18,
color: PRIMARY_COLOR,
}
});
export { styles as default };
|
import { connect } from 'react-redux';
import Head from '../components/Head';
function mapStateToProps(state) {
return {
title: state.db.title,
...state.theme
}
}
export default connect(mapStateToProps)(Head);
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
var React;
var ReactDOM;
var ReactDOMComponentTree;
var ReactTestUtils;
var SelectEventPlugin;
describe('SelectEventPlugin', () => {
function extract(node, topLevelEvent) {
return SelectEventPlugin.extractEvents(
topLevelEvent,
ReactDOMComponentTree.getInstanceFromNode(node),
{target: node},
node,
);
}
beforeEach(() => {
React = require('react');
ReactDOM = require('react-dom');
ReactTestUtils = require('react-dom/test-utils');
// TODO: can we express this test with only public API?
ReactDOMComponentTree = require('../../client/ReactDOMComponentTree')
.default;
SelectEventPlugin = require('../SelectEventPlugin').default;
});
it('should skip extraction if no listeners are present', () => {
class WithoutSelect extends React.Component {
render() {
return <input type="text" />;
}
}
var rendered = ReactTestUtils.renderIntoDocument(<WithoutSelect />);
var node = ReactDOM.findDOMNode(rendered);
node.focus();
// It seems that .focus() isn't triggering this event in our test
// environment so we need to ensure it gets set for this test to be valid.
var fakeNativeEvent = function() {};
fakeNativeEvent.target = node;
ReactTestUtils.simulateNativeEventOnNode('topFocus', node, fakeNativeEvent);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).toBe(null);
});
it('should extract if an `onSelect` listener is present', () => {
class WithSelect extends React.Component {
render() {
return <input type="text" onSelect={this.props.onSelect} />;
}
}
var cb = jest.fn();
var rendered = ReactTestUtils.renderIntoDocument(
<WithSelect onSelect={cb} />,
);
var node = ReactDOM.findDOMNode(rendered);
node.selectionStart = 0;
node.selectionEnd = 0;
node.focus();
var focus = extract(node, 'topFocus');
expect(focus).toBe(null);
var mousedown = extract(node, 'topMouseDown');
expect(mousedown).toBe(null);
var mouseup = extract(node, 'topMouseUp');
expect(mouseup).not.toBe(null);
expect(typeof mouseup).toBe('object');
expect(mouseup.type).toBe('select');
expect(mouseup.target).toBe(node);
});
});
|
function output(x) {
document.getElementById("output").innerHTML += x + "\n";
}
function main () {
try {
do_tests();
} catch (e) {
alert(JSON.stringify(e));
}
}
var hex_digit_value = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4,
"5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"a": 10, "A": 10,
"b": 11, "B": 11,
"c": 12, "C": 12,
"d": 13, "D": 13,
"e": 14, "E": 14,
"f": 15, "F": 15 };
function from_hex(s) {
if (s.length & 1) throw { message: "from_hex: odd-length input" };
var result = new Uint8Array(s.length / 2);
for (var i = 0; i < s.length; i += 2) {
var v1 = hex_digit_value[s[i]];
var v2 = hex_digit_value[s[i+1]];
if ((typeof v1 === "undefined")) throw { message: "Illegal hex digit: " + s[i] };
if ((typeof v2 === "undefined")) throw { message: "Illegal hex digit: " + s[i+1] };
result[i >> 1] = (v1 << 4) | v2;
}
return result;
}
function do_tests() {
output("Starting...");
output(scrypt.to_hex(from_hex("0123456789abcdef")));
output("");
function check(password, salt, n, r, p, expected_hex) {
var expected = from_hex(expected_hex);
var startTime = new Date().getTime();
var actual = scrypt.crypto_scrypt(scrypt.encode_utf8(password),
scrypt.encode_utf8(salt),
n, r, p, expected.length);
var stopTime = new Date().getTime();
output("Milliseconds for "+password+"/"+salt+"/"+n+"/"+r+"/"+p+": " +
(stopTime - startTime));
if (scrypt.to_hex(actual) !== expected_hex) {
output("FAILED");
output("expected: " + expected_hex);
output("actual: " + scrypt.to_hex(actual));
}
}
check("", "", 16, 1, 1, "77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906");
check("password", "NaCl", 1024, 8, 16, "fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640");
check("pleaseletmein", "SodiumChloride", 16384, 8, 1, "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887");
// Disabled: wayyyy too slow.
//
// check("pleaseletmein", "SodiumChloride", 1048576, 8, 1, "2101cb9b6a511aaeaddbbe09cf70f881ec568d574a2ffd4dabe5ee9820adaa478e56fd8f4ba5d09ffa1c6d927c40f4c337304049e8a952fbcbf45c6fa77a41a4");
output("");
output("...done.");
}
window.onload = main;
|
(function () {
'use strict';
angular
.module('certificates.admin')
.controller('CertificatesAdminListController', CertificatesAdminListController);
CertificatesAdminListController.$inject = ['CertificateService'];
function CertificatesAdminListController(CertificatesService) {
var vm = this;
vm.certificates = CertificatesService.query();
}
}());
|
/*******************************
* 名称:详情
* 作者:rubbish.boy@163.com
*******************************
*/
//获取应用实例
var app = getApp()
var config={
//页面的初始数据
data: {
title : '名片介绍',
userInfo : {},
session_id :'',
requestlock :true,
domainName : app.globalData.domainName,
dataid :"",
infodata :{}
},
//生命周期函数--监听页面加载
onLoad: function (options) {
var that = this
//调用应用实例的方法获取全局数据
app.getUserInfo(function(userInfo){
//更新数据
that.setData({
userInfo:userInfo
})
})
//异步获取缓存session_id
wx.getStorage({
key: 'session_id',
success: function(res) {
that.setData({
session_id:res.data
})
that.get_info(options.id);
}
})
that.setData({
dataid:options.id
})
},
//生命周期函数--监听页面初次渲染完成
onReady: function() {
// Do something when page ready.
},
//生命周期函数--监听页面显示
onShow: function() {
// Do something when page show.
if(this.data.requestlock==false)
{
this.get_info(this.data.dataid);
}
else
{
this.setData({
requestlock:false
})
}
},
//生命周期函数--监听页面隐藏
onHide: function() {
// Do something when page hide.
},
//生命周期函数--监听页面卸载
onUnload: function() {
// Do something when page close.
},
//页面相关事件处理函数--监听用户下拉动作
onPullDownRefresh: function() {
// Do something when pull down.
this.get_info(this.data.dataid,"onPullDownRefresh");
},
//页面上拉触底事件的处理函数
onReachBottom: function() {
// Do something when page reach bottom.
},
//导航处理函数
bindNavigateTo: function(action)
{
app.bindNavigateTo(action.target.dataset.action,action.target.dataset.params)
},
//页面打开导航处理函数
bindRedirectTo: function(action)
{
app.bindRedirectTo(action.target.dataset.action,action.target.dataset.params)
},
//跳转到 tabBar 页面
bindSwitchTo: function(action)
{
app.bindSwitchTo(action.target.dataset.action)
},
//获取详情数据
get_info: function(id,actionway="")
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,id:id}
app.action_loading();
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_businesscard_info,post_data,function(resback){
if(resback.status==1)
{
app.action_loading_hidden();
that.setData({
infodata:resback.resource
})
if(actionway=="onPullDownRefresh")
{
setTimeout(function(){
wx.stopPullDownRefresh()
},800)
}
}
else
{
app.action_loading_hidden();
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
},
//删除请求
del_action:function(action)
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,actiondata:action.target.dataset}
app.func.showModal("确定要执行删除?",function(resback){
if(resback.confirm)
{
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_del,post_data,function(resback){
if(resback.status==1)
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_success(msgdata);
}
else
{
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata);
//console.log('获取用户登录态失败!' + resback.info);
}
})
}
else
{
var msgdata=new Object
msgdata.url=""
msgdata.msg="取消"
app.func.showToast_default(msgdata);
}
})
},
//拨号请求
makePhoneCall:function(action)
{
app.func.makePhoneCall(action.target.dataset.phoneNumber)
},
}
Page(config)
|
v = JSONSchema({
k1: {
type: String
},
k2: {
type: Number
},
k3: {
type: Boolean
},
k4: [{
x: {
type: Number
},
y: {
type: String
}
}],
k5: {
type: Date
},
k6: {
x: {
type: Boolean
},
y: {
type: Date
},
z: {
m: {
type: String
},
n: {
type: Date
}
}
}
});
r = v.validate({
k1: '1',
k2: 10,
k3: true,
k4: [{
x: 10,
y: "sdf"
},
{
x: '20',
y: "sdgfds"
}
],
k5: new Date(),
k6: {
x: false,
y: new Date(),
z: {
n: "sdfgfdg",
m: new Date()
}
}
})
console.log(r);
|
import color from 'color';
import { Platform } from 'react-native';
/* This is an example of a theme */
export default {
// Badge
badgeBg: '#ED1727',
badgeColor: '#fff',
// Button
btnFontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto_medium',
btnDisabledBg: '#b5b5b5',
btnDisabledClr: '#f1f1f1',
get btnPrimaryBg() {
return this.brandPrimary;
},
get btnPrimaryColor() {
return this.inverseTextColor;
},
get btnInfoBg() {
return this.brandInfo;
},
get btnInfoColor() {
return this.inverseTextColor;
},
get btnSuccessBg() {
return this.brandSuccess;
},
get btnSuccessColor() {
return this.inverseTextColor;
},
get btnDangerBg() {
return this.brandDanger;
},
get btnDangerColor() {
return this.inverseTextColor;
},
get btnWarningBg() {
return this.brandWarning;
},
get btnWarningColor() {
return this.inverseTextColor;
},
get btnTextSize() {
return (Platform.OS === 'ios') ? this.fontSizeBase * 1.1 :
this.fontSizeBase - 1;
},
get btnTextSizeLarge() {
return this.fontSizeBase * 1.5;
},
get btnTextSizeSmall() {
return this.fontSizeBase * 0.8;
},
get borderRadiusLarge() {
return this.fontSizeBase * 3.8;
},
buttonPadding: 6,
get iconSizeLarge() {
return this.iconFontSize * 1.5;
},
get iconSizeSmall() {
return this.iconFontSize * 0.6;
},
// Card
cardDefaultBg: '#fff',
// Check Box
checkboxBgColor: '#039BE5',
checkboxSize: 23,
checkboxTickColor: '#fff',
// Color
brandPrimary: '#5067FF',
brandInfo: '#5bc0de',
brandSuccess: '#5cb85c',
brandDanger: '#d9534f',
brandWarning: '#f0ad4e',
brandSidebar: '#252932',
// Font
fontFamily: (Platform.OS === 'ios') ? 'HelveticaNeue' : 'Roboto',
fontSizeBase: 15,
get fontSizeH1() {
return this.fontSizeBase * 1.8;
},
get fontSizeH2() {
return this.fontSizeBase * 1.6;
},
get fontSizeH3() {
return this.fontSizeBase * 1.4;
},
// Footer
footerHeight: 55,
footerDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
// FooterTab
tabBarTextColor: (Platform.OS === 'ios') ? '#6b6b6b' : '#b3c7f9',
tabBarActiveTextColor: (Platform.OS === 'ios') ? '#007aff' : '#fff',
tabActiveBgColor: (Platform.OS === 'ios') ? '#cde1f9' : undefined,
// Header
iosToolbarBtnColor: '#007aff',
toolbarDefaultBg: (Platform.OS === 'ios') ? '#F8F8F8' : '#4179F7',
toolbarHeight: (Platform.OS === 'ios') ? 64 : 56,
toolbarIconSize: (Platform.OS === 'ios') ? 20 : 22,
toolbarInputColor: '#CECDD2',
toolbarInverseBg: '#222',
toolbarTextColor: (Platform.OS === 'ios') ? '#000' : '#fff',
get statusBarColor() {
return color(this.toolbarDefaultBg).darken(0.2).hexString();
},
// Icon
iconFamily: 'Ionicons',
iconFontSize: (Platform.OS === 'ios') ? 30 : 28,
iconMargin: 7,
// InputGroup
inputFontSize: 15,
inputBorderColor: '#D9D5DC',
inputSuccessBorderColor: '#2b8339',
inputErrorBorderColor: '#ed2f2f',
get inputColor() {
return this.textColor;
},
get inputColorPlaceholder() {
return '#575757';
},
inputGroupMarginBottom: 10,
inputHeightBase: 40,
inputPaddingLeft: 5,
get inputPaddingLeftIcon() {
return this.inputPaddingLeft * 8;
},
// Line Height
btnLineHeight: 19,
lineHeightH1: 32,
lineHeightH2: 27,
lineHeightH3: 22,
iconLineHeight: (Platform.OS === 'ios') ? 37 : 30,
lineHeight: (Platform.OS === 'ios') ? 20 : 24,
// List
listBorderColor: '#ddd',
listDividerBg: '#ddd',
listItemHeight: 45,
listItemPadding: 9,
listNoteColor: '#808080',
listNoteSize: 13,
// Progress Bar
defaultProgressColor: '#E4202D',
inverseProgressColor: '#1A191B',
// Radio Button
radioBtnSize: (Platform.OS === 'ios') ? 25 : 23,
radioColor: '#7e7e7e',
get radioSelectedColor() {
return color(this.radioColor).darken(0.2).hexString();
},
// Spinner
defaultSpinnerColor: '#45D56E',
inverseSpinnerColor: '#1A191B',
// Tabs
tabBgColor: '#F8F8F8',
tabFontSize: 15,
tabTextColor: '#fff',
// Text
textColor: '#000',
inverseTextColor: '#fff',
// Title
titleFontSize: (Platform.OS === 'ios') ? 17 : 19,
subTitleFontSize: (Platform.OS === 'ios') ? 12 : 14,
subtitleColor: '#8e8e93',
// Other
borderRadiusBase: (Platform.OS === 'ios') ? 5 : 2,
borderWidth: 1,
contentPadding: 10,
get darkenHeader() {
return color(this.tabBgColor).darken(0.03).hexString();
},
dropdownBg: '#000',
dropdownLinkColor: '#414142',
inputLineHeight: 24,
jumbotronBg: '#C9C9CE',
jumbotronPadding: 30,
};
|
var translattionTable = {
"search": "Buscar",
"emptyTable": "",
"decimal": "",
"info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
"infoEmpty": "",
"infoFiltered": "(filtradas de _MAX_ entradas)",
"infoPostFix": "",
"thousands": ",",
"lengthMenu": "Mostrar _MENU_",
"loadingRecords": "Cargando...",
"processing": "Procesando...",
"zeroRecords": "",
"paginate": {
"first": "Primera",
"last": "Última",
"next": ">",
"previous": "<"
}
};
|
'use strict';
const { expect } = require('chai');
const _ = require('lodash');
const sinon = require('sinon');
const run = require('../../../src/lib/run');
describe('Command runner library', () => {
describe('run method', () => {
const data = [
{
name: 'first',
words: ['foo', 'bar'],
},
{
name: 'second',
words: ['baz', 'quux'],
},
];
it('should handle a basic expression', () => {
expect(run.run(data, '["foo"]')).to.eql(['foo']);
});
it('should handle an object', () => {
expect(
run.run(data, '{"foo": "bar"}')
).to.eql({ foo: 'bar' });
});
describe('provided variables to the command', () => {
it('should include parsed data as "d"', () => {
expect(
run.run(data, '{"word": d[1].words[0]}')
).to.eql({ word: 'baz' });
});
it('should include the chain as "c"', () => {
expect(
run.run(data, 'c.get(0).value()')
).to.eql(data[0]);
});
it('should include lodash as "_"', () => {
expect(
run.run(data, 'c.get("0.words").map(_.capitalize).value()')
).to.eql(['Foo', 'Bar']);
});
describe('"p"', () => {
beforeEach(() => {
sinon.spy(console, 'json');
});
afterEach(() => {
console.json.restore();
});
it('should include console.json as "p"', () => {
// console.json does not document its return value,
// so don't test for it
run.run(data, 'p(d)');
sinon.assert.calledOnce(console.json);
sinon.assert.calledWithExactly(console.json, data);
});
it('should return the first item passed to it', () => {
expect(
run.run(data, 'p(d,d)')
).to.eql(data);
});
});
it('should not include other variables leaked into scope', () => {
expect(
_.bind(run.run, run, data, 'command')
).to.throw();
});
});
});
});
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
function isOnlyChange(event) {
return event.type === 'changed';
}
module.exports = function(options) {
var watch = function(srcDir, watchOptions) {
return function() {
if (!watchOptions) {
watchOptions = {};
}
watchOptions.watchSrcLess = watchOptions.watchSrcLess || true;
watchOptions.watchSrcHtml = watchOptions.watchSrcHtml || true;
watchOptions.srcJs = watchOptions.srcJs || '/**/*.js';
gulp.watch([options.app + '/*.html', 'bower.json'], ['inject']);
if (watchOptions.watchSrcLess) {
gulp.watch([
srcDir + '/**/*.less'
], function(event) {
if(isOnlyChange(event)) {
gulp.start('styles');
} else {
gulp.start('inject');
}
});
}
gulp.watch([srcDir + watchOptions.srcJs, options.app + '/**/*.js'], function(event) {
if(isOnlyChange(event)) {
gulp.start('scripts');
} else {
gulp.start('inject');
}
});
var htmlToWatch = [options.app + '/*.html'];
if (watchOptions.watchSrcHtml) {
htmlToWatch.push(srcDir + '/**/*.html');
}
return gulp.watch(htmlToWatch, function(event) {
browserSync.reload(event.path);
});
};
};
gulp.task('watch', ['inject'], watch(options.src));
gulp.task('watch:dist', ['inject:dist'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.js'}));
gulp.task('watch:dist:min', ['inject:dist:min'], watch(options.dist, {watchSrcLess: false, watchSrcHtml: false, srcJs: 'angular-notification-icons.min.js'}));
};
|
app.controller('gregorianToJalaliCrtl', function($scope,dateConvertor) {
/**
* validate date
* @returns {undefined}
*/
$scope.allValidation = function () {
$scope.validateGregorianYear();
$scope.validateGregorianMonth();
$scope.validateGregorianDay();
}
/**
* convert date
* @returns {undefined}
*/
$scope.convert = function () {
$scope.allValidation();
if(!$scope.greToShFrm.$invalid) {
// convert to jalali date
var date=dateConvertor.gregorianToJalali($scope.fromGreToShYear,$scope.fromGreToShMonth,$scope.fromGreToShDay);
// showing converted date
$scope.setConvertedDate(date[2]+' '+dateConvertor.getMonthName(date[1],'jalali')+' '+date[0]);
}
}
/**
* validate gregorian year
* @returns {undefined}
*/
$scope.validateGregorianYear = function() {
var result=true;
var yearValue=$scope.fromGreToShYear;
var itemInvalid=false;
var formInvalid=false;
if(!yearValue) {
$scope.fromGreToShYearMessage='سال را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(yearValue <= 0) {
$scope.fromGreToShYearMessage='سال را صحیح وارد نمائید';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShYear.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
};
/**
* validate gregorian moth
* @returns {undefined}
*/
$scope.validateGregorianMonth = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var monthValue=$scope.fromGreToShMonth;
if(!monthValue) {
$scope.fromGreToShMonthMessage='ماه را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result && (monthValue < 1 || monthValue > 12)) {
$scope.fromGreToShMonthMessage='ماه باید عددی بین 1 تا 12 باشد';
itemInvalid=true;
formInvalid=true;
}
$scope.greToShFrm.fromGreToShMonth.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
* validate gregorian day
* @returns {undefined}
*/
$scope.validateGregorianDay = function () {
if(!$scope.greToShFrm.fromGreToShYear.$invalid && !$scope.greToShFrm.fromGreToShMonth.$invalid) {
var result=true;
var itemInvalid=false;
var formInvalid=false;
var yearValue=$scope.fromGreToShYear;
var monthValue=$scope.fromGreToShMonth;
var dayValue=$scope.fromGreToShDay;
if(!dayValue) {
$scope.fromGreToShDayMessage='روز را وارد نمائید';
itemInvalid=true;
formInvalid=true;
result=false;
}
if(result) {
// var dayResult=true;
if(dayValue < 1 || dayValue > 31) {
$scope.fromGreToShDayMessage='روز باید عددی بین 1 تا 31 باشد';
itemInvalid=true;
formInvalid=true;
// dayResult=false;
}
}
$scope.greToShFrm.fromGreToShDay.$invalid=itemInvalid;
$scope.greToShFrm.$invalid=formInvalid;
}
};
/**
*
* set value of converted date
* @param {string} value
* @returns {undefined}
*/
$scope.setConvertedDate = function(value) {
$scope.convertedDate=value;
};
/**
* empty converted date
* @returns {undefined}
*/
$scope.emptyConvertedDate = function() {
$scope.convertedDate='';
};
});
|
import ProjectLibraryModel from './project-library.model';
let libraries = {
angular: new ProjectLibraryModel(1, 'Angular', require('../../../../images/logos/angular.svg')),
angularJS: new ProjectLibraryModel(2, 'AngularJS', require('../../../../images/logos/angularjs.png')),
jQuery: new ProjectLibraryModel(3, 'jQuery', require('../../../../images/logos/jquery.png')),
cordova: new ProjectLibraryModel(4, 'Cordova/PhoneGap', require('../../../../images/logos/cordova.png')),
materialDesignNG1: new ProjectLibraryModel(5, 'Material Design (AngularJS 1.x.x)', null),
firebase: new ProjectLibraryModel(6, 'Firebase PaaS', null),
dotNET: new ProjectLibraryModel(7, '.NET', null)
};
export default libraries;
|
/// <reference path="../jquery-1.7.1-vsdoc.js" />
var Audio = {
//-- Functions
Initialize: function () {
Audio.player = $('audio').get(0);
$('#Audio_PlayButton').on('click', Audio.Handlers.Button.Play);
$('audio').on('ended', Audio.Handlers.Events.Ended);
$('audio').on('pause', Audio.Handlers.Events.Pause);
$('audio').on('play', Audio.Handlers.Events.Play);
$('audio').on('timeupdate', Audio.Handlers.Events.TimeUpdate);
},
Notify: function (title, text, sticky, time) {
$.gritter.add({
title: title,
text: text,
sticky: sticky,
time: time
});
},
Refresh: function () {
},
Source: function (dataURI) {
Audio.player.src = dataURI;
Audio.player.load();
return (Audio.player.src = dataURI);
},
Play: function () {
Audio.Handlers.Button.Play();
},
//-- Event Handlers
Handlers: {
Button: {
Play: function () {
if (Audio.player.paused) {
Audio.player.play();
}
else {
Audio.player.pause();
}
}
},
Events: {
Ended: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
Play: function (e) {
$('#Audio_PlayButton > i').removeClass('icon-play').addClass('icon-pause');
},
Pause: function (e) {
$('#Audio_PlayButton > i').addClass('icon-play').removeClass('icon-pause');
},
TimeUpdate: function (e) {
$('#Audio_Progress').css('width', e.target.currentTime / e.target.duration * 100 + '%');
}
}
},
//-- Settings & Persistence
Settings: {
},
//-- Internal Vars
player: null
};
|
import express from 'express';
import helpers from '../helpers';
import controller from '../controllers/voteController';
const router = express.Router();
router.get('/', helpers.isAuth, controller.initialize, controller.canVoteUT100, (req, res) => {
res.locals.moduleTitle = 'Votar';
res.locals.module = () => 'vote';
res.locals.active = {
vote: true
};
res.render('index');
});
router.get('/ultratop100', controller.initialize, controller.verifyRewardUT100, controller.handleRewardUT100);
export default router;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.