text
stringlengths
2
6.14k
const express = require('express'); const router = express.Router(); const routes = require('./routes')(router); module.exports = router;
var HDWalletProvider = require("truffle-hdwallet-provider"); var mnemonic = "candy maple cake sugar pudding cream honey rich smooth crumble sweet treat"; module.exports = { networks: { development: { provider: function () { return new HDWalletProvider(mnemonic, "http://127.0.0.1:7545/", 0, 50); }, network_id: "*", }, }, compilers: { solc: { version: "^0.5.2", }, }, };
var ExtractTextPlugin = require("extract-text-webpack-plugin"); var HtmlWebpackPlugin = require("html-webpack-plugin"); var path = require("path"); var webpack = require("webpack"); var projectTemplatesRoot = "../../ppb/templates/"; module.exports = { context: path.resolve(__dirname, "src"), entry: { app: "./js/main.js" }, output: { path: path.resolve(__dirname, "dist"), filename: "js/site.js?[hash]", publicPath: "/site_media/static" }, module: { loaders: [ { test: /\.(gif|png|ico|jpg|svg)$/, include: [ path.resolve(__dirname, "src/images") ], loader: "file-loader?name=/images/[name].[ext]" }, { test: /\.less$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader") }, { test: /\.(woff|woff2|ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, include: [ path.resolve(__dirname, "/src/fonts"), path.resolve(__dirname, "../node_modules") ], loader: "file-loader?name=/fonts/[name].[ext]?[hash]" }, { test: /\.jsx?$/, loader: "babel-loader", query: {compact: false} }, ] }, resolve: { extensions: ["", ".js", ".jsx"], }, plugins: [ new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new ExtractTextPlugin("css/site.css?[hash]"), new HtmlWebpackPlugin({ filename: projectTemplatesRoot + "_styles.html", templateContent: function(templateParams, compilation) { var link = ""; for (var css in templateParams.htmlWebpackPlugin.files.css) { link += "<link href='" + templateParams.htmlWebpackPlugin.files.css[css] + "' rel='stylesheet' />\n" } return link; } }), new HtmlWebpackPlugin({ filename: projectTemplatesRoot + "_scripts.html", templateContent: function(templateParams, compilation) { var script = ""; for (var js in templateParams.htmlWebpackPlugin.files.js) { script += "<script src='" + templateParams.htmlWebpackPlugin.files.js[js] + "'></script>\n" } return script; } }) ] };
var h = require('hyperscript') var human = require('human-time') exports.needs = {} exports.gives = 'message_meta' exports.create = function () { function updateTimestampEl(el) { el.firstChild.nodeValue = human(new Date(el.timestamp)) return el } setInterval(function () { var els = [].slice.call(document.querySelectorAll('.timestamp')) els.forEach(updateTimestampEl) }, 60e3) return function (msg) { return updateTimestampEl(h('a.enter.timestamp', { href: '#'+msg.key, timestamp: msg.value.timestamp, title: new Date(msg.value.timestamp) }, '')) } }
version https://git-lfs.github.com/spec/v1 oid sha256:e40a08695f05163cfb0eaeeef4588fcfad55a6576cfadfb079505495605beb33 size 27133
/** * The MIT License (MIT) * * Copyright (c) 2015 Famous Industries Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ 'use strict'; import { Geometry } from '../Geometry'; import { GeometryHelper } from '../GeometryHelper'; /** * This function generates custom buffers and passes them to * a new static geometry, which is returned to the user. * * @class Tetrahedron * @constructor * * @param {Object} options Parameters that alter the * vertex buffers of the generated geometry. * * @return {Object} constructed geometry */ class Tetrahedron extends Geometry { constructor(options) { //handled by es6 transpiler //if (!(this instanceof Tetrahedron)) return new Tetrahedron(options); var textureCoords = []; var normals = []; var detail; var i; var t = Math.sqrt(3); var vertices = [ // Back 1, -1, -1 / t, -1, -1, -1 / t, 0, 1, 0, // Right 0, 1, 0, 0, -1, t - 1 / t, 1, -1, -1 / t, // Left 0, 1, 0, -1, -1, -1 / t, 0, -1, t - 1 / t, // Bottom 0, -1, t - 1 / t, -1, -1, -1 / t, 1, -1, -1 / t ]; var indices = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]; for (i = 0; i < 4; i++) { textureCoords.push( 0.0, 0.0, 0.5, 1.0, 1.0, 0.0 ); } options = options || {}; while (--detail) GeometryHelper.subdivide(indices, vertices, textureCoords); normals = GeometryHelper.computeNormals(vertices, indices); options.buffers = [ { name: 'a_pos', data: vertices }, { name: 'a_texCoord', data: textureCoords, size: 2 }, { name: 'a_normals', data: normals }, { name: 'indices', data: indices, size: 1 } ]; super(options); } } export { Tetrahedron };
import React, { Component } from 'react' import PropTypes from 'prop-types' import { MultiSelect } from '../../src' class MultiSelectWithStringValues extends Component { constructor(props) { super(props) this.state = { value: [] } } handleChange = (event) => { const { valueKey } = this.props this.setState({ value: event.value.map((val) => val[valueKey]) }) } render() { const { value } = this.state return <MultiSelect {...this.props} onChange={this.handleChange} value={value} /> } } MultiSelectWithStringValues.propTypes = { valueKey: PropTypes.string.isRequired } export default MultiSelectWithStringValues
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
if ( !window.console ) window.console = { log:function(){} }; jQuery(document).ready(function($) { console.log('Keep being awesome.'); });
'use strict'; var emojiArr = require('./emojis'); var i = 0; var existingRules = {}; var generateEmoji = function(selector) { if (!existingRules[selector]) { existingRules[selector] = emojiArr[i]; if (i !== emojiArr.length) { i++ } else { i = 0; } } return existingRules[selector]; } module.exports = generateEmoji;
var fractal = fractal || {}; fractal.workerPaths = { "mandelbrot": "public/js/mandel.js", }; fractal.Fractal = function (canvas, workerCount) { this.canvas = canvas; this.workerCount = workerCount; this.workerDoneCount = 0; this.ctx = canvas.getContext("2d"); this.width = canvas.width; this.height = canvas.height; this.workerPath = fractal.workerPaths["mandelbrot"]; this.topLeft = new Complex(-1.5, 1.1); this.bottomRight = new Complex(0.8, -1.1); this.maxIter = 1200; var lingrad = this.ctx.createLinearGradient(0, 0, this.width, 0); lingrad.addColorStop(0, '#00f'); lingrad.addColorStop(0.1, '#fa0'); lingrad.addColorStop(0.5, '#ff0'); lingrad.addColorStop(0.7, '#f1b'); lingrad.addColorStop(1, '#fff'); this.ctx.fillStyle = lingrad; this.ctx.fillRect(0, 0, this.width, 2); this.gradientImage = this.ctx.getImageData(0, 0, this.width, 1); this.imgData = this.ctx.getImageData(0, 0, this.width, this.height); this.ondone = null; this.workers = []; }; fractal.Fractal.prototype = function () { var computeRow = function (workerIndex, row) { var args = { action: "computeRow", row: row, workerIndex: workerIndex }; this.workers[workerIndex].postMessage(args); }; var initializeWorker = function (workerIndex) { var drow = (this.bottomRight.imag - this.topLeft.imag) / this.height; var dcol = (this.bottomRight.real - this.topLeft.real) / this.width; var args = { action: "setup", maxIter: this.maxIter, width: this.width, height: this.height, topLeft: this.topLeft, bottomRight: this.bottomRight, drow: drow, dcol: dcol, workerIndex: workerIndex, juliaPoint: this.juliaPoint }; this.workers[workerIndex].postMessage(args); }; var createWorkers = function (workerPath) { var obj = this; var rowData = obj.ctx.createImageData(obj.width, 1); for (var workerIndex = 0; workerIndex < obj.workerCount; workerIndex++) { obj.workers[workerIndex] = new Worker(obj.workerPath); this.workers[workerIndex].onmessage = function (event) { if (event.data.logData) { console.log("Worker: " + event.data.logData); } if (event.data.row >= 0) { var wIndex = event.data.workerIndex; for (var index = 0; index < obj.width; index++) { var color = getColor.call(obj, event.data.iterData[index]); var destIndex = 4 * index; rowData.data[destIndex] = color.red; rowData.data[destIndex + 1] = color.green; rowData.data[destIndex + 2] = color.blue; rowData.data[destIndex + 3] = color.alpha; } obj.ctx.putImageData(rowData, 0, event.data.row); if (obj.nextRow < obj.height) { console.log("Worker: " + wIndex, " nextRow: " + obj.nextRow); computeRow.call(obj, wIndex, obj.nextRow); obj.nextRow = obj.nextRow + 1; } else { obj.workerDoneCount++; if (obj.workerDoneCount == obj.workerCount) { var duration = new Date().getTime() - obj.startTime; if (typeof obj.ondone === 'function') { obj.ondone(duration); } } } } }; } }; var getColor = function (iter) { if (iter == this.maxIter) { return { red: 0, green: 0, blue: 0, alpha: 255 }; } var index = (iter % this.gradientImage.width) * 4; return { red: this.gradientImage.data[index], green: this.gradientImage.data[index + 1], blue: this.gradientImage.data[index + 2], alpha: this.gradientImage.data[index + 3] }; }, render = function () { this.startTime = new Date().getTime(); this.workerDoneCount = 0; createWorkers.call(this, this.workerPath); this.nextRow = this.workerCount; for (var workerIndex = 0; workerIndex < this.workerCount; workerIndex++) { initializeWorker.call(this, workerIndex); computeRow.call(this, workerIndex, workerIndex); } } return { render: render }; } (); jQuery(function($) { var fra = new fractal.Fractal(document.getElementById("fractal"), 2); $('#draw-fractal').on('click',function() { fra.render(); }); });
describe('raureif', function () { it('test', function () { }); });
/** * @file ui/core/styleguide/index//html/01-body/40-main/main.js * @description Listeners on the body, iframe, and rightpull bar. */ /* istanbul ignore if */ if (typeof window === 'object') { document.addEventListener('DOMContentLoaded', () => { const $orgs = FEPPER_UI.requerio.$orgs; const { uiFns, uiProps } = FEPPER_UI; $orgs['#sg-rightpull'].on('mouseenter', function () { $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-hover'); }); $orgs['#sg-rightpull'].on('mouseleave', function () { $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); }); // Handle manually resizing the viewport. // 1. On "mousedown" store the click location. // 2. Make a hidden div visible so that the cursor doesn't get lost in the iframe. // 3. On "mousemove" calculate the math, save the results to a cookie, and update the viewport. $orgs['#sg-rightpull'].on('mousedown', function (e) { uiProps.sgRightpull.posX = e.pageX; uiProps.sgRightpull.vpWidth = uiProps.vpWidth; // Show the cover. $orgs['#sg-cover'].dispatchAction('addClass', 'shown-by-rightpull-drag'); }); // Add the mouse move event and capture data. Also update the viewport width. $orgs['#patternlab-body'].on('mousemove', function (e) { if ($orgs['#sg-cover'].getState().classArray.includes('shown-by-rightpull-drag')) { let vpWidthNew = uiProps.sgRightpull.vpWidth; if (uiProps.dockPosition === 'bottom') { vpWidthNew += 2 * (e.pageX - uiProps.sgRightpull.posX); } else { vpWidthNew += e.pageX - uiProps.sgRightpull.posX; } if (vpWidthNew > uiProps.minViewportWidth) { uiFns.sizeIframe(vpWidthNew, false); } } }); // Handle letting go of rightpull bar after dragging to resize. $orgs['#patternlab-body'].on('mouseup', function () { uiProps.sgRightpull.posX = null; uiProps.sgRightpull.vpWidth = null; $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-hover'); $orgs['#sg-cover'].dispatchAction('removeClass', 'shown-by-rightpull-drag'); }); }); }
define(function() { return { draw: function(context, t) { var x = this.getNumber("x", t, 100), y = this.getNumber("y", t, 100), size = this.getNumber("size", t, 60), h = this.getNumber("h", t, 40), colorLeft = this.getColor("colorLeft", t, "#999999"), colorRight = this.getColor("colorRight", t, "#cccccc"), colorTop = this.getColor("colorTop", t, "#eeeeee"), scaleX = this.getNumber("scaleX", t, 1), scaleY = this.getNumber("scaleY", t, 1); context.translate(x, y); context.scale(scaleX, scaleY); if(h >= 0) { context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, -1); context.lineTo(0, size / 4 - 1); context.lineTo(-size / 2, -1); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorRight; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(0, size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); } else { // clip path context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(size / 2, 0); context.lineTo(0, size / 4); context.lineTo(-size / 2, 0); context.clip(); context.fillStyle = colorRight; context.beginPath(); context.moveTo(-size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(-size / 2, -h); context.lineTo(-size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorLeft; context.beginPath(); context.moveTo(size / 2, 0); context.lineTo(0, -size / 4); context.lineTo(0, -size / 4 -h); context.lineTo(size / 2, -h); context.lineTo(size / 2, 0); this.drawFillAndStroke(context, t, true, false); context.fillStyle = colorTop; context.beginPath(); context.moveTo(-size / 2, -h); context.lineTo(0, -size / 4 - h); context.lineTo(size / 2, -h); context.lineTo(0, size / 4 - h); context.lineTo(-size / 2, -h); this.drawFillAndStroke(context, t, true, false); } } } });
'use strict'; function valuefy(value) { if (typeof value !== 'object') { return (typeof value === 'string') ? `"${value}"` : value; } let values = []; if (Array.isArray(value)) { for (const v of value) { values.push(valuefy(v)); } values = `[${values.join(',')}]`; } else { for (let v in value) { if ({}.hasOwnProperty.call(value, v)) { values.push(`"${v}":${valuefy(value[v])}`); } } values = `{${values.join(',')}}`; } return values; } function serialize(target) { if (!target || typeof target !== 'object') { throw new TypeError('Invalid type of target'); } let values = []; for (let t in target) { if ({}.hasOwnProperty.call(target, t)) { values.push(`${t}=${valuefy(target[t])}`); } } return values; } function extract(t, outter, onlyContent) { const start = onlyContent ? 1 : 0; const pad = onlyContent ? 0 : 1; return t.slice(start, t.lastIndexOf(outter) + pad); } function objectify(v) { if (v[0] === '{') { return JSON.parse(extract(v, '}')); } else if (v[0] === '[') { const set = []; const es = extract(v, ']', true); if (es[0] === '[' || es[0] === '{') { set.push(objectify(es)); } else { for (const e of es.split(',')) { set.push(objectify(e)); } } return set; } else if (v[0] === '"') { v = extract(v, '"', true); } return v; } function deserialize(values) { if (!values) { throw new TypeError('Invalid type of values'); } else if (!Array.isArray(values)) { values = [values]; } const target = {}; for (const v of values) { const fieldValue = v.split('=', 2); target[fieldValue[0]] = objectify(fieldValue[1]); } return target; } module.exports = { pairify: serialize, parse: deserialize };
export default class TasksService { static async fetchTasks() { const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); await delay(1000); return [ { id: 0, description: "task1", status: "Active" }, { id: 1, description: "task2", status: "Active" }, ]; } }
/** * Vasya Hobot * * Copyright (c) 2013-2014 Vyacheslav Slinko * Licensed under the MIT License */ function Message(chat, body) { this._chat = chat; this._body = body; } Message.prototype.getChat = function() { return this._chat; }; Message.prototype.getBody = function() { return this._body; }; module.exports = Message;
import React from 'react'; import { shallow } from 'enzyme'; import UserProfile from '../UserProfile'; import Wrapper from '../Wrapper'; describe('<UserProfile />', () => { it('should render <Wrapper />', () => { const wrapper = shallow(<UserProfile />); expect(wrapper.find(Wrapper).length).toEqual(1); }); });
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; import LookCell from './LookCell.js'; import User from './User.js'; import DoneFooter from './DoneFooter.js'; import Icon from 'react-native-vector-icons/Ionicons'; const LookDetail = React.createClass({ getInitialState() { return { dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}), comments: [], next:true, pageNo:1, animating:true }; }, getDefaultProps() { return { look:{}, navigator:"", }; }, componentWillMount() { this.queryRromServer(1); }, getDataSource(comments) { // return false; return this.state.dataSource.cloneWithRows(comments); }, renderFooter() { if (!this.state.next) { return ( <DoneFooter/> ); } return <ActivityIndicator style={styles.scrollSpinner} animating={this.state.animating}/>; }, renderHeader() { return ( <LookCell look={this.props.look} navigator={this.props.navigator} onSelect={function(){}} userCell={true} /> ); }, onEndReached() { if(this.props.look.comments_count==0){ this.setState({ next:false, }); return; } if (this.state.next && !this.state.animating) { this.setState({ animating: true }); this.queryRromServer(this.state.pageNo); } }, onSelectUser(user) { this.props.navigator.push({ component: User, title: user.name, backButtonTitle:' ', passProps: { user:user, navigator:this.props.navigator, }, }); }, // shouldComponentUpdate: function(nextProps, nextState) { // console.log('LookDetail.js.js-shouldComponentUpdate'); // return JSON.stringify(nextState)!=JSON.stringify(this.state); // }, renderRow(comments) { if(!comments.comment||!comments.comment.user){ return false; } return ( <TouchableOpacity activeOpacity={0.8} onPress={()=>this.onSelectUser(comments.comment.user)} style={styles.flexContainer}> <Image source={{uri:comments.comment.user.photo}} style={styles.avatar}/> <View style={styles.commentBody}> <View style={styles.commentHeader}> <View style={{flex:1}}> <Text style={styles.userName}>{comments.comment.user.name}</Text> </View> <View style={styles.timeView}> <Icon name="ios-clock-outline" color={globalVariables.textBase} size={15}/> <Text style={styles.time}> {globalVariables.formatDateToString(comments.comment.created_at)}</Text> </View> </View> <Text style={styles.commentText}>{comments.comment.body}</Text> </View> </TouchableOpacity> ); }, render() { console.log(new Date()-0); console.log('LookDetail.js.js-render'); return ( <ListView dataSource={this.state.dataSource} renderRow={this.renderRow} onEndReached={this.onEndReached} renderHeader={this.renderHeader} renderFooter={this.renderFooter} onEndReachedThreshold={10} automaticallyAdjustContentInsets={false} keyboardDismissMode='on-drag' keyboardShouldPersistTaps={false} showsVerticalScrollIndicator={true} style={styles.container} /> ); }, queryRromServer(page) { globalVariables.queryRromServer(globalVariables.apiLookServer+this.props.look.id+'/comments/'+(page||1),this.processsResults); }, processsResults(data) { if (!data||!data.comments||!data.comments.length) { this.setState({ animating: false, next:false, }); return; } var newComments= this.state.comments.concat(data.comments); var next=newComments.length>=this.props.look.comments_count?false:true; this.setState({ comments: newComments, animating: false, dataSource: this.getDataSource(newComments), pageNo: this.state.pageNo+1, next:next, }); } }); const styles = StyleSheet.create({ container: { paddingTop: 64, backgroundColor: globalVariables.background, }, flexContainer: { opacity:0.97, padding: 10, flexDirection: 'row', justifyContent: 'flex-start', }, commentBody: { flex: 1, flexDirection: "column", justifyContent: "center", }, commentHeader: { flexDirection: "row", alignItems: "flex-start" }, userName: { color:globalVariables.base, // fontSize:12, }, timeView:{ // width:50, flexDirection: "row", alignItems:'center', marginRight:5, }, time:{ color:globalVariables.textBase, fontSize:12, // , }, commentText: { // fontSize:12, marginTop:8, flexDirection: "row", color:globalVariables.textBase, }, avatar: { borderRadius: 18, width: 36, height: 36, marginRight: 10, marginLeft: 5, backgroundColor:globalVariables.textBase2, }, scrollSpinner: { marginVertical: 20, }, }); export default LookDetail;
var cv = require('../lib/opencv'); var COLOR = [0, 255, 0]; // default red var thickness = 2; // default 1 cv.readImage('./files/mona.png', function(err, im) { if (err) throw err; if (im.width() < 1 || im.height() < 1) throw new Error('Image has no size'); im.detectObject('../data/haarcascade_frontalface_alt2.xml', {}, function(err, faces) { if (err) throw err; for (var i = 0; i < faces.length; i++) { var face = faces[i]; im.rectangle([face.x, face.y], [face.width, face.height], COLOR, 2); } im.save('./tmp/face-detection-rectangle.png'); console.log('Image saved to ./tmp/face-detection-rectangle.png'); }); });
// ======================================================================== // SproutCore -- JavaScript Application Framework // Copyright ©2006-2011, Strobe Inc. and contributors. // Portions copyright ©2008 Apple Inc. All rights reserved. // ======================================================================== sc_require('controllers/object'); sc_require('mixins/selection_support'); sc_require('private/tree_item_observer'); /** @class A TreeController manages a tree of model objects that you might want to display in the UI using a collection view. For the most part, you should work with a TreeController much like you would an ObjectController, except that the TreeController will also provide an arrangedObjects property that can be used as the content of a CollectionView. TODO: Document More @extends SC.ObjectController @extends SC.SelectionSupport @since SproutCore 1.0 */ SC.TreeController = SC.ObjectController.extend(SC.SelectionSupport, /** @scope SC.TreeController.prototype */ { // .......................................................... // PROPERTIES // /** Set to YES if you want the top-level items in the tree to be displayed as group items in the collection view. @property {Boolean} */ treeItemIsGrouped: NO, /** If your content support expanding and collapsing of content, then set this property to the name of the key on your model that should be used to determine the expansion state of the item. The default is "treeItemIsExpanded" @property {String} */ treeItemIsExpandedKey: "treeItemIsExpanded", /** Set to the name of the property on your content object that holds the children array for each tree node. The default is "treeItemChildren". @property {String} */ treeItemChildrenKey: "treeItemChildren", /** Returns an SC.Array object that actually will represent the tree as a flat array suitable for use by a CollectionView. Other than binding this property as the content of a CollectionView, you generally should not use this property directly. Instead, work on the tree content using the TreeController like you would any other ObjectController. @property {SC.Array} */ arrangedObjects: function() { var ret, content = this.get('content'); if (content) { ret = SC.TreeItemObserver.create({ item: content, delegate: this }); } else ret = null; // empty! this._sctc_arrangedObjects = ret ; return ret ; }.property().cacheable(), // .......................................................... // PRIVATE // /** @private Manually invalidate the arrangedObjects cache so that we can teardown any existing value. We do it via an observer so that this will fire immediately instead of waiting on some other component to get arrangedObjects again. */ _sctc_invalidateArrangedObjects: function() { this.propertyWillChange('arrangedObjects'); var ret = this._sctc_arrangedObjects; if (ret) ret.destroy(); this._sctc_arrangedObjects = null; this.propertyDidChange('arrangedObjects'); }.observes('content', 'treeItemIsExpandedKey', 'treeItemChildrenKey', 'treeItemIsGrouped'), _sctc_arrangedObjectsContentDidChange: function() { this.updateSelectionAfterContentChange(); }.observes('*arrangedObjects.[]'), /** @private Returns the first item in arrangeObjects that is not a group. This uses a brute force approach right now; we assume you probably don't have a lot of groups up front. */ firstSelectableObject: function() { var objects = this.get('arrangedObjects'), indexes, len, idx = 0; if (!objects) return null; // fast track indexes = objects.contentGroupIndexes(null, objects); len = objects.get('length'); while(indexes.contains(idx) && (idx<len)) idx++; return idx>=len ? null : objects.objectAt(idx); }.property() });
import React, {Component} from 'react'; import PdfJS from './pdfJS'; import Contract from "../../contract"; import Event from '../../event'; import AnnotationLoader from '../../annotator/loader'; class Viewer extends Component { constructor(props) { super(props); this.state = ({ page_no: 0, pdf_url: "", scale: 0, loading: true }); } componentDidMount() { this.subscribe_zoom = Event.subscribe('zoom:change', (scale) => { this.setState({scale: scale}); }); this.updateState(this.props); } updateState(props) { var {page_no, pdf_url} = props.page; var scale = Contract.getPdfScale(); this.setState({ page_no, pdf_url, scale, loading: false }); } componentWillUnmount() { this.subscribe_zoom.remove(); } getPageID() { return 'pdf-' + this.state.page_no; } getAnnotations() { let page = []; let annotations = Contract.getAnnotations(); annotations.result.forEach(annotation=> { if (typeof annotation.shapes == 'object' && this.state.page_no == annotation.page_no) { page.push(annotation); } }); return page; } onPageRendered() { if (!this.annotator) { this.annotator = new AnnotationLoader('.pdf-annotator'); this.annotator.init(); Contract.setAnnotatorInstance(this.annotator); } const annotations = this.getAnnotations(); if (annotations.length > 0) { this.annotator.content.annotator("loadAnnotations", annotations); } Event.publish('annotation:loaded', 'pdf'); } componentWillReceiveProps(props) { this.updateState(props); } shouldComponentUpdate(nextProps, nextState) { return (nextProps.page.page_no !== this.state.page_no || this.state.scale !== nextState.scale); } render() { if (this.state.loading) { return ( <div className="pdf-viewer pdf-annotator"> <div className="pdf-wrapper"> Loading... </div> </div>); } return ( <div className="pdf-viewer pdf-annotator"> <div id={this.getPageID()} className="pdf-wrapper"> <PdfJS onPageRendered={this.onPageRendered.bind(this)} file={this.state.pdf_url} page={this.state.page_no} scale={this.state.scale}/> </div> <a href="#" className="change-view-icon exit-fullscreen"></a> </div> ); } } export default Viewer;
var ratio = require('ratio') function error(actual, expected) { return Math.abs(actual - expected) / expected } function approx(target, max) { max = (max || 10) // find a good approximation var best = 1, j, e, result for (var i = 1; i < max; i++) { j = Math.round(i * target) e = error(j / i, target) if (e >= best) continue best = e result = ratio(j, i) } return result } module.exports = approx
/** * Write the input to the paramsified file * * --- * INPUTS: * * - FILES * Write the list of files to the paramsified file (line feed after each filename). * * - STRINGS * Write the strings (concatenated) to the paramsified file. * * - STRING * Write the string to the paramsified file. * * - UNDEFINED * Touch the file. * * OUTPUT: * * - FILES * The filename that was written. * --- * * @module tasks * @submodule write */ var State = require('../state'), path = require('path'), mkdirp = require('mkdirp').mkdirp, fs = require('fs'); /** * Write out the input to the destination filename. * * This can only apply to single string inputs. * * @method writeTask * @param options {Object} Write task options * @param options.name {String} Filename to write to. * @param options.encoding {String} [default='utf8'] Encoding to use when writing the file * @param options.mkdir {Boolean} [default=true] Make destination directory if it does not exist * @param options.dirmode {String} [default='0755'] Create new directories with this mode (chmod) * @param status {EventEmitter} Status object, handles 'complete' and 'failed' task exit statuses. * @param logger {winston.Logger} Logger instance, if additional logging required (other than task exit status) * @return {undefined} * @public */ function writeTask(options, status, logger) { var self = this, pathname = path.resolve(path.dirname(options.name)), name = options.name, encoding = options && options.encoding || 'utf8', mkdir = options && options.mkdir || true, dirmode = options && options.dirmode || '0755'; // Write the content to the specified file. function writeFile(filename, data) { fs.writeFile(filename, data, encoding, function(err) { if (err) { status.emit('failed', 'write', 'error writing destination file: ' + err); } else { self._state.set(State.TYPES.FILES, [ filename ]); status.emit('complete', 'write', 'wrote ' + filename); } }); } // Create the paramsified path if it does not exist. function mkdirIfNotExist(filename, callback) { path.exists(filename, function(exists) { if (!exists) { if (mkdir === true) { mkdirp(filename, dirmode, function(err) { if (err) { callback(err); } else { callback(null); } }); } else { callback('tried to write a file to a non-existing directory and mkdir is false'); } } else { callback(null); } }); } switch (this._state.get().type) { case State.TYPES.FILES: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("\n")); } }); break; case State.TYPES.STRING: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value); } }); break; case State.TYPES.STRINGS: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, self._state.get().value.join("")); } }); break; case State.TYPES.UNDEFINED: mkdirIfNotExist(pathname, function(err) { if (err) { status.emit('failed', 'write', 'error creating destination directory: ' + err); } else { writeFile(name, ""); } }); break; default: status.emit('failed', 'write', 'unrecognised input type: ' + this._type); break; } } exports.tasks = { 'write' : { callback: writeTask } };
(function () { "use strict"; /** * This module have an ability to contain constants. * No one can reinitialize any of already initialized constants */ var module = (function () { var constants = {}, hasOwnProperty = Object.prototype.hasOwnProperty, prefix = (Math.random() + "_").slice(2), isAllowed; /** * This private method checks if value is acceptable * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} * @private */ isAllowed = function (value) { switch (typeof value) { case "number": return true; case "string": return true; case "boolean": return true; default: return false; } }; return { /** * Constant getter * @param name {String} - the name of the constant * @returns {String|Number|Boolean|null} */ getConstant: function (name) { if (this.isDefined(name) === true) { return constants[prefix + name]; } return undefined; }, /** * Setter * @param name {String} - the name of the constant * @param value {String|Number|Boolean} - the value of the constant * @returns {boolean} */ setConstant: function (name, value) { if (isAllowed(value) !== true) { return false; } if (this.isDefined(name) === true) { return false; } constants[prefix + name] = value; return true; }, /** * This method checks if constant is already defined * @param name {String} - the name of the constant * @returns {boolean} */ isDefined: function (name) { return hasOwnProperty.call(constants, prefix + name); } }; })(); /**Testing*/ module.setConstant("test", 123); print("test == " + module.getConstant("test")); print("idDefined(\"test\") == " + module.isDefined("test")); print("test2 == " + module.getConstant("test2")); print("idDefined(\"test2\") == " + module.isDefined("test2")); print(""); module.setConstant("test", 321); print("test == " + module.getConstant("test")); print(""); module.setConstant("test3", {a: 123}); print("test3 == " + module.getConstant("test3")); })();
module.exports = { parserOptions: { sourceType: 'script', }, };
window.ImageViewer = function(url, alt, title){ var img = $('<img />').attr('src', url).attr('alt', title).css({ display: 'inline-block', 'max-width': '90vw', 'max-height': '90vh' }); var a = $('<a></a>').attr('target', '_blank') .attr('title', title) .attr('href', url) .css({ display: 'inline-block', height: '100%' }) .append(img); var close_it = function(){ overlay.remove(); container.remove(); }; var closeBtn = $('<a class="icon-remove-sign"></a>').css({ color: 'red', 'font-size': 'x-large', 'margin-left': '-0.1em' }).bind('click', close_it); var closeWrapper = $('<div></div>').css({ height: '100%', width: '2em', 'text-align': 'left', 'display': 'inline-block', 'vertical-algin': 'top', 'margin-top': '-0.6em', 'float': 'right' }).append(closeBtn); var container = $('<div></div>').append( $('<div></div>').css({ margin: '5vh 1vw', display: 'inline-block', 'vertical-align': 'top' }).append(a).append(closeWrapper)) .css({ 'z-index': 30000000, 'position': 'fixed', 'padding': 0, 'margin': 0, 'width': '100vw', 'height': '100vh', 'top': 0, 'left': 0, 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle' }) .bind('click',close_it) .appendTo('body'); var overlay = $('<div class="blockUI blockMsg blockPage">').css({ 'z-index': 9999, 'position': 'fixed', padding: 0, margin: 0, width: '100vw', height: '100vh', top: '0vh', left: '0vw', 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle', 'background-color': 'gray', 'opacity': '0.4' }).bind('click', close_it).appendTo('body'); this.close = close_it; return this; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { } }; app.initialize();
/** * Error for services to through when they encounter a problem with the request. * Distinguishes between a bad service request and a general error */ function ServiceError(message) { this.name = "ServiceError"; this.message = (message || ""); } ServiceError.prototype = Object.create(Error.prototype, { constructor: {value: ServiceError} }); /** * Error for when an item is not found */ function NotFoundError(message) { this.name = "NotFoundError"; this.message = (message || "Not found"); } NotFoundError.prototype = Object.create(ServiceError.prototype, { constructor: { value: NotFoundError} }); exports.ServiceError = ServiceError; exports.NotFoundError = NotFoundError;
import shaven from 'shaven' const svgNS = 'http://www.w3.org/2000/svg' export default function (svg, config) { const yDensity = 0.1 const yRange = config.max.value - config.min.value const graphHeight = config.height * 0.8 const graphWidth = config.width * 0.95 const coSysHeight = config.height * 0.6 const coSysWidth = config.width * 0.85 const barchart = shaven( ['g', { transform: 'translate(' + [graphWidth * 0.1, graphHeight].join() + ')', }], svgNS, )[0] const coordinateSystem = shaven(['g'], svgNS)[0] const bars = shaven(['g'], svgNS)[0] function buildCoordinateSystem () { function ordinates () { let cssClass let index for (index = 0; index < config.size; index++) { cssClass = index === 0 ? 'vectual_coordinate_axis_y' : 'vectual_coordinate_lines_y' shaven( [coordinateSystem, ['line', { class: cssClass, x1: (coSysWidth / config.size) * index, y1: '5', x2: (coSysWidth / config.size) * index, y2: -coSysHeight, }], ['text', config.keys[index], { class: 'vectual_coordinate_labels_x', transform: 'rotate(40 ' + ((coSysWidth / config.size) * index) + ', 10)', // eslint-disable-next-line id-length x: (coSysWidth / config.size) * index, y: 10, // eslint-disable-line id-length }], ], svgNS, ) } } function abscissas () { let styleClass let index for (index = 0; index <= (yRange * yDensity); index++) { styleClass = index === 0 ? 'vectual_coordinate_axis_x' : 'vectual_coordinate_lines_x' shaven( [coordinateSystem, ['line', { class: styleClass, x1: -5, y1: -(coSysHeight / yRange) * (index / yDensity), x2: coSysWidth, y2: -(coSysHeight / yRange) * (index / yDensity), }], ['text', String(index / yDensity + config.min.value), { class: 'vectual_coordinate_labels_y', x: -coSysWidth * 0.05, // eslint-disable-line id-length // eslint-disable-next-line id-length y: -(coSysHeight / yRange) * (index / yDensity), }], ], svgNS, ) } } abscissas() ordinates() } function buildBars () { function drawBar (element, index) { const height = config.animations ? 0 : (config.values[index] - config.min.value) * (coSysHeight / yRange) const bar = shaven( ['rect', { class: 'vectual_bar_bar', // eslint-disable-next-line id-length x: index * (coSysWidth / config.size), // eslint-disable-next-line id-length y: -(config.values[index] - config.min.value) * (coSysHeight / yRange), height: height, width: 0.7 * (coSysWidth / config.size), }, ['title', config.keys[index] + ': ' + config.values[index]], ], svgNS, )[0] function localSetAnimations () { shaven( [bar, ['animate', { attributeName: 'height', to: (config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'y', from: 0, to: -(config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'fill', to: 'rgb(100,210,255)', begin: 'mouseover', dur: '100ms', fill: 'freeze', additive: 'replace', }], ['animate', { attributeName: 'fill', to: 'rgb(0,150,250)', begin: 'mouseout', dur: '200ms', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function localInject () { shaven([bars, [bar]]) } if (config.animations) localSetAnimations() localInject() } config.data.forEach(drawBar) } function setAnimations () { shaven( [bars, ['animate', { attributeName: 'opacity', from: 0, to: 0.8, begin: '0s', dur: '1s', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function inject () { shaven( [svg, [barchart, [coordinateSystem], [bars], ], ], ) } buildCoordinateSystem() buildBars() if (config.animations) setAnimations() inject() return svg }
import Ember from "ember"; export default Ember.Route.extend({ model: function() { return this.store.query('answer', {correct: true}); } });
//This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { 'use strict'; return "/**\n\ * Converts an RGB color to HSB (hue, saturation, brightness)\n\ * HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n\ *\n\ * @name czm_RGBToHSB\n\ * @glslFunction\n\ * \n\ * @param {vec3} rgb The color in RGB.\n\ *\n\ * @returns {vec3} The color in HSB.\n\ *\n\ * @example\n\ * vec3 hsb = czm_RGBToHSB(rgb);\n\ * hsb.z *= 0.1;\n\ * rgb = czm_HSBToRGB(hsb);\n\ */\n\ \n\ const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\ \n\ vec3 czm_RGBToHSB(vec3 rgb)\n\ {\n\ vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\ vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\ \n\ float d = q.x - min(q.w, q.y);\n\ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\ }\n\ "; });
import modelExtend from 'dva-model-extend' import { create, remove, update } from '../services/user' import * as usersService from '../services/users' import { pageModel } from './common' import { config } from 'utils' const { query } = usersService const { prefix } = config export default modelExtend(pageModel, { namespace: 'user', state: { currentItem: {}, modalVisible: false, modalType: 'create', selectedRowKeys: [], isMotion: localStorage.getItem(`${prefix}userIsMotion`) === 'true', }, subscriptions: { setup ({ dispatch, history }) { history.listen(location => { if (location.pathname === '/user') { dispatch({ type: 'query', payload: location.query, }) } }) }, }, effects: { *query ({ payload = {} }, { call, put }) { const data = yield call(query, payload) if (data) { yield put({ type: 'querySuccess', payload: { list: data.data, pagination: { current: Number(payload.page) || 1, pageSize: Number(payload.pageSize) || 10, total: data.total, }, }, }) } }, *'delete' ({ payload }, { call, put, select }) { const data = yield call(remove, { id: payload }) const { selectedRowKeys } = yield select(_ => _.user) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } }) yield put({ type: 'query' }) } else { throw data } }, *'multiDelete' ({ payload }, { call, put }) { const data = yield call(usersService.remove, payload) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: [] } }) yield put({ type: 'query' }) } else { throw data } }, *create ({ payload }, { call, put }) { const data = yield call(create, payload) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, *update ({ payload }, { select, call, put }) { const id = yield select(({ user }) => user.currentItem.id) const newUser = { ...payload, id } const data = yield call(update, newUser) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, }, reducers: { showModal (state, { payload }) { return { ...state, ...payload, modalVisible: true } }, hideModal (state) { return { ...state, modalVisible: false } }, switchIsMotion (state) { localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion) return { ...state, isMotion: !state.isMotion } }, }, })
var blueMarker = L.AwesomeMarkers.icon({ icon: 'record', prefix: 'glyphicon', markerColor: 'blue' }); var airportMarker = L.AwesomeMarkers.icon({ icon: 'plane', prefix: 'fa', markerColor: 'cadetblue' }); var cityMarker = L.AwesomeMarkers.icon({ icon: 'home', markerColor: 'red' }); var stationMarker = L.AwesomeMarkers.icon({ icon: 'train', prefix: 'fa', markerColor: 'cadetblue' });
'use strict'; var app = angular.module('Fablab'); app.controller('GlobalPurchaseEditController', function ($scope, $location, $filter, $window, PurchaseService, NotificationService, StaticDataService, SupplyService) { $scope.selected = {purchase: undefined}; $scope.currency = App.CONFIG.CURRENCY; $scope.loadPurchase = function (id) { PurchaseService.get(id, function (data) { $scope.purchase = data; }); }; $scope.save = function () { var purchaseCurrent = angular.copy($scope.purchase); updateStock(); PurchaseService.save(purchaseCurrent, function (data) { $scope.purchase = data; NotificationService.notify("success", "purchase.notification.saved"); $location.path("purchases"); }); }; var updateStock = function () { var stockInit = $scope.purchase.supply.quantityStock; $scope.purchase.supply.quantityStock = parseFloat(stockInit) - parseFloat($scope.purchase.quantity); var supplyCurrent = angular.copy($scope.purchase.supply); SupplyService.save(supplyCurrent, function (data) { $scope.purchase.supply = data; }); }; $scope.maxMoney = function () { return parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice); }; $scope.updatePrice = function () { var interTotal = parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice); if ($scope.purchase.discount === undefined || !$scope.purchase.discount) { //0.05 cts ceil var val = $window.Math.ceil(interTotal * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); ; } else { if ($scope.purchase.discountPercent) { var discountInter = parseFloat(interTotal) * (parseFloat($scope.purchase.discount) / parseFloat(100)); var total = parseFloat(interTotal) - parseFloat(discountInter); //0.05 cts ceil var val = $window.Math.ceil(total * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); } else { var total = parseFloat(interTotal) - parseFloat($scope.purchase.discount); //0.05 cts ceil var val = $window.Math.ceil(total * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); } } }; $scope.firstPercent = App.CONFIG.FIRST_PERCENT.toUpperCase() === "PERCENT"; $scope.optionsPercent = [{ name: "%", value: true }, { name: App.CONFIG.CURRENCY, value: false }]; $scope.today = function () { $scope.dt = new Date(); }; $scope.today(); $scope.clear = function () { $scope.dt = null; }; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[2]; var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); var afterTomorrow = new Date(); afterTomorrow.setDate(tomorrow.getDate() + 2); $scope.events = [ { date: tomorrow, status: 'full' }, { date: afterTomorrow, status: 'partially' } ]; $scope.getDayClass = function (date, mode) { if (mode === 'day') { var dayToCheck = new Date(date).setHours(0, 0, 0, 0); for (var i = 0; i < $scope.events.length; i++) { var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0); if (dayToCheck === currentDay) { return $scope.events[i].status; } } } return ''; }; StaticDataService.loadSupplyStock(function (data) { $scope.supplyStock = data; }); StaticDataService.loadCashiers(function (data) { $scope.cashierList = data; }); } ); app.controller('PurchaseNewController', function ($scope, $controller, $rootScope) { $controller('GlobalPurchaseEditController', {$scope: $scope}); $scope.newPurchase = true; $scope.paidDirectly = false; $scope.purchase = { purchaseDate: new Date(), user: $rootScope.connectedUser.user }; } ); app.controller('PurchaseEditController', function ($scope, $routeParams, $controller) { $controller('GlobalPurchaseEditController', {$scope: $scope}); $scope.newPurchase = false; $scope.loadPurchase($routeParams.id); } );
import Form from 'cerebral-module-forms/Form' import submitForm from './chains/submitForm' import resetForm from './chains/resetForm' import validateForm from './chains/validateForm' export default (options = {}) => { return (module, controller) => { module.addState(Form({ name: { value: '', isRequired: true }, email: { value: '', validations: ['isEmail'], errorMessages: ['Not valid email'], isRequired: true }, password: { value: '', validations: ['equalsField:repeatPassword'], dependsOn: 'simple.repeatPassword', errorMessages: ['Not equal to repeated password'], isRequired: true }, repeatPassword: { value: '', validations: ['equalsField:password'], dependsOn: 'simple.password', errorMessages: ['Not equal to password'], isRequired: true }, address: Form({ street: { value: '' }, postalCode: { value: '', validations: ['isLength:4', 'isNumeric'], errorMessages: ['Has to be length 4', 'Can only contain numbers'] } }) })) module.addSignals({ formSubmitted: submitForm, resetClicked: resetForm, validateFormClicked: validateForm }) } }
"use strict"; define("ace/snippets/scala", ["require", "exports", "module"], function (require, exports, module) { "use strict"; exports.snippetText = undefined; exports.scope = "scala"; });
'use strict'; module.exports = { set: function (v) { this.setProperty('src', v); }, get: function () { return this.getPropertyValue('src'); }, enumerable: true };
'use strict'; exports.connect = function () { var mongoose = require('mongoose'), config = require('../config'), options = { user : config.mongo.user, pass : config.mongo.pass }; mongoose.connect(config.db, options); return mongoose.connection; };
//APP var app = angular.module('PortfolioApp', ['ngRoute', 'slick']); //ROUTING app.config(function ($routeProvider) { "ngInject"; $routeProvider .when('/', { controller: "HomeController", templateUrl: "js/angular/views/home-view.html" }) .when('/work/:projectId', { controller: 'ProjectController', templateUrl: 'js/angular/views/project-view.html' }) .otherwise({ redirectTo: '/' }); }); //CONTROLLERS app.controller('HomeController', ['$scope', 'projects', function($scope, projects) { "ngInject"; projects.success(function(data) { $scope.projects = data; }); //init function for binding function bindListeners() { $("header").on("click", ".mobile-toggle", function() { $(this).toggleClass("active"); }) $("header, .about").on("click", ".nav-link", function(e) { e.preventDefault(); e.stopImmediatePropagation(); if($(window).width() <= 740) $(".mobile-toggle").removeClass("active"); var anchor = $(this).attr("href"); $('html, body').animate({ scrollTop: $(anchor).offset().top - 70 }, 500); }) } //Home page initializations angular.element(document).ready(function () { bindListeners(); }); }]); app.controller('ProjectController', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http, $sce) { "ngInject"; $scope.video = false; $http.get('projects/' + $routeParams.projectId + '.json').success(function(data) { $scope.detail = data; }) .error(function(data) { console.log("Failed to get data") }); } ]); //SERVICES app.factory('projects', ['$http', function($http) { "ngInject"; return $http.get('projects/project-list.json') .success(function(data) { return data; }) .error(function(data) { return data; console.log("Failed to get data") }); }]); //FILTERS app.filter('safe', function($sce) { "ngInject"; return function(val) { return $sce.trustAsHtml(val); }; });
import { moduleForModel, test } from 'ember-qunit'; import Pretender from 'pretender'; // ToDo: Install ember-cli-faker import mocks from './mocks'; const { inventoryMock, productMock, componentsMock } = mocks; let mockServer; moduleForModel('inventory', 'Unit | Serializer | inventory', { needs: ['serializer:application', 'model:product', 'model:inventory', 'model:component'], beforeEach() { mockServer = new Pretender(function() { this.get('/products', function() { const response = { records: [productMock] }; return [200, { "Content-Type": "application/json" }, JSON.stringify(response)]; }); this.get(`/products/${productMock.id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(productMock)]; }); this.get('/inventories', function() { const response = { records: [inventoryMock] }; return [200, { "Content-Type": "application/json" }, JSON.stringify(response)]; }); this.get(`/components/${componentsMock[0].id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[0])]; }); this.get(`/components/${componentsMock[1].id}`, function() { return [200, { "Content-Type": "application/json" }, JSON.stringify(componentsMock[1])]; }); }); }, afterEach() { mockServer.shutdown(); } }); test('it serializes records', function(assert) { return this.store().findAll('inventory').then((inventories) => { assert.equal(inventories.get('length'), 1); const inventory = inventories.objectAt(0); assert.ok(inventory.get('created')); assert.equal(inventory.get('qty'), inventoryMock.fields['qty']); assert.equal(inventory.get('restock-at'), inventoryMock.fields['restock-at']); }); }); test('it serializes belongsTo relationship', function(assert) { return this.store().findAll('inventory').then((inventories) => { const inventory = inventories.objectAt(0); inventory.get('product').then((product) => { assert.equal(product.get('name'), productMock.fields.name); assert.equal(product.get('description'), productMock.fields.description); }); }); }); test('it serializes hasMany relationship', function(assert) { return this.store().findAll('product').then((products) => { const product = products.objectAt(0); product.get('components').then((components) => { components.forEach((component, index) => { assert.equal(component.get('name'), componentsMock[index].fields.name); }); }); }); });
+(function () { 'use strict'; angular .module('DashboardApplication') .controller('FileManagerRemoveFolderController', ['$scope', '$q', 'Event', 'FoldersRest', FileManagerRemoveFolderController]); function FileManagerRemoveFolderController($scope, $q, Event, FoldersRest) { var vm = this; var folderId = $scope.ngDialogData.folderId; vm.removeFolder = removeFolder; function removeFolder() { var id = folderId; var $defer = $q.defer(); FoldersRest.one(id).remove().then(function () { console.log("FoldersRest"); debugger; Event.publish('FOLDERS_TREEVIEW_UPDATED'); alert('فولدر با موفقیت حذف شد', 'انجام شد!'); $defer.resolve(); }, function (error) { $defer.reject(error); }); return $defer.promise; } } })();
/** * @module {Module} utils/math * @parent utils * * The module's description is the first paragraph. * * The body of the module's documentation. */ import _ from 'lodash'; /** * @function * * This function's description is the first * paragraph. * * This starts the body. This text comes after the signature. * * @param {Number} first This param's description. * @param {Number} second This param's description. * @return {Number} This return value's description. */ export function sum(first, second){ ... }; /** * @property {{}} * * This function's description is the first * paragraph. * * @option {Number} pi The description of pi. * * @option {Number} e The description of e. */ export var constants = { pi: 3.14159265359, e: 2.71828 };
// *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-guide // *********************************************************** // This function is called when a project is opened or re-opened (e.g. due to // the project's config changing) module.exports = (on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config if (process.env.CYPRESS_CONNECTION_TYPE) { on(`before:browser:launch`, (browser = {}, args) => { if ( browser.name === `chrome` && process.env.CYPRESS_CONNECTION_TYPE === `slow` ) { args.push(`--force-effective-connection-type=2G`) } return args }) } }
var box, mbox; function demo() { cam ( 0, 20, 40 ); world = new OIMO.World(); world.add({ size:[50, 10, 50], pos:[0,-5,0] }); // ground var options = { type:'box', size:[10, 10, 10], pos:[0,20,0], density:1, move:true } box = world.add( options ); mbox = view.add( options ); // three mesh }; function update () { world.step(); mbox.position.copy( box.getPosition() ); mbox.quaternion.copy( box.getQuaternion() ); }
var fs = require('fs'), cons = require('consolidate'), dust = require('dustjs-linkedin'); var pages = [ 'index', 'contact', 'faq', 'registration', 'sponsors', 'travel', 'visit', 'volunteers' ]; pages.forEach(function(page) { cons.dust('views/'+page+'.dust', { views: __dirname+'/views'}, function(err, html) { if(err) return console.log('error: ', err); fs.writeFile(__dirname+'/dist/'+page+'.html', html, function(err) { if(err) return console.log('error saving file: ', page, err); console.log('create page: ', page); }); }); });
'use strict'; module.exports = function (grunt) { var exec = require('child_process').exec; grunt.registerMultiTask('install-dependencies', 'Installs npm dependencies.', function () { var cb, options, cp; cb = this.async(); options = this.options({ cwd: '', stdout: true, stderr: true, failOnError: true, isDevelopment: false }); var cmd = "npm install"; if(!options.isDevelopment ) cmd += " -production"; cp = exec(cmd, {cwd: options.cwd}, function (err, stdout, stderr) { if (err && options.failOnError) { grunt.warn(err); } cb(); }); grunt.verbose.writeflags(options, 'Options'); if (options.stdout || grunt.option('verbose')) { console.log("Running npm install in: " + options.cwd); cp.stdout.pipe(process.stdout); } if (options.stderr || grunt.option('verbose')) { cp.stderr.pipe(process.stderr); } }); };
const electron = require('electron'); const ipcRenderer = electron.ipcRenderer; window.onload = function() { ipcRenderer.send('game-preview-loaded'); } ipcRenderer.on('game-preview-start', function(event, data) { var app = new Application({ // resize: true, fullscreen: true, antyAliasing: true, preload: function(){ console.log(data.assets); //load images for (var i = 0; i < data.assets.length; i++) { var meta = data.assets[i]; if(meta.type == 'script') { require(meta.path); // connect script with uuid } else { this.loader.load(meta.type, meta.path, meta.name, meta.uuid); } } //load scene (json) // this.loader.load('json', scene file path, 'scene.json'); }, //instantiate scene objects loaded: function(){ //instantiate all object for(var i = 0; i < data.sceneFile.length; i++) { if(data.sceneFile[i].tag == 'mainCamera') { this.mainCamera = this.scene.instantiate(data.sceneFile[i]); } else { this.scene.instantiate(data.sceneFile[i]); } } }, //actual start function start: function(){ //show must go on }, preupdate: function(){ }, postupdate: function(){ }, postrender: function(){ // var layer = this.mainCamera.camera.layer; // layer.ctx.save(); // layer.textAlign('left'); // layer.font('30px Arial'); // layer.fillStyle('white'); // // var fps = (Time.deltaTime).toFixed(3); // // layer.fillText(fps || 0, 0,30); // layer.ctx.restore(); } }); })
module.exports = { token: 'TELEGRAM_BOT_TOKEN', polling: { timeout: 3, limit: 100 } };
Template.friendPosts.onCreated(function() { Bisia.Notification.resetNotify('note', 'post'); }) Template.friendPosts.helpers({ getPost: function(postId) { var post = Posts.findOne(postId); if (post) { var user = Users.findOne({ '_id': post.authorId }, { 'fields': { 'username': 1, 'profile.city': 1, 'profile.gender': 1, 'profile.status': 1, 'profile.avatar': 1, 'profile.online': 1, 'profile.birthday': 1 }}); post.showHeader = true; post.usern = user.username; post.profile = user.profile; return post; } }, detectFirstPage: function() { var increment = Bisia.getController('increment'); var limit = Bisia.getController('params')['pageLimit']; // Don't show spinner by default var pageDisplay = true; // If we are on the first page... if (!limit || limit == increment) { // pageDisplay becomes reactive pageDisplay = this.pageReady; } // Add pageDisplay to this return _.extend(this, { pageDisplay: pageDisplay }); } }); Template.friendPosts.events({ 'scroll .content': function(e, t) { Bisia.Ui.toggleAtBottom(e, '#helpbars', 'bottom-show'); } });
import { all, takeEvery } from 'redux-saga/effects'; import actions from '#actions'; import handleShareFormChange from './startAlbumsSharingService/handleShareFormChange'; import handleShareFormSubmit from './startAlbumsSharingService/handleShareFormSubmit'; import handleShareItemsSelect from './startAlbumsSharingService/handleShareItemsSelect'; function* startAlbumsSharingService(apis) { yield all([ takeEvery(actions.uiShareItemsSelected, handleShareItemsSelect, apis), takeEvery(actions.uiShareFormSubmited, handleShareFormSubmit, apis), takeEvery(actions.uiShareFormChanged, handleShareFormChange, apis), ]); } export default startAlbumsSharingService;
var fs = require('fs'), eol = require('eol'), path = require('path'), mkdirp = require('mkdirp'), watch = require('watch'); var specialFiles = { 'welcome.md': function(fileContent, consoleContent) { consoleContent.welcome = processFileContent(fileContent); }, 'config.json': function(fileContent, consoleContent) { var config = JSON.parse(fileContent); consoleContent.executables = config.executables; consoleContent.__config = config; } }; function processFileContent(fileContent) { fileContent = eol.lf(fileContent); fileContent = new Buffer(fileContent).toString('base64'); return fileContent; } function createContentFile(fileName, fileContent) { var parsed = path.parse(fileName); return { content: processFileContent(fileContent), base: fileName, name: parsed.name, ext: parsed.ext }; } function hasExecutableForFile(executables, fileName) { if (!executables) { return false; } for (var i in executables) { if (executables[i].file === fileName) { return true; } } return false; } function setFilePermissions(files, config) { if (!files) { return; } for (var fileName in files) { var file = files[fileName]; if (!config.noRead || config.noRead.indexOf(file.base) === -1) { file.readable = true; } if (config.writeable && config.writeable.indexOf(file.base) !== -1) { file.writeable = true; } if (hasExecutableForFile(config.executables, file.base)) { file.executable = true; } } } /** * This badass here reads all files from the console folders and creates the content.json file. */ function createConsoleContent() { var srcPath = './src/content'; var targetPath = './dist/content'; var consoleFolders = fs.readdirSync(srcPath); if (!consoleFolders) { return; } consoleFolders.forEach(function(folderName) { var consoleSrcPath = srcPath + '/' + folderName; var consoleTargetPath = targetPath + '/' + folderName; var stats = fs.statSync(consoleSrcPath); if (!stats.isDirectory()) { return; } var files = fs.readdirSync(consoleSrcPath); if (!files || files.length === 0) { console.log('No files found for ' + consoleSrcPath); } else { console.log('Processing content ' + folderName); var consoleContent = { files: {} }; files.forEach(function(file) { var fileContent = fs.readFileSync(consoleSrcPath + '/' + file, 'utf8'); if (specialFiles[file]) { specialFiles[file](fileContent, consoleContent); } else { consoleContent.files[file] = createContentFile(file, fileContent); } }); if (consoleContent.__config) { setFilePermissions(consoleContent.files, consoleContent.__config); delete consoleContent.__config; } mkdirp.sync(consoleTargetPath); fs.writeFileSync(consoleTargetPath + '/content.json', JSON.stringify(consoleContent), 'utf8'); } }); } if (process.argv.indexOf('--watching') !== -1) { watch.watchTree('./src/content', function() { createConsoleContent(); }); } else { createConsoleContent(); }
const determineTestFilesToRun = ({ inputFile, inputArgs = [], config }) => { const path = require("path"); const fs = require("fs"); const glob = require("glob"); let filesToRun = []; if (inputFile) { filesToRun.push(inputFile); } else if (inputArgs.length > 0) { inputArgs.forEach(inputArg => filesToRun.push(inputArg)); } if (filesToRun.length === 0) { const directoryContents = glob.sync( `${config.test_directory}${path.sep}**${path.sep}*` ); filesToRun = directoryContents.filter(item => fs.statSync(item).isFile()) || []; } return filesToRun.filter(file => { return file.match(config.test_file_extension_regexp) !== null; }); }; module.exports = { determineTestFilesToRun };
// nodejs按行读取文件流 var Stream = require('stream').Stream, util = require('util'); var LineStream = function() { this.writable = true; this.readable = true; this.buffer = ''; }; util.inherits(LineStream, Stream); LineStream.prototype.write = function(data, encoding) { if (Buffer.isBuffer(data)) { data = data.toString(encoding || 'utf8'); } var parts = data.split(/\n/g); var len = parts.length; for (var i = 0; i < len; i++) { this.emit('data', parts[i]+'\n'); } }; LineStream.prototype.end = function() { if(this.buffer.length > 0){ this.emit('data',this.buffer); this.buffer = ''; } this.emit('end'); }; module.exports = LineStream;
'use strict'; /** * Module dependencies. */ var users = require('../../app/controllers/users'), goaliedash = require('../../app/controllers/goaliedash'); module.exports = function(app) { app.route('/goaliedash') .get(users.requiresLogin, users.hasAuthorization); };
// @flow import React from 'react' import withPropsStream from '@vega/utils/withPropsStream' import {map} from 'rxjs/operators' import styles from './styles/Communicator.css' import ThreadList from './ThreadList' import CreateComment from './CreateComment' function getPropsStream(props$) { // todo: implement open/close behavior return props$.pipe(map(props => ({...props, isOpen: true}))) } type Props = { isOpen: boolean, subjectIds: string[], focusedCommentId: string } export default withPropsStream( getPropsStream, class Communicator extends React.Component<Props> { state = { createCommentIsSticky: false } handleCloseCreateComment = event => { this.setState({ createCommentIsSticky: false }) event.stopPropagation() } handleStickCreateComment = () => { this.setState({ createCommentIsSticky: true }) } render() { const {isOpen, subjectIds, focusedCommentId} = this.props const {createCommentIsSticky} = this.state return isOpen ? ( <div className={styles.root}> <div className={ createCommentIsSticky ? styles.feedWithWithStickyCreateComment : styles.feed } > <ThreadList subjectId={subjectIds} focusedCommentId={focusedCommentId} /> </div> {subjectIds.length === 1 && ( <CreateComment subjectId={subjectIds[0]} showCloseButton={createCommentIsSticky} className={ createCommentIsSticky ? styles.createCommentSticky : styles.createComment } onClose={this.handleCloseCreateComment} onSubmit={this.handleCloseCreateComment} onClick={this.handleStickCreateComment} /> )} </div> ) : null } } )
var models = require('../models'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { console.log(req.session); res.render('layout'); }); module.exports = router;
var passport = require('passport'); var WebIDStrategy = require('passport-webid').Strategy; var tokens = require('../../util/tokens'); var ids = require('../../util/id'); var console = require('../../log'); var createError = require('http-errors'); var dateUtils = require('../../util/date'); var url = require('url'); function loadStrategy(conf, entityStorageConf) { var auth_type = "webid"; var db = require('../../db')(conf, entityStorageConf); var enabled = conf.enabledStrategies.filter(function (v) { return (v === auth_type); }); if (enabled.length === 0) { console.log('ignoring ' + auth_type + ' strategy for user authentication. Not enabled in the configuration'); return false; } else { try { passport.use(auth_type, new WebIDStrategy( function (webid, certificate, req, done) { console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); console.log("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); var id = { user_name: webid, auth_type: auth_type }; var oauth2ReturnToParsed = url.parse(req.session.returnTo, true).query; console.log(" sesion in strategy " + auth_type + JSON.stringify(oauth2ReturnToParsed)); console.log(" client id from session in " + auth_type + JSON.stringify(oauth2ReturnToParsed.client_id)); console.log(" response_type for oauth2 in " + auth_type + JSON.stringify(oauth2ReturnToParsed.response_type)); var accessToken = tokens.uid(30); var d = Date.parse(certificate.valid_to); var default_exp = dateUtils.dateToEpochMilis(d); db.users.findByUsernameAndAuthType(webid, auth_type, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } db.accessTokens.saveOauth2Token(accessToken, user.id, oauth2ReturnToParsed.client_id, "bearer", [conf.gateway_id], default_exp, null, oauth2ReturnToParsed.response_type, function (err) { if (err) { return done(err); } return done(null, user); }); }); } )); console.log('finished registering passport ' + auth_type + ' strategy'); return true; } catch (e) { console.log('FAIL TO register a strategy'); console.log('ERROR: error loading ' + auth_type + ' passport strategy: ' + e); return false; } } } module.exports = loadStrategy;
const chai = require('chai'); const expect = chai.expect; const ComplexArray = require('../complex-array/complex-array'); function assertArrayEquals(first, second) { const message = `${first} != ${second}`; first.forEach((item, i) => { expect(item).to.equal(second[i], message); }); } describe('Complex Array', () => { describe('Consructor', () => { it('should construct from a number', () => { const a = new ComplexArray(10); expect(a).to.exist; expect(a.real.length).to.equal(10); expect(a.imag.length).to.equal(10); expect(a.real[0]).to.equal(0); expect(a.imag[0]).to.equal(0); }); it('should construct from a number with a type', () => { const a = new ComplexArray(10, Int32Array); expect(a.ArrayType).to.equal(Int32Array); expect(a.real.length).to.equal(10); expect(a.imag.length).to.equal(10); expect(a.real[0]).to.equal(0); expect(a.imag[0]).to.equal(0); }); it('should contruct from a real array', () => { const a = new ComplexArray([1, 2]); assertArrayEquals([1, 2], a.real); assertArrayEquals([0, 0], a.imag); }); it('should contruct from a real array with a type', () => { const a = new ComplexArray([1, 2], Int32Array); expect(a.ArrayType).to.equal(Int32Array) assertArrayEquals([1, 2], a.real); assertArrayEquals([0, 0], a.imag); }); it('should contruct from another complex array', () => { const a = new ComplexArray(new ComplexArray([1, 2])); assertArrayEquals([1, 2], a.real); assertArrayEquals([0, 0], a.imag); }); }); describe('`map` method', () => { it('should alter all values', () => { const a = new ComplexArray([1, 2]).map((value, i) => { value.real *= 10; value.imag = i; }); assertArrayEquals([10, 20], a.real); assertArrayEquals([0, 1], a.imag); }); }); describe('`forEach` method', () => { it('should touch every value', () => { const a = new ComplexArray([1, 2]); a.imag[0] = 4; a.imag[1] = 8; let sum = 0; a.forEach((value, i) => { sum += value.real; sum += value.imag; }); expect(sum).to.equal(15); }); }); describe('`conjugate` method', () => { it('should multiply a number', () => { const a = new ComplexArray([1, 2]); a.imag[0] = 1; a.imag[1] = -2; const b = a.conjugate(); assertArrayEquals([1, 2], b.real); assertArrayEquals([-1, 2], b.imag); }); }); describe('`magnitude` method', () => { it('should give the an array of magnitudes', () => { const a = new ComplexArray([1, 3]); a.imag[0] = 0; a.imag[1] = 4; assertArrayEquals([1, 5], a.magnitude()); }); it('should return an iterable ArrayType object', () => { const a = new ComplexArray([1, 2]); let sum = 0; a.magnitude().forEach((value, i) => { sum += value; }); expect(sum).to.equal(3); }); }); });
/** @jsx h */ import h from '../../helpers/h' export const schema = { blocks: { paragraph: { marks: [{ type: 'bold' }, { type: 'underline' }], }, }, } export const input = ( <value> <document> <paragraph> one <i>two</i> three </paragraph> </document> </value> ) export const output = ( <value> <document> <paragraph>one two three</paragraph> </document> </value> )
/* ======================================================================== * DOM-based Routing * Based on http://goo.gl/EUTi53 by Paul Irish * * Only fires on body classes that match. If a body class contains a dash, * replace the dash with an underscore when adding it to the object below. * * .noConflict() * The routing is enclosed within an anonymous function so that you can * always reference jQuery with $, even when in .noConflict() mode. * * Google CDN, Latest jQuery * To use the default WordPress version of jQuery, go to lib/config.php and * remove or comment out: add_theme_support('jquery-cdn'); * ======================================================================== */ (function($) { // Use this variable to set up the common and page specific functions. If you // rename this variable, you will also need to rename the namespace below. var Sage = { // All pages 'common': { init: function() { // JavaScript to be fired on all pages }, finalize: function() { // JavaScript to be fired on all pages, after page specific JS is fired } }, // Home page 'home': { init: function() { // JavaScript to be fired on the home page }, finalize: function() { // JavaScript to be fired on the home page, after the init JS } }, // About us page, note the change from about-us to about_us. 'about_us': { init: function() { // JavaScript to be fired on the about us page } } }; // The routing fires all common scripts, followed by the page specific scripts. // Add additional events for more control over timing e.g. a finalize event var UTIL = { fire: function(func, funcname, args) { var fire; var namespace = Sage; funcname = (funcname === undefined) ? 'init' : funcname; fire = func !== ''; fire = fire && namespace[func]; fire = fire && typeof namespace[func][funcname] === 'function'; if (fire) { namespace[func][funcname](args); } }, loadEvents: function() { // Fire common init JS UTIL.fire('common'); // Fire page-specific init JS, and then finalize JS $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) { UTIL.fire(classnm); UTIL.fire(classnm, 'finalize'); }); // Fire common finalize JS UTIL.fire('common', 'finalize'); } }; // Load Events $(document).ready(UTIL.loadEvents); })(jQuery); // Fully reference jQuery after this point. $(document).ready(function(){ $("#sidebar-home ul li").addClass( "col-md-3 col-sm-6" ); $("#sidebar-home div").addClass( "clearfix" ); });
module.exports = { before: [function () { console.log('global beforeAll1'); }, 'alias1'], 'alias1': 'alias2', 'alias2': function () { console.log('global beforeAll2'); }, 'One': function () { this.sum = 1; }, 'plus one': function () { this.sum += 1; }, 'equals two': function () { if (this.sum !== 2) { throw new Error(this.sum + ' !== 2'); } } };
'use strict'; angular.module('terminaaliApp') .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { var currentUser = {}; if($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @param {Object} user - login info * @param {Function} callback - optional * @return {Promise} */ login: function(user, callback) { var cb = callback || angular.noop; var deferred = $q.defer(); $http.post('/auth/local', { email: user.email, password: user.password }). success(function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); deferred.resolve(data); return cb(); }). error(function(err) { this.logout(); deferred.reject(err); return cb(err); }.bind(this)); return deferred.promise; }, /** * Delete access token and user info * * @param {Function} */ logout: function() { $cookieStore.remove('token'); currentUser = {}; }, /** * Create a new user * * @param {Object} user - user info * @param {Function} callback - optional * @return {Promise} */ createUser: function(user, callback) { var cb = callback || angular.noop; return User.save(user, function(data) { $cookieStore.put('token', data.token); currentUser = User.get(); return cb(user); }, function(err) { this.logout(); return cb(err); }.bind(this)).$promise; }, /** * Change password * * @param {String} oldPassword * @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) { var cb = callback || angular.noop; return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword }, function(user) { return cb(user); }, function(err) { return cb(err); }).$promise; }, /** * Gets all available info on authenticated user * * @return {Object} user */ getCurrentUser: function() { return currentUser; }, /** * Check if a user is logged in * * @return {Boolean} */ isLoggedIn: function() { return currentUser.hasOwnProperty('role'); }, /** * Waits for currentUser to resolve before checking if user is logged in */ isLoggedInAsync: function(cb) { if(currentUser.hasOwnProperty('$promise')) { currentUser.$promise.then(function() { cb(true); }).catch(function() { cb(false); }); } else if(currentUser.hasOwnProperty('role')) { cb(true); } else { cb(false); } }, /** * Check if a user is an admin * * @return {Boolean} */ isAdmin: function() { return currentUser.role === 'admin'; }, /** * Get auth token */ getToken: function() { return $cookieStore.get('token'); } }; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = undefined; var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _objectAssign = require('object-assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _rcTable = require('rc-table'); var _rcTable2 = _interopRequireDefault(_rcTable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var __assign = undefined && undefined.__assign || Object.assign || function (t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } } return t; }; var Table = function (_React$Component) { (0, _inherits3["default"])(Table, _React$Component); function Table() { (0, _classCallCheck3["default"])(this, Table); return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments)); } Table.prototype.render = function render() { var _props = this.props, columns = _props.columns, dataSource = _props.dataSource, direction = _props.direction, scrollX = _props.scrollX, titleFixed = _props.titleFixed; var _props2 = this.props, style = _props2.style, className = _props2.className; var restProps = (0, _objectAssign2["default"])({}, this.props); ['style', 'className'].forEach(function (prop) { if (restProps.hasOwnProperty(prop)) { delete restProps[prop]; } }); var table = void 0; // 默认纵向 if (!direction || direction === 'vertical') { if (titleFixed) { table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: true }, showHeader: false })); } else { table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } })); } } else if (direction === 'horizon') { columns[0].className = 'am-table-horizonTitle'; table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", showHeader: false, scroll: { x: scrollX } })); } else if (direction === 'mix') { columns[0].className = 'am-table-horizonTitle'; table = _react2["default"].createElement(_rcTable2["default"], __assign({}, restProps, { columns: columns, data: dataSource, className: "am-table", scroll: { x: scrollX } })); } return _react2["default"].createElement("div", { className: className, style: style }, table); }; return Table; }(_react2["default"].Component); exports["default"] = Table; Table.defaultProps = { dataSource: [], prefixCls: 'am-table' }; module.exports = exports['default'];
import { assign, forEach, isArray } from 'min-dash'; var abs= Math.abs, round = Math.round; var TOLERANCE = 10; export default function BendpointSnapping(eventBus) { function snapTo(values, value) { if (isArray(values)) { var i = values.length; while (i--) if (abs(values[i] - value) <= TOLERANCE) { return values[i]; } } else { values = +values; var rem = value % values; if (rem < TOLERANCE) { return value - rem; } if (rem > values - TOLERANCE) { return value - rem + values; } } return value; } function mid(element) { if (element.width) { return { x: round(element.width / 2 + element.x), y: round(element.height / 2 + element.y) }; } } // connection segment snapping ////////////////////// function getConnectionSegmentSnaps(context) { var snapPoints = context.snapPoints, connection = context.connection, waypoints = connection.waypoints, segmentStart = context.segmentStart, segmentStartIndex = context.segmentStartIndex, segmentEnd = context.segmentEnd, segmentEndIndex = context.segmentEndIndex, axis = context.axis; if (snapPoints) { return snapPoints; } var referenceWaypoints = [ waypoints[segmentStartIndex - 1], segmentStart, segmentEnd, waypoints[segmentEndIndex + 1] ]; if (segmentStartIndex < 2) { referenceWaypoints.unshift(mid(connection.source)); } if (segmentEndIndex > waypoints.length - 3) { referenceWaypoints.unshift(mid(connection.target)); } context.snapPoints = snapPoints = { horizontal: [] , vertical: [] }; forEach(referenceWaypoints, function(p) { // we snap on existing bendpoints only, // not placeholders that are inserted during add if (p) { p = p.original || p; if (axis === 'y') { snapPoints.horizontal.push(p.y); } if (axis === 'x') { snapPoints.vertical.push(p.x); } } }); return snapPoints; } eventBus.on('connectionSegment.move.move', 1500, function(event) { var context = event.context, snapPoints = getConnectionSegmentSnaps(context), x = event.x, y = event.y, sx, sy; if (!snapPoints) { return; } // snap sx = snapTo(snapPoints.vertical, x); sy = snapTo(snapPoints.horizontal, y); // correction x/y var cx = (x - sx), cy = (y - sy); // update delta assign(event, { dx: event.dx - cx, dy: event.dy - cy, x: sx, y: sy }); }); // bendpoint snapping ////////////////////// function getBendpointSnaps(context) { var snapPoints = context.snapPoints, waypoints = context.connection.waypoints, bendpointIndex = context.bendpointIndex; if (snapPoints) { return snapPoints; } var referenceWaypoints = [ waypoints[bendpointIndex - 1], waypoints[bendpointIndex + 1] ]; context.snapPoints = snapPoints = { horizontal: [] , vertical: [] }; forEach(referenceWaypoints, function(p) { // we snap on existing bendpoints only, // not placeholders that are inserted during add if (p) { p = p.original || p; snapPoints.horizontal.push(p.y); snapPoints.vertical.push(p.x); } }); return snapPoints; } eventBus.on('bendpoint.move.move', 1500, function(event) { var context = event.context, snapPoints = getBendpointSnaps(context), target = context.target, targetMid = target && mid(target), x = event.x, y = event.y, sx, sy; if (!snapPoints) { return; } // snap sx = snapTo(targetMid ? snapPoints.vertical.concat([ targetMid.x ]) : snapPoints.vertical, x); sy = snapTo(targetMid ? snapPoints.horizontal.concat([ targetMid.y ]) : snapPoints.horizontal, y); // correction x/y var cx = (x - sx), cy = (y - sy); // update delta assign(event, { dx: event.dx - cx, dy: event.dy - cy, x: event.x - cx, y: event.y - cy }); }); } BendpointSnapping.$inject = [ 'eventBus' ];
var changeSpan; var i = 0; var hobbies = [ 'Music', 'HTML5', 'Learning', 'Exploring', 'Art', 'Teaching', 'Virtual Reality', 'The Cosmos', 'Unity3D', 'Tilemaps', 'Reading', 'Butterscotch', 'Drawing', 'Taking Photos', 'Smiles', 'The Poetics of Space', 'Making Sounds', 'Board games', 'Travelling', 'Sweetened condensed milk' ]; function changeWord() { changeSpan.textContent = hobbies[i]; i++; if (i >= hobbies.length) i = 0; } function init() { console.log('initialising scrolling text'); changeSpan = document.getElementById("scrollingText"); nIntervId = setInterval(changeWord, 950); changeWord(); } if (document.addEventListener) { init(); } else { init(); }
import { GraphQLInputObjectType, GraphQLID, GraphQLList, GraphQLBoolean, } from 'graphql'; import RecipientTypeEnum from './RecipientTypeEnum'; import MessageTypeEnum from './MessageTypeEnum'; import NoteInputType from './NoteInputType'; import TranslationInputType from './TranslationInputType'; import CommunicationInputType from './CommunicationInputType'; const MessageInputType = new GraphQLInputObjectType({ name: 'MessageInput', fields: { parentId: { type: GraphQLID, }, note: { type: NoteInputType, }, communication: { type: CommunicationInputType, }, subject: { type: TranslationInputType, }, enforceEmail: { type: GraphQLBoolean, }, isDraft: { type: GraphQLBoolean, }, recipients: { type: new GraphQLList(GraphQLID), }, recipientType: { type: RecipientTypeEnum }, messageType: { type: MessageTypeEnum }, }, }); export default MessageInputType;
let _ = require('underscore'), React = require('react'); class Icon extends React.Component { render() { let className = "icon " + this.props.icon; let other = _.omit(this.props.icon, "icon"); return ( <span className={className} role="img" {...other}></span> ); } } Icon.propTypes = { icon: React.PropTypes.string.isRequired }; module.exports = Icon;
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class ChevronDown extends React.Component { render() { if(this.props.bare) { return <g> <path d="M256,298.3L256,298.3L256,298.3l174.2-167.2c4.3-4.2,11.4-4.1,15.8,0.2l30.6,29.9c4.4,4.3,4.5,11.3,0.2,15.5L264.1,380.9 c-2.2,2.2-5.2,3.2-8.1,3c-3,0.1-5.9-0.9-8.1-3L35.2,176.7c-4.3-4.2-4.2-11.2,0.2-15.5L66,131.3c4.4-4.3,11.5-4.4,15.8-0.2L256,298.3 z"></path> </g>; } return <IconBase> <path d="M256,298.3L256,298.3L256,298.3l174.2-167.2c4.3-4.2,11.4-4.1,15.8,0.2l30.6,29.9c4.4,4.3,4.5,11.3,0.2,15.5L264.1,380.9 c-2.2,2.2-5.2,3.2-8.1,3c-3,0.1-5.9-0.9-8.1-3L35.2,176.7c-4.3-4.2-4.2-11.2,0.2-15.5L66,131.3c4.4-4.3,11.5-4.4,15.8-0.2L256,298.3 z"></path> </IconBase>; } };ChevronDown.defaultProps = {bare: false}
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const webpack = require('webpack'); const paths = require('./tools/paths'); const env = { 'process.env.NODE_ENV': JSON.stringify('development') }; module.exports = { devtool: 'cheap-module-eval-source-map', entry: [ require.resolve('./tools/polyfills'), 'webpack-dev-server/client?http://localhost:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index' ], output: { filename: 'static/js/bundle.js', path: paths.appDist, pathinfo: true, publicPath: '/' }, module: { rules: [ // Default loader: load all assets that are not handled // by other loaders with the url loader. // Note: This list needs to be updated with every change of extensions // the other loaders match. // E.g., when adding a loader for a new supported file extension, // we need to add the supported extension to this loader too. // Add one new line in `exclude` for each loader. // // "file" loader makes sure those assets get served by WebpackDevServer. // When you `import` an asset, you get its (virtual) filename. // In production, they would get copied to the `dist` folder. // "url" loader works like "file" loader except that it embeds assets // smaller than specified limit in bytes as data URLs to avoid requests. // A missing `test` is equivalent to a match. { exclude: [ /\.html$/, /\.js$/, /\.scss$/, /\.json$/, /\.svg$/, /node_modules/ ], use: [{ loader: 'url-loader', options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]' } }] }, { test: /\.js$/, enforce: 'pre', include: paths.appSrc, use: [{ loader: 'xo-loader', options: { // This loader must ALWAYS return warnings during development. If // errors are emitted, no changes will be pushed to the browser for // testing until the errors have been resolved. emitWarning: true } }] }, { test: /\.js$/, include: paths.appSrc, use: [{ loader: 'babel-loader', options: { // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true } }] }, { test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2 } }, 'postcss-loader', 'sass-loader' ] }, { test: /\.svg$/, use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }] } ] }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: paths.appHtml }), new webpack.DefinePlugin(env), new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), // Watcher doesn't work well if you mistype casing in a path so we use // a plugin that prints an error when you attempt to do this. // See https://github.com/facebookincubator/create-react-app/issues/240 new CaseSensitivePathsPlugin(), // If you require a missing module and then `npm install` it, you still have // to restart the development server for Webpack to discover it. This plugin // makes the discovery automatic so you don't have to restart. // See https://github.com/facebookincubator/create-react-app/issues/186 new WatchMissingNodeModulesPlugin(paths.appNodeModules) ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { fs: 'empty', net: 'empty', tls: 'empty' } };
import Ember from 'ember'; import { module, test } from 'qunit'; import startApp from 'superhero/tests/helpers/start-app'; import characterData from '../fixtures/character'; var application, server; module('Acceptance: Character', { beforeEach: function() { application = startApp(); var character = characterData(); server = new Pretender(function() { this.get('/v1/public/characters/1009609', function(request) { var responseData = JSON.stringify(character); return [ 200, {"Content-Type": "application/json"}, responseData ]; }); }); }, afterEach: function() { Ember.run(application, 'destroy'); server.shutdown(); } }); test('visiting /characters/1009609 shows character detail', function(assert) { assert.expect(3); visit('/characters/1009609'); andThen(function() { assert.equal(currentURL(), '/characters/1009609'); assert.equal(find('.heading').text(), 'Spider-Girl (May Parker)', 'Should show character heading'); assert.equal( find('.description').text(), "May \"Mayday\" Parker is the daughter of Spider-Man and Mary Jane Watson-Parker. Born with all her father's powers-and the same silly sense of humor-she's grown up to become one of Earth's most trusted heroes and a fitting tribute to her proud papa.", 'Should show character descripton' ); }); }); test('visiting /characters/1009609 shows key events for the character', function(assert) { assert.expect(2); visit('/characters/1009609'); andThen(function() { assert.equal(find('.events .event').length, 1, 'Should show one event'); assert.equal( find('.events .event:first').text(), 'Fear Itself', 'Should show event name' ); }); });
#!/usr/bin/env node (function () { var DirectoryLayout = require('../lib/index.js'), program = require('commander'), options; program .version('1.0.2') .usage('[options] <path, ...>') .option('-g, --generate <path> <output-directory-layout-file-path>', 'Generate directory layout') .option('-v, --verify <input-directory-layout-file-path> <path>', 'Verify directory layout') .parse(process.argv); if(program.generate) { options = { output: program.args[0] || 'layout.md', ignore: [] }; console.log('Generating layout for ' + program.generate + '... \n') DirectoryLayout .generate(program.generate, options) .then(function() { console.log('Layout generated at: ' + options.output); }); } else if(program.verify) { options = { root: program.args[0] }; console.log('Verifying layout for ' + options.root + ' ...\n'); DirectoryLayout .verify(program.verify, options) .then(function() { console.log('Successfully verified layout available in ' + program.verify + '.'); }); } }());
var class_snowflake_1_1_game_1_1_game_database = [ [ "GameDatabase", "class_snowflake_1_1_game_1_1_game_database.html#a2f09c1f7fe18beaf8be1447e541f4d68", null ], [ "AddGame", "class_snowflake_1_1_game_1_1_game_database.html#a859513bbac24328df5d3fe2e47dbc183", null ], [ "GetAllGames", "class_snowflake_1_1_game_1_1_game_database.html#a7c43f2ccabe44f0491ae25e9b88bb07a", null ], [ "GetGameByUUID", "class_snowflake_1_1_game_1_1_game_database.html#ada7d853b053f0bbfbc6dea8eb89e85c4", null ], [ "GetGamesByName", "class_snowflake_1_1_game_1_1_game_database.html#ac1bbd90e79957e360dd5542f6052616e", null ], [ "GetGamesByPlatform", "class_snowflake_1_1_game_1_1_game_database.html#a2e93a35ea18a9caac9a6165cb33b5494", null ] ];
// JavaScript Document $(document).ready(function() { $('form input[type="file"]').change(function() { var filename = $(this).val(); $(this).prev('i').text(filename); }); $('.input-file').click(function() { $(this).find('input').click(); }); /* * Previene doble click en boton submit de envio de datos de formulario y evitar doble envio */ $('form').on('submit', function() { var submit = $(this).find('input[type="submit"]'); submit.attr('disabled','yes').css('cursor', 'not-allowed'); }); $('form').on('reset', function() { $('form .input-file i').text('Selecciona un archivo'); }); /* * Toggle en menu principal lateral */ $('ul#navi li').click(function() { $(this).next('ul').slideToggle('fast'); //$(this).toggleClass('active'); }); /* * Coloca un simbolo para identificar los item con subitems en el menu navegacion izquierda */ $('ul.subnavi').each(function() { var ori_text = $(this).prev('li').find('a').text(); $(this).prev('li').find('a').html(ori_text+'<span class="fa ellipsis">&#xf107;</span>'); }); /* * Despliega cuadro de informacion de usuario */ $('li.user_photo, li.user_letter').click(function(e) { $(this).next('div.user_area').fadeToggle(50); e.stopPropagation(); }); $('body').click(function() { $('li.user_photo, li.user_letter').next('div.user_area').hide(); }); $('div.user_area').click(function(e) { e.stopPropagation(); }); /* * Mostrar/Ocultar mapa */ $('#toggle_map').click(function() { $('ul.map_icon_options').fadeToggle('fast'); $('img#mapa').fadeToggle('fast'); $(this).toggleClass('active'); }); /* * Confirmación de cerrar sesión */ /*$('#cerrar_sesion').click(function() { return confirm(String.fromCharCode(191)+'Esta seguro que desea salir de la sesi'+String.fromCharCode(243)+'n?'); });*/ /* * Confirmación de eliminar datos */ $('a.eliminar').click(function() { return confirm(String.fromCharCode(191)+'Esta seguro que desea eliminar este registro?'); }); /* * Confirmación de quitar asignacion a responsable de un area */ $('a.quitar_asignacion').click(function() { return confirm('Se quitara la asignacion al usuario. '+String.fromCharCode(191)+'Desea continuar?'); }); /* * Ajusta tamaño a imagenes de mapas que son mas altas que anchas */ $('.map_wrapper img#mapa').each(function() { var h = $(this).height(); var w = $(this).width(); if(h > w) { $(this).css('width', '50%').addClass('halign'); } }) /* * Envia a impresion */ $('#print').click(function() { window.print(); }); /* * Inhabilita el click derecho */ $(function(){ $(document).bind("contextmenu",function(e){ return false; }); }); /* * Toma atruto ALT de campo de formulario y lo usa como descripcion debajo del campo */ $('form.undertitled').find('input:text, input:password, input:file, select, textarea').each(function() { $(this).after('<span>'+$(this).attr('title')+'</span>'); }); /* * Hack para centrar horizontalmente mensajes de notificación */ $('p.notify').each(function() { var w = $(this).width(); $(this).css('left', -(w/2)+'px'); }).delay(5000).fadeOut('medium'); //-- /* * Focus en elementos de tabla */ $("table tbody tr").click(function() { $(this).addClass('current').siblings("tr").removeClass('current'); }); /* * Hace scroll al tope de la página * * $('.boton_accion').toTop(); */ $.fn.toTop = function() { $(this).click(function() { $('html, body').animate({scrollTop:0}, 'medium'); }) } //-- /* * Ventana modal * @param text box * Qparam text overlay * * $('.boton_que_acciona_ventana').lightbox('.objeto_a_mostrar', 'w|d : opcional') * w : Muestra una ventana al centro de la pantalla en fondo blanco * d : Muestra una ventana al top de la pantalla sobre fondo negro, si no define * el segundo parametro se mostrara por default este modo. */ $.fn.lightbox = function(box, overlay='d') { $(this).click(function() { var ol = (overlay=='w') ? 'div.overlay_white' : 'div.overlay'; $(ol).fadeIn(250).click(function() { $(box).slideUp(220); $(this).delay(221).fadeOut(250); }).attr('title','Click para cerrar'); $(box).delay(251).slideDown(220); }); if(overlay=='d') { $(box).each(function() { $(this).html($(this).html()+'<p style="border-top:1px #CCC solid; color:#888; margin-bottom:0; padding-top:10px">Para cerrar esta ventana haga click sobre el &aacute;rea sombreada.</p>'); }); } }; //-- })
/** * Created by raynald on 8/22/14. */ App.Collections.Contacts = Backbone.Collection.extend({ model : App.Models.Contact, localStorage: new Backbone.LocalStorage('my-contacts') });
const assert = require('assert')
'use strict'; var _ = require('lodash'), jsonFormat = require('json-format'), grunt = require('grunt'); var util = require('../util/util'); module.exports = { json: function(data, options, generatedContent, callback){ if(_.isString(options.dest)){ grunt.file.write(options.dest + '/json/' + generatedContent.task + '.json', jsonFormat(generatedContent)); grunt.file.write(options.dest + '/json/content/' + data.uuid + '.json', jsonFormat(data)); } callback(generatedContent); } }; //
/** * Dont edit this file! * This module generates itself from lang.js files! * Instead edit the language files in /lang/ **/ /*global define*/ define(function () { "use strict"; var i18n = {}; i18n.de = { "Visit %s overview" : "Zur %s Übersicht", "An error occured, please reload." : "Es gab einen unerwarteten Fehler. Bitte laden Sie die Seite neu.", "Order successfully saved" : "Reihenfolge erfolgreich gespeichert", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "Ihr Browser unterstützt die folgenden Technologien nicht: %s <br>Bitte installieren Sie eine neuere Version Ihres Browsers!", "Close" : "Schließen", "When asynchronously trying to load a ressource, I came across an error: %s" : "Beim Laden einer Ressource gab es leider folgenden Fehler: %s", "You are using an outdated web browser. Please consider an update!" : "Sie benutzen eine veraltete Browser Version. Bitte installieren Sie einen aktuelleren Browser.", "No results found." : "Keine Ergebnisse gefunden.", "No results found for \"%s\"." : "Keine Ergebnisse für \"%s\" gefunden.", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "Du hast es fast geschafft!", "Show overview" : "Übersicht anzeigen", "Show %d contents for \"%s\"" : "", "Abort": "Abbrechen" }; i18n.en = { "An error occured, please reload." : "", "Close" : "", "Visit %s overview" : "", "Order successfully saved" : "", "Your browser doesnt support the following technologies: %s <br>Please update your browser!" : "", "When asynchronously trying to load a ressource, I came across an error: %s" : "", "You are using an outdated web browser. Please consider an update!" : "", "No results found." : "", "No results found for \"%s\"." : "", "Illegal injection found" : "", "Could not load injection" : "", "You\'re almost done!" : "", "Show overview" : "", "Show %d contents for \"%s\"" : "", "Abort": "" }; return i18n; });
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Person = mongoose.model('Person'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), _ = require('lodash'); /** * Create a Person */ exports.create = function(req, res) { var person = new Person(req.body); person.user = req.user; person.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * Show the current Person */ exports.read = function(req, res) { // convert mongoose document to JSON var person = req.person ? req.person.toJSON() : {}; // Add a custom field to the Article, for determining if the current User is the "owner". // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model. // person.isCurrentUserOwner = req.user && person.user && person.user._id.toString() === req.user._id.toString(); res.jsonp(person); }; /** * Update a Person */ exports.update = function(req, res) { var person = req.person; person = _.extend(person, req.body); person.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * Delete a Person */ exports.delete = function(req, res) { var person = req.person; person.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(person); } }); }; /** * List of People */ exports.list = function(req, res) { var search = {}; if (req.query.full_name) { search.full_name = new RegExp(req.query.full_name, 'i'); } if (req.query.url) { search.url = new RegExp(req.query.url, 'i'); } if (req.query.email) { search.email = new RegExp(req.query.email, 'i'); } if (req.query.job) { search.job = new RegExp(req.query.job, 'i'); } if (req.query.location_safe) { search.location_safe = new RegExp(req.query.location_safe, 'i'); } if (req.query.phone) { search.phone = new RegExp(req.query.phone, 'i'); } if (req.query.notes) { search.notes = new RegExp(req.query.notes, 'i'); } if (req.query.keywords) { search.keywords = new RegExp(req.query.keywords, 'i'); } Person.find(search).sort('-created').exec(function (err, people) { if (err) { return res.status(400).send({ message: err.message }); } else { res.json(people); } }); }; /** * List of Dupliacte People */ exports.duplicates = function (req, res) { var aggregate = [ { $group: { _id: { url: '$url' }, count: { $sum: 1 } } }, { $match: { count: { $gte: 2 } } } ]; Person.aggregate(aggregate, function (err, groups) { if (err) { return res.status(400).send({ message: err.message }); } else { var dup_urls = []; for (var i = 0; i < groups.length; i++) { var group = groups[i]; var _id = group._id; dup_urls.push(_id.url); } Person.find({ url: { $in: dup_urls } }).sort('url').exec(function (err, people) { if (err) { return res.status(400).send({ message: err.message }); } else { res.json(people); } }); } }); }; /** * Person middleware */ exports.personByID = function(req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Person is invalid' }); } Person.findById(id).populate('user', 'displayName').exec(function (err, person) { if (err) { return next(err); } else if (!person) { return res.status(404).send({ message: 'No Person with that identifier has been found' }); } req.person = person; next(); }); };
"use strict";require("retape")(require("./index"))
/** * Copyright © 2009-2012 A. Matías Quezada */ use('sassmine').on(function(sas) { var Block = Class.extend({ constructor: function(message, code) { this.base(); this.message = message; this.code = code; this.before = []; this.after = []; }, execute: function() { this.code.call(null, sas); }, addBeforeEach: function(action) { this.before.push(action); }, addAfterEach: function(action) { this.after.push(action); }, beforeEach: function() { for (var i = 0; i < this.before.length; i++) this.before[i].call(null, sas); }, afterEach: function() { for (var i = 0; i < this.after.length; i++) this.after[i].call(null, sas); } }); sas.Spec = sas.Suite = Block.extend(); });
// package metadata file for Meteor.js Package.describe({ name: 'startup-cafe', "author": "Dragos Mateescu <dmateescu@tremend.ro>", "licenses": [ { "type": "MIT", "url": "http://opensource.org/licenses/MIT" } ], "scripts": { }, "engines": { "node": ">= 0.10.0" }, "devDependencies": { "grunt": "~0.4.5", "grunt-autoprefixer": "~0.8.1", "grunt-contrib-concat": "~0.4.0", "grunt-contrib-jshint": "~0.10.0", "grunt-contrib-less": "~0.11.3", "grunt-contrib-uglify": "~0.5.0", "grunt-contrib-watch": "~0.6.1", "grunt-contrib-clean": "~ v0.6.0", "grunt-modernizr": "~0.5.2", "grunt-stripmq": "0.0.6", "grunt-wp-assets": "~0.2.6", "load-grunt-tasks": "~0.6.0", "time-grunt": "~0.3.2", "grunt-bless": "^0.1.1" } }); Package.onUse(function (api) { api.versionsFrom('METEOR@1.0'); api.use('jquery', 'client'); api.addFiles([ 'dist/fonts/glyphicons-halflings-regular.eot', 'dist/fonts/glyphicons-halflings-regular.svg', 'dist/fonts/glyphicons-halflings-regular.ttf', 'dist/fonts/glyphicons-halflings-regular.woff', 'dist/fonts/glyphicons-halflings-regular.woff2', 'dist/css/bootstrap.css', 'dist/js/bootstrap.js', ], 'client'); });
exports.engine = function(version){ version = version || null; switch (version){ case null: case '0.8.2': return require('./0.8.2').engine; default: return null; } };
'use strict'; var Killable = artifacts.require('../contracts/lifecycle/Killable.sol'); require('./helpers/transactionMined.js'); contract('Killable', function(accounts) { it('should send balance to owner after death', async function() { let killable = await Killable.new({from: accounts[0], value: web3.toWei('10','ether')}); let owner = await killable.owner(); let initBalance = web3.eth.getBalance(owner); await killable.kill({from: owner}); let newBalance = web3.eth.getBalance(owner); assert.isTrue(newBalance > initBalance); }); });
'use strict'; describe('Directive: resize', function () { // load the directive's module beforeEach(module('orderDisplayApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); //TODO: Add unit tests /*it('should change height', inject(function ($compile, $window) { element = angular.element('<resize></resize>'); element = $compile(element)(scope); expect(scope.screenHeight).toBe($window.outerHeight); }));*/ });
/*eslint-disable */ var webpack = require( "webpack" ); var sml = require( "source-map-loader" ); /*eslint-enable */ var path = require( "path" ); module.exports = { module: { preLoaders: [ { test: /\.js$/, loader: "source-map-loader" } ], loaders: [ { test: /sinon.*\.js/, loader: "imports?define=>false" }, { test: /\.spec\.js$/, exclude: /node_modules/, loader: "babel-loader" } ], postLoaders: [ { test: /\.js$/, exclude: /(spec|node_modules)\//, loader: "istanbul-instrumenter" } ] }, resolve: { alias: { "when.parallel": "when/parallel", "when.pipeline": "when/pipeline", react: "react/dist/react-with-addons.js", lux: path.join( __dirname, "./lib/lux.js" ) } } };
const { environment } = require('@rails/webpacker') const webpack = require('webpack') // excluding node_modules from being transpiled by babel-loader. environment.loaders.delete("nodeModules"); environment.plugins.prepend('Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', jquery: "jquery", Popper: ['popper.js', 'default'] })) // const aliasConfig = { // 'jquery': 'jquery-ui-dist/external/jquery/jquery.js', // 'jquery-ui': 'jquery-ui-dist/jquery-ui.js' // }; // environment.config.set('resolve.alias', aliasConfig); // resolve-url-loader must be used before sass-loader // https://github.com/rails/webpacker/blob/master/docs/css.md#resolve-url-loader environment.loaders.get("sass").use.splice(-1, 0, { loader: "resolve-url-loader" }); module.exports = environment
const ResponseMessage = require('../../messages').Response; const through2 = require('through2'); const xtend = require('xtend'); var defaults = { ignore_invalid: false }; function encoder(Message, options) { options = xtend(defaults, options || {}); return through2.obj(function(message, enc, callback) { if (Message.verify(message)) { if (options.ignore_invalid) { return this.queue(message); } throw new Error('unhandled request'); } return callback(null, Message.encodeDelimited(message).finish()); }); } module.exports = function () { return encoder(ResponseMessage); };
var log = require('./logger')('reporter', 'yellow'); var colors = require('colors'); /* eslint no-console: 0 */ module.exports = function(diff) { var keys = Object.keys(diff); var count = 0; var timer = log.timer('reporting'); if (keys.length === 0) { log('✔ no diff detected', 'green'); } else { log('✗ build doesn\'t match!', 'red'); console.log('\nREPORT\n' + colors.white.bgBlack(' [selector] ') + '\n [attribute] ' + '[actual] '.red + '[expected]'.green); keys.forEach(function(key) { var rules = Object.keys(diff[key]); console.log(colors.white.bgBlack('\n ' + key + ' ')); rules.forEach(function(rule) { count++; var expected = pretty(diff[key][rule].expected); var actual = pretty(diff[key][rule].actual); console.log(' ' + rule + ': ' + actual.red + ' ' + expected.green); }); }); } console.log(''); var c = count === 0 ? 'green' : 'red'; log('Broken rules: ' + count, c); log('Affected selectors: ' + keys.length, c); timer(); }; function pretty(val) { if (typeof val !== 'string') { val = JSON.stringify(val, null, 4); } return val; }
// // partial2js // Copyright (c) 2014 Dennis Sänger // Licensed under the MIT // http://opensource.org/licenses/MIT // "use strict"; var glob = require('glob-all'); var fs = require('fs'); var path = require('path'); var stream = require('stream'); var htmlmin = require('html-minifier').minify; var escape = require('js-string-escape'); var eol = require('os').EOL; function Partial2Js( opts ) { opts = opts || {}; var self = this; this.debug = !!opts.debug; this.patterns = []; this.files = []; this.contents = {}; this.uniqueFn = function( file ) { return file; }; var log = (function log() { if ( this.debug ) { console.log.apply( console, arguments ); } }).bind( this ); var find = (function() { this.files = glob.sync( this.patterns.slice( 0 )) || []; }).bind( this ); function cleanPatterns( patterns ) { return patterns.map(function( entry ) { return entry.replace(/\/\*+/g, ''); }); } function compare( patterns, a, b ) { return matchInPattern( patterns, a ) - matchInPattern( patterns, b ); } var sort = (function() { var clean = cleanPatterns( this.patterns ); this.files.sort(function( a, b ) { return compare( clean, a, b ); }); }).bind( this ); // // this function is not every functional ;) // Should use findIndex() [ES6] as soon as possible // function matchInPattern( patterns, entry ) { var res = patterns.length + 100; patterns.every(function( pattern, index ) { if ( entry.indexOf( pattern ) > -1 ) { res = index; return false; } return true; }); return res; } var unique = (function() { if ( typeof this.uniqueFn === 'function' && this.files && this.files.length ) { var obj = {}; this.files.forEach(function( file ) { var key = self.uniqueFn( file ); if ( !obj[key] ) { obj[key] = file; } }); this.files = obj; } }).bind( this ); var asString = (function( moduleName ) { var buffer = ''; buffer += '(function(window,document){' + eol; buffer += '"use strict";' + eol; buffer += 'angular.module("'+moduleName+'",[]).run(["$templateCache",function($templateCache){' + eol; for ( var k in this.contents ) { buffer += ' $templateCache.put("'+k+'","'+this.contents[k]+'");' + eol; } buffer += '}]);' + eol; buffer += '})(window,document);'; return buffer; }).bind( this ); var read = (function() { var id, path, stat; this.contents = {}; for( var k in this.files ) { id = k; path = this.files[k]; stat = fs.statSync( path ); if ( stat.isFile()) { log('read file:', path, '=>', id ); this.contents[id] = fs.readFileSync( path ); } } return this.contents; }).bind( this ); var asStream = function( string ) { var s = new stream.Readable(); s._read = function noop() {}; s.push( string ); s.push(null); return s; }; var minify = (function() { var opts = { collapseWhitespace: true, preserveLineBreaks: false, removeComments: true, removeRedundantAttributes: true, removeEmptyAttributes: false, keepClosingSlash: true, maxLineLength: 0, customAttrCollapse: /.+/, html5: true }; for ( var k in this.contents ) { this.contents[k] = escape(htmlmin( String(this.contents[k]), opts )); } }).bind( this ); this.add = function( pattern ) { this.patterns.push( pattern ); return this; }; this.not = function( pattern ) { this.patterns.push( '!'+pattern ); return this; }; this.folder = function( folder ) { if ( folder && String( folder ) === folder ) { folder = path.resolve( folder ) + '/**/*'; this.patterns.push( folder ); } return this; }; this.unique = function( fn ) { this.uniqueFn = fn; return this; }; this.stringify = function( moduleName ) { find(); sort(); unique(); read(); minify(); return asString( moduleName ); }; this.stream = function( moduleName ) { return asStream( this.stringify( moduleName ) ); }; } module.exports = function( opts ) { return new Partial2Js( opts ); };
var testLogin = function(){ var username = document.getElementById("username").value; var password = document.getElementById("password").value; alert("username="+username+" , password="+password); } window.onload = function (){ }
import React from "react"; import { Message } from "semantic-ui-react"; import Bracket from "./Bracket"; import "./index.scss"; import parseStats from './parseStats'; export default class Brackets extends React.PureComponent { constructor(props) { super(props); this.state = { data: this.updateStats(props), }; } componentWillReceiveProps(nextProps) { if (nextProps.stats !== this.props.stats) { this.setState({ data: this.updateStats(nextProps), }); } } updateStats = (props) => { return parseStats(props.stats); }; render () { if (!this.props.stats) { return ( <Message>Waiting for Tournament Stats...</Message> ); } return ( <div> {this.state.data.map((bracket, $index) => ( <div className="tournament-bracket" key={ bracket.match.matchID }> <Bracket finished={ this.props.stats.finished } item={bracket} key={$index} totalGames={ this.props.stats.options.numberOfGames } /> </div> ))} </div> ); } }
define([ 'backbone', 'metro', 'util' ], function(Backbone, Metro, Util) { var MotivationBtnView = Backbone.View.extend({ className: 'motivation-btn-view menu-btn', events: { 'click': 'toggle', 'mouseover': 'over', 'mouseout': 'out', }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out'); //initial param this.motivationView = new MotivationView(); //add to page this.render(); }, render: function() { var $button = $('<span class="mif-compass">'); $(this.el).html($button); $(this.el).attr('title', 'motivation...'); $('body > .container').append($(this.el)); return this; }, unrender: function() { this.drawElementsView.unrender(); $(this.el).remove(); }, toggle: function() { this.drawElementsView.toggle(); }, over: function() { $(this.el).addClass('expand'); }, out: function() { $(this.el).removeClass('expand'); } }); var MotivationView = Backbone.View.extend({ className: 'motivation-view', events: { 'click .draw': 'draw', 'click .clean': 'clean', 'change .input-type > select': 'clean' }, initialize: function(){ //ensure correct scope _.bindAll(this, 'render', 'unrender', 'toggle', 'drawMotivation', 'drawGPS', 'drawAssignedSection', 'drawAugmentedSection'); //motivation param this.param = {}; this.param.o_lng = 114.05604600906372; this.param.o_lat = 22.551225247189432; this.param.d_lng = 114.09120440483093; this.param.d_lat = 22.545463347318833; this.param.path = "33879,33880,33881,33882,33883,33884,33885,41084,421,422,423,2383,2377,2376,2334,2335,2565,2566,2567,2568,2569,2570,2571,2572,2573,39716,39717,39718,39719,39720,39721,39722,39723,448,39677,39678"; //GPS param this.param.gps = "114.05538082122803,22.551086528436926#114.05844390392303,22.551324331927283#114.06151771545409,22.551264881093118#114.06260132789612,22.54908499948478#114.06269788742065,22.5456862971879#114.06271934509277,22.54315951091646#114.06271934509277,22.538938188315093#114.06284809112547,22.53441944644356"; //assigned section param this.param.assign = "33878,33881,33883,2874,2877,2347,937,941"; //augmented section param //33878,33879,33880,33881,33882,33883,2874,2875,2876,2877,2878,2347,935,936,937,938,939,940,941, this.param.augment = "33879,33880,33882,2875,2876,2878,935,936,938,939,940"; //add to page this.render(); }, render: function() { //this.drawMotivation(); this.drawAssignedSection(); this.drawAugmentedSection(); this.drawGPS(); return this; }, unrender: function() { $(this.el).remove(); }, toggle: function() { $(this.el).css('display') == 'none' ? $(this.el).show() : $(this.el).hide(); }, drawMotivation: function() { $.get('api/trajectories/motivation', this.param, function(data){ Backbone.trigger('MapView:drawMotivation', data); }); }, drawGPS: function() { var self = this; setTimeout(function() { var points = self.param.gps.split('#'); _.each(points, function(point_text, index) { var data = {}; data.geojson = self._getPoint(point_text); data.options = {}; Backbone.trigger('MapView:drawSampleGPSPoint', data); }); }, 2000); }, drawAssignedSection: function() { $.get('api/elements/sections', {id: this.param.assign}, function(data){ Backbone.trigger('MapView:drawSampleAssignedSection', data); }); }, drawAugmentedSection: function() { $.get('api/elements/sections', {id: this.param.augment}, function(data){ Backbone.trigger('MapView:drawSampleAugmentedSection', data); }); }, _getPoint: function(text) { var point = text.split(','); var geojson = { "type": "FeatureCollection", "features":[{ "type": "Feature", "geometry": { "type": "Point", "coordinates": [parseFloat(point[0]), parseFloat(point[1])] } }] }; return geojson; }, }); return MotivationBtnView; });
/* * App Actions * * Actions change things in your application * Since this boilerplate uses a uni-directional data flow, specifically redux, * we have these actions which are the only way your application interacts with * your application state. This guarantees that your state is up to date and nobody * messes it up weirdly somewhere. * * To add a new Action: * 1) Import your constant * 2) Add a function like this: * export function yourAction(var) { * return { type: YOUR_ACTION_CONSTANT, var: var } * } */ import { LOAD_SONGS, LOAD_SONGS_SUCCESS, LOAD_SONGS_ERROR, } from './constants'; // /** // * Load the repositories, this action starts the request saga // * // * @return {object} An action object with a type of LOAD_REPOS // */ export function loadSongs() { return { type: LOAD_SONGS, }; } // /** // * Dispatched when the repositories are loaded by the request saga // * // * @param {array} repos The repository data // * @param {string} username The current username // * // * @return {object} An action object with a type of LOAD_REPOS_SUCCESS passing the repos // */ export function songsLoaded(repos, username) { return { type: LOAD_SONGS_SUCCESS, repos, username, }; } // /** // * Dispatched when loading the repositories fails // * // * @param {object} error The error // * // * @return {object} An action object with a type of LOAD_REPOS_ERROR passing the error // */ export function songsLoadingError(error) { return { type: LOAD_SONGS_ERROR, error, }; }
const simple_sort = (key, a, b) => { if (a[key] < b[key]) return -1 if (a[key] > b[key]) return 1 return 0 } const name_sort = (a, b) => simple_sort('name', a, b) const skill_sort = (a, b) => simple_sort('skill', a, b) const speed_sort = (a, b) => simple_sort('speed', a, b) export { simple_sort, name_sort, skill_sort, speed_sort }
export { default } from './EditData';
const Koa = require('koa') const screenshot = require('./screenshot') const app = new Koa() app.use(async ctx => { var url = ctx.query.url console.log('goto:', url) if (!/^https?:\/\/.+/.test(url)) { ctx.body = 'url 不合法' } else { if (!isNaN(ctx.query.wait)) { ctx.query.wait = ~~ctx.query.wait } let data = await screenshot(url, ctx.query.wait, ~~ctx.query.width) if (ctx.query.base64) { ctx.body = 'data:image/jpeg;base64,' + data } else { ctx.body = `<img src="data:image/jpeg;base64,${data}" />` } } }) app.listen(8000) console.log('server start success at 8000') // process.on('unCaughtException', function (err) { // console.log(err) // })
// Test get machiens var fs = require('fs'); try { fs.accessSync('testdb.json', fs.F_OK); fs.unlinkSync('testdb.json'); // Do something } catch (e) { // It isn't accessible console.log(e); } var server = require('../server.js').createServer(8000, 'testdb.json'); var addTestMachine = function(name) { var newMachine = {}; newMachine.name = name; newMachine.type = 'washer'; newMachine.queue = []; newMachine.operational = true; newMachine.problemMessage = ""; newMachine.activeJob = {}; server.db('machines').push(newMachine); } describe('ALL THE TESTS LOL', function() { it('should add a machine', function(done) { var options = { method: 'POST', url: '/machines', payload: { name: 'test1', type: 'washer' } } server.inject(options, function(response) { expect(response.statusCode).toBe(200); var p = JSON.parse(response.payload); expect(p.name).toBe(options.payload.name); expect(p.type).toBe(options.payload.type); done(); }) }); it('should get all machines', function(done) { var name = 'testMachine'; var name2 = 'anotherMachine'; addTestMachine(name); addTestMachine(name2); var options = { method: 'GET', url: '/machines', } server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); // check p has test and anotherMachine done(); }); }); it('should get one machine', function(done) { var name = 'sweetTestMachine'; addTestMachine(name); var options = { method: 'GET', url: '/machines/'+name }; server.inject(options, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe(name); done(); }); }); it('should add a job the queue then th queue should have the person', function(done) { addTestMachine('queueTest'); var addOptions = { method: 'POST', url: '/machines/queueTest/queue', payload: { user: 'test@mail.com', pin: 1234, minutes: 50 } }; server.inject(addOptions, function(res) { expect(res.statusCode).toBe(200); var p = JSON.parse(res.payload); expect(p.name).toBe('queueTest'); var getQueue = { method: 'GET', url: '/machines/queueTest/queue' }; server.inject(getQueue, function(newRes) { expect(newRes.statusCode).toBe(200); var q = JSON.parse(newRes.payload); console.log(q); expect(q.queue[0].user).toBe('test@mail.com'); expect(q.queue[0].pin).toBe(1234); done(); }) }) }); it('should delete a job from the queue', function(done) { addTestMachine('anotherQueue'); var addOptions = { method: 'POST', url: '/machines/anotherQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(res) { var deleteOptions = addOptions; deleteOptions.url = '/machines/anotherQueue/queue/delete'; deleteOptions.payload = { user: addOptions.payload.user, pin: addOptions.payload.pin } server.inject(deleteOptions, function(r) { expect(r.statusCode).toBe(200); console.log(JSON.parse(r.payload)); done(); }) }) }) it('should add a job to the active queue', function(done) { addTestMachine('activeQueue'); var addOptions = { method: 'POST', url: '/machines/activeQueue/queue', payload: { user: 'test@mail.com', pin: 1235, minutes: 50 } }; server.inject(addOptions, function(r) { var runJobOptions = { method: 'POST', url: '/machines/activeQueue/queue/start', payload: { command: 'next', pin: 1235, minutes: 0 } }; server.inject(runJobOptions, function(res) { expect(res.statusCode).toBe(200); done(); }) }) }); });
require('./loader.jsx');
import Helper from '@ember/component/helper'; import { inject as service } from '@ember/service'; import { get } from '@ember/object'; export default class MediaHelper extends Helper { @service() media; constructor() { super(...arguments); this.media.on('mediaChanged', () => { this.recompute(); }); } compute([prop]) { return get(this, `media.${prop}`); } }