text
stringlengths 2
6.14k
|
|---|
// # Ghost Data API
// Provides access to the data model
var _ = require('underscore'),
when = require('when'),
config = require('../config'),
errors = require('../errorHandling'),
db = require('./db'),
settings = require('./settings'),
notifications = require('./notifications'),
posts = require('./posts'),
users = require('./users'),
tags = require('./tags'),
requestHandler,
init;
// ## Request Handlers
function cacheInvalidationHeader(req, result) {
var parsedUrl = req._parsedUrl.pathname.replace(/\/$/, '').split('/'),
method = req.method,
endpoint = parsedUrl[4],
id = parsedUrl[5],
cacheInvalidate,
jsonResult = result.toJSON ? result.toJSON() : result;
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
if (endpoint === 'settings' || endpoint === 'users' || endpoint === 'db') {
cacheInvalidate = "/*";
} else if (endpoint === 'posts') {
cacheInvalidate = "/, /page/*, /rss/, /rss/*";
if (id && jsonResult.slug) {
return config.paths.urlForPost(settings, jsonResult).then(function (postUrl) {
return cacheInvalidate + ', ' + postUrl;
});
}
}
}
return when(cacheInvalidate);
}
// ### requestHandler
// decorator for api functions which are called via an HTTP request
// takes the API method and wraps it so that it gets data from the request and returns a sensible JSON response
requestHandler = function (apiMethod) {
return function (req, res) {
var options = _.extend(req.body, req.files, req.query, req.params),
apiContext = {
user: req.session && req.session.user
};
return apiMethod.call(apiContext, options).then(function (result) {
res.json(result || {});
return cacheInvalidationHeader(req, result).then(function (header) {
if (header) {
res.set({
"X-Cache-Invalidate": header
});
}
});
}, function (error) {
var errorCode = error.errorCode || 500,
errorMsg = {error: _.isString(error) ? error : (_.isObject(error) ? error.message : 'Unknown API Error')};
res.json(errorCode, errorMsg);
});
};
};
init = function () {
return settings.updateSettingsCache();
};
// Public API
module.exports = {
posts: posts,
users: users,
tags: tags,
notifications: notifications,
settings: settings,
db: db,
requestHandler: requestHandler,
init: init
};
|
var path = require('path');
var webpack = require('webpack');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
devFlagPlugin
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
|
var path = require('path');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var logger = require('morgan');
var app = require('./app');
// var models = require('./models');
// logging
app.use(logger('combined'));
// serve index.html
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'prod_index.html'));
});
// listen on selected port
app.listen(3000, function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
|
/*
* StoryQuest 2
*
* Copyright (c) 2014 Questor GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var fs = require("fs");
var path = require("path");
var nodetypes = require("../logic/nodetypes");
exports.registerServices = function(config, app) {
app.get("/api/nodetree/:projectId", authUser, authProject, this.renderNodeTree);
};
exports.renderNodeTree = function(req, res){
var projectId = req.param("projectId");
var configDir = path.join(Utils.getProjectDir(projectId), "stationconfig");
var tree = {
"nodes": [],
"edges": []
};
fs.readdir(configDir, function (err, list) {
var nodeIdList = [];
// pass 1: parse nodes
list.forEach(function (file) {
if (file.indexOf(".json")!=-1 && file.indexOf("~")==-1) {
var node = JSON.parse(fs.readFileSync(path.join(configDir, file)));
// parse node
var thisNode = {
id: node.id,
title: node.title,
x: node.x || Math.random(),
y: node.y || Math.random(),
size: 1,
linkVertices: node.linkVertices,
color: node.editorColor || "#3c8dbc",
type: node.type,
image: {
url: "/images/icons/" + node.type + ".png",
scale: 0.8,
clip: 0.85
}
};
tree.nodes.push(thisNode);
nodeIdList.push(thisNode.id);
}
});
// pass 2: parse edges, has to be done after indexing all node id's above
list.forEach(function (file) {
if (file.indexOf(".json")!=-1) {
var node = JSON.parse(fs.readFileSync(path.join(configDir, file)));
// parse edges
var edges = nodetypes.parseNodeConnections(configDir, node);
if (edges) {
for (var i=0; i < edges.length; i++) {
var thisEdge = edges[i];
// only add the edge if the target node actually exists
if (nodeIdList.indexOf(thisEdge.target)!=-1) {
thisEdge.size = 1;
thisEdge.color = "#ccc";
thisEdge.type = "curvedArrow";
tree.edges.push(thisEdge);
}
}
}
}
});
res.json(tree);
});
};
|
const mod = angular.module('pa.utils.delay', []);
mod.factory('paDelayS', ['$timeout', '$q', ($timeout, $q) => {
return (millis) => {
let deferred = $q.defer();
$timeout(deferred.resolve.bind(deferred, millis), millis);
return deferred.promise;
};
}]);
export default mod;
|
var _ = require('../../extras/util');
module.exports = function(criteria, prev){
return not(criteria, prev);
};
function not(criteria, prev){
var _final = [];
if(_.isArray(criteria))return prev;
if(_.isString(criteria) || _.isObject(criteria))_final.push(criteria);
if(prev) { for(i in _final) prev.push(_final[i]); _final = prev; }
return _final;
};
|
"use strict";
import { arrayUtilities } from "necessary";
import NonSignificantToken from "../../token/nonSignificant";
import { NEW_LINE } from "../../../constants";
import { endOfLineType } from "../../types";
import { sanitiseContent } from "../../../utilities/content";
const { first } = arrayUtilities;
export default class EndOfLineNonSignificantToken extends NonSignificantToken {
constructor(type, content, innerHTML, significant, index) {
super(type, content, innerHTML, significant);
this.index = index;
}
getIndex() {
return this.index;
}
asHTML() {
const html = NEW_LINE;
return html;
}
clone(startPosition, endPosition) { return super.clone(EndOfLineNonSignificantToken, startPosition, endPosition, this.index); }
static match(content) {
let endOfLineNonSignificantToken = null;
const regularExpression = /\r\n|\r|\n/,
matches = content.match(regularExpression);
if (matches !== null) {
const firstMatch = first(matches);
content = firstMatch; ///
const contentLength = content.length;
if (contentLength > 0) {
const type = endOfLineType, ///
sanitisedContent = sanitiseContent(content),
innerHTML = sanitisedContent, ///
significant = false,
{ index } = matches;
endOfLineNonSignificantToken = new EndOfLineNonSignificantToken(type, content, innerHTML, significant, index);
}
}
return endOfLineNonSignificantToken;
}
}
|
import errorResponse from '../libs/errorResponse';
import '../../../src/modules/box';
import '../../../src/modules/facebook';
import '../../../src/modules/flickr';
import '../../../src/modules/google';
import '../../../src/modules/windows';
import '../../../src/modules/dropbox';
import '../../../src/modules/twitter';
import '../../../src/modules/yahoo';
import '../../../src/modules/instagram';
import '../../../src/modules/joinme';
import '../../../src/modules/linkedin';
import '../../../src/modules/foursquare';
import '../../../src/modules/github';
import '../../../src/modules/bikeindex';
import '../../../src/modules/soundcloud';
import '../../../src/modules/vk';
describe('E2E modules', function() {
// Loop through all services
for (var name in hello.services) {
setupModuleTests(hello.services[name], name);
}
function setupModuleTests(module, name) {
describe(name, function() {
var MATCH_URL = /^https?\:\/\//;
it('should contain oauth.auth path', function() {
var path = module.oauth.auth;
expect(path).to.match(/^https?\:\/\//);
});
it('should specify a base url', function() {
// Loop through all services
expect(module.base).to.match(/^https?\:\/\//);
});
it('should be using OAuth1 contain, auth, request, token properties', function() {
// Loop through all services
var oauth = module.oauth;
if (oauth && parseInt(oauth.version, 10) === 1) {
expect(oauth.auth).to.match(MATCH_URL);
expect(oauth.token).to.match(MATCH_URL);
expect(oauth.request).to.match(MATCH_URL);
}
});
xit('should return error object when an api request is made with an unverified user', function(done) {
var i = 0;
this.timeout(60000);
var cb = errorResponse(null, function() {
if (++i === 2)
done();
});
// Ensure user is signed out
hello.logout(name);
// Make a request that returns an error object
hello(name)
.api('me', cb)
.then(null, cb);
});
});
}
});
|
/**
* Created by Igor Zalutsky on 12.08.12 at 17:40
*/
(function () {
"use strict";
// publishing namespace
if (!window.elist) {
window.elist = {};
}
var elist = window.elist;
/**
* View of single Expense
* @param expenseModel
* @constructor
*/
elist.ExpenseView = function(expenseModel){
//TODO Param validation in ExpenseView
var view = this;
var model = expenseModel;
this.listeners = {};
this.isVisible = false;
this.model = expenseModel;
this.parentNode = null;
this.activeAmount = new elist.ObservableProperty(0);
this.model.amount.notify(function(){
view.updateActiveAmount();
});
this.model.isActive.notify(function(){
view.updateActiveAmount();
});
this.activeShare = new elist.ObservableProperty(0);
this.node = document.createElement("tr");
for (var i = 0; i < 6; i+=1){
this.node.appendChild(document.createElement("td"));
}
// creating controls
this.descriptionControl = new elist.EditableView(model.description, "TextView", "InputEdit", "text");
this.dateControl = new elist.EditableView(model.date, "DateView", "InputEdit", "date");
this.amountControl = new elist.EditableView(model.amount, "AmountView", "InputEdit", "number");
this.activeControl = new elist.FlagView(model.isActive);
this.shareControl = new elist.ShareView(this.activeShare);
// rendering controls
this.descriptionControl.renderTo(this.node.children[0]);
this.dateControl.renderTo(this.node.children[1]);
this.amountControl.renderTo(this.node.children[2]);
this.activeControl.renderTo(this.node.children[4]);
this.shareControl.renderTo(this.node.children[3]);
// working with DOM
this.deleteButton = document.createElement("button");
this.deleteButton.type = "button";
this.deleteButton.innerHTML = "Удалить";
this.deleteButton.addEventListener("click", function(){
view.emit("deleteRequest");
}, false);
this.node.children[5].appendChild(this.deleteButton);
this.updateActiveAmount();
};
// Extending BaseView
elist.ExpenseView.inheritFrom(elist.BaseView);
/**
* Recalculates active amount and assigns it to observable property
*/
elist.ExpenseView.prototype.updateActiveAmount = function(){
var isActive = this.model.isActive.get();
var amount = this.model.amount.get();
this.activeAmount.set(isActive ? amount : 0);
};
/**
* Toggles edit mode for all editable properties
*/
elist.ExpenseView.prototype.editAll = function(){
this.descriptionControl.edit();
this.dateControl.edit();
this.amountControl.edit();
};
}());
|
const CACHE_PREFIX = 'GE_'
export const getCache = key => {
let result = null
let cache = localStorage.getItem(`${CACHE_PREFIX}${key}`);
try{
result = JSON.parse(cache);
console.log(`get from cache ${key}, created ${result.created} `, result);
// we will cache per one day
if (result) {
let dateNow = new Date().getDate();
let createdDate = new Date(result.created).getDate();
if (dateNow !== createdDate) {
// return null for refresh cache
result = null
} else {
// just return the datas
result = result.data
}
}
}catch(err){
// do nothing
}
return result;
};
export const saveCache = (key, data) => {
let obj = {
created: new Date().getTime(),
data: data
}
let dataString = JSON.stringify(obj)
localStorage.setItem(`${CACHE_PREFIX}${key}`, dataString);
};
|
'use strict';
import React from 'react';
import { capitalize } from '../helpers';
let DOM = React.DOM;
const ScoreItem = function({ color, isHighlighted, score }) {
let className = color;
if (isHighlighted) {
className += ' highlighted';
}
return DOM.div({ className }, capitalize(color) + ': ' + score);
};
ScoreItem.propTypes = {
color: React.PropTypes.string.isRequired,
isHighlighted: React.PropTypes.bool,
score: React.PropTypes.number
};
ScoreItem.defaultProps = {
isHighlighted: false,
score: 0
};
export default ScoreItem;
|
describe('Request', function () {
var subject, navigator;
beforeEach(function () {
navigator = Aviator._navigator;
});
describe('namedParams', function () {
describe('with named params', function () {
var route = '/snap/:uuid/dawg/:section/bro';
beforeEach(function () {
subject = navigator.createRequest(
'/snap/foo/dawg/bar%20noo%20gan/bro',
null,
route
);
});
it('extracts the named params', function () {
expect( subject.namedParams ).toEqual({
uuid: 'foo',
section: 'bar noo gan'
});
});
});
});
describe('queryParams', function () {
var route, queryString;
beforeEach(function () {
route = '/snap';
});
describe('with a regular query string', function () {
queryString = '?bro=foo&dawg=bar&baz=boo';
beforeEach(function () {
subject = navigator.createRequest('/snap', queryString, route);
});
it('extracts the query string params', function () {
expect( subject.queryParams ).toEqual({
bro: 'foo',
dawg: 'bar',
baz: 'boo'
});
});
});
describe('using the rails convention for arrays in a query', function () {
beforeEach(function () {
queryString = '?bros[]=simon&bros[]=barnaby&chickens[]=earl&dinosaurs=fun';
subject = navigator.createRequest('/snap', queryString, route);
});
it('stores values for the same key in an array', function () {
expect( subject.queryParams['bros'] ).toEqual( [ 'simon', 'barnaby' ] );
});
it('does not assume that single values are meant to be in arrays', function () {
expect( subject.queryParams['dinosaurs'] ).toEqual( 'fun' );
});
it('puts values explicitly specified to be in arrays in arrays', function () {
expect( subject.queryParams['chickens'] ).toEqual( [ 'earl' ] )
});
});
describe('with an invalid query string key', function () {
beforeEach(function () {
queryString = '?bros=keith&bros-george';
subject = navigator.createRequest('/snap', queryString, route);
});
it('includes the valid params', function () {
expect( subject.queryParams['bros'] ).toBe( 'keith' );
});
it('does not include invalid params', function () {
expect( Object.keys(subject.queryParams).length ).toBe( 1 );
});
});
});
describe('params', function () {
beforeEach(function () {
subject = navigator.createRequest('/bro/bar', '?baz=boo', '/bro/:foo');
});
it('is a merge of namedParams and queryParams', function () {
expect( subject.params ).toEqual({
foo: 'bar',
baz: 'boo'
});
});
});
});
|
var searchData=
[
['mxml_5fattr_5fs',['mxml_attr_s',['../structmxml__attr__s.html',1,'']]],
['mxml_5fcustom_5fs',['mxml_custom_s',['../structmxml__custom__s.html',1,'']]],
['mxml_5felement_5fs',['mxml_element_s',['../structmxml__element__s.html',1,'']]],
['mxml_5findex_5fs',['mxml_index_s',['../structmxml__index__s.html',1,'']]],
['mxml_5fnode_5fs',['mxml_node_s',['../structmxml__node__s.html',1,'']]],
['mxml_5ftext_5fs',['mxml_text_s',['../structmxml__text__s.html',1,'']]],
['mxml_5fvalue_5fu',['mxml_value_u',['../unionmxml__value__u.html',1,'']]]
];
|
// Keep this file in sync with lib/dc/language.rb
dc.language = {
NAMES: {
'eng': 'English',
'spa': 'Español/Spanish',
'fra': 'Français/French',
'deu': 'Duetch/German',
'dan': 'Danish',
'rus': 'Russian',
'ukr': 'Ukrainian'
},
USER: ['eng','spa','rus','ukr']
};
dc.language.SUPPORTED = _.keys(dc.language.NAMES);
|
/** @jsx h */
import React from 'react'
import h from '../../helpers/h'
function Bold(props) {
return React.createElement('strong', null, props.children)
}
function renderMark(props) {
switch (props.mark.type) {
case 'bold':
return Bold(props)
}
}
export const props = {
renderMark,
}
export const value = (
<value>
<document>
<paragraph>
one<b>two</b>three
</paragraph>
</document>
</value>
)
export const output = `
<div data-slate-editor="true" contenteditable="true" role="textbox">
<div style="position:relative">
<span>
<span>one</span>
<span><strong>two</strong></span>
<span>three</span>
</span>
</div>
</div>
`.trim()
|
(function($, window){
$(window).on('new_notification', attachListeners);
$(attachListeners)
function attachListeners() {
$('.flash').on('click', '.flash_close', removeFlash)
}
function removeFlash() {
$flash = $(this).closest('.flash');
$flash.addClass('flash_hidden');
setTimeout(function(){
$flash.remove();
if ($('.flash').length == 0) $('#flash_container').remove()
}, 200);
}
$(function(){
$('.flash.flash_hidden').each(function(i){
var _this = this;
setTimeout(function(){$(_this).removeClass('flash_hidden')}, (i + 6)*250);
});
});
})(jQuery, window)
|
'use strict';
/* @flow */
var console = require('console');
var PeersCollection = require('./peers-collection.js');
/*::
import * as type from './relay-handler.h.js';
declare var RelayHandler : Class<type.RelayHandler>
declare var RelayInfo : Class<type.RelayInfo>
*/
module.exports = RelayHandler;
function RelayHandler(channel, destinations) {
if (!(this instanceof RelayHandler)) {
return new RelayHandler(channel, destinations);
}
this.channel = channel;
this.peers = new PeersCollection(channel);
this.responseCount = 0;
for (var i = 0; i < destinations.length; i++) {
this.peers.createConnection(destinations[i]);
}
}
RelayHandler.prototype.handleFrame =
function handleFrame(frame) {
var self/*:RelayHandler*/ = this;
var frameType = frame.readFrameType();
switch (frameType) {
case 0x01:
return self.handleInitRequest(frame);
case 0x02:
return self.handleInitResponse(frame);
case 0x03:
return self.handleCallRequest(frame);
case 0x04:
return self.handleCallResponse(frame);
default:
return self.handleUnknownFrame(frame);
}
};
RelayHandler.prototype.handleInitRequest =
function handleInitRequest(frame) {
var conn = frame.sourceConnection;
conn.handleInitRequest(frame);
// LazyFrame.free(frame);
};
RelayHandler.prototype.handleInitResponse =
function handleInitResponse(frame) {
var conn = frame.sourceConnection;
conn.handleInitResponse(frame);
// LazyFrame.free(frame);
};
RelayHandler.prototype.handleCallRequest =
function handleCallRequest(frame) {
var self/*:RelayHandler*/ = this;
var inId = frame.readId();
var destConn = self.peers.roundRobinConn();
var outId = destConn.allocateId();
frame.writeId(outId);
var info = new RelayInfo(inId, frame.sourceConnection);
destConn.addPendingOutReq(outId, info, 1000);
var buf = frame.frameBuffer.slice(frame.offset, frame.length);
destConn.writeFrame(buf);
};
RelayHandler.prototype.handleCallResponse =
function handleCallResponse(frame) {
var self/*:RelayHandler*/ = this;
// VERY IMPORTANT LOL
frame.markAsCallResponse();
self.responseCount++;
var frameId = frame.readId();
var op = frame.sourceConnection.popPendingOutReq(frameId);
if (!op) {
console.error('Got unknown call response');
return;
}
frame.writeId(op.data.inId);
var buf = frame.frameBuffer.slice(frame.offset, frame.length);
op.data.connection.writeFrame(buf);
};
function RelayInfo(inId, connection) {
this.inId = inId;
this.connection = connection;
}
RelayHandler.prototype.handleUnknownFrame =
function handleUnknownFrame(frame) {
/* eslint no-console: 0*/
console.error('unknown frame', frame);
console.error('buf as string', frame.frameBuffer.toString());
};
|
pmb_im.services.factory('UserService', ['$http', function($http) {
//var baseURL = "http://pmbuy.development.datauy.org/auth/ajax/";
var UserObj = {};
UserObj.name = null;
UserObj.email = null;
UserObj.password = null;
UserObj.identity_document = null;
UserObj.phone = '';
UserObj.picture_url = "url(./img/icon-user-anonymous.png)";
UserObj.save_user_data = function (user_name, user_email, user_password, user_id_doc, user_phone, user_picture_url) {
UserObj.name = user_name;
UserObj.email = user_email;
UserObj.password = user_password;
UserObj.identity_document = user_id_doc;
UserObj.phone = user_phone;
UserObj.picture_url = user_picture_url;
//SAVE IN POUCHDB
}
UserObj.erase_user_data = function () {
UserObj.name = null;
UserObj.email = null;
UserObj.password = null;
UserObj.identity_document = null;
UserObj.phone = null;
UserObj.picture_url = null;
//DELETE IN POUCHDB
}
UserObj.get_user_data = function () {
//LEVANTA DE POUCHDB LOS DATOS DEL USUARIO. SI HAY LOS PONE EN LAS VARIABLES DEL SERVICIO. SI NO HAY PONE TODO NULL
}
UserObj.add_photo = function (user_picture_url) {
UserObj.picture_url = user_picture_url;
}
UserObj.isLogged = function () {
if(UserObj.name!=null && UserObj.name!=""){
return true;
}else{
return false;
}
}
return UserObj;
}]);
|
using("IGE");
using("IGE.Modification");
define("IGE.Modification.IGEObjectModifier", "abstract").extend("IGEAreaModifier").assign({
solidDirsTop: null,
solidDirsLeft: null,
solidDirsRight: null,
solidDirsBottom: null,
activate: abstractFunction(IGEObject),
deactivate: abstractFunction(IGEObject)
});
unusing("IGE");
unusing("IGE.Modification");
|
#!/usr/bin/env node
/*!
* Script to run vnu-jar if Java is available.
* Copyright 2017-2021 The Bootstrap Authors
* Copyright 2017-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
'use strict'
const childProcess = require('child_process')
const vnu = require('vnu-jar')
childProcess.exec('java -version', (error, stdout, stderr) => {
if (error) {
console.error('Skipping vnu-jar test; Java is missing.')
return
}
const is32bitJava = !/64-Bit/.test(stderr)
// vnu-jar accepts multiple ignores joined with a `|`.
// Also note that the ignores are regular expressions.
const ignores = [
// "autocomplete" is included in <button> and checkboxes and radio <input>s due to
// Firefox's non-standard autocomplete behavior - see https://bugzilla.mozilla.org/show_bug.cgi?id=654072
'Attribute “autocomplete” is only allowed when the input type is.*',
'Attribute “autocomplete” not allowed on element “button” at this point.',
// Markup used in Components → Forms → Layout → Form grid → Horizontal form is currently invalid,
// but used this way due to lack of support for flexbox layout on <fieldset> element in most browsers
'Element “legend” not allowed as child of element “div” in this context.*',
// Content → Reboot uses various date/time inputs as a visual example.
// Documentation does not rely on them being usable.
'The “date” input type is not supported in all browsers.*',
'The “week” input type is not supported in all browsers.*',
'The “month” input type is not supported in all browsers.*',
'The “color” input type is not supported in all browsers.*',
'The “datetime-local” input type is not supported in all browsers.*',
'The “time” input type is not supported in all browsers.*'
].join('|')
const args = [
'-jar',
`"${vnu}"`,
'--asciiquotes',
'--skip-non-html',
// Ignore the language code warnings
'--no-langdetect',
'--Werror',
`--filterpattern "${ignores}"`,
'_site/',
'js/tests/'
]
// For the 32-bit Java we need to pass `-Xss512k`
if (is32bitJava) {
args.splice(0, 0, '-Xss512k')
}
return childProcess.spawn('java', args, {
shell: true,
stdio: 'inherit'
})
.on('exit', process.exit)
})
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
goog.module('test_files.arrow_fn.untyped.arrow_fn.untyped');
var module = module || { id: 'test_files/arrow_fn.untyped/arrow_fn.untyped.ts' };
module = module;
exports = {};
/** @type {?} */
var fn3 = (/**
* @param {?} a
* @return {?}
*/
(a) => 12);
|
import { Document } from 'camo';
import { User } from './User';
export class Character extends Document {
constructor () {
super();
this.name = String;
this.owner = User;
}
async preValidate () {
if (typeof this.owner === 'string'){
this.owner = await User
.findOne({ _id: this.owner })
.then((res) => {
if (!res) throw new Error(`User for Character not found with provided id: ${this.owner}`);
return res;
});
} else if (typeof this.owner != User) {
throw new Error('Character must have owner of type User or User ID')
}
await Character
.find({ name: this.name, owner: this.owner._id })
.then((res) => {
if (res.length) throw new Error('A Character with the same name is already owned by the User');
});
this.owner.characters.push(this);
await this.owner.save();
}
}
export default Character;
|
import React from 'react';
import Router from 'react-router';
import { Provider } from 'react-redux';
import configureStore from '../store/index.js';
import routes from '../views/routes.js';
import prefetch from '../utils/prefetch.js';
import { superagentClient } from '../api/client.js';
function renderPage(html, initialState) {
return `
<!doctype html>
<html>
<head>
<title>Shellscripts</title>
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="/assets/bundle.css">
</head>
<body>
<div id='wrapper'>${html}</div>
<script>
window.__INITIAL_STATE__ = ${JSON.stringify(initialState)};
</script>
<script src="/assets/bundle.js"></script>
</body>
</html>
`;
}
export default function serverRenderer(req, res) {
const store = configureStore(undefined, superagentClient(req));
Router.run(routes, req.originalUrl, (Handler, routerState) => {
prefetch(store, routerState)
.then(() => {
let appHtml = React.renderToString(
<div id='root'>
<Provider store={store}>
{() => <Handler routerState={routerState} />}
</Provider>
</div>
);
let page = renderPage(appHtml, store.getState());
res.send(page);
});
});
}
|
'use strict';
// Dependencies
//
const assert = require('assert');
const server = require('../../lib/server');
describe('server', () => {
it('should return a http server', (done) => {
assert(typeof server.listen === 'function');
done();
});
it('should have router functions available', (done) => {
const check = i => assert(typeof server[i] === 'function');
['get', 'post', 'put', 'delete', 'patch', 'head'].map(check);
done();
});
});
|
var source = "<p>Hello, my name is {{name}}. I am from {{underscored hometown}}. I have " +
"{{kids.length}} kids:</p>" +
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);
var data = { "name": "Alan", "hometown": "Somewhere, TX",
"kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);
document.getElementsByTagName('div')[0].innerHTML = result;
|
(function () {
'use strict';
angular
.module('P1.sessionStorageFactory', [])
.factory('sessionStorageFactory', sessionStorageFactory);
sessionStorageFactory.$inject = ['$window'];
function sessionStorageFactory ($window) {
var sessionStorageFactory = {
set: set,
get: get,
setObj: setObj,
getObj: getObj,
remove: remove
};
return sessionStorageFactory;
function set (key, value) {
$window.sessionStorage[key] = value;
}
function get (key, defaultValue) {
return $window.sessionStorage[key] || defaultValue;
}
function setObj (key, value) {
$window.sessionStorage[key] = JSON.stringify(value);
}
function getObj (key) {
return $window.sessionStorage[key] ? JSON.parse($window.sessionStorage[key]) : null;
}
function remove (key) {
$window.sessionStorage.removeItem(key);
console.log('Session "' + key + '" has been removed.');
}
}
})();
|
var Tabview = function Tabview(options) {
'use strict';
return App.Common.View.call(this, options);
};
Tabview.prototype = Object.create(App.Common.View.prototype);
Tabview.prototype.constructor = Tabview;
Tabview.prototype.controller = function(opts) {
if (!this.get('initialized')) {
// Set item status as initialized
this.set('initialized', true);
// Patch component object
this.component(opts);
// Link stylesheet
this.stylesheet(['components/tabview.css']);
// Create and modifiy element
this.set('index', 0);
}
};
Tabview.prototype.view = function() {
return m('div', {
config: this.instance().autoconfig.bind(this.instance()),
class: [
'dribbble-component',
'component-tabview',
'tabview-element'
].join(' '),
style: {
width: ((this.get('items').length * 110) + 'px')
}
}, [
((typeof this.get('items') === 'object' && this.get('items') instanceof Array && this.get('items').length > 0) ? m('ul', {
class: [
'dribbble-component',
'component-tabview',
'tabview-container'
].join(' ')
}, [
this.get('items').map(function(item, index) {
return m('li', {
class: [
'dribbble-component',
'component-tabview',
'tabview-item',
index === this.get('index') ? 'item-selected' : ''
].join(' ')
}, [
m('button', {
class: [
'dribbble-component',
'component-tabview',
'tabview-button',
'mdl-button',
'mdl-js-button',
'mdl-js-ripple-effect'
].join(' ')
}, item)
]);
}.bind(this))
]) : undefined)
]);
};
App.Components.Tabview = Tabview;
|
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')(),
config = require('./../utils/config');
gulp.task('compile-html', ['process-html'], function() {
return gulp.src(config.distRoot + 'index.html')
.pipe(plugins.fileInclude({
prefix: '@@',
basepath: '@file'
}))
.pipe(gulp.dest(config.distRoot));
});
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Reservation = mongoose.model('Reservation'),
_ = require('lodash');
/**
* Create a Reservation
*/
exports.create = function(req, res) {
var reservation = new Reservation(req.body);
reservation.user = req.user;
reservation.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(reservation);
}
});
};
/**
* Show the current Reservation
*/
exports.read = function(req, res) {
res.jsonp(req.reservation);
};
/**
* Update a Reservation
*/
exports.update = function(req, res) {
var reservation = req.reservation ;
reservation = _.extend(reservation , req.body);
reservation.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(reservation);
}
});
};
/**
* Delete an Reservation
*/
exports.delete = function(req, res) {
var reservation = req.reservation ;
reservation.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(reservation);
}
});
};
/**
* List of Reservations
*/
exports.list = function(req, res) {
Reservation.find().sort('-created').populate('user', 'displayName').exec(function(err, reservations) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(reservations);
}
});
};
/**
* Reservation middleware
*/
exports.reservationByID = function(req, res, next, id) {
Reservation.findById(id).populate('user', 'displayName').exec(function(err, reservation) {
if (err) return next(err);
if (! reservation) return next(new Error('Failed to load Reservation ' + id));
req.reservation = reservation ;
next();
});
};
/**
* Reservation authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.reservation.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
'use strict';
const h = require('highland');
const _ = require('lodash');
const ua = require('universal-analytics');
module.exports = {
dest: (glob, opts) => {
return h.pipeline(stream => {
return stream
/**
* Cope with Vinyl and non-Vinyl:
*/
.map(file => {
return file.data || (file.contents && JSON.parse(file.contents)) || file;
})
/**
* Add any additional properties specified as options:
*/
.map(data => {
if (opts.ga) {
_.merge(data, opts.ga);
}
return data;
})
/**
* Push the data to GA:
*/
.doto(data => {
ua((data && data.trackingId) || (glob && glob.trackingId) || (opts && opts.trackingId))
.event(data, err => {
if (err) {
console.error(`An error occurred writing to Google Analytics:${err}`);
}
})
;
})
;
});
}
};
|
const nodemailer = require("nodemailer");
function sendEmail(subject, from, email, value) {
if (subject) {
subject = "Message Check";
}
var stmpTransport = nodemailer.createTransport({
host: "smtp.126.com",
secureConnection: true,
port: 25,
auth: {
user: "[email protected]", //你的邮箱帐号,
pass: "sqwangyi22" //你的邮箱授权码
}
});
var mailOptions = {
from: from, //标题
to: email, //收件人
subject: subject, // 标题
html: value // html 内容
};
stmpTransport.sendMail(mailOptions, function(error, response) {
if (error) {
console.log("error", error);
} else {
console.log("Message sent:" + response.message);
}
stmpTransport.close();
});
}
module.exports = {
sendEmail
};
|
import 'babel-polyfill';
import {
getSettings,
setSimQuality,
setSimSpeed
} from '../profileService.js';
beforeEach(() => {
global.localStorage.getItem.mockReset();
global.localStorage.setItem.mockReset();
global.localStorage.clear.mockReset();
global.localStorage.removeItem.mockReset();
});
test('get settings default', async () => {
const result = await getSettings();
expect(result).toHaveProperty('simSpeed', 1);
expect(result).toHaveProperty('qualitySettings', 0.5);
});
test('get stored settings', async () => {
global.localStorage.getItem.mockImplementation((key) => {
switch (key) {
case 'settings.simSpeed': return 2.34
case 'settings.quality': return 'auto'
default: return undefined;
}
})
const result = await getSettings();
expect(result).toHaveProperty('simSpeed', 2.34);
expect(result).toHaveProperty('qualitySettings', 'auto');
});
test('set simulation speed', async () => {
await setSimSpeed(4.391);
expect(global.localStorage.setItem.mock.calls).toHaveLength(1);
expect(global.localStorage.setItem.mock.calls[0][0]).toBe("settings.simSpeed");
expect(global.localStorage.setItem.mock.calls[0][1]).toBe(4.391);
});
test('set quality speed', async () => {
await setSimQuality(0.07);
expect(global.localStorage.setItem.mock.calls).toHaveLength(1);
expect(global.localStorage.setItem.mock.calls[0][0]).toBe("settings.quality");
expect(global.localStorage.setItem.mock.calls[0][1]).toBe(0.07);
global.localStorage.setItem.mockReset();
await setSimQuality('auto');
expect(global.localStorage.setItem.mock.calls).toHaveLength(1);
expect(global.localStorage.setItem.mock.calls[0][0]).toBe("settings.quality");
expect(global.localStorage.setItem.mock.calls[0][1]).toBe('auto');
});
|
$(document).ready(function(){
playVid();
openSideBar();
sideBar();
});
function playVid(){
console.log("I'm inside playVid muhahahah")
$('.intro-section').videoBG({
// mp4:'assets/vid/sp2p2.mp4',
webm:'assets/vid/sp2p2.webm',
scale:true,
zIndex:1
// position:fixed
});
// this mutes vide
$('video,audio').each(function(){this.muted=true})
};
function sideBar(){
$("#menu-close").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#sidebar-wrapper").toggleClass("active");
});
};
function openSideBar(){
$('#more-menu').on('click',function(evt){
evt.preventDefault();
var slideoutMenu = $('#slideout-menu');
var slideoutMenuWidth = $('#slideout-menu').width();
slideoutMenu.toggleClass("open");
if(slideoutMenu.hasClass("open")){
slideoutMenu.animate({
left:"0px"
});
}else {
slideoutMenu.animate({
left: -slideoutMenu
},250);
}
});
}
|
// Dialog events
CmsEngine.Dialog.Events.Delete = function () {
// Should cover all delete scenarios coming from tables
$.post(CmsEngine.ClickedElement[0].href, function (data) {
if (data.isError == false) {
$("#general-dialog").modal("hide");
alert(data.message);
CmsEngine.ClickedElement.closest("tr").hide("fast");
}
else {
alert("Error: " + data.message);
}
});
};
CmsEngine.Dialog.Events.BulkDelete = function () {
// Should cover all bulk delete scenarios coming from tables
var itemsToDelete = [];
CmsEngine.SelectedElements.each(function () {
itemsToDelete.push($(this).val());
});
$.post(CmsEngine.ClickedElement[0].href, { 'vanityId[]': itemsToDelete }, function (data) {
if (data.isError == false) {
$("#general-dialog").modal("hide");
alert(data.message);
CmsEngine.SelectedElements.closest("tr").hide("fast");
}
else {
alert("Error: " + data.message);
}
});
};
|
events.push.apply(events,
[
{
title: '<center> Kid Birthday Party <br/>5 tables reserved </center>',
start: '2016-11-19T11:00:00',
end: '2016-11-19T14:00:00',
color: "Magenta"
},
{
title: '<center> PKU Party <br/> 7 tables reserved </center>',
start: '2016-11-23T18:00:00',
end: '2016-11-23T22:00:00',
color: "SlateBlue"
},
{
title: '<center> PPC Anniversary Party <br/>No Open Play after 5pm. </center>',
start: '2017-05-13T17:00:00',
end: '2017-05-13T23:30:00',
url: "ppc-ann-chinese.html",
color: "Magenta"
},
{
title: '<center> 2018 Dream Open <br/>all tables reserved </center>',
start: '2018-01-01T09:00:00',
end: '2018-01-01T18:00:00',
url: "http://www.amandachou.com/",
color: "Magenta"
},
]);
|
jQuery(function($){
window.Contacts = Spine.Controller.create({
elements: {
".show": "showEl",
".edit": "editEl",
".show .content": "showContent",
".edit .content": "editContent"
},
events: {
"click .optEdit": "edit",
"click .optEmail": "email",
"click .optDestroy": "destroy",
"click .optSave": "save"
},
proxied: ["render", "show", "edit"],
init: function(){
this.editEl.hide();
Contact.bind("change", this.render);
this.App.bind("show:contact", this.show);
this.App.bind("edit:contact", this.edit);
},
change: function(item){
this.current = item;
this.render();
},
render: function(){
this.showContent.html($("#contactTemplate").tmpl(this.current));
this.editContent.html($("#editContactTemplate").tmpl(this.current));
},
show: function(item){
if (item && item.model) this.change(item);
this.showEl.show();
this.editEl.hide();
},
edit: function(item){
if (item && item.model) this.change(item);
this.showEl.hide();
this.editEl.show();
},
destroy: function(){
this.current.destroy();
},
email: function(){
if ( !this.current.email ) return;
window.location = "mailto:" + this.current.email;
},
save: function(){
var atts = this.editEl.serializeForm();
this.current.updateAttributes(atts);
this.show();
}
});
})
|
const mapsSchema = {
TableName: "Maps",
KeySchema: [
{
AttributeName: "mapID",
KeyType: "HASH"
}
],
AttributeDefinitions: [
{
AttributeName: "mapID",
AttributeType: "N"
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
const nodesSchema = {
TableName: "Nodes",
KeySchema: [
{
AttributeName: "nodeID",
KeyType: "HASH"
}
],
GlobalSecondaryIndexes: [
{
IndexName: "MapIndex",
KeySchema: [
{
AttributeName: "mapID",
KeyType: "HASH"
}
],
Projection: { ProjectionType: "ALL" },
ProvisionedThroughput: {
ReadCapacityUnits: 3,
WriteCapacityUnits: 3
}
}
],
AttributeDefinitions: [
{
AttributeName: "nodeID",
AttributeType: "N"
},
{
AttributeName: "mapID",
AttributeType: "N"
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
const resourcesSchema = {
TableName: "Resources",
KeySchema: [
{
AttributeName: "resourceID",
KeyType: "HASH",
},
],
GlobalSecondaryIndexes: [
{
IndexName: "MapIndex",
KeySchema: [
{
AttributeName: "mapID",
KeyType: "HASH"
}
],
Projection: { ProjectionType: "ALL" },
ProvisionedThroughput: {
ReadCapacityUnits: 3,
WriteCapacityUnits: 3
}
}
],
AttributeDefinitions: [
{
AttributeName: "resourceID",
AttributeType: "S",
},
{
AttributeName: "mapID",
AttributeType: "N"
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
};
const votesSchema = {
TableName: "Votes",
KeySchema: [
{
AttributeName: "userID",
KeyType: "HASH"
},
{
AttributeName: "resourceID",
KeyType: "RANGE"
},
],
GlobalSecondaryIndexes: [
{
IndexName: "MapIndex",
KeySchema: [
{
AttributeName: "userID",
KeyType: "HASH"
},
{
AttributeName: "mapID",
KeyType: "RANGE"
},
],
Projection: { ProjectionType: "ALL" },
ProvisionedThroughput: {
ReadCapacityUnits: 3,
WriteCapacityUnits: 3
}
}
],
AttributeDefinitions: [
{
AttributeName: "userID",
AttributeType: "S"
},
{
AttributeName: "resourceID",
AttributeType: "S"
},
{
AttributeName: "mapID",
AttributeType: "N"
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 5,
WriteCapacityUnits: 5
}
};
module.exports = {
Maps: mapsSchema,
Nodes: nodesSchema,
Resources: resourcesSchema,
Votes: votesSchema,
};
|
const _ = require('lodash');
const Artist = require('../seeds/artist');
const db = require('./db');
/**
* Finds a single artist in the artist collection.
* @param {string} _id - The ID of the record to find.
* @return {promise} A promise that resolves with the Artist that matches the id
*/
module.exports = (_id) => {
const artist = _.find(db, a => a._id === _id);
return new Promise((resolve, reject) => {
resolve(artist);
});
};
|
/**
*
* COMPUTE: covariance
*
*
* DESCRIPTION:
* - Computes the covariance between one or more numeric arrays.
*
*
* NOTES:
* [1]
*
*
* TODO:
* [1]
*
*
* LICENSE:
* MIT
*
* Copyright (c) 2014. Athan Reines.
*
*
* AUTHOR:
* Athan Reines. [email protected]. 2014.
*
*/
'use strict';
// MODULES //
var isObject = require( 'validate.io-object' );
// COVARIANCE //
/**
* FUNCTION: covariance( arr1[, arr2,...,opts] )
* Computes the covariance between one or more numeric arrays.
*
* @param {...Array} arr - numeric array
* @param {Object} [opts] - function options
* @param {Boolean} [opts.bias] - boolean indicating whether to calculate a biased or unbiased estimate of the covariance (default: false)
* @returns {Array} covariance matrix
*/
function covariance() {
var bias = false,
args,
opts,
nArgs,
len,
deltas,
delta,
means,
C,
cov,
arr,
N, r, A, B, sum, val,
i, j, n;
args = Array.prototype.slice.call( arguments );
nArgs = args.length;
if ( isObject( args[nArgs-1] ) ) {
opts = args.pop();
nArgs = nArgs - 1;
if ( opts.hasOwnProperty( 'bias' ) ) {
if ( typeof opts.bias !== 'boolean' ) {
throw new TypeError( 'covariance()::invalid input argument. Bias option must be a boolean.' );
}
bias = opts.bias;
}
}
if ( !nArgs ) {
throw new Error( 'covariance()::insufficient input arguments. Must provide array arguments.' );
}
for ( i = 0; i < nArgs; i++ ) {
if ( !Array.isArray( args[i] ) ) {
throw new TypeError( 'covariance()::invalid input argument. Must provide array arguments.' );
}
}
if ( Array.isArray( args[0][0] ) ) {
// If the first argument is an array of arrays, calculate the covariance over the nested arrays, disregarding any other arguments...
args = args[ 0 ];
}
nArgs = args.length;
len = args[ 0 ].length;
for ( i = 1; i < nArgs; i++ ) {
if ( args[i].length !== len ) {
throw new Error( 'covariance()::invalid input argument. All arrays must have equal length.' );
}
}
// [0] Initialization...
deltas = new Array( nArgs );
means = new Array( nArgs );
C = new Array( nArgs );
cov = new Array( nArgs );
for ( i = 0; i < nArgs; i++ ) {
means[ i ] = args[ i ][ 0 ];
arr = new Array( nArgs );
for ( j = 0; j < nArgs; j++ ) {
arr[ j ] = 0;
}
C[ i ] = arr;
cov[ i ] = arr.slice(); // copy!
}
if ( len < 2 ) {
return cov;
}
// [1] Compute the covariance...
for ( n = 1; n < len; n++ ) {
N = n + 1;
r = n / N;
// [a] Extract the values and compute the deltas...
for ( i = 0; i < nArgs; i++ ) {
deltas[ i ] = args[ i ][ n ] - means[ i ];
}
// [b] Update the covariance between one array and every other array...
for ( i = 0; i < nArgs; i++ ) {
arr = C[ i ];
delta = deltas[ i ];
for ( j = i; j < nArgs; j++ ) {
A = arr[ j ];
B = r * delta * deltas[ j ];
sum = A + B;
// Exploit the fact that the covariance matrix is symmetric...
if ( i !== j ) {
C[ j ][ i ] = sum;
}
arr[ j ] = sum;
} // end FOR j
} // end FOR i
// [c] Update the means...
for ( i = 0; i < nArgs; i++ ) {
means[ i ] += deltas[ i ] / N;
}
} // end FOR n
// [2] Normalize the co-moments...
n = N - 1;
if ( bias ) {
n = N;
}
for ( i = 0; i < nArgs; i++ ) {
arr = C[ i ];
for ( j = i; j < nArgs; j++ ) {
val = arr[ j ] / n;
cov[ i ][ j ] = val;
if ( i !== j ) {
cov[ j ][ i ] = val;
}
}
}
return cov;
} // end FUNCTION covariance()
// EXPORTS //
module.exports = covariance;
|
import { module } from 'qunit';
import { test } from 'ember-qunit';
import hoverintent from 'hoverintent';
module('Ember-CLI-hoverintent shim');
test('it exports vendor shim', function (assert) {
assert.equal(typeof(hoverintent), 'function', 'function is imported from vendor shim');
});
|
var moment = require('moment');
var mc = {};
// fake memcache
var set = function(key, value) {
var ts = moment().add(3,'minutes').unix();
var item = { value: value, ts:ts};
mc[key] = item;
};
var get = function(key) {
var ts = moment().unix();
if(typeof mc[key] != "undefined" && ts < mc[key].ts) {
return mc[key].value;
}
return null;
};
module.exports = {
set: set,
get: get
}
|
// @flow
import React, { Component, Fragment } from 'react';
import { Input } from 'antd';
import { func, any, bool } from 'prop-types';
import CellStyled from './Cell.styles';
import { MODES } from '../../constants';
type Props = {
children: any,
onChange: func,
mode?: string,
editable?: boolean,
shouldAutoFocus?: boolean,
};
type State = {
value: any,
};
class NumberCell extends Component<Props, State> {
state = {
value: this.props.children,
};
// $FlowFixMe
handleChange = e => {
const {
target: { value: nextValue },
} = e;
this.setState(({ value }) => {
// eslint-disable-next-line
if (!isNaN(nextValue)) {
return { value: nextValue };
}
return { value };
});
};
saveChange = () => {
const { onChange } = this.props;
const { value } = this.state;
let nextValue = value;
if (value === '' || value === '-') {
nextValue = 0;
this.setState({ value: nextValue });
}
onChange(Number(nextValue));
};
render() {
const { children, mode, editable, shouldAutoFocus } = this.props;
const { value } = this.state;
return (
<Fragment>
{editable || mode === MODES.EDIT ? (
<Input
tabIndex="0"
role="Gridcell"
value={value}
onChange={this.handleChange}
css={{
height: '100% important',
width: '100% !important',
border: `${
shouldAutoFocus ? 'none' : 'auto'
} !important`,
}}
onBlur={this.saveChange}
/>
) : (
<CellStyled>{children}</CellStyled>
)}
</Fragment>
);
}
}
NumberCell.propTypes = {
onChange: func.isRequired,
children: any,
shouldAutoFocus: bool,
};
export default NumberCell;
|
module.exports = {
name: "kick",
ns: "irc",
description: "Kick Message",
phrases: {
active: "Somebody is kicked..."
},
ports: {
input: {
bot: {
title: "IRC Client",
type: "Client",
required: true
}
},
output: {
channel: {
title: "Channel",
type: "string"
},
who: {
title: "Who",
type: "string"
},
by: {
title: "By",
type: "string"
},
reason: {
title: "Reason",
type: "string"
},
raw: {
title: "Raw",
type: "string"
}
}
},
fn: function kick(input, $, output, state, done, cb, on) {
var r = function() {
$.bot.kick('kick', function kickCallback(channel, who, by, reason, raw) {
cb({
channel: channel,
who: who,
by: by,
reason: reason,
raw: raw
});
});
}.call(this);
return {
output: output,
state: state,
on: on,
return: r
};
}
}
|
//Form
export InputInline from './InputInline/InputInline';
export Simple from './Simple/Simple';
export Control from './Control/Control';
export InputGroup from './InputGroup/InputGroup';
export OtherInput from './OtherInput/OtherInput';
export ValidateTag from './ValidateTag/ValidateTag';
export SearchInput from './SearchInput/SearchInput';
export Validate from './Validate/Validate';
export CustomValidate from './CustomValidate/CustomValidate';
export Modal from './Modal/Modal';
export DynamicAdd from './DynamicAdd/DynamicAdd';
|
// import document from 'global/document';
import QUnit from 'qunit';
import sinon from 'sinon';
import videojs from 'video.js';
// import plugin from '../src/plugin';
// const Player = videojs.getComponent('Player');
QUnit.test('the environment is sane', function(assert) {
assert.strictEqual(typeof Array.isArray, 'function', 'es5 exists');
assert.strictEqual(typeof sinon, 'object', 'sinon exists');
assert.strictEqual(typeof videojs, 'function', 'videojs exists');
});
// // QUnit.module('videojs-ogvjs', {
// // beforeEach() {
// // this.fixture = document.getElementById('qunit-fixture');
// // this.video = document.createElement('video');
// // this.fixture.appendChild(this.video);
// // this.player = new Player();
// // // Mock the environment's timers because certain things - particularly
// // // player readiness - are asynchronous in video.js 5.
// // this.clock = sinon.useFakeTimers();
// // },
// // afterEach() {
// // this.player.dispose();
// // this.clock.restore();
// // }
// // });
// QUnit.test('registers itself with video.js', function(assert) {
// assert.ok(
// typeof videojs.getTech('Ogvjs'),
// 'function',
// 'videojs-ogvjs plugin is a function'
// );
// assert.strictEqual(
// Player.prototype.ogvjs,
// plugin,
// 'videojs-ogvjs plugin was registered'
// );
// this.player.ogvjs();
// // Tick the clock forward enough to trigger the player to be "ready".
// this.clock.tick(1);
// assert.ok(
// this.player.hasClass('vjs-ogvjs'),
// 'the plugin adds a class to the player'
// );
// });
|
var windowToggleState = 0;
$(document).ready(function () {
$("#graphics").resizable({handles: "e"});
if ($(window).width() < 700) {
windowToggleState = 1;
$("#graphics").show();
$("#graphics").width($("#view").width());
$("#code").width(0);
}
$("#toggle-view-button").click(function () {
if (++windowToggleState > 2) windowToggleState = 0;
if (windowToggleState === 0 && $(window).width() < 750) {
windowToggleState = 1;
$("#graphics").show();
}
switch (windowToggleState) {
case 0:
$("#graphics").show();
$("#graphics").width($("#view").width() / 2);
$("#code").width($("#view").width() / 2 - 3);
break;
case 1:
$("#graphics").width($("#view").width());
$("#code").width(0);
break;
case 2:
$("#code").width($("#view").width() - 3);
$("#graphics").width(0);
$("#graphics").hide();
break;
}
});
});
$("#graphics").resize(function () {
$("#code").width($("#view").width() - $("#graphics").width() - 3);
});
$(window).resize(function(){
$("#code").width($("#view").width() - $("#graphics").width() - 3);
$("#graphics").height($("#view").height());
});
|
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('projects').del()
.then(function () {
return Promise.all([
// Inserts seed entries
knex('projects').insert({id: 1, projectTitle: 'FootPrints', dateCreated: '6/11/16', user_id: 1}),
knex('projects').insert({id: 6, projectTitle: 'Kate is Kool', dateCreated: '11/11/16', user_id: 2})
]);
});
};
|
let transactionController = require("../server/controllers/transactionController");
let userController = require("../server/controllers/userController");
module.exports = function(app, passport) {
// show the home page (will also have our login links)
app.get('/', function(req, res) {
// res.render('index.ejs');
});
app.get('/getTransactions', async function (req, res) {
console.log(req.isAuthenticated());
let transactions = await transactionController.findAll();
res.json({results: transactions});
});
app.get('/fetchLatest', async function (req, res) {
//console.log(req.isAuthenticated());
let transactions = await transactionController.fetchLastTransaction();
res.json({results: transactions});
});
app.get('/getTransactionsFromBank', async function (req, res) {
let noOfDays = 30;
let transactions = await transactionController.fetchAndInsert(noOfDays);
res.json({results: transactions});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// process the login form
app.post('/login', passport.authenticate('local-login'), async function (req, res) {
console.log("I am logged in");
console.log(req.body);
res.send({message : "Success"})
});
// process the signup form
app.post('/signup', async function (req, res) {
console.log(req.body);
let insertResult = await userController.insertUser(req.body);
console.log("I am signed in");
console.log(req.body);
res.send({message : "Success"})
});
};
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
|
var class_rater_fixture =
[
[ "CPPUNIT_TEST", "class_rater_fixture.html#a9fb06cbfee5dd9f3b6821243372cf614", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a11c3ec6a97dfebdc53b0bb798104a0ca", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a6e1b01b5702a7e687106c544b19cf08b", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#ad713737d6cd9fb83679aa7830fc211e2", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a092cb193c4652cc72933508852c55495", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a579b212aa7f710541edc08093e8dc5b1", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#aa2b272f17474ba2cbd96c525e844999e", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a3990c9c3fcc06af6e53e6fa73067abb3", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a0575e92ef521f0499af5bba707b0e49d", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a16e2f65de7c5ab9a4ad995b7122a3960", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a9195e5154823705dc0dcb64297dd85ca", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a4967ed30caf84689b7646837485b7641", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a03c5d435c46986c9c17250c8e354cc48", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#ad9efb308b71acf023e8eba189665830f", null ],
[ "CPPUNIT_TEST", "class_rater_fixture.html#a77012113cebf4e4a7de6313c905d1568", null ],
[ "CPPUNIT_TEST_SUITE", "class_rater_fixture.html#a23dec3073d268a176547e13081ed92f2", null ],
[ "CPPUNIT_TEST_SUITE_END", "class_rater_fixture.html#a7e4013cfb0c41e75f82ecc3e370c86e7", null ],
[ "ignoreCourseOnLunchBreak", "class_rater_fixture.html#a6e9dd08e95e017cd87b4c3820474c3d1", null ],
[ "ignoreCourseOverlappingLunch", "class_rater_fixture.html#a172fac505bbb5a9d2a238c10a5a13643", null ],
[ "setRatingForAfternoonTimePref", "class_rater_fixture.html#ab000f8fbc0f53d2ab71da503b7c4f867", null ],
[ "setRatingForCourseAfterLunchBreak", "class_rater_fixture.html#aa7ce8da24361bdcb89d9b21f4384f21f", null ],
[ "setRatingForCourseBeforeLunchBreak", "class_rater_fixture.html#a701f009378e70c068456d2d98c36ee77", null ],
[ "setRatingForLabAfterLunchBreak", "class_rater_fixture.html#aca38452908c382b99f709ff46c444cce", null ],
[ "setRatingForLabAfternoonPref", "class_rater_fixture.html#adc9af7d69bc6aba3e5a63e0aa3bbd769", null ],
[ "setRatingForLabBeforeLunchBreak", "class_rater_fixture.html#a051a4b0069c54dd90c8caa6c566b22a7", null ],
[ "setRatingForLabMorningPref", "class_rater_fixture.html#af3844bf952955079ce222be7bc6852b0", null ],
[ "setRatingForMorningTimePref", "class_rater_fixture.html#a5328e09749665a0888268b587dfe6f7e", null ],
[ "setRatingForMultipleLabs", "class_rater_fixture.html#abdc880f314e1c687b7301392297b4411", null ],
[ "setRatingForMultipleReqCourses", "class_rater_fixture.html#a120e573d61bc3ac3ea12b268e06448f7", null ],
[ "setRatingForNoTimePref", "class_rater_fixture.html#afadf8598cd9639e238f64efe2d05c4ea", null ],
[ "setRatingOnReqCourses", "class_rater_fixture.html#a4500846e04efb6f3a8fbe1b059554616", null ],
[ "setRatingOnReqLab", "class_rater_fixture.html#a2239f81d70ed6bbf4e572e98a0830ba6", null ],
[ "setUp", "class_rater_fixture.html#a9bb92fd068f3e56175f7d7a3aaef380b", null ],
[ "tearDown", "class_rater_fixture.html#a66a9afc07ff28535270997ee27a87d0f", null ],
[ "cc", "class_rater_fixture.html#aea8be9e2ee28f9a20de5d042b587c714", null ],
[ "opts", "class_rater_fixture.html#ad3a24ad9fadcbd5c63960427b191a140", null ]
];
|
angular.module('dandelionApp.admin')
.controller('OrderItemsCtrl', function ($scope, $uibModalInstance, items) {
$scope.items = items;
$scope.ok = function () {
$uibModalInstance.close();
};
});
|
/**
* 400 (Bad Request) Handler
*
* Usage:
* return res.badRequest();
* return res.badRequest(data);
* return res.badRequest(data, 'some/specific/badRequest/view');
*
* e.g.:
* ```
* return res.badRequest(
* 'Please choose a valid `password` (6-12 characters)',
* 'trial/signup'
* );
* ```
*/
module.exports = function badRequest(data, options) {
// Get access to `req`, `res`, & `sails`
var req = this.req;
var res = this.res;
var sails = req._sails;
// Set status code
res.status(400);
// Log error to console
if (data !== undefined) {
sails.log.verbose('Sending 400 ("Bad Request") response: \n', data);
}
else sails.log.verbose('Sending 400 ("Bad Request") response');
// Only include errors in response if application environment
// is not set to 'production'. In production, we shouldn't
// send back any identifying information about errors.
if (sails.config.environment === 'production') {
data = undefined;
}
// If the user-agent wants JSON, always respond with JSON
if (req.wantsJSON) {
return res.jsonx(data);
}
// If second argument is a string, we take that to mean it refers to a view.
// If it was omitted, use an empty object (`{}`)
options = (typeof options === 'string') ? {view: options} : options || {};
// If a view was provided in options, serve it.
// Otherwise try to guess an appropriate view, or if that doesn't
// work, just send JSON.
if (options.view) {
return res.view(options.view, {data: data});
}
// If no second argument provided, try to serve the implied view,
// but fall back to sending JSON(P) if no view can be inferred.
else return res.guessView({data: data}, function couldNotGuessView() {
return res.jsonx(data);
});
};
|
(function () {
'use strict';
var $ = window.bebop, fix, fixtures, html;
describe('IO', function () {
before(function () {
fix = new Fixture('test/fixtures');
fixtures = fix.load('node.html');
});
after(function () {
fix.cleanup();
});
describe('types', function () {
it('should do a get request', function (done) {
$.io.get({
bust: true,
url: '/io/one.txt',
type: 'text'
}).then(function (xhr) {
expect(xhr.res.status).to.not.equal(404);
done()
}).catch(function (err) {
done(err);
});
});
it('should do a head request', function (done) {
$.io.head({
bust: true,
url: '/io/one.txt'
}).then(function (xhr) {
expect(xhr.res.status).to.not.equal(404);
done()
}).catch(function (err) {
done(err);
});
});
it('should do a post request', function (done) {
$.io.post({
bust: true,
url: '/io/one.txt'
}).then(function (xhr) {
expect(xhr.res.status).to.not.equal(404);
done()
}).catch(function (err) {
done(err);
});
});
it('should do a put request', function (done) {
$.io.put({
bust: true,
url: '/io/one.txt'
}).then(function (xhr) {
expect(xhr.res.status).to.not.equal(404);
done()
}).catch(function (err) {
done(err);
});
});
it('should do a del request', function (done) {
$.io.del({
bust: true,
url: '/io/one.txt'
}).then(function (xhr) {
expect(xhr.res.status).to.not.equal(404);
done()
}).catch(function (err) {
done(err);
});
});
});
describe('content', function () {
it('should request text', function (done) {
$.io.get({
url: '/io/one.txt'
}).then(function (xhr) {
expect(xhr.res.data).to.equal('foo bar');
done()
}).catch(function (err) {
done(err);
});
});
it('should request json', function (done) {
$.io.get({
url: '/io/two.json',
type: 'json'
}).then(function (xhr) {
expect(xhr.res.data).to.be.an('object').and.to.have.property('foo');
done()
}).catch(function (err) {
done(err);
});
});
it('should return broken json as text', function (done) {
$.io.get({
url: '/io/fail.json',
type: 'json'
}).then(function (xhr) {
expect(xhr.res.data).to.equal(xhr.req.responseText);
done()
}).catch(function (err) {
done(err);
});
});
it('should request html', function (done) {
$.io.get({
url: '/io/three.html',
type: 'html'
}).then(function (xhr) {
expect(xhr.res.data.matches('span.foo')).to.be.true; //jshint ignore:line
done()
}).catch(function (err) {
done(err);
});
});
it('should return broken html as text', function (done) {
$.io.get({
url: '/io/fail.html',
type: 'html'
}).then(function (xhr) {
expect(xhr.res.data._node).to.be.undefined;
done()
}).catch(function (err) {
done(err);
});
});
it('should request xml', function (done) {
$.io.get({
url: '/io/four.xml',
type: 'xml'
}).then(function (xhr) {
expect(xhr.res.data).to.be.ok; //jshint ignore:line
done()
}).catch(function (err) {
done(err);
});
});
});
describe('data', function () {
it('should get with data', function (done) {
$.io.get({
url: '/io/one.txt',
bust: true,
data: {foo: 'bar'}
}).then(function (xhr) {
expect(xhr.res.url).to.match(/one\.txt\?foo=bar$/);
done()
}).catch(function (err) {
done(err);
});
});
it('should post with form', function(done) {
var form = $.one('form', fix.el);
$.io.post({
url: '/io/one.txt',
bust: true,
data: new FormData(form._node)
}).then(function (xhr) {
expect(xhr.res.url).to.match(/one\.txt$/);
done()
}).catch(function (err) {
done(err);
});
});
});
describe('header', function () {
it('should set custom header', function () {
$.io.get({
url: '/io/one.txt',
bust: true,
head: {
'X-Sent-By': 'Karma'
}
});
});
});
});
}());
|
export default function isString(object) {
return toString.call(object) == '[object String]';
}
|
var CSSLint = require("csslint").CSSLint;
exports = module.exports = function(content,log) {
var result = CSSLint.verify(content);
if (!result.messages.length) {
log(null, "CSS");
}
else {
for (var idx in result.messages) {
var warn = result.messages[idx];
var message = warn.message.split(" at line ")[0].replace(/\.$/, "");
log({
message: message,
line: warn.line,
col: warn.col
}, "CSS");
}
}
}
|
/**
* Main application routes
*/
'use strict';
var errors = require('./components/errors');
module.exports = function(app) {
// Insert routes below
app.use('/api/packs', require('./api/pack'));
app.use('/api/users', require('./api/user'));
app.use('/api/students', require ('./api/student'));
app.use('/auth', require('./auth'));
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
};
|
const db = require('georap-db');
const lib = require('./lib');
module.exports = (params, callback) => {
// Parameters:
// params:
// locationId
// locationName
// username
// newType
// string
// oldType
// string
const newEvent = {
type: 'location_type_changed',
user: params.username,
time: db.timestamp(),
locationId: params.locationId,
locationName: params.locationName,
data: {
newType: params.newType,
oldType: params.oldType,
},
};
lib.insertAndEmit(newEvent, callback);
};
|
function setEnvDefault(key, val) {
if (!process.env[key]) {
process.env[key] = val;
}
}
setEnvDefault('NODE_ENV', 'development');
setEnvDefault('TOGA_ENVIRONMENT', 'development');
setEnvDefault('TOGA_HONEYBADGER_KEY', 'its a secret');
setEnvDefault('TOGA_LOGFILE', './logs/application.logstash.log');
|
var classrocksdb_1_1RateLimiter =
[
[ "~RateLimiter", "classrocksdb_1_1RateLimiter.html#aecf58cff5b5c087953e9f55614ece237", null ],
[ "GetSingleBurstBytes", "classrocksdb_1_1RateLimiter.html#a4354ccb1bd11c7bf84210adb30544ce5", null ],
[ "GetTotalBytesThrough", "classrocksdb_1_1RateLimiter.html#a09bcea728c13012315223e3e08a18df0", null ],
[ "GetTotalRequests", "classrocksdb_1_1RateLimiter.html#a612909dc7934f497042312bfdb185844", null ],
[ "Request", "classrocksdb_1_1RateLimiter.html#a810573502b5fe0a1e97a9357eaee2abf", null ],
[ "SetBytesPerSecond", "classrocksdb_1_1RateLimiter.html#a53648ecfbbd85daa0966017b3a57ec44", null ]
];
|
/**
* Page Component for Flashcard Manager
*/
// import node packages
import React, { Component } from 'react';
import PropTypes from 'prop-types';
// import local components
import FlashcardContainer from './containers/FlashcardContainer';
import FlashcardHelper from './helpers/FlashcardHelper';
import PageDiv from './presenters/PageDiv';
// Component Metadata
const propTypes = {
library: PropTypes.object.isRequired,
};
const defaultProps = {
library: {},
};
// Component Class for Explorer View
class FlashcardExplorer extends Component {
constructor (props) {
super(props);
// Member Variables
this.state = {
flashcards: FlashcardHelper.getAllCards(this.props.library),
};
// Function Bindings
this.handleDeleteCard = this.handleDeleteCard.bind(this);
this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this);
this.render = this.render.bind(this);
} // end constructor
// Class Functions
handleDeleteCard (idx) {
alert("Delete from flashcard manager not yet implemented.");
} // end handleDeleteCard
componentWillReceiveProps(nextProps) {
if (nextProps !== this.props) {
var newCards = FlashcardHelper.getAllCards(nextProps.library);
this.setState({ flashcards: newCards });
}
} // end componentWillReceiveProps
render () {
if (this.state.flashcards.length > 0) {
return (
<PageDiv width='60%'>
{this.state.flashcards.map(card => (
<FlashcardContainer
flashcard={card}
viewType="li"
readOnly={true} />
))}
</PageDiv>
);
} else {
return (
<PageDiv>
There don't appear to be any flashcards in this notebook yet.
</PageDiv>
);
}
} // end render
}
FlashcardExplorer.propTypes = propTypes;
FlashcardExplorer.defaultProps = defaultProps;
export default FlashcardExplorer;
|
define('routeParser', ['each'], function(each) {
var rx1 = /:(\w+)/g;
var rx2 = /\/:(\w+)/g;
function keyValues(key, index, list, params) {
if (key[0] === ':') {
params.result[key.replace(':', '')] = params.parts[index];
}
}
function urlKeyValues(str, index, list, result) {
var parts = str.split('=');
result[parts[0]] = parts[1];
}
function getPathname(url, dropQueryParams) {
if (dropQueryParams) {
url = url.split('?').shift();
}
url = url.replace(/^\w+:\/\//, '');// replace protocol
url = url.replace(/^\w+:\d+\//, '/');// replace port
url = url.replace(/^\w+\.\w+\//, '/');// replace domain
return url;
}
function extractParams(patternUrl, url, combined) {
url = getPathname(url);
var parts = url.split('?'),
searchParams = parts[1],
params = {},
queryParams = {};
if (patternUrl[0] === '/' && parts[0][0] !== '/') {
parts[0] = '/' + parts[0];// make sure the indexes line up.
}
parts = parts[0].split('/');
each(patternUrl.split('/'), {result:params, parts:parts}, keyValues);
if (searchParams) {
each(searchParams.split('&'), queryParams, urlKeyValues);
}
return combined ? combine({}, [params, queryParams]) : {params:params, query: queryParams};
}
function combine(target, objects) {
var i, j, len = objects.length, object;
for(i = 0; i < len; i += 1) {
object = objects[i];
for (j in object) {
if (object.hasOwnProperty(j)) {
target[j] = object[j];
}
}
}
return target;
}
function matchParam(value, index, list, params) {
if (value === '') {
// ignore that param.
} else if (!params.values.hasOwnProperty(value) || params.values[value] === undefined) {
params.hasParams = false;
}
}
function match(patternUrl, url) {
var patternParams = patternUrl.indexOf('?') !== -1 ? patternUrl.split('?').pop().split('&') : [];
patternUrl.replace(rx1, function(match, g) {
patternParams.push(g);
return match;
});
var params = {
values: extractParams(patternUrl.split('?').shift(), url, true),
hasParams: !!patternParams.length
};
if (params.hasParams) {
each(patternParams, params, matchParam);
if (!params.hasParams) {
return null;// it did not match all of the required params.
}
}
// now we need to fix up the url so that it can be matched on.
var matchUrl = patternUrl.split('?').shift().replace(rx2, function(match, g1) {
return '/' + params.values[g1];
});
// stips url down to path, then only matches from the end what was built.
var endOfPathName = getPathname(url, true);
return endOfPathName === matchUrl;
}
return {
match: match,
extractParams: extractParams
};
});
|
"use strict";
module.exports = require("@jsdevtools/ez-spawn");
|
Future = Npm.require("fibers/future");
[ "aggregate", "count", "distinct", "group", "findOne", "find" ].forEach( m => {
//create "countAsync", "aggregateAsync", "groupAsync", and "findOneAsync" methods for collections
//these are just direct versions of mongodb driver calls
Mongo.Collection.prototype[ m + "Async" ] = function( ...args) {
var col = this.rawCollection();
col[ m ].apply( col, args );
};
//wrap async functions to return a future, i.e. "findFuture"
Mongo.Collection.prototype[ m + "Future" ] = function ( ...args ) {
return Future.wrap( this[ m + "Async" ] ).apply( this, args );
};
Mongo.Collection.prototype[ m + "Promise" ] = function( ...args ){
var self = this;
return new Promise( ( resolve, reject ) => {
var cb = (err,res) => {
if ( err ) reject( err );
else resolve( res );
};
self[ m + "Async"].call( self, ...args, cb );
});
}
});
//add synchronous versions of methods meteor doesn"t provide
[ "count", "aggregate", "group", "distinct" ].forEach( m => {
Mongo.Collection.prototype[ m ] = function( ...args ){
return Meteor.wrapAsync( this[ m + "Async" ] ).apply( this, args );
}
});
|
module.exports = {
extends: ['./react.js'],
parser: 'babel-eslint',
rules: {
'react/no-unknown-property': [2, { ignore: ['class'] }],
'react/prop-types': 0
},
settings: { react: { pragma: 'h' } }
};
|
/* eslint-env node */
'use strict';
const getChannelURL = require('ember-source-channel-url');
module.exports = function() {
return Promise.all([
getChannelURL('release'),
getChannelURL('beta'),
getChannelURL('canary'),
]).then(urls => {
return {
useYarn: true,
scenarios: [
{
name: 'ember-3.8',
npm: {
devDependencies: {
'ember-data': '3.8.0',
'ember-source': '3.8.0',
}
}
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-data': 'release',
'ember-source': urls[0],
}
}
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-data': 'beta',
'ember-source': urls[1],
}
}
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-data': 'canary',
'ember-source': urls[2],
}
}
}
]
};
});
};
|
// Regular expression that matches all symbols in the Mandaic block as per Unicode v8.0.0:
/[\u0840-\u085F]/;
|
const PImage = require('pureimage');
const fs = require('fs');
const RGBBuffer = require('./RGBBuffer');
const dateFormat = require('dateformat');
const settings = new (require('./OverlaySettings').OverlaySettings)();
/**
* Overlay class that processes a raw bitmap by drawing related data on top of
* it, and outputs it in the bitmap format.
*/
class Overlay {
constructor() {
/**
* Humidity icon bitmap.
* @type {Bitmap}
*/
this.iconHumidity = null;
/**
* Temperature icon bitmap.
* @type {Bitmap}
*/
this.iconTemperature = null;
/**
* Water level icon bitmap.
* @type {Bitmap}
*/
this.iconWaterLevel = null;
/**
* Keeps track of whether the resources have been loaded or not.
* @type {Boolean}
*/
this.resourcesLoaded = false;
}
/**
* Loads all necessary filesystem resources for drawing the overlay.
* @return {Promise} Promise that resolves when all resouces have been loaded.
*/
loadResources() {
// If the resources have already been loaded, we can skip this.
if(this.resourcesLoaded) {
return true;
}
// Load in the humidity image.
var humidityPromise = PImage.decodePNGFromStream( fs.createReadStream(settings.HUMIDITY_IMAGE_PATH) )
.then((bitmap) => {
this.iconHumidity = bitmap;
});
// Load in the temperature image.
var temperaturePromise = PImage.decodePNGFromStream( fs.createReadStream(settings.TEMPERATURE_IMAGE_PATH) )
.then((bitmap) => {
this.iconTemperature = bitmap;
});
// Load in the water level image.
var waterLevelPromise = PImage.decodePNGFromStream( fs.createReadStream(settings.WATER_LEVEL_IMAGE_PATH) )
.then((bitmap) => {
this.iconWaterLevel = bitmap;
});
// Load in the font.
var fontPromise = new Promise((resolve, reject) => {
PImage.registerFont(settings.STATUS_FONT_PATH, settings.STATUS_FONT_NAME).load(() => {
resolve();
});
});
// Resolve all promises.
return Promise.all([humidityPromise, temperaturePromise, waterLevelPromise, fontPromise]).then(() => {
this.resourcesLoaded = true;
});
};
/**
* Overlays one bitmap onto another, blending by alpha.
* @param {Bitmap} targetBitmap The bitmap to draw onto.
* @param {Bitmap} imageBitmap The bitmap to draw on top of the target.
* @param {Number} left The x coordinate to draw to.
* @param {Number} top The y coordinate to draw to.
*/
overlayImage(targetBitmap, imageBitmap, left, top) {
let targetData = targetBitmap.data;
let imageData = imageBitmap.data;
// Iterate the pixels of the image bitmap, so that we can draw an alpha
// blended icon into the target canvas.
for(var x=0; x < imageBitmap.width; x++) {
for(var y=0; y < imageBitmap.height; y++) {
let targetIndex = targetBitmap.calculateIndex(left + x, top + y);
let imageIndex = imageBitmap.calculateIndex(x, y);
let imageAlpha = imageBitmap.data[imageIndex + 3] / 0xFF;
// Blend the colors by using a simple blending formula
// targetColor = (imageColor * imageAlpha) + (targetColor * (1 - imageAlpha))
targetData[targetIndex] = (imageData[imageIndex] * imageAlpha) + (targetData[targetIndex] * (1 - imageAlpha));
targetData[targetIndex+1] = (imageData[imageIndex+1] * imageAlpha) + (targetData[targetIndex+1] * (1 - imageAlpha));
targetData[targetIndex+2] = (imageData[imageIndex+2] * imageAlpha) + (targetData[targetIndex+2] * (1 - imageAlpha));
}
}
}
/**
* Draws an anchored icon bitmap, in the specified target bitmap, using a y position.
* @param {Bitmap} targetBitmap The target bitmap to draw the icon into.
* @param {Bitmap} imageBitmap The image to draw to the target.
* @param {Number} yAnchor The Y position to draw the icon at.
*/
drawAnchoredIcon(targetBitmap, imageBitmap, yAnchor) {
// Center Image
let x = settings.ICON_IMAGE_X_OFFSET - imageBitmap.width / 2;
let y = yAnchor;
this.overlayImage(targetBitmap, imageBitmap, x, y);
}
/**
* Draws the overlay onto the provided bitmap, using the temperature and
* humidity values.
* @param {Bitmap} bitmap The bitmap to draw to.
* @param {Number} temperature The temperature value to draw.
* @param {Number} humidity The humidity value to draw.
*/
drawOverlay(bitmap, temperature, humidity) {
// Get canvas instance.
var ctx = bitmap.getContext('2d');
// Get formatted date string.
let dateString = dateFormat(new Date(), 'dddd, mmmm dS, yyyy, h:MM:ss TT')
// Keep track of the current icon drawing positions.
let iconImageY = settings.ICON_IMAGE_Y_START;
let iconTextY = settings.ICON_TEXT_Y_START;
// Set up the font styling
ctx.font = `24pt ${settings.STATUS_FONT_NAME}`;
ctx.fillStyle = '#FFFFFF';
// Draw the date timestamp
ctx.fillText(dateString, settings.STATUS_TEXT_X_OFFSET, settings.STATUS_TEXT_Y_OFFSET);
// Draw the temperature
this.drawAnchoredIcon(bitmap, this.iconTemperature, iconImageY);
ctx.fillText(temperature.toFixed(2) + '°', settings.ICON_TEXT_X_OFFSET, iconTextY);
// Draw the humidity
this.drawAnchoredIcon(bitmap, this.iconHumidity, (iconImageY += settings.ICON_Y_SPACING));
ctx.fillText(humidity.toFixed(2) + '%', settings.ICON_TEXT_X_OFFSET, (iconTextY += settings.ICON_Y_SPACING));
// Draw the water level
// this.drawAnchoredIcon(bitmap, this.iconWaterLevel, (iconImageY += settings.ICON_Y_SPACING));
// ctx.fillText("N/A", settings.ICON_TEXT_X_OFFSET, (iconTextY += settings.ICON_Y_SPACING));
};
}
exports.Overlay = Overlay;
|
var express = require('express');
var router = express.Router();
var multer=require('multer');
var upload=multer({dest:'./uploads/'});
var quizController=require('../controllers/quiz_controller');
var commentController=require('../controllers/comment_controller');
var userController=require('../controllers/user_controller');
var sessionController=require('../controllers/session_controller');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
router.param('format',quizController.format);
//Autoload quiz
router.param('quizId',quizController.load);//cuando quizId existe
//Autoload user
router.param('userId',userController.load);//cuando userId existe
//Autoload user
router.param('commentId',commentController.load);
// Definición de rutas de sesion
router.get('/session', sessionController.new); // formulario login
router.post('/session', sessionController.create); // crear sesión
router.delete('/session', sessionController.destroy); // destruir sesión
//rutas /quizzes
router.get('/quizzes.:format?', quizController.index);
router.get('/quizzes/:quizId(\\d+).:format?', quizController.show);
router.get('/quizzes/:quizId(\\d+)/check', quizController.check);
router.get('/quizzes/new', sessionController.loginRequired, quizController.new);
router.post('/quizzes', sessionController.loginRequired,
upload.single('image'),
quizController.create);
router.get('/quizzes/:quizId(\\d+)/edit', sessionController.loginRequired,
quizController.ownershipRequired,
quizController.edit);
router.put('/quizzes/:quizId(\\d+)', sessionController.loginRequired,
quizController.ownershipRequired,
upload.single('image'),
quizController.update);
router.delete('/quizzes/:quizId(\\d+)', sessionController.loginRequired,
quizController.ownershipRequired,
quizController.destroy);
//rutas comments
router.get('/quizzes/:quizId(\\d+)/comments/new', sessionController.loginRequired, commentController.new);
router.post('/quizzes/:quizId(\\d+)/comments', sessionController.loginRequired, commentController.create);
router.put('/quizzes/:quizId(\\d+)/comments/:commentId(\\d+)/accept',sessionController.loginRequired,
quizController.ownershipRequired,
commentController.accept);
//rutas users
router.get('/users',userController.index);
router.get('/users/:userId(\\d+)',userController.show);
router.get('/users/new',userController.new);
router.post('/users',userController.create);
router.get('/users/:userId(\\d+)/edit', sessionController.loginRequired,
sessionController.adminOrMyselfRequired,
userController.edit); // editar información de cuenta
router.put('/users/:userId(\\d+)', sessionController.loginRequired,
sessionController.adminOrMyselfRequired,
userController.update); // actualizar información de cuenta
router.delete('/users/:userId(\\d+)', sessionController.loginRequired,
sessionController.adminAndNotMyselfRequired,
userController.destroy); // borrar cuenta
router.get('/author',function(req, res, next) { res.render('author');});
module.exports = router;
|
'use strict';
//Drivers service used for drivers REST endpoint
angular.module('mean.drivers').factory('Drivers', ['$resource',
function($resource) {
return $resource('drivers/:driverId', {
driverId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
'use strict'
const content = require('../../static/content')
const replies = require('./util/replies')
// Handle help command
module.exports = (user, args, callback) => {
replies.delayReply(content.help, callback)
}
|
import React from 'react'
import { Flex } from 'rebass/styled-components'
import { FormattedMessage } from 'react-intl'
import { Button, Text } from 'components/UI'
import messages from './messages'
const Tutorials = props => (
<Flex alignItems="center" flexDirection="column" justifyContent="center" {...props}>
<Text my={3}>
<FormattedMessage {...messages.tutorials_list_description} />
</Text>
<Button mx="auto" onClick={() => window.Zap.openHelpPage()} size="small">
<FormattedMessage {...messages.tutorials_button_text} />
</Button>
</Flex>
)
export default Tutorials
|
const { spawnPromise, parseOptions } = require('../helpers')
const path = require('path')
module.exports = ({ stylelintOptions, extendStylelintOptions }) => {
const params = parseOptions({
overwriteOptions: stylelintOptions,
extendOptions: extendStylelintOptions,
defaultParams: [
'src/**/*.css',
'--allow-empty-input',
'--color',
'--config',
path.resolve(__dirname, '../configs/stylelintrc.json')
]
})
return spawnPromise({ bin: 'stylelint', params })
}
|
function Weapon(data) {
AbstractModel.call(this, data)
}
Weapon.create = AbstractModel.create;
Weapon.prototype = {
// Any calc method
getSpeciality : function () {
return this.group;
},
// Calculate the damages of the weapon
calculateDamage : function (qualityId) {
var degats = 0;
if(qualityId) {
var quality = _.find(Data.get('qualities'), (o) => o.id == qualityId);
degats = quality.bonus.deg;
}
if(this.associatedComp.length === 0) {
return degats;
}
if(this.associatedComp) {
var degatsCompStr = $("#" + this.associatedComp).val();
if (degatsCompStr) {
degats += Number(degatsCompStr);
}
}
if(this.bonusBase) {
degats += Number(this.bonusBase);
}
if(this.bonusSpe) {
var degatsSpeStr = $("#" + this.bonusSpe).html();
if (degatsSpeStr) {
degats += Number(degatsSpeStr);
}
}
return degats;
},
getAttribute : function (qualityId) {
var attribute = this.attributs.label;
if(qualityId) {
var quality = _.find(Data.get('qualities'), (o) => o.id == qualityId);
attribute = quality.calculateAttribute(this.id);
}
return attribute;
},
hasPerforanteAttribute : function () {
return this.attributs.isPerf === true;
}
};
|
var btn = document.querySelector('button');
var p = document.getElementsByTagName('p')[0];
var request = new XMLHttpRequest();
function getStatus(){
request.onreadystatechange = function(){
p.innerHTML += request.readyState + "<br />";
}
request.open('GET', 'php.php', true);
request.send(null);
};
btn.addEventListener('click', getStatus, false);
|
Error.stackTraceLimit = Infinity;
require('core-js/es6');
require('reflect-metadata');
require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');
var appContext = require.context('../src', true, /\.spec\.ts/);
appContext.keys().forEach(appContext);
var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');
testing.setBaseTestProviders(
browser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS,
browser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS
);
|
const through2 = require('through2')
, superagent = require('superagent')
, filecheck = require('workshopper-exercise/filecheck')
, execute = require('workshopper-exercise/execute')
, comparestdout = require('workshopper-exercise/comparestdout')
, rndport = require('../../lib/rndport')
let exercise = require('workshopper-exercise')()
// checks that the submission file actually exists
exercise = filecheck(exercise)
// execute the solution and submission in parallel with spawn()
exercise = execute(exercise)
// set up ports to be passed to submission and solution
exercise.addSetup(function(mode, callback) {
this.submissionPort = rndport()
this.solutionPort = this.submissionPort + 1
this.submissionArgs = [this.submissionPort]
this.solutionArgs = [this.solutionPort]
process.nextTick(callback)
})
// add a processor for both run and verify calls, added *before*
// the comparestdout processor so we can mess with the stdouts
exercise.addProcessor(function (mode, callback) {
this.submissionStdout.pipe(process.stdout)
// replace stdout with our own streams
this.submissionStdout = through2()
if (mode == 'verify')
this.solutionStdout = through2()
setTimeout(query.bind(this, mode), 1500)
process.nextTick(function () {
callback(null, true)
})
})
// compare stdout of solution and submission
exercise = comparestdout(exercise)
// delayed for 500ms to wait for servers to start so we can start
// playing with them
function query (mode) {
const exercise = this
function connect (port, stream) {
const url = 'http://localhost:' + port + '/home'
superagent.get(url)
.on('error', function (err) {
exercise.emit(
'fail'
, exercise.__('fail.connection', {address: url, message: err.message})
)
})
.pipe(stream)
}
connect(this.submissionPort, this.submissionStdout)
if (mode == 'verify')
connect(this.solutionPort, this.solutionStdout)
}
module.exports = exercise
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.commons.HorizontalDivider.
sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'],
function(jQuery, library, Control) {
"use strict";
/**
* Constructor for a new HorizontalDivider.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Divides the screen in visual areas.
* @extends sap.ui.core.Control
* @version 1.36.6
*
* @constructor
* @public
* @alias sap.ui.commons.HorizontalDivider
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var HorizontalDivider = Control.extend("sap.ui.commons.HorizontalDivider", /** @lends sap.ui.commons.HorizontalDivider.prototype */ { metadata : {
library : "sap.ui.commons",
properties : {
/**
* Defines the width of the divider.
*/
width : {type : "sap.ui.core.CSSSize", group : "Appearance", defaultValue : '100%'},
/**
* Defines the type of the divider.
*/
type : {type : "sap.ui.commons.HorizontalDividerType", group : "Appearance", defaultValue : sap.ui.commons.HorizontalDividerType.Area},
/**
* Defines the height of the divider.
*/
height : {type : "sap.ui.commons.HorizontalDividerHeight", group : "Appearance", defaultValue : sap.ui.commons.HorizontalDividerHeight.Medium}
}
}});
// No Behaviour
return HorizontalDivider;
}, /* bExport= */ true);
|
/*
* kvtable.js v0.1
* Copyright 47rooks.com 2017
* Release under MIT License.
*
* Timer requires Vue.js to be loaded before it.
*/
Vue.component('f7-kvtable', {
template: `
<div>
<h3> {{heading}} </h3>
<table id="kvTable">
<tr v-for="elt in kv">
<td> {{elt.k}} </td>
<td class="number" v-if="!isNaN(parseFloat(elt.v)) && isFinite(elt.v)"> {{elt.v}} </td>
<td v-else> {{elt.v}} </td>
</tr>
</table>
</div>`,
data: function() {
return {
heading: null,
kv: [],
}
},
methods: {
set: function(kvData) {
this.heading = kvData.heading;
this.kv = kvData.kv;
}
}
});
|
/*
Script: GrowingInput.js
Alters the size of an input depending on its content
License:
MIT-style license.
Authors:
Guillermo Rauch
*/
(function(){
GrowingInput = function(element, options){
var value, lastValue, calc;
options = $.extend({
min: 0,
max: null,
startWidth: 15,
correction: 15
}, options);
element = $(element).data('growing', this);
var self = this;
var init = function(){
calc = $('<span></span>').css({
'float': 'left',
'display': 'inline-block',
'position': 'absolute',
'left': -1000
}).insertAfter(element);
$.each(['font-size', 'font-family', 'padding-left', 'padding-top', 'padding-bottom',
'padding-right', 'border-left', 'border-right', 'border-top', 'border-bottom',
'word-spacing', 'letter-spacing', 'text-indent', 'text-transform'], function(i, p){
calc.css(p, element.css(p));
});
element.blur(resize).keyup(resize).keydown(resize).keypress(resize);
resize();
};
var calculate = function(chars){
calc.html(chars);
var width = calc.width();
return (width ? width : options.startWidth) + options.correction;
};
var resize = function(){
lastValue = value;
value = element.val();
var retValue = value;
if(chk(options.min) && value.length < options.min){
if(chk(lastValue) && (lastValue.length <= options.min)) return;
retValue = str_pad(value, options.min, '-');
} else if(chk(options.max) && value.length > options.max){
if(chk(lastValue) && (lastValue.length >= options.max)) return;
retValue = value.substr(0, options.max);
}
element.width(calculate(retValue));
return self;
};
this.resize = resize;
init();
};
var chk = function(v){ return !!(v || v === 0); };
var str_repeat = function(str, times){ return new Array(times + 1).join(str); };
var str_pad = function(self, length, str, dir){
if (self.length >= length) return this;
str = str || ' ';
var pad = str_repeat(str, length - self.length).substr(0, length - self.length);
if (!dir || dir == 'right') return self + pad;
if (dir == 'left') return pad + self;
return pad.substr(0, (pad.length / 2).floor()) + self + pad.substr(0, (pad.length / 2).ceil());
};
})();
|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['sap/ui/model/odata/type/DateTimeBase'],
function(DateTimeBase) {
"use strict";
/**
* Adjusts the constraints for DateTimeBase.
*
* @param {sap.ui.model.odata.type.DateTime} oType
* the type
* @param {object} [oConstraints]
* constraints, see {@link #constructor}
* @returns {object}
* the constraints adjusted for DateTimeBase
*/
function adjustConstraints(oType, oConstraints) {
var oAdjustedConstraints = {};
if (oConstraints) {
switch (oConstraints.displayFormat) {
case "Date":
oAdjustedConstraints.isDateOnly = true;
break;
case undefined:
break;
default:
jQuery.sap.log.warning("Illegal displayFormat: " + oConstraints.displayFormat,
null, oType.getName());
}
oAdjustedConstraints.nullable = oConstraints.nullable;
}
return oAdjustedConstraints;
}
/**
* Constructor for a primitive type <code>Edm.DateTime</code>.
*
* @class This class represents the OData primitive type <a
* href="http://www.odata.org/documentation/odata-version-2-0/overview#AbstractTypeSystem">
* <code>Edm.DateTime</code></a>.
*
* If you want to display a date and a time, prefer {@link
* sap.ui.model.odata.type.DateTimeOffset}, specifically designed for this purpose.
*
* Use <code>DateTime</code> with the SAP-specific annotation <code>display-format=Date</code>
* (resp. the constraint <code>displayFormat: "Date"</code>) to display only a date.
*
* In {@link sap.ui.model.odata.v2.ODataModel ODataModel} this type is represented as a
* <code>Date</code>. With the constraint <code>displayFormat: "Date"</code>, the timezone is
* UTF and the time part is ignored, otherwise it is a date/time value in local time.
*
* @extends sap.ui.model.odata.type.DateTimeBase
*
* @author SAP SE
* @version 1.32.10
*
* @alias sap.ui.model.odata.type.DateTime
* @param {object} [oFormatOptions]
* format options as defined in {@link sap.ui.core.format.DateFormat}
* @param {object} [oConstraints]
* constraints; {@link sap.ui.model.odata.type.DateTimeBase#validateValue validateValue}
* throws an error if any constraint is violated
* @param {boolean|string} [oConstraints.nullable=true]
* if <code>true</code>, the value <code>null</code> is accepted
* @param {string} [oConstraints.displayFormat=undefined]
* may be "Date", in this case only the date part is used, the time part is always 00:00:00
* and the timezone is UTC to avoid timezone-related problems
* @public
* @since 1.27.0
*/
var DateTime = DateTimeBase.extend("sap.ui.model.odata.type.DateTime", {
constructor : function (oFormatOptions, oConstraints) {
DateTimeBase.call(this, oFormatOptions, adjustConstraints(this, oConstraints));
}
}
);
/**
* Returns the type's name.
*
* @returns {string}
* the type's name
* @public
*/
DateTime.prototype.getName = function () {
return "sap.ui.model.odata.type.DateTime";
};
return DateTime;
});
|
"use strict";
const runPrettier = require("../run-prettier.js");
const EOL = "\n";
describe("uses 'extensions' from languages to determine parser", () => {
runPrettier("plugins/extensions", ["*.foo", "--plugin=./plugin"], {
ignoreLineEndings: true,
}).test({
stdout: "!contents" + EOL,
stderr: "",
status: 0,
write: [],
});
});
|
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var transactionTypeSchema = new Schema({
name: String,
sign: Number,
allowPlace: Boolean,
allowConcept: Boolean,
automaticTransaction: Boolean,
id_AccountType : { type: Schema.Types.ObjectId, ref: 'AccountType' }
});
module.exports = mongoose.model('TransactionType', transactionTypeSchema);
|
(function() {
'use strict';
angular
.module('noctemApp')
.directive('activeMenu', activeMenu);
activeMenu.$inject = ['$translate', '$locale', 'tmhDynamicLocale'];
function activeMenu($translate, $locale, tmhDynamicLocale) {
var directive = {
restrict: 'A',
link: linkFunc
};
return directive;
function linkFunc(scope, element, attrs) {
var language = attrs.activeMenu;
scope.$watch(function() {
return $translate.use();
}, function(selectedLanguage) {
if (language === selectedLanguage) {
tmhDynamicLocale.set(language);
element.addClass('active');
} else {
element.removeClass('active');
}
});
}
}
})();
|
import builder from './builder';
// @todo: like reducer -> control
export const NAVIGATE_TO = 'NAVIGATE_TO';
export const navigateTo = (value) => {
return {
type: NAVIGATE_TO,
value,
};
};
export const FOLLOW_USER_SET = 'FOLLOW_USER_SET';
export const followUserSet = (value) => {
return {
type: FOLLOW_USER_SET,
value,
};
};
export const CONVERSION_LOCATION_VISIT_SHOW = 'CONVERSION_LOCATION_VISIT_SHOW';
export const conversionLocationVisitShow = builder(CONVERSION_LOCATION_VISIT_SHOW);
export const CONVERSION_LOCATION_VISIT_HIDE = 'CONVERSION_LOCATION_VISIT_HIDE';
export const conversionLocationVisitHide = builder(CONVERSION_LOCATION_VISIT_HIDE);
|
$(document).ready(function () {
$('.tabs li').on('click', function () {
var tab_id = $(this).data('for');
$('.tabs li.active').removeClass('active');
$(this).addClass('active');
$('.tab.visible').removeClass('visible');
$('#' + tab_id).addClass('visible');
});
var server;
var update_input_table = function () {
console.log('update inputs table called.', server._input_register);
var tbody = $('#input_registers_body'),
tr, td_index, td_val, td_hex, td_bin;
tbody.empty();
for (var i in server._input_register) {
tr = $('<tr></tr>');
td_index = $('<td></td>').html(i);
td_val = $('<td></td>').html(server._input_register[i]);
td_hex = $('<td></td>').html(server._input_register[i].toString(16));
td_bin = $('<td></td>').html(server._input_register[i].toString(2));
tr.append(td_index, td_val, td_hex, td_bin);
tbody.append(tr);
}
};
var update_holding_table = function () {
var tbody = $('#holding_registers_body'),
tr, td_index, td_val, td_hex, td_bin;
tbody.empty();
for (var i in server._holding_register) {
tr = $('<tr></tr>');
td_index = $('<td></td>').html(i);
td_val = $('<td></td>').html(server._holding_register[i]);
td_hex = $('<td></td>').html(server._holding_register[i].toString(16));
td_bin = $('<td></td>').html(server._holding_register[i].toString(2));
tr.append(td_index, td_val, td_hex, td_bin);
tbody.append(tr);
}
};
var start_server = function () {
var host = $('#host').val(),
port = parseInt($('#port').val());
server = new ModbusServer(host, port, 200); // with simulation delay
server.createNewRegister(12288);
server.start();
server.on('write_single_register', update_holding_table);
server.on('read_input_registers', update_input_table);
server.on('read_holding_registers', update_holding_table);
$('#start_server').html('Stop');
$('#start_server').off('click').on('click', stop_server);
};
var stop_server = function () {
if (!server) {
return;
}
server.stop();
$('#start_server').html('Start');
$('#start_server').off('click').on('click', start_server);
};
$('#start_server').on('click', start_server);
});
|
import React from 'react';
import Dropdown from 'wix-style-react/Dropdown';
import Input from 'wix-style-react/Input';
const style = {
display: 'inline-block',
padding: '0 5px',
width: '140px',
lineHeight: '22px'
};
const options = [
{id: 0, value: 'Option 1'},
{id: 1, value: 'Option 2'},
{id: 2, value: 'Option 3'},
{id: 3, value: 'Option 4'},
{id: 'footer', overrideStyle: true, value: <div style={{height: '240px', padding: '20px', backgroundColor: '#F0F'}}>Click <a href="http://www.wix.com">here</a> to go to wix.</div>}
];
const rtlOptions = [
{id: 0, value: 'אופציה 1'},
{id: 1, value: 'אופציה 2'},
{id: 2, value: 'אופציה 3'},
{id: 3, value: 'אופציה 4'}
];
export default () =>
<div>
<div>
<div className="ltr" style={style}>
<div>Left to right</div>
<Dropdown selectedId={1} options={options}/>
</div>
<div className="rtl" style={style}>
<div>Right to left</div>
<Dropdown options={rtlOptions}/>
</div>
<div className="ltr" style={style}>
<div>Drop direction up</div>
<Dropdown options={options} dropDirectionUp/>
</div>
</div>
<div>
<div className="ltr" style={style}>
<div>Small</div>
<Dropdown options={options} dropDirectionUp size="small"/>
</div>
<div className="ltr" style={style}>
<div>Default</div>
<Dropdown options={options} dropDirectionUp/>
</div>
<div className="ltr" style={style}>
<div>Large</div>
<Dropdown options={options} dropDirectionUp size="large"/>
</div>
</div>
<div>
<div className="ltr" style={style}>
<div>With prefix</div>
<Dropdown options={options} dropDirectionUp prefix={<Input.Unit>$</Input.Unit>}/>
</div>
<div className="ltr" style={style}>
<div>With suffix</div>
<Dropdown options={options} dropDirectionUp suffix={<Input.Unit>%</Input.Unit>}/>
</div>
<div className="rtl" style={style}>
<div>With suffix RTL</div>
<Dropdown options={options} dropDirectionUp suffix={<Input.Unit>%</Input.Unit>}/>
</div>
</div>
</div>;
|
requirejs.config({
'baseUrl': 'assets/vendor',
'paths': {
'app': '../js/app',
'jquery': 'jquery/dist/jquery',
'scribe': 'scribe/scribe',
'scribe-plugin-blockquote-command': 'scribe-plugin-blockquote-command/scribe-plugin-blockquote-command',
'scribe-plugin-curly-quotes': 'scribe-plugin-curly-quotes/scribe-plugin-curly-quotes',
'scribe-plugin-formatter-plain-text-convert-new-lines-to-html': 'scribe-plugin-formatter-plain-text-convert-new-lines-to-html/scribe-plugin-formatter-plain-text-convert-new-lines-to-html',
'scribe-plugin-heading-command': 'scribe-plugin-heading-command/scribe-plugin-heading-command',
'scribe-plugin-intelligent-unlink-command': 'scribe-plugin-intelligent-unlink-command/scribe-plugin-intelligent-unlink-command',
//'scribe-plugin-keyboard-shortcuts': 'scribe-plugin-keyboard-shortcuts/scribe-plugin-keyboard-shortcuts',
'scribe-plugin-link-prompt-command': 'scribe-plugin-link-prompt-command/scribe-plugin-link-prompt-command',
'scribe-plugin-sanitizer': 'scribe-plugin-sanitizer/scribe-plugin-sanitizer',
'scribe-plugin-smart-lists': 'scribe-plugin-smart-lists/scribe-plugin-smart-lists',
'scribe-plugin-toolbar': 'scribe-plugin-toolbar/scribe-plugin-toolbar',
'scribe-plugin-ghost-toolbar': '../js/scribe-plugin-ghost-toolbar/scribe-plugin-ghost-toolbar',
// not required to acutally use scribe
'beautify': 'js-beautify/js/lib/beautify',
'beautify-html': 'js-beautify/js/lib/beautify-html',
'beautify-css': 'js-beautify/js/lib/beautify-css',
'highlightjs': 'highlightjs/highlight'
},
shim: {
'highlightjs': {
exports: 'hljs'
}
}
});
// Load the main app module to start the app
requirejs(['app/ghostwriter']);
|
var gulp = require('gulp');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
let cleanCSS = require('gulp-clean-css');
gulp.task('compressJS', function () {
gulp.src([
'./bower_components/jquery/dist/jquery.js',
'./bower_components/jquery-ui/jquery-ui.js',
'./app/assets/lib/jquery.ui.touch-punch.min.js',
'./bower_components/bootstrap/dist/js/bootstrap.min.js',
'./app/assets/lib/bootstrap-material-design/js/material.min.js',
'./app/assets/lib/bootstrap-material-design/js/ripples.min.js',
'./bower_components/angular/angular.min.js',
'./bower_components/angular-ui-sortable/sortable.js',
'./bower_components/angular-route/angular-route.min.js',
'./app/assets/lib/chart-js/Chart.min.js',
'./app/assets/lib/angular-chart-js/angular-chart.min.js',
'./app/assets/lib/raphael/raphael.js',
'./app/assets/lib/morris/morris.min.js',
'./app/assets/lib/crypto.js',
'./app/assets/lib/canvas-gauge/gauge.min.js',
'./app/dashboard.js',
'./app/app.js',
'./app/widgets/**/*Service.js',
'./app/widgets/**/**/*Service.js',
'./app/widgets/**/*Controller.js',
'./app/widgets/**/**/*Controller.js',
'./app/widgets/**/*Directive.js',
'./app/widgets/**/**/*Directive.js',
'./app/widgets/**/*Filter.js',
'./app/widgets/**/**/*Filter.js'
]).pipe(concat('main.js'))
.pipe(minify({ noSource: true }))
.pipe(gulp.dest('./app/dist/'));
});
gulp.task('compressCSS', function () {
gulp.src([
'./bower_components/bootstrap/dist/css/bootstrap.min.css',
'../app/assets/lib/bootstrap-material-design/css/material.min.css',
'./app/assets/lib/bootstrap-material-design/css/material-fullpalette.min.css',
'./app/assets/lib/bootstrap-material-design/css/ripples.min.css',
'./app/assets/lib/bootstrap-material-design/css/roboto.min.css',
'./app/assets/lib/angular-chart-js/angular-chart.css',
'./app/assets/lib/morris/morris.css',
'./app/assets/lib/weather-icons-master/css/weather-icons.css',
'./app/assets/lib/css-percentage-circle/circle.css',
'./app/assets/css/dashboard.css'
]).pipe(concat('main.css'))
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(gulp.dest('./app/dist/'));
});
|
define([
'plotly'
], function (
plotly
) {
function render(node, input) {
var layout = {
title: '<b>Contig Length Distribution</b>',
fontsize: 24,
xaxis: { title: '<b>Length (bp)</b>' },
yaxis: { title: '<b>Count</b>' }
};
var data = [{
x: Object.keys(input.assembly.contig_lengths).map(function (id) { return input.assembly.contig_lengths[id]; }),
type: 'histogram',
marker: { line: { width: 1, color: 'rgb(255,255,255)' } }
}];
node.innerHTML = '';
plotly.plot(node, data, layout);
}
return {
render: render
};
});
|
(function() { globe.onDefine('window.jQuery && $("#elections-linkbar").length', function() {
require('./ResizeSensor.js');
// require('./jquery.relevant-dropdown.js');
require('./main.js');
}); }());
|
/*!
* OO UI TestTimer class.
*/
/**
* @class
*
* @constructor
*/
OO.ui.TestTimer = function TestTimer() {
this.pendingCalls = [];
this.nextId = 1;
this.timestamp = 0;
};
/* Inheritance */
OO.initClass( OO.ui.TestTimer );
/* Methods */
/**
* Return the fake timestamp
*
* @return {number} The fake timestamp
*/
OO.ui.TestTimer.prototype.now = function () {
return this.timestamp;
};
/**
* Emulated setTimeout; just pushes the call into a queue
*
* @param {Function} f The function to call
* @param {number} [timeout=0] Minimum wait time in ms
* @return {number} Timeout id for cancellation
*/
OO.ui.TestTimer.prototype.setTimeout = function ( f, timeout ) {
this.pendingCalls.push( {
id: this.nextId,
f: f,
timestamp: this.timestamp + ( timeout || 0 )
} );
return this.nextId++;
};
/**
* Emulated clearTimeout; just blanks the queued call function
*
* @param {number} id Timeout id for cancellation
*/
OO.ui.TestTimer.prototype.clearTimeout = function ( id ) {
this.pendingCalls.forEach( function ( call ) {
if ( call.id === id ) {
call.f = null;
}
} );
};
/**
* Run queued calls
*
* @param {number} [interval] Apparent passed time since last call (defaults to infinite)
*/
OO.ui.TestTimer.prototype.runPending = function ( interval ) {
var calls, i, len, call;
this.timestamp += ( interval || 0 );
calls = this.pendingCalls.splice( 0, this.pendingCalls.length ).sort( function ( a, b ) {
return a.timeout - b.timeout;
} );
for ( i = 0, len = calls.length; i < len; i++ ) {
call = calls[ i ];
if ( interval === undefined || call.timestamp <= this.timestamp ) {
if ( call.f ) {
call.f();
}
} else {
this.pendingCalls.push( call );
}
}
};
|
import React, { Component } from "react";
/**
* A general component function used for rendering sub components under a title.
* @extends Component
*/
class Body extends Component {
render() {
return (
<div className="body">
<div className="container">
<div className="content">
{this.props.title &&
<div className="title">
<span>{this.props.title}</span>
</div>
}
</div>
</div>
{this.props.children}
</div>
);
}
}
export default Body;
|
/** @ignore */
const Transformer = require('./Transformer');
/**
* The guild transformer, allows for an easier way
* to interact with guild database records.
*
* @extends {Transformer}
*/
class GuildTypeTransformer extends Transformer {
/**
* Prepares the transformers data.
*
* @override
*
* @param {Object} data The data that should be transformed.
* @param {Lodash} _ The lodash instance.
* @return {Object}
*/
prepare(data, _) {
data.limits = this.parseJson(data, 'limits');
return data;
}
/**
* The default data objects for the transformer.
*
* @override
*
* @return {Object}
*/
defaults() {
return {
name: 'Default',
limits: {
playlist: {
lists: 5,
songs: 30
},
aliases: 20
}
};
}
}
module.exports = GuildTypeTransformer;
|
version https://git-lfs.github.com/spec/v1
oid sha256:a57bfcf74507f3909fb0a9d99ceba0df97fea3b8506e680d2953b3440899cf94
size 1151
|
import React from 'react';
import BaseObject from './_baseObject';
import InlineSVG from 'svg-inline-react';
import svg from '!svg-inline-loader!../../../assets/svg/sending.svg';
import MusicStream from '../../../classes/musicStream';
class Muziek extends React.Component {
componentWillMount() {
if(!this.props.main) {
return;
}
this.musicStream = new MusicStream();
}
componentDidUpdate(){
if(!this.props.main) {
return;
}
const digibordConnected = this.props.digibordConnected;
if(digibordConnected) {
this.musicStream.pause();
this.prevConnectedState = digibordConnected;
return;
}
const stream = this.props.object.state;
if(stream === this.prevState && digibordConnected === this.prevConnectedState) {
return;
}
this.prevState = stream;
this.prevConnectedState = digibordConnected;
this.musicStream.play(stream);
}
render() {
let classes = 'icon';
if(this.props.digibordConnected) {
classes += ' on-digiboard';
}
return <div className={ classes }>
<div className="off"></div>
<div className="on">
<div className="connected"><InlineSVG src={ svg } /></div>
</div>
</div>;
}
}
export default BaseObject(Muziek, 'muziek');
|
import React from 'react';
import Helmet from 'react-helmet';
//
import * as Basic from '../../components/basic';
import { LongRunningTaskManager } from '../../redux';
import LongRunningTaskTable from './LongRunningTaskTable';
const UIKEY = 'all-long-running-task-table';
const manager = new LongRunningTaskManager();
/**
* All task table with FilterButtons
*
* @author Radek Tomiška
*/
export default class AllTasks extends Basic.AbstractContent {
getContentKey() {
return 'content.scheduler.all-tasks';
}
getNavigationKey() {
return 'scheduler-all-tasks';
}
render() {
//
return (
<Basic.Div>
<Helmet title={ this.i18n('title') } />
<LongRunningTaskTable manager={ manager } uiKey={ UIKEY }/>
</Basic.Div>
);
}
}
|
// stores and manages sprites
// interface for doing sprite queries
// nth sprite -- fast based on array index
// sprites for tag -- super fast query based on hash index
// sprites overlapping a box -- slow; has to iterate over all sprites
// sprites contained in a box -- slow; has to iterate over all sprites
// garbage collectino
// sprite iterators
// addSprite --
// registerSpriteForTag
// deleteSprite
// addToGarbageCollector
// spritesForTag
var SpriteStore = function( message_bus ) {
this.message_bus = message_bus;
this._sprites = new Set(); // HashSet of sprites we're managing
this._index = {}; // hash of HashSets keyed by tag
this.message_bus.subscribe( 'sprite_tag_added', this.handleSpriteTagAdded.bind(this) );
this.message_bus.subscribe( 'sprite_tag_removed', this.handleSpriteTagRemoved.bind(this) );
};
// returns the number of sprites in storage
SpriteStore.prototype.count = function() {
return this._sprites.size();
};
// given a Sprite object, add that sprite to storage
// if the sprite has tags, those will be indexed.
SpriteStore.prototype.addSprite = function( sprite ) {
this._sprites.add( sprite );
var tag;
for ( tag in sprite.tags ) {
this.addSpriteToTags( sprite, tag );
}
this.message_bus.publish( 'sprite_added', { store: this, sprite: sprite } );
return this;
};
SpriteStore.prototype.spritesWithTag = function( tag ) {
var sprites = this._index[tag];
if ( typeof sprites === 'undefined' ) {
return [];
}
return sprites;
}
// given a Sprite object, delete it from storage
SpriteStore.prototype.deleteSprite = function( sprite ) {
this._sprites.delete( sprite );
var tag;
for ( tag in sprite.tags ) {
this._index[tag].delete( sprite );
}
this.message_bus.publish( 'sprite_deleted', { store: this, sprite: sprite } );
return this;
};
// given a tag and a sprite, add given sprite to the tag index
SpriteStore.prototype.addSpriteToTags = function( sprite, tag ) {
if ( typeof this._index[tag] === 'undefined' ) {
this._index[tag] = new Set();
}
this._index[tag].add( sprite );
return this;
};
SpriteStore.prototype.deleteSpriteFromTags = function( sprite, tag ) {
if ( typeof this._index[tag] === 'undefined') {
return this;
}
this._index[tag].delete( sprite );
};
SpriteStore.prototype.handleSpriteTagAdded = function( type, payload ) {
var sprite = payload.sprite,
tag = payload.tag;
this.addSpriteToTags( sprite, tag );
};
SpriteStore.prototype.handleSpriteTagRemoved = function( type, payload ) {
var sprite = payload.sprite,
tag = payload.tag;
this.deleteSpriteFromTags( sprite, tag );
};
SpriteStore.prototype.removeDeadSprites = function() {
var sprite;
for ( sprite of this._sprites) {
if ( sprite.dead ) {
this.deleteSprite( sprite );
}
}
}
export default SpriteStore;
|
//= require cause/CauseViewModel
describe("p2.cause.CauseViewModel", function () {
it("should load details data from the server", function () {
spyOn($, "getJSON").andCallFake(function (url, data, callback) {
if (url != "/api/v1/cause/1/detail") {
return;
}
callback({
name: 'Name',
short_description: 'Short Description',
long_description_html: 'Long Description',
homepage_fixed: 'Homepage'
});
})
var model = new p2.cause.CauseViewModel(1);
model.load();
expect(model.name()).toBe('Name');
expect(model.short_description()).toBe('Short Description');
expect(model.long_description()).toBe('Long Description');
expect(model.homepage()).toBe('Homepage');
});
it("should load a collection of news data from the server", function () {
spyOn($, "get").andCallFake(function (url, data, callback) {
if (url != "/api/v1/cause/1/news") {
return;
}
var result = [
{ id: 1 },
{ id: 2 }
];
callback(result);
});
var model = new p2.cause.CauseViewModel(1);
model.load();
expect(model.news().size()).toBe(2);
expect(model.news().entries()[0].id).toBe(1);
expect(model.news().entries()[1].id).toBe(2);
});
it("should load all fields of news data from the server", function () {
spyOn($, "get").andCallFake(function (url, data, callback) {
if (url != "/api/v1/cause/1/news") {
return;
}
var result = [
{
id: 1,
title: "Title",
message: "Message"
}
];
callback(result);
});
var model = new p2.cause.CauseViewModel(1);
model.load();
var news = model.news().entries()[0];
expect(news.id).toBe(1);
expect(news.title()).toBe("Title");
expect(news.message()).toBe("Message");
});
it("should a collection of campaign data from the server", function () {
spyOn($, "get").andCallFake(function (url, data, callback) {
if (url != "/api/v1/cause/1/campaigns") {
return;
}
var result = [
{ id: 1 },
{ id: 2 }
];
callback(result);
});
var model = new p2.cause.CauseViewModel(1);
model.load();
expect(model.campaigns().size()).toBe(2);
expect(model.campaigns().entries()[0].id).toBe(1);
expect(model.campaigns().entries()[1].id).toBe(2);
});
it("should load all fields of a campaign from the server", function () {
spyOn($, "get").andCallFake(function (url, data, callback) {
if (url != "/api/v1/cause/1/campaigns") {
return;
}
var result = [
{
id: 1,
name: "Name",
start_date: "1/1/2013",
end_date: "31/12/2013",
url: "/campaign/1",
short_description: "Short Description"
}
];
callback(result);
});
var model = new p2.cause.CauseViewModel(1);
model.load();
var campaign = model.campaigns().entries()[0];
expect(campaign.id).toBe(1);
expect(campaign.name()).toBe("Name");
expect(campaign.start_date()).toBe("1/1/2013");
expect(campaign.end_date()).toBe("31/12/2013");
expect(campaign.path()).toBe("/campaign/1");
expect(campaign.short_description()).toBe("Short Description");
})
});
|
import Check from '../check';
export default class RegExpCheck extends Check {
constructor() {
super();
this._match = null;
}
match(value = null) {
if (value === null) {
return this._match;
}
this._match = value;
return this;
}
check(field, value, errors) {
value = String(value);
return this._match.test(value) === true ?
value : this._error(field, false, errors);
}
_error(field, reason, errors) {
errors[field] = {
regexp: reason
};
return false;
}
}
|
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
gulp.task('compile', function() {
return gulp.src('src/*.ls')
.pipe($.livescript({bare: true}))
.pipe(gulp.dest('./build'));
});
gulp.task('test-compile', ['compile'], function () {
return gulp.src('test/*.ls')
.pipe($.livescript())
.pipe($.espower())
.pipe(gulp.dest('./powered-test'));
});
gulp.task('test', ['test-compile'], function() {
return gulp.src('powered-test/*.js')
.pipe($.mocha());
});
gulp.task('default', ['test']);
|
var Connection = require('./Connection.js'),
collections = {},
Builder = function () {
var self = this;
self.collections = function (name, callback) {
if (collections[name] != undefined) {
Connection.getInstance(function (db) {
callback(db.collection(name));
});
} else {
Connection.getInstance(function (db) {
db.collections(function (err, results) {
for (var i in results) {
collections[results[i].collectionName] = results[i];
}
if (collections[name] != undefined) {
callback(db.collection(name));
} else {
db.createCollection(name, {}, function (newCollection) {
collections[name] = newCollection;
callback(db.collection(name));
});
}
});
});
}
return self;
};
return self;
};
module.exports = new Builder;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.