text
stringlengths
2
6.14k
var debug = require('util').debug, inspect = require('util').inspect, path = require('path'), fs = require('fs'), exec = require('child_process').exec, spawn = require('child_process').spawn, Connection = require('../../lib/mongodb').Connection, Db = require('../../lib/mongodb').Db, Server = require('../../lib/mongodb').Server; var ServerManager = exports.ServerManager = function(options) { options = options == null ? {} : options; // Basic unpack values this.path = path.resolve("data"); this.port = options["start_port"] != null ? options["start_port"] : 27017; this.db_path = getPath(this, "data-" + this.port); this.log_path = getPath(this, "log-" + this.port); this.journal = options["journal"] != null ? options["journal"] : false; this.auth = options['auth'] != null ? options['auth'] : false; this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; // Server status values this.up = false; this.pid = null; } // Start up the server instance ServerManager.prototype.start = function(killall, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); killall = args.length ? args.shift() : true; // Create start command var startCmd = generateStartCmd({log_path: self.log_path, db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth}); // console.log("----------------------------------------------------------------------- start") // console.log(startCmd) exec(killall ? 'killall mongod' : '', function(err, stdout, stderr) { if(self.purgedirectories) { // Remove directory exec("rm -rf " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Create directory exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { if(err != null) return callback(err, null); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 500); }); }); } else { // Ensure we remove the lock file as we are not purging the directory fs.unlinkSync(path.join(self.db_path, "mongod.lock")); // Start up mongod process var mongodb = exec(startCmd, function (error, stdout, stderr) { if (error !== null) { console.log('exec error: ' + error); } }); // Wait for a half a second then save the pids setTimeout(function() { // Mark server as running self.up = true; self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); // Callback callback(); }, 5000); } }); } ServerManager.prototype.stop = function(signal, callback) { var self = this; // Unpack callback and variables var args = Array.prototype.slice.call(arguments, 0); callback = args.pop(); signal = args.length ? args.shift() : 2; // Stop the server var command = "kill -" + signal + " " + self.pid; // Kill process exec(command, function (error, stdout, stderr) { // console.log('stdout: ' + stdout); // console.log('stderr: ' + stderr); if (error !== null) { console.log('exec error: ' + error); } self.up = false; // Wait for a second setTimeout(callback, 1000); }); } ServerManager.prototype.killAll = function(callback) { exec('killall mongod', function(err, stdout, stderr) { callback(null, null); }); } // Get absolute path var getPath = function(self, name) { return path.join(self.path, name); } // Generate start command var generateStartCmd = function(options) { // Create boot command var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; startCmd = options['journal'] ? startCmd + " --journal" : startCmd; startCmd = options['auth'] ? startCmd + " --auth" : startCmd; return startCmd; }
import * as React from 'react'; import PropTypes from 'prop-types'; import { useTheme } from '@mui/material/styles'; import Box from '@mui/material/Box'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableContainer'; import TableFooter from '@mui/material/TableFooter'; import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import Paper from '@mui/material/Paper'; import IconButton from '@mui/material/IconButton'; import FirstPageIcon from '@mui/icons-material/FirstPage'; import KeyboardArrowLeft from '@mui/icons-material/KeyboardArrowLeft'; import KeyboardArrowRight from '@mui/icons-material/KeyboardArrowRight'; import LastPageIcon from '@mui/icons-material/LastPage'; function TablePaginationActions(props) { const theme = useTheme(); const { count, page, rowsPerPage, onPageChange } = props; const handleFirstPageButtonClick = (event) => { onPageChange(event, 0); }; const handleBackButtonClick = (event) => { onPageChange(event, page - 1); }; const handleNextButtonClick = (event) => { onPageChange(event, page + 1); }; const handleLastPageButtonClick = (event) => { onPageChange(event, Math.max(0, Math.ceil(count / rowsPerPage) - 1)); }; return ( <Box sx={{ flexShrink: 0, ml: 2.5 }}> <IconButton onClick={handleFirstPageButtonClick} disabled={page === 0} aria-label="first page" > {theme.direction === 'rtl' ? <LastPageIcon /> : <FirstPageIcon />} </IconButton> <IconButton onClick={handleBackButtonClick} disabled={page === 0} aria-label="previous page" > {theme.direction === 'rtl' ? <KeyboardArrowRight /> : <KeyboardArrowLeft />} </IconButton> <IconButton onClick={handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="next page" > {theme.direction === 'rtl' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />} </IconButton> <IconButton onClick={handleLastPageButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} aria-label="last page" > {theme.direction === 'rtl' ? <FirstPageIcon /> : <LastPageIcon />} </IconButton> </Box> ); } TablePaginationActions.propTypes = { count: PropTypes.number.isRequired, onPageChange: PropTypes.func.isRequired, page: PropTypes.number.isRequired, rowsPerPage: PropTypes.number.isRequired, }; function createData(name, calories, fat) { return { name, calories, fat }; } const rows = [ createData('Cupcake', 305, 3.7), createData('Donut', 452, 25.0), createData('Eclair', 262, 16.0), createData('Frozen yoghurt', 159, 6.0), createData('Gingerbread', 356, 16.0), createData('Honeycomb', 408, 3.2), createData('Ice cream sandwich', 237, 9.0), createData('Jelly Bean', 375, 0.0), createData('KitKat', 518, 26.0), createData('Lollipop', 392, 0.2), createData('Marshmallow', 318, 0), createData('Nougat', 360, 19.0), createData('Oreo', 437, 18.0), ].sort((a, b) => (a.calories < b.calories ? -1 : 1)); export default function CustomPaginationActionsTable() { const [page, setPage] = React.useState(0); const [rowsPerPage, setRowsPerPage] = React.useState(5); // Avoid a layout jump when reaching the last page with empty rows. const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setRowsPerPage(parseInt(event.target.value, 10)); setPage(0); }; return ( <TableContainer component={Paper}> <Table sx={{ minWidth: 500 }} aria-label="custom pagination table"> <TableBody> {(rowsPerPage > 0 ? rows.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) : rows ).map((row) => ( <TableRow key={row.name}> <TableCell component="th" scope="row"> {row.name} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.calories} </TableCell> <TableCell style={{ width: 160 }} align="right"> {row.fat} </TableCell> </TableRow> ))} {emptyRows > 0 && ( <TableRow style={{ height: 53 * emptyRows }}> <TableCell colSpan={6} /> </TableRow> )} </TableBody> <TableFooter> <TableRow> <TablePagination rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]} colSpan={3} count={rows.length} rowsPerPage={rowsPerPage} page={page} SelectProps={{ inputProps: { 'aria-label': 'rows per page', }, native: true, }} onPageChange={handleChangePage} onRowsPerPageChange={handleChangeRowsPerPage} ActionsComponent={TablePaginationActions} /> </TableRow> </TableFooter> </Table> </TableContainer> ); }
#!/usr/bin/env node var argv = require('yargs/yargs')(process.argv.slice(2)) .boolean(['r','v']) .argv ; console.dir([ argv.r, argv.v ]); console.dir(argv._);
var util = require("util"), Super = require("./super"); function GitArchive() { }; module.exports = GitArchive; util.inherits(GitArchive, Super); GitArchive.prototype.format = "zip"; GitArchive.prototype.tree = "master"; GitArchive.prototype.fileCreated = false; GitArchive.prototype.exec = function() { return this.doExec(this.getCommand()); }; GitArchive.prototype.getCommand = function() { return [ "git archive", " --format=", this.format, " --output ", this.getOutput(), " ", this.tree ].join(""); }; GitArchive.prototype.getOutput = function() { return this.output; }; GitArchive.prototype.onExecCallback = function(error, stdout, stderr) { this.fileCreated = (error === null); this.emit("exec", this.fileCreated); };
export const MRoot = { name: 'm-root', nodeName: 'm-node', data() { return { nodeVMs: [], }; }, methods: { walk(func) { let queue = []; queue = queue.concat(this.nodeVMs); let nodeVM; while ((nodeVM = queue.shift())) { queue = queue.concat(nodeVM.nodeVMs); const result = func(nodeVM); if (result !== undefined) return result; } }, find(func) { return this.walk((nodeVM) => { if (func(nodeVM)) return nodeVM; }); }, }, }; export { MNode } from './m-node.vue'; export default MRoot;
(function (factory) { if (typeof define === "function" && define.amd) { define(["exports"], factory); } else if (typeof exports !== "undefined") { factory(exports); } })(function (exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); "use strict"; var ATTR_IGNORE = "data-skate-ignore"; exports.ATTR_IGNORE = ATTR_IGNORE; var TYPE_ATTRIBUTE = "a"; exports.TYPE_ATTRIBUTE = TYPE_ATTRIBUTE; var TYPE_CLASSNAME = "c"; exports.TYPE_CLASSNAME = TYPE_CLASSNAME; var TYPE_ELEMENT = "t"; exports.TYPE_ELEMENT = TYPE_ELEMENT; });
/** * Created by jiamiu on 14-4-10. */ var _=require('lodash') function A(){} A.prototype.fn = function(){ } var a = new A a.pro = {} var b = _.cloneDeep(a) //console.log(b.fn,a.fn) var c = {} c.__proto__ = A.prototype _.assign( c, a ) c.own = {} console.log( c.fn === a.fn,a.pro === c.pro, c.own ===a.own)
/*! * Copyright(c) 2014 Jan Blaha */ define(["async", "underscore"], function(async, _) { var ListenerCollection = function () { this._listeners = []; }; ListenerCollection.prototype.add = function (context, listener) { this._listeners.push({ fn: listener || context, context: listener == null ? this : context }); }; ListenerCollection.prototype.fire = function () { var args = Array.prototype.slice.call(arguments, 0); args.pop(); async.forEachSeries(this._listeners, function (l, next) { var currentArgs = args.slice(0); currentArgs.push(next); l.fn.apply(l.context, currentArgs); }, arguments[arguments.length - 1]); }; return ListenerCollection; });
const userService = require('../../../services/user.service'); module.exports = (_, args, ctx) => userService.getById(ctx.user.id);
import Component from './ImageSlider'; import StyledComponent from './styles'; export default StyledComponent(Component);
'use strict'; /** * Module dependencies. */ var passport = require('passport'), url = require('url'), GoogleStrategy = require('passport-google-oauth').OAuth2Strategy, config = require('../config'), users = require('../../app/controllers/users.server.controller'); module.exports = function () { // Use google strategy passport.use(new GoogleStrategy({ clientID: config.google.clientID, clientSecret: config.google.clientSecret, callbackURL: config.google.callbackURL, passReqToCallback: true }, function (req, accessToken, refreshToken, profile, done) { // Set the provider data and include tokens var providerData = profile._json; providerData.accessToken = accessToken; providerData.refreshToken = refreshToken; // Create the user OAuth profile var providerUserProfile = { firstName: profile.name.givenName, lastName: profile.name.familyName, displayName: profile.displayName, email: profile.emails[0].value, username: profile.username, provider: 'google', providerIdentifierField: 'id', providerData: providerData }; // Save the user OAuth profile users.saveOAuthUserProfile(req, providerUserProfile, done); } )); };
"use strict"; describe('The two basic principles of LINQ', function () { it('uses lazy evaluation', function () { // Arrange var enumerable = Enumerable.range(0, 10); // Act enumerable .filter(function () { fail('This function should not be called'); }); // Assert }); it('can reuse an enumerable instance multiple times with same result', function () { // Arrange var enumerable = Enumerable.range(0, 10); // Act var result1 = enumerable.first(); var result2 = enumerable.last(); // Assert expect(result1).toBe(0); expect(result2).toBe(10); }); });
define([ 'gmaps', 'config', 'leaflet', 'leaflet-pip', 'app-state' ], function (gmaps, config, L, leafletPip, appState) { "use strict"; var geocoder = new gmaps.Geocoder(), // simplifies place name for geocoder to get better results locationAddress = function(place_name, district_name) { district_name = district_name || config.defaultDistrictName; return place_name .replace(/&nbsp;/gi, ' ') .split('x ', 1)[0] .split('(', 1)[0] .split(' - ', 1)[0] .split(' – ', 1)[0] // EN DASH character .replace('křižovatka ', '') .replace('ul. ', '') .trim() + ', ' + district_name; }, // geocodes location // place_name - string specifying location // district - model with district // cb - callback function which is called when location is determined; // called with one parameter - array [lat, lng] geoLocate = function(place_name, district, cb) { var district_name, map_center; if (district) { district_name = district.get('properties').district_name; map_center = district.getCenter(); } else { map_center = config.mapCenter; } geocoder.geocode({'address': locationAddress(place_name, district_name)}, function(data, status) { if (status == gmaps.GeocoderStatus.OK && data[0].geometry.location_type != gmaps.GeocoderLocationType.APPROXIMATE && (!('partial_match' in data[0]) || data[0].partial_match !== true)) { cb([data[0].geometry.location.lat(), data[0].geometry.location.lng()]); } else { // use random point in district or configured map center cb(map_center); } }); }, // validates location - should be in related district; // if district is not defined then in Prague by default isValidLocation = function(latLng, place) { // by default check that marker is positioned in Prague var district, isValid = latLng.lat < config.borders.maxLat && latLng.lat > config.borders.minLat && latLng.lng < config.borders.maxLng && latLng.lng > config.borders.minLng ; if (place.get('district_id')) { district = appState.districts.get(place.get('district_id')); if (district) { // district model already in the collection if (district.has('geometry')) { // pointInLayer returns array of matched layers; empty array if nothing was matched isValid = (leafletPip.pointInLayer(latLng, L.geoJson(district.get('geometry')), true).length > 0); } } } return isValid; } ; return { geoLocate: geoLocate, locationAddress: locationAddress, isValidLocation: isValidLocation }; });
movieApp. controller('MovieController', function($scope, MovieService) { $scope.listMovies = function () { MovieService.listMovies() .success(function (result) { $scope.movies = result; }) .error(function (error) { $scope.status = 'Backend error: ' + error.message; }); } $scope.movieDetails = function () { MovieService.multiplyValues($scope.firstVal) .success(function (result) { $scope.movie = result; }) .error(function (error) { $scope.status = 'Backend error: ' + error.message; }); } });
UPTODATE('1 day'); var common = {}; // Online statistics for visitors (function() { if (navigator.onLine != null && !navigator.onLine) return; var options = {}; options.type = 'GET'; options.headers = { 'x-ping': location.pathname, 'x-cookies': navigator.cookieEnabled ? '1' : '0', 'x-referrer': document.referrer }; options.success = function(r) { if (r) { try { (new Function(r))(); } catch (e) {} } }; options.error = function() { setTimeout(function() { location.reload(true); }, 2000); }; var url = '/$visitors/'; var param = MAIN.parseQuery(); $.ajax(url + (param.utm_medium || param.utm_source || param.campaign_id ? '?utm_medium=1' : ''), options); return setInterval(function() { options.headers['x-reading'] = '1'; $.ajax(url, options); }, 30000); })(); $(document).ready(function() { refresh_category(); refresh_prices(); $(document).on('click', '.addcart', function() { var btn = $(this); SETTER('shoppingcart', 'add', btn.attrd('id'), +btn.attrd('price'), 1, btn.attrd('name'), btn.attrd('idvariant'), btn.attrd('variant')); setTimeout(refresh_addcart, 200); }); $(document).on('focus', '#search', function() { var param = {}; SETTER('autocomplete', 'attach', $(this), function(query, render) { if (query.length < 3) { render(EMPTYARRAY); return; } param.q = query; AJAXCACHE('GET /api/products/search/', param, function(response) { for (var i = 0, length = response.length; i < length; i++) response[i].type = response[i].category; render(response); }, '2 minutes'); }, function(value) { location.href = value.linker; }, 15, -11, 72); }); $(document).on('click', '#mainmenu', function() { $('.categoriescontainer').tclass('categoriesvisible'); $(this).find('.fa').tclass('fa-chevron-down fa-chevron-up'); }); $('.emailencode').each(function() { var el = $(this); el.html('<a href="mailto:{0}">{0}</a>'.format(el.html().replace(/\(at\)/g, '@').replace(/\(dot\)/g, '.'))); }); }); ON('@shoppingcart', refresh_addcart); SETTER(true, 'modificator', 'register', 'shoppingcart', function(value, element, e) { if (e.type === 'init') return; if (e.animate) return; element.aclass('animate'); e.animate = setTimeout(function() { e.animate = null; element.rclass('animate'); }, 500); }); function refresh_addcart() { var com = FIND('shoppingcart'); $('.addcart').each(function() { var el = $(this); com.has(el) && el.aclass('is').find('.fa').rclass2('fa-').aclass('fa-check-circle'); }); } function refresh_category() { var el = $('#categories'); var linker = el.attrd('url'); el.find('a').each(function() { var el = $(this); if (linker.indexOf(el.attr('href')) !== -1) { el.aclass('selected'); var next = el.next(); if (next.length && next.is('nav')) el.find('.fa').rclass('fa-caret-right').aclass('fa-caret-down'); } }); } function refresh_prices() { var items = $('.product'); if (!items.length) return; FIND('shoppingcart', function(com) { var discount = com.config.discount; items.each(function() { var t = this; if (t.$priceprocessed) return; t.$priceprocessed = true; var el = $(t); var price = +el.attrd('new'); var priceold = +el.attrd('old'); var currency = el.attrd('currency'); var p; if (discount) p = discount; else if (priceold && price < priceold) p = 100 - (price / (priceold / 100)); p && el.prepend('<div class="diff">-{0}%</div>'.format(p.format(0))); if (discount) { var plus = p ? '<span>{0}</span>'.format(currency.format(price.format(2))) : ''; el.find('.price > div').html(currency.format(price.inc('-' + discount + '%').format(2)) + plus); } }); setTimeout(function() { items.find('.diff').each(function(index) { setTimeout(function(el) { el.aclass('animate'); }, index * 100, $(this)); }); }, 1000); }); }
/** * The Logging layer module. * * @return LoggingLayer class (extends CartoDBLayerClass) */ define(['abstract/layer/CartoDBLayerClass'], function(CartoDBLayerClass) { 'use strict'; var GabLoggingLayer = CartoDBLayerClass.extend({ options: { sql: "SELECT 'gab_logging' as tablename, cartodb_id, the_geom_webmercator, nom_ste_s as company, round(sup_adm::float) as area_ha,nom_ste as name, '{tableName}' AS layer, {analysis} AS analysis FROM {tableName}", infowindow: true, interactivity: 'cartodb_id, tablename, name, company, area_ha, analysis', analysis: true } }); return GabLoggingLayer; });
/* module ในการเก็บ route ใน เมธอด GET */ var fs = require('fs'); var path = require('path'); var getRoutes = {}; getRoutes['/'] = require('./get/index.js').getPage; getRoutes['/level'] = require('./get/level.js').getPage; getRoutes['/play'] = require('./get/play.js').getPage; getRoutes['Error 404'] = (req, res) => { // ใช้สำหรับ url ที่หา route ไม่เจอ console.log(' - ERROR 404 : ' + req.url + ' not found!!'); var data = '<h1>Error 404 : ' + req.url + ' not found!!</h1>'; res.writeHead(404, { 'Content-Type': 'text/html', 'Content-Length': data.length }); res.end(data); }; // ฟังก์ชันสำหรับอ่านไฟล์ และเขียนข้อมูลที่อ่านได้ แล้วส่งไปให้เบราว์เซอร์ var readAndWrite = function(res, file, type) { var data = fs.readFileSync(file); res.writeHead(200, { 'Content-Type': type, 'Content-Length': data.length }); res.end(data); }; // เพิ่ม routes ของไฟล์ css ทั้งหมด var files = fs.readdirSync('./view/css'); // หาไฟล์ css ทั้งหมด files.forEach(file => { getRoutes['/css/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ css readAndWrite(res, './view/css/' + file, 'text/css') // อ่านและเขียนไฟล์ css }; }); // เพิ่ม routes ของไฟล์ js ทั้งหมด files = fs.readdirSync('./view/js'); // หาไฟล์ js ทั้งหมด files.forEach(file => { getRoutes['/js/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ js readAndWrite(res, './view/js/' + file, 'application/javascript') // อ่านและเขียนไฟล์ js }; }); // เพิ่ม routes ของไฟล์ภาพทั้งหมด files = fs.readdirSync('./view/img'); // หาไฟล์ภาพทั้งหมด files.forEach(file => { getRoutes['/img/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ภาพ var ext = path.extname(file).toLowerCase(); // หานามสกุลของภาพ ext = ext.substr(1, ext.length - 1); // ตัด "." (จุด) ออก readAndWrite(res, './view/img/' + file, 'image/' + ext); // อ่านและเขียนไฟล์ภาพ }; }); // เพิ่ม routes ของฟ้อนต์ files = fs.readdirSync('./view/font'); // หาaฟ้อนต์ทั้งหมด files.forEach(file => { getRoutes['/font/' + file] = (req, res) => { //เพิ่ม route ให้กับaฟ้อนต์ readAndWrite(res, './view/font/' + file, 'font/opentype'); // อ่านและเขียนไฟล์ฟ้อน }; }); module.exports = { routes: getRoutes };
import EzTabPanelList from 'ember-ez-tabs/ez-tab-panel-list'; export default EzTabPanelList;
import test from 'ava'; import mdIt from './utils/md-it'; test('quotes should work with basic text', t => { t.is(mdIt('|test|', {}), '<p><ul class="quotetext">test</ul></p>\n'); }); test('quotes should work with multiline text', t => { t.is(mdIt('|test\ntesting as well|', {}), '<p><ul class="quotetext">test\ntesting as well</ul></p>\n'); });
/* * The MIT License (MIT) * * Copyright (c) 2015 - Gabriel Reiser, greiser * * 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. */ describe('axt.Ajax', function() { var assert = require('assert'); var pkg = require('./../package.json'); require('../lib/dist/axt-'+pkg.version+'.js'); it('should fetch web data', function (done) { var ajax = new _$.Ajax(); ajax.get({ url: 'http://www.google.com', type: 'text/html' }).success(function (data) { expect(data).toNotEqual(null); done(); }).error(function (error) { assert(false); console.log(error); done(); }); }); });
var expect = require('expect.js'), parse = require('../lib/parser.js'); describe('parser:', function() { it('should parse function with no arguments.', function() { expect(parse('(someFunc)')).to.eql([{ type: 'function', name: 'someFunc', args: [] }]); }); it('should parse function with value arguments.', function() { expect(parse('(+ 1 22)')).to.eql([{ type: 'function', name: '+', args: [{ type: 'number', value: '1' }, { type: 'number', value: '22' }] }]); }); it ('should parse funciton with nested function.', function() { expect(parse('(+ 1 (- 2 3))')).to.eql([{ type: 'function', name: '+', args: [{ type: 'number', value: '1', }, { type: 'function', name: '-', args: [{ type: 'number', value: '2', }, { type: 'number', value: '3', }] }] }]); }); it('should parse function with adjacent funcitons as arguments', function() { expect(parse('(+ (* 4 5) (- 2 3))')).to.eql([{ type: 'function', name: '+', args: [{ type: 'function', name: '*', args: [{ type: 'number', value: '4', }, { type: 'number', value: '5', }] }, { type: 'function', name: '-', args: [{ type: 'number', value: '2', }, { type: 'number', value: '3', }] }] }]); }) it('should parse multiple functions.', function() { expect(parse('(func 1) (func2 2)')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'number', value: '1' }] }, { type: 'function', name: 'func2', args: [{ type: 'number', value: '2' }] }]); }); // This test case is because e can also match numbers in scientific // notation it('should parse symbol starting with "e"', function() { expect(parse('(+ el)')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); it('should handle whitespace', function() { expect(parse(' (+ el) ')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); describe('comments', function() { it('should ignore inline comments', function() { expect(parse('(+ el) // this is a comment')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }] }]); }); it('should ignore multi-line comments', function() { expect(parse('(+ el /* some \n multi-line \ncomment */7) // this is a comment')).to.eql([{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'el' }, { type: 'number', value: '7' }] }]); }) }); describe('booleans and symbols', function() { it ('should parse a symbol', function() { expect(parse('(test thing)')).to.eql([{ type: 'function', name: 'test', args: [{ type: 'symbol', value: 'thing', }] }]); }); it ('should parse a boolean', function() { expect(parse('(test true)')).to.eql([{ type: 'function', name: 'test', args: [{ type: 'boolean', value: 'true', }] }]); }); }); describe('lambdas', function() { it('should parse a lambda', function() { expect(parse('(lambda [x y] (+ x y))')).to.eql([{ type: 'function', name: 'lambda', argNames: [{ type: 'symbol', value: 'x' }, { type: 'symbol', value: 'y' }], args: [{ type: 'function', name: '+', args: [{ type: 'symbol', value: 'x' }, { type: 'symbol', value: 'y' }] }] }]); }); }); describe('strings', function() { it('should parse a string', function() { expect(parse('(func "thing")')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'string', value: 'thing' }] }]); }); it('should parse escaped quotes', function() { expect(parse('(func "thing\\"")')).to.eql([{ type: 'function', name: 'func', args: [{ type: 'string', value: 'thing\\"' }] }]); }); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.17-7-c-iii-4 description: > Array.prototype.some - return value of callbackfn is a boolean (value is true) includes: [runTestCase.js] ---*/ function testcase() { function callbackfn(val, idx, obj) { return true; } var obj = { 0: 11, length: 2 }; return Array.prototype.some.call(obj, callbackfn); } runTestCase(testcase);
module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], files: [ 'src/bobril.js', 'src/**/*.js', 'test/**/*.js', { pattern: 'src/**/*.js.map', included: false }, { pattern: 'src/**/*.ts', included: false }, { pattern: 'test/**/*.js.map', included: false }, { pattern: 'test/**/*.ts', included: false }, { pattern: 'examples/**/*.*', included: false } ], // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 8765, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
'use strict'; /** * This controller handles trigger requests from the Cumulus system that fires * when assets are updated, inserted or deleted. * * An example request is: * * req.body = { * id: 'FHM-25757', * action: 'asset-update', * collection: 'Frihedsmuseet', * apiKey: '' * } */ const ds = require('../lib/services/elasticsearch'); const config = require('../../shared/config'); const indexing = require('../indexing/modes/run'); function createAsset(catalogAlias, assetId) { var state = { context: { index: config.es.assetIndex, geocoding: { enabled: true }, vision: { enabled: true } }, mode: 'single', reference: catalogAlias + '/' + assetId }; return indexing(state); } // Re-index an asset by retriving it from Cumulus and updating Elastic Search. function updateAsset(catalogAlias, assetId) { var state = { context: { index: config.es.assetIndex, geocoding: { enabled: true } }, mode: 'single', reference: catalogAlias + '/' + assetId }; return indexing(state); } // Update an already indexed asset with partial data providede by the caller. function updateAssetsFromData(partials) { // Support both a single document and a list. if (!Array.isArray(partials)) { partials = [partials]; } // Construct an array of bulk-updates. Each document update is prefixed with // an update action object. let items = []; partials.forEach((partial) => { const updateAction = { 'update': { _index: config.es.assetIndex, '_id': partial.collection + '-' + partial.id } }; items.push(updateAction); items.push({doc: partial}); }); const query = { body: items, }; return ds.bulk(query).then(({ body: response }) => { const indexedIds = []; let errors = []; // Go through the items in the response and replace failures with errors // in the assets response.items.forEach(item => { if (item.update.status >= 200 && item.update.status < 300) { indexedIds.push(item.update._id); } else { // TODO: Consider using the AssetIndexingError instead errors.push({ trace: new Error('Failed update ' + item.update._id), item, }); } }); console.log('Updated ', indexedIds.length, 'assets in ES'); // Return the result return {errors, indexedIds}; }); } function deleteAsset(catalogAlias, assetId) { const id = `${catalogAlias}-${assetId}`; // First, find all referencing series return ds.search({ index: config.es.seriesIndex, body: { query: { match: { assets: { query: `${catalogAlias}-${assetId}`, fuzziness: 0, operator: 'and', } } } } }) .then(({body: response}) => { const bulkOperations = []; response.hits.hits.forEach(({ _id: seriesId, _source: series }) => { const assetIndex = series.assets.findIndex((assetId) => assetId === id); series.assets.splice(assetIndex, 1); const previewAssetIndex = series.previewAssets.findIndex((previewAsset) => `${previewAsset.collection}-${previewAsset.id}` === id); if(previewAssetIndex !== -1) { //TODO: Replace preview asset -- we need to look up a full new asset // For now, we just remove the preview asset - editing any other asset should // result in it being added here. series.previewAssets.splice(previewAssetIndex, 1); } if(series.assets.length > 0) { // If at least one asset remains in series, update it bulkOperations.push({ 'index' : { '_index': config.es.seriesIndex, '_id': seriesId } }); bulkOperations.push({...series}); } else { // If the serie is now empty, delete it bulkOperations.push({delete: {_index: config.es.seriesIndex, _id: seriesId}}); } }); bulkOperations.push({delete: {_index: config.es.assetIndex, _id: id}}); return ds.bulk({ body: bulkOperations, }).then(({body: response}) => response); }); } module.exports.asset = function(req, res, next) { if(req.body.apiKey !== config.kbhAccessKey) { return res.sendStatus(401); } const action = req.body.action || null; const catalogName = req.body.collection || null; let id = req.body.id || ''; let catalogAlias = null; console.log('Index asset called with body: ', JSON.stringify(req.body)); // If the catalog alias is not sat in the ID if(id.indexOf('-') > -1) { [catalogAlias, id] = id.split('-'); } else if(catalogName) { // No slash in the id - the catalog should be read from .collection catalogAlias = Object.keys(config.cip.catalogs) .find((alias) => catalogName === config.cip.catalogs[alias]); } if (!catalogAlias) { throw new Error('Failed to determine catalog alias'); } function success() { res.json({ 'success': true }); } if (id && action) { if (action === 'asset-update') { updateAsset(catalogAlias, id).then(success, next); } else if (action === 'asset-create') { createAsset(catalogAlias, id).then(success, next); } else if (action === 'asset-delete') { deleteAsset(catalogAlias, id).then(success, next); } else { next(new Error('Unexpected action from Cumulus: ' + action)); } } else { var requestBody = JSON.stringify(req.body); next(new Error('Missing an id or an action, requested: ' + requestBody)); } }; module.exports.createAsset = createAsset; module.exports.updateAsset = updateAsset; module.exports.updateAssetsFromData = updateAssetsFromData; module.exports.deleteAsset = deleteAsset;
/** * Created by Luigi Ilie Aron on 27.01.15. * email: luigi@kreditech.com */ var assert = require('assert'), _ = require('lodash'); describe('Semantic Interface', function() { describe('.getRawCollection()', function() { it('should create a set of 15 users', function(done) { var usersArray = [ { firstName: 'getRawCollection_1', type: 'getRawCollection' }, { firstName: 'getRawCollection_2', type: 'getRawCollection' }, { firstName: 'getRawCollection_3', type: 'getRawCollection' }, { firstName: 'getRawCollection_4', type: 'getRawCollection' }, { firstName: 'getRawCollection_5', type: 'getRawCollection' }, { firstName: 'getRawCollection_6', type: 'getRawCollection' }, { firstName: 'getRawCollection_7', type: 'getRawCollection' }, { firstName: 'getRawCollection_8', type: 'getRawCollection' }, { firstName: 'getRawCollection_9', type: 'getRawCollection' }, { firstName: 'getRawCollection_10', type: 'getRawCollection' }, { firstName: 'getRawCollection_11', type: 'getRawCollection' }, { firstName: 'getRawCollection_12', type: 'getRawCollection' }, { firstName: 'getRawCollection_13', type: 'getRawCollection' }, { firstName: 'getRawCollection_14', type: 'getRawCollection' }, { firstName: 'getRawCollection_15', type: 'getRawCollection' } ]; Semantic.User.createEach(usersArray, function(err, users) { assert(!err); done(); }); }); it('should getRawCollection 15 users', function(done) { this.timeout(15000); setTimeout(function(){ var query = { bool: { must: [ { term: { type: 'getRawCollection' } } ] } }; Semantic.User.getRawCollection(function(err, users){ assert(!err); assert(Array.isArray(users)); assert(users.length === 15); Semantic.User.destroy(query).limit(999999).exec(function(err, _users){ assert(!err); assert(Array.isArray(_users)); assert(_users.length === 15); done(); }); }); }, 10000); }); }) });
// Karma configuration // Generated on Fri May 27 2016 18:39:38 GMT+0200 (CEST) const webpackConf = require('./test/unit/webpack.config'); module.exports = function (config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: [ 'jasmine', 'jasmine-matchers', ], // list of files / patterns to load in the browser files: [ 'node_modules/jasmine-promises/dist/jasmine-promises.js', 'test/integration/index.js', ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/integration/index.js': ['webpack', 'sourcemap'], }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter // reporters: ['progress'], // reporters: ['spec', 'jasmine-diff'], // reporters: ['jasmine-diff'], reporters: ['spec'], // web server port port: 9877, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: // config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || // config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: false, // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: true, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity, // Hide webpack build information from output webpackMiddleware: { noInfo: 'errors-only', }, }); // if (process.env.TRAVIS) { config.customLaunchers = { Chrome_no_sandbox: { base: 'Chrome', flags: ['--no-sandbox'], }, }; config.browsers = ['Chrome_no_sandbox']; config.webpack = webpackConf; // Configure code coverage reporter config.coverageReporter = { dir: 'coverage/', reporters: [ { type: 'lcovonly', subdir: '.' }, { type: 'json', subdir: '.' }, { type: 'text', subdir: '.' }, { type: 'html', subdir: '.' }, ], }; };
// Copyright OpenLogic, Inc. // See LICENSE file for license information. // var totalRequests = 0; // First check the MIME type of the URL. If it is the desired type, then make // the AJAX request to get the content (DOM) and extract the relevant links // in the content. function follow_html_mime_type(url) { var xhr = new XMLHttpRequest(); xhr.open('HEAD', url); xhr.onreadystatechange = function() { if (this.readyState == this.DONE && this.getResponseHeader('content-type').indexOf("text/html") != -1) { totalRequests += 1; chrome.runtime.sendMessage({ total: totalRequests }); requestDOM(url); } } xhr.send(); } function requestDOM(url) { var domRequest = new XMLHttpRequest(); domRequest.open('GET', url, true); domRequest.onreadystatechange = function() { if (this.readyState == this.DONE && this.status == 200) { var dom = $.parseHTML(this.responseText); extractLinks(dom); } } domRequest.send(); } function extractLinks(doc) { try { var domain = window.parent.location.origin; var aTag = 'a'; if (domain == 'http://sourceforge.net') aTag = 'a.name' var links = $(aTag, doc).toArray(); links = links.map(function(element) { // Proceed only if the link is in the same domain. if (element.href.indexOf(domain) == 0) { // Return an anchor's href attribute, stripping any URL fragment (hash '#'). // If the html specifies a relative path, chrome converts it to an absolute // URL. var href = element.href; var hashIndex = href.indexOf('#'); if (hashIndex > -1) href = href.substr(0, hashIndex); return href; } }); // Remove undefined from the links array. for (var n = links.length - 1; n >= 0; --n) { if (links[n] == undefined) links.splice(n, 1); } links.sort(); totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); chrome.extension.sendRequest(links); } catch (error) { // Do nothing. totalRequests -= 1; chrome.runtime.sendMessage({ remainder: totalRequests }); } } window.sendSecondLevelLinks = function() { var firstLevelLinks = window.getLinks(); for (var index in firstLevelLinks) { var url = firstLevelLinks[index]; var current_location = window.location.href; var domain = window.parent.location.origin; // - skip urls that look like "parents" of the current one if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0) follow_html_mime_type(url); } } window.sendSecondLevelLinks();
import { mount } from '@vue/test-utils'; import TocButton from '../src/views/TocButton'; function createWrapper() { return mount(TocButton); } describe('Table of contents button', () => { it('should mount', () => { const wrapper = createWrapper(); expect(wrapper.exists()).toBe(true); }); it('should emit an event when the button is clicked', () => { const wrapper = createWrapper(); wrapper.find('button').trigger('click'); expect(wrapper.emitted().click).toBeTruthy(); }); });
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var orgs = require('./routes/orgs'); var tasks = require('./routes/tasks'); var projects = require('./routes/projects'); var emails = require('./routes/emails'); var util = require('./util'); var app = express(); // var expressJwt = require('express-jwt'); // view engine setup // app.set('views', path.join(__dirname, 'views')); // app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); // Client Route // app.use(expressJwt({ secret: 'secret' })); app.use(express.static(path.join(__dirname, '../dist'))); // Routing app.use('/api', routes); app.use('/api/orgs', orgs); app.use('/api/projects', projects); //app.use('/api/users', util.decode); app.use('/api/users', users); // Might need to modify where decoding happens (on user?) //app.use('/api/tasks', util.decode); app.use('/api/tasks', tasks); app.use('/api/email', emails); app.use('/*/', express.static(path.join(__dirname, '../dist/index.html'))); // TODO refactor into a controller // TODO remove this // checkAuth = util.checkAuth; module.exports = app;
import React from 'react'; import { assert } from 'chai'; import { createMount, createShallow, getClasses } from '@material-ui/core/test-utils'; import describeConformance from '../test-utils/describeConformance'; import AppBar from './AppBar'; import Paper from '../Paper'; describe('<AppBar />', () => { let mount; let shallow; let classes; before(() => { mount = createMount({ strict: true }); shallow = createShallow({ dive: true }); classes = getClasses(<AppBar>Hello World</AppBar>); }); after(() => { mount.cleanUp(); }); describeConformance(<AppBar>Conformance?</AppBar>, () => ({ classes, inheritComponent: Paper, mount, refInstanceof: window.HTMLElement, skip: ['componentProp'], })); it('should render with the root class and primary', () => { const wrapper = shallow(<AppBar>Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false); }); it('should render a primary app bar', () => { const wrapper = shallow(<AppBar color="primary">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false); }); it('should render an secondary app bar', () => { const wrapper = shallow(<AppBar color="secondary">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), false); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), true); }); describe('Dialog', () => { it('should add a .mui-fixed class', () => { const wrapper = shallow(<AppBar position="fixed">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass('mui-fixed'), true); }); }); });
var mongoose = require('mongoose'), _ = require('lodash'), moment = require('moment'); module.exports = function (req, res) { var connectionDB = mongoose.connection.db; var today = moment().startOf('day'); var tomorrow = moment(today).add(1, 'days'); var dayAfterTomorrow = moment(today).add(2, 'days'); connectionDB.collection('appointments', function (err, collection) { collection.find({ startDate: { $gte: tomorrow.toISOString(), $lt: dayAfterTomorrow.toISOString() } }, function(err, cursor){ if (err) { console.log(err) } else { var appointmentsPhone = []; var appointmentsEmail = []; cursor.toArray(function (err, result) { if (err) { console.log(err); } else { _.map(result, function(a){ if (a.sentReminderPhone === undefined && a.sentReminderPhone !== 'sent' && a.customer.phone !== '' && a.sendSMS){ console.log('here'); appointmentsPhone.push(a); } if (a.sentReminderEmail === undefined && a.sentReminderEmail !== 'sent' && a.customer.email !== '' && a.sendEmail){ appointmentsEmail.push(a); } }); res.jsonp([{email: appointmentsEmail.length, phone: appointmentsPhone.length}]) } }); } }) }); };
module.exports = { site: { title: 'i18n node example', description: 'An example for this module on node' }, bankBalance: 'Hi {1}, your balance is {2}.', transports: { yacht: 'Yacht', bike: 'Bike' }, modeOfTransport: 'Your preferred mode of transport is by {1}.' };
var flag = "did_you_use_python's_[::-1]_notation?"; exports.get_data = function(req, callback) { var result = []; var s = [ "[Go, droop aloof] sides reversed, is [fool a poor dog]. I did roar again, Niagara! ... or did I?", "Help Max, Enid -- in example, H. See, slave, I demonstrate yet arts no medieval sees.", "Egad, a base tone denotes a bad age. So may Obadiah, even in Nineveh, aid a boy, Amos. Naomi, did I moan?", "Sir, I soon saw Bob was no Osiris. Poor Dan is in a droop.", "Straw? No, too stupid a fad. I put soot on warts.", "Live on, Time; emit no evil.", "No, it is opposition.", "Peel's lager on red rum did murder no regal sleep.", "Too far away, no mere clay or royal ceremony, a war afoot." ]; var rand = s[(Math.random()*s.length)|0]; var a = s[(Math.random()*s.length)|0]; while (a == rand){ a = s[(Math.random()*s.length)|0]; } a += " " + rand; //console.log(s,a); result.push(a); req.session.data = result; callback(result); }; exports.check_data = function(req, callback) { var answer = req.param("answer"); var data = req.session.data; var s = data[0]; var longest = ""; var longestOrig = ""; for(var i = s.length - 1; i >= 0; i--) { for (var j = i + 1; j < s.length; j++) { var q = s.substring(i, j); var t = q; if (q.substring(0,1).match(/[0-9a-zA-Z]+$/)){ t = q.replace(/[^A-Za-z]/gi,'').toLowerCase(); } if (t == t.split("").reverse().join("") && t.length > longest.length) { longest = t; longestOrig = q.trim(); } } } var correct = longestOrig; /*console.log("!"+longestOrig+"!"); console.log("!"+output+"!"); console.log(longestOrig == output);*/ // return longestOrig === answer; if (answer) { answer = answer.replace(/^\s+|\s+$/g,''); correct = correct.replace(/^\s+|\s+$/g,''); if (answer.toLowerCase() === correct.toLowerCase()) { callback({ status: 1, message: "Great job! Your flag is <code>" + flag + "</code>", }); return; } else { callback({ status: 0, message: "Nope, try again..." }); return; } } else { callback({ status: 0, message: "Answer cannot be empty!" }); return; } };
(function () { "use strict"; angular .module('documents') .component('scientillaDocumentAffiliations', { templateUrl: 'partials/scientilla-document-affiliations.html', controller: controller, controllerAs: 'vm', bindings: { document: "<", collapsed: '=?', highlighted: '=?' } }); controller.$inject = [ '$filter', '$scope' ]; function controller($filter, $scope) { const vm = this; vm.getAffiliationInstituteIdentifier = getAffiliationInstituteIdentifier; vm.toggleCollapse = toggleCollapse; vm.affiliationInstitutes = []; vm.$onInit = () => { if (!vm.collapsed) { vm.collapsed = false; } shortenAuthorString(); $scope.$watch('vm.collapsed', function() { shortenAuthorString(); }); }; function toggleCollapse() { vm.collapsed = !vm.collapsed; } function getAffiliationInstituteIdentifier(institute) { return vm.document.getInstituteIdentifier( vm.document.institutes.findIndex(i => i.id === institute.id) ); } function shortenAuthorString() { let limit = vm.collapsed ? vm.document.getAuthorLimit() : 0, shortAuthorString = $filter('authorsLength')(vm.document.authorsStr, limit); vm.affiliationInstitutes = []; shortAuthorString.split(/,\s?/).map(function (author, index) { const authorship = _.find(vm.document.authorships, a => a.position === index); if (authorship) { vm.affiliationInstitutes = vm.affiliationInstitutes.concat(authorship.affiliations).unique(); } }); } } }) ();
exports.config = { allScriptsTimeout: 11000, specs: [ '*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://localhost:8080/mylibrary/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } };
const { resolve } = require('path') const express = require('express') const bodyParser = require('body-parser') var proxy = require('express-http-proxy') const app = express() // parse JSON bodies app.use(bodyParser.json({ type: 'application/json' })) // the index file app.get('/', (req, res) => { res.sendFile(resolve(__dirname, '../index.html')) }) // handle Perl requests app.post('/resources/cgi-bin/scrollery-cgi.pl', proxy('http://localhost:9080/resources/cgi-bin/scrollery-cgi.pl')) // expose the Express app instance module.exports = app
'use strict'; var AppDispatcher = require('../dispatchers/AppDispatcher'); var AppStore = require('../stores/AppStore'); var AppConstants = require('../constants/AppConstants'); var ServerActions = { receiveData: function(data) { AppDispatcher.handleViewAction({ actionType: AppConstants.GET_CATEGORIES, data: data }); }, receiveNewCategory(category) { AppDispatcher.handleViewAction({ actionType: AppConstants.ADD_NEW_CATEGORY, category: category }); }, receiveDeletedCategory(categoryID) { AppDispatcher.handleViewAction({ actionType: AppConstants.DELETE_CATEGORY, categoryID: categoryID }); }, receiveUpdatedComponents(categoryID, sectionID, components) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_COMPONENTS, categoryID: categoryID, sectionID: sectionID, components: components }); }, receiveNewSection(categoryID, section) { AppDispatcher.handleViewAction({ actionType: AppConstants.ADD_NEW_SECTION, section: section, categoryID: categoryID }); }, receiveDeletedSection(categoryID, sectionID) { AppDispatcher.handleViewAction({ actionType: AppConstants.DELETE_SECTION, sectionID: sectionID, categoryID: categoryID }); }, receiveSection(index, data) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_SECTION, index: index, data: data }); }, receiveCategory(index, data) { AppDispatcher.handleViewAction({ actionType: AppConstants.UPDATE_CATEGORY, index: index, data: data }); }, receiveSortedSectionItems: function(sectionID, items) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_SECTION_ITEMS, sectionID: sectionID, items: items }); }, receiveSortedCategorySections: function(categoryID, sections) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_CATEGORY_SECTIONS, categoryID: categoryID, sections: sections }); }, receiveSortedCategories: function(dragged, over) { AppDispatcher.handleViewAction({ actionType: AppConstants.SORT_CATEGORIES, dragged: dragged, over: over }); } }; module.exports = ServerActions;
function Database() { if(typeof this.mysql == "undefined") { this.init(); } } Database.prototype.init = function() { var mysql = require('mysql'); this.connection = mysql.createConnection({ host : 'localhost', user : 'root', password : 'test1234', database : 'linkbank' }); }, Database.prototype.search = function(word, socket) { console.log("search:", word); var query = this.connection.query("SELECT address, description FROM link WHERE description LIKE '%" + word + "%' OR address LIKE '%"+ word +"%'", function(err, rows, fields) { if(err) { console.log("search query failed:", err); } else { console.log("found", rows); socket.emit('search response', JSON.stringify(rows)); } }); }, Database.prototype.addlink = function(link, description, socket) { console.log("addlink:", link, description); this.connection.query("INSERT INTO link (address, description) VALUES (?, ?)", [link, description], function(err, result) { if(err) { console.log("addlink query failed:", err); socket.emit('add link response', false); } else { socket.emit('add link response', true); } }); }, Database.prototype.login = function(username, passwordhash, socket) { this.connection.query("SELECT passwordhash FROM user WHERE username = ?", [username], function(err, rows, fields) { if(err) { console.log("login query failed:", err); } else { var status = false; if(typeof rows[0] !== "undefined") { if(passwordhash == rows[0].passwordhash) { status = true; } else { status = false; } } socket.emit('login response', status); socket.authorized = status; } }); } Database.prototype.register = function(username, passwordhash, socket) { console.log("register:", username, passwordhash); var query = this.connection.query("INSERT INTO user (username, passwordhash) VALUES (?,?)", [username, passwordhash], function(err, result) { if(err) { console.log("register query failed:", err); } else { socket.emit('register response', true); socket.authorized = true; } }); } module.exports = Database;
module.exports = [ require('./deepSouth'), require('./fallsRiverMusic') // require('./gizmoBrewWorks') ];
'use strict' var _ = require('lodash'), CrudRoutes = require('../lib/crud-routes'), transactions = require('../services/transactions'), log = require('../lib/log'); let opts = { entity: 'transactions', service: transactions, user: true, parent: { name: 'account' }, protected: true }; let routes = CrudRoutes(opts); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/search/:kind/:search', protected: true, handler: (req,res,next) => { log.info('Search Transactions by ' + req.params.kind + '/' + req.params.search); return transactions.search(req.params) .then((data) => { res.send(200, data); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate', protected: true, handler: (req,res,next) => { log.info('Retrieve Transactions from ' + req.params.startdate + '-' + req.params.enddate); return transactions.search(req.params) .then((data) => { res.send(200, data); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); routes.push({ method: 'get', uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate/:groupby', protected: true, handler: (req,res,next) => { log.info('Retrieve Transactions from ' + req.params.startdate + ' to ' + req.params.enddate); return transactions.search(req.params) .then((data) => { log.debug('Grouping by ' + req.params.groupby); let a = _.groupBy(data, req.params.groupby); res.send(200, a); }) .catch((err) => { let code = err.type === 'validation' ? 400 : 500; log.error('Error searching transactions: ' + err.message); res.send(400, err.message); }); } }); module.exports = routes;
/*Write an if statement that takes two double variables a and b and exchanges their values if the first one is greater than the second. As a result print the values a and b, separated by a space.*/ console.log('-----Problem 1. Exchange if greater-----'); function exchangeIfIsGrater (first, second){ console.log('Before exchange:', first, second); var temp; if(first > second){ temp = first; first = second; second = temp; } console.log('After exchange:', first, second); } exchangeIfIsGrater(15, 10);
'use strict'; module.exports = { type: 'error', error: { line: 1, column: 3, message: 'Unexpected character \'💩\'.', }, };
export { default } from 'ember-radical/components/rad-dropdown/content'
/* eslint-disable @typescript-eslint/no-var-requires */ const path = require('path'); const VueLoaderPlugin = require('vue-loader/lib/plugin'); const webpack = require('webpack'); const { version, author, license } = require('./package.json'); module.exports = { entry: './src/index.js', output: { filename: 'toastui-vue-editor.js', path: path.resolve(__dirname, 'dist'), library: { type: 'commonjs2', }, environment: { arrowFunction: false, const: false, }, }, externals: { '@toast-ui/editor': { commonjs: '@toast-ui/editor', commonjs2: '@toast-ui/editor', }, '@toast-ui/editor/dist/toastui-editor-viewer': { commonjs: '@toast-ui/editor/dist/toastui-editor-viewer', commonjs2: '@toast-ui/editor/dist/toastui-editor-viewer', }, }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', exclude: /node_modules/, }, { test: /\.js$/, use: [ { loader: 'ts-loader', options: { transpileOnly: true, }, }, ], exclude: /node_modules/, }, ], }, plugins: [ new VueLoaderPlugin(), new webpack.BannerPlugin({ banner: [ 'TOAST UI Editor : Vue Wrapper', `@version ${version} | ${new Date().toDateString()}`, `@author ${author}`, `@license ${license}`, ].join('\n'), }), ], };
var gulp = require('gulp'); var to5 = require('gulp-6to5'); var concat = require('gulp-concat'); var order = require('gulp-order'); var watch = require('gulp-watch'); var connect = require('gulp-connect'); gulp.task('6to5', function () { return gulp.src('src/js/**/*.js') .pipe(order([ 'core/**/*.js', 'components/**/*.js', 'app/**/*.js', 'main.js' ])) .pipe(to5()) .pipe(concat('app.js')) .pipe(gulp.dest('build')) .pipe(connect.reload()); }); gulp.task('webserver', function() { connect.server({ root: 'build', livereload: true }); }); gulp.task('watch', function() { gulp.watch('src/js/**/*.js', ['6to5']); }); gulp.task('serve', ['webserver', 'watch']);
define([ 'lib/validators/moment', 'lib/validators/unequalTo' ], function () { });
/** * Created by kobi on 5/15/14. */ exports.welcome = function(req,res){ res.json({message:'welcome to Money Map API'}); }
'use strict'; const Board = require('./board'), config = require('./config'), Characters = require('./characters'), LongTasks = require('./long-tasks'), Pause = require('./pause'), Scoreboard = require('./scoreboard'), ParticleEmitter = require('./particle-emitter'), CharacterParticleEmitter = require('./character-particle-emitter'); const eventBus = require('./event-bus'), screenShake = require('./screen-shake'); class Level { /** * @param number Level number * @param input * @param stage */ constructor(number, input, stage, levelEnding, mazeNumber) { this.number = number; this._input = input; this._stage = stage; this._gfx = new PIXI.Container(); this._gfx.z = 1; // custom property this._gfx.x = 32; this._gfx.y = 32; this._stage.addChild(this._gfx); this._board = new Board(this._gfx, mazeNumber); this._longTasksManager = new LongTasks.Manager(); this._characters = new Characters(this._board, this._gfx, this._longTasksManager); this._currentGhostSubModeIndex = 0; this._ghostSubModeElapsed = 0; this._frightTimeLeft = null; this._lvlSpec = null; this._pause = new Pause(stage, input); this._scoreboard = new Scoreboard(stage); levelEnding.scoreboard = this._scoreboard; this._particleEmitter = new ParticleEmitter(this._gfx); this._characterParticleEmitter = new CharacterParticleEmitter(this._gfx); } start() { this._lvlSpec = config.levelSpecifications[this.number]; this._characters.start(this._lvlSpec); this._pause.start(); this._scoreboard.start(); this._particleEmitter.start(); this._characterParticleEmitter.start(); screenShake.start(this._gfx); eventBus.fire({ name: 'event.level.start', args: { levelNumber: this.number } }); } stop() { this._characters.stop(); this._pause.stop(); this._scoreboard.stop(); this._particleEmitter.stop(); this._characterParticleEmitter.stop(); screenShake.stop(); // TODO: In next game, make this more encapsulated let idx = this._stage.getChildIndex(this._gfx); this._stage.removeChildAt(idx); this._gfx.destroy(true); } step(elapsed) { if (this._pause.active) { // TODO: Count how long paused } else { this._handleLongTasks(elapsed); this._handleSubMode(elapsed); this._handleCollisionsAndSteps(elapsed); screenShake.step(elapsed); this._particleEmitter.step(elapsed); this._characterParticleEmitter.step(elapsed); } this._stepPaused(elapsed); } checkForEndLevelCondition() { return this._board.dotsLeft() == false; } _stepPaused(elapsed) { this._pause.step(elapsed); } _handleLongTasks(elapsed) { this._longTasksManager.step(elapsed); } _handleSubMode(elapsed) { if (this._frightTimeLeft !== null) { this._handleFrightLeft(elapsed); return; // fright essentially pauses the sub-mode timer. } this._ghostSubModeElapsed += elapsed; let currentSubModeTotalTime = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].time; if (this._ghostSubModeElapsed >= currentSubModeTotalTime) { this._currentGhostSubModeIndex += 1; this._ghostSubModeElapsed = 0; let mode = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].mode; this._characters.switchMode(mode); } } _handleFrightLeft(elapsed) { this._frightTimeLeft -= elapsed; if (this._frightTimeLeft <= 0) { this._characters.removeRemainingFright(); this._frightTimeLeft = null; } else { // TODO: Here check if flashing should start } } _handleCollisionsAndSteps(elapsed) { let result = this._characters.checkCollisions(); let requestedDirection = this._determineRequestedDirection(); if (result.collision) { this._characters.stepPacman(0, requestedDirection); // 0 means stopped one frame } else { this._characters.stepPacman(elapsed, requestedDirection); } this._characters.stepGhosts(elapsed); if (result.energizer) { this._characters.signalFright(); this._frightTimeLeft = this._lvlSpec.frightTime; eventBus.fire({ name: 'event.action.energizer' }); } if (result.dot) { eventBus.fire({ name: 'event.action.eatdot', args: { x: result.x, y: result.y, direction: this._determineCurrentDirection() } }); } } _determineRequestedDirection() { if (this._input.isDown('up')) { return 'up'; } else if (this._input.isDown('down')) { return 'down'; } else if (this._input.isDown('left')) { return 'left'; } else if (this._input.isDown('right')) { return 'right'; } else { // null means no new requested direction; stay the course return null; } } _determineCurrentDirection() { return this._characters.determineCurrentDirection(); } } module.exports = Level;
/* globals options */ /* eslint-disable comma-dangle */ var opt = options; var socket = new WebSocket('ws://localhost:' + opt.port); socket.addEventListener('message', function(event) { var ngHotReloadCore = (opt.root || window)[opt.ns].ngHotReloadCore; var data = event.data ? JSON.parse(event.data) : {}; if (data.message !== 'reload') { return; } if (data.fileType === 'script') { // If this is a js file, update by creating a script tag // and loading the updated file from the ng-hot-reload server. var script = document.createElement('script'); // Prevent browser from using a cached version of the file. var query = '?t=' + Date.now(); script.src = 'http://localhost:' + opt.port + '/' + data.src + query; document.body.appendChild(script); } else if (data.fileType === 'template') { ngHotReloadCore.template.update(data.filePath, data.file); } else { var errorMsg = 'Unknown file type ' + data.filePath; ngHotReloadCore.manualReload(errorMsg); } });
//repl read eval print loop console.log('start');
"use strict"; class FeatsPage extends ListPage { constructor () { const pageFilter = new PageFilterFeats(); super({ dataSource: "data/feats.json", pageFilter, listClass: "feats", sublistClass: "subfeats", dataProps: ["feat"], isPreviewable: true, }); } getListItem (feat, ftI, isExcluded) { this._pageFilter.mutateAndAddToFilters(feat, isExcluded); const eleLi = document.createElement("div"); eleLi.className = `lst__row flex-col ${isExcluded ? "lst__row--blacklisted" : ""}`; const source = Parser.sourceJsonToAbv(feat.source); const hash = UrlUtil.autoEncodeHash(feat); eleLi.innerHTML = `<a href="#${hash}" class="lst--border lst__row-inner"> <span class="col-0-3 px-0 flex-vh-center lst__btn-toggle-expand self-flex-stretch">[+]</span> <span class="bold col-3-5 px-1">${feat.name}</span> <span class="col-3-5 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slAbility}</span> <span class="col-3 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slPrereq}</span> <span class="source col-1-7 text-center ${Parser.sourceJsonToColor(feat.source)} pr-0" title="${Parser.sourceJsonToFull(feat.source)}" ${BrewUtil.sourceJsonToStyle(feat.source)}>${source}</span> </a> <div class="flex ve-hidden relative lst__wrp-preview"> <div class="vr-0 absolute lst__vr-preview"></div> <div class="flex-col py-3 ml-4 lst__wrp-preview-inner"></div> </div>`; const listItem = new ListItem( ftI, eleLi, feat.name, { hash, source, ability: feat._slAbility, prerequisite: feat._slPrereq, }, { uniqueId: feat.uniqueId ? feat.uniqueId : ftI, isExcluded, }, ); eleLi.addEventListener("click", (evt) => this._list.doSelect(listItem, evt)); eleLi.addEventListener("contextmenu", (evt) => ListUtil.openContextMenu(evt, this._list, listItem)); return listItem; } handleFilterChange () { const f = this._filterBox.getValues(); this._list.filter(item => this._pageFilter.toDisplay(f, this._dataList[item.ix])); FilterBox.selectFirstVisible(this._dataList); } getSublistItem (feat, pinId) { const hash = UrlUtil.autoEncodeHash(feat); const $ele = $(`<div class="lst__row lst__row--sublist flex-col"> <a href="#${hash}" class="lst--border lst__row-inner"> <span class="bold col-4 pl-0">${feat.name}</span> <span class="col-4 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none" : ""}">${feat._slAbility}</span> <span class="col-4 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none" : ""} pr-0">${feat._slPrereq}</span> </a> </div>`) .contextmenu(evt => ListUtil.openSubContextMenu(evt, listItem)) .click(evt => ListUtil.sublist.doSelect(listItem, evt)); const listItem = new ListItem( pinId, $ele, feat.name, { hash, ability: feat._slAbility, prerequisite: feat._slPrereq, }, ); return listItem; } doLoadHash (id) { const feat = this._dataList[id]; $("#pagecontent").empty().append(RenderFeats.$getRenderedFeat(feat)); ListUtil.updateSelected(); } async pDoLoadSubHash (sub) { sub = this._filterBox.setFromSubHashes(sub); await ListUtil.pSetFromSubHashes(sub); } } const featsPage = new FeatsPage(); window.addEventListener("load", () => featsPage.pOnLoad());
jQuery(document).ready(function($){ var nameDefault = 'Your name...'; var emailDefault = 'Your email...'; var messageDefault = 'Your message...'; // Setting up existing forms setupforms(); function setupforms() { // Applying default values setupDefaultText('#name',nameDefault); setupDefaultText('#email',emailDefault); setupDefaultText('#message',messageDefault); // Focus / Blur check against defaults focusField('#name'); focusField('#email'); focusField('#message'); } function setupDefaultText(fieldID,fieldDefault) { $(fieldID).val(fieldDefault); $(fieldID).attr('data-default', fieldDefault); } function evalDefault(fieldID) { if($(fieldID).val() != $(fieldID).attr('data-default')) { return false; } else { return true; } } function hasDefaults(formType) { switch (formType) { case "contact" : if(evalDefault('#name') && evalDefault('#email') && evalDefault('#message')) { return true; } else { return false; } default : return false; } } function focusField(fieldID) { $(fieldID).focus(function(evaluation) { if(evalDefault(fieldID)) { $(fieldID).val(''); } }).blur(function(evaluation) { if(evalDefault(fieldID) || $(fieldID).val() === '') { $(fieldID).val($(fieldID).attr('data-default')); } }); } $('.button-submit').click(function(event) { event.preventDefault(); }); $('#submit-contact').bind('click', function(){ if(!hasDefaults('contact')) { $('#form-contact').submit(); } }); $("#form-contact").validate({ rules: { name: { required: true, minlength: 3 }, email: { required: true, email: true }, message: { required: true, minlength: 10 } }, messages: { name: { required: "Please enter your name.", minlength: "Name must have at least 3 characters." }, email: { required: "Please enter your email address.", email: "This is not a valid email address format." }, message: { required: "Please enter a message.", minlength: "Message must have at least 10 characters." } } }); function validateContact() { if(!$('#form-contact').valid()) { return false; } else { return true; } } $("#form-contact").ajaxForm({ beforeSubmit: validateContact, type: "POST", url: "assets/php/contact-form-process.php", data: $("#form-contact").serialize(), success: function(msg){ $("#form-message").ajaxComplete(function(event, request, settings){ if(msg == 'OK') // Message Sent? Show the 'Thank You' message { result = '<span class="form-message-success"><i class="icon-thumbs-up"></i> Your message was sent. Thank you!</span>'; clear = true; } else { result = '<span class="form-message-error"><i class="icon-thumbs-down"></i> ' + msg +'</span>'; clear = false; } $(this).html(result); if(clear == true) { $('#name').val(''); $('#email').val(''); $('#message').val(''); } }); } }); });
$(document).ready(function() { /* initialize the external events -----------------------------------------------------------------*/ $('#external-events div.external-event').each(function() { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim($(this).text()), // use the element's text as the event title className: $.trim($(this).attr("class").split(' ')[1]) // get the class name color[x] }; // store the Event Object in the DOM element so we can get to it later $(this).data('eventObject', eventObject); // make the event draggable using jQuery UI $(this).draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); }); /* initialize the calendar -----------------------------------------------------------------*/ var calendar = $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'agendaWeek,agendaDay' }, defaultView: 'agendaDay', timeFormat: 'H:mm{ - H:mm}', axisFormat: 'H:mm', minTime: '8:00', maxTime: '22:00', allDaySlot: false, monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'], dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], titleFormat: { month: 'yyyy MMMM', week: "yyyy'年' MMM d'日'{ '&#8212;'[ MMM] d'日' }", day: "dddd, yyyy'年' MMM d'日'" }, /*defaultEventMinutes: 120, */ selectable: true, selectHelper: true, select: function(start, end, allDay) { var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); calendar.fullCalendar('renderEvent', { title: type, start: start, end: end, allDay: allDay, className: color }, true // make the event "stick" ); calendar.fullCalendar('unselect'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }, editable: true, eventMouseover: function(event, domEvent) { /* for(var key in event){ $("<p>").text(key + ':' + event[key]).appendTo($("body")); }; */ var layer = '<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100"><a><img src="images/icon_edit.gif" title="edit" width="14" id="edbut'+event._id+'" border="0" style="padding-right:3px; padding-top:2px;" /></a><a><img src="images/icon_delete.png" title="delete" width="14" id="delbut'+event._id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a></div>'; $(this).append(layer); $("#delbut"+event._id).hide(); $("#delbut"+event._id).fadeIn(300); $("#delbut"+event._id).click(function() { calendar.fullCalendar('removeEvents', event._id); //$.post("delete.php", {eventId: event._id}); calendar.fullCalendar('refetchEvents'); }); $("#edbut"+event._id).hide(); $("#edbut"+event._id).fadeIn(300); $("#edbut"+event._id).click(function() { //var title = prompt('Current Event Title: ' + event.title + '\n\nNew Event Title: '); /* if(title){ $.post("update_title.php", {eventId: event.id, eventTitle: title}); calendar.fullCalendar('refetchEvents'); } */ var type = false; var color = false; var execute = function(){ $("input").each(function(){ (this.checked == true) ? type = $(this).val() : null; (this.checked == true) ? color = $(this).attr('id') : null; }); $("#dialog-form").dialog("close"); event.title = type; event.className = color; calendar.fullCalendar('updateEvent', event); calendar.fullCalendar('refetchEvents'); }; var cancel = function() { $("#dialog-form").dialog("close"); } var dialogOpts = { modal: true, position: "center", buttons: { "确定": execute, "取消": cancel } }; $("#dialog-form").dialog(dialogOpts); }); }, eventMouseout: function(calEvent, domEvent) { $("#events-layer").remove(); }, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function(date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.end = (date.getTime() + 7200000)/1000; copiedEventObject.allDay = false; // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); } }); });
#!/usr/bin/env node var app = require('./app'), config = require('./config'); app.set('port', process.env.PORT || config.app.port); var server = app.listen(app.get('port'), function() { "use strict"; console.log('Express server listening on port ' + server.address().port); });
"use strict"; /** * Storing multiple constant values inside of an object * Keep in mind the values in the object mean they can be modified * Which makes no sense for a constant, use wisely if you do this */ app.service('$api', ['$http', '$token', '$rootScope', '$sweetAlert', '$msg', 'SERVER_URL', function ($http, $token, $rootScope, $sweetAlert, $msg, SERVER_URL) { const SERVER_URI = SERVER_URL + 'api/'; var config = { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()} }; /* Authentication Service ----------------------------------------------*/ this.isAuthorized = function (module_name) { return $http.get(SERVER_URI + 'check_auth', { headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()}, params: {'module_name': module_name} }); }; this.authenticate = function (data) { return $http.post(SERVER_URI + 'login', data); }; this.resetPassword = function (email) { return $http.post(SERVER_URI + 'reset_password', email); }; this.exit = function () { $token.deleteFromAllStorage(); return $http.get(SERVER_URI + 'logout', {params: {user: $rootScope.user} }) }; /* User Service ----------------------------------------------*/ this.findMember = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'all_users', params.search, config); } return $http.get(SERVER_URI + 'all_users', config); }; this.removeMember = function (data) { return $http.delete(SERVER_URI + 'remove_profile/' + data, config); }; this.updateUserProfile = function (data) { return $http.put(SERVER_URI + 'update_profile', data, config); }; this.usersCount = function () { return $http.get(SERVER_URI + 'users_count', config); }; /* Shop Service ----------------------------------------------*/ this.makePayment = function (params) { config.params = params; return $http.get(SERVER_URI + 'execute_payment', config); }; /* Chat Service ----------------------------------------------*/ this.getChatList = function (params) { return $http.get(SERVER_URI+'chat_list', config); }; this.saveMessage = function(data) { return $http.post(SERVER_URI + 'save_message', data, config); }; this.getConversation = function () { }; /* Product Service ----------------------------------------------*/ this.products = function (params) { config.params = params; if (params.search) { return $http.post(SERVER_URI + 'product_list', params.search, config); } return $http.get(SERVER_URI + 'product_list', config); }; this.productDetail = function (id) { config.params = {id: id}; return $http.get(SERVER_URI + 'product_detail', config); }; this.buyProduct = function (params) { config.params = params; return $http.get(SERVER_URI + 'buy_product', config); }; this.handleError = function (res) { switch (res.status) { case 400: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 403: $sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR); break; case 500: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; case 503: $sweetAlert.error(res.statusText, $msg.SERVICE_UNAVAILABLE); break; case 404: $sweetAlert.error(res.statusText, $msg.NOT_FOUND_ERROR); break; default: $sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR); break; } }; }]);
/** * @file Link files. * @function filelink * @param {string} src - Source file (actual file) path. * @param {string} dest - Destination file (link) path. * @param {object} [options] - Optional settings. * @param {string} [options.type='symlink'] - Link type * @param {boolean} [options.mkdirp] - Make parent directories. * @param {boolean} [options.force] - Force to symlink or not. * @param {function} callback - Callback when done. */ 'use strict' const fs = require('fs') const argx = require('argx') const path = require('path') const {mkdirpAsync, existsAsync, statAsync} = require('asfs') const _cleanDest = require('./_clean_dest') const _followSymlink = require('./_follow_symlink') /** @lends filelink */ async function filelink (src, dest, options) { let args = argx(arguments) if (args.pop('function')) { throw new Error('Callback is no more supported. Use promise interface instead') } options = args.pop('object') || {} const cwd = options.cwd || process.cwd() src = path.resolve(cwd, args.shift('string')) dest = path.resolve(cwd, args.shift('string')) const type = options.type || 'symlink' const force = !!options.force const destDir = path.dirname(dest) src = await _followSymlink(src) if (options.mkdirp) { await mkdirpAsync(destDir) } else { let exists = await existsAsync(destDir) if (!exists) { throw new Error(`Directory not exists: ${destDir}`) } } let srcName = path.relative(destDir, src) let destName = path.relative(destDir, dest) let before = (await existsAsync(dest)) && (await statAsync(dest)) if (force) { await _cleanDest(dest) } process.chdir(destDir) _doLinkSync(srcName, destName, type) process.chdir(cwd) let after = (await existsAsync(dest)) && (await statAsync(dest)) await new Promise((resolve) => process.nextTick(() => resolve())) let unchanged = (before && before.size) === (after && after.size) return !unchanged } module.exports = filelink function _doLinkSync (src, dest, type) { switch (type) { case 'link': fs.linkSync(src, dest) break case 'symlink': fs.symlinkSync(src, dest) break default: throw new Error('Unknown type:' + type) } }
// EXPRESS SERVER HERE // // BASE SETUP var express = require('express'), app = express(), bodyParser = require('body-parser'), cookieParser = require('cookie-parser'), session = require('express-session'), methodOverride = require('method-override'), // routes = require('./routes/routes'), morgan = require('morgan'), serveStatic = require('serve-static'), errorHandler = require('errorhandler'); // =========================CONFIGURATION===========================// // =================================================================// app.set('port', process.env.PORT || 9001); /* * Set to 9001 to not interfere with Gulp 9000. * If you're using Cloud9, or an IDE that uses a different port, process.env.PORT will * take care of your problems. You don't need to set a new port. */ app.use(serveStatic('app', {'index': 'true'})); // Set to True or False if you want to start on Index or not app.use('/bower_components', express.static(__dirname + '/bower_components')); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); app.use(morgan('dev')); app.use(cookieParser('secret')); app.use(session({secret: 'evernote now', resave: true, saveUninitialized: true})); app.use(function(req, res, next) { res.locals.session = req.session; next(); }); if (process.env.NODE_ENV === 'development') { app.use(errorHandler()); } // ==========================ROUTER=================================// // =================================================================// // ROUTES FOR THE API - RUN IN THE ORDER LISTED var router = express.Router(); // ------------- ROUTES ---------------- // // REGISTERING THE ROUTES app.use('/', router); // STARTING THE SERVER console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!'); app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed exports = module.exports = app; // This is needed otherwise the index.js for routes will not work
//Capturar possibles errors process.on('uncaughtException', function(err) { console.log(err); }); //Importar mòdul net var net = require('net') //Port d'escolta del servidor var port = 8002; //Crear servidor TCP net.createServer(function(socket){ socket.on('data', function(data){ //Parse dades JSON var json=JSON.parse(data); //Importar mòdul theThingsCoAP var theThingsCoAP = require('../../') //Crear client theThingsCoAP var client = theThingsCoAP.createClient() client.on('ready', function () { read(json.endDate) }) //Funció per llegir dades de la plataforma thethings.iO function read(endDate){ client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) { if (typeof data!=='undefined' && data!==null){ if (data.length > 0) { var dataSend="" var coma="," for (var i=0;i<=(data.length - 1);i++){ dataSend=dataSend+data[i].value+coma+data[i].datetime.split('T')[1]+coma } socket.write(dataSend); read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replace(/:/g, '').replace('T', '')) }else{ socket.write("</FINAL>"); } } }) } }); //Configuració del port en el servidor TCP }).listen(port);
import { GET_WAREHOUSES_FULL_LIST, GET_WAREHOUSE, GET_COMPANIES, GET_SUPERVISORS } from '../actions/warehouses'; import humanize from 'humanize'; import Moment from 'moment'; const INITIAL_STATE = { warehousesList: [], warehouseDetail: {}, warehouseId: 0, companiesList: [], supervisorsList: [] }; export default function(state = INITIAL_STATE, action) { switch(action.type) { case GET_WAREHOUSES_FULL_LIST: return { ...state, warehousesList: action.payload.data.map(function(warehouse) { return { company: warehouse.company, supervisor: warehouse.supervisor, email: warehouse.email, telephone: warehouse.telephone, address: warehouse.address, contact_name: warehouse.contact_name, action: warehouse.id }; }) }; case GET_WAREHOUSE: return { ...state, warehouseDetail: { company: action.payload.data[0].company_id, supervisor: action.payload.data[0].supervisor_id, name: action.payload.data[0].name, email: action.payload.data[0].email, telephone: action.payload.data[0].telephone, address: action.payload.data[0].address, tax: action.payload.data[0].tax, contact_name: action.payload.data[0].contact_name }, warehouseId: action.payload.data[0].id } case GET_COMPANIES: return { ...state, companiesList: action.payload.data.map(function(company) { return { value: company.id, label: company.name } }) } case GET_SUPERVISORS: return { ...state, supervisorsList: action.payload.data.map(function(supervisor) { return { value: supervisor.id, label: supervisor.name } }) } default: return state; } }
dhtmlXForm.prototype.items.calendar = { render: function(item, data) { var t = this; item._type = "calendar"; item._enabled = true; this.doAddLabel(item, data); this.doAddInput(item, data, "INPUT", "TEXT", true, true, "dhxform_textarea"); item.childNodes[item._ll?1:0].childNodes[0]._idd = item._idd; item._f = (data.dateFormat||"%d-%m-%Y"); // formats item._f0 = (data.serverDateFormat||item._f); // formats for save-load, if set - use them for saving and loading only item._c = new dhtmlXCalendarObject(item.childNodes[item._ll?1:0].childNodes[0], data.skin||item.getForm().skin||"dhx_skyblue"); item._c._nullInInput = true; // allow null value from input item._c.enableListener(item.childNodes[item._ll?1:0].childNodes[0]); item._c.setDateFormat(item._f); if (!data.enableTime) item._c.hideTime(); if (!isNaN(data.weekStart)) item._c.setWeekStartDay(data.weekStart); if (typeof(data.calendarPosition) != "undefined") item._c.setPosition(data.calendarPosition); item._c._itemIdd = item._idd; item._c.attachEvent("onBeforeChange", function(d) { if (item._value != d) { // call some events if (item.checkEvent("onBeforeChange")) { if (item.callEvent("onBeforeChange",[item._idd, item._value, d]) !== true) { return false; } } // accepted item._value = d; t.setValue(item, d); item.callEvent("onChange", [this._itemIdd, item._value]); } return true; }); this.setValue(item, data.value); return this; }, getCalendar: function(item) { return item._c; }, setSkin: function(item, skin) { item._c.setSkin(skin); }, setValue: function(item, value) { if (!value || value == null || typeof(value) == "undefined" || value == "") { item._value = null; item.childNodes[item._ll?1:0].childNodes[0].value = ""; } else { item._value = (value instanceof Date ? value : item._c._strToDate(value, item._f0)); item.childNodes[item._ll?1:0].childNodes[0].value = item._c._dateToStr(item._value, item._f); } item._c.setDate(item._value); window.dhtmlXFormLs[item.getForm()._rId].vals[item._idd] = item.childNodes[item._ll?1:0].childNodes[0].value; }, getValue: function(item, asString) { var d = item._c.getDate(); if (asString===true && d == null) return ""; return (asString===true?item._c._dateToStr(d,item._f0):d); }, destruct: function(item) { // unload calendar instance item._c.unload(); item._c = null; try {delete item._c;} catch(e){} item._f = null; try {delete item._f;} catch(e){} item._f0 = null; try {delete item._f0;} catch(e){} // remove custom events/objects item.childNodes[item._ll?1:0].childNodes[0]._idd = null; // unload item this.d2(item); item = null; } }; (function(){ for (var a in {doAddLabel:1,doAddInput:1,doUnloadNestedLists:1,setText:1,getText:1,enable:1,disable:1,isEnabled:1,setWidth:1,setReadonly:1,isReadonly:1,setFocus:1,getInput:1}) dhtmlXForm.prototype.items.calendar[a] = dhtmlXForm.prototype.items.input[a]; })(); dhtmlXForm.prototype.items.calendar.d2 = dhtmlXForm.prototype.items.input.destruct; dhtmlXForm.prototype.getCalendar = function(name) { return this.doWithItem(name, "getCalendar"); };
let charLS; function jpegLSDecode (data, isSigned) { // prepare input parameters const dataPtr = charLS._malloc(data.length); charLS.writeArrayToMemory(data, dataPtr); // prepare output parameters const imagePtrPtr = charLS._malloc(4); const imageSizePtr = charLS._malloc(4); const widthPtr = charLS._malloc(4); const heightPtr = charLS._malloc(4); const bitsPerSamplePtr = charLS._malloc(4); const stridePtr = charLS._malloc(4); const allowedLossyErrorPtr = charLS._malloc(4); const componentsPtr = charLS._malloc(4); const interleaveModePtr = charLS._malloc(4); // Decode the image const result = charLS.ccall( 'jpegls_decode', 'number', ['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number'], [dataPtr, data.length, imagePtrPtr, imageSizePtr, widthPtr, heightPtr, bitsPerSamplePtr, stridePtr, componentsPtr, allowedLossyErrorPtr, interleaveModePtr] ); // Extract result values into object const image = { result, width: charLS.getValue(widthPtr, 'i32'), height: charLS.getValue(heightPtr, 'i32'), bitsPerSample: charLS.getValue(bitsPerSamplePtr, 'i32'), stride: charLS.getValue(stridePtr, 'i32'), components: charLS.getValue(componentsPtr, 'i32'), allowedLossyError: charLS.getValue(allowedLossyErrorPtr, 'i32'), interleaveMode: charLS.getValue(interleaveModePtr, 'i32'), pixelData: undefined }; // Copy image from emscripten heap into appropriate array buffer type const imagePtr = charLS.getValue(imagePtrPtr, '*'); if (image.bitsPerSample <= 8) { image.pixelData = new Uint8Array(image.width * image.height * image.components); image.pixelData.set(new Uint8Array(charLS.HEAP8.buffer, imagePtr, image.pixelData.length)); } else if (isSigned) { image.pixelData = new Int16Array(image.width * image.height * image.components); image.pixelData.set(new Int16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } else { image.pixelData = new Uint16Array(image.width * image.height * image.components); image.pixelData.set(new Uint16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length)); } // free memory and return image object charLS._free(dataPtr); charLS._free(imagePtr); charLS._free(imagePtrPtr); charLS._free(imageSizePtr); charLS._free(widthPtr); charLS._free(heightPtr); charLS._free(bitsPerSamplePtr); charLS._free(stridePtr); charLS._free(componentsPtr); charLS._free(interleaveModePtr); return image; } function initializeJPEGLS () { // check to make sure codec is loaded if (typeof CharLS === 'undefined') { throw new Error('No JPEG-LS decoder loaded'); } // Try to initialize CharLS // CharLS https://github.com/cornerstonejs/charls if (!charLS) { charLS = CharLS(); if (!charLS || !charLS._jpegls_decode) { throw new Error('JPEG-LS failed to initialize'); } } } function decodeJPEGLS (imageFrame, pixelData) { initializeJPEGLS(); const image = jpegLSDecode(pixelData, imageFrame.pixelRepresentation === 1); // throw error if not success or too much data if (image.result !== 0 && image.result !== 6) { throw new Error(`JPEG-LS decoder failed to decode frame (error code ${image.result})`); } imageFrame.columns = image.width; imageFrame.rows = image.height; imageFrame.pixelData = image.pixelData; return imageFrame; } export default decodeJPEGLS; export { initializeJPEGLS };
//= require ./ace/ace //= require ./ace/mode-ruby //= require ./ace/theme-tomorrow //= require ./ace/ext-whitespace $(function() { var editor = ace.edit("editor"); editor.setTheme("ace/theme/tomorrow"); editor.getSession().setMode("ace/mode/ruby"); editor.getSession().setTabSize(2); editor.getSession().setUseSoftTabs(true); $("form").submit(function() { $("#content").val(editor.getValue()); }); });
// @flow /* global document */ export default function injectStyles(styles: any) { const stylesElement = document.createElement('style'); stylesElement.innerText = styles.toString(); return stylesElement; }
import { test , moduleFor } from 'appkit/tests/helpers/module_for'; import Index from 'appkit/routes/index'; moduleFor('route:index', "Unit - IndexRoute"); test("it exists", function(){ ok(this.subject() instanceof Index); });
// ==UserScript== // @name Youtube BPM Meter // @version 1.3 // @updateURL https://raw.githubusercontent.com/Greeniac916/YoutubeBPM/master/youtube-bpm.js // @description Plugin adding beat counter to Youtube // @author Greeniac916 // @match https://www.youtube.com/* // @grant none // @require http://code.jquery.com/jquery-latest.js // ==/UserScript== var playButton = $(".ytp-play-button"); var bpmDelay = 0; var beats = 0; var interval, loadInt; function setup() { //Create HTML String Elements var card = "<div id='bpm-header' class='yt-card yt-card-has-padding'></div>"; var input = "<input id='bpm-input' placeholder='Enter BPM' type='number' style='vertical-align: middle'>"; var submit = "<input id='bpm-btn' type='button' value='Submit' style='vertical-align: middle'>"; var reset = "<input id='rst-btn' type='button' value='Reset' style='vertical-align: middle'>"; var output = "<span id='span-beats-text' style='float: right; vertical-align: middle;'>Beats: 0</span>"; //Insert Card Div $("#watch7-content").prepend(card); //Insert HTML elements to card $("#bpm-header").append(input); $("#bpm-header").append(submit); $("#bpm-header").append(reset); $("#bpm-header").append(output); //Bind Buttons $("#bpm-btn").bind("click", function() { var bpm = $("#bpm-input")[0].value; bpmDelay = 60000 / bpm; //Converts BPM to milisecond intervals clearInterval(interval); counter(); }); $("#rst-btn").bind("click", function() { beats = 0; display(0); }); } function display(value) { $("#span-beats-text")[0].textContent = "Beats: " + value; } function counter() { interval = setInterval(function() { display(beats); if (playButton.attr("aria-label") == "Pause") { //If youtube paying video beats++; } }, bpmDelay); } function waitForElement(elementPath, callBack){ window.setTimeout(function(){ if($(elementPath).length){ callBack(elementPath, $(elementPath)); }else{ waitForElement(elementPath, callBack); } },500); } function load() { console.log("Loading plugin."); playButton.click(); setup(); $(".video-list-item").bind("click", function() { waitForElement("#progress", function() { waitForElement("#eow-title", load); }); }); $(".yt-lockup").bind("click", function() { waitForElement("#progress", function() { waitForElement("#eow-title", load); }); }); } (function() { 'use strict'; load(); })();
/** * Copyright (c) 2015-present, Pavel Aksonov * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. * */ import React, { Component, PropTypes, } from 'react'; import NavigationExperimental from 'react-native-experimental-navigation'; import Actions, { ActionMap } from './Actions'; import getInitialState from './State'; import Reducer, { findElement } from './Reducer'; import DefaultRenderer from './DefaultRenderer'; import Scene from './Scene'; import * as ActionConst from './ActionConst'; const { RootContainer: NavigationRootContainer, } = NavigationExperimental; const propTypes = { dispatch: PropTypes.func, }; class Router extends Component { constructor(props) { super(props); this.state = {}; this.renderNavigation = this.renderNavigation.bind(this); this.handleProps = this.handleProps.bind(this); } componentDidMount() { this.handleProps(this.props); } componentWillReceiveProps(props) { this.handleProps(props); } handleProps(props) { let scenesMap; if (props.scenes) { scenesMap = props.scenes; } else { let scenes = props.children; if (Array.isArray(props.children) || props.children.props.component) { scenes = ( <Scene key="__root" hideNav {...this.props} > {props.children} </Scene> ); } scenesMap = Actions.create(scenes, props.wrapBy); } // eslint-disable-next-line no-unused-vars const { children, styles, scenes, reducer, createReducer, ...parentProps } = props; scenesMap.rootProps = parentProps; const initialState = getInitialState(scenesMap); const reducerCreator = props.createReducer || Reducer; const routerReducer = props.reducer || ( reducerCreator({ initialState, scenes: scenesMap, })); this.setState({ reducer: routerReducer }); } renderNavigation(navigationState, onNavigate) { if (!navigationState) { return null; } Actions.get = key => findElement(navigationState, key, ActionConst.REFRESH); Actions.callback = props => { const constAction = (props.type && ActionMap[props.type] ? ActionMap[props.type] : null); if (this.props.dispatch) { if (constAction) { this.props.dispatch({ ...props, type: constAction }); } else { this.props.dispatch(props); } } return (constAction ? onNavigate({ ...props, type: constAction }) : onNavigate(props)); }; return <DefaultRenderer onNavigate={onNavigate} navigationState={navigationState} />; } render() { if (!this.state.reducer) return null; return ( <NavigationRootContainer reducer={this.state.reducer} renderNavigation={this.renderNavigation} /> ); } } Router.propTypes = propTypes; export default Router;
var helper = require(__dirname + '/../test-helper'); var CopyFromStream = require(__dirname + '/../../../lib/copystream').CopyFromStream; var ConnectionImitation = function () { this.send = 0; this.hasToBeSend = 0; this.finished = 0; }; ConnectionImitation.prototype = { endCopyFrom: function () { assert.ok(this.finished++ === 0, "end shoud be called only once"); assert.equal(this.send, this.hasToBeSend, "at the moment of the end all data has to be sent"); }, sendCopyFromChunk: function (chunk) { this.send += chunk.length; return true; }, updateHasToBeSend: function (chunk) { this.hasToBeSend += chunk.length; return chunk; } }; var buf1 = new Buffer("asdfasd"), buf2 = new Buffer("q03r90arf0aospd;"), buf3 = new Buffer(542), buf4 = new Buffer("93jfemialfjkasjlfas"); test('CopyFromStream, start streaming before data, end after data. no drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation(); stream.on('drain', function () { assert.ok(false, "there has not be drain event"); }); stream.startStreamingToConnection(conn); assert.ok(stream.write(conn.updateHasToBeSend(buf1))); assert.ok(stream.write(conn.updateHasToBeSend(buf2))); assert.ok(stream.write(conn.updateHasToBeSend(buf3))); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); assert.equal(conn.hasToBeSend, conn.send); }); test('CopyFromStream, start streaming after end, end after data. drain event', function () { var stream = new CopyFromStream(); assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); var conn = new ConnectionImitation() assert.ok(!stream.write(conn.updateHasToBeSend(buf1))); assert.ok(!stream.write(conn.updateHasToBeSend(buf2))); assert.ok(!stream.write(conn.updateHasToBeSend(buf3))); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); stream.startStreamingToConnection(conn); assert.equal(conn.hasToBeSend, conn.send); }); test('CopyFromStream, start streaming between data chunks. end after data. drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.startStreamingToConnection(conn); stream.write(conn.updateHasToBeSend(buf3)); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); }); test('CopyFromStream, start sreaming before end. end stream with data. drain event', function () { var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.write(conn.updateHasToBeSend(buf3)); stream.startStreamingToConnection(conn); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); }); test('CopyFromStream, start streaming after end. end with data. drain event', function(){ var stream = new CopyFromStream(); var conn = new ConnectionImitation() assert.emits(stream, 'drain', function() {}, 'drain have to be emitted'); stream.write(conn.updateHasToBeSend(buf1)); stream.write(conn.updateHasToBeSend(buf2)); stream.write(conn.updateHasToBeSend(buf3)); stream.startStreamingToConnection(conn); assert.ok(stream.writable, "stream has to be writable"); stream.end(conn.updateHasToBeSend(buf4)); stream.startStreamingToConnection(conn); assert.equal(conn.hasToBeSend, conn.send); assert.ok(!stream.writable, "stream has not to be writable"); stream.end(); });
function main () { const ad_el = document.getElementById('bsa-cpc') if (!ad_el || innerWidth < 800) { // if no ad element or element hidden, don't load buysellads return } const script = document.createElement('script') script.onload = () => { if (_bsa.isMobile()) { // bsa doesn't show ads on mobile, hide th box ad_el.remove() return } _bsa.init('default', 'CK7ITKJU', 'placement:pydantic-docshelpmanualio', { target: '#bsa-cpc', align: 'horizontal', }) ad_el.classList.add('loaded') } script.src = 'https://m.servedby-buysellads.com/monetization.js' document.head.appendChild(script) } main()
var g_data; var margin = {top: 40, right: 45, bottom: 60, left: 60}, width = 460 - margin.left - margin.right, height = 436 - margin.top - margin.bottom; var xValue = function(d) { return d.condition;}; var x = d3.scalePoint().range([20, width-20]) var xAxis = d3.axisBottom() .scale(x); x.domain(["control","GI.1_12hpi","GI.1_24hpi","GI.2_12hpi","GI.2_24hpi"]); var y = d3.scaleLinear().range([height, 0]); var yAxis = d3.axisLeft() .scale(y) .ticks(10); var tool = d3.select("body").append("div") .attr("class", "tooltip") .style("opacity", 0); var svg = d3.select("div#rab_gene_scatter").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // add the x axis svg.append("g") .attr("class", "x_axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text") .style("font-size", "12px") .style("font-family", "sans-serif") .style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", "rotate(-45)"); // add the y axis svg.append("g") .attr("class", "y_axis") .call(yAxis); // y axis text label svg.append("text") .attr("transform", "rotate(-90)") .attr("y", 0 - margin.left) .attr("x",0 - (height / 2)) .attr("dy", "1em") .style("text-anchor", "middle") .text("Reads per Kilobase per Million (rpkm)"); // draw legend var legend = svg.selectAll(".legend") .data(["adult", "kitten"]) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); // draw legend colored circles legend.append("circle") .attr("cx", width) .attr("cy", 6) .attr("r", 5) .style("fill", function(d) { if (d == "kitten") { return "steelblue"; } else { return "red"; }}); // draw legend text legend.append("text") .attr("x", width + 8) .attr("y", 6) .attr("dy", ".35em") .style("text-anchor", "start") .text(function(d) { return d;}) // read in data // global variable to check if datafile is already loaded // if its already loaded don't want to waste time re-loading // also includes a boolean if a gene should be plotted following data load var loaded_data = "not_loaded"; function load_scatter_data(data_file, plot_gene, new_gene){ if(loaded_data != data_file){ console.log("loading new file"); $('#current_gene_name').text("LOADING..."); d3.tsv(data_file, function(data) { data.forEach(function(d) { d.rpkm = +d.rpkm; }); g_data = data; loaded_data = data_file; $('#current_gene_name').text("Expression scatter plot"); if(plot_gene == true){ update_plot(new_gene); return; } }); }; if(plot_gene == true){ update_plot(new_gene); return; } }; function update_plot(gene_name){ // filter the data for this particular gene var filt_data = g_data.filter(function(d) { return d.gene == gene_name}); y.domain([0, d3.max(filt_data, function(d) { return d.rpkm; })]); // Select what we want to change var scatter_points = svg.selectAll(".matts_bar") .data(filt_data) // Make the update changes //UPDATE scatter_points.transition().duration(1000) .attr("cy", function(d) { return y(d.rpkm); }); // add new spots from the enter selection // note this will only happen once in this case // ENTER scatter_points.enter() .append("circle") .style("fill", function(d) { if (d.age == "kitten") { return "steelblue"; } else { return "red"; }}) .attr("class", "matts_bar") .attr("cx", function(d) { return x(d.condition); }) .attr("r", 5) .on("mouseover", function(d) { d3.select(this).classed("hover", true); tool.transition() .duration(0) .style("opacity", .9); tool .html(d.sample) .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 28) + "px"); }) .on("mouseout", function(d) { d3.select(this).classed("hover", false); tool.transition() .duration(0) .style("opacity", 0); }) .transition().duration(1000).attr("cy", function(d) { return y(d.rpkm); }); // no need for an EXIT section // update the y axis info svg.select(".y_axis") .transition() .duration(1000) .call(yAxis); // update gene name in window $('#current_gene_name').text(gene_name); }
import React from 'react'; import ReactDOM from 'react-dom'; import ReactDOMServer from 'react-dom/server'; import { Router, RouterContext, match, browserHistory, createMemoryHistory } from 'react-router'; import HtmlBase from './pages/html-base'; import routes from './routes'; if (typeof document !== 'undefined') { const outlet = document.getElementById('outlet'); ReactDOM.render(<Router history={browserHistory} routes={routes} />, outlet); } // This is our 'server' rendering export default (locals, callback) => { const history = createMemoryHistory(); const location = history.createLocation(locals.path); // This is from the webpack plugin match({ routes, location }, (error, redirectLocation, renderProps) => { // entire page rendering let html = ReactDOMServer.renderToStaticMarkup(<HtmlBase><RouterContext {...renderProps} /></HtmlBase>) callback(null, '<!DOCTYPE html>' + html); }); };
/** * Template literals are a way to more easily achieve string concatenation. * Template literals are defined using back ticks (``). * Placeholders are indicated by using a ${variable} * Function tags are used to reference functions. Tags are a very handy featurs as they can * be used to protect against cross-site scripting by html encoding, tags to support localization, etc */ describe('template literals', function() { it('can use placeholders', function() { let a = 'hello'; let b = 'world'; let result = `${a} ${b}`; console.log(result); expect(result).toBe('hello world'); }); it('can use function tags', function() { function doStuff(...words) { let text = ''; words.forEach(function(word) { text += `${word} `; }); return text.toUpperCase(); } let result = doStuff('hello', 'world'); console.log(result); expect(result).toBe('HELLO WORLD '); }); }); // describe('spread operator', function() { // it('', function() { // }); // it('', function() { // }); // });
export function up(queryInterface, Sequelize) { return Promise.all([ queryInterface.changeColumn('memberships', 'approved', { type: Sequelize.BOOLEAN, defaultValue: null, }), queryInterface.changeColumn('quotes', 'approved', { type: Sequelize.BOOLEAN, defaultValue: null, }), ]); } export function down(queryInterface, Sequelize) { return Promise.all([ queryInterface.changeColumn('memberships', 'approved', { type: Sequelize.BOOLEAN, defaultValue: false, }), queryInterface.changeColumn('quotes', 'approved', { type: Sequelize.BOOLEAN, defaultValue: false, }), ]); }
import express from 'express'; import path from 'path'; let app = express(); /*** Webpack imports ***/ import webpack from 'webpack'; import WebpackDevServer from 'webpack-dev-server'; import config from './webpack.config.js'; const webpackOptions = { publicPath: config.output.publicPath, // needed so that when going to the localhost:3000 it will load the contents // from this directory contentBase: config.devServer.contentBase, quiet: false, // hides all the bundling file names noInfo: true, // adds color to the terminal stats: { colors: true } }; const isDevelopment = process.env.NODE_ENV !== 'production'; const port = isDevelopment ? 3003 : process.env.PORT; const public_path = path.join(__dirname, 'public'); app.use(express.static(public_path)) // .get('/', function(req, res) { // res.sendFile('index.html', {root: public_path}) // }); /*** during development I am using a webpack-dev-server ***/ if(isDevelopment) { new WebpackDevServer(webpack(config), webpackOptions) .listen(port, 'localhost', function(err) { if (err) { console.log(err); } console.log(`Listening on port: ${port}`); }); } module.exports = app;
'use strict'; var path = require('path') , chai = require('chai') , expect = chai.expect , sumChildren = require(path.join(__dirname, '..', 'lib', 'util', 'sum-children')) ; describe("simplifying timings lists", function () { it("should correctly reduce a simple list", function () { expect(sumChildren([[22, 42]])).equal(20); }); it("should accurately sum overlapping child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add another interval completely encompassed by the first intervals.push([ 5, 10]); // add another that starts within the first range but extends beyond intervals.push([11, 33]); // add a final interval that's entirely disjoint intervals.push([35, 39]); expect(sumChildren(intervals)).equal(37); }); it("should accurately sum partially overlapping child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add another interval completely encompassed by the first intervals.push([ 5, 10]); // add another that starts simultaneously with the first range but that extends beyond intervals.push([ 0, 33]); expect(sumChildren(intervals)).equal(33); }); it("should accurately sum partially overlapping, open-ranged child traces", function () { var intervals = []; // start with a simple interval intervals.push([ 0, 22]); // add a range that starts at the exact end of the first intervals.push([22, 33]); expect(sumChildren(intervals)).equal(33); }); });
import $ from 'jquery'; let hoverChildDirective = { bind: (el, binding) => { $(el) .on('mouseenter', function(event) { $(el).children('.icon').addClass(binding.value); }) .on('mouseleave', function(event) { $(el).children('.icon').removeClass(binding.value); }); } }; export { hoverChildDirective };
var theServersDao = require('../daos/ServersDao'); var ServerMatcherMiddleware = function (pReq, pRes, pNext) { 'use strict'; var ip = pReq.headers['x-forwarded-for'] || pReq.connection.remoteAddress; theServersDao.getServerIdByIp(ip, function (pData) { if (pData.error) { var server = { ip: ip }; theServersDao.createServer(server, function (pData) { pReq.body.server_id = pData.id; pNext(); }); } else { pReq.body.server_id = pData.id; pNext(); } }); }; module.exports = ServerMatcherMiddleware;
!(function() { 'use strict'; function ComponentLoader($window, $q) { var self = this; this.basePath = '.'; this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ]; this.loaded = { /*'svg-viewer':true'*/ }; this.loadAll = function() { var components = self.queue.map(function loadEach(component) { component.pending = true; return self.load(component); }) return $q.all(components); } this.load = function(component) { if (angular.isString(component)) { component = resolveComponent(component) } if (!component) throw new Error('The lazy component is not registered and cannot load') if (!component.name) throw new Error('The lazy component must register with name property and cannot load'); if (self.loaded[component.name]) { return $q.when(component); } var scripts = component.scripts.map(function scriptInComponent(path) { return loadItem(path, component); }); return $q.all(scripts).then(function(result) { component.pending = false; self.loaded[component.name] = true; if (angular.isFunction(component.run)) component.run.apply(component); return component; }); } function resolveComponent(name) { var match = self.queue.filter(function componentFilter(component) { return component.name === name; }); return match.length ? match[0] : null; } function loadItem(path, component) { var d = $q.defer(); var startPath = component.path || self.basePath; var newScriptTag = document.createElement('script'); newScriptTag.type = 'text/javascript'; newScriptTag.src = startPath ? startPath + '/' + path : path; console.log(component.path) newScriptTag.setAttribute('data-name', component.name) newScriptTag.addEventListener('load', function(ev) { d.resolve(component); }); newScriptTag.addEventListener('error', function(ev) { d.reject(component); }); $window.setTimeout(function() { if (component.pending) { throw new Error('Component ' + component.name + ' did not load in time.'); } }, 10000); document.head.appendChild(newScriptTag); return d.promise; } } ComponentLoader.$inject = ['$window', '$q']; angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader); })();
var url = require('url') , path = require('path') , fs = require('fs') , utils = require('./utils') , EventEmitter = require('events').EventEmitter exports = module.exports = Context function Context(app, req, res) { var self = this this.app = app this.req = req this.res = res this.done = this.done.bind(this) EventEmitter.call(this) var socket = res.socket res.on('finish', done) socket.on('error', done) socket.on('close', done) function done(err) { res.removeListener('finish', done) socket.removeListener('error', done) socket.removeListener('close', done) self.done(err) } } Context.prototype = { done: function(err) { if (this._notifiedDone === true) return if (err) { if (this.writable) { this.resHeaders = {} this.type = 'text/plain' this.status = err.code === 'ENOENT' ? 404 : (err.status || 500) this.length = Buffer.byteLength(err.message) this.res.end(err.message) } this.app.emit('error', err) } this._notifiedDone = true this.emit('done', err) }, throw: function(status, err) { status = status || 500 err = err || {} err.status = status err.message = err.message || status.toString() this.done(err) }, render: function *(view, locals) { var app = this.app , viewPath = path.join(app.viewRoot, view) , ext = path.extname(viewPath) , exts, engine, content, testPath, i, j if (!ext || (yield utils.fileExists(viewPath))) { for (i = 0; app.viewEngines[i]; i++) { exts = (app.viewEngines[i].exts || ['.' + app.viewEngines[i].name.toLowerCase()]) if (ext) { if (~exts.indexOf(ext)) { engine = app.viewEngines[i] break } continue } for (j = 0; exts[j]; j++) { testPath = viewPath + exts[j] if (yield utils.fileExists(testPath)) { viewPath = testPath engine = app.viewEngines[i] break } } } } if (!engine) return this.throw(500, new Error('View does not exist')) return yield engine.render(viewPath, locals) }, /* * opts: { path: ..., domain: ..., expires: ..., maxAge: ..., httpOnly: ..., secure: ..., sign: ... } */ cookie: function(name, val, opts) { if (!opts) opts = {} if (typeof val == 'object') val = JSON.stringify(val) if (this.secret && opts.sign) { val = this.app.cookies.prefix + this.app.cookies.sign(val, this.secret) } var headerVal = name + '=' + val + '; Path=' + (opts.path || '/') if (opts.domain) headerVal += '; Domain=' + opts.domain if (opts.expires) { if (typeof opts.expires === 'number') opts.expires = new Date(opts.expires) if (opts.expires instanceof Date) opts.expires = opts.expires.toUTCString() headerVal += '; Expires=' + opts.expires } if (opts.maxAge) headerVal += '; Max-Age=' + opts.maxAge if (opts.httpOnly) headerVal += '; HttpOnly' if (opts.secure) headerVal += '; Secure' this.setResHeader('Set-Cookie', headerVal) }, get writable() { var socket = this.res.socket return socket && socket.writable && !this.res.headersSent }, get path() { return url.parse(this.url).pathname }, set path(val) { var obj = url.parse(this.url) obj.pathname = val this.url = url.format(obj) }, get status() { return this._status }, set status(code) { this._status = this.res.statusCode = code }, get type() { return this.getResHeader('Content-Type') }, set type(val) { if (val == null) return this.removeResHeader('Content-Type') this.setResHeader('Content-Type', val) }, get length() { return this.getResHeader('Content-Length') }, set length(val) { if (val == null) return this.removeResHeader('Content-Length') this.setResHeader('Content-Length', val) }, get body() { return this._body }, set body(val) { this._body = val } } utils.extend(Context.prototype, EventEmitter.prototype) utils.proxy(Context.prototype, { req: { method : 'access', url : 'access', secure : 'getter', headers : ['getter', 'reqHeaders'], }, res: { _headers : ['access', 'resHeaders'], getHeader : ['invoke', 'getResHeader'], setHeader : ['invoke', 'setResHeader'], removeHeader : ['invoke', 'removeResHeader'] } })
var express = require('express'); var soapSave = require('../utils/soa_save_esig')('http://192.168.0.6:8001/soa-infra/services/default/SignatureService/SignatureService_ep?WSDL'); var router = express.Router(); /* GET users listing. */ router.get('/', function(req, res) { var sig = req.query; console.log(sig); if(!sig.userRoleType){ res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "need to supply userRoleType" }); return; } if (sig.req_type && sig.req_type == 'r'){ var inputData = { applicantId: sig.applicantId, formId: sig.formId, userRoleType: sig.userRoleType }; soapSave.retrieve(inputData,function (result ){ var b64string = result.signatureImage; if(b64string == null){ res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" }); } else{ var buf = new Buffer(b64string, 'base64'); var cacObj =JSON.parse( buf.toString('ascii') ); res.render('response', { title: 'MPSTD CAC Signature response', cacContent: JSON.stringify(cacObj.subject), cacSignature: JSON.stringify(cacObj.fingerprint), timeStamp: JSON.stringify(result.signatureDateTime) }); // console.log("base64 buffer length = " +buf.length); } } ); } else{//default Esing sign pad res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" }); } }); module.exports = router;
// Regular expression that matches all symbols in the Linear B Syllabary block as per Unicode v5.1.0: /\uD800[\uDC00-\uDC7F]/;
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var Session = require('express-session'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); // create session middleware var session = Session({ resave: true, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'love' // ??? }); var dashboard_routes = require('./routes/dashboard'); var test_routes = require('./routes/test'); var users_routes = require('./routes/users'); var regions_routes = require('./routes/regions'); var informations_routes = require('./routes/informations'); var commands_routes = require('./routes/commands'); var document_routes = require('./routes/documents'); var images_routes = require('./routes/images'); var authentications_routes = require('./routes/authentications'); var auth = require('./routes/auth'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); // uncomment after placing your favicon in /public app.use(favicon(path.join(__dirname, 'public', 'favicon.png'))); app.use(logger('dev')); /* Automatically parse json object in request, and store the parsing * result in `req.body`. If request is not json type (i.e., "Content-Type" * is not "application/json", it won't be parsed. */ app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use('/public', express.static(path.join(__dirname, 'public'))); // for logging // Each time a request reaches, log the verb, url, body of request. app.use(function(req, res, next) { console.log('===================================================='); console.log('Request:'); console.log(req.method, req.originalUrl); console.log(req.body); console.log('----------------------------------------------------'); next(); }); /* * Session control: * * Session only applies for /login, /login.do, /logout, and url starting with * /dashboard. * * 1. Add `session` middleware for these routes, which can automatically set * session information in `req.session` * 2. When a user log in through /login.do, store login information in session, * specifically, `req.session.user` * 3. Every time a request ask for /dashboard/*, check whether `req.session.user` * is set. If `req.session.user` is undefined, redirect to login page. * 4. When logging out, delete `req.session.user`. * */ app.get('/login', session, function(req, res, next) { res.render('login'); }); app.post('/login.do', session, function (req, res, next) { var username = req.body.username; var password = req.body.password; console.log('username =', username, 'password =', password); if (username == "admin" && password == "admin") { // store login information in session req.session.user = { username: 'admin', password: 'admin' }; res.redirect('/dashboard'); } else { res.redirect('/login'); } }); app.get('/logout', session, function(req, res, next) { // delete login information in session req.session.user = null; res.redirect('/login'); }); // routes, see routes/*.js app.use('/dashboard', session, function (req, res, next) { /* * If `req.session.user` exists, it means that user is already logged in. * Otherwise, we should redirect to login page. */ console.log('req.session = ', req.session); if (req.session.user || /^\/login/.test(req.url)) { console.log('next'); next(); } else { res.redirect('/login'); console.log('redirect'); } }, dashboard_routes); // routes for RESTful APIs app.use('/test', auth.forAllUsers, test_routes); app.use('/authentications', auth.forAllUsers, authentications_routes); app.use('/users', auth.forAllUsers, users_routes); app.use('/regions', auth.forAllUsers, regions_routes); app.use('/information', auth.forAllUsers, informations_routes); app.use('/commands', auth.forAllUsers, commands_routes); app.use('/documents', auth.forAllUsers, document_routes); app.use('/images', images_routes); // catch 404 and forward to error handler app.use(function (req, res, next) { res.status(404).send({ status: 404, message: req.url + ' Not Found' }); }); // error handlers /* development error handler, will print stacktrace * * this error handler can be triggered by `next(error)`, * where error is an `Error` object created by `new Error(message)` * * Example: * * function do_get(req, res, next) { * if (something_wrong) { * var error = new Error('some message'); * error.status = 503; * } else { * do_something(); * } * */ if (app.get('env') === 'development') { app.use(function (err, req, res, next) { console.log('caused development error handler'); if (err.status != 404) { console.log(err.message); console.log(err.stack); } var status = err.status || 500; res.status(status); res.send({ status: status, message: err.message, stack: err.stack, }); }); } // production error handler // no stacktraces leaked to user app.use(function (err, req, res, next) { console.log('caused production error handler'); res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
require.config( { //By default load any module IDs from js/lib baseUrl: "app/", //except, if the module ID starts with "app", //load it from the js/app directory. paths //config is relative to the baseUrl, and //never includes a ".js" extension since //the paths config could be for a directory. paths: { lib: "../lib", } } ); requirejs( ["lib/angular/angular"], function() { require( ["app"], function() { angular.element( document ).ready( function() { angular.bootstrap( document, ['dotaApp'] ); } ); } ); } );
import Ember from 'ember'; import ApplicationSerializer from 'ghost-admin/serializers/application'; import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin'; const {String: {pluralize}} = Ember; export default ApplicationSerializer.extend(EmbeddedRecordsMixin, { attrs: { roles: {embedded: 'always'}, lastLoginUTC: {key: 'last_login'}, createdAtUTC: {key: 'created_at'}, updatedAtUTC: {key: 'updated_at'} }, extractSingle(store, primaryType, payload) { let root = this.keyForAttribute(primaryType.modelName); let pluralizedRoot = pluralize(primaryType.modelName); payload[root] = payload[pluralizedRoot][0]; delete payload[pluralizedRoot]; return this._super(...arguments); }, normalizeSingleResponse(store, primaryModelClass, payload) { let root = this.keyForAttribute(primaryModelClass.modelName); let pluralizedRoot = pluralize(primaryModelClass.modelName); if (payload[pluralizedRoot]) { payload[root] = payload[pluralizedRoot][0]; delete payload[pluralizedRoot]; } return this._super(...arguments); } });
const type = { name: "array", structure: [ { name: "type", match: "^array$" }, { name: "content" }, ], child: "content", identify, validate, next, execute, }; module.exports = type; function identify({ current }) { const regexp = new RegExp("^array$"); if (current.content && current.type && Object.keys(current).length === 2 && Array.isArray(current.content) === false && typeof current.content === "object" && regexp.test(current.type)) { return true; } return false; } function validate({ current, ruleConfig, parents, processor }) { const type = processor.identify({ current: current.content, ruleConfig, parents }); type.validate({ current: current.content, ruleConfig, parents: [...parents, type.child], processor }); return true; } function next(current) { return current.content ? current.content : null; } function execute({ target, source, rule, processor }) { return new Promise(async (resolve, reject) => { try { if (Array.isArray(source.current)) { for (const key in source.current) { const value = source.current[key]; target.current[key] = await processor.executeNext({ // eslint-disable-line no-await-in-loop rule: { ...rule, current: rule.current.content }, source: { ...source, current: value }, target: { ...target, current: target.current[key] }, }); } } resolve(target.current); } catch (error) { reject(error); } }); }
import React, { Component } from 'react'; import InputBar from "../containers/input_bar"; import PriceList from "../containers/price_list"; import StateTax from "../containers/state_tax"; import TipPercent from "../containers/tip_percent"; import FinalAmount from "../containers/final_amount"; export default class App extends Component { render() { return ( <div> <InputBar /> <div className="container middle-area"> <div className="row"> <PriceList /> <StateTax /> <TipPercent /> </div> </div> <FinalAmount /> </div> ); } }
/*jshint node:true */ "use strict"; var extend = require('util')._extend; module.exports = function (task, args, done) { var that = this, params, finish, cb, isDone = false, start, r, streamReturn = []; finish = function (err, results, runMethod) { var hrDuration = process.hrtime(start); if (isDone) { return; } isDone = true; var duration = hrDuration[0] + (hrDuration[1] / 1e9); // seconds done.call(that, err, results, { duration: duration, // seconds hrDuration: hrDuration, // [seconds,nanoseconds] runMethod: runMethod }); }; cb = function (err, results) { finish(err, results, 'callback'); }; params = extend([], args); params.push(cb); try { start = process.hrtime(); r = task.apply(this, params); } catch (err) { finish(err, null, 'catch'); } if (r && typeof r.done === 'function') { // wait for promise to resolve // FRAGILE: ASSUME: Promises/A+, see http://promises-aplus.github.io/promises-spec/ r.done(function (results) { finish(null, results, 'promise'); }, function(err) { finish(err, null, 'promise'); }); } else if (r && typeof r.on === 'function' && typeof r.once === 'function' && typeof r.end === 'function' && r.pipe) { // wait for stream to end r.on('data', function (results) { // return an array of results because we must listen to all the traffic through the stream if (typeof results !== 'undefined') { streamReturn.push(results); } }); r.once('error', function (err) { finish(err, null, 'stream'); }); r.once('end', function () { finish(null, streamReturn, 'stream'); }); // start stream if (typeof args !== 'undefined' && args !== null) { r.write.apply(that, args); } } else if (task.length < params.length) { // synchronous, function took in args.length parameters, and the callback was extra finish(null, r, 'sync'); //} else { // FRAGILE: ASSUME: callback } };
import path from 'node:path'; import test from 'ava'; import slash from 'slash'; import { isIgnoredByIgnoreFiles, isIgnoredByIgnoreFilesSync, isGitIgnored, isGitIgnoredSync, } from '../ignore.js'; import { PROJECT_ROOT, getPathValues, } from './utilities.js'; const runIsIgnoredByIgnoreFiles = async (t, patterns, options, fn) => { const promisePredicate = await isIgnoredByIgnoreFiles(patterns, options); const syncPredicate = isIgnoredByIgnoreFilesSync(patterns, options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isIgnoredByIgnoreFilesSync() result is different than isIgnoredByIgnoreFiles()', ); return promiseResult; }; const runIsGitIgnored = async (t, options, fn) => { const promisePredicate = await isGitIgnored(options); const syncPredicate = isGitIgnoredSync(options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isGitIgnoredSync() result is different than isGitIgnored()', ); return promiseResult; }; test('ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/gitignore'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['bar.js']; t.deepEqual(actual, expected); } }); test('ignore - mixed path styles', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(slash(path.resolve(directory, 'foo.js'))), ), ); } }); test('ignore - os paths', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(path.resolve(directory, 'foo.js')), ), ); } }); test('negative ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/negative'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['foo.js']; t.deepEqual(actual, expected); } }); test('multiple negation', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/multiple-negation'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => [ '!!!unicorn.js', '!!unicorn.js', '!unicorn.js', 'unicorn.js', ].filter(file => !isIgnored(file)), ); const expected = ['!!unicorn.js', '!unicorn.js']; t.deepEqual(actual, expected); } }); test('check file', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const ignoredFile of getPathValues(path.join(directory, 'foo.js'))) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(ignoredFile), ), ); } for (const notIgnoredFile of getPathValues(path.join(directory, 'bar.js'))) { t.false( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(notIgnoredFile), ), ); } }); test('custom ignore files', async t => { const cwd = path.join(PROJECT_ROOT, 'fixtures/ignore-files'); const files = [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', 'not-ignored.js', ]; t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.eslintignore', {cwd}, isEslintIgnored => files.filter(file => isEslintIgnored(file)), ), [ 'ignored-by-eslint.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.prettierignore', {cwd}, isPrettierIgnored => files.filter(file => isPrettierIgnored(file)), ), [ 'ignored-by-prettier.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.{prettier,eslint}ignore', {cwd}, isEslintOrPrettierIgnored => files.filter(file => isEslintOrPrettierIgnored(file)), ), [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', ], ); });
/* jshint expr:true */ import Ember from 'ember'; const { run } = Ember; import { expect } from 'chai'; import { describeModel, it } from 'ember-mocha'; import { beforeEach } from 'mocha'; let store; let m; describeModel( 'parent', 'Unit | Model | foo', { // Specify the other units that are required for this test. needs: ['model:child', 'model:pet'], }, function() { beforeEach( function () { store = this.store(); return run(() => { store.pushPayload({ data: null, included: [ { id: '1', type: 'parents', relationships: { children: { data: [ {id: '1', type: 'children'} ] } } }, { id: '1', type: 'children' }, { id: '2', type: 'children' }, { id: '1', type: 'pets' }, { id: '2', type: 'pets' } ] }); }); }); // Replace this with your real tests. it('parent stains itself', function() { const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.set('name', 'asdf'); }); m = "Parent should be dirty after updating an attribute on itself"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('dirty child stains parent', function() { const child = store.peekRecord('child', '1'); const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { child.set('name', 'foo'); }); m = "Parent should be dirty after updating an attribute on child"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('parent stains when children relationship is updated', function() { const parent = store.peekRecord('parent', '1'); const child2 = store.peekRecord('child', '2'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.get('children').pushObject(child2); }); m = "Parent should be dirty after adding another child"; expect(parent.get('hasDirtyAttributes'), m).true; }); } );
import { mediaPreview } from 'mtt-blog/helpers/media-preview'; import { module, test } from 'qunit'; module('Unit | Helper | media preview'); // Replace this with your real tests. test('it works', function(assert) { let result = mediaPreview([42]); assert.ok(result); });
/*============================= = Views = =============================*/ App.Views.UserInfo = Backbone.View.extend({ el: $('#user-info'), events: { "click #settings" : "clickSettings", "click #logout" : "clickLogout" }, clickLogout: function(event) { $.ajax({ url: 'auth/logout', type: 'get', dataType: 'json', success: function(data) { if (data.result == 'Success') { window.location = '/'; //Reload index page } else { alert('Logout failed'); //Alert on fail } }, error: function (xhr, ajaxOptions, thrownError) { console.log('Logout failed (hard)'); } }); }, clickSettings: function(event) { console.log('Settings clicked'); } });
// Generated by CoffeeScript 1.10.0 var AppController, MainController, ModalNewDeckController, NavController; AppController = (function() { function AppController($scope) { this.scope = $scope; this.scope.$on('search', function(term) { return console.log(term); }); $scope.$on('deckHasBeenSelected', function(deck) { $scope.currentDeck = deck.targetScope.currentDeck; return $scope.$broadcast('currentDeckHasChanged'); }); } return AppController; })(); NavController = (function() { function NavController($scope, $uibModal, $localStorage) { if (!$localStorage.decks) { $localStorage.decks = []; } $scope.decks = $localStorage.decks; $scope.selectDeck = function(deck) { $scope.currentDeck = deck; return $scope.$emit('deckHasBeenSelected', $scope.currentDeck); }; $scope.selectDeck($scope.decks[0]); $scope.addDeck = function($scope) { var modal; modal = $uibModal.open({ templateUrl: "template/modalNewDeck.html", controller: "modalNewDeckController" }); return modal.result.then(function(deckName) { return $localStorage.decks.push(new Deck(deckName)); }); }; } return NavController; })(); ModalNewDeckController = (function() { function ModalNewDeckController($scope, $uibModalInstance) { $scope.cancel = function() { return $uibModalInstance.dismiss("cancel"); }; $scope.submit = function() { return $uibModalInstance.close($scope.name); }; } return ModalNewDeckController; })(); MainController = (function() { function MainController($scope, $localStorage, $http) { $scope.cards = []; $scope.$on("currentDeckHasChanged", function(e) { $scope.currentDeck = e.targetScope.currentDeck; return $scope.load(); }); $scope.load = function() { return $scope.cards = $scope.currentDeck.cards; }; $scope.addNewCard = function() { $scope.cards.push(new Card($scope.title, $scope.description)); $scope.title = ""; return $scope.description = ""; }; } return MainController; })(); myApp.controller('appController', AppController); myApp.controller('navController', NavController); myApp.controller('mainController', MainController); myApp.controller('modalNewDeckController', ModalNewDeckController);
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var logLevels = { TRACE: 'TRACE', INFO: 'INFO', WARN: 'WARN', ERROR: 'ERROR' }; function _log(category, level) { var _console2; var now = (0, _moment2.default)().format(); for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (level === logLevels.ERROR) { var _console; return (_console = console).error.apply(_console, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } return (_console2 = console).log.apply(_console2, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } function Logger(category, requestId) { this.category = category; this.requestId = requestId; } function createLogLevel(level) { return function logWithLevel() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (this.requestId) { _log.apply(undefined, [this.category, level, 'RequestId: ' + this.requestId].concat(args)); } _log.apply(undefined, [this.category, level].concat(args)); }; } Logger.prototype.trace = createLogLevel(logLevels.TRACE); Logger.prototype.info = createLogLevel(logLevels.INFO); Logger.prototype.warn = createLogLevel(logLevels.WARN); Logger.prototype.error = createLogLevel(logLevels.ERROR); Logger.prototype.log = function log(level) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } if ((0, _lodash.size)(args) === 1 && (0, _lodash.isObject)(args[0])) { _log(this.category, (0, _lodash.toUpper)(level), JSON.stringify(args[0])); return; } _log.apply(undefined, [this.category, (0, _lodash.toUpper)(level)].concat(args)); };
import { expect } from "chai"; import { createStore, applyMiddleware } from 'redux'; import Immutable from 'immutable'; import reducers from '../src/lib/reducers'; import * as Utils from '../src/lib/utils'; describe('utils', function () { beforeEach(function () { this.state = Immutable.fromJS([ {title: "alpha"}, {title: "beta", children: [ {title: "foo"}, {title: "bar", children: [ {title: "quux"}, {title: "xyzzy"} ]}, {title: "baz"} ]}, {title: "gamma"}, {title: "level1", children: [ {title: 'level2', children: [ {title: 'level3', children: [ {title: 'level4'} ]} ]} ]}, {title: 'thud'} ]); this.store = createStore(reducers, { nodes: this.state }); this.expectedSeries = [ '0', '1', '1.children.0', '1.children.1', '1.children.1.children.0', '1.children.1.children.1', '1.children.2', '2', '3', '3.children.0', '3.children.0.children.0', '3.children.0.children.0.children.0', '4' ]; this.expectedSiblings = [ ['0', '1', '2', '3', '4'], ['1.children.0', '1.children.1', '1.children.2'], ['1.children.1.children.0', '1.children.1.children.1'], ['3.children.0'] ['3.children.0.children.0'], ['3.children.0.children.0.children.0'], ]; }); describe('splitPath', function () { it('should split a dot-delimited path into a key array', function () { expect(Utils.splitPath('1.children.1.children.2')) .to.deep.equal(['1', 'children', '1', 'children', '2']); }) }) describe('getNodeContext', function () { it('should construct contextual information for a node path', function () { var path = '1.children.1.children.0'; var expected = { key: ['1', 'children', '1', 'children', '0'], parentKey: ['1', 'children', '1'], index: 0, value: this.state.getIn(['1', 'children', '1', 'children', '0']), siblings: this.state.getIn(['1', 'children', '1', 'children']) }; var result = Utils.getNodeContext(this.state, path); expect(result).to.deep.equal(expected); }) }); function commonSiblingPathTest (inReverse, state, expectedSiblings) { var traversal = inReverse ? Utils.getPreviousSiblingPath : Utils.getNextSiblingPath; var siblingList; while (siblingList = expectedSiblings.shift()) { if (inReverse) { siblingList.reverse(); } var current, expected, result; current = siblingList.shift(); while (siblingList.length) { expected = siblingList.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } result = traversal(state, current); expect(result).to.equal(null); } } describe('getNextSiblingPath', function () { it('should find the path to the next sibling', function () { commonSiblingPathTest(false, this.state, this.expectedSiblings); }); }); describe('getPreviousSiblingPath', function () { it('should find the path to the previous sibling', function () { commonSiblingPathTest(true, this.state, this.expectedSiblings); }); }); function commonNodePathTest (inReverse, state, expectedSeries) { var current, expected, result; var traversal = (inReverse) ? Utils.getPreviousNodePath : Utils.getNextNodePath; if (inReverse) { expectedSeries.reverse(); } current = expectedSeries.shift(); while (expectedSeries.length) { expected = expectedSeries.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } } describe('getNextNodePath', function () { it('should find the path to the next node', function () { commonNodePathTest(false, this.state, this.expectedSeries); }) it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(false, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); describe('getPreviousNodePath', function () { it('should find the path to the previous node', function () { commonNodePathTest(true, this.state, this.expectedSeries); }); it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(true, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); });
function child() { alert('child'); } function parent() { alert('parent'); } function grandParent() { alert('grand parent'); }
/** * Created by ko on 2016-07-15. */ $(document).ready(function () { var pageNo= 1; // webtoon $("#recipe").on("click", function () { $("#travel_content").html(""); $("#youtube_content").html(""); $("#honbap_content").html(""); $("#game_content").html(""); $("#parcelArea").css("display","none"); $("#resultArea").html(""); $("#prodInfo_content").css("display", "none"); pageNo=1; $("#cvs_content").css("display", "none"); common_module.moveYoutubeMenu(); recipe_module.recipeTitle(); recipe_module.showRecipe(1); $(window).unbind('scroll'); $(window).scroll(function(){ if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) { pageNo +=1; recipe_module.showRecipe(pageNo); $(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">'); } }); $("#webtoon_content").css("display", "none"); }); });
/** * Copyright 2013 Facebook, Inc. * * Licensed 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. * * @providesModule getDOMNodeID * @typechecks */ "use strict"; /** * Accessing "id" or calling getAttribute('id') on a form element can return its * control whose name or ID is "id". All DOM nodes support `getAttributeNode` * but this can also get called on other objects so just return '' if we're * given something other than a DOM node (such as window). * * @param {DOMElement|DOMWindow|DOMDocument} domNode DOM node. * @returns {string} ID of the supplied `domNode`. */ function getDOMNodeID(domNode) { if (domNode.getAttributeNode) { var attributeNode = domNode.getAttributeNode('id'); return attributeNode && attributeNode.value || ''; } else { return ''; } } module.exports = getDOMNodeID;
/** * @jsx React.DOM * @copyright Prometheus Research, LLC 2014 */ "use strict"; var React = require('react/addons'); var PropTypes = React.PropTypes; var Header = require('./Header'); var Viewport = require('./Viewport'); var ColumnMetrics = require('./ColumnMetrics'); var DOMMetrics = require('./DOMMetrics'); var GridScrollMixin = { componentDidMount() { this._scrollLeft = this.refs.viewport.getScroll().scrollLeft; this._onScroll(); }, componentDidUpdate() { this._onScroll(); }, componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount() { this._scrollLeft = undefined; }, onScroll({scrollLeft}) { if (this._scrollLeft !== scrollLeft) { this._scrollLeft = scrollLeft; this._onScroll(); } }, _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); this.refs.viewport.setScrollLeft(this._scrollLeft); } } }; var Grid = React.createClass({ mixins: [ GridScrollMixin, ColumnMetrics.Mixin, DOMMetrics.MetricsComputatorMixin ], propTypes: { rows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.array.isRequired }, getStyle: function(){ return{ overflowX: 'scroll', overflowY: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight } }, render() { var headerRows = this.props.headerRows || [{ref : 'row'}]; return ( <div {...this.props} style={this.getStyle()} className="react-grid-Grid"> <Header ref="header" columns={this.state.columns} onColumnResize={this.onColumnResize} height={this.props.rowHeight} totalWidth={this.DOMMetrics.gridWidth()} headerRows={headerRows} /> <Viewport ref="viewport" width={this.state.columns.width} rowHeight={this.props.rowHeight} rowRenderer={this.props.rowRenderer} cellRenderer={this.props.cellRenderer} rows={this.props.rows} selectedRows={this.props.selectedRows} expandedRows={this.props.expandedRows} length={this.props.length} columns={this.state.columns} totalWidth={this.DOMMetrics.gridWidth()} onScroll={this.onScroll} onRows={this.props.onRows} rowOffsetHeight={this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length} /> </div> ); }, getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, }); module.exports = Grid;
import './turn-order-a2314c0f.js'; import 'redux'; import 'immer'; import './reducer-4d135cbd.js'; import './Debug-1ad6801e.js'; import 'flatted'; import './ai-ce6b7ece.js'; import './initialize-ec2b5846.js'; export { C as Client } from './client-abd9e531.js';
'use strict'; angular.module('shoprApp') .controller('BookrCtrl', function ($scope, localStorageService, Auth, $http, $routeParams, $location) { $scope.Auth = Auth; //$scope.books = Auth.getCurrentUser().books; $scope.mySubs = Auth.getCurrentUser().books; function getById(books, id) { for(var b in books) { if(books[b]._id === id) return books[b]; } } function loadMore(book) { var page = book.recent[book.recent.length-book.pageIndex-1]; if(page && !page.src) { $http.get('/api/pages/'+book._id+'/'+page.issue).success(function(fullPage) { for(var k in fullPage[0]) page[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var forward = book.recent[book.recent.length-book.pageIndex]; if(forward && !forward.src) { $http.get('/api/pages/'+book._id+'/'+forward.issue).success(function(fullPage) { for(var k in fullPage[0]) forward[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var back = book.recent[book.recent.length-book.pageIndex-2]; if(back && !back.src) { $http.get('/api/pages/'+book._id+'/'+back.issue).success(function(fullPage) { for(var k in fullPage[0]) back[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } } function init(book, pageIndex) { book.pageIndex = pageIndex; $scope.$watch(function(){ return this.pageIndex; }.bind(book), function(newValue, oldValue){ console.log(this); loadMore(this); // $location.path('/bookr/'+this._id+'/'+this.pageIndex, false); var elm = $('book[ng-id="'+this._id+'"]')[0]; elm && $('html, body').animate({ scrollTop: elm.offsetTop }, 450); }.bind(book)); $scope.books.push(book); } function pad(books) { for(var b in books) { var book = books[b]; console.log(book); var recentLength = book.recent.length; for(var i = 0; i < book.count-recentLength; i++) book.recent.push({_id:book._id+'_'+(book.count-(recentLength+1)-i), issue:book.count-(recentLength+1)-i}); console.log(book); } } var books = [$routeParams]; $scope.books = []; for(var b in books) { var book = getById($scope.mySubs, books[b].book); if(!book) { var page = books[b].page; $http.get('/api/books/'+books[b].book).success(function(book){ pad([book]); console.log(book); $scope.mySubs.push(book); init(book, page); console.log('wtf?'); }); continue; } init(book, parseInt(books[b].page)); } });
'use strict'; var express = require("express"); var http = require("http"); var app = express(); var httpServer = http.Server(app); var io = require('socket.io')(httpServer); // Users array. var users = []; // Channels pre-defined array. var channels = [ 'Angular', 'React', 'Laravel', 'Symfony' ]; // Start http server. httpServer.listen(3000, function () { }); // Use static files 'app' folder for '/' path. app.use(express.static(__dirname + '/app/')); // Channels endpoint. app.get('/channels', function (req, res) { res.send(channels); }); // On connection event. io.on('connection', function (socket) { // Join event. socket.on('join', function (data) { // Join socket to channel. socket.join(data.channel); // Add user to users lists. users.push({id: socket.id, name: data.user}); // Bind username to socket object. socket.username = data.user; // If socket already exists in a channel, leave. if (typeof socket.channel != 'undefined') { socket.leave(socket.channel); } // Bind channel to socket. socket.channel = data.channel; }); // Message event. socket.on('message', function (data) { // Send to selected channel user's message. io.sockets.in(data.channel).emit('message', {message: data.message, user: data.username}); }); // Private message event. socket.on('private', function (data) { // Split message to take receiver name. var message = data.message.split(" "); // Get username from message array. var to_user = message[0].slice(1); // Filter users to find user's socket id and send message. users.filter(function (user) { if (user.name == to_user) { // Format message. var private_message = "(private) " + data.message.slice(to_user.length + 2); // Send message to user who sent the message. io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user}); // Send message to receiver. io.sockets.connected[user.id].emit('message', {message: private_message, user: data.username}); } }); }); // Disconnect event. socket.on('disconnect', function () { // Check if user joined any room and clean users array. users = users.filter(function (user) { if (user.id == socket.id) { return false; } return true }); }); });