code
stringlengths
2
1.05M
#!/usr/bin/env node /* Terminal Kit Copyright (c) 2009 - 2021 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; var fs = require( 'fs' ) ; var termkit = require( 'terminal-kit' ) ; var term = termkit.terminal ; var autoCompleter = function autoCompleter( inputString , callback ) { var index = inputString.lastIndexOf( ' ' ) ; var prefix = inputString.slice( 0 , index + 1 ) ; inputString = inputString.slice( index + 1 ) ; fs.readdir( __dirname , function( error , files ) { callback( undefined , termkit.autoComplete( files , inputString , true , prefix ) ) ; } ) ; } ; term( 'Choose a file: ' ) ; term.inputField( { autoComplete: autoCompleter , autoCompleteMenu: true } , function( error , input ) { if ( error ) { term.red.bold( "\nAn error occurs: " + error + "\n" ) ; } else { term.green( "\nYour file is '%s'\n" , input ) ; } process.exit() ; } ) ;
var setFileOverlayHandler = function(id) {} var imageHook = function (e, data) { if(data.result.status === "success") { $('input[name=profileImage').val(data.result.content); $('.playsHideAndSeek').hide('slow'); } else { console.log("error" + data.result.content); } };
const express = require('express'); const app = express(); const routers = require('./routers'); routers.init(app); app.listen(8000, function() { let addr = this.address(); console.log('Start Listen->%s:%s', addr.address, addr.port) });
function solve(args) { var numbers = args[1] .split(' ') .map(Number) .filter(function (a) { return +a === +args[2]; }).length; console.log(numbers); } solve([ '8', '28 6 21 6 -7856 73 73 -56', '73' ]);
/** * * search query results manager * * @param {type} _ * @param {type} utilities * @param {type} EventsLibrary * @param {type} searchQueriesResultsCollection * @param {type} tracksManager * @param {type} TracksCollection * @param {type} async * * @returns {_L17.Anonym$2} */ define([ 'underscore', 'chrisweb-utilities', 'library.events', 'collections.SearchQueries', 'manager.tracks', 'collections.SearchQueryTracks', 'async', 'models.SearchQueryResultTrack' ], function ( _, utilities, EventsLibrary, searchQueriesResultsCollection, tracksManager, SearchQueryTracksCollection, async, SearchQueryResultTrackModel ) { 'use strict'; // the collection which contains all the search queries results of the app var searchQueriesResultsCollection; // are the listeners already on var alreadyListening = false; /** * * initialize the tracks cache manager * * @returns {undefined} */ var initialize = function initializeFunction() { searchQueriesResultsCollection = new searchQueriesResultsCollection(); // avoid duplicate listeners if (!alreadyListening) { startListening(); } }; /** * * add one or more search query / queries result(s) to the search queries results manager * * @param {type} addMe * @returns {undefined} */ var add = function addFunction(addMe) { if (!_.isArray(addMe)) { addMe = [addMe]; } var modelsToAdd = []; _.each(addMe, function(searchQueryResultModel) { var existingSearchQueryResultModel = searchQueriesResultsCollection.get(searchQueryResultModel.get('searchQuery')); // check if the model is not already in the manager if (existingSearchQueryResultModel === undefined) { modelsToAdd.push(searchQueryResultModel); } }); searchQueriesResultsCollection.add(modelsToAdd); }; /** * * get one or more search query / queries result(s) * * @param {type} getMe * @param {type} callback * * @returns {undefined} */ var get = function getFunction(getMe, callback) { utilities.log('[SEARCH QUERIES] get, getMe:', getMe); if (!_.isArray(getMe)) { getMe = [getMe]; } var getMeObjectsArray = []; _.each(getMe, function eachGetMeCallback(getMeSearchQuery) { var getMeObject; // if its a string and not yet an object, then create the object if (!_.isObject(getMeSearchQuery)) { getMeObject = { searchQuery: getMeSearchQuery, withTracksList: true // search query results by default contain the tracksList, something else seems pretty useless }; getMeObjectsArray.push(getMeObject); } else { if ( _.has(getMeSearchQuery, 'searchQuery') && _.has(getMeSearchQuery, 'withTracksList') ) { getMeObjectsArray.push(getMeSearchQuery); } else { callback('one or more properties are missing'); } } }); var fetchMeObjectsArray = []; var searchQueriesResultsAlreadyLoaded = []; // are there any search queries that need to get fetched or are they all // already available in the client _.each(getMeObjectsArray, function eachGetMeObjectsArrayCallback(getMeObject) { // get the query / queries result(s) from query / queries result(s) collection, the response will be // undefined if there is not already a model for that search query result in the collection var existingsearchQueryResultModel = searchQueriesResultsCollection.where({ query: getMeObject.searchQuery }); // check if the query / queries result(s) is not already in the query / queries result(s) manager if (existingsearchQueryResultModel.length === 0) { fetchMeObjectsArray.push(getMeObject); } else { searchQueriesResultsAlreadyLoaded.push(existingsearchQueryResultModel); } }); // did we find search query / queries result(s) that need to get fetched if (fetchMeObjectsArray.length > 0) { fetch(fetchMeObjectsArray, function(error, serverSearchQueriesResultsArray) { if (!error) { var returnMe = searchQueriesResultsAlreadyLoaded.concat(serverSearchQueriesResultsArray); callback(null, returnMe); } else { callback(error); } }); } }; /** * * we don't have the search query result yet, fetch it from the server * * @param {type} fetchMe * @param {type} callback * * @returns {undefined} */ var fetch = function fetchFunction(fetchMeObjectsArray, callback) { utilities.log('[SEARCH QUERIES] fetch the search query result from the server, fetchMeObjectsArray:', fetchMeObjectsArray); if (fetchMeObjectsArray.length > 0) { var functionsArray = []; _.each(fetchMeObjectsArray, function forEachCallback(fetchMeObject) { functionsArray.push(function callbackFromAsyncFunction(callbackFromAsyncFunction) { fetchQuery(fetchMeObject.searchQuery, callbackFromAsyncFunction); }); }); // execute all the getCollaborativePlaylistTracks queries asynchronously async.parallel(functionsArray, function asyncParallelCallback(error, queryResults) { if (!error) { callback(null, queryResults); } else { callback(error); } }); } } var fetchQuery = function fetchQueryFunction(searchQuery, callback) { // fetch a model from server searchQueriesResultsCollection.fetch({ data: { q: searchQuery }, error: function (collection, response, options) { //utilities.log(collection, response, options); callback('error fetching search query result(s), status: ' + response.status); }, success: function (collection, response, options) { //utilities.log(collection, response, options); var searchQueryModel = collection.first(); var tracksList = new SearchQueryTracksCollection(); // convert the objects into models and add them to the tracksList collection _.each(searchQueryModel.get('tracksList'), function eachTracksListCallback(trackData) { var searchQueryResultTrackModel = new SearchQueryResultTrackModel({ id: trackData.id, position: trackData.position }); tracksList.add(searchQueryResultTrackModel, { silent: true }); }); // add the tracksList to the model searchQueryModel.set('tracksList', tracksList); // return the model callback(null, searchQueryModel); } }); }; /** * * start listening for events * * @returns {undefined} */ var startListening = function startListeningFunction() { alreadyListening = true; EventsLibrary.on(EventsLibrary.constants.SEARCH_QUERIES_MANAGER_ADD, function addSearchQueryEventFunction(attributes) { add(attributes.model); }); EventsLibrary.on(EventsLibrary.constants.SEARCH_QUERIES_MANAGER_GET, function getEventFunction(attributes) { var searchQuery = attributes.searchQuery; get(searchQuery, function getSearchQueryCallback() { //EventsLibrary.trigger }); }); }; /** * * get the next track of the query * * @returns {undefined} */ var nextTrack = function nextTrackFunction() { }; return { initialize: initialize, add: add, get: get, fetch: fetch, nextTrack: nextTrack }; });
import * as ActionTypes from './action-types'; export const searchFlightStarted = () => ({ type: ActionTypes.SEARCH_FLIGHT_STARTED, payload: {} }); export const searchFlightFailed = (payload) => ({ type: ActionTypes.SEARCH_FLIGHT_FAILED, payload }); export const searchFlightCompleted = (payload) => ({ type: ActionTypes.SEARCH_FLIGHT_COMPLETED, payload }); export const changeFlightWay = (payload) => ({ type: ActionTypes.CHANGE_FLIGHT_WAY_TYPE, payload });
var fs = require("fs"); var file = "page.html"; var content = fs.readFileSync(file, { encoding: "utf8" }); var data = { file: file, content: content }; fs.writeFileSync("page.json", JSON.stringify(content));
import Promise from 'bluebird' import { merge } from 'ramda' import runTest from '../../test/runTest' const findOptions = { connect: { api_key: 'abc123', }, method: 'GET', body: { api_key: 'abc123', }, } test('client.transfers.find', () => { const find = runTest(merge(findOptions, { subject: client => client.transfers.find({ id: 1337 }), url: '/transfers/1337', })) const findAll = runTest(merge(findOptions, { subject: client => client.transfers.find({ count: 10, page: 2 }), url: '/transfers', })) return Promise.props({ find, findAll, }) }) test('client.transfers.all', () => runTest(merge(findOptions, { subject: client => client.transfers.all({ count: 10, page: 2 }), url: '/transfers', })) ) test('client.transfers.create', () => runTest({ connect: { api_key: 'abc123', }, subject: client => client.transfers.create({ amount: 12345, }), method: 'POST', url: '/transfers', body: { api_key: 'abc123', amount: 12345, }, }) ) test('client.transfers.cancel', () => runTest({ connect: { api_key: 'abc123', }, subject: client => client.transfers.cancel({ id: 1234 }), method: 'POST', url: '/transfers/1234/cancel', body: { api_key: 'abc123', }, }) ) test('client.transfers.days', () => runTest({ connect: { api_key: 'abc123', }, subject: client => client.transfers.days(), method: 'GET', url: '/transfers/days', body: { api_key: 'abc123', }, }) ) test('client.transfers.limits', () => runTest({ connect: { api_key: 'abc123', }, subject: client => client.transfers.limits(), method: 'GET', url: '/transfers/limits', body: { api_key: 'abc123', }, }) ) test('client.transfers.limits with recipient_id', () => runTest({ connect: { api_key: 'abc123', }, subject: client => client.transfers.limits({ recipient_id: 're_11111' }), method: 'GET', url: '/transfers/limits', body: { api_key: 'abc123', recipient_id: 're_11111', }, }) )
define(function() { return window.getComputedStyle; });
/* global createSelect2 */ $(document).ready(function() { createSelect2('#user_per_page', { width: '70px', minimumResultsForSearch: 20, }); createSelect2('#user_default_view', { width: '100px', minimumResultsForSearch: 20, }); createSelect2('#user_default_character_split', { width: '250px', minimumResultsForSearch: 20, }); createSelect2('#user_default_editor', { width: '100px', minimumResultsForSearch: 20, }); createSelect2('#user_layout', { width: '150px', minimumResultsForSearch: 20, }); createSelect2('#user_timezone', {width: '250px'}); createSelect2('#user_time_display', { width: '200px', minimumResultsForSearch: 20 }); });
(function( $ ) { $.widget("smartclassroom.treeview", { version: "1.0.0", options: { onNodeClick: function(node){}, onNodeCollapsed: function(node){}, onNodeExpanded: function(node){} }, _create: function(){ var that = this, element = this.element; element.find('.node.collapsed').find('ul').hide(); element.find('.node-toggle').on('click', function(e){ var $this = $(this), node = $this.parent().parent("li"); if (node.hasClass("keep-open")) return; node.toggleClass('collapsed'); if (node.hasClass('collapsed')) { node.children('ul').fadeOut('fast'); that.options.onNodeCollapsed(node); } else { node.children('ul').fadeIn('fast'); that.options.onNodeExpanded(node); } that.options.onNodeClick(node); e.preventDefault(); e.stopPropagation(); }); element.find("a").each(function(){ var $this = $(this); $this.css({ paddingLeft: ($this.parents("ul").length-1) * 10 }); }); element.find('a').on('click', function(e){ var $this = $(this), node = $this.parent('li'); element.find('a').removeClass('active'); $this.toggleClass('active'); that.options.onNodeClick(node); e.preventDefault(); }); }, _destroy: function(){ }, _setOption: function(key, value){ this._super('_setOption', key, value); } }) })( jQuery );
export { default } from 'modal-components/components/form-label';
// UAParser.js v0.6.16 // Lightweight JavaScript-based User-Agent string parser // https://github.com/faisalman/ua-parser-js // // Copyright © 2012-2013 Faisalman <fyzlman@gmail.com> // Dual licensed under GPLv2 & MIT (function (window, undefined) { 'use strict'; ////////////// // Constants ///////////// var EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', MAJOR = 'major', MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet', SMARTTV = 'smarttv'; /////////// // Helper ////////// var util = { has : function (str1, str2) { if (typeof str1 === "string") { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; } }, lowerize : function (str) { return str.toLowerCase(); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function () { // loop through all regexes maps for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) { var regex = args[i], // even sequence (0,2,4,..) props = args[i + 1]; // odd sequence (1,3,5,..) // construct object barebones if (typeof(result) === UNDEF_TYPE) { result = {}; for (p in props) { q = props[p]; if (typeof(q) === OBJ_TYPE) { result[q[0]] = undefined; } else { result[q] = undefined; } } } // try matching uastring with regexes for (j = k = 0; j < regex.length; j++) { matches = regex[j].exec(this.getUA()); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof(q) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof(q[1]) == FUNC_TYPE) { // assign modified match result[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match result[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex result[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { result[q] = match ? match : undefined; } } break; } } if(!!matches) break; // break the loop immediately if match found } return result; }, str : function (str, map) { for (var i in map) { // check if array if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { major : { '1' : ['/8', '/1', '/3'], '2' : '/4', '?' : '/' }, version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION, MAJOR], [ /\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION, MAJOR], [ // Mixed /(kindle)\/((\d+)?[\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron ], [NAME, VERSION, MAJOR], [ /(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION, MAJOR], [ /(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION, MAJOR], [ /(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION, MAJOR], [ /(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION, MAJOR], [ /((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION, MAJOR], [ /version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [ /version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, MAJOR, NAME], [ /webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0 ], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror /(webkit|khtml)\/((\d+)?[\w\.]+)/i ], [NAME, VERSION, MAJOR], [ // Gecko based /(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION, MAJOR], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i, // UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser /(links)\s\(((\d+)?[\w\.]+)/i, // Links /(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic ], [NAME, VERSION, MAJOR], [ /(apple(?:coremedia|))\/((\d+)[\w\._]+)/i, // Generic Apple CoreMedia /(coremedia) v((\d+)[\w\._]+)/i ], [NAME, VERSION, MAJOR], [ /(aqualung|lyssna|bsplayer)\/([\w\.-]+)/i // Aqualung/Lyssna/BSPlayer ], [NAME, VERSION], [ /(ares|ossproxy)\s((\d+)[\w\.-]+)/i // Ares/OSSProxy ], [NAME, VERSION, MAJOR], [ /(audacious|audimusicstream|amarok|bass|core|dalvik|gnomemplayer|music on console|nsplayer|psp-internetradioplayer|videos)\/((\d+)[\w\.-]+)/i, // Audacious/AudiMusicStream/Amarok/BASS/OpenCORE/Dalvik/GnomeMplayer/MoC // NSPlayer/PSP-InternetRadioPlayer/Videos /(clementine|music player daemon)\s((\d+)[\w\.-]+)/i, // Clementine/MPD /(lg player|nexplayer)\s((\d+)[\d\.]+)/i, /player\/(nexplayer|lg player)\s((\d+)[\w\.-]+)/i // NexPlayer/LG Player ], [NAME, VERSION, MAJOR], [ /(nexplayer)\s((\d+)[\w\.-]+)/i // Nexplayer ], [NAME, VERSION, MAJOR], [ /(flrp)\/((\d+)[\w\.-]+)/i // Flip Player ], [[NAME, 'Flip Player'], VERSION, MAJOR], [ /(fstream|nativehost|queryseekspider|ia-archiver|facebookexternalhit)/i // FStream/NativeHost/QuerySeekSpider/IA Archiver/facebookexternalhit ], [NAME], [ /(gstreamer) souphttpsrc (?:\([^\)]+\)){0,1} libsoup\/((\d+)[\w\.-]+)/i // Gstreamer ], [NAME, VERSION, MAJOR], [ /(htc streaming player)\s[\w_]+\s\/\s((\d+)[\d\.]+)/i, // HTC Streaming Player /(java|python-urllib|python-requests|wget|libcurl)\/((\d+)[\w\.-_]+)/i, // Java/urllib/requests/wget/cURL /(lavf)((\d+)[\d\.]+)/i // Lavf (FFMPEG) ], [NAME, VERSION, MAJOR], [ /(htc_one_s)\/((\d+)[\d\.]+)/i, // HTC One S ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(mplayer)(?:\s|\/)(?:(?:sherpya-){0,1}svn)(?:-|\s)(r\d+(?:-\d+[\w\.-]+){0,1})/i, // MPlayer SVN ], [NAME, VERSION], [ /(mplayer)(?:\s|\/)((\d+)[\w\.-]+)/i, // MPlayer /(mplayer) unknown-((\d+)[\w\.\-]+)/i // MPlayer UNKNOWN ], [NAME, VERSION, MAJOR], [ /(mplayer)/i, // MPlayer (no other info) /(yourmuze)/i, // YourMuze /(media player classic|nero showtime)/i // Media Player Classic/Nero ShowTime ], [NAME], [ /(nero (?:home|scout))\/((\d+)[\w\.-]+)/i // Nero Home/Nero Scout ], [NAME, VERSION, MAJOR], [ /(nokia\d+)\/((\d+)[\w\.-]+)/i // Nokia ], [NAME, VERSION, MAJOR], [ /\s(songbird)\/((\d+)[\w\.-]+)/i // Songbird/Philips-Songbird ], [NAME, VERSION, MAJOR], [ /(winamp)3 version ((\d+)[\w\.-]+)/i, // Winamp /(winamp)\s((\d+)[\w\.-]+)/i, /(winamp)mpeg\/((\d+)[\w\.-]+)/i ], [NAME, VERSION, MAJOR], [ /(ocms-bot|tapinradio|tunein radio|unknown|winamp|inlight radio)/i // OCMS-bot/tap in radio/tunein/unknown/winamp (no other info) // inlight radio ], [NAME], [ /(quicktime|rma|radioapp|radioclientapplication|soundtap|totem|stagefright|streamium)\/((\d+)[\w\.-]+)/i // QuickTime/RealMedia/RadioApp/RadioClientApplication/ // SoundTap/Totem/Stagefright/Streamium ], [NAME, VERSION, MAJOR], [ /(smp)((\d+)[\d\.]+)/i // SMP ], [NAME, VERSION, MAJOR], [ /(vlc) media player - version ((\d+)[\w\.]+)/i, // VLC Videolan /(vlc)\/((\d+)[\w\.-]+)/i, /(xbmc|gvfs|xine|xmms|irapp)\/((\d+)[\w\.-]+)/i, // XBMC/gvfs/Xine/XMMS/irapp /(foobar2000)\/((\d+)[\d\.]+)/i, // Foobar2000 /(itunes)\/((\d+)[\d\.]+)/i // iTunes ], [NAME, VERSION, MAJOR], [ /(wmplayer)\/((\d+)[\w\.-]+)/i, // Windows Media Player /(windows-media-player)\/((\d+)[\w\.-]+)/i ], [[NAME, /-/g, ' '], VERSION, MAJOR], [ /windows\/((\d+)[\w\.-]+) upnp\/[\d\.]+ dlnadoc\/[\d\.]+ (home media server)/i, // Windows Media Server ], [VERSION, MAJOR, [NAME, 'Windows']], [ /(com\.riseupradioalarm)\/((\d+)[\d\.]*)/i // RiseUP Radio Alarm ], [NAME, VERSION, MAJOR], [ /(rad.io)\s((\d+)[\d\.]+)/i, // Rad.io /(radio.(?:de|at|fr))\s((\d+)[\d\.]+)/i ], [[NAME, 'rad.io'], VERSION, MAJOR] ], cpu : [[ /(?:(amd|x(?:(?:86|64)[_-])?|wow|win)64)[;\)]/i // AMD64 ], [[ARCHITECTURE, 'amd64']], [ /(ia32(?=;))/i // IA32 (quicktime) ], [[ARCHITECTURE, util.lowerize]], [ /((?:i[346]|x)86)[;\)]/i // IA32 ], [[ARCHITECTURE, 'ia32']], [ // PocketPC mistakenly identified as PowerPC /windows\s(ce|mobile);\sppc;/i ], [[ARCHITECTURE, 'arm']], [ /((?:ppc|powerpc)(?:64)?)(?:\smac|;|\))/i // PowerPC ], [[ARCHITECTURE, /ower/, '', util.lowerize]], [ /(sun4\w)[;\)]/i // SPARC ], [[ARCHITECTURE, 'sparc']], [ /(ia64(?=;)|68k(?=\))|arm(?=v\d+;)|(?:irix|mips|sparc)(?:64)?(?=;)|pa-risc)/i // IA64, 68K, ARM, IRIX, MIPS, SPARC, PA-RISC ], [ARCHITECTURE, util.lowerize] ], device : [[ /\((ipad|playbook);[\w\s\);-]+(rim|apple)/i // iPad/PlayBook ], [MODEL, VENDOR, [TYPE, TABLET]], [ /applecoremedia\/[\w\.]+ \((ipad)/ // iPad ], [MODEL, [VENDOR, 'Apple'], [TYPE, TABLET]], [ /(apple\s{0,1}tv)/i // Apple TV ], [[MODEL, 'Apple TV'], [VENDOR, 'Apple']], [ /(hp).+(touchpad)/i, // HP TouchPad /(kindle)\/([\w\.]+)/i, // Kindle /\s(nook)[\w\s]+build\/(\w+)/i, // Nook /(dell)\s(strea[kpr\s\d]*[\dko])/i // Dell Streak ], [VENDOR, MODEL, [TYPE, TABLET]], [ /\((ip[honed|\s\w*]+);.+(apple)/i // iPod/iPhone ], [MODEL, VENDOR, [TYPE, MOBILE]], [ /\((ip[honed|\s\w*]+);/i // iPod/iPhone ], [MODEL, [VENDOR, 'Apple'], [TYPE, MOBILE]], [ /(blackberry)[\s-]?(\w+)/i, // BlackBerry /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|huawei|meizu|motorola)[\s_-]?([\w-]+)*/i, // BenQ/Palm/Sony-Ericsson/Acer/Asus/Dell/Huawei/Meizu/Motorola /(hp)\s([\w\s]+\w)/i, // HP iPAQ /(asus)-?(\w+)/i // Asus ], [VENDOR, MODEL, [TYPE, MOBILE]], [ /\((bb10);\s(\w+)/i // BlackBerry 10 ], [[VENDOR, 'BlackBerry'], MODEL, [TYPE, MOBILE]], [ // Asus Tablets /android.+((transfo[prime\s]{4,10}\s\w+|eeepc|slider\s\w+|nexus 7))/i ], [[VENDOR, 'Asus'], MODEL, [TYPE, TABLET]], [ /(sony)\s(tablet\s[ps])/i // Sony Tablets ], [VENDOR, MODEL, [TYPE, TABLET]], [ /(nintendo)\s([wids3u]+)/i // Nintendo ], [VENDOR, MODEL, [TYPE, CONSOLE]], [ /((playstation)\s[3portablevi]+)/i // Playstation ], [[VENDOR, 'Sony'], MODEL, [TYPE, CONSOLE]], [ /(sprint\s(\w+))/i // Sprint Phones ], [[VENDOR, mapper.str, maps.device.sprint.vendor], [MODEL, mapper.str, maps.device.sprint.model], [TYPE, MOBILE]], [ /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i, // HTC /(zte)-(\w+)*/i, // ZTE /(alcatel|geeksphone|huawei|lenovo|nexian|panasonic|(?=;\s)sony)[_\s-]?([\w-]+)*/i // Alcatel/GeeksPhone/Huawei/Lenovo/Nexian/Panasonic/Sony ], [VENDOR, [MODEL, /_/g, ' '], [TYPE, MOBILE]], [ // Motorola /\s((milestone|droid(?:[2-4x]|\s(?:bionic|x2|pro|razr))?(:?\s4g)?))[\w\s]+build\//i, /(mot)[\s-]?(\w+)*/i ], [[VENDOR, 'Motorola'], MODEL, [TYPE, MOBILE]], [ /android.+\s((mz60\d|xoom[\s2]{0,2}))\sbuild\//i ], [[VENDOR, 'Motorola'], MODEL, [TYPE, TABLET]], [ /android.+((sch-i[89]0\d|shw-m380s|gt-p\d{4}|gt-n8000|sgh-t8[56]9|nexus 10))/i ], [[VENDOR, 'Samsung'], MODEL, [TYPE, TABLET]], [ // Samsung /((s[cgp]h-\w+|gt-\w+|galaxy\snexus))/i, /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i, /sec-((sgh\w+))/i ], [[VENDOR, 'Samsung'], MODEL, [TYPE, MOBILE]], [ /(sie)-(\w+)*/i // Siemens ], [[VENDOR, 'Siemens'], MODEL, [TYPE, MOBILE]], [ /(maemo|nokia).*(n900|lumia\s\d+)/i, // Nokia /(nokia)[\s_-]?([\w-]+)*/i ], [[VENDOR, 'Nokia'], MODEL, [TYPE, MOBILE]], [ /android\s3\.[\s\w-;]{10}((a\d{3}))/i // Acer ], [[VENDOR, 'Acer'], MODEL, [TYPE, TABLET]], [ /android\s3\.[\s\w-;]{10}(lg?)-([06cv9]{3,4})/i // LG ], [[VENDOR, 'LG'], MODEL, [TYPE, TABLET]], [ /((nexus\s[45]))/i, /(lg)[e;\s-\/]+(\w+)*/i ], [[VENDOR, 'LG'], MODEL, [TYPE, MOBILE]], [ /android.+((ideatab[a-z0-9\-\s]+))/i // Lenovo ], [[VENDOR, 'Lenovo'], MODEL, [TYPE, TABLET]], [ /(lg) netcast\.tv/i // LG SmartTV ], [VENDOR, [TYPE, SMARTTV]], [ /(mobile|tablet);.+rv\:.+gecko\//i // Unidentifiable ], [TYPE, VENDOR, MODEL] ], engine : [[ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /microsoft\s(windows)\s(vista|xp)/i, // Windows (iTunes) ], [NAME, VERSION], [ /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)\/([\w\.]+)/i, // Tizen /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION],[ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [ /(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS ], [NAME, [VERSION, /_/g, '.']], [ // Other /(haiku)\s(\w+)/i, // Haiku /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (uastring) { var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); if (!(this instanceof UAParser)) { return new UAParser(uastring).getResult(); } this.getBrowser = function () { return mapper.rgx.apply(this, regexes.browser); }; this.getCPU = function () { return mapper.rgx.apply(this, regexes.cpu); }; this.getDevice = function () { return mapper.rgx.apply(this, regexes.device); }; this.getEngine = function () { return mapper.rgx.apply(this, regexes.engine); }; this.getOS = function () { return mapper.rgx.apply(this, regexes.os); }; this.getResult = function() { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS(), device : this.getDevice(), cpu : this.getCPU() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; return this; }; this.setUA(ua); }; /////////// // Export ////////// // check js environment if (typeof(exports) !== UNDEF_TYPE) { // nodejs env if (typeof(module) !== UNDEF_TYPE && module.exports) { exports = module.exports = UAParser; } exports.UAParser = UAParser; } else { // browser env // Stop putting it on window // window.UAParser = UAParser; // requirejs env (optional) if (typeof(define) === FUNC_TYPE && define.amd) { define(function () { return UAParser; }); } // jQuery specific (optional) if (typeof(window.jQuery) !== UNDEF_TYPE) { var $ = window.jQuery; var parser = new UAParser(); $.ua = parser.getResult(); $.ua.get = function() { return parser.getUA(); }; $.ua.set = function (uastring) { parser.setUA(uastring); var result = parser.getResult(); for (var prop in result) { $.ua[prop] = result[prop]; } }; } } })(this);
/** * Importamos el módulo ab-pasarelaAbanca */ const abAbanca = require('ab-pasarelaAbanca'); /** * Crea una instancia de abAbanca con los datos estáticos */ const abanca = new abAbanca(cyphKey, MerchantID, AcquirerBIN, TerminalID, Cifrado, TipoMoneda, Exponente, Pago_soportado, Idioma, tpvUrl); /** * Devuelve un formulario firmado y listo para enviar a la pasarela de pago */ let form = abanca.getFormSigned(urlOk, urlNok, Num_operacion, Importe) /** * Valida la firma de los datos enviados desde la pasarela de pago */ let valid = abanca.isValid(sign, Num_operacion, Importe, Referencia) /** * Devuelve la respuesta de confirmación de pago para enviar a la pasarela */ let responseMessageOk = abanca.getResponseOk(message) /** * Devuelve la respuesta de cancelación de pago a la pasarela */ let responseMessageNok = abanca.getResponseNok(message)
'use strict'; /* Directives */ app.directive('ensureUnique', ['RestFul', function (RestFul) { return { require: 'ngModel', link: function (scope, elm, attrs, ctrl) { scope.$watch(attrs.ngModel, function () { if ((attrs.ensureUnique !== '') && (attrs.action === 'new')) { RestFul.get({ jsonFile: 'users.json', type: 'unique', username: attrs.ensureUnique }, function (data) { if (data.length === 0) { ctrl.$setValidity('unique', true); } else { ctrl.$setValidity('unique', false); } }); } else { ctrl.$setValidity('unique', true); } }); } }; }]); app.directive('pwCheck', [function () { return { require: 'ngModel', link: function (scope, elem, attrs, ctrl) { var firstPassword = '#' + attrs.pwCheck; elem.add(firstPassword).on('keyup', function () { scope.$apply(function () { var v = elem.val() === $(firstPassword).val(); ctrl.$setValidity('pwmatch', v); }); }); } }; }]);
'use strict'; //Agegroups service used to communicate Agegroups REST endpoints angular.module('agegroups').factory('Agegroups', ['$resource', function($resource) { return $resource('agegroups/:agegroupId', { agegroupId: '@_id' }, { update: { method: 'PUT' } }); } ]);
'use strict'; /** * Module dependencies. */ var _ = require('lodash'); /** * Extend user's controller */ module.exports = _.extend( require('./users/authentication.js'), require('./users/authorization.js'), require('./users/password.js'), require('./users/profile.js'), require('./users/create.js') );
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2007, 2008, 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /** * * @constructor * @class * * @author Dave Comfort * * @param id [int] numeric ID * @param name [string] name * @param parent [ZmOrganizer] parent organizer * @param tree [ZmTree] tree model that contains this organizer * @param color * @param url [string]* URL for this organizer's feed * @param owner * @param zid [string]* Zimbra id of owner, if remote share * @param rid [string]* Remote id of organizer, if remote share * @param restUrl [string]* The REST URL of this organizer. */ ZmVoiceFolder = function(params) { params.type = ZmOrganizer.VOICE; ZmOrganizer.call(this, params); this.phone = params.phone; this.callType = params.name; // A constant...ACCOUNT, PLACED, etc. this.view = params.view; } ZmVoiceFolder.prototype = new ZmOrganizer; ZmVoiceFolder.prototype.constructor = ZmVoiceFolder; ZmVoiceFolder.ACCOUNT = "USER_ROOT"; ZmVoiceFolder.PLACED_CALL = "Placed Calls"; ZmVoiceFolder.ANSWERED_CALL = "Answered Calls"; ZmVoiceFolder.MISSED_CALL = "Missed Calls"; ZmVoiceFolder.VOICEMAIL = "Voicemail Inbox"; ZmVoiceFolder.TRASH = "Trash"; ZmVoiceFolder.ACCOUNT_ID = "1"; ZmVoiceFolder.PLACED_CALL_ID = "1027"; ZmVoiceFolder.ANSWERED_CALL_ID = "1026"; ZmVoiceFolder.MISSED_CALL_ID = "1025"; ZmVoiceFolder.VOICEMAIL_ID = "1024"; ZmVoiceFolder.TRASH_ID = "1028"; ZmVoiceFolder.SORT_ORDER = {}; ZmVoiceFolder.SORT_ORDER[ZmVoiceFolder.PLACED_CALL] = 5; ZmVoiceFolder.SORT_ORDER[ZmVoiceFolder.ANSWERED_CALL] = 4; ZmVoiceFolder.SORT_ORDER[ZmVoiceFolder.MISSED_CALL] = 3; ZmVoiceFolder.SORT_ORDER[ZmVoiceFolder.VOICEMAIL] = 1; ZmVoiceFolder.SORT_ORDER[ZmVoiceFolder.TRASH] = 2; // Public methods ZmVoiceFolder.prototype.toString = function() { return "ZmVoiceFolder"; }; ZmVoiceFolder.prototype.getName = function(showUnread, maxLength, noMarkup) { var name; switch (this.callType) { case ZmVoiceFolder.ACCOUNT: name = this.phone.getDisplay(); break; case ZmVoiceFolder.PLACED_CALL: name = ZmMsg.placedCalls; break; case ZmVoiceFolder.ANSWERED_CALL: name = ZmMsg.answeredCalls; break; case ZmVoiceFolder.MISSED_CALL: name = ZmMsg.missedCalls; break; case ZmVoiceFolder.VOICEMAIL: name = ZmMsg.voiceMail; break; case ZmVoiceFolder.TRASH: name = ZmMsg.trash; break; } return this._markupName(name, showUnread && (this.callType != ZmVoiceFolder.TRASH), noMarkup); }; ZmVoiceFolder.prototype.getIcon = function() { switch (this.callType) { case ZmVoiceFolder.ACCOUNT: { return null; } case ZmVoiceFolder.PLACED_CALL: { return "PlacedCalls"; } case ZmVoiceFolder.ANSWERED_CALL: { return "AnsweredCalls"; } case ZmVoiceFolder.MISSED_CALL: { return "MissedCalls"; } case ZmVoiceFolder.VOICEMAIL: { return "Voicemail"; } case ZmVoiceFolder.TRASH: { return "Trash"; } default: { return null; } } }; ZmVoiceFolder.prototype.getSearchType = function() { return (this.callType == ZmVoiceFolder.VOICEMAIL) || (this.callType == ZmVoiceFolder.TRASH) ? ZmItem.VOICEMAIL : ZmItem.CALL; }; ZmVoiceFolder.prototype.getSearchQuery = function() { var query = [ "phone:", this.phone.name ]; if (this.callType != ZmVoiceFolder.VOICEMAIL) { query.push(" in:\""); query.push(this.callType); query.push("\""); } return query.join(""); }; ZmVoiceFolder.prototype.isInTrash = function() { var folder = this; while (folder) { if (this.callType == ZmVoiceFolder.TRASH) { return true; } folder = folder.parent; } return false; }; ZmVoiceFolder.prototype.mayContain = function(what, folderType) { var items = (what instanceof Array) ? what : [what]; for (var i = 0, count = items.length; i < count; i++) { var voicemail = items[i]; if (!(voicemail instanceof ZmVoicemail)) { return false; } if ((this.callType != ZmVoiceFolder.VOICEMAIL) && (this.callType !== ZmVoiceFolder.TRASH)) { return false; } var folder = voicemail.getFolder(); if (folder == this) { return false; } if (folder.phone != this.phone) { return false; } } return true; }; ZmVoiceFolder.prototype.changeNumUnheardBy = function(delta) { var newValue = (this.numUnread || 0) + delta; this.notifyModify( { u: newValue } ); }; /** * This updates the num total in the folder * @param delta {int} value to change num total by */ ZmVoiceFolder.prototype.changeNumTotal = function(delta) { var newValue = (this.numTotal || 0 ) + delta; this.notifyModify( {n: newValue}); }; ZmVoiceFolder.get = function(phone, folderType) { var folderId = [folderType, "-", phone.name].join(""); return phone.folderTree.getById(folderId); }; ZmVoiceFolder.sortCompare = function(folderA, folderB) { if ((folderA instanceof ZmVoiceFolder) && (folderB instanceof ZmVoiceFolder)) { var sortA = ZmVoiceFolder.SORT_ORDER[folderA.callType]; var sortB = ZmVoiceFolder.SORT_ORDER[folderB.callType]; if (sortA && sortB) { return sortA - sortB; } } return 0; }; ZmVoiceFolder.prototype.getToolTip = function (force) { return ZmOrganizer.prototype.getToolTip.call(this, force); }; ZmVoiceFolder.prototype._getItemsText = function() { switch (this.callType){ case ZmVoiceFolder.VOICEMAIL: case ZmVoiceFolder.TRASH: return ZmMsg.voicemailMessages; case ZmVoiceFolder.ANSWERED_CALL: return ZmMsg.answeredCalls; case ZmVoiceFolder.MISSED_CALL: return ZmMsg.missedCalls; case ZmVoiceFolder.PLACED_CALL: return ZmMsg.placedCalls; default: return ZmMsg.calls; } }; ZmVoiceFolder.prototype._getUnreadLabel = function() { return ZmMsg.unheard; }; ZmVoiceFolder.prototype.empty = function(){ DBG.println(AjxDebug.DBG1, "emptying: " + this.name + ", ID: " + this.id); var soapDoc = AjxSoapDoc.create("VoiceMsgActionRequest", "urn:zimbraVoice"); var node = soapDoc.set("action"); node.setAttribute("op", "empty"); node.setAttribute("id", this.id); node.setAttribute("phone", this.phone.name); this._handleResponseEmptyObj = this._handleResponseEmptyObj || new AjxCallback(this, this._handleResponseEmpty); var params = { soapDoc: soapDoc, asyncMode: true, callback: this._handleResponseEmptyObj }; appCtxt.getAppController().sendRequest(params); }; ZmVoiceFolder.prototype._handleResponseEmpty = function() { // If this folder is visible, clear the contents of the view. var controller = AjxDispatcher.run("GetVoiceController"); if (controller.getFolder() == this) { controller.getListView().removeAll(); } };
$(document).ready(function() { /**** Global Variables *******/ var objects = new Array('ball','banana','cup','flower','glass'); var currentDragObject; //store the id of current drag object selected var currentDropObject; //store the id of current drop object selected var dropNumber; //current drop Area number var dragNumber; //current drop Area number var dropRow; //current row var dropCol; //current column var stackedObjects = []; //store the value of the stacked objects of particular type if at right var stacklevel; var num_objects = 0; var randPositions = []; //store the random positions for the generated image numbers var randImages = new Array("2","3","2","1","2"); var draggedImage = 0; //store the current drag image id i.e. 0 for ball var dragImgPos = []; var barGraphComplete = 0; //set to 1 bar graph is complete var currentAnswer; var currentQuestion = 0; var questions = new Array( "बल कति वटा छन् ?","केरा कति वटा छन् ?","कप कति वटा छन् ?","फुल कति वटा छन् ?","गिलास कति वटा छन् ?", "केरा फुल भन्दा कति बढी ?","फुल भन्दा बल कति बढी ?","गिलास केरा भन्दा कति कम ?","कप र फुलमा कुन बढी ?","केरा र बलमा कुन बढी ?"); var answers = new Array("2","3","2","1","2","2","1","1","cup","banana"); /**** Questions **** * How Many ? (5 Questions) * Which one is greater? 3 questions * */ /*****************************/ //generate_random_number_of_images(); $('#questionSection').hide(); generate_objects(); draw_bar_graph(); check_bar_graph_completion(); /***** Methods *******/ function generate_questions(){ if(currentQuestion > 9 ){ display_game_over(); } else{ $("#questionSection").html(""); $("#questionSection").append('<div id="question'+currentQuestion+'" class="questions">'); $("#questionSection").append(questions[currentQuestion]); $("#questionSection").append('</div>'); } } function check_answer(){ if(currentAnswer == answers[currentQuestion]){ currentQuestion += 1; generate_questions(); } } function display_game_over(){ $("#questionSection").html(""); $("#questionSection").append('<div class="questions">'); $("#questionSection").append('बधाई छ तिमीले सबै प्रश्नको जवाफ दियौ !!! '); $("#questionSection").append('</div>'); } function checkNumberPressed(pressedNumber){ if(barGraphComplete === 1){ currentAnswer = pressedNumber; check_answer(); } } function check_bar_graph_completion(){ if(num_objects == 10){ barGraphComplete = 1; $('#questionSection').show(); generate_questions(); } } /*******************************/ function generate_numbers(x){ $("#numbersSection").append('<a href="#"></a>'); $('#numbersSection a:last-of-type').append('<div id="number'+i+'" draggable="false" class="numbers">'+x+'</div>'); $('#numbersSection a:last-of-type').click(function(){ checkNumberPressed(x); }); } function generate_objects_bottom(objectid){ $("#objectsSection").append('<a href="#"></a>'); $("#objectsSection a:last-of-type").append('<img src="assets/image/'+objects[objectid]+'.png" draggable="false" class="objects" />'); $('#objectsSection a:last-of-type').click(function(){ checkNumberPressed(objects[objectid]); }); } function draw_bar_graph(){ $("#barGraph").html(""); for(var i=0; i<77; i++){ $("#barGraph").append('<div id="dropObj'+i+'" class="dropObjects"></div>'); } $("#numbersSection").html(""); for(var i=0; i<7; i++){ var x= 7-i; generate_numbers(x); } $("#objectsSection").html(""); for(var i=0; i<5; i++){ generate_objects_bottom(i); } num_objects = 0; } function generate_random_number() { //generate random number include 0 var rand_no = Math.floor(10*Math.random()); return rand_no; } function generate_random_positions(){ randPositions[0] = generate_random_number(); for(i=1; i<10; i++){ do{ flag = 0; randPositions[i] = generate_random_number(); for(j=0; j<i; j++){ if(randPositions[i]===randPositions[j]){ flag++; } } }while(flag != 0 ); //end of do while loop } } function generate_objects(){ generate_random_positions(); for(var i=0; i<5; i++){ stackedObjects[i] = 0; } $("#imageSection").html(""); for(var i=0; i<10; i++){ $("#imageSection").append('<div id="dragImg'+i+'" class="dragObjects">'); $("#imageSection").append('</div>'); } var x=0; var randImgPos; for(var i=0; i<5; i++){ for(var j=0; j<randImages[i];j++){ randImgPos = randPositions[x]; $('#dragImg'+randImgPos).css('background-image','url(assets/image/'+objects[i]+'.png)'); dragImgPos[x] = randImgPos; x++; } } } /**** Drag Handling Functions ***/ $('.dragObjects').draggable({ containment: '#gameSection', scroll: false }); $('.dragObjects').bind('dragstart', function(event, ui) { currentDragObject = event.target.id; $('#'+currentDragObject).css('background-color','#93D7F9'); dragNumber = parseInt(currentDragObject.substring(7)); //assign the id for the images with dragNumber var x = 0; for(var i=0; i<5; i++){ for(var j=0; j<randImages[i];j++){ if(dragNumber === dragImgPos[x]){ draggedImage = i; } x++; } } }); /**** Drop Handling Functions ***/ $(".dropObjects").droppable({ tolerance: 'intersect', hoverClass: 'drophover' }); $('.dropObjects').bind('drop', function(event, ui) { currentDropObject = event.target.id; if(currentDropObject == "imageSection"){ //means returned to the prvious image section $('#'+currentDragObject).css('background-color','#CAFFCE'); } var topPos,leftPos,stack; dropNumber = parseInt(currentDropObject.substring(7)); dropRow = parseInt(dropNumber/11); dropCol = parseInt(dropNumber%11); //revert the dragged image back to its original position if not at correct place if(dropCol == 1){ y = 0; } if(dropCol == 3){ y = 1; } if(dropCol == 5){ y = 2; } if(dropCol == 7){ y = 3; } if(dropCol == 9){ y = 4; } if(dropCol%2 !=0 && draggedImage == y){ stacklevel = stackedObjects[y]; var stack = 6 - stacklevel; topPos = -43+(stack*64); leftPos = (-52+(dropCol*64))-(62*dragNumber); stackedObjects[y]= stacklevel + 1; $('#'+currentDragObject).draggable( 'disable' ); num_objects++; } else{ topPos = 5; leftPos = 5; $('#'+currentDragObject).css('background-color','#CAFFCE'); } $('#'+currentDragObject).css({'top': topPos+'px','left': leftPos+'px'}); //drop the object to fit the drop area check_bar_graph_completion(); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:758594af7f95ef916f6fecca9e438a190cdbb157dc29923b7d9cfada6de561d4 size 2543
/* * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ // German - strings /*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */ /*global define */ define({ 'TITLE': 'Occurrences Marker Einstellungen', 'ENABLED': 'Markiere Auftreten', 'TIME_INTERVAL': 'Wartezeit vor Markierung in Sekunden (0 - 10)', 'EXCLUDE': 'Folgende Dateitypen von der Markierung ausschließen', 'SELECTED_ONLY': 'Markiere nur ausgewählten Text und nicht das Wort unter dem Cursor', 'BACKGROUND_COLOR': 'Hintergrundfarbe oder CSS Style für Markierungen', 'ANIM': 'Markierungen animieren', 'CANCEL': 'Abbrechen', 'DONE': 'Fertig' });
export default function(server) { server.createList('car', 10); server.createList('part', 10, { car_id: 1 }); // Seed your development database using your factories. This // data will not be loaded in your tests. // server.createList('contact', 10); }
$('#input-form2').one('submit',function(){ var inputq11 = encodeURIComponent($('#input-q11').val()); var inputq12 = encodeURIComponent($('#input-q12').val()); var inputq13 = encodeURIComponent($('#input-q13').val()); var inputq14 = encodeURIComponent($('#input-q14').val()); var inputq15 = encodeURIComponent($('#input-q15').val()); var inputq16 = encodeURIComponent($('#input-q16').val()); var inputq17 = encodeURIComponent($('#input-q17').val()); var inputq18 = encodeURIComponent($('#input-q18').val()); var inputq19 = encodeURIComponent($('#input-q19').val()); var inputq20 = encodeURIComponent($('#input-q20').val()); var q11ID = "entry.251838911"; var q12ID = "entry.381860659"; var q13ID = "entry.1389576103"; var q14ID = "entry.1177177518"; var q15ID = "entry.1231175216"; var q16ID = "entry.213420359"; var q17ID = "entry.1623121702"; var q18ID = "entry.522561307"; var q19ID = "entry.1828892445"; var q20ID = "entry.328542916"; var baseURL2 = 'https://docs.google.com/forms/d/e/1FAIpQLSef32bXUVXKJmlMg1C6v3FAWyQ1Lh8VvsKbLl2ndMxoAc9hjg/formResponse?'; var submitRef2 = '&submit=Submit'; var submitURL2 = (baseURL2 +q11ID + "=" + inputq11 + "&" + q12ID + "=" + inputq12 + "&" + q13ID + "=" + inputq13 + "&" + q14ID + "=" + inputq14 + "&" + q15ID + "=" + inputq15 + "&" + q16ID + "=" + inputq16 + "&" + q17ID + "=" + inputq17 + "&" + q18ID + "=" + inputq18 + "&" + q19ID + "=" + inputq19 + "&" + q20ID + "=" + inputq20 + "&" + submitRef2); // console.log(submitURL); $(this)[0].action=submitURL2; // $('#input-feedback').text('Thank You!'); }); // var FB_PUBLIC_LOAD_DATA_ = [null, [null, [ // // [208930674, "Nume, Prenume", null, 1, [ // // [251838911, null, 0] // // ]], // // [907255577, "Nr. de telefon", null, 1, [ // // [381860659, null, 0] // // ]], // // [13760712, "Email", null, 1, [ // // [1389576103, null, 0] // // ]], // // [1009252901, "Grupa", null, 1, [ // // [213420359, null, 0] // // ]], // [250942002, "Facultatea", null, 1, [ // [1231175216, null, 0] // ]], // [447970812, "Facebook link", null, 1, [ // [1177177518, null, 0] // ]], // [1874621295, "Ai echipă? Dacă da, specifică numele echipei și a membrilor.", null, 1, [ // [1623121702, null, 0] // ]], // [1982582975, "1) Intrebare tehnica 1 ", null, 1, [ // [522561307, null, 0] // ]], // [1745046284, "2) Intrebare tehnica 2", null, 1, [ // [1828892445, null, 0] // ]], // [377484222, "Cum ai auzit de noi?", null, 1, [ // [328542916, null, 0] // ]]
'use strict'; var StakeController = {}; /** * Module dependencies. */ var util = require('../utilities/util'), stakeService = require('../services/stake'); module.exports = StakeController; StakeController.fnReadByID = function(req, res) { var id = req.params.id || req.body.id; var promise = stakeService.fnReadById(id); util.fnProcessServicePromiseInController(promise, res); };
// This is the proper way to start a javascript library (function() { // This makes the arguments variable behave the way we want it to and a few // other things. For more info: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode 'use strict'; // This allows us to use our "_" anywhere. In a web browser, properties of window // are available everywhere without having to type "window." /* global _ */ window._ = {}; /** * START OF OUR LIBRARY! * Implement each function below it's instructions */ /** _.identity() * Arguments: * 1) Anything * Objectives: * 1) Returns <anything> unchanged * Examples: * _.identity(5) === 5 * _.identity({a: "b"}) === {a: "b"} */ _.identity = function(anything){ return anything; } /** _.typeOf() * Arguments: * 1) Anything * Objectives: * 1) Return the type of <anything> as a string * Types are one of: * - "string" * - "array" * - "object" * - "undefined" * - "number" * - "boolean" * - "null" * - "function" * Examples: * _.typeOf(134) -> "number" * _.typeOf("javascript") -> "string" * _.typeOf([1,2,3]) -> "array" */ _.typeOf = function(anything){ if (anything === null){ return "null"; } else if (anything instanceof Date){ return "date"; } else if (Array.isArray(anything)){ return "array"; } else { return typeof anything; } }; /** _.first() * Arguments: * 1) An array * 2) A number * Objectives: * 1) If <array> is not an array, return [] * 2) If <number> is not given or not a number, return just the first element in <array>. * 3) Otherwise, return the first <number> items of <array> * Gotchas: * 1) What if <number> is negative? * 2) What if <number> is greater than <array>.length? * Examples: * _.first(["a","b","c"], 1) -> "a" * _.first(["a","b","c"], 2) -> ["a", "b"] * _.first(["a", "b", "c"], "ponies") -> ["a","b","c"] */ _.first = function(array, number){ if(!Array.isArray(array)){ return []; } if (number < 0){ return []; } if (number === undefined || typeof number !== "number"){ return array[0]; } else if (number > array.length){ return array; } else { var container = []; for (var i = 0; i < number; i++){ container.push(array[i]); } return container; } }; /** _.last() * Arguments: * 1) An array * 2) A number * Objectives: * 1) If <array> is not an array, return [] * 2) If <number> is not given or not a number, return just the last element in <array>. * 3) Otherwise, return the last <number> items of <array> * Gotchas: * 1) What if <nubmer> is negative? * 2) What if <number> is greater than <array>.length? * Examples: * _.last(["a","b","c"], 2) -> ["b","c"] * _.last(["a", "b", "c"], "ponies") -> ["a","b","c"] */ _.last = function(array, number){ if (!Array.isArray(array)){ return []; } else if (number === undefined || typeof number !== "number"){ return array[array.length-1]; } else if (number < 0){ return []; } else if (number > array.length){ return array; } else { var container = []; for (var i = array.length-number; i<array.length; i++){ container.push(array[i]); } return container; } } /** _.each() * Arguments: * 1) A collection * 2) A function * Objectives: * 1) if <collection> is an array, call <function> once for each element * with the arguments: * the element, it's index, <collection> * 2) if <collection> is an object, call <function> once for each property * with the arguments: * the property's value, it's key, <collection> * Examples: * _.each(["a","b","c"], function(e,i,a){ console.log(e)}); * -> should log "a" "b" "c" to the console */ _.each = function(collection, fun){ if (Array.isArray(collection)){ for (var i = 0; i<collection.length; i++){ fun(collection[i], i, collection); } } else if (collection instanceof Object){ for (var keys in collection){ fun(collection[keys], keys, collection); } } } /** _.indexOf() * Arguments: * 1) An array * 2) A value * Objectives: * 1) Return the index of <array> that is the first occurrance of <value> * 2) Return -1 if <value> is not in <array> * 3) Do not use [].indexOf()! * Gotchas: * 1) What if <array> has multiple occurances of val? * 2) What if <val> isn't in <array>? * Examples: * _.indexOf(["a","b","c"], "c") -> 2 * _.indexOf(["a","b","c"], "d") -> -1 */ _.indexOf = function(array, value){ for (var i = 0; i<array.length; i++){ if (value === array[i]){ return i; } } return -1; } /** _.filter() * Arguments: * 1) An array * 2) A function * Objectives: * 1) call <function> for each element in <array> passing the arguments: * the element, it's index, <array> * 2) return a new array of elements for which calling <function> returned true * Gotchas: * 1) What if <function> returns something other than true or false? * Examples: * _.filter([1,2,3,4,5], function(x){return x%2 === 0}) -> [2,4] * Extra Credit: * use _.each in your implementation */ _.filter = function(array, test){ ///named the function; params array, test var container = []; //because we're filtering and don't wanna modify outside of the scope, we make a new container _.each(array, function(el, i, array){ //implementing "each", with params of array(same as filter funtion) and A.F. (anonymousAFfunction) //for (var i = 0; i<array.length; i++){ //each already did this step for us, which is why its commented out if (test(el, i, array) === true){ //the A.F.'s code says that if the test on the parameters comes back true, push the element to the containter container.push(el)} }) return container; //returns the container, outside of the A.F., and outside of the each function. }; /** _.reject() * Arguments: * 1) An array * 2) A function * Objectives: * 1) call <function> for each element in <array> passing the arguments: * the element, it's index, <array> * 2) return a new array of elements for which calling <function> returned false * 3) This is the logical inverse if _.filter(), you must use _.filter() in your implementation * Examples: * _.reject([1,2,3,4,5], function(e){return e%2 === 0}) -> [1,3,5] */ _.reject = function(array, fun){ //set the name of the function and its paramete return _.filter(array, function(val, pos, coll){ //return the filter function; it needs the array(from reject params), and a function of its own return !fun(val, pos, coll); //this function returns NOTtrue values for the test passed in the reject filter. }) } //we want to use the filter function, which we'll pass the collection to and an anonymous function to test whether it's true/false //that anonymous function will push all of the false element to our new array, which we'll return. /** _.partition() * Arguments: * 1) An array * 2) A function * Objectives: * 1) Call <function> for each element in <array> passing it the arguments: * element, key, <array> * 2) Return an array that is made up of 2 sub arrays: * 0) An array that contains all the values for which <function> returned something truthy * 1) An array that contains all the values for which <function> returned something falsy * Gotchas: * 1) This is going to return an array of arrays. * Examples: * _.partition([1,2,3,4,5], function(element,index,arr){ * return element % 2 === 0; * }); -> [[2,4],[1,3,5]] } */ _.partition = function(array, func){ let truthy = _.filter(array, func); //the input function of the partition call. let falsy = _.reject(array, func); //as a param--and that function is defined as the func param from partition, with params el, i, coll. let result = [truthy, falsy]; //since we know we should have two arrays and we want it in an array, we set result to an array containing return result; //truthy and falsy; returned the result. } //return [_.filter(array, func), _.reject(array, func)] // one line solution. filter/reject both take arrays and test functions; extra work in mine. /** _.unique() * Arguments: * 1) An array * Objectives: * 1) Return a new array of all elements from <array> with duplicates removed * 2) Use _.indexOf() from above * Examples: * _.unique([1,2,2,4,5,6,5,2]) -> [1,2,4,5,6] */ /* _.indexOf = function(array, value){ for (var i = 0; i<array.length; i++){ if (value === array[i]){ return i; } } return -1; } */ //we're comparing two values; if the container value is not equal to arr val, push arrVal to container; so for evrey number not in container, we push. /*_.unique = function(array){ let container = []; _.each(array, function(el, i, array){ if(_.indexOf(array, container[container.length-1]) === -1){ container.push(array[i]); } }) return container; } */ _.unique = function(array){ var newArr = []; //we want to use indexOf, which will return the i value for an el matching a given value. //each can help us iterate through a list. indexOf can help us identify the position of the duplicate. _.filter(array, function(val, i, array){ //the filter returns values for which the test A.F. returns true. The A.F. takes params val, i, array if (_.indexOf(array, val) === i) //and tests if the value in some position in the array first occurs at i. newArr.push(val); //if that comes back true, the value gets pushed the the array. If false, it does not. }) return newArr; } /** _.map() * Arguments: * 1) A collection * 2) a function * Objectives: * 1) call <function> for each element in <collection> passing the arguments: * if <collection> is an array: * the element, it's index, <collection> * if <collection> is an object: * the value, it's key, <collection> * 2) save the return value of each <function> call in a new array * 3) return the new array * Examples: * _.map([1,2,3,4], function(e){return e * 2}) -> [2,4,6,8] */ _.map = function(collection, fun){ var output = []; //needs somewhere to push to _.each(collection, function(el, i, coll){ //each iterates through output.push(fun(el, i, coll)); //pushes the output of the fun argument to the output container }) return output; //return output } /** _.pluck() * Arguments: * 1) An array of objects * 2) A property * Objectives: * 1) Return an array containing the value of <property> for every element in <array> * 2) You must use _.map() in your implementation. * Examples: * _.pluck([{a: "one"}, {a: "two"}], "a") -> ["one", "two"] */ _.pluck = function(arr, prop){ let container = []; _.map(arr, function(valOb, i, col){ return container.push(valOb[prop]); }) return container; } /* _.pluck = function(arrObj, prop){ return _.map(arrObj, function(el, i, coll){ //return the map function return arrObj[i][prop]; //function returns }) } */ /** _.contains() * Arguments: * 1) An array * 2) A value * Objectives: * 1) Return true if <array> contains <value> * 2) Return false otherwise * 3) You must use the ternary operator in your implementation. * Gotchas: * 1) did you use === ? * 2) what if no <value> is given? * Examples: * _.contains([1,"two", 3.14], "two") -> true */ //NUMBER 13 _.contains = function(array, value){ var fill = _.filter(array, function(el, i, col){ return array[i] === value }) return fill.length > 0 ? true : false; } /** _.every() * Arguments: * 1) A collection * 2) A function * Objectives: * 1) Call <function> for every element of <collection> with the paramaters: * if <collection> is an array: * current element, it's index, <collection> * if <collection> is an object: * current value, current key, <collection> * 2) If the return value of calling <function> for every element is true, return true * 3) If even one of them returns false, return false * 4) If <function> is not provided, return true if every element is truthy, otherwise return false * Gotchas: * 1) what if <function> doesn't return a boolean * 2) What if <function> is not given? * Examples: * _.every([2,4,6], function(e){return e % 2 === 0}) -> true * _.every([1,2,3], function(e){return e % 2 === 0}) -> false */ //NUMBER 14 _.every = function(col, fun){ let flag = true; //if everything passes as true, return true; //if it's not true, change the flag; var fill = []; if (fun === undefined){ fun = _.identity; } _.each(col, function(el, i, col){ if(fun(el, i, col) === false){ flag = false; } }); return flag; } /*if (fun(val, i, col) === true){ return true } else { return false; } }) }; */ /*_.each(col, function(el, i, collection){ if (fun(el, i, collection) === false){ return false; } return true; }) }*/ //NUMBER 15 /** _.some() * Arguments: * 1) A collection * 2) A function * Objectives: * 1) Call <function> for every element of <collection> with the paramaters: * if <collection> is an array: * current element, it's index, <collection> * if <collection> is an object: * current value, current key, <collection> * 2) If the return value of calling <function> is true for at least one element, return true * 3) If it is false for all elements, return false * 4) If <function> is not provided return true if at least one element is truthy, otherwise return false * Gotchas: * 1) what if <function> doesn't return a boolean * 2) What if <function> is not given? * Examples: * _.some([1,3,5], function(e){return e % 2 === 0}) -> false * _.some([1,2,3], function(e){return e % 2 === 0}) -> true */ _.some = function(col, fun){ let flag = false; if (fun === undefined){ fun = _.identity; } _.each(col, function(el, i, col){ if(fun(el, i, col) === true){ flag = true; } }) return flag; } //NUMBER 16 /** _.reduce() * Arguments: * 1) An array * 2) A function * 3) A seed * Objectives: * 1) Call <function> for every element in <collection> passing the arguments: * previous result, element, index * 2) Use the return value of <function> as the "previous result" * for the next iteration * 3) On the very first iteration, use <seed> as the "previous result" * 4) If no <seed> was given, use the first element/value of <collection> as <seed> * 5) After the last iteration, return the return value of the final <function> call * Gotchas: * 1) What if <seed> is not given? * Examples: * _.reduce([1,2,3], function(previousSum, currentValue, currentIndex){ return previousSum + currentValue }, 0) -> 6 */ _.reduce = function(array, combine, seed){ let combined = seed, i = 0; if (combined === undefined){ combined = array[0]; i = 1; } for (; i<array.length; i++){ combined = combine(combined, array[i], i, array); } return combined; }; //NUMBER 17 /** _.extend() * Arguments: * 1) An Object * 2) An Object * ...Possibly more objects * Objectives: * 1) Copy properties from <object 2> to <object 1> * 2) If more objects are passed in, copy their properties to <object 1> as well, in the order they are passed in. * 3) Return the update <object 1> * Examples: * var data = {a:"one"}; * _.extend(data, {b:"two"}); -> data now equals {a:"one",b:"two"} * _.extend(data, {a:"two"}); -> data now equals {a:"two"} */ _.extend = function(object1, object2){ let theArgs = arguments; for (var keys in object2){ object1[keys] = object2[keys] } for (var i = 0; i < theArgs.length; i++){ for (var keys in theArgs[i]){ object1[keys] = theArgs[i][keys]; } } return object1; } // This is the proper way to end a javascript library }());
import { ms } from "../src/milsymbol"; ms.reset(); import { app6b } from "stanagapp6"; import verify from "./letter-sidc"; ms.setStandard("APP6"); import { air as icons } from "../src/lettersidc"; ms.addIcons(icons); export default verify(ms, "APP-6 B Air", app6b.WAR.AIRTRK);
'use strict'; var fs = require('fs'); var path = require('path'); var Sequelize = require('sequelize'); var env = process.env.NODE_ENV || 'development'; var config = require(__dirname + '/../bin/config.json')[env]; var sequelize = new Sequelize('postgres:/Southwind'); var db = {}; // if (config.use_env_variable) { // var sequelize = new Sequelize(process.env[config.use_env_variable]); // } else { // } fs .readdirSync(__dirname) .filter(function(file) { return (file.indexOf('.') !== 0) && (file !== 'index.js'); }) .forEach(function(file) { var model = sequelize.import(path.join(__dirname, file)); model.removeAttribute('id') model.removeAttribute('createdAt') model.removeAttribute('updatedAt') db[model.name] = model; }); Object.keys(db).forEach(function(modelName) { if (db[modelName].associate) { db[modelName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; module.exports = db;
const coap = require('coap') ,request = coap.request ,bl = require('bl') ,req = request({hostname: 'localhost',port:5683,pathname: '',method: 'POST'}); req.setOption('Block2', [new Buffer('1'),new Buffer("'must'"), new Buffer('23'), new Buffer('12')]); req.setHeader("Accept", "application/json"); req.on('response', function(res) { res.pipe(bl(function(err, data) { console.log(data); process.exit(0); })); }); req.end();
'use strict'; var React = require('react') var subscribeUIEvent = require('subscribe-ui-event') /* * <_Resize_ onResize={this.handleResize} throttle='raf' /> */ class _Resize_ extends React.Component { constructor() { super() this.resize = null this.resizeStart = null this.resizeEnd = null } // May want to remove this in the future and dynamically modify subscriptions if a prop changes shouldComponentUpdate() { return false } componentDidMount() { const options = { throttle: this.props.throttle, enableResizeInfo: this.props.passInfo, useRAF: this.props.throttle === 'RAF', } // resizeing handled by subscribe-ui-event if (this.props.onResize) { this.resize = subscribeUIEvent.subscribe('resize', this.handleResize, options) } if (this.props.onStart) { this.resizeStart = subscribeUIEvent.subscribe('resizeStart', this.handleResizeStart, options) } if (this.props.onEnd) { this.resizeEnd = subscribeUIEvent.subscribe('resizeEnd', this.handleResizeEnd, options) } } componentWillUnmount() { if (this.resize !== null) { this.resize.unsubscribe() } if (this.resizeStart !== null) { this.resizeStart.unsubscribe() } if (this.resizeEnd !== null) { this.resizeEnd.unsubscribe() } } handleResize = (e, { resize }) => { this.props.onResize(e, resize) } handleResizeStart = (e, { resize }) => { this.props.onStart(e, resize) } handleResizeEnd = (e, { resize }) => { this.props.onEnd(e, resize) } render() { return null } } module.exports = _Resize_
module.exports = [ { a: true, b: true, c: true, e: true, f: true, g: true, h: true, i: true, j: true, k: true, l: true, m: true, n: true, o: true, p: true, q: true, r: true, s: true, t: true, u: true, } ];
/* * blogdown * * Copyright (c) 2013 Maximilian Antoni <mail@maxantoni.de> * * @license MIT */ 'use strict'; var RESET = '\x1B[0m'; var NORMAL = '\x1B[0;'; var BOLD = '\x1B[1;'; var WHITE = '37m'; var YELLOW = '33m'; var RED = '31m'; function wrap(fn, prefix, color) { return function () { var args = Array.prototype.slice.call(arguments); var msg = args[0]; if (typeof msg === 'string') { args[0] = color + prefix + msg + RESET; } fn.apply(console, args); }; } var log = console.log; console.log = function () {}; console.info = wrap(log, '[INFO ] ', BOLD + WHITE); console.warn = wrap(log, '[WARN ] ', NORMAL + YELLOW); console.error = wrap(log, '[ERROR] ', NORMAL + RED); exports.enableDebug = function () { console.log = wrap(log, '[DEBUG] ', NORMAL + WHITE); };
/** * Created by Maurice on 6/17/2015. */ var gulp = require('gulp'); var mocha = require('gulp-mocha'); gulp.task('mocha', function() { return gulp.src('test/index-tests.js', { read: false }).pipe(mocha()); }); gulp.task('watch', function() { gulp.watch('**/*.js', ['mocha']); }); gulp.task('default', ['mocha', 'watch']);
let pieceToFunc = { 'pawn': pawnMoveCheck, 'knight': knightMove, 'bishop': bishopMove, 'rook': rookMove, 'queen': queenMove, 'king': kingMove } let threatCheck = { 'pawn': pawnThreat, 'knight': knightMove, 'bishop': bishopMove, 'rook': rookMove, 'queen': queenMove, 'king': kingMove } function isMate(pieces, player){ let possibles = [] let ownPieces = pieces.filter(p => p.owner === player) ownPieces.forEach(p => { let pMoves = pieceToFunc[p.piece](pieces, player, p, true) pMoves.length > 0 ? possibles.push(...pMoves) : null }) return possibles } function isCheck(pieces, player){ let ks = pieces.find(p => p.piece === 'king' && p.owner === player) let opp = pieces.filter(p => p.owner !== player) let threats = [] opp.forEach(o =>{ let pMoves = threatCheck[o.piece](pieces, player^1, o, false) pMoves.length > 0 ? threats.push(...pMoves) : null }) threats = threats.filter(t => t[0] === ks.x && t[1] === ks.y) //console.log( threats) return threats.length > 0 ? true : false } function checkCheck(pieces, piece, trgt){ let oP = {'x': piece.x, 'y': piece.y} let tI = pieces.findIndex(p => p.x === trgt.x && p.y === trgt.y) let oTP tI > -1 ? oTP = pieces.splice(tI,1) : null piece.x = trgt.x piece.y = trgt.y let res = isCheck(pieces, piece.owner) piece.x = oP.x piece.y = oP.y if (oTP){ pieces.splice(0,0,oTP[0]) } return res } function pawnMoveCheck(pieces, player, pawn, check){ let moves = pawnMove(pieces, player, pawn, check) let takes = pawnThreat(pieces, player, pawn, check) return [...moves, ...takes] } function pawnThreat(pieces, player, pawn, check){ let takes = [] let flip = (-player || 1) let range = [-1,1] range.forEach(r => { if (pieces.find(p => p.x === pawn.x + r && p.y === pawn.y + flip && p.owner !== player)){ let trgt = {'x': pawn.x+r, 'y': pawn.y+flip} if (!check || !checkCheck(pieces, pawn, trgt)){ takes.push([pawn.x + r, pawn.y + flip]) } } // en passant (needs move history to remove captured pawn from pieces) if (pieces.find(p => p.x == pawn.x + r && p.y === (flip ? 4 : 3) && p.piece === 'pawn' && p.owner !== player)){ takes.push([pawn.x + r, pawn.y + flip]) } }) return takes } function pawnMove(pieces, player, pawn, check){ let moves = [] let flip = (-player || 1); if (! pieces.find(p => p.x === pawn.x && p.y === pawn.y + flip)){ let trgt = {'x': pawn.x, 'y': pawn.y + flip} if (!check || !checkCheck(pieces, pawn, trgt)){ moves.push([pawn.x, (pawn.y + flip)]) } } if (pawn.y === (7+flip)%7 && !pieces.find(p => p.x === pawn.x && p.y === pawn.y + flip*2)){ let trgt = {'x': pawn.x, 'y': pawn.y + flip*2} if (!check || !checkCheck(pieces, pawn, trgt)){ moves.push([pawn.x, pawn.y + flip*2]) } } return moves } function knightMove(pieces, player, knight, check){ let moves = [] let x = [1,-1, 2, -2]; for (let i=0; i<x.length; i++){ for (let j=0; j<x.length; j++){ if (Math.abs(x[i]) !== Math.abs(x[j])){ if (knight.x+x[i]<8 && knight.y+x[j]<8 && knight.x+x[i]>-1 && knight.y+x[j]>-1){ if (!pieces.find(p => p.x === knight.x+x[i] && p.y === knight.y+x[j] && p.owner === player)){ let trgt = {'x': knight.x+x[i], 'y': knight.y+x[j]} if (!check || !checkCheck(pieces, knight, trgt, false)){ moves.push([knight.x + x[i], knight.y + x[j]]) } } } } } } return moves } function bishopMove(pieces, player, bishop, check){ let moves = [] let dir = [-1, 1] dir.forEach(dX => { dir.forEach(dY => { let rangeX = (dX === 1 ? 7 - bishop.x : bishop.x) let rangeY = (dY === 1 ? 7 - bishop.y : bishop.y) let range = rangeX < rangeY ? rangeX : rangeY for (let r=1; r<range+1; r++){ let sq = pieces.find(p => p.x === bishop.x + (r*dX) && p.y === bishop.y + (r*dY)) let trgt = {'x': bishop.x + r*dX, 'y': bishop.y + r*dY} if(!sq){ if (!check || !checkCheck(pieces, bishop, trgt, false)){ moves.push([(bishop.x + r*dX),(bishop.y + r*dY)]) } } else if (sq.owner !== player){ if (!check || !checkCheck(pieces, bishop, trgt, false)){ moves.push([sq.x, sq.y]) break } } else break } }) }) return moves } function rookMove(pieces, player, rook, check){ let moves = [] let dir = [-1,1] dir.forEach(dX =>{ let rangeX = (dX === 1 ? 7 - rook.x : rook.x) for (let x=1; x<rangeX+1; x++){ let trgt = pieces.find(p => p.x === rook.x + x*dX && p.y === rook.y) let sq = {'x': rook.x + x*dX, 'y': rook.y} if (!trgt){ if (!check || !checkCheck(pieces, rook, sq, false)){ moves.push([sq.x, sq.y]) } } else if (trgt.owner !== player){ if (!check || !checkCheck(pieces, rook, trgt, false)){ moves.push([sq.x, sq.y]) break } } else break } }) dir.forEach(dY => { let rangeY = (dY === 1 ? 7 - rook.y : rook.y) for (let y=1; y<rangeY+1; y++){ let trgt = pieces.find(p => p.y === rook.y + y*dY && p.x === rook.x) let sq = {'x': rook.x, 'y': rook.y + y*dY} if (!trgt){ if (!check || !checkCheck(pieces, rook, sq, false)){ moves.push([sq.x, sq.y]) } } else if (trgt.owner !== player){ if (!check || !checkCheck(pieces, rook, trgt, false)){ moves.push([trgt.x, trgt.y]) break } } else break } }) return moves } function queenMove(pieces, player, queen, check){ let rMoves = rookMove(pieces, player, queen, check) let bMoves = bishopMove(pieces, player, queen, check) return [...bMoves, ...rMoves] } function kingMove(pieces, player, king, check){ let moves = [] let range = [-1,0,1] range.forEach(x => range.forEach(y => { if (x|y){ let kX = king.x + x let kY = king.y + y if (kX <= 7 && kX >= 0 && kY <= 7 && kY >= 0){ let sq = pieces.find(p => p.x === kX && p.y === kY) let trgt = {'x': kX, 'y': kY} if (!sq){ if (!check || !checkCheck(pieces, king, trgt, false)) moves.push([kX, kY]) } else if (sq.owner !== player){ if (!check || !checkCheck(pieces, king, trgt, false)) moves.push([kX, kY]) } } } }) ) return moves } module.exports = { pieceToFunc: pieceToFunc, isCheck: isCheck, isMate: isMate }
//= require jquery //= require ./jquery.ui.widget //= require ./jquery.iframe-transport //= require ./jquery.fileupload //= require ./upload //= require ./image_picker //= require ./fullscreen //= require ./Markdown.Converter //= require ./Markdown.Editor //= require ./editor
;(function () { 'use strict'; angular.module('app') .controller('NutzungDirectiveController', NutzungDirectiveController); NutzungDirectiveController.$inject = ['$scope']; function NutzungDirectiveController($scope) { let vm = this; vm.nutzung = $scope.nutzung; vm.zusatzliche = $scope.zusatzliche; vm.parseEuroFormat = parseEuroFormat; function parseEuroFormat(number) { if (typeof number === 'string') { return parseFloat((number.replace('.', '')).replace(',', '.')); }else { return number; } } } })();
var compose = require('ksf/utils/compose') var _Evented = require('ksf/base/_Evented') var delegateGetSet = require('./utils/delegateGetSet'); var getSet = require('./utils/getSet') var onOffEvent = require('./utils/onOffEvent') module.exports = compose(_Evented, function(ratioWH, content) { this._ratio = ratioWH this._content = content }, { _applyWidth: function(width) { this._content.width(width) this._emit('width', width) }, width: getSet( function() { return this._content.width() }, function(width) { this._applyWidth(width) this._applyHeight(width / this._ratio) } ), _applyHeight: function(height) { this._content.height(height) this._emit('height', height) }, height: getSet( function() { return this._content.height() }, function(height) { this._applyHeight(height) this._applyWidth(height * this._ratio) } ), left: delegateGetSet('_content', 'left'), top: delegateGetSet('_content', 'top'), zIndex: delegateGetSet('_content', 'zIndex'), depth: delegateGetSet('_content', 'depth'), parentNode: delegateGetSet('_content', 'parentNode'), containerVisible: delegateGetSet('_content', 'containerVisible'), visible: delegateGetSet('_content', 'visible'), }, onOffEvent('width'), onOffEvent('height') );
/* LG.js * Event * Dependant: core */ (function($lg, window) { if(!$lg) { return; } var lg = $lg.proto; $lg.event = { eventStore : {}, eventObj : function(event) { if(event.lg_fixed === $lg.expando) { return event; } var newevent = { lg_fixed : $lg.expando, originalEvent : event, bubbles : ('bubbles' in event) ? event.bubbles : (event.target && event.target.parentNode ? true : false), keyCode : event.keyCode || event.which, target : event.target || event.srcElement || document, defaultPrevented : false, propagationStopped : false, immediatePropagationStopped : false, stopPropagation : function() { if(this.originalEvent.stopPropagation) this.originalEvent.stopPropagation(); this.originalEvent.cancelBubble = this.propagationStopped = true; }, isPropagationStopped : function() { return this.propagationStopped; }, preventDefault : function() { this.defaultPrevented = true; if(this.originalEvent.preventDefault) this.originalEvent.preventDefault(); }, isDefaultPrevented : function() { return this.defaultPrevented; }, stopImmediatePropagation : function() { if(this.originalEvent.stopImmediatePropagation) this.originalEvent.stopImmediatePropagation(); this.immediatePropagationStopped = true; }, isImmediatePropagationStopped : function() { return this.immediatePropagationStopped; } }; for(var data in event) { if( !(data in newevent) ) { newevent[data] = event[data]; } } //real dom event or custom? newevent.custom = !(event instanceof window.Event); if( newevent.target.nodeType === 3 ) { newevent.target = newevent.target.parentNode; } if( !newevent.which ) { newevent.which = newevent.keyCode || newevent.charCode; } if( !newevent.metaKey ) { newevent.metaKey = newevent.ctrlKey; } return newevent; }, bind : function(target, type, handler) { if(type.indexOf(' ') > 0) { return $lg.array_walk(type.split(' '), function(t) { $lg.event.bind(target, t, handler); }); } var events = $lg(target).data('events') || {}; if(!events[type] && $lg.is_function(handler)) { events[type] = []; if(events.eventTypes) { events.eventTypes.push(type); } else { events.eventTypes = [type]; } try { if(target.attachEvent) { target.attachEvent('on' + type, $lg.event.listener); } else if(target.addEventListener) { target.addEventListener(type, $lg.event.listener); } }catch(e){}; //try-catch block to prevent errors with custom events. } if($lg.is_function(handler)) { handler.uid = $lg.unique_id(); events[type].push(handler); } $lg(target).data('events', events); }, listener : function(event) { if($lg.event.ignore !== event.target) { return $lg.event.trigger(event.target, event.type, event); } }, trigger : function(target, type, event) { if(event && !event.target) { event.target = target; } event = $lg.event.eventObj(event || {target: target}); var propagation = [] , events = null; //create a propagation path. do { events = $lg(target).data('events') || {}; if(events[type]) { propagation.push({target:target, handlers:events[type]}); } } while(event.bubbles && (target = target.parentNode)) if(propagation.length === 0) { return; } $lg.array_walk(propagation, function(data) { if( !event.isPropagationStopped() ) { var ret = true; //since we stop natural propagation, inline handlers won't fire. So do this manually too. if(data.target['on' + type]) { ret = data.target['on' + type].call(data.target, event); } //call all the handlers of this target unless immProp is stopped. $lg.array_walk(data.handlers, function(fn) { if( !event.isImmediatePropagationStopped() && fn.call(data.target, event) === false) { ret = false; } }); if(ret === false) { //allow preventing default by returning false event.preventDefault(); } } }); //we must fire the actual dom event for manually fired funcs. Aka, for 'click', they haven't actually clicked. So we must click for em. if(event.custom && !event.isDefaultPrevented() && $lg.is_function(event.target[type])) { $lg.event.ignore = event.target; event.target[type](); $lg.event.ignore = null; } //now we stop the native propagation, since we've done it ourselves. if(!event.isPropagationStopped()) { event.stopPropagation(); } }, remove : function(target, type, fn) { if(!target) return; //a target is needed at least. var events = $lg(target).data('events') , types , removeListener = false; if(events) { if(type && (types = events[type])) { //if a specific event type has been specified if(fn) { types = $lg.array_walk('f', types, function(f) { return f.uid !== fn.uid || f === fn; }); } else { types = []; } events[type] = types; if(types.length === 0) { removeListener = true; delete events[type]; } } else if(!type) { events = {eventTypes: events.eventTypes}; removeListener = true; } if(removeListener) { var removeTypes = type ? [type] : events.eventTypes; $lg.array_walk(removeTypes, function(t) { try { if(target.detachEvent) { target.detachEvent('on' + t, $lg.event.listener); } else if(target.removeEventListener) { target.removeEventListener(t, $lg.event.listener); } }catch(e){}; //try-catch block to prevent any errors with custom events. }); events.eventTypes = $lg.array_walk('f', events.eventTypes, function(t) { return t in events; }); } $lg(target).data('events', events); } } } lg.bind = lg.on = function(type, handler) { return this.all(function(elem) { $lg.event.bind(elem, type, handler); }); }; lg.fire = function(type, data) { if(type === 'hover') { return this.hover(); } return this.all(function(elem) { $lg.event.trigger(elem, type, $lg.is_object(data) ? data : {}); }); }; lg.removeEvent = function(type, fn) { return this.all(function(elem) { $lg.event.remove(elem, type, fn); }); }; //fixed mouseenter for cross-browser. One that doesn't fire when entering or leaving child element. lg.hover = function(enter, leave) { if( $lg.is_function(enter) ) { if('mouseenter' in document.body) { this.bind('mouseenter', enter) } else { this.mouseover(function(e) { if( e.custom || (e.fromElement && !$lg(e.fromElement.tagName.toLowerCase(), this).includes(e.fromElement)) ) { enter.call(this, e); } }); } } if( $lg.is_function(leave) ) { if('mouseleave' in document.body) { return this.bind('mouseleave', leave) } else { this.mouseout(function(e) { if( e.custom || (e.toElement && !$lg(e.toElement.tagName.toLowerCase(), e.target).includes(e.toElement)) ) { leave.call(this, e); } }); } } if(!enter && !leave) { this.fire('mouseenter' in document.body ? 'mouseenter' : 'mouseover'); } return this; }; $lg.array_walk(('close click dblclick mouseup mousedown mouseover mouseout mousemove contextmenu keydown keypress keyup load unload error resize scroll blur focus change submit select reset change').split(' '), function(name) { lg[name] = function(fn) { return $lg.is(fn, 'function') ? this.bind(name, fn) : this.fire(name, fn); }; }); $lg.installed.event = 1; })($lg, window);
import { Config } from "loco-js-model"; Config.protocolWithHost = "http://localhost:3000";
var express = require('express'); var router = express.Router(); var filter = require('./passport.js'); var Page = require('../db/page'); router.post('/', function (req, res, next) { filter.authorize(req, res, function (req, res) { var itemId = req.body.itemId; var type = req.body.type; var pageId = req.body.pageId; Page.copyItem(itemId, type, pageId,function (err, itemEntity) { if (err) { res.status('500'); res.send({ success: false, // 标记失败 model: { error: '系统错误' } }); } else { res.status('200'); res.send({ success: true, model: itemEntity }); } }); }); }); module.exports = router;
$(function() { $('.votes span').click(function(e) { e.preventDefault(); var url, element = $(this); if ($(this).data('type') == 'question') { url = '/app_dev.php/question/vote/'; } else if ($(this).data('type') == 'answer') { url = '/app_dev.php/answer/vote/'; } $.ajax({ url: url + $(this).data('id') + '/' + $(this).data('vote'), success: function (data, status) { if (isNaN(data)) { alert(data); } else { $(element).siblings('span.num').html(data); } } }); }); $('#add-tag').click(function (e) { e.preventDefault(); var inputCount = $('ul.tags').find('input').length; var formHtml = $('ul.tags').data('prototype'); $('ul.tags').append("<li>" + formHtml.replace(/__name__/g, inputCount) + "</li>"); }) });
import _ from 'underscore' export default class Sync { static checkMatches (payload) { const storage = SyncStorage.getStored() let notification = false if (storage.matches.length) { payload.matches.forEach(function (match) { const storedMatch = _.findWhere(storage.matches, {_id: match._id}) const event = new CustomEvent('message', { 'detail': match }) if (!storedMatch) { match.new = true notification = true } else { match.new = storedMatch.new if (match.messages && !storedMatch.messages) { match.newMessage = true notification = true window.dispatchEvent(event) } else if (match.messages && storedMatch.messages) { if (match.messages.length > storedMatch.messages.length) { match.newMessage = true notification = true window.dispatchEvent(event) } else { match.newMessage = storedMatch.newMessage } } } }) } SyncStorage.setStored(payload) return notification } static getMatches () { return SyncStorage.getStored() } static addNewMatch (match) { match.new = true var stored = SyncStorage.getStored() stored.matches.unshift(match) SyncStorage.setStored(stored) } static addNewMessage (matchId, messages) { var stored = SyncStorage.getStored() for (var i = 0; i < stored.matches.length; i++) { if (stored.matches[i]._id === matchId) { stored.matches[i].messages = messages break } } SyncStorage.setStored(stored) } static unsetNew (matchId) { var stored = SyncStorage.getStored() for (var i = 0; i < stored.matches.length; i++) { if (stored.matches[i]._id === matchId) { stored.matches[i].new = false stored.matches[i].newMessage = false break } } SyncStorage.setStored(stored) } } class SyncStorage { static getStored () { if (localStorage.history) { return JSON.parse(localStorage.history) } else { return {matches: [], goingout: []} } } static setStored (data) { localStorage.history = JSON.stringify(data) } }
import initialState from './initialState'; import {LOAD_LIBRARIES_SUCCESS} from '../actions/'; export default function libraryReducer(state = initialState.library, action) { switch (action.type) { case LOAD_LIBRARIES_SUCCESS : { return action.payload; } default: return state; } }
var regex = /\/xyz/gi;
const Config = require('../../models/config'); describe('config model', () => { it('requires name', done => { const config = new Config(); config.validate() .then(() => done('expected error')) .catch(() => done()); }); it('validates with required fields', done => { const config = new Config({name: 'test', config_id: '1'}); config.validate() .then(done) .catch(done); }); });
(function () { 'use strict'; var coordToWGS84 = function(coord) { var wgs_coord = { "latitudeRef" : coord.latitude > 0 ? "N" : "S", "latitude" : [[Math.floor(Math.abs(coord.latitude)),1]], "longitudeRef" : coord.longitude > 0 ? "E" : "W", "longitude": [[Math.floor(Math.abs(coord.longitude)),1]], "altitudeRef" : 0, "altitude" : [coord.altitude, 1] }; var tmp = (Math.abs(coord.latitude) - wgs_coord.latitude[0][0]) * 60; wgs_coord.latitude.push( [ Math.floor(tmp), 1 ] ); wgs_coord.latitude.push( [ Math.floor( (tmp - wgs_coord.latitude[1][0]) * 6000 ), 100 ] ); tmp = (Math.abs(coord.longitude) - wgs_coord.longitude[0][0]) * 60; wgs_coord.longitude.push( [ Math.floor(tmp), 1 ] ); wgs_coord.longitude.push( [ Math.floor( (tmp - wgs_coord.longitude[1][0]) * 6000 ), 100 ] ); return wgs_coord; }; var addLines = function(lines) { var path = []; var max = { lat: null, lng: null }; var min = { lat: null, lng: null }; for (var i in lines) { path.push({ lat: lines[i].latitude, lng: lines[i].longitude }); max.lat = max.lat === null ? lines[i].latitude : Math.max(max.lat, lines[i].latitude); max.lng = max.lng === null ? lines[i].longitude : Math.max(max.lng, lines[i].longitude); min.lat = min.lat === null ? lines[i].latitude : Math.min(min.lat, lines[i].latitude); min.lng = min.lng === null ? lines[i].longitude : Math.min(min.lng, lines[i].longitude); } var flightPath = new google.maps.Polyline({ path: path, geodesic: true, strokeColor: '#FF0000', strokeOpacity: 1.0, strokeWeight: 2 }); flightPath.setMap(cgotag.map); var bounds = new google.maps.LatLngBounds(); flightPath.getPath().forEach(function(latLng) { bounds.extend(latLng); }); cgotag.map.fitBounds(bounds); cgotag.map.setCenter({ lat: (max.lat + min.lat) / 2, lng: (max.lng + min.lng) / 2 }); }; if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') { module.exports.cgotag.coordToWGS84 = coordToWGS84; // No add lines for nodejs } else { cgotag.coordToWGS84 = coordToWGS84; cgotag.addLines = addLines; } }());
import * as lamb from "../.."; describe("throttle", function () { var value = 0; var foo = jest.fn(function () { ++value; }); var now = Date.now(); jest.spyOn(Date, "now") .mockReturnValueOnce(now) .mockReturnValueOnce(now + 10) .mockReturnValueOnce(now + 50) .mockReturnValueOnce(now + 101) .mockReturnValueOnce(now + 151) .mockReturnValueOnce(now + 201); it("should return a function that will invoke the passed function at most once in the given timespan", function () { var throttledFoo = lamb.throttle(foo, 100); throttledFoo(); throttledFoo(); throttledFoo(); expect(foo).toHaveBeenCalledTimes(1); expect(value).toBe(1); foo.mockClear(); throttledFoo(); throttledFoo(); expect(foo).toHaveBeenCalledTimes(1); expect(value).toBe(2); throttledFoo(); expect(foo).toHaveBeenCalledTimes(2); expect(value).toBe(3); }); });
(function(){ 'use strict'; angular.module('topFive.search', []); })();
import { parser as saxParser } from 'sax'; function isAllowedType(type) { switch(type) { case 'text': case 'opentag': case 'closetag': case 'doctype': case 'processinginstruction': case 'attribute': case 'comment': case 'opencdata': case 'closecdata': case 'opennamespace': case 'closenamespace': case 'opentagstart': return true; default: return false; } } function clone(node) { const out = {}; for(let key in node) { const value = node[key]; if(typeof value === 'object') { out[key] = clone(value); } else { out[key] = value; } } return out; } export function makePulley(xml, options) { if(!options) options = {}; const types = options.types || ['opentag', 'closetag', 'text']; const opentag = options.opentag || (function() { for(let i = 0; i < types.length; ++i) { if(types[i] === 'opentagstart') { return 'opentagstart'; } return 'opentag'; } })(); if(opentag !== 'opentag' && opentag !== 'opentagstart') { throw Error(`options.opentag must be an opening tag type, not ${opentag}!`); } const queue = []; const parser = saxParser(true, { xmlns: options.xmlns, position: false }); const skipWS = options.skipWhitespaceOnly; const trim = options.trim, normalize = options.normalize; const textOpts = (t) => { if(trim) t = t.trim(); if(normalize) t = t.replace(/\s+/g, " ") return t; }; let text = null, rawText = null, wsText = null, wsRawText = null; const flushText = () => { if(skipWS && wsText !== null) { queue.push({ type: 'wstext', text: wsText, rawText: wsRawText, wsHasNext: text !== null }); wsText = wsRawText = null; } if(text !== null) { queue.push({ type: 'text', text, rawText }); text = rawText = null; } }; parser.onerror = (err) => { throw err; }; types.forEach((type) => { if(type === 'text') { parser.ontext = (t) => { const pt = textOpts(t); if(skipWS) { if(wsText) { wsText += pt; wsRawText += t; } else { wsText = pt; wsRawText = t; } } if(!skipWS || /\S/.test(t)) { if(text) { text += pt; rawText += t; } else { text = pt; rawText = t; } } }; parser.oncdata = (t) => { if(text) { text += t; rawText += t; } else { text = rawText = t; } }; } else if(type === 'comment') { parser.oncomment = (t) => { flushText(); queue.push({ type: 'comment', text: textOpts(t), rawText: t }); } } else if(type === 'doctype') { parser.ondoctype = (t) => { flushText(); queue.push({ type: 'doctype', text: t }); } } else if(type === 'closetag') { parser.onclosetag = (t) => { flushText(); queue.push({ type: 'closetag', name: t }); } } else if(type === 'opencdata' || type === 'closecdata') { parser['on'+type] = (data) => { flushText(); queue.push({ type: type }); } } else if(isAllowedType(type)) { parser['on'+type] = (data) => { flushText(); data = clone(data); data.type = type; queue.push(data); } } else { throw Error(`${type} isn't an allowed type!`); } }); parser.write(xml).close(); flushText(); queue.reverse(); return constructPulley(queue, skipWS, opentag); } function constructPulley(queue, skipWS, opentag, checkoutcb) { let self; const next = skipWS ? () => { let out; while((out = queue.pop()) && out.type === 'wstext') { } return out; } : () => queue.pop(); const peek = skipWS ? () => { for(let i = queue.length - 1; i >= 0; --i) { const v = queue[i]; if(v.type !== 'wstext') return v; } } : () => queue[queue.length - 1]; const nextText = () => { const v = queue[queue.length - 1]; if(v && v.type === 'text') { return queue.pop(); } else if(v && v.type === 'wstext') { queue.pop(); if(v.wsHasNext) queue.pop(); return { type: 'text', text: v.text, rawText: v.rawText }; } else { return { type: 'text', text: '', rawText: '' }; } }; const peekText = () => { const v = queue[queue.length - 1]; if(v && v.type === 'text') { return v; } else if(v && v.type === 'wstext') { return { type: 'text', text: v.text, rawText: v.rawText }; } else { return { type: 'text', text: '', rawText: '' }; } }; const check = (type, error) => { const out = peek(); assertType(out, type, error); return out; }; const checkName = (name, type, wrongNameError, wrongTypeError) => { type = type || opentag; const out = peek(); assertType(out, type, wrongTypeError || wrongNameError); assertName(out, name, wrongNameError); return out; }; const expect = (type, error) => { const out = check(type, error); next(); return out; }; const expectName = (name, type, wrongNameError, wrongTypeError) => { const out = checkName(name, type, wrongNameError, wrongTypeError); next(); return out; }; const loop = (callback, endType) => { endType = endType || 'closetag'; let node; while((node = peek()) && node.type !== endType) { if(callback(self)) break; } }; const loopTag = (callback, name) => { const tag = name ? expectName(name) : expect(opentag); let node; while((node = peek()) && node.type !== 'closetag') { callback(self, tag); } expectName(tag.name, 'closetag'); return tag; }; const skipTag = (name) => { return loopTag((pulley) => { const tag = pulley.peek(); if(tag.type === opentag) { pulley.skipTag(tag.name); } else { pulley.next(); } }, name); }; const _checkoutcb = (queue2) => { queue = queue2; return self; }; const checkin = () => constructPulley(queue.slice(), skipWS, opentag, _checkoutcb); const checkout = checkoutcb ? () => { const parent = checkoutcb(queue); queue = []; return parent; } : () => { throw Error("Can't check out a pulley that wasn't checked in!"); }; return self = { next, peek, nextText, peekText, check, checkName, expect, expectName, loop, loopTag, skipTag, checkin, checkout }; } export function assertType(node, type, error) { if(node === undefined) { throw error || Error(`Expected ${type}; got end of file!`); } else if(node.type !== type) { throw error || Error(`Expected ${type}; got ${node.type}: ${nodeRepr(node)}!`); } } export function assertName(tag, name, error) { if(tag.name !== name) { throw error || Error(`${tag.type} had name ${tag.name} instead of ${name}!`); } } export function nodeRepr(tag) { switch(tag.type) { case 'text': case 'comment': return `"${tag.text}"`; case 'opentag': case 'opentagstart': return `<${tag.name}>`; case 'closetag': return `</${tag.name}>`; case 'doctype': return `<!${tag.text}>`; case 'processinginstruction': return `<?${tag.name} ${tag.body}?>`; case 'attribute': return `${tag.name}="${tag.value}"`; default: } }
'use strict'; var chai = require('chai-stack'); var prepare = require('../lib/prepare-db'); var rc = require('../lib/redis-client'); var t = chai.assert; suite('prepare-db'); before(function (done) { prepare(done); }); test('prepare(cb) creates namespaces hash if does not exist', function (done) { rc.hgetall('namespaces:', function (err, result) { t.isObject(result); t.isNotNull(result['cont:']); t.isNotNull(result['meta:']); t.isNotNull(result['id:']); t.isNotNull(result['url:']); t.isNotNull(result['srcurl:']); t.isNotNull(result['server:']); done(); }); }); test('running prepare(cb) multiple times is fine', function (done) { rc.hget('server:', 'id', function (err, result) { if (err) return done(err); prepare(function (err) { // called in before and now again if (err) return done(err); rc.hget('server:', 'id', function (err, result2) { t.equal(result2, result, 'server id should be the same once created'); done(); }); }); }); });
/** * Created by gurpreet.singh on 04/22/2015. */ 'use strict'; app.factory('CrudService', ['$http','$q', 'RestangularCustom', function ($http,$q, Restangular) { return{ getById : function(baseUrl, id){ return Restangular.one(baseUrl, id).get(); }, getAll : function(baseUrl){ return Restangular.all(baseUrl).getList(); }, add : function(baseUrl, objToAdd){ return Restangular.all(baseUrl).post(objToAdd); }, update:function(baseUrl, objToUpdate){ return Restangular.one(baseUrl, objToUpdate.Id).customPUT(objToUpdate); }, delete:function(baseUrl, objToUpdate){ return Restangular.one(baseUrl, objToUpdate.Id).remove(); }, search : function(baseUrl, objToSearch) { return Restangular.all(baseUrl).post(objToSearch); } }; }]);
var AMDFormatter = require('es6-module-transpiler-amd-formatter'); var PlsLoadFormatter = module.exports = function PlsLoadFormatter() { AMDFormatter.call(this); }; PlsLoadFormatter.prototype = Object.create(AMDFormatter.prototype); PlsLoadFormatter.prototype.constructor = PlsLoadFormatter; PlsLoadFormatter.prototype.build = function(modules) { return AMDFormatter.prototype.build.call(this, modules).map(function(ast) { var body = ast.program.body; var define = body[0]; var factory = define.expression.arguments[define.expression.arguments.length - 1].body; // rename the define call to plsload define.expression.callee.name = 'plsload'; // remove the module name, we key modules based on their url define.expression.arguments.shift(); // amd enables strict mode, but plsload needs to be more permissive factory.body.shift(); return ast; }); };
var webpack = require('webpack'); var config = require('./webpack.config'); var statsConfig = require('./statsConfig'); config.resolve.alias = { 'react': 'preact-compat', 'react-dom': 'preact-compat' }; config.entry = './src/DonutChartWebComponent.js'; config.output.filename = 'DonutChartWebComponent.js'; webpack(config).run(function (err, stats) { console.log(stats.toString(statsConfig)); });
var Transformer = require('tree-transformer'); var VisitorAsync = require('tree-visitor-async'); var _visitNode = VisitorAsync.prototype._visitNode; module.exports = TransformerAsync; function TransformerAsync() {} TransformerAsync.prototype = new VisitorAsync(); TransformerAsync.prototype._visitNodes = function (nodes) { var self = this; return visitNodesFrom(0); function visitNodesFrom(i) { var promise = _visitNode.call(self); if (i >= nodes.length) return promise.then(function () { return nodes }); return promise.then(function () { return _visitNode.call(this, nodes[i]); }).then(function (ret) { i = Transformer.replaceNode(ret, i, nodes); return visitNodesFrom(i); }); } }; TransformerAsync.prototype._visitNode = function (node) { return VisitorAsync.prototype._visitNode.call(this, node).then(function (ret) { return ret === undefined ? node : ret; }); };
// Generated by CoffeeScript 1.6.3 (function() { var DateRange, moment; moment = (typeof require !== "undefined" && require !== null) && !require.amd ? require("moment") : this.moment; /** * DateRange class to store ranges and query dates. * @typedef {!Object} * */ DateRange = (function() { /** * DateRange instance. * @param {(Moment|Date)} start Start of interval. * @param {(Moment|Date)} end End of interval. * @constructor * */ function DateRange(start, end) { this.start = moment(start); this.end = moment(end); } /** * Determine if the current interval contains a given moment/date. * @param {(Moment|Date)} moment Date to check. * @return {!boolean} * */ DateRange.prototype.contains = function(moment) { return (this.start <= moment && moment <= this.end); }; DateRange.prototype._by_string = function(interval, hollaback) { var current, _results; current = moment(this.start); _results = []; while (this.contains(current)) { hollaback.call(this, current.clone()); _results.push(current.add(interval, 1)); } return _results; }; DateRange.prototype._by_range = function(range_interval, hollaback) { var i, l, _i, _results; l = Math.round(this / range_interval); if (l === Infinity) { return this; } _results = []; for (i = _i = 0; 0 <= l ? _i <= l : _i >= l; i = 0 <= l ? ++_i : --_i) { _results.push(hollaback.call(this, moment(this.start.valueOf() + range_interval.valueOf() * i))); } return _results; }; /** * Determine if the current date range overlaps a given date range. * @param {DateRange} range Date range to check. * @return {!boolean} * */ DateRange.prototype.overlaps = function(range) { return this.start < range.end && this.end > range.start; }; /** * Iterate over the date range by a given date range, executing a function * for each sub-range. * @param {!DateRange|String} range Date range to be used for iteration or shorthand string (shorthands: http://momentjs.com/docs/#/manipulating/add/) * @param {!function(Moment)} hollaback Function to execute for each sub-range. * @return {!boolean} * */ DateRange.prototype.by = function(range, hollaback) { if (typeof range === 'string') { this._by_string(range, hollaback); } else { this._by_range(range, hollaback); } return this; }; /** * Date range in milliseconds. Allows basic coercion math of date ranges. * @return {!number} * */ DateRange.prototype.valueOf = function() { return this.end - this.start; }; return DateRange; })(); /** * Build a date range. * @param {(Moment|Date)} start Start of range. * @param {(Moment|Date)} end End of range. * @this {Moment} * @return {!DateRange} * */ moment.fn.range = function(start, end) { return new DateRange(start, end); }; /** * Check if the current moment is within a given date range. * @param {!DateRange} range Date range to check. * @this {Moment} * @return {!boolean} * */ moment.fn.within = function(range) { return range.contains(this._d); }; if ((typeof module !== "undefined" && module !== null ? module.exports : void 0) != null) { module.exports = moment; } }).call(this);
(function() { 'use strict'; var Counter = Jedo.createUI({ model: function() { return { count: 0 }; }, template: function() { return ( '<div class="counter-ui">' + '<span class="count"><%= count %></span>' + '</div>' ); } }); // render UI var _Counter = Counter.render( document.getElementById('c1') ); var count = 0; $('#action').on('click', function() { _Counter.update({ count: ++count }); }); }).call(this);
import React, { Component, PropTypes } from 'react'; import { Table } from 'antd'; import * as pageConfigs from 'pageConfigs'; import { connect } from 'react-redux'; import * as tableActions from 'reducers/table'; import { bindActionCreators } from 'redux'; import { Link } from 'react-router'; class AjaxTable extends Component { constructor(props, context) { super(props, context); const { pagination } = props; this.state = { pagination: pagination, config: () => { } }; console.log('default conc init'); } componentDidMount() { let { pagination, params, config, actions } = this.props; const pageConfig = config(this); this.setState({ config: pageConfig }); actions.load(pageConfig.api); console.log(`default componentDidMount:${pageConfig.api}`); } componentWillReceiveProps(nextProps) { const {params, actions} = this.props; const {created, edited, deleted, params: nextParams, config: nextConfig} = nextProps; if (params.id !== nextParams.id) { console.log(`default componentWillReceiveProps:before-${params.id};after-${nextParams.id}`,nextConfig); const config = nextConfig(this); this.setState({ config }); actions.load(config.api); } } handleTableChange = (pagination, filters, sorter) => { const pager = this.state.pagination; const { actions } = this.props; pager.current = pagination.current; this.setState({ pagination: pager, }); actions.pagination(this.state.config.api, pagination, filters, sorter); } onDelete = (obj) => { return () => { const {actions, params} = this.props; actions.remove(params.id, obj.id).then(() => { actions.load(this.state.config.api); }); // alert(obj.code); } } render() { const { loading, data} = this.props; const { config, pagination} = this.state; return ( <Table columns={config.columns} rowKey={record => record.code} dataSource={data} footer={() => { return <Link to={config.newFormUrl}>添加</Link> } } pagination={this.state.pagination} loading={loading} onChange={this.handleTableChange} /> ); } } AjaxTable.propTypes = { config: PropTypes.func.isRequired } export default connect((state, ownProps) => { console.log(`default connect : ${ownProps.params.id}`); return { ...state.table, config: pageConfigs[ownProps.params.id]() }; }, (dispatch) => { return { actions: bindActionCreators(tableActions, dispatch) }; })(AjaxTable);
'use strict'; var _ = require('lodash'); var Holodeck = require('../../../../holodeck'); var Request = require('../../../../../../lib/http/request'); var Response = require('../../../../../../lib/http/response'); var Twilio = require('../../../../../../lib'); var client; var holodeck; describe('ConnectApp', function() { beforeEach(function() { holodeck = new Holodeck(); client = new Twilio('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'AUTHTOKEN', holodeck); }); it('should generate valid fetch request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps('CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/ConnectApps/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid fetch response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'authorize_redirect_url': 'http://example.com/redirect', 'company_name': 'Twilio', 'deauthorize_callback_method': 'GET', 'deauthorize_callback_url': 'http://example.com/deauth', 'description': null, 'friendly_name': 'Connect app for deletion', 'homepage_url': 'http://example.com/home', 'permissions': [], 'sid': 'CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps('CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').fetch(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid update request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps('CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').update(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', sid: 'CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/ConnectApps/<%= sid %>.json')(solution); holodeck.assertHasRequest(new Request({ method: 'POST', url: url })); } ); it('should generate valid update response', function() { var body = JSON.stringify({ 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'authorize_redirect_url': 'http://example.com/redirect', 'company_name': 'Twilio', 'deauthorize_callback_method': 'GET', 'deauthorize_callback_url': 'http://example.com/deauth', 'description': null, 'friendly_name': 'Connect app for deletion', 'homepage_url': 'http://example.com/home', 'permissions': [], 'sid': 'CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps('CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa').update(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid list request', function() { holodeck.mock(new Response(500, '')); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps.list(); promise = promise.then(function() { throw new Error('failed'); }, function(error) { expect(error.constructor).toBe(Error.prototype.constructor); }); promise.done(); var solution = { accountSid: 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' }; var url = _.template('https://api.twilio.com/2010-04-01/Accounts/<%= accountSid %>/ConnectApps.json')(solution); holodeck.assertHasRequest(new Request({ method: 'GET', url: url })); } ); it('should generate valid read_full response', function() { var body = JSON.stringify({ 'connect_apps': [ { 'account_sid': 'ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'authorize_redirect_url': 'http://example.com/redirect', 'company_name': 'Twilio', 'deauthorize_callback_method': 'GET', 'deauthorize_callback_url': 'http://example.com/deauth', 'description': null, 'friendly_name': 'Connect app for deletion', 'homepage_url': 'http://example.com/home', 'permissions': [], 'sid': 'CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps/CNaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json' } ], 'end': 0, 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50', 'next_page_uri': null, 'num_pages': 1, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'start': 0, 'total': 1, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); it('should generate valid read_empty response', function() { var body = JSON.stringify({ 'connect_apps': [], 'end': 0, 'first_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50', 'last_page_uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json?Page=0&PageSize=50', 'next_page_uri': null, 'num_pages': 1, 'page': 0, 'page_size': 50, 'previous_page_uri': null, 'start': 0, 'total': 1, 'uri': '/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/ConnectApps.json' }); holodeck.mock(new Response(200, body)); var promise = client.api.v2010.accounts('ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') .connectApps.list(); promise = promise.then(function(response) { expect(response).toBeDefined(); }, function() { throw new Error('failed'); }); promise.done(); } ); });
var assert = require("assert"), doT = require("../doT"); describe('doT', function(){ var basictemplate = "<div>{{!it.foo}}</div>", basiccompiled = doT.template(basictemplate), definestemplate = "{{##def.tmp:<div>{{!it.foo}}</div>#}}{{#def.tmp}}", definescompiled = doT.template(definestemplate); describe('#template()', function(){ it('should return a function', function(){ assert.equal(typeof basiccompiled, "function"); }); }); describe('#()', function(){ it('should render the template', function(){ assert.equal(basiccompiled({foo:"http"}), "<div>http</div>"); assert.equal(basiccompiled({foo:"http://abc.com"}), "<div>http:&#47;&#47;abc.com</div>"); assert.equal(basiccompiled({}), "<div></div>"); }); }); describe('defines', function(){ it('should render define', function(){ assert.equal(definescompiled({foo:"http"}), "<div>http</div>"); assert.equal(definescompiled({foo:"http://abc.com"}), "<div>http:&#47;&#47;abc.com</div>"); assert.equal(definescompiled({}), "<div></div>"); }); }); describe('encoding with doNotSkipEncoded=false', function() { it('should not replace &', function() { global._encodeHTML = undefined; doT.templateSettings.doNotSkipEncoded = false; assert.equal(doT.template(definestemplate)({foo:"&amp;"}), "<div>&amp;</div>"); }); }); describe('evaluate 2 numbers', function() { it('should print numbers next to each other', function() { var fn = doT.template("{{=it.one}}{{=it.two}}"); assert.equal(fn({one:1, two: 2}), "12"); }); }); describe('evaluate 2 numbers in the middle', function() { it('should print numbers next to each other', function() { var fn = doT.template("{{?it.one}}{{=it.one}}{{?}}{{=it.one}}{{=it.two}}"); assert.equal(fn({one:1, two: 2}), "112"); }); }); describe('encoding with doNotSkipEncoded=true', function() { it('should replace &', function() { global._encodeHTML = undefined; doT.templateSettings.doNotSkipEncoded = true; assert.equal(doT.template(definestemplate)({foo:"&amp;"}), "<div>&#38;amp;</div>"); assert.equal(doT.template('{{!it.a}}')({a:"& < > / ' \""}), "&#38; &#60; &#62; &#47; &#39; &#34;"); assert.equal(doT.template('{{!"& < > / \' \\""}}')(), "&#38; &#60; &#62; &#47; &#39; &#34;"); }); }); });
chrome.tabs.onCreated.addListener(function(){ chrome.storage.sync.get('limit', function(settings){ var tabLimit = settings.limit; chrome.tabs.query({'currentWindow': true, 'active': true}, function(tabs){ var activeTabURL = tabs[0].url chrome.tabs.query({'currentWindow': true}, function(tabs){ if(tabs.length >= tabLimit && activeTabURL.indexOf("alert.html") == -1 ){ chrome.tabs.create({'url':'alert.html'}); } }); }); }); });
$ = jQuery = require('jquery'); // unfortunately bootstrap requires jquery to be acesable globally :( var React = require('react'); var Home = require('./components/homePage'); var About = require('./components/about/aboutPage'); var Header = require('./components/common/header'); var Authors = require('./components/authors/authorPage'); // a way to have use strict in a block of a code IIFE // the reason why it can not be global is because of global jQuery assignment (function (win) { "use strict"; var App = React.createClass({ // You can not use arrow function here, because this version of react has problems with handling es6 render: function() { var Child; switch (this.props.route) { case 'about': Child = About; break; case 'authors': Child = Authors; break; default: Child = Home; } return ( <div> <Header/> <Child/> </div> ); } }); function render() { var route = win.location.hash.substr(1); React.render(<App route={route}/>, document.getElementById('app')); } // Event that is raised when a hash is changed in URL win.addEventListener('hashchange', render); render(); }(window));
import Sprite from './Sprite' /** * Crate class. */ export default class Crate extends Sprite { }
version https://git-lfs.github.com/spec/v1 oid sha256:1829dcc9a5e12eb1392952062be20d728ee3704aed4e950ba9b56854746173d6 size 7182
cm.define('Com.TagsInput', { 'modules' : [ 'Params', 'Events', 'Langs', 'Structure', 'DataConfig', 'Stack' ], 'require' : [ 'Com.Autocomplete' ], 'events' : [ 'onRender', 'onAdd', 'onRemove', 'onChange', 'onOpen', 'onClose', 'onReset' ], 'params' : { 'input' : null, // Deprecated, use 'node' parameter instead. 'node' : cm.node('input', {'type' : 'text'}), 'container' : null, 'name' : '', 'embedStructure' : 'replace', 'data' : [], 'maxSingleTagLength': 255, 'max' : 0, // Not implemented 'autocomplete' : false, 'icons' : { 'add' : 'icon default linked', 'remove' : 'icon default linked' }, 'Com.Autocomplete' : { 'clearOnEmpty' : false } }, 'strings' : { 'tags' : 'Tags', 'add' : 'Add', 'remove' : 'Remove', 'placeholder' : 'Add tags...' } }, function(params){ var that = this, nodes = {}, tags = [], items = {}; that.isDestructed = null; that.value = null; that.components = {}; that.isAutocomplete = false; var init = function(){ var sourceTags, splitTags; preValidateParams(); // Init modules that.setParams(params); that.convertEvents(that.params['events']); that.getDataConfig(that.params['node']); // Render validateParams(); render(); that.addToStack(nodes['container']); that.triggerEvent('onRender'); // Set tags splitTags = that.params['node'].value.split(','); sourceTags = cm.extend(that.params['data'], splitTags); cm.forEach(sourceTags, function(tag){ addTag(tag); }); }; var preValidateParams = function(){ if(cm.isNode(that.params['input'])){ that.params['node'] = that.params['input']; } }; var validateParams = function(){ if(cm.isNode(that.params['node'])){ that.params['name'] = that.params['node'].getAttribute('name') || that.params['name']; } that.isAutocomplete = that.params['autocomplete']; }; var render = function(){ // Structure nodes['container'] = cm.node('div', {'class' : 'com__tags-input'}, nodes['hidden'] = cm.node('input', {'type' : 'hidden'}), nodes['inner'] = cm.node('div', {'class' : 'inner input'}, nodes['tags'] = cm.node('div', {'class' : 'tags'}) ) ); renderInput(); // Attributes if(that.params['name']){ nodes['hidden'].setAttribute('name', that.params['name']); } // Events cm.addEvent(nodes['container'], 'click', function(e){ var target = cm.getEventTarget(e); if(!cm.isParent(nodes['tags'], target, true)){ nodes['input'].focus(); } }); // Append that.embedStructure(nodes['container']); }; var renderInput = function(){ // Structure nodes['input'] = cm.node('input', {'type' : 'text', 'maxlength' : that.params['maxSingleTagLength'], 'class' : 'adder', 'placeholder' : that.lang('placeholder')}); cm.appendChild(nodes['input'], nodes['inner']); // Autocomplete if(that.isAutocomplete){ cm.getConstructor('Com.Autocomplete', function(classConstructor){ that.components['autocomplete'] = new classConstructor(cm.merge(that.params['Com.Autocomplete'], { 'events' : { 'onClickSelect' : function(){ addAdderTags(true); } } })); }); that.components['autocomplete'].setTarget(nodes['input']); that.components['autocomplete'].setInput(nodes['input']); } // Add new tag on comma cm.addEvent(nodes['input'], 'keypress', function(e){ if(e.charCode === 44 || e.charCode === 59){ cm.preventDefault(e); addAdderTags(true); that.isAutocomplete && that.components['autocomplete'].hide(); } }); // Add new tag on enter or escape cm.addEvent(nodes['input'], 'keydown', function(e){ if(cm.isKey(e, ['enter', 'escape'])){ cm.preventDefault(e); addAdderTags(true); that.isAutocomplete && that.components['autocomplete'].hide(); } }); cm.addEvent(nodes['input'], 'focus', function(){ cm.addClass(nodes['container'], 'active'); cm.addClass(nodes['inner'], 'input-focus'); }); cm.addEvent(nodes['input'], 'blur', function(){ addAdderTags(true); cm.removeClass(nodes['container'], 'active'); cm.removeClass(nodes['inner'], 'input-focus'); }); }; var addAdderTags = function(execute){ var sourceTags = nodes['input'].value.split(','); cm.forEach(sourceTags, function(tag){ addTag(tag, execute); }); nodes['input'].value = ''; that.isAutocomplete && that.components['autocomplete'].clear(); }; var addTag = function(tag, execute){ tag = tag.trim(); if(tag && tag.length && !/^[\s]*$/.test(tag) && !cm.inArray(tags, tag)){ tags.push(tag); renderTag(tag); setHiddenInputData(); // Execute events if(execute){ // API onChange Event that.triggerEvent('onChange', {'tag' : tag}); // API onAdd Event that.triggerEvent('onAdd', {'tag' : tag}); } } }; var renderTag = function(tag){ var item = { 'tag' : tag }; // Structure item['container'] = cm.node('div', {'class' : 'item'}, cm.node('div', {'class' : 'inner'}, cm.node('div', {'class' : 'text', 'title' : tag}, tag), item['button'] = cm.node('div', {'class' : that.params['icons']['remove'], 'title' : that.lang('remove')}) ) ); item['anim'] = new cm.Animation(item['container']); // Append cm.appendChild(item['container'], nodes['tags']); // Add click event on "Remove Tag" button cm.addEvent(item['button'], 'click', function(){ removeTag(item); }); // Push to global array items[tag] = item; }; var removeTag = function(item){ // Remove tag from data tags = cm.arrayRemove(tags, item['tag']); delete items[item['tag']]; setHiddenInputData(); // API onChange Event that.triggerEvent('onChange', { 'tag' : item['tag'] }); // API onRemove Event that.triggerEvent('onRemove', { 'tag' : item['tag'] }); // Hide cm.remove(item['container']); item = null; }; var setHiddenInputData = function(){ that.value = tags.join(','); nodes['hidden'].value = that.value; }; /* ******* MAIN ******* */ that.destruct = function(){ var that = this; if(!that.isDestructed){ that.isDestructed = true; that.removeFromStack(); } return that; }; that.get = function(){ return !cm.isEmpty(that.value) ? that.value : ''; }; that.set = function(value){ that.add(value); return that; }; that.add = function(tag /* or tags comma separated or array */){ var sourceTags; if(!tag){ sourceTags = []; }else if(cm.isArray(tag)){ sourceTags = tag; }else{ sourceTags = tag.split(','); } cm.forEach(sourceTags, function(tag){ addTag(tag, true); }); return that; }; that.remove = function(tag){ var sourceTags; if(!tag){ sourceTags = []; }else if(cm.isArray(tag)){ sourceTags = tag; }else{ sourceTags = tag.split(','); } cm.forEach(sourceTags, function(tag){ if(cm.inArray(tags, tag)){ removeTag(items[tag]); } }); return that; }; that.reset = function(){ cm.forEach(items, function(item){ removeTag(item, true); }); that.triggerEvent('onReset'); return that; }; that.getAutocomplete = function(){ return that.components['autocomplete']; }; init(); }); /* ****** FORM FIELD COMPONENT ******* */ Com.FormFields.add('tags', { 'node' : cm.node('input', {'type' : 'text'}), 'fieldConstructor' : 'Com.AbstractFormField', 'constructor' : 'Com.TagsInput' });
Template.StartingList.rendered = function(evt, template) { var currentPlayerId, currentGameId; $('ol.starting').droppable({ activeClass: 'active', hoverClass: 'hover', drop: function(event, ui) { currentPlayerId = Session.get('sPlayerId'); currentGameId = Session.get('sGameId'); Games.update(currentGameId, { $addToSet: { starting: currentPlayerId } }, function(error) { if (error) { alert(error.reason); } }); } }); }; // find all players that have a status of 'sub' Template.StartingList.helpers({ cStarting: function(evt, template) { var currentGame, myStarters, arrWithPlayerNames, i, player; // get the doc for this game currentGame = Games.findOne({ _id: Session.get('sGameId') }); // check if current game exists if (currentGame) { // grab all the subs myStarters = currentGame.starting; // create an empty array arrWithPlayerNames = []; // if there are subs if (myStarters) { // run this for loop through all the subs for (i = 0; i < myStarters.length; i++) { // grab the playerid for each sub player = Players.findOne({ _id: myStarters[i] }); // store the full name inside a variable // var playerFullName = player.fullName; // push each fullName inside the empty array arrWithPlayerNames.push(player); } return arrWithPlayerNames; } } else { return false; } } }); Template.StartingList.events({ 'mousedown li ': function(evt, template) { Session.set('sPlayerId', this._id); } }); Template.StarterList.helpers({ // if there is a team return false // so we can hide the add team form cGame: function() { if (Meteor.user()) { return Games.findOne({ _id: Session.get('sGameId') }); } }, sGameId: function() { return Session.get('sGameId'); } });
/* */ 'use strict' var qs = require('qs') , querystring = require('querystring') function Querystring (request) { this.request = request this.lib = null this.useQuerystring = null this.parseOptions = null this.stringifyOptions = null } Querystring.prototype.init = function (options) { if (this.lib) {return} this.useQuerystring = options.useQuerystring this.lib = (this.useQuerystring ? querystring : qs) this.parseOptions = options.qsParseOptions || {} this.stringifyOptions = options.qsStringifyOptions || {} } Querystring.prototype.stringify = function (obj) { return (this.useQuerystring) ? this.rfc3986(this.lib.stringify(obj, this.stringifyOptions.sep || null, this.stringifyOptions.eq || null, this.stringifyOptions)) : this.lib.stringify(obj, this.stringifyOptions) } Querystring.prototype.parse = function (str) { return (this.useQuerystring) ? this.lib.parse(str, this.parseOptions.sep || null, this.parseOptions.eq || null, this.parseOptions) : this.lib.parse(str, this.parseOptions) } Querystring.prototype.rfc3986 = function (str) { return str.replace(/[!'()*]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } Querystring.prototype.unescape = querystring.unescape exports.Querystring = Querystring
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Word Schema */ var WordSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Word name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Word', WordSchema);
(function (){ const ObjecExtends = (source, add) => { Object.keys(add).forEach(addProperty => { source[addProperty] = add[addProperty]; }); }; const selector = (sel, ele) => { ele = ele || document; if (typeof(sel) !== 'string') { return [sel]; } else { return Array.prototype.slice.call(ele.querySelectorAll(sel)); } }; const DOMMethod = { html(value){ if (typeof(value) !== 'undefined') { this.forEach(ele => { ele.innerHTML = value; }) } else { return this.map(ele => { return ele.innerHTML; }); } }, text(value){ if (typeof(value) !== 'undefined') { this.forEach(ele => { ele.innerText = value; }); } else { let textArr = this.map(ele => ele.innerText); if (textArr.length === 1) { textArr = textArr[0]; } return textArr; } }, append(ele){ this[this.length - 1].appendChild(ele); }, getAttributesValue(attrEle, name){ let attr = attrEle.attributes.getNamedItem(name); if (attr === null) { return null; } else { return attr.value; } }, getAttr(name){ let elementAttributesArr = this.map(ele => vools(`[${name}]`, ele).map(attr => this.getAttributesValue(attr, name)).map(valueArr => { if (valueArr.length === 1) { valueArr = valueArr[0]; } return valueArr; }) ); if (elementAttributesArr.length === 1) { return elementAttributesArr[0]; } else { return elementAttributesArr; } }, setAttr(name, value){ }, attr(name, value){ if (arguments.length === 0) { return this.map(attrEle => { return this.getAttributesValue(attrEle) }); } else if (arguments.length === 1) { return this.getAttr(name); } else if (arguments.length > 1) { return this.setAttr(name, value); } }, }; const DOMs = function (sel, ele) { ObjecExtends(this, DOMMethod); }; DOMs.prototype = Array.prototype; const vools = function (sel, ele) { const doms = new DOMs; const domArr = selector(sel, ele); domArr.forEach(element => doms.push(element)); return doms; }; vools.rjax = (() => { const stringifyRequest = (() => { const backValueKey = (key, value) => `${key}=` + encodeURIComponent(value); const stringifyArray = (key, arr) => arr.length ? arr.map(item => backValueKey(key, item)).join('&') : backValueKey(key, ''); const fetcher = (data, key) => Array.isArray(data[key]) ? stringifyArray(key, data[key]) : backValueKey(key, data[key]); return data => Object.keys(data).map(key => fetcher(data, key)).join('&'); })(); return (url, args) => { var xhr = new XMLHttpRequest; xhr.onloadend = () => { args.success && args.success(xhr.responseText, xhr.status, xhr); }; if (args.method === undefined) { throw new Error('请求方法未指定'); } xhr.open(args.method.toUpperCase(), url, true); if (args.data !== undefined) { xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); if (typeof args.data === 'object') { let formated = stringifyRequest(args.data); xhr.send(formated); } else { xhr.send(args.data); } } else { xhr.send(); } }; })(); const voolsEvent = function (){}; ObjecExtends(voolsEvent.prototype, { }); window.voolsEvent = voolsEvent; window.vools = vools; window.$ = vools; window.$$ = function (){ return vools.apply(null, arguments)[0]; }; })();
'use strict'; (function(angular) { var oauth2 = angular.module('OAuth2', ['ngCookies']); // @include ../interceptor.js // @include ../auth.js })(angular);
'use strict'; var Logger = require('../lib/logger.js'); var path = require('path'); // setup config var logger = new Logger(path.join(__dirname, 'config.json')); logger.on('log', function (level, message) { console.log('logged: ' + message + ' with level of: ' + level); }); module.exports = logger;
/** * Main file * Pokemon Showdown - http://pokemonshowdown.com/ * * This is the main Pokemon Showdown app, and the file you should be * running to start Pokemon Showdown if you're using it normally. * * This file sets up our SockJS server, which handles communication * between users and your server, and also sets up globals. You can * see details in their corresponding files, but here's an overview: * * Users - from users.js * * Most of the communication with users happens in users.js, we just * forward messages between the sockets.js and users.js. * * Rooms - from rooms.js * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * Dex - from sim/dex.js * * Handles getting data about Pokemon, items, etc. * * Ladders - from ladders.js and ladders-remote.js * * Handles Elo rating tracking for players. * * Chat - from chat.js * * Handles chat and parses chat commands like /me and /ban * * Sockets - from sockets.js * * Used to abstract out network connections. sockets.js handles * the actual server and connection set-up. * * @license MIT license */ 'use strict'; const fs = require('fs'); const path = require('path'); // Check for dependencies try { require.resolve('sockjs'); } catch (e) { throw new Error("Dependencies unmet; run npm install"); } /********************************************************* * Load configuration *********************************************************/ try { require.resolve('./config/config'); } catch (err) { if (err.code !== 'MODULE_NOT_FOUND') throw err; // should never happen // Copy it over synchronously from config-example.js since it's needed before we can start the server console.log("config.js doesn't exist - creating one with default settings..."); fs.writeFileSync(path.resolve(__dirname, 'config/config.js'), fs.readFileSync(path.resolve(__dirname, 'config/config-example.js')) ); } finally { global.Config = require('./config/config'); } if (Config.watchconfig) { let configPath = require.resolve('./config/config'); fs.watchFile(configPath, (curr, prev) => { if (curr.mtime <= prev.mtime) return; try { delete require.cache[configPath]; global.Config = require('./config/config'); if (global.Users) Users.cacheGroupData(); console.log('Reloaded config/config.js'); } catch (e) { console.log('Error reloading config/config.js: ' + e.stack); } }); } /********************************************************* * Set up most of our globals *********************************************************/ global.SG = {}; global.Db = require('nef')(require('nef-fs')('config/db')); global.Monitor = require('./monitor'); global.Dex = require('./sim/dex'); global.toId = Dex.getId; global.LoginServer = require('./loginserver'); global.Ladders = require(Config.remoteladder ? './ladders-remote' : './ladders'); global.Users = require('./users'); global.Punishments = require('./punishments'); global.Chat = require('./chat'); global.Rooms = require('./rooms'); global.Tells = require('./tells.js'); delete process.send; // in case we're a child process global.Verifier = require('./verifier'); Verifier.PM.spawn(); global.Tournaments = require('./tournaments'); global.Dnsbl = require('./dnsbl'); Dnsbl.loadDatacenters(); if (Config.crashguard) { // graceful crash - allow current battles to finish before restarting process.on('uncaughtException', err => { let crashType = require('./crashlogger')(err, 'The main process'); if (crashType === 'lockdown') { Rooms.global.startLockdown(err); } else { Rooms.global.reportCrash(err); } }); process.on('unhandledRejection', err => { throw err; }); process.on('exit', code => { let exitCodes = { 1: 'Uncaught Fatal Exception', 2: 'Misuse of shell builtins', 3: 'Internal JavaScript Parse Error', 4: 'Internal JavaScript Evaluation Failure', 5: 'Fatal Error', 6: 'Non-function Internal Exception Handler', 7: 'Internal Exception Handler Run-Time Failure', 8: 'Unused Error Code. Formerly used by nodejs. Sometimes indicate a uncaught exception', 9: 'Invalid Argument', 10: 'Internal JavaScript Run-Time Failure', 11: 'A sysadmin forced an emergency exit', 12: 'Invalid Debug Argument', 130: 'Control-C via Terminal or Command Prompt', }; if (code !== 0) { let exitInfo = 'Unused Error Code'; if (exitCodes[code]) { exitInfo = exitCodes[code]; } else if (code > 128) { exitInfo = 'Signal Exit'; } console.log(''); console.error('WARNING: Process exiting with code ' + code); console.error('Exit code details: ' + exitInfo + '.'); console.error('Refer to https://github.com/nodejs/node-v0.x-archive/blob/master/doc/api/process.markdown#exit-codes for more details. The process will now exit.'); } }); } /********************************************************* * Start networking processes to be connected to *********************************************************/ global.Sockets = require('./sockets'); exports.listen = function (port, bindAddress, workerCount) { Sockets.listen(port, bindAddress, workerCount); }; if (require.main === module) { // if running with node app.js, set up the server directly // (otherwise, wait for app.listen()) let port; if (process.argv[2]) { port = parseInt(process.argv[2]); // eslint-disable-line radix } Sockets.listen(port); } /********************************************************* * Set up our last global *********************************************************/ global.TeamValidator = require('./team-validator'); TeamValidator.PM.spawn(); /********************************************************* * Start up the githubhook server ********************************************************/ require('./github'); /********************************************************* * Start up the REPL server *********************************************************/ require('./repl').start('app', cmd => eval(cmd));
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema, crypto = require('crypto'), validator = require('validator'); /** * A Validation function for local strategy properties */ var validateLocalStrategyProperty = function (property) { return ((this.provider !== 'local' && !this.updated) || property.length); }; /** * A Validation function for local strategy password */ var validateLocalStrategyPassword = function (password) { return (this.provider !== 'local' || validator.isLength(password, 6)); }; /** * A Validation function for local strategy email */ var validateLocalStrategyEmail = function (email) { return ((this.provider !== 'local' && !this.updated) || validator.isEmail(email)); }; /** * User Schema */ var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, lastName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your last name'] }, displayName: { type: String, trim: true }, email: { type: String, trim: true, unique: true, default: '', validate: [validateLocalStrategyEmail, 'Please fill a valid email address'] }, username: { type: String, unique: 'Username already exists', required: 'Please fill in a username', trim: true }, password: { type: String, default: '', validate: [validateLocalStrategyPassword, 'Password should be longer'] }, salt: { type: String }, profileImageURL: { type: String, default: 'modules/users/img/profile/default.png' }, provider: { type: String, required: 'Provider is required' }, providerData: {}, additionalProvidersData: {}, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, updated: { type: Date }, created: { type: Date, default: Date.now }, /* For reset password */ resetPasswordToken: { type: String }, resetPasswordExpires: { type: Date } }); /** * Hook a pre save method to hash the password */ UserSchema.pre('save', function (next) { if (this.password && this.isModified('password') && this.password.length > 6) { this.salt = crypto.randomBytes(16).toString('base64'); this.password = this.hashPassword(this.password); } next(); }); /** * Create instance method for hashing a password */ UserSchema.methods.hashPassword = function (password) { if (this.salt && password) { return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64).toString('base64'); } else { return password; } }; /** * Create instance method for authenticating user */ UserSchema.methods.authenticate = function (password) { return this.password === this.hashPassword(password); }; /** * Find possible not used username */ UserSchema.statics.findUniqueUsername = function (username, suffix, callback) { var _this = this; var possibleUsername = username + (suffix || ''); _this.findOne({ username: possibleUsername }, function (err, user) { if (!err) { if (!user) { callback(possibleUsername); } else { return _this.findUniqueUsername(username, (suffix || 0) + 1, callback); } } else { callback(null); } }); }; mongoose.model('User', UserSchema);
/** * @param object Global Cockpit namespace * @param object jQuery */ ;( function( cockpit, $ ) { $( document ).ready( function(){ $(".cockpit_metaboxes").parent().addClass('cockpit_tab_metaboxes') // tabbed content $(".cockpit_tabcontent").hide(); $(".cockpit_tabcontent:first").show(); $("ul.cockpit_tabs li:first").addClass("active") /* if in tab mode */ $("ul.cockpit_tabs li").click(function() { $(".cockpit_tabcontent").hide(); var activeTab = $(this).attr("data-rel"); $("#"+activeTab).fadeIn(); $("ul.cockpit_tabs li").removeClass("active"); $(this).addClass("active"); $(".cockpit_tab_drawer_heading").removeClass("d_active"); $(".cockpit_tab_drawer_heading[data-rel^='"+activeTab+"']").addClass("d_active"); }); /* if in drawer mode */ $(".cockpit_tab_drawer_heading").click(function() { $(".cockpit_tabcontent").hide(); var d_activeTab = $(this).attr("data-rel"); $("#"+d_activeTab).fadeIn(); $(".cockpit_tab_drawer_heading").removeClass("d_active"); $(this).addClass("d_active"); $("ul.cockpit_tabs li").removeClass("active"); $("ul.cockpit_tabs li[data-rel^='"+d_activeTab+"']").addClass("active"); }); /* Extra class "tab_last" to add border to right side of last tab */ $('ul.cockpit-tabs li').last().addClass("tab_last"); }); } )( window.cockpit = window.cockpit || {}, jQuery );
import Utils from '../utils' function updateBinding (el, { value, modifiers }, ctx) { if (!value) { ctx.update() return } if (typeof value === 'number') { ctx.offset = value ctx.update() return } if (value && Object(value) !== value) { console.error('v-back-to-top requires an object {offset, duration} as parameter', el) return } if (value.offset) { if (typeof value.offset !== 'number') { console.error('v-back-to-top requires a number as offset', el) return } ctx.offset = value.offset } if (value.duration) { if (typeof value.duration !== 'number') { console.error('v-back-to-top requires a number as duration', el) return } ctx.duration = value.duration } ctx.update() } export default { bind (el) { let ctx = { offset: 200, duration: 300, update: Utils.debounce(() => { const trigger = Utils.dom.getScrollPosition(ctx.scrollTarget) > ctx.offset if (ctx.visible !== trigger) { ctx.visible = trigger el.classList[trigger ? 'remove' : 'add']('hidden') } }, 25), goToTop () { Utils.dom.setScrollPosition(ctx.scrollTarget, 0, ctx.animate ? ctx.duration : 0) } } el.classList.add('hidden') Utils.store.add('backtotop', el, ctx) }, inserted (el, binding) { let ctx = Utils.store.get('backtotop', el) ctx.scrollTarget = Utils.dom.getScrollTarget(el) ctx.animate = binding.modifiers.animate updateBinding(el, binding, ctx) ctx.scrollTarget.addEventListener('scroll', ctx.update) window.addEventListener('resize', ctx.update) el.addEventListener('click', ctx.goToTop) }, update (el, binding) { if (binding.oldValue !== binding.value) { updateBinding(el, binding, Utils.store.get('backtotop', el)) } }, unbind (el) { let ctx = Utils.store.get('backtotop', el) ctx.scrollTarget.removeEventListener('scroll', ctx.update) window.removeEventListener('resize', ctx.update) el.removeEventListener('click', ctx.goToTop) Utils.store.remove('backtotop', el) } }
/* * GET home page. */ var conf = require('../config'), logger = require('tracer')[conf.log.strategy](conf.log.setting); exports.index = function(req, res, next) { logger.debug('index'); res.render('index', { title : 'Express' }) };
import Direction from 'Pool/Direction.js'; export default class Ball { constructor(color, position) { this.color = color; this.position = position; this.acceleration = 0.01; this.direction = new Direction(Math.random() * 360); } getColor() { return this.color; } getPosition() { return this.position; } move() { this.position = this.position.shift(this.direction, this.acceleration); this.acceleration -= Ball.ACCELERATION_DECAY; this.acceleration = (this.acceleration < 0) ? 0 : this.acceleration; } /** * * @param {Ball} ball */ ballCollisionCheck(ball) { if (ball === this) { return; } if (ball.getPosition().isWithin(Ball.DIAMETER, this.getPosition())) { var totalAcceleration = this.acceleration + ball.acceleration; ball.acceleration = totalAcceleration / 2; ball.direction = ball.direction.invert(); this.acceleration = totalAcceleration / 2; this.direction = this.direction.invert(); } } /** * * @param {Table} table */ cushionCollisionCheck(table) { var boundaryLeft = Ball.DIAMETER; var boundaryTop = Ball.DIAMETER; var boundaryRight = Ball.DIAMETER + table.getLength(); var boundaryBottom = Ball.DIAMETER + table.getWidth(); if (this.getPosition().getX() < boundaryLeft) { // Collided with left wall. this.direction = this.direction.reflect(new Direction(90)); } else if (this.getPosition().getY() < boundaryTop) { // Collided with top cushion. this.direction = this.direction.reflect(new Direction(180)); } else if (this.getPosition().getX() > boundaryRight) { // Collided with right cushion. this.direction = this.direction.reflect(new Direction(90)); } else if (this.getPosition().getY() > boundaryBottom) { // Collided with bottom cushion. this.direction = this.direction.reflect(new Direction(180)); } } } Ball.ACCELERATION_DECAY = 0.000; Ball.DIAMETER = 0.10; Ball.COLOR_RED = 'red'; Ball.COLOR_YELLOW = 'yellow'; Ball.COLOR_BLACK = 'black'; Ball.COLOR_WHITE = 'white';
/* SITOA - Make Partition from Material - Gergely Wootsch 07/09/2015. Adds Arnold Visibility and Matte properties to a partition created based on selected material(s). The partition is overridden by the material by d efault or if specified below, creates a localised override ('makelocal = true'). */ var makelocal = true; var makelocal_prefix = "shadowLight"; var Arnold_Visibility = { "camera": true, "shadows": true, "reflected": false, "refracted": false, "diffuse": false, "glossy": false } var Arnold_Matte = { "camera": false, "camera_colorR": 0, "camera_colorG": 0, "camera_colorB": 0, "camera_colorA": 0, "use_alpha": true, "use_opacity": false, "opacity": 1 } function apply(name, makelocal, makelocal_prefix){ //Check if Pass exists already in the partition var check = Dictionary.GetObject(Application.ActiveProject.ActiveScene.ActivePass.fullname + "." + name,false); if (check) { logMessage(name + ": Partition already exists. Skipping.",2); return false } else { SelectObjectsUsingMaterial("Sources.Materials.DefaultLib." + name); CreatePartition(Application.ActiveProject.ActiveScene.ActivePass, name, null, null); CopyPaste("Sources.Materials.DefaultLib." + name, null, Application.ActiveProject.ActiveScene.ActivePass + "." + name, 1); //Add SITOA_Visibility Property and Matte to Partition and Set Defaults var vis_props = SITOA_AddVisibilityProperties( Application.ActiveProject.ActiveScene.ActivePass.fullname + "." + name, true); for (var i=0; i<vis_props.count; i++) { var vis_prop = vis_props.Item(i); vis_prop.Parameters("camera").Value = Arnold_Visibility.camera; vis_prop.Parameters("shadows").Value = Arnold_Visibility.shadows; vis_prop.Parameters("reflected").Value = Arnold_Visibility.reflected; vis_prop.Parameters("refracted").Value = Arnold_Visibility.refracted; vis_prop.Parameters("diffuse").Value = Arnold_Visibility.diffuse; vis_prop.Parameters("glossy").Value = Arnold_Visibility.glossy; } var matte_props = SITOA_AddMatteProperties( Application.ActiveProject.ActiveScene.ActivePass.fullname + "." + name, true); for (var i=0; i<matte_props.count; i++) { var matte_prop = matte_props.Item(i); matte_prop.Parameters("camera").Value = Arnold_Matte.camera; matte_prop.Parameters("camera_colorR").Value = Arnold_Matte.camera_colorR; matte_prop.Parameters("camera_colorG").Value = Arnold_Matte.camera_colorG; matte_prop.Parameters("camera_colorB").Value = Arnold_Matte.camera_colorB; matte_prop.Parameters("camera_colorA").Value = Arnold_Matte.camera_colorA; matte_prop.Parameters("use_alpha").Value = Arnold_Matte.use_alpha; matte_prop.Parameters("use_opacity").Value = Arnold_Matte.use_opacity; matte_prop.Parameters("opacity").Value = Arnold_Matte.opacity; } //Add local copy of partition material if (makelocal) { var a = MakeLocal(Application.ActiveProject.ActiveScene.ActivePass + "." + name + ".LocalProperties." + name, siDefaultPropagation); var b = String(a); var c = b.slice(b.lastIndexOf('.')+1); SetValue("Sources.Materials.DefaultLib." + c + ".Name", makelocal_prefix + "_" + name, null); var d = "Sources.Materials.DefaultLib." + makelocal_prefix + "_" + name; //ADD CUSTOM ACTION HERE TO MODIFY THE LOCALISED MATERIAL //ShadowLight var opacity = get_opacitySource(d); CreateShaderFromProgID("ArnoldCoreShaders.standard.1.0", d, "standard"); SIConnectShaderToCnxPoint(d + ".standard.out", d + ".surface", false); SIConnectShaderToCnxPoint(opacity, d + ".standard.opacity", false); //Depth /* RemoveAllShadersFromCnxPoint(d + ".utility.color", siShaderCnxPointBasePorts); SetValue(d + ".utility.color.blue", 0, null); SetValue(d + ".utility.color.green", 0, null); SetValue(d + ".utility.color.red", 0, null); SetValue(d + ".utility.shade_mode", "flat", null); */ } return true } } function get_opacitySource(materialName){ var opacityShaderOut; var src = Dictionary.GetObject(materialName).surface.Source.fullname; var opacitySrc = Dictionary.GetObject(src.slice(0,src.lastIndexOf('.'))); if (opacitySrc.opacity.source != undefined) { var o = opacitySrc.opacity.source.fullname; var opacityShader = Dictionary.GetObject(o.slice(0,o.lastIndexOf('.'))); // 3 = Scalar, 4 = Color if (opacityShader.OutputType == 3) { opacityShaderOut = Dictionary.GetObject(opacityShader.input.source.fullname.slice(0,opacityShader.input.source.fullname.lastIndexOf('.'))).out.fullname; } if (opacityShader.OutputType == 4) { opacityShaderOut = opacityShader.out.fullname; } } else { opacityShaderOut = undefined; } return opacityShaderOut; } var names = []; function push() { var names = []; var sel = application.selection; for ( i=0; i < sel.count; i++){ names.push(sel(i).name)} return names } var names = push(); for (i=0; i < names.length; i++) { //Add operation here //Full name of the object = sel(i).fullname apply(names[i], makelocal, makelocal_prefix); }
(window.webpackJsonp=window.webpackJsonp||[]).push([[60],{MLPm:function(n,w,o){}},[["MLPm",2]]]); //# sourceMappingURL=light.591ee81e63053ad31983.js.map
/* */ (function(process) { "use strict"; var schedule; var noAsyncScheduler = function() { throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a"); }; if (require("./util").isNode) { var version = process.versions.node.split(".").map(Number); schedule = (version[0] === 0 && version[1] > 10) || (version[0] > 0) ? global.setImmediate : process.nextTick; if (!schedule) { if (typeof setImmediate !== "undefined") { schedule = setImmediate; } else if (typeof setTimeout !== "undefined") { schedule = setTimeout; } else { schedule = noAsyncScheduler; } } } else if (typeof MutationObserver !== "undefined") { schedule = function(fn) { var div = document.createElement("div"); var observer = new MutationObserver(fn); observer.observe(div, {attributes: true}); return function() { div.classList.toggle("foo"); }; }; schedule.isStatic = true; } else if (typeof setImmediate !== "undefined") { schedule = function(fn) { setImmediate(fn); }; } else if (typeof setTimeout !== "undefined") { schedule = function(fn) { setTimeout(fn, 0); }; } else { schedule = noAsyncScheduler; } module.exports = schedule; })(require("process"));
//http://stackoverflow.com/a/14760377 String.prototype.paddingLeft = function (paddingValue) { return String(paddingValue + this).slice(-paddingValue.length); }; //Horde of Torque methods and other helpers that are super useful getWord = function(text, word) { return text.split(" ")[word]; }; getWordCount = function(text) { return text.split(" ").length; }; getWords = function(text, start, end) { if (typeof(end) === "undefined") end = getWordCount(text); return text.split(" ").slice(start, end + 1).join(" "); }; firstWord = function(text) { return getWord(text, 0); }; restWords = function(text) { return getWords(text, 1, getWordCount(text)); }; decodeName = function(text) { return text.replace(/-SPC-/g, " ").replace(/-TAB-/g, "\t").replace(/-NL-/g, "\n"); }; encodeName = function(text) { return text.replace(/ /g, "-SPC-").replace(/\t/g, "-TAB-").replace(/\n/g, "-NL-"); }; htmlDecode = function(text) { //The server replaces spaces with + symbols because of issues with spaces. // We also need to encode all bare % symbols (with no numbers following) because // decodeURIComponent() thinks that they are HTML entities. //Also replace all &lt; &gt; and &amp; with their originals because we replace them below. //Nasty regex that gets all % symbols without any following 0-9a-f and replaces them with %25 var toDecode = text .replace(/\+/g, " ") .replace(/%(?=[^0-9a-fA-F]+)/g, "%25") .replace(/&gt;/g, ">") .replace(/&lt;/g, "<") .replace(/&amp;/g, "&"); var decoded = decodeURIComponent(toDecode); //HTML characters that need to be escaped (&, <, >) decoded = decoded .replace(/&/g, "&amp;") .replace(/>/g, "&gt;") .replace(/</g, "&lt;"); return decoded; }; formatTime = function(time) { var isNeg = (time < 0); time = Math.abs(time); //xx:xx.xxx var millis = (time % 1000) .toString().paddingLeft("000"); var seconds = Math.floor((time % 60000) / 1000).toString().paddingLeft("00"); var minutes = Math.floor( time / 60000) .toString().paddingLeft("00"); return minutes + ":" + seconds + "." + millis; }; upperFirst = function(str) { return str[0].toUpperCase() + str.substring(1); }; invertColor = function(color) { var r = parseInt(color.substring(0, 2), 16); var g = parseInt(color.substring(2, 4), 16); var b = parseInt(color.substring(4, 6), 16); //Super cool actually investigating this rather than just using a hue/saturation calculation r = 255 - r; g = 255 - g; b = 255 - b; var c = [r, g, b]; //Which color index is the largest or smallest? var max = r > g ? (r > b ? 0 : 2) : (g > b ? 1 : 2); var min = r < g ? (r < b ? 0 : 2) : (g < b ? 1 : 2); //Which one did we not get? var other = (max + min == 1 ? 2 : (max + min == 3 ? 0 : 1)); //Calculate c[other] (probably a cleaner way to do this) c[other] = (c[max] - c[other]) + c[min]; //Save it because we can't just forget the value var cmax = c[max]; //Swap the two of them c[max] = c[min]; c[min] = cmax; var add = Math.floor(((255 * 3) - (c[0] + c[1] + c[2])) / 6); c[0] = (c[0] + add > 255 ? 255 : c[0] + add); c[1] = (c[1] + add > 255 ? 255 : c[1] + add); c[2] = (c[2] + add > 255 ? 255 : c[2] + add); r = c[0].toString(16).paddingLeft("00"); g = c[1].toString(16).paddingLeft("00"); b = c[2].toString(16).paddingLeft("00"); return r + g + b; }; // HTML5™, baby! http://mathiasbynens.be/notes/document-head document.head = document.head || document.getElementsByTagName('head')[0]; changeFavicon = function(src) { var link = document.createElement('link'), oldLink = document.getElementById('dynamic-favicon'); link.id = 'dynamic-favicon'; link.rel = 'shortcut icon'; link.href = src; if (oldLink) { document.head.removeChild(oldLink); } document.head.appendChild(link); }; window.addEventListener("focus", function(e) { webchat.flashTitle(); });
var axios = require('axios'); var _ = require('lodash'); var moment = require('moment'); var utilities = module.exports = { checkResponseStatus: function(res) { if (res.status !== 200) { throw new Error(res); } else { return res; } }, massageResponseData: function(data) { return data.data.lscd; }, filteredTeamCurrentRecord: function(payload, teamId) { var lastGameObject = _.last(payload) if (teamId === lastGameObject.v.tid) { return lastGameObject.v.re } else { return lastGameObject.h.re } }, filteredTeamNextGamesFromCurrentDate: function(schedule, date) { var scheduleFromCurrentDate = []; for (var i = 0; i < schedule.length; i++) { if (moment(date).isSameOrBefore(schedule[i].gdte)) { scheduleFromCurrentDate.push(schedule[i]) } } return scheduleFromCurrentDate; }, getHead: function(arr) { var test = [] _.filter(arr, function(x) { if (x === 1) { test.push('yes') } }) return test; }, filterForTeamSchedule: function(schedule, teamId) { var teamSchedule = []; _.filter(schedule, function(payloadSch) { if (payloadSch.v.tid === teamId || payloadSch.h.tid === teamId) { teamSchedule.push(payloadSch) } }); return teamSchedule; }, getCurrentSchedule: function(data) { var schedule = [] for (var mscdObj = 0; mscdObj < data.length; mscdObj++) { var gameSchedule = data[mscdObj].mscd.g; for (var gameObj = 0; gameObj < gameSchedule.length; gameObj++) { schedule.push(gameSchedule[gameObj]) } } return schedule; }, getResults: function(results) { console.log("READY!", results, results.length) return results; }, getDataFromApi: function(url) { return axios.get(url) .then(utilities.checkResponseStatus) .then(utilities.massageResponseData) .then(utilities.getCurrentSchedule) .catch(function(error) { if (error.response) { console.log(error.response.data) console.log(error.response.status) } else { console.log("Error with getData", error.message) } }); }, getFilteredTeamSchedule: function(payload, teamId) { return utilities.filterForTeamSchedule(payload, teamId) }, teamSchedule: function(url, teamId) { var getScheduleFromApi = utilities.getDataFromApi(url); return getScheduleFromApi.then(function(payload) { return utilities.getFilteredTeamSchedule(payload, teamId) }); }, currentScheduleFromDate: function(payload) { var now = moment().format('YYYY MM DD'); var date = now.replace(/\s+/g, '-'); return utilities.filteredTeamNextGamesFromCurrentDate(payload, date) }, getData: function(url, teamId) { return utilities.teamSchedule(url, teamId); } };
"autocall";function $_GET(){for(var o=window.location.search.substr(1).split("&"),n={},t=0;t<o.length;t++){var e=o[t].split("=");n[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return n}
'use strict' var format_if_necessary = require('./format_if_necessary') var R = require('ramda') module.exports = R.curry(function (space_replacement, data, header) { var to_grab = header.toLowerCase().replace(/ /g, space_replacement) return format_if_necessary(header)(data[to_grab]) })
/** * @author mrdoob / http://mrdoob.com/ */ import { BufferGeometry, DefaultLoadingManager, FileLoader, Float32BufferAttribute, Group, LineBasicMaterial, LineSegments, Material, Mesh, MeshPhongMaterial, NoColors, Points, PointsMaterial, VertexColors } from "../../../build/three.module.js"; var OBJLoader = ( function () { // o object_name | g group_name var object_pattern = /^[og]\s*(.+)?/; // mtllib file_reference var material_library_pattern = /^mtllib /; // usemtl material_name var material_use_pattern = /^usemtl /; function ParserState() { var state = { objects: [], object: {}, vertices: [], normals: [], colors: [], uvs: [], materialLibraries: [], startObject: function ( name, fromDeclaration ) { // If the current object (initial from reset) is not from a g/o declaration in the parsed // file. We need to use it for the first parsed g/o to keep things in sync. if ( this.object && this.object.fromDeclaration === false ) { this.object.name = name; this.object.fromDeclaration = ( fromDeclaration !== false ); return; } var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined ); if ( this.object && typeof this.object._finalize === 'function' ) { this.object._finalize( true ); } this.object = { name: name || '', fromDeclaration: ( fromDeclaration !== false ), geometry: { vertices: [], normals: [], colors: [], uvs: [] }, materials: [], smooth: true, startMaterial: function ( name, libraries ) { var previous = this._finalize( false ); // New usemtl declaration overwrites an inherited material, except if faces were declared // after the material, then it must be preserved for proper MultiMaterial continuation. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) { this.materials.splice( previous.index, 1 ); } var material = { index: this.materials.length, name: name || '', mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ), smooth: ( previous !== undefined ? previous.smooth : this.smooth ), groupStart: ( previous !== undefined ? previous.groupEnd : 0 ), groupEnd: - 1, groupCount: - 1, inherited: false, clone: function ( index ) { var cloned = { index: ( typeof index === 'number' ? index : this.index ), name: this.name, mtllib: this.mtllib, smooth: this.smooth, groupStart: 0, groupEnd: - 1, groupCount: - 1, inherited: false }; cloned.clone = this.clone.bind( cloned ); return cloned; } }; this.materials.push( material ); return material; }, currentMaterial: function () { if ( this.materials.length > 0 ) { return this.materials[ this.materials.length - 1 ]; } return undefined; }, _finalize: function ( end ) { var lastMultiMaterial = this.currentMaterial(); if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) { lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3; lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart; lastMultiMaterial.inherited = false; } // Ignore objects tail materials if no face declarations followed them before a new o/g started. if ( end && this.materials.length > 1 ) { for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) { if ( this.materials[ mi ].groupCount <= 0 ) { this.materials.splice( mi, 1 ); } } } // Guarantee at least one empty material, this makes the creation later more straight forward. if ( end && this.materials.length === 0 ) { this.materials.push( { name: '', smooth: this.smooth } ); } return lastMultiMaterial; } }; // Inherit previous objects material. // Spec tells us that a declared material must be set to all objects until a new material is declared. // If a usemtl declaration is encountered while this new object is being parsed, it will // overwrite the inherited material. Exception being that there was already face declarations // to the inherited material, then it will be preserved for proper MultiMaterial continuation. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) { var declared = previousMaterial.clone( 0 ); declared.inherited = true; this.object.materials.push( declared ); } this.objects.push( this.object ); }, finalize: function () { if ( this.object && typeof this.object._finalize === 'function' ) { this.object._finalize( true ); } }, parseVertexIndex: function ( value, len ) { var index = parseInt( value, 10 ); return ( index >= 0 ? index - 1 : index + len / 3 ) * 3; }, parseNormalIndex: function ( value, len ) { var index = parseInt( value, 10 ); return ( index >= 0 ? index - 1 : index + len / 3 ) * 3; }, parseUVIndex: function ( value, len ) { var index = parseInt( value, 10 ); return ( index >= 0 ? index - 1 : index + len / 2 ) * 2; }, addVertex: function ( a, b, c ) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] ); dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] ); dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] ); }, addVertexPoint: function ( a ) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] ); }, addVertexLine: function ( a ) { var src = this.vertices; var dst = this.object.geometry.vertices; dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] ); }, addNormal: function ( a, b, c ) { var src = this.normals; var dst = this.object.geometry.normals; dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] ); dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] ); dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] ); }, addColor: function ( a, b, c ) { var src = this.colors; var dst = this.object.geometry.colors; dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] ); dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] ); dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] ); }, addUV: function ( a, b, c ) { var src = this.uvs; var dst = this.object.geometry.uvs; dst.push( src[ a + 0 ], src[ a + 1 ] ); dst.push( src[ b + 0 ], src[ b + 1 ] ); dst.push( src[ c + 0 ], src[ c + 1 ] ); }, addUVLine: function ( a ) { var src = this.uvs; var dst = this.object.geometry.uvs; dst.push( src[ a + 0 ], src[ a + 1 ] ); }, addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) { var vLen = this.vertices.length; var ia = this.parseVertexIndex( a, vLen ); var ib = this.parseVertexIndex( b, vLen ); var ic = this.parseVertexIndex( c, vLen ); this.addVertex( ia, ib, ic ); if ( ua !== undefined && ua !== '' ) { var uvLen = this.uvs.length; ia = this.parseUVIndex( ua, uvLen ); ib = this.parseUVIndex( ub, uvLen ); ic = this.parseUVIndex( uc, uvLen ); this.addUV( ia, ib, ic ); } if ( na !== undefined && na !== '' ) { // Normals are many times the same. If so, skip function call and parseInt. var nLen = this.normals.length; ia = this.parseNormalIndex( na, nLen ); ib = na === nb ? ia : this.parseNormalIndex( nb, nLen ); ic = na === nc ? ia : this.parseNormalIndex( nc, nLen ); this.addNormal( ia, ib, ic ); } if ( this.colors.length > 0 ) { this.addColor( ia, ib, ic ); } }, addPointGeometry: function ( vertices ) { this.object.geometry.type = 'Points'; var vLen = this.vertices.length; for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) { this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) ); } }, addLineGeometry: function ( vertices, uvs ) { this.object.geometry.type = 'Line'; var vLen = this.vertices.length; var uvLen = this.uvs.length; for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) { this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) ); } for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) { this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) ); } } }; state.startObject( '', false ); return state; } // function OBJLoader( manager ) { this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager; this.materials = null; } OBJLoader.prototype = { constructor: OBJLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var loader = new FileLoader( scope.manager ); loader.setPath( this.path ); loader.load( url, function ( text ) { onLoad( scope.parse( text ) ); }, onProgress, onError ); }, setPath: function ( value ) { this.path = value; return this; }, setMaterials: function ( materials ) { this.materials = materials; return this; }, parse: function ( text ) { console.time( 'OBJLoader' ); var state = new ParserState(); if ( text.indexOf( '\r\n' ) !== - 1 ) { // This is faster than String.split with regex that splits on both text = text.replace( /\r\n/g, '\n' ); } if ( text.indexOf( '\\\n' ) !== - 1 ) { // join lines separated by a line continuation character (\) text = text.replace( /\\\n/g, '' ); } var lines = text.split( '\n' ); var line = '', lineFirstChar = ''; var lineLength = 0; var result = []; // Faster to just trim left side of the line. Use if available. var trimLeft = ( typeof ''.trimLeft === 'function' ); for ( var i = 0, l = lines.length; i < l; i ++ ) { line = lines[ i ]; line = trimLeft ? line.trimLeft() : line.trim(); lineLength = line.length; if ( lineLength === 0 ) continue; lineFirstChar = line.charAt( 0 ); // @todo invoke passed in handler if any if ( lineFirstChar === '#' ) continue; if ( lineFirstChar === 'v' ) { var data = line.split( /\s+/ ); switch ( data[ 0 ] ) { case 'v': state.vertices.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ), parseFloat( data[ 3 ] ) ); if ( data.length >= 7 ) { state.colors.push( parseFloat( data[ 4 ] ), parseFloat( data[ 5 ] ), parseFloat( data[ 6 ] ) ); } break; case 'vn': state.normals.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ), parseFloat( data[ 3 ] ) ); break; case 'vt': state.uvs.push( parseFloat( data[ 1 ] ), parseFloat( data[ 2 ] ) ); break; } } else if ( lineFirstChar === 'f' ) { var lineData = line.substr( 1 ).trim(); var vertexData = lineData.split( /\s+/ ); var faceVertices = []; // Parse the face vertex data into an easy to work with format for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) { var vertex = vertexData[ j ]; if ( vertex.length > 0 ) { var vertexParts = vertex.split( '/' ); faceVertices.push( vertexParts ); } } // Draw an edge between the first vertex and all subsequent vertices to form an n-gon var v1 = faceVertices[ 0 ]; for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) { var v2 = faceVertices[ j ]; var v3 = faceVertices[ j + 1 ]; state.addFace( v1[ 0 ], v2[ 0 ], v3[ 0 ], v1[ 1 ], v2[ 1 ], v3[ 1 ], v1[ 2 ], v2[ 2 ], v3[ 2 ] ); } } else if ( lineFirstChar === 'l' ) { var lineParts = line.substring( 1 ).trim().split( " " ); var lineVertices = [], lineUVs = []; if ( line.indexOf( "/" ) === - 1 ) { lineVertices = lineParts; } else { for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) { var parts = lineParts[ li ].split( "/" ); if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] ); if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] ); } } state.addLineGeometry( lineVertices, lineUVs ); } else if ( lineFirstChar === 'p' ) { var lineData = line.substr( 1 ).trim(); var pointData = lineData.split( " " ); state.addPointGeometry( pointData ); } else if ( ( result = object_pattern.exec( line ) ) !== null ) { // o object_name // or // g group_name // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869 // var name = result[ 0 ].substr( 1 ).trim(); var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 ); state.startObject( name ); } else if ( material_use_pattern.test( line ) ) { // material state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries ); } else if ( material_library_pattern.test( line ) ) { // mtl file state.materialLibraries.push( line.substring( 7 ).trim() ); } else if ( lineFirstChar === 's' ) { result = line.split( ' ' ); // smooth shading // @todo Handle files that have varying smooth values for a set of faces inside one geometry, // but does not define a usemtl for each face set. // This should be detected and a dummy material created (later MultiMaterial and geometry groups). // This requires some care to not create extra material on each smooth value for "normal" obj files. // where explicit usemtl defines geometry groups. // Example asset: examples/models/obj/cerberus/Cerberus.obj /* * http://paulbourke.net/dataformats/obj/ * or * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf * * From chapter "Grouping" Syntax explanation "s group_number": * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form * surfaces, smoothing groups are either turned on or off; there is no difference between values greater * than 0." */ if ( result.length > 1 ) { var value = result[ 1 ].trim().toLowerCase(); state.object.smooth = ( value !== '0' && value !== 'off' ); } else { // ZBrush can produce "s" lines #11707 state.object.smooth = true; } var material = state.object.currentMaterial(); if ( material ) material.smooth = state.object.smooth; } else { // Handle null terminated files without exception if ( line === '\0' ) continue; throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' ); } } state.finalize(); var container = new Group(); container.materialLibraries = [].concat( state.materialLibraries ); for ( var i = 0, l = state.objects.length; i < l; i ++ ) { var object = state.objects[ i ]; var geometry = object.geometry; var materials = object.materials; var isLine = ( geometry.type === 'Line' ); var isPoints = ( geometry.type === 'Points' ); var hasVertexColors = false; // Skip o/g line declarations that did not follow with any faces if ( geometry.vertices.length === 0 ) continue; var buffergeometry = new BufferGeometry(); buffergeometry.addAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) ); if ( geometry.normals.length > 0 ) { buffergeometry.addAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) ); } else { buffergeometry.computeVertexNormals(); } if ( geometry.colors.length > 0 ) { hasVertexColors = true; buffergeometry.addAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) ); } if ( geometry.uvs.length > 0 ) { buffergeometry.addAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) ); } // Create materials var createdMaterials = []; for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) { var sourceMaterial = materials[ mi ]; var material = undefined; if ( this.materials !== null ) { material = this.materials.create( sourceMaterial.name ); // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) { var materialLine = new LineBasicMaterial(); Material.prototype.copy.call( materialLine, material ); materialLine.color.copy( material.color ); materialLine.lights = false; material = materialLine; } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) { var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } ); Material.prototype.copy.call( materialPoints, material ); materialPoints.color.copy( material.color ); materialPoints.map = material.map; materialPoints.lights = false; material = materialPoints; } } if ( ! material ) { if ( isLine ) { material = new LineBasicMaterial(); } else if ( isPoints ) { material = new PointsMaterial( { size: 1, sizeAttenuation: false } ); } else { material = new MeshPhongMaterial(); } material.name = sourceMaterial.name; } material.flatShading = sourceMaterial.smooth ? false : true; material.vertexColors = hasVertexColors ? VertexColors : NoColors; createdMaterials.push( material ); } // Create mesh var mesh; if ( createdMaterials.length > 1 ) { for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) { var sourceMaterial = materials[ mi ]; buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi ); } if ( isLine ) { mesh = new LineSegments( buffergeometry, createdMaterials ); } else if ( isPoints ) { mesh = new Points( buffergeometry, createdMaterials ); } else { mesh = new Mesh( buffergeometry, createdMaterials ); } } else { if ( isLine ) { mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] ); } else if ( isPoints ) { mesh = new Points( buffergeometry, createdMaterials[ 0 ] ); } else { mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] ); } } mesh.name = object.name; container.add( mesh ); } console.timeEnd( 'OBJLoader' ); return container; } }; return OBJLoader; } )(); export { OBJLoader };
angular.module('gamilms_controller', []) .controller('InstanceCtrl', ['$scope', '$uibModalInstance', 'snackbar', function($scope, $uibModalInstance, snackbar) { $scope.share = function() { snackbar.create("Hello World!!"); }; $scope.ok = function() { $uibModalInstance.close(); }; }]);
var util = require('util'); var fs = require('fs'); var _ = require('underscore'); var Stream = require('stream'); // my lib var Replacer = require('./replace-text'); var GrepReplaceTextInFile = function (opts) { var validReplacers = _.isArray(opts.replacers) && _.every(opts.replacers, function (replacer) { return (replacer instanceof Replacer); }); // minimal error checking if (!_.isObject(opts)) { throw new Error('an opts obj must be passed to GrepReplaceTextInFile contructor'); } // streaming error evts if (_.isFunction(opts.cb)) { this.cb = opts.cb; } //////////////////////////////////////////// // initialise regex classes // //////////////////////////////////////////// if (validReplacers) { this.replacers = opts.replacers; // console.log('this.replacers', this.replacers); } else { // throw new Error({ // message: "invalid replacers" // }); // TO DO: change tests so can delete below this.replacers = []; opts.assets.forEach(function (path) { var replacerOpts = { newVersion: opts.newVersion, requireJs: opts.requireJs, filePath: path }; this.replacers.push(new Replacer(replacerOpts)); }.bind(this)); } ///////////////////////////////////// // file to be grepped // // opts.filePath: @{string} // // can only grep on file at a time // ///////////////////////////////////// this.inputFilePath = opts.filePath; this.outputFilePath = opts.filePath + '.tmp'; // file streams this.inputFile = fs.createReadStream(this.inputFilePath); this.outputFile = fs.createWriteStream(this.outputFilePath); // this.outputFile = fs.createWriteStream(this.replacer.run(opts.filePath, true)); // tranforming stream > performs replaces on text before piping thru to write stream this.tranformStream = new Stream(); this.tranformStream.readable = true; this.tranformStream.writable = true; _(this).bindAll('run'); }; GrepReplaceTextInFile.prototype.runSync = function (callback) { var input = fs.readFileSync(this.inputFilePath, 'utf8'); this.replacers.forEach(function (replacer) { input = replacer.run(input); }); fs.writeFileSync(this.inputFilePath, input, 'utf8'); fs.unlink(self.inputFilePath, callback); }; GrepReplaceTextInFile.prototype.run = function (callback) { var self = this, cb = (_.isFunction(callback)) ? callback : self.cb; this.tranformStream.write = function (buf) { var str = buf.toString(); self.replacers.forEach(function (replacer) { str = replacer.run(str); }); self.tranformStream.emit('data', str); }; this.tranformStream.end = function (buf) { // flush buffer + close stream if (arguments.length) { self.tranformStream.write(buf); } // delete input file fs.unlink(self.inputFilePath, function (err) { if (err) { cb(err); } else { // rename output file back to original input file's name that we've just deleted fs.rename(self.outputFilePath, self.inputFilePath, function (err, results) { if (err) cb(err); // return original file path for logging success to terminal cb(null, self.inputFilePath); }); } }); self.tranformStream.writable = false; }; this.tranformStream.destroy = function () { self.tranformStream.writable = false; }; //////////////////// // Error Handling // //////////////////// this.inputFile.on('error', cb); this.outputFile.on('error', cb); this.tranformStream.on('error', cb); ///////////////// // Bombs Away! // ///////////////// this.inputFile.pipe(this.tranformStream).pipe(this.outputFile); }; module.exports = GrepReplaceTextInFile;
define(['jquery', 'Leaflet', 'text!templates/location.html', 'text!templates/fave-row.html', 'common', 'favorites', 'Handlebars'], function($, L, html, html_row, common, favorites, Handlebars) { 'use strict'; $(document).ready(function() { var $apply_button = $('#faves-contact'), apply_sites = []; // Draw the Handlebars template for a location function drawTable(data, copa_locations, non_copa_locations) { var template = Handlebars.compile(html_row), $copa_body = $('#copa-table'), $non_copa_body = $('#non-copa-table'), copa_faves = [], non_copa_faves = [], application_site_ids = [], application_site_total = application_site_ids.length, copa_total = copa_locations.length, non_copa_total = non_copa_locations.length; for (var i=0; i < copa_total; i++) { var loc = copa_locations[i]; loc.index = i + 1; var $location = $(template(loc)); copa_faves.push($location); } for (var i=0; i < non_copa_total; i++) { var loc = non_copa_locations[i]; loc.index = i + 1; var $location = $(template(loc)); non_copa_faves.push($location); } if (copa_total > 0) { $copa_body.html(copa_faves); } if (non_copa_total > 0) { $non_copa_body.html(non_copa_faves); $('#non-copa').show(); } if (application_site_total == 0) { $apply_button.addClass('disabled'); } // Set removal listeners $('.hide-fave').on('click', function(e) { var $favorite = $(this), id = $favorite.data('id'), key = $favorite.data('key'), $fave_row = $('#fave-' + id); favorites.removeIdFromCookie(id); uncheckSite(id, key); if ( key ) { copa_total--; } else { non_copa_total--; } $fave_row.hide(); if ( copa_total == 0 ) { $('.empty-faves').show(); } if ( non_copa_total == 0 ) { $('#non-copa').hide(); } }); // Set apply checkbox listeners $('.apply-checkbox').on('change', function(e) { var $favorite = $(this), id = $favorite.data('id'), key = $favorite.data('key'); if (this.checked) { checkSite(id, key); } else { uncheckSite(id, key); } }); } function drawMap(data, copa_locations, non_copa_locations) { var mapboxURL = '', $map = $('#location-map'), latLng; if ($map.data("address-latitude") && $map.data("address-longitude")) { latLng = new L.LatLng($map.data("address-latitude"), $map.data("address-longitude")); } if (common.isRetinaDisplay()) { mapboxURL = 'https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}@2x.png?access_token=' } else { mapboxURL = 'https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=' } var accessToken = 'pk.eyJ1IjoidGhlYW5kcmV3YnJpZ2dzIiwiYSI6ImNpaHh2Z2hpcDAzZnd0bG0xeDNqYXdiOGkifQ.jV7_LuEh4KX2r5RudiQdIg'; var mapboxTiles = L.tileLayer(mapboxURL + accessToken, {attribution: 'Imagery from <a href="http://mapbox.com/about/maps/">MapBox</a>'}); var map = new L.Map('location-map', { center: latLng, zoom: 15}); var copa_markers = [] $.each(copa_locations, function(i, location) { var copa_icon = new L.divIcon({ className: "cel-icon copa-location-icon", iconSize: new L.point(50, 50), iconAnchor: [17, 45], html: i + 1 }); copa_markers.push(L.marker([location.geometry.latitude, location.geometry.longitude], {icon: copa_icon})); }); var non_copa_markers = [] $.each(non_copa_locations, function(i, location) { var copa_icon = new L.divIcon({ className: "cel-icon non-copa-location-icon", iconSize: new L.point(50, 50), html: i + 1 }); non_copa_markers.push(L.marker([location.geometry.latitude, location.geometry.longitude], {icon: copa_icon})); }); var bounds = L.featureGroup($.merge(copa_markers, non_copa_markers)).getBounds(); map.fitBounds(bounds, {padding: [50, 50]}); var copaLayer = new L.layerGroup(copa_markers), nonCopaLayer = new L.layerGroup(non_copa_markers); map.addLayer(mapboxTiles); map.addLayer(copaLayer); map.addLayer(nonCopaLayer); if (latLng) { var geolocatedIcon = L.icon({iconUrl: common.getUrl('icon-geolocation'), iconSize: [50, 50], iconAnchor: [17, 45]}), geolocatedMarker = L.marker([latLng.lat, latLng.lng], {icon: geolocatedIcon}).addTo(map).setZIndexOffset(1000); } } function checkSite(id, key) { apply_sites.push(key); if (apply_sites.length > 0) { $apply_button.removeClass('disabled'); } if (apply_sites.length == 2) { $('input:checkbox:not(:checked)').attr('disabled', true); } var copa_url = common.getUrl('copa-apply', { ids: apply_sites}); $('#faves-contact').attr('href', copa_url); } function uncheckSite(id, key) { apply_sites = apply_sites.filter(function (item) { return item !== key; }); var copa_url = common.getUrl('copa-apply', { ids: apply_sites}); $('#faves-contact').attr('href', copa_url); if (apply_sites.length == 0) {$apply_button.addClass('disabled');} $('input:checkbox:disabled').attr('disabled', false); } // get location ids: // url --> string :: /starred/12,13,54/ --> "12,13,54" // -- or -- // cookie string var cookie = favorites.getCookie(), regexResult = /([0-9,]+)/.exec(window.location.pathname), starredIds = ""; if (regexResult || cookie) { starredIds = regexResult ? regexResult[1] : cookie; $.getJSON(common.getUrl('starred-location-api', { locations: starredIds }), function (results) { var locations = results.locations, copa = [], non_copa = []; for (var i=0; i<locations.length; i++) { if (locations[i].copa.key == 0) { non_copa.push(locations[i]); } else { copa.push(locations[i]); } } if ( copa.length == 0 ) { $('.empty-faves').show(); } drawTable(results, copa, non_copa); drawMap(results, copa, non_copa); }); } else { $('.empty-faves').show(); } if(regexResult) { var initial_ids = regexResult[1].split(','); $.each(initial_ids, function(i, value) { favorites.addIdToCookie(value); }); } favorites.addClearListener(); // Handle back button logic. If there is a history.length greater than 2, // take them to /search/ otherwise do history.go(-1) $('#back-button').on('click', function(e) { if(regexResult) { var url = window.location.protocol + '//' + window.location.host + '/search/' window.location.href = url; } else { window.history.go(-1); } }); $('#faves-contact').on('click', function(e) { if ($('#faves-contact').hasClass('disabled')) { e.preventDefault(); } }); }); } );
var structuredClone = require('./structured-clone'); var HELLO_INTERVAL_LENGTH = 200; var HELLO_TIMEOUT_LENGTH = 60000; function IFrameEndpoint() { var listeners = {}; var isInitialized = false; var connected = false; var postMessageQueue = []; var helloInterval; function postToParent(message) { // See http://dev.opera.com/articles/view/window-postmessage-messagechannel/#crossdoc // https://github.com/Modernizr/Modernizr/issues/388 // http://jsfiddle.net/ryanseddon/uZTgD/2/ if (structuredClone.supported()) { window.parent.postMessage(message, '*'); } else { window.parent.postMessage(JSON.stringify(message), '*'); } } function post(type, content) { var message; // Message object can be constructed from 'type' and 'content' arguments or it can be passed // as the first argument. if (arguments.length === 1 && typeof type === 'object' && typeof type.type === 'string') { message = type; } else { message = { type: type, content: content }; } if (connected) { postToParent(message); } else { postMessageQueue.push(message); } } function postHello() { postToParent({ type: 'hello' }); } function addListener(type, fn) { listeners[type] = fn; } function removeListener(type) { delete listeners[type]; } function removeAllListeners() { listeners = {}; } function getListenerNames() { return Object.keys(listeners); } function messageListener(message) { // Anyone can send us a message. Only pay attention to messages from parent. if (message.source !== window.parent) return; var messageData = message.data; if (typeof messageData === 'string') messageData = JSON.parse(messageData); if (!connected && messageData.type === 'hello') { connected = true; stopPostingHello(); while (postMessageQueue.length > 0) { post(postMessageQueue.shift()); } } if (connected && listeners[messageData.type]) { listeners[messageData.type](messageData.content); } } function disconnect() { connected = false; stopPostingHello(); removeAllListeners(); window.removeEventListener('message', messageListener); } /** Initialize communication with the parent frame. This should not be called until the app's custom listeners are registered (via our 'addListener' public method) because, once we open the communication, the parent window may send any messages it may have queued. Messages for which we don't have handlers will be silently ignored. */ function initialize() { if (isInitialized) { return; } isInitialized = true; if (window.parent === window) return; // We kick off communication with the parent window by sending a "hello" message. Then we wait // for a handshake (another "hello" message) from the parent window. startPostingHello(); window.addEventListener('message', messageListener, false); } function startPostingHello() { if (helloInterval) { stopPostingHello(); } helloInterval = window.setInterval(postHello, HELLO_INTERVAL_LENGTH); window.setTimeout(stopPostingHello, HELLO_TIMEOUT_LENGTH); // Post the first msg immediately. postHello(); } function stopPostingHello() { window.clearInterval(helloInterval); helloInterval = null; } // Public API. return { initialize: initialize, getListenerNames: getListenerNames, addListener: addListener, removeListener: removeListener, removeAllListeners: removeAllListeners, disconnect: disconnect, post: post }; } var instance = null; // IFrameEndpoint is a singleton, as iframe can't have multiple parents anyway. module.exports = function getIFrameEndpoint() { if (!instance) { instance = new IFrameEndpoint(); } return instance; };
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp", "fr-ca", { title: "Instructions d'accessibilité", contents: "Contenu de l'aide. Pour fermer cette fenêtre, appuyez sur ESC.", legend: [ { name: "Général", items: [ { name: "Barre d'outil de l'éditeur", legend: "Appuyer sur ${toolbarFocus} pour accéder à la barre d'outils. Se déplacer vers les groupes suivant ou précédent de la barre d'outil avec les touches TAB et SHIFT-TAB. Se déplacer vers les boutons suivant ou précédent de la barre d'outils avec les touches FLECHE DROITE et FLECHE GAUCHE. Appuyer sur la barre d'espace ou la touche ENTRER pour activer le bouton de barre d'outils." }, { name: "Dialogue de l'éditeur", legend: "A l'intérieur d'un dialogue, appuyer sur la touche TAB pour naviguer jusqu'au champ de dalogue suivant, appuyez sur les touches SHIFT + TAB pour revenir au champ précédent, appuyez sur la touche ENTRER pour soumettre le dialogue, appuyer sur la touche ESC pour annuler le dialogue. Pour les dialogues avec plusieurs pages d'onglets, appuyer sur ALT + F10 pour naviguer jusqu'à la liste des onglets. Puis se déplacer vers l'onglet suivant avec la touche TAB ou FLECHE DROITE. Se déplacer vers l'onglet précédent avec les touches SHIFT + TAB ou FLECHE GAUCHE. Appuyer sur la barre d'espace ou la touche ENTRER pour sélectionner la page de l'onglet." }, { name: "Menu contextuel de l'éditeur", legend: "Appuyer sur ${contextMenu} ou entrer le RACCOURCI CLAVIER pour ouvrir le menu contextuel. Puis se déplacer vers l'option suivante du menu avec les touches TAB ou FLECHE BAS. Se déplacer vers l'option précédente avec les touches SHIFT+TAB ou FLECHE HAUT. appuyer sur la BARRE D'ESPACE ou la touche ENTREE pour sélectionner l'option du menu. Oovrir le sous-menu de l'option courante avec la BARRE D'ESPACE ou les touches ENTREE ou FLECHE DROITE. Revenir à l'élément de menu parent avec les touches ESC ou FLECHE GAUCHE. Fermer le menu contextuel avec ESC." }, { name: "Menu déroulant de l'éditeur", legend: "A l'intérieur d'une liste en menu déroulant, se déplacer vers l'élément suivant de la liste avec les touches TAB ou FLECHE BAS. Se déplacer vers l'élément précédent de la liste avec les touches SHIFT + TAB ou FLECHE HAUT. Appuyer sur la BARRE D'ESPACE ou sur ENTREE pour sélectionner l'option dans la liste. Appuyer sur ESC pour fermer le menu déroulant." }, { name: "Barre d'emplacement des éléments de l'éditeur", legend: "Appuyer sur ${elementsPathFocus} pour naviguer vers la barre d'emplacement des éléments de léditeur. Se déplacer vers le bouton d'élément suivant avec les touches TAB ou FLECHE DROITE. Se déplacer vers le bouton d'élément précédent avec les touches SHIFT+TAB ou FLECHE GAUCHE. Appuyer sur la BARRE D'ESPACE ou sur ENTREE pour sélectionner l'élément dans l'éditeur." } ] }, { name: "Commandes", items: [ { name: "Annuler", legend: "Appuyer sur ${undo}" }, { name: "Refaire", legend: "Appuyer sur ${redo}" }, { name: "Gras", legend: "Appuyer sur ${bold}" }, { name: "Italique", legend: "Appuyer sur ${italic}" }, { name: "Souligné", legend: "Appuyer sur ${underline}" }, { name: "Lien", legend: "Appuyer sur ${link}" }, { name: "Enrouler la barre d'outils", legend: "Appuyer sur ${toolbarCollapse}" }, { name: "Accéder à l'objet de focus précédent", legend: "Appuyer ${accessPreviousSpace} pour accéder au prochain espace disponible avant le curseur, par exemple: deux éléments HR adjacents. Répéter la combinaison pour joindre les éléments d'espaces distantes." }, { name: "Accéder au prochain objet de focus", legend: "Appuyer ${accessNextSpace} pour accéder au prochain espace disponible après le curseur, par exemple: deux éléments HR adjacents. Répéter la combinaison pour joindre les éléments d'espaces distantes." }, { name: "Aide d'accessibilité", legend: "Appuyer sur ${a11yHelp}" } ] } ] });
global.path = __dirname; var app = require('./backend'); app.run();
var fileName; function OracleRecorder(recordRTCOptions){ //Constructor of a recorder that requires RecordRTC and recordRTCOptions which are mono 44,1kHz by default if(typeof recordRTCOptions == "undefined"){ recordRTCOptions = {type: 'audio', bufferSize: 16384, sampleRate: 44100, leftChannel: false, disableLogs: true}; } this.recordRTCOptions = recordRTCOptions ; this.recorder = false ; this.stream = false ; var self = this ; //events this.onStart = function(callback){ //a function with no parameters that's executed when recording succesfully starts self.startRecordingSuccess = callback ; }; this.onStop = function(callback){ //a function (that takes the url of the audio and (optionnally) the blob of the recording) which is executed when recording succesfully stops self.stopRecordingSuccess = callback ; }; this.onMikeError = function(callback){ //a fuction called, when the microphone is not shared self.mikeError = function(err){ console.error(err); callback() ; self.recorder = false; } }; //actual processes this.stopRecording = function(){ self.recorder.stopRecording(function(audioURL){ self.stopRecordingSuccess(audioURL, self.recorder.blob); previewRec(audioURL); fileName = 'rec_' + Math.round((Date.now()-1400000000000)/92) + "" + Math.round(Math.random() * 99); var fileReader = new FileReader(); fileReader.onload = function(event) { var newBlob = new Blob([event.target.result], {type:"audio/ogg", endings:"native"}); //~ POST_using_XHR( newBlob ); PostBlob(newBlob, 'audio', fileName + ".ogg"); }; fileReader.readAsArrayBuffer(self.recorder.blob); }); }; this.startRecording = function(){ if(self.stream !== false){ //clearRecordedData, seems to lose the second parameter of getUserMedia //so we start a brand new recorder with the same stream self.recorder = RecordRTC(self.stream, self.recordRTCOptions); self.recorder.startRecording(); self.startRecordingSuccess(); } else{ navigator.getUserMedia( {video: false, audio: true}, function(stream){ self.stream = stream; if(window.isChrome){ self.stream = new window.MediaStream(stream.getAudioTracks()); } if (stream.getAudioTracks().length === 0) { console.log('you have no webcam nore mic available on your device'); } else { self.recorder = RecordRTC(self.stream, self.recordRTCOptions); self.recorder.startRecording(); self.startRecordingSuccess(); } }, self.mikeError); } }; } // Fonction qui permet de supprimer l'enregistrement du serveur s'il ne nous convient pas lors de l'écoute function deleteAudioVideoFiles() { if (!fileName) return; var formData = new FormData(); formData.append('delete-file', fileName); xhr('delete.php', formData, null, null, function(response) { console.log(response+"ici"); }); fileName = null; container.innerHTML = ''; } function previewRec (url){ container.appendChild(document.createElement('hr')); var mediaElement = document.createElement("audio"); var source = document.createElement('source'); source.src = url; source.type = 'audio/mp3'; mediaElement.appendChild(source); mediaElement.muted = false; mediaElement.controls = true; container.appendChild(mediaElement); mediaElement.play(); } // PostBlob method uses XHR2 and FormData to submit // recorded blob to the PHP server function PostBlob(blob, fileType, fileName) { // FormData var formData = new FormData(); formData.append(fileType + '-filename', fileName); formData.append(fileType + '-blob', blob); // progress-bar var hr = document.createElement('hr'); container.appendChild(hr); var strong = document.createElement('strong'); strong.id = 'percentage'; strong.innerHTML = fileType + ' oracleupload progress: '; container.appendChild(strong); var progress = document.createElement('progress'); container.appendChild(progress); //Récupération des identifiants pour insertion dans la table enregistrement var userid = $("#userid").attr("data-userid"); var userlang = $("#lang").attr("data-userlang"); var gamelang = $("#lang").attr("data-gamelang"); var cardid = $("#cardid").attr("data-cardid"); var gamelevel = $("#level").attr("data-gamelevel"); var levelcard = $("#level").attr("data-levelcard"); // POST the Blob using XHR2 xhr('save.php?cardid='+cardid, formData, progress, percentage, function(fileURL) { var href = location.href.substr(0, location.href.lastIndexOf('/') + 1); progress.parentNode.removeChild(progress); strong.parentNode.removeChild(strong); hr.parentNode.removeChild(hr); }); } function xhr(url, data, progress, percentage, callback) { var request = new XMLHttpRequest(); request.onreadystatechange = function() { if (request.readyState == 4 && request.status == 200) { callback(request.responseText); } }; // TODO : si firefox alors addeventlistener ; si chrome alors onloadstart/progress/load if (url.indexOf('delete.php') == -1) { if(!isChrome){ request.upload.addEventListener("loadstart", function() { percentage.innerHTML = 'Upload started...'; },false); request.upload.addEventListener("progress", function(event){ progress.max = event.total; progress.value = event.loaded; percentage.innerHTML = 'Upload Progress ' + Math.round(event.loaded / event.total * 100) + "% "; },false); request.upload.addEventListener("load",function(){ percentage.innerHTML = 'Saved!'; $("#form-cmd").show("slow"); },false); } else { request.upload.onloadstart = function() { percentage.innerHTML = 'Upload started...'; }; request.upload.onprogress = function(event) { progress.max = event.total; progress.value = event.loaded; percentage.innerHTML = 'Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%"; }; request.upload.onload = function() { percentage.innerHTML = 'Saved!'; $("#form-cmd").show("slow"); }; } } request.open('POST', url); request.send(data); }
/** * @file 脚本支持 * @author hejieye * @time 2019-05-16 * @version 2.2.0 */ define(function (require) { var $ = require('zepto'); var customElem = require('customElement').create(); var busUid = ''; // var httpPath = 'https://mipp.iask.cn'; var httpPath = 'https://m.iask.sina.com.cn'; var fetchJsonp = require('fetch-jsonp'); var utf8Encode = function (string) { string = string.replace(/\r\n/g, '\n'); var utftext = ''; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; var utf8Decode = function (utftext) { var string = ''; var i = 0; var c = 0; var c1 = 0; var c2 = 0; var c3 = 0; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }; var Base64 = function () { var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; this.encode = function (input) { var output = ''; var chr1; var chr2; var chr3; var enc1; var enc2; var enc3; var enc4; var i = 0; var input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; }; this.decode = function (input) { if (input.indexOf('appid') !== -1 || input.indexOf('smqid') !== -1 || input.indexOf('adList') !== -1) { return input; } var output = ''; var chr1; var chr2; var chr3; var enc1; var enc2; var enc3; var enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); while (i < input.length) { enc1 = keyStr.indexOf(input.charAt(i++)); enc2 = keyStr.indexOf(input.charAt(i++)); enc3 = keyStr.indexOf(input.charAt(i++)); enc4 = keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } } output = utf8Decode(output); return output; }; }; var setCookie = function (name, value) { var Days = 360 * 10; // 此cookie将被保存10年 var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString(); }; var getCookie = function (name) { var arr = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)')); if (arr !== null) { unescape(arr[2]); } else { return null; } }; var delCookie = function (name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval !== null) { document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString(); } }; var encodeURIStr = function (str) { var result = encodeURIComponent(JSON.stringify(str)); return result; }; var loadStatsToken = function ($tokenDiv, token) { $tokenDiv.innerHTML = '<mip-stats-baidu token="' + token + '"></mip-stats-baidu>'; }; var ipLoad = function (callback) { var url = 'https://ipip.iask.cn/iplookup/search?format=json&callback=?'; // var url = 'https://mipp.iask.cn/iplookup/search?format=json&ip=43.226.37.75&callback=?'; try { $.getJSON(url, function (data) { callback(data); }); } catch (e) {} }; var hotRecommendUnLi = function (url, img, title, statsBaid, pos) { var htmls = ''; if (pos === '') { htmls += '<div href=' + url + ' target=\'_blank\' class=\'href_log\'' + statsBaid + '>'; } else { htmls += '<div href=' + url + ' target=\'_blank\' pos="' + pos + '" class=\'href_log\'' + statsBaid + '>'; } htmls += '<mip-img class=\'mip-img\' src=' + img + '>'; htmls += '<p class=\'mip-img-subtitle\'>' + title + '</p>'; htmls += '</mip-img>'; htmls += '</div>'; return htmls; }; var hotRecommend = function (url, img, title, statsBaid, pos) { var htmls = ''; htmls += '<li>'; if (pos === '') { htmls += '<div href=' + url + ' target=\'_blank\' class=\'href_log\'' + statsBaid + '>'; } else { htmls += '<div href=' + url + ' target=\'_blank\' pos="' + pos + '" class=\'href_log\'' + statsBaid + '>'; } htmls += '<mip-img class=\'mip-img\' src=' + img + '>'; htmls += '<p class=\'mip-img-subtitle\'>' + title + '</p>'; htmls += '</mip-img>'; htmls += '</div></li>'; return htmls; }; var hotRecommendDiv = function (str) { var html = '<div class="hot-tui hot_recomd_div" id="rm_recommend">'; html += '<h3>热门推荐<span class="icon-bai"></span></h3>'; html += '<ul class="hot-tui-list">'; html += str; html += '</ul></div>'; return html; }; var hotSpotUnLi = function (url, title) { var htmls = ''; htmls += '<a href=' + url + ' target=\'_blank\' class=\'href_log\'>' + title + '</a>'; return htmls; }; var getChannel = function (ele) { var list = {}; var $that = ele.querySelectorAll('.channel_source li'); if ($that.length > 0) { for (var i = 0; i < $that.length; i ++) { var txt = $that[i].getAttribute('txt'); var val = $that[i].getAttribute('val'); list[txt] = val; } } return list; }; var getUserId = function (source, uid, adOwnerId) { if (source === '202' || source === '500' || source === '501' || source === '600' || source === '700' || source === '800') { return uid; } else if (source === '1000' || source === '101' || source === '300' || source === '102' || source === '103' || source === '105' || source === '106') { return adOwnerId; } return ''; }; var getSysTime = function () { var mydate = new Date(); var month = mydate.getMonth() + 1; var day = mydate.getDate(); var hours = mydate.getHours(); var minutes = mydate.getMinutes(); var seconds = mydate.getSeconds(); return mydate.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + ' ' + (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds); }; var removeClass = function (obj, cls) { var objClass = ' ' + obj.className + ' '; objClass = objClass.replace(/(\s+)/gi, ' '); var removed = objClass.replace(' ' + cls + ' ', ' '); removed = removed.replace(/(^\s+)|(\s+$)/g, ''); obj.className = removed; }; var addClass = function (obj, cls) { var objClass = ' ' + obj.className + ' '; var add = objClass + ' ' + cls; obj.className = add; }; var advLogInfo = function (ele, sourceType, mode) { var $that = ele.querySelector('.paramDiv'); var qid = $that.getAttribute('qid') || ''; var materialTag = $that.getAttribute('mainTags') || ''; var ip = ''; var province = ''; var city = ''; var qcid = $that.getAttribute('qcid') || ''; var cid = $that.getAttribute('cid') || ''; var uid = $that.getAttribute('uid') || ''; var adOwnerId = $that.getAttribute('adOwnerId') || ''; var version = $that.getAttribute('version') || ''; if (sourceType === 'COOPERATE_BRAND' && version === '1') { sourceType = 'COOPERATE_BRAND_1'; } else if (sourceType === 'COOPERATE_BRAND_MARKET' && version === '3') { sourceType = 'COOPERATE_BRAND_MARKET_3'; } var source = getChannel(ele)[sourceType] || 999; uid = getUserId(source, uid, adOwnerId) || busUid; var pos = $that.getAttribute('pos') || ''; var pv = ''; if (pos === undefined || pos === 'undefined') { pos = ''; } // 2018-09-14 上报需要uid // uid = ''; ipLoad(function (data) { ip = data.ip || ''; province = data.province || ''; city = data.city || ''; if (!!materialTag) { materialTag = materialTag.replace('[', '').replace(']', ''); } pv = encodeURI('pv=' + mode + '_' + qid + '_' + ip + '_' + province + '_' + city + '_' + materialTag + '_' + qcid + '_' + cid + '_' + source + '_' + uid + '_' + pos); var url = httpPath + '/advLogInfo?' + pv; $.get(url); }); }; var advLogInfoClick = function (ele, clazz, $that, newSource) { $(clazz).on('click', function () { var pos = $(this).attr('pos'); var url = $(this).attr('href'); openURL(ele, pos, url, $that, newSource); }); }; function openURL(ele, pos, url, $that, newSource) { var sources = $that.getAttribute('sources'); var sysource = $that.getAttribute('sysources'); if (sysource === 'COMMERCIAL_ZWZD') { sysource = 'COOPERATE_COMMERCIAL'; } if (newSource !== '' && newSource !== undefined) { sources = newSource; } $that.setAttribute('pos', pos); advLogInfo(ele, sources, 1); openWindowUrl(ele, url); } function openWindowUrl(ele, url) { var $that = ele.querySelectorAll('.camnpr'); if ($that.length > 0) { for (var i = 0; i < $that.length; i++) { var t = $that[i]; t.parentNode.removeChild(t); } } var a = ele.createElement('a'); a.setAttribute('href', url); a.setAttribute('target', '_blank'); a.setAttribute('class', 'camnpr'); ele.body.appendChild(a); a.click(); } var subStringIask = function (str, size) { if (!str) { return ''; } if (str.length > size) { return str.substring(0, size) + '...'; } return str; }; var centralBanner = function (picLink, picLocal, statsBaidu, pos) { var htmls = ''; if (pos === '') { htmls += '<div href=' + picLink + ' class=\'href_log\' ' + statsBaidu + '>'; } else { htmls += '<div href=' + picLink + ' pos="' + pos + '" class=\'href_log\'' + statsBaidu + '>'; } htmls += '<mip-img class=\'mip-img bottom-img\' src=' + picLocal + '></mip-img>'; htmls += '<span class=\'icon-bai-bottom\'></span>'; htmls += '</div>'; return htmls; }; // 判断节点是否存在, 存在则在该位置上投放广告 var isExistsNode = function () { var pos = ''; if ($('.new-similar-dl').length > 0) { pos = '.new-similar-dl'; } else if ($('.similar').length > 0) { pos = '.similar'; } else if ($('.hot-top').length > 0) { pos = '.hot-top'; } return pos; }; // 企业信息广告 var putQiyeInfo = function (ele, companyName, drName, website, picLocal, statsBaidu, pos, newSource) { var $thatQS = ele.querySelectorAll('.qs_bar'); var $thatDiv = ele.querySelectorAll('.mip_as_other_qiye_div'); if (!!companyName) { if (companyName.length > 9) { companyName = companyName.substring(0, 9); } } if (!!drName) { if (drName.length > 15) { drName = drName.substring(0, 15); } } var htmls = '<div class=\'firms-con href_log\' href=' + website + ' ' + statsBaidu + ' pos="' + pos + '">'; htmls += '<div class=\'firms-pic\'>'; htmls += '<mip-img class=\'mip-img\' src=' + picLocal + '></mip-img>'; htmls += '<span class=\'icon-v\'></span>'; htmls += '</div>'; htmls += '<div class=\'firms-text\'>'; htmls += '<p><span class=\'name\'>' + companyName + '</span>'; htmls += '<span class=\'time\'> 1小时前</span><span class=\'icon-tui\'>广告</span></p>'; if (!!drName) { htmls += '<p>' + drName + '</p>'; } htmls += '</div>'; htmls += '<span class=\'btn-ask \' >咨询专家</span>'; htmls += '</div>'; htmls += '</div>'; try { var $thatQSHLog = ele.querySelectorAll('.qs_bar .href_log'); var $thatDivHLog = ele.querySelectorAll('.mip_as_other_qiye_div .href_log'); if ($thatQS.length >= 1 && $thatQSHLog.length === 0) { $thatQS[0].innerHTML = htmls; } else if ($thatQS.length > 1 && $thatQSHLog.length > 0) { $thatQS[1].innerHTML = htmls; } else if ($thatDiv.length >= 1 && $thatDivHLog.length === 0) { $thatDiv[0].innerHTML = htmls; } else if ($thatDiv.length >= 1 && $thatQSHLog.length > 0) { $thatDiv[0].innerHTML = htmls; } else { $thatDiv[1].innerHTML = htmls; } $('.qs_bar .href_log').unbind(); $('.mip_as_other_qiye_div .href_log').unbind(); advLogInfoClick(ele, '.qs_bar .href_log', ele.querySelector('.paramDiv'), newSource); advLogInfoClick(ele, '.mip_as_other_qiye_div .href_log', ele.querySelector('.paramDiv'), newSource); } catch (e) { console.log(e); } }; // 品牌企业信息广告 var putBrandQiyeInfo = function (ele, companyName, drName, website, picLocal, statsBaidu, pos, brandLink) { var $thatQS = ele.querySelectorAll('.qs_bar'); var $thatDiv = ele.querySelectorAll('.mip_as_other_qiye_div'); if (companyName.length > 9) { companyName = companyName.substring(0, 9); } var htmls = '<div class=\'firms-con\' >'; htmls += '<div class=\'firms-pic\' ><a href=' + brandLink + '>'; htmls += '<mip-img class=\'mip-img\' src=' + picLocal + '></mip-img>'; htmls += '<span class=\'icon-v\'></span>'; htmls += '</a></div>'; htmls += '<div class=\'firms-text\'>'; htmls += '<p><a href=' + brandLink + '><span class=\'name \'>' + companyName + '</span></a>'; htmls += '<span class=\'time\'> 1小时前</span><span class=\'icon-tui\'>广告</span></p>'; htmls += '<p class=\' href_log\' href=' + website + ' ' + statsBaidu + ' pos="' + pos + '">' + drName + '</p>'; htmls += '</div>'; htmls += '<span class=\'btn-ask href_log\''; htmls += 'href=' + website + ' ' + statsBaidu + ' pos="' + pos + '">咨询专家</span>'; htmls += '</div>'; htmls += '</div>'; if ($thatQS.length > 0) { $thatQS[0].innerHTML = htmls; advLogInfoClick(ele, '.qs_bar .href_log', ele.querySelector('.paramDiv'), ''); } else if ($thatDiv.length > 0) { $thatDiv[0].innerHTML = htmls; advLogInfoClick(ele, '.mip_as_other_qiye_div .href_log', ele.querySelector('.paramDiv'), ''); } }; // 保险企业信息广告 var putBaoXiangQiyeInfo = function (ele, picLink, picLocal, statsBaidu, pos) { var $thatQS = ele.querySelectorAll('.qs_bar'); var $thatDiv = ele.querySelectorAll('.mip_as_other_qiye_div'); var htmls = ''; if (pos === '') { htmls += '<a href="tel:' + picLink + '" ' + statsBaidu + '>'; } else { htmls += '<a href="tel:' + picLink + '" pos="' + pos + '" ' + statsBaidu + '>'; } htmls += '<mip-img class=\'mip-img baoxiang-img\' src=' + picLocal + '></mip-img>'; htmls += '</a>'; try { if ($thatQS.length > 0) { $thatQS[0].innerHTML = htmls; } else if ($thatDiv.length > 0) { $thatDiv[0].innerHTML = htmls; } advLogInfoClick(ele, '.mip_as_other_qiye_div .href_log', ele.querySelector('.paramDiv'), ''); } catch (e) { console.log(e); } }; var feedInfo = function (ele, statsBaidu, userImg, useName, shortIntroduce, materialIntroduce, materialLink, picList, pos) { var $that = ele.querySelector('.youlai_feed_div'); var $thatLink = ele.querySelector('.youlai_feed_div span'); var $thatFeed = ele.querySelectorAll('.youlai_feed_div .youlai_feed'); var objPicUrl = '<mip-img class="mip-img" src="' + userImg + '"></mip-img>'; ele.querySelector('.youlai_feed_div .youlai_feed_title').innerHTML = materialIntroduce; ele.querySelector('.youlai_feed_div .youlai_feed_use_img').innerHTML = objPicUrl; ele.querySelector('.youlai_feed_div .youlai_feed_use_name').innerHTML = useName; ele.querySelector('.youlai_feed_div .youlai_feed_txt').innerHTML = shortIntroduce; $thatLink.setAttribute('pos', pos); $thatLink.setAttribute('href', materialLink); $thatLink.setAttribute('class', 'href_log'); $thatLink.setAttribute('data-stats-baidu-obj', statsBaidu); if ($thatFeed.length > 0) { for (var i = 0; i < $thatFeed.length; i++) { $thatFeed[i].innerHTML = '<mip-img class="mip-img" src="' + picList[i] + '"></mip-img>'; } } addClass($that, 'show'); advLogInfoClick(ele, '.youlai_feed_div .href_log', ele.querySelector('.paramDiv'), ''); }; // 商业广告 var busBottomAM = function (ele, $tokenDiv, token) { var $thatBottom = ele.querySelectorAll('.bus_bottom_div div'); var $thatHot = ele.querySelectorAll('.bus_hot_recommend_div div'); var $thatRecomd = ele.querySelector('.hot_recomd_div'); var $thatHotSpot = ele.querySelectorAll('.bus_hot_spot div'); var nodeClass = isExistsNode(); if ($thatBottom.length > 0) { for (var i = 0; i < $thatBottom.length; i++) { var area = $thatBottom[i].getAttribute('area'); var imgurl = $thatBottom[i].getAttribute('imgurl'); var picurl = $thatBottom[i].getAttribute('picurl'); busUid = $thatBottom[i].getAttribute('uid'); if (area === '') { $(nodeClass).append(centralBanner(imgurl, picurl, '', '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), ''); } else { ipLoad(function (data) { if (area.indexOf(data.province) > -1) { $(nodeClass).append(centralBanner(imgurl, picurl, '', '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), ''); } }); } } } if ($thatHot.length > 0) { for (var i = 0; i < $thatHot.length; i ++) { var area = $thatHot[i].getAttribute('area'); var url = $thatHot[i].getAttribute('texturl'); var img = $thatHot[i].getAttribute('img'); var title = $thatHot[i].getAttribute('imgtitle'); busUid = $thatHot[i].getAttribute('uid'); if (area === '') { var str = hotRecommendUnLi(url, img, title, '', ''); var liDom = ele.createElement('li'); liDom.innerHTML = str; ele.querySelector('.hot-tui-list').appendChild(liDom); } else { ipLoad(function (data) { var str = hotRecommendUnLi(url, img, title, '', ''); var liDom = ele.createElement('li'); liDom.innerHTML = str; ele.querySelector('.hot-tui-list').appendChild(liDom); }); } } addClass($thatRecomd, 'show'); advLogInfoClick(ele, '.hot_recomd_div .href_log', ele.querySelector('.paramDiv'), ''); } if ($thatHotSpot.length > 0) { for (var i = 0; i < $thatHotSpot.length; i++) { var area = $thatHotSpot[i].getAttribute('area'); var url = $thatHotSpot[i].getAttribute('texturl'); var title = $thatHotSpot[i].getAttribute('imgtitle'); busUid = $thatHotSpot[i].getAttribute('uid'); if (area === '') { var str = hotSpotUnLi(url, title); var liDom = ele.createElement('li'); liDom.innerHTML = str; ele.querySelector('.hot-point-list').appendChild(liDom); } else { ipLoad(function (data) { var str = hotSpotUnLi(url, title); var liDom = ele.createElement('li'); liDom.innerHTML = str; ele.querySelector('.hot-point-list').appendChild(liDom); }); } } advLogInfoClick(ele, '.hot-point-list .href_log', ele.querySelector('.paramDiv'), ''); } loadStatsToken($tokenDiv, token); }; var validatePut = function (ele) { var $that = ele.querySelectorAll('.paramDiv')[0]; var mmaintags = $that.getAttribute('mainTags'); var qcid = $that.getAttribute('qcid') || ''; var sources = $that.getAttribute('sources'); var version = $that.getAttribute('version'); var iscommercial = $that.getAttribute('iscommercial'); if ('COOPERATE_BRAND' === sources && version === '2') { return false; } if (iscommercial === 'true' && sources !== 'COOPERATE_COMMERCIAL') { // 过滤掉第三合作广告 return false; } if (qcid === '82' && (mmaintags.indexOf('财务税务') !== -1 || mmaintags.indexOf('商业工具') !== -1)) { return true; } return false; }; // 移除百度广告 var removeBaiduAd = function (ele) { var $that = ele.querySelectorAll('.mip_baidu_sy'); if ($that.length > 0) { for (var i = 0; i < $that.length; i++) { var t = $that[i]; t.style.display = 'none'; } } }; var removeInfo = function (ele) { var $that = ele.querySelectorAll('.info-flow-json'); if ($that.length > 0) { for (var i = 0; i < $that.length; i++) { var t = $that[i]; t.parentNode.removeChild(t); } } }; var hexToDec = function (str) { try { if (str.indexOf('\\u') !== -1) { str = str.replace(/\\/g, '%'); return unescape(str); } return str; } catch (e) { return str; } }; var youLai = function (ele, data) { var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; var json = data.adList; var baiduStr = ''; var baiduObj = ''; for (var key in json) { if (json[key].type === '3') { // 企业信息 var obj = json[key]; var companyName = obj.companyName; var drName = obj.drName; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1000', 'skip', 'MIP_SY_1000_qyxx']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; putQiyeInfo(ele, drName, companyName, data.website, obj.picUrl, baiduObj, '2'); } else if (json[key].type === '5') { var obj2 = {}; for (var k in json) { if (json[k].type === '3') { obj2 = json[k]; } } var obj = json[key]; var picList = obj.picList; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1000', 'skip', 'MIP_SY_1000_feedgg']}; baiduObj = encodeURIStr(baiduStr); feedInfo(ele, baiduObj, obj2.picUrl, obj2.companyName, obj.describe, obj.title, obj.picLink, picList, '3'); } else if (json[key].type === '6') { var obj = json[key]; var picList = obj.adDetailList; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1000', 'skip', 'MIP_SY_1000_qtgg']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; var str = ''; for (var pic in picList) { var picLink = obj.picLink; var picUrl = picList[pic].picUrl; var describe = picList[pic].describe; str += hotRecommend(picLink, picUrl, describe, baiduObj, '4'); } $('.everyone_notices_div').prepend(hotRecommendDiv(str)); advLogInfoClick(ele, '.hot-tui-list .href_log', ele.querySelector('.paramDiv'), ''); } } loadStatsToken($tokenDiv, token); }; var soulew = function (ele, data, cn) { var nodeClass = isExistsNode(); var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; var json = data.adList; var bStr = ''; var baiduObj = ''; var desc = ''; if (cn === 300) { desc = 'tz'; } else if (cn === 101) { desc = 'sl'; } else if (cn === 102) { desc = 'hxdl'; } else if (cn === 106) { desc = '258'; } else if (cn === 105) { desc = 'zq'; } for (var key in json) { var material = json[key]; if (material.type === '4' || (material.type === '1' && material.materialType === '5')) { bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + cn, 'skip', 'MIP_SY_' + cn + '_' + desc]}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; $(nodeClass).append(centralBanner(material.picLink, material.picUrl, baiduObj, '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), ''); } else if (material.type === '3') { // 企业信息 var obj = material; var companyName = obj.companyName; var drName = obj.drName; bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + cn, 'skip', 'MIP_SY_' + cn + '_' + desc]}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; putQiyeInfo(ele, companyName, drName, data.website, obj.picUrl, baiduObj, ''); } else if (material.type === '5') { var obj2 = {}; for (var k in json) { if (json[k].type === '3') { obj2 = json[k]; } } var obj = json[key]; var picList = obj.picList; bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + cn, 'skip', 'MIP_SY_' + cn + '_' + desc]}; baiduObj = encodeURIStr(bStr); feedInfo(ele, baiduObj, obj2.picUrl, obj.companyName, obj.describe, obj.title, obj.picLink, picList, ''); } else if (material.type === '6' || material.type === '8') { var obj = json[key]; var picList = obj.adDetailList; bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + cn, 'skip', 'MIP_SY_' + cn + '_' + desc]}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; var str = ''; for (var pic in picList) { var picLink = obj.picLink; var picUrl = picList[pic].picUrl; var describe = picList[pic].describe; str += hotRecommend(picLink, picUrl, describe, baiduObj, ''); } $('.hot-top').after(hotRecommendDiv(str)); advLogInfoClick(ele, '.hot-tui-list .href_log', ele.querySelector('.paramDiv'), ''); } } loadStatsToken($tokenDiv, token); }; var brandMedical = function (ele, data) { // 品牌医疗 var json = data.adList; var qiyeData = null; var nodeClass = isExistsNode(); var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; var tempStr = ''; var statsBaidu = ''; for (var k in json) { if (json[k].adType === 3) { qiyeData = json[k]; } } for (var key in json) { if (json[key].adType === 1) { tempStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_800_yl', 'skip', 'MIP_SY_800_yl']}; statsBaidu = 'data-stats-baidu-obj="' + encodeURIStr(tempStr) + '"'; $(nodeClass).append(centralBanner(json[key].materialLink, json[key].materialImg, statsBaidu, '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), ''); } else if (json[key].adType === 3) { var obj = qiyeData; var companyName = obj.shortIntroduce; var drName = obj.brandName; tempStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_800_yl', 'skip', 'MIP_SY_800_yl']}; statsBaidu = 'data-stats-baidu-obj="' + encodeURIStr(tempStr) + '"'; putQiyeInfo(ele, drName, companyName, obj.materialLink, obj.materialImg, statsBaidu, ''); } else if (json[key].adType === 5) { var obj = json[key]; var picList = new Array(0); var materImg = obj.materialImg.split(','); for (var k in materImg) { picList.push(materImg[k]); } tempStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_800_yl', 'skip', 'MIP_SY_800_yl']}; statsBaidu = encodeURIStr(tempStr); feedInfo(ele, statsBaidu, qiyeData.materialImg, qiyeData.brandName, obj.materialIntroduce, obj.shortIntroduce, obj.materialLink, picList, ''); } else if (json[key].adType === 6) { var obj = json[key]; tempStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_800_yl', 'skip', 'MIP_SY_800_yl']}; statsBaidu = 'data-stats-baidu-obj="' + encodeURIStr(tempStr) + '"'; var arrayPic = new Array(0); var arrayDesc = new Array(0); var materImg = obj.materialImg.split(','); var materDesc = obj.materialIntroduce.split('|'); for (var index in materImg) { arrayPic.push(materImg[index]); arrayDesc.push(materDesc[index]); } var str = ''; for (var pic in arrayPic) { var picLink = obj.materialLink; var picUrl = arrayPic[pic]; var describe = arrayDesc[pic]; str += hotRecommend(picLink, picUrl, describe, statsBaidu, ''); } $('.critics').after(hotRecommendDiv(str)); advLogInfoClick(ele, '.hot-tui-list .href_log', ele.querySelector('.paramDiv'), ''); } } loadStatsToken($tokenDiv, token); }; // 商业广告标准版企业信息 var commercialSqc = function (ele, divData, commercialStandardHover) { var nodeClass = isExistsNode(); var tempStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_600', 'skip', 'MIP_SY_600_bz']}; var statsBaidu = 'data-stats-baidu-obj="' + encodeURIStr(tempStr) + '"'; var imgsrc = divData.getAttribute('imgsrc'); var brandname = divData.getAttribute('brandname'); var link = divData.getAttribute('link'); var introduce = divData.getAttribute('introduce'); var uid = divData.getAttribute('uid'); var brandLink = httpPath + '/brand/' + uid + '.html'; putBrandQiyeInfo(ele, brandname, introduce, link, imgsrc, statsBaidu, '', brandLink); var tImgSrc = commercialStandardHover.getAttribute('imgsrc'); var tLink = commercialStandardHover.getAttribute('link'); var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_600', 'skip', 'MIP_SY_600_bz']}; var baiduTop = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; $(nodeClass).append(centralBanner(tLink, tImgSrc, baiduTop, '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv')); }; var loadAd = function (ele, sources, openId, questionId, version) { var type = ''; if (sources === 'COOPERATE_HUASHENG') { type = 'HS'; } else if (sources === 'COOPERATE_HUASHENG_QA') { type = 'HSQA'; } else if (sources === 'COOPERATE_YOULAI') { type = 'YL'; } else if (sources === 'COOPERATE_TIANZHU') { type = 'TZ'; } else if (sources === 'COOPERATE_BRAND_MARKET' && version === '4') { type = 'PPYL'; } else if (sources === 'COOPERATE_SOULE') { type = 'SLW'; } else if (sources === 'COOPERATE_HUAXIN') { type = 'HX'; } else if (sources === 'COOPERATE_ZHONGQI') { type = 'ZQ'; } else if (sources === 'COOPERATE_258JT') { type = '258'; } else if (type === '') { return; } var url = httpPath + '/t/wlsh?openCorporationId=' + openId + '&type=' + type; url += '&questionId=' + questionId + '&version=' + version; $.get(url, function (data) { var base = new Base64(); var res = $.parseJSON(data); if (res.succ === 'Y') { var json = $.parseJSON(base.decode(res.html)); if (type === 'YL') { youLai(ele, json); return; } if (type === 'TZ') { soulew(ele, json, 300); return; } if (type === 'PPYL') { brandMedical(ele, json); return; } if (type === 'SLW') { soulew(ele, json, 101); return; }; if (type === 'HX') { soulew(ele, json, 102); return; }; if (type === '258') { soulew(ele, json, 106); return; }; if (type === 'ZQ') { soulew(ele, json, 105); return; }; } }); }; var loadInit = function (options) { var defaults = { province: '', lenGood: 0, lenother: 0, commercialSource: '', qSourceType: '' }; var opts = $.extend(defaults, options); return opts; }; var loadData = function (options, cmJsonData) { if (options.commercialSource === 'COMMERCIAL_ZWZD' || options.qSourceType === 'COOPERATE_SOUTHNETWORK' || options.qSourceType === 'COOPERATE_HUASHENG' || options.qSourceType === 'COOPERATE_HUASHENG_QA') { return null; } var array = new Array(0); $.each(cmJsonData, function (index) { try { var val = cmJsonData[index]; var qTags = val.qTags; var mainTags = val.mainTags; var startTime = val.startTime; var endTime = val.endTime; var province = '不限'; var nprovince = '不限'; var city = '不限'; var ncity = '不限'; var isDeliveryArea = val.isDeliveryArea; var provinceCode = val.provinceCode; var cityCode = val.cityCode; if (!!val.city) { city = val.city; } if (!!val.ncity) { ncity = val.ncity; } if (!!val.province) { province = val.province; } if (!!val.nprovince) { nprovince = val.nprovince; } if (options.qCid === '79' || options.bCid === '147') { if (checkTime(options.nowTime, startTime, endTime) && checkTag(options.qTags, qTags, options.mainTags, hexToDec(mainTags))) { if (isDeliveryArea === 'Y') { array.push(val); } else if (!options.city) { array.push(val); } else if (checkProvinceCode(options.provinceCode, provinceCode) && checkCityCode(options.cityCode, cityCode)) { array.push(val); } else if (checkProvince(options.province, hexToDec(province), nprovince) && checkCity(options.city, hexToDec(city), ncity)) { array.push(val); } } } } catch (e) {} }); if (array.length === 0) { return null; } return array; }; var loadURLJS = function (ele, tags, params, sourceType, questionId, $thatParam, $thatLog, $tokenDiv, token) { var url = httpPath + '/mib/tag/'; var arry = tags.split(':'); var youlaiTag = ''; var runhaiTag = ''; var visitFlag = true; for (var i = 0; i < arry.length; i++) { youlaiTag = arry[i].replace('[', '').replace(']', ''); if (youlaiTag === '') { visitFlag = false; } runhaiTag = 'runhai' + youlaiTag; if (visitFlag) { break; } } try { var province = ''; // 省份 var provinceCode = ''; // 省份code var city = ''; // 城市 var cityCode = ''; // 城市code var paramsArry = params.split(':'); var qCid = paramsArry[6] || '79'; var bCid = paramsArry[7]; ipLoad(function (data) { province = data.province; provinceCode = data.provinceCode; city = data.city; cityCode = data.cityCode; var param = loadInit({ mainTags: paramsArry[5], province: province, provinceCode: provinceCode, qCid: qCid, bCid: bCid, city: city, cityCode: cityCode, lenGood: parseInt(paramsArry[0], 0), lenother: parseInt(paramsArry[1], 0), commercialSource: paramsArry[3], qSourceType: paramsArry[2], qTags: paramsArry[4], nowTime: getSysTime() }); if (visitFlag) { fetchJsonp(url + youlaiTag, { jsonpCallback: 'callback' }).then(function (res) { return res.json(); }).then(function (data) { var youlaiArray = loadData(param, data); fetchJsonp(url + runhaiTag, { jsonpCallback: 'callback' }).then(function (res) { return res.json(); }).then(function (datas) { var runhaiArray = loadData(param, datas); if (youlaiArray !== null && youlaiArray.length > 0) { for (var i = 0; i < youlaiArray.length; i++) { adPut(ele, youlaiArray[i]); } advLogInfo(ele, sourceType, 0); } if (runhaiArray !== null && runhaiArray.length > 0) { var $thatDiv = ele.querySelector('.baidu_label_div'); removeBaiduAd(ele); var runhaiData = runhaiArray[Math.floor(Math.random() * runhaiArray.length)]; runhaiPut(ele, runhaiData); advLogInfo(ele, 'COOPERATE_RUNHAI', 0); var ds = 'MIP_sSY1001医疗包月广告-下'; var baiduStr = {'type': 'load', 'data': ['_setPageTag', 'MIP_SY_1001', 'skip', ds]}; var baiduObj = '<div data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '" ></div>'; $thatDiv.innerHTML = baiduObj; } if ((runhaiArray === null || runhaiArray.length === 0) && (youlaiArray === null || youlaiArray.length === 0)) { loadEffect(ele, questionId, $thatParam, $thatLog, $tokenDiv, token); } else { loadStatsToken($tokenDiv, token); } }); }); } if (!visitFlag) { loadEffect(ele, questionId, $thatParam, $thatLog, $tokenDiv, token); // 加载效果广告 } }); } catch (e) { } }; // 加载效果广告 var loadEffect = function (ele, questionId, $thatParam, $thatLog, $tokenDiv, token) { if ($thatLog.length === 0) { var sourceType = 'COOPERATE_EFFECT'; $thatParam.setAttribute('sources', sourceType); // 商业效果广告 effectAvertisement(ele, questionId, sourceType, $tokenDiv, token); } }; // 润海广告 var runhaiPut = function (ele, data) { var $paramDiv = ele.querySelector('.paramDiv'); var json = data.adList; var adUserId = data.adUserId; var baiduStr = ''; var baiduObj = ''; for (var key in json) { if (json[key].type === '1') { // answerInfo feed 广告 var object = json[key]; var answerConNumber = parseInt($paramDiv.getAttribute('answerConNumber'), 0); var goodNum = parseInt($paramDiv.getAttribute('goodLen'), 0); var otherNum = parseInt($paramDiv.getAttribute('otherLen'), 0); var answerTotal = goodNum + otherNum; var numTotal = false; if ((answerTotal === 1 && answerConNumber !== 0 && answerConNumber < 170) || (answerTotal === 2 && answerConNumber !== 0 && answerConNumber < 160)) { numTotal = true; } var $that = ele.querySelectorAll('.critics-list'); baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_feed']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyFeed1($that, adUserId, object, numTotal, baiduObj, '1'); advLogInfoClick(ele, '.runhai_feed1 .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } else if (json[key].type === '2') { var object = json[key]; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_zx']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyZixun('.new-similar-dl', adUserId, object, baiduObj, '2'); advLogInfoClick(ele, '.runhai_zixun .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } else if (json[key].type === '4') { var object = json[key]; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_wzlz']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyWenzhil('.wait_answer_question', 'everyone_wenzhil1', adUserId, object, baiduObj, '4'); advLogInfoClick(ele, '.everyone_wenzhil1 .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } else if (json[key].type === '5') { var object = json[key]; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_feed2']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyFeed2('.hot-top', adUserId, object, baiduObj, '5'); advLogInfoClick(ele, '.runhaiFeed2 .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } else if (json[key].type === '3') { // 热门推荐 var obj = json[key]; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_qt']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyHotRecommend('.relative_kownlege', adUserId, obj, baiduObj, '3'); advLogInfoClick(ele, '.hot_recomd_div .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } else if (json[key].type === '6') { var object = json[key]; baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_1001', 'skip', 'MIP_SY_1001_wzly']}; baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; monthlyWenzhil('.everyone_notices_div', 'everyone_wenzhil2', adUserId, object, baiduObj, '6'); advLogInfoClick(ele, '.everyone_wenzhil2 .href_log', $paramDiv, 'COOPERATE_RUNHAI'); } } }; var monthlyHotRecommend = function (clazz, adUserId, object, baiduObj, pos) { var html = '<div class="hot-tui hot_recomd_div" >'; html += '<h3>热门推荐<span class="icon-bai"></span></h3>'; html += '<ul class="hot-tui-list href_log" uid="' + adUserId + '"'; html += ' href="' + object.picLink + '" ' + baiduObj + ' pos="' + pos + '">'; for (var i in object.adDetailList) { html += '<li><mip-img class="mip-img" src="' + object.adDetailList[i].picUrl + '">'; var describe = object.adDetailList[i].describe; html += '<p class="mip-img-subtitle">' + subStringIask(hexToDec(describe), 8) + '</p>'; html += '</mip-img></li>'; } html += ' </ul>'; html += '</div>'; $(clazz).after(html); }; var monthlyFeed1 = function ($that, adUserId, object, numTotal, baiduObj, pos) { var html = '<div class="m-yy-con runhai_feed1" >'; html += '<div class="href_log" uid="' + adUserId + '"'; html += ' href="' + object.picLink + '" pos="' + pos + '" ' + baiduObj + '>'; html += '<h2 class="m-yy-title">' + subStringIask(hexToDec(object.title), 24) + '</h2>'; if (!numTotal) { html += '<ul class="m-yy-list href_log" uid="' + adUserId + '"'; html += ' href="' + object.picLink + '" pos="' + object.type + '" ' + baiduObj + '>'; html += '<li><span class="feed-span"><mip-img src="' + object.picList[0] + '"'; html += ' class="mip-img"></mip-img></span></li>'; html += '<li><span class="feed-span"><mip-img src="' + object.picList[1] + '"'; html += ' class="mip-img"></mip-img></span></li>'; html += '<li><span class="feed-span"><mip-img src="' + object.picList[2] + '"'; html += ' class="mip-img"></mip-img></span></li>'; html += '</ul>'; } html += '<p class="m-yy-text">' + subStringIask(hexToDec(object.describe), 60) + '</p>'; html += '<div class="m-yy-info">'; html += '<div class="m-left">'; html += '<div class="m-user-img"><mip-img src="/static/images/w-v03/head_normal_50.png"'; html += ' class="mip-img"></mip-img></div>'; html += '<span class="m-user-name">' + subStringIask(hexToDec(object.companyName), 14) + '</span>'; html += '<span class="time">1小时前</span>'; html += '<span class="icon-tui">广告</span>'; html += '</div>'; html += '<span class="m-yy-link">查看详情</span>'; html += '</div></div></div>'; var index = $that.length - 1; if ($that.length > 0) { var newdiv = document.createElement('div'); newdiv.innerHTML = html; $that[index].parentNode.appendChild(newdiv); } }; var monthlyZixun = function (clazz, adUserId, object, baiduObj, pos) { var html = '<div class="m-doc-con runhai_zixun">'; html += '<i class="icon-feed-tui"></i>'; html += '<h2 class="m-doc-title">' + hexToDec(object.title) + '</h2>'; html += '<ul class="m-doc-list href_log" uid="' + adUserId + '"'; html += ' href=' + object.picLink + ' pos="' + pos + '" ' + baiduObj + '>'; for (var index in object.adDetailList) { var obj = object.adDetailList[index]; html += '<li><div class="doc-item"><div class="doc-pic">'; html += '<mip-img src="' + obj.picUrl + '" class="mip-img"></mip-img></div>'; html += '<p class="doc-name">' + hexToDec(obj.name) + '</p>'; html += '<p class="doc-text">' + hexToDec(obj.describe) + '</p>'; html += '<span class="btn-doc" >向TA提问</span></div></li>'; } html += '</ul>'; html += '</div>'; $(clazz).after(html); }; var monthlyFeed2 = function (clazz, adUserId, object, baiduObj, pos) { var html = '<div class="m-focus-tui-con runhaiFeed2" >'; html += '<ul class="m-focus-tui-list href_log" href="' + object.picLink + '"'; html += ' uid="' + adUserId + '" pos="' + pos + '" ' + baiduObj + '>'; for (var index in object.adDetailList) { var obj = object.adDetailList[index]; html += '<li><div class="pic-con">'; html += '<mip-img src="' + obj.picUrl + '" class="mip-img"></mip-img></div>'; html += '<div class="text-con"><p class="text">' + hexToDec(obj.describe) + '</p>'; html += '<span class="view-more">查看详情</span></div><i class="icon-feed-tui"></i></li>'; } html += '</ul>'; html += '</div>'; $(clazz).after(html); }; var monthlyWenzhil = function (clazz, clickClass, adUserId, object, baiduObj, pos) { var html = '<ul class="m-word-tui ' + clickClass + ' ">'; for (var index in object.adDetailList) { var obj = object.adDetailList[index]; html += '<li class="href_log" uid="' + adUserId + '" href="' + object.adDetailList[0].picLink + '"'; html += 'pos="' + pos + '"' + baiduObj + '>' + hexToDec(obj.describe) + '<i'; html += ' class="icon-feed-tui"></i></li>'; } html += '</ul>'; $(clazz).after(html); }; var adPut = function (ele, val) { if (val === undefined) { return; } var adPosition = val.adPosition; var arry = adPosition.split(','); for (var i = 0; i < arry.length; i++) { callMethod(ele, arry[i], val); } }; var callMethod = function (ele, tp, val) { try { if (tp === '1') { put1(ele, val); } else if (tp === '2') { put2(ele, val); } else if (tp === '5') { put3(ele, val); } } catch (e) {} }; var put1 = function (ele, val) { var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_202', 'skip', 'MIP_SY_202_qy1']}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; putQiyeInfo(ele, hexToDec(val.hospitalName), hexToDec(val.contacts), val.url, val.logo, baiduObj, '1'); }; var put2 = function (ele, val) { var baiduStr = {type: 'click', data: ['_trackEvent', 'skip', 'MIP_SY_202_qy2']}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; putQiyeInfo(ele, hexToDec(val.hospitalName), hexToDec(val.contacts), val.url, val.logo, baiduObj, '2'); }; var put3 = function (ele, val) { var baiduStr = {type: 'click', data: ['_trackEvent', 'skip', 'MIP_SY_202_wzl']}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; console.log(val); var strArr = val.introductions.split('|'); var html = '<ul class="m-word-tui youlaibyclick">'; for (var index in strArr) { var wzl = strArr[index]; html += '<li class="href_log" uid="' + val.adUserId + '" href="' + val.mUrl + '"'; html += 'pos="4"' + baiduObj + '>' + hexToDec(wzl) + '<i'; html += ' class="icon-feed-tui"></i></li>'; } html += '</ul>'; $('.new-similar-dl').after(html); advLogInfoClick(ele, '.youlaibyclick .href_log', ele.querySelector('.paramDiv')); }; var checkTime = function (nowTime, startTime, endTime) { if (startTime <= nowTime && nowTime < endTime) { return true; } return false; }; var checkCity = function (city, putCity, nCity) { if (nCity.indexOf(city) !== -1) { return false; } if (putCity === '不限' || putCity === '') { return true; } var arrays = putCity.split(','); for (var i = 0; i < arrays.length; i++) { var arr = arrays[i]; var arrsub = arr.substring(arr.length - 1, arr.length); if (arrsub === '州' || arrsub === '县') { arr = arr.substring(0, arr.length - 1); } if (city.indexOf(arr) !== -1) { return true; } } return putCity.indexOf(city) > -1 ? true : false; }; var checkProvince = function (province, putProvince, nprovince) { if (nprovince.indexOf(province) !== -1 && nprovince !== '不限') { return false; } if (putProvince === '不限') { return true; } if (putProvince.indexOf(province) !== -1) { return true; } return false; }; var checkProvinceCode = function (provinceCode, putProvinceCode) { if (provinceCode === '' || putProvinceCode === '') { return false; } return putProvinceCode.indexOf(provinceCode) > -1 ? true : false; }; var checkCityCode = function (cityCode, putCityCode) { if (cityCode === '' || putCityCode === '') { return false; } return putCityCode.indexOf(cityCode) > -1 ? true : false; }; var checkTag = function (tag, putTag, mainTags, putMainTags) { if (!!putTag) { var arr = putTag.split(','); for (var i = 0; i < arr.length; i++) { if (tag.indexOf(arr[i]) !== -1) { return true; } } } if (!!putMainTags) { var arr = putMainTags.split(','); for (var i = 0; i < arr.length; i++) { if (mainTags.indexOf(arr[i]) !== -1) { return true; } } } return false; }; var fRandomBy = function (under, over) { switch (arguments.length) { case 1 : return parseInt((Math.random() * under + 1), 0); case 2: return parseInt((Math.random() * (over - under + 1) + under), 0); default: return 0; } }; // 广告 var currencyAM = function (ele, sourceType, openId, questionId, version) { loadAd(ele, sourceType, openId, questionId, version); advLogInfo(ele, sourceType, 0); }; // 南方网通 var southnetwork = function (ele, openId) { var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; var type = 'SOUTH'; var version = ele.querySelector('.paramDiv').getAttribute('version'); var channel = version === '4' ? '104' : '100'; var sourceType = version === '4' ? 'COOPERATE_SOUTHNETWORK_4' : 'COOPERATE_SOUTHNETWORK'; try { var url = httpPath + '/t/wlsh?openCorporationId=' + openId + '&type=' + type; $.get(url, function (data) { var base = new Base64(); var res = $.parseJSON(data); if (res.succ === 'Y') { var json = $.parseJSON(base.decode(res.html)); for (var i in json.adList) { var material = json.adList[i]; var ds = ''; if (material.materialType === '5') { ds = 'MIP_SY_' + channel + '_tpgg'; var bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + channel, 'skip', ds]}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; var nodeClass = isExistsNode(); $(nodeClass).append(centralBanner(material.picLink, material.picUrl, baiduObj, '3')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), sourceType); } else if (material.type === '3') { ds = 'MIP_SY_' + channel + '_qyxx'; var bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + channel, 'skip', ds]}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; putQiyeInfo(ele, material.companyName, material.descb, json.website, material.picUrl, baiduObj, '1', sourceType); } else if (material.type === '8') { ds = 'MIP_SY_' + channel + '_qtgg'; var bStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_' + channel, 'skip', ds]}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(bStr) + '"'; var str = ''; for (var index in material.adDetailList) { var picLink = material.picLink; var picUrl = material.adDetailList[index].picUrl; var picDesc = material.adDetailList[index].describe; str += hotRecommend(picLink, picUrl, picDesc, baiduObj, '2'); } $('.critics').after(hotRecommendDiv(str)); advLogInfoClick(ele, '.hot-tui-list .href_log', ele.querySelector('.paramDiv'), sourceType); } } advLogInfo(ele, sourceType, 0); loadStatsToken($tokenDiv, token); } }); } catch (e) {} }; var yunwangke = function (ele, openId, questionId, version) { var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; var url = httpPath + '/t/wlsh?openCorporationId=' + openId; url += '&type=YWK&questionId=' + questionId + '&version=' + version; $.get(url, function (data) { var base = new Base64(); var res = $.parseJSON(data); if (res.succ === 'Y') { var json = $.parseJSON(base.decode(res.html)); var basedata = json.adList; var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_103', 'skip', 'MIP_SY_103_ywk']}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; for (var key in basedata) { var obj = basedata[key]; if (obj.type === '1' && obj.materialType === '5') { var nodeClass = isExistsNode(); $(nodeClass).append(centralBanner(obj.picLink, obj.picUrl, baiduObj, '')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv')); } else if (obj.type === '3') { var website = json.website; var companyName = obj.companyName; var drName = obj.descb; putQiyeInfo(ele, companyName, drName, website, obj.picUrl, baiduObj, ''); } else if (obj.type === '8') { var str = ''; var picList = obj.adDetailList; var picLink = obj.picLink; for (var i = 0; i < picList.length; i++) { var pic = picList[i].picUrl; var picDesc = picList[i].describe; str += hotRecommend(picLink, pic, picDesc, baiduObj, ''); } $('.critics').after(hotRecommendDiv(str)); advLogInfoClick(ele, '.hot-tui-list .href_log', ele.querySelector('.paramDiv')); } } advLogInfo(ele, 'COOPERATE_YUNWANG', 0); loadStatsToken($tokenDiv, token); removeBaiduAd(ele); } }); }; var getmainCategoryPics = function (ele) { var list = {}; var $that = ele.querySelectorAll('.mianCategoryPics li'); if ($that.length > 0) { for (var i = 0; i < $that.length; i ++) { var cid = $that[i].getAttribute('cid'); var val = $that[i].getAttribute('val'); var picArr = val.split(','); list[cid] = picArr; } } return list; }; var loadMImagesrc = function (picsArr, cid) { var list = picsArr[cid]; if (undefined === list) { list = picsArr['0000']; } var cur = fRandomBy(0, list.length - 1); var pic = list[cur]; return pic; }; var getFlowEmbed = function (ele, classFlag, tp) { var $that = ele.querySelectorAll('.flow-info-params li'); var htmls = ''; if ($that.length > 0) { for (var i = 0; i < $that.length; i ++) { var clazz = $that[i].getAttribute('class'); var domainBd = $that[i].getAttribute('domain'); var tokenBd = $that[i].getAttribute('token'); var index = $that[i].getAttribute('tp'); if (classFlag.indexOf(clazz) > -1 && tp === index) { htmls = '<mip-embed type="baidu-wm-ext" domain="' + domainBd + '"'; htmls += ' token="' + tokenBd + '" ><div id="' + tokenBd + '"></div></mip-embed>'; break; } } } return htmls; }; var addFlowEmbed = function (ele, clazz) { var $that = ele.querySelectorAll(clazz); if ($that.length > 0) { for (var i = 0; i < $that.length; i++) { var c = $that[i].getAttribute('class'); var tp = $that[i].getAttribute('tq'); if (c.indexOf('hide') > -1) { continue; } if ($that[i].innerHTML !== '') { continue; } $that[i].innerHTML = getFlowEmbed(ele, c, tp); } } }; var infoFlow = function (ele) { try { var $that = ele.querySelector('.info-flow-json-data'); if ($that !== null) { removeInfo(ele); $('.info-flow-json-data').removeClass('hide').addClass('show'); } else { return; } var picsArr = getmainCategoryPics(ele); var $that = ele.querySelectorAll('.issues-list .category-img'); if ($that.length > 0) { for (var i = 0; i < $that.length; i++) { var cid = $that[i].getAttribute('cid'); var pic = loadMImagesrc(picsArr, cid); var img = '<mip-img class="mip-img"'; img += ' src="http://pic.iask.cn/fimg/' + pic + '_560.jpg" ></mip-img>'; $that[i].innerHTML = img; picsArr = removeArray(ele, picsArr, cid, pic); } } addFlowEmbed(ele, '.issues-item .xgzs-info-flow'); addFlowEmbed(ele, '.issues-item .bd-info-flow'); } catch (e) { } }; var removeArray = function (ele, picsArr, cid, val) { var list = picsArr[cid]; if (undefined === list) { list = picsArr['0000']; } for (var i = 0; i < list.length; i++) { if (list[i] === val) { list.splice(i, 1); } } if (list.length === 0) { list = picsArr['0000']; if (list.length === 0) { return getmainCategoryPics(ele); } } picsArr[cid] = list; return picsArr; }; var issuesChange = function (clazz) { $(clazz).click(function () { var $notices = $('.relationRecommend'); $notices.find('li.show').removeClass('show').addClass('hide').appendTo($notices); var i = 0; $notices.find('li.hide').each(function () { if (i === 6) { return; } i ++; $(this).removeClass('hide').addClass('show'); }); addFlowEmbed(document, '.issues-item .xgzs-info-flow'); }); }; // 商业效果广告 var effectAvertisement = function (ele, questionId, sourceType, $tokenDiv, token) { ipLoad(function (data) { var provinceCode = data.provinceCode; var url = httpPath + '/mib/tag/test?q=' + questionId + '&c=' + provinceCode; try { $.getJSON(url, function (res) { if (res.jsonData != null) { advEffectCallBack(ele, res.jsonData); advLogInfo(ele, sourceType, 0); loadStatsToken($tokenDiv, token); } else { advLogInfo(ele, '', 0); // 信息流图片 infoFlow(ele); } }); } catch (e) { } }); }; var advEffectCallBack = function (ele, materiel) { var $that = ele.querySelector('.paramDiv'); var $thatDiv = ele.querySelector('.baidu_label_div'); var list = materiel.materialList; var version = materiel.version; var channelCode = materiel.channelCode; $that.setAttribute('uid', materiel.userId); if ('2' !== version) { // 如果不是标准版,则删除百度广告 removeBaiduAd(ele); } for (var i = 0; i < list.length; i++) { var obj = list[i]; if (version === '1') { showEffectAdv(ele, obj, 1, channelCode); } else if (version === '2') { showEffectAdv(ele, obj, 2, channelCode); } else { showEffectAdv(ele, obj, 3, channelCode); } } var baiduStr = {'type': 'load', 'data': ['_setPageTag', 'MIP_SY_700', 'skip', 'MIP_SY_效果广告']}; var baiduObj = '<div data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '" ></div>'; $thatDiv.innerHTML = baiduObj; }; var showEffectAdv = function (ele, json, tp, channelCode) { var $thatParam = ele.querySelector('.paramDiv'); if (json.adType === '3') { var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_700', 'skip', 'MIP_SY_700_qyxx']}; var baiduObj = 'data-stats-baidu-obj="' + encodeURIStr(baiduStr) + '"'; var brandLink = ''; var uid = $thatParam.getAttribute('uid'); if ('10002' === channelCode) { brandLink = json.materialLink; // 南方网通效果广告-链接跳转自己的物料链接 } else { brandLink = httpPath + '/brand/' + uid + '.html'; } putBrandQiyeInfo(ele, json.brandName, json.shortIntroduce, json.materialLink, json.materialImg, baiduObj, '3', brandLink); return; } if (json.adType === '2') { return; } // 旗舰版feed if (json.adType === '5') { var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_700', 'skip', 'MIP_SY_700_feed']}; var materialImg = json.materialImg; var picList = materialImg.split(','); var picUrl = 'http://tp2.sinaimg.cn/1169181841/50/0/1'; feedInfo(ele, encodeURIStr(baiduStr), picUrl, json.brandName, json.shortIntroduce, json.materialIntroduce, json.materialLink, picList, '2'); return; } if (json.adType === '1' && json.materialType === '5') { var baiduStr = {type: 'click', data: ['_trackEvent', 'MIP_SY_700', 'skip', 'MIP_SY_700_tpgg']}; var nodeClass = isExistsNode(); $(nodeClass).append(centralBanner(json.materialLink, json.materialImg, encodeURIStr(baiduStr), '3')); advLogInfoClick(ele, nodeClass + ' .href_log', ele.querySelector('.paramDiv'), ''); } }; var brandAvertisement = function (ele, sourceType, $tokenDiv, token) { advLogInfo(ele, sourceType, 0); advLogInfoClick(ele, '.href_log', ele.querySelector('.paramDiv')); loadStatsToken($tokenDiv, token); }; var checkData2017 = function (postDate) { var d1 = new Date(postDate); var d2 = new Date('2017-11-01 00:00:00'); if (d1.getFullYear() < d2.getFullYear()) { return 3; } if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() < d2.getMonth()) { return 3; } if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() <= d2.getDate()) { return 3; } return 1; }; var checkDate = function (thetime) { var d1 = new Date(thetime); var d2 = new Date(); if (d1.getFullYear() < d2.getFullYear()) { return false; } if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() < d2.getMonth()) { return false; } if (d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth() && d1.getDate() < d2.getDate()) { return false; } return true; }; var addDateYear = function (time, num) { var d1 = new Date(time); var d2 = new Date(d1); d2.setFullYear(d2.getFullYear() + num); d2.setDate(d2.getDate() - 1); return d2; }; // 选择投放广告 var selectAS = function () { // 因为参数都定义在了组件外部,所以需要使用全局选择器 var ele = this.document; var $thatParam = ele.querySelector('.paramDiv'); var $thatHover = ele.querySelector('.commercialStandardHover'); var $thatQiye = ele.querySelector('.commercialStandard_qiye_cp'); var sourceType = $thatParam.getAttribute('sources'); var sources = $thatParam.getAttribute('sysources') == null ? sourceType : $thatParam.getAttribute('sysources'); var version1 = $thatParam.getAttribute('version'); var version2 = $thatParam.getAttribute('syversion'); var version = $thatParam.getAttribute('syversion') == null ? version1 : version2; var openId = $thatParam.getAttribute('openId'); var tags = $thatParam.getAttribute('tags'); var params = $thatParam.getAttribute('params'); var mainTags = $thatParam.getAttribute('maintags'); var questionId = $thatParam.getAttribute('qid'); var qcid = $thatParam.getAttribute('qcid'); var postDate = $thatParam.getAttribute('postDate'); var $tokenDiv = ele.querySelector('.mip-stats-token-div'); var token = ele.querySelector('.mip-token-value').innerHTML; if (sources === 'COMMERCIAL_IAD' || sources === 'COMMERCIAL_ZWZD' || sources === 'COMMERCIAL_CAD') { // 商业广告 removeBaiduAd(ele); busBottomAM(ele, $tokenDiv, token); if (sources === 'COMMERCIAL_ZWZD') { sources = 'COOPERATE_COMMERCIAL'; } advLogInfo(ele, sources, 0); } else if ((sources === 'COOPERATE_BRAND' || sources === 'COOPERATE_BRAND_MARKET') && (version === '1' || version === '3')) { // 商业广告-旗舰版、专业版本 brandAvertisement(ele, sources, $tokenDiv, token); } else if (sourceType === 'COOPERATE_BRAND' && version === '2') { // 商业广告-标准版 $thatParam.setAttribute('sources', 'COOPERATE_BRAND'); commercialSqc(ele, $thatQiye, $thatHover); advLogInfo(ele, 'COOPERATE_BRAND', 0); advLogInfoClick(ele, '.mip_as_bottm_div .href_log', ele.querySelector('.paramDiv')); loadStatsToken($tokenDiv, token); } else if (sourceType === 'COOPERATE_HUASHENG' || sourceType === 'COOPERATE_HUASHENG_QA' || sourceType === 'COOPERATE_YOULAI' || sourceType === 'COOPERATE_TIANZHU' || sourceType === 'COOPERATE_BRAND_MARKET' || sourceType === 'COOPERATE_258JT' || sourceType === 'COOPERATE_ZHONGQI' || sourceType === 'COOPERATE_SOULE' || sourceType === 'COOPERATE_HUAXIN') { // 第三方合作广告 if (sourceType === 'COOPERATE_YOULAI' || sourceType === 'COOPERATE_TIANZHU' || sourceType === 'COOPERATE_SOULE' || sourceType === 'COOPERATE_HUAXIN' || sourceType === 'COOPERATE_ZHONGQI' || sourceType === 'COOPERATE_258JT' || (sourceType === 'COOPERATE_BRAND_MARKET' && version === '4')) { // 需要删除百度广告 removeBaiduAd(ele); } currencyAM(ele, sourceType, openId, questionId, version); } else if (sourceType === 'COOPERATE_SOUTHNETWORK' && checkDate(addDateYear(postDate, checkData2017(postDate)))) { // 南方网通广告 southnetwork(ele, openId); removeBaiduAd(ele); } else if (sourceType === 'COOPERATE_YUNWANG') { // 云网客广告 yunwangke(ele, openId, questionId, version); removeBaiduAd(ele); } else if (sourceType !== 'COOPERATE_HUASHENG' && sourceType !== 'COOPERATE_HUASHENG_QA') { var $thatLog = ele.querySelectorAll('.href_log'); if (tags) { sourceType = 'COOPERATE_HUASHENG_BY'; $thatParam.setAttribute('sources', sourceType); loadURLJS(ele, tags, params, sourceType, questionId, $thatParam, $thatLog, $tokenDiv, token); } } }; var effects = { newLoadAd: function () { selectAS(); }, init: function () { this.newLoadAd(); } }; // build 方法,元素插入到文档时执行,仅会执行一次 customElem.prototype.build = function () { effects.init(); }; return customElem; });
'use strict'; var assert = require("assert"); var hypersort = require('../src/hypersort').hypersort; var gsUtils = require('./gsUtils').gsUtils; // FixMe: Not sure why the .peopleMaker is needed var peopleMaker = require('./testUtils').peopleMaker; // FixMe: Not sure why the .peopleMaker is needed describe('Testing Sorts', function() { var makeDataSets = function(n) { console.log('Making Datasets, n= ' + n); var timer = gsUtils.newTimer(); var dataSets = [{ name: 'Random set of small set of values (8)', // midwayPrint: timer.log(' Making DataSet: MV'), data: peopleMaker.makePeople(n), // finalPrint: timer.log(' Finished DataSet: MV'), }, { name: 'Two Values all larger then smaller', // midwayPrint: timer.log(' Making DataSet: 2V'), data: peopleMaker.makeTwoValuedPeople(n), // finalPrint: timer.log(' Finished DataSet: 2V'), }, { name: 'All Values Distinct and random', // midwayPrint: timer.log(' Making DataSet: Random'), data: peopleMaker.makeDistinctValuedPeople(n), // finalPrint: timer.log(' Finished DataSet: Random'), }]; return dataSets; }; var sortTypes = hypersort.getSortTypes(); var copy = function(from, to) { if (from.length != to.length) { to = new Array(from.length); } for (var i = 0; i < from.length; i++) { to[i] = from[i]; } return to; }; var workingData = []; // Used to store a copy of the unsorted dataset for testing. var dump = function(data) { console.log('-------------------'); for (var i = 0; i < data.length; i++) { console.log(i + ': ' + data[i]); } }; var tlog = function(message) { console.log('\t' + message); }; var performTest = function(sort, dataSet, colName) { it(dataSet.name, function() { workingData = copy(dataSet.data, workingData); // assert.equals(peopleMaker.validate(data, colName, sort.isStable), true); // assert.equals('foo', 'foo'); var timer = gsUtils.newTimer(); sort.sortFunction(workingData, colName); var valid = peopleMaker.validate(workingData, colName, sort.isStable); // var resultMessage = timer.getDuration() + ' ms spent ' + message; // console.log('sorted'); // for (i = 0; i < data.length; i++) { // console.log(i + ': ' + data[i]); // } tlog((valid ? 'PASS ' : 'FAIL ') + timer.getDuration() + ' ms spent completing the following:'); assert.equal(valid, true); }); }; var testSortOnAllDataSets = function(sort, dataSets, colName) { var title = sort.name + ': Expecting result to ' + (sort.isStable ? '' : 'NOT') + ' be stable'; describe(title, function() { for (var i = 0; i < dataSets.length; i++) { performTest(sort, dataSets[i], colName); } }); }; var testSuite = function(sortTypes, dataSets, colName, subtype) { if (subtype === 'absoluteValue') { describe('Absolute Value Test', function() { it('NOT IMPLEMENTED', function() { }); }); return; } describe('Run full Test Suite on col = "' + colName + '", n = ' + n, function() { // var dataSets = makeDataSets(n); for (var i = 0; i < sortTypes.length; i++) { var sort = sortTypes[i]; testSortOnAllDataSets(sort, dataSets, colName); } }); }; var n = 100; var dataSets = makeDataSets(n); testSuite(sortTypes, dataSets, 'textValue'); testSuite(sortTypes, dataSets, 'numericValue'); testSuite(sortTypes, dataSets, 'dateValue'); testSuite(sortTypes, dataSets, 'numericValue', 'absoluteValue'); });
import React from 'react' import codegen from 'codegen.macro' import {isPreact} from './constants' let PropTypes /* istanbul ignore next */ if (isPreact) { if (!React.PropTypes) { PropTypes = () => PropTypes const allTypes = [ 'array', 'bool', 'func', 'number', 'object', 'string', 'symbol', 'any', 'arrayOf', 'element', 'instanceOf', 'node', 'objectOf', 'oneOf', 'oneOfType', 'shape', 'exact', ] allTypes.forEach(type => { PropTypes[type] = PropTypes }) } // copied from preact-compat /* eslint-disable no-eq-null, eqeqeq, consistent-return */ if (!React.Children) { const Children = { map(children, fn, ctx) { if (children == null) { return null } children = Children.toArray(children) if (ctx && ctx !== children) { fn = fn.bind(ctx) } return children.map(fn) }, forEach(children, fn, ctx) { if (children == null) { return null } children = Children.toArray(children) if (ctx && ctx !== children) { fn = fn.bind(ctx) } children.forEach(fn) }, count(children) { return (children && children.length) || 0 }, only(children) { children = Children.toArray(children) if (children.length !== 1) { throw new Error('Children.only() expects only one child.') } return children[0] }, toArray(children) { if (children == null) { return [] } return [].concat(children) }, } React.Children = Children } /* eslint-enable no-eq-null, eqeqeq, consistent-return */ } else if (parseFloat(React.version.slice(0, 4)) >= 15.5) { /* istanbul ignore next */ try { PropTypes = codegen` if (process.env.BUILD_FORMAT === 'umd') { module.exports = "(typeof window !== 'undefined' ? window : global).PropTypes" } else { module.exports = "require('prop-types')" } ` /* istanbul ignore next */ } catch (error) { // ignore } } /* istanbul ignore next */ PropTypes = PropTypes || React.PropTypes export {PropTypes} /* eslint import/no-mutable-exports:0, import/prefer-default-export:0, react/no-deprecated:0 */
import hash from 'string-hash' import { join, basename } from 'path' import babelLoader from 'babel-loader' // increment 'd' to invalidate cache const cacheKey = 'babel-cache-' + 'd' + '-' const nextBabelPreset = require('../../babel/preset') const getModernOptions = (babelOptions = {}) => { const presetEnvOptions = Object.assign({}, babelOptions['preset-env']) const transformRuntimeOptions = Object.assign( {}, babelOptions['transform-runtime'], { regenerator: false } ) presetEnvOptions.targets = { esmodules: true } presetEnvOptions.exclude = [ ...(presetEnvOptions.exclude || []), // Blacklist accidental inclusions 'transform-regenerator', 'transform-async-to-generator' ] return { ...babelOptions, 'preset-env': presetEnvOptions, 'transform-runtime': transformRuntimeOptions } } const nextBabelPresetModern = presetOptions => context => nextBabelPreset(context, getModernOptions(presetOptions)) module.exports = babelLoader.custom(babel => { const presetItem = babel.createConfigItem(nextBabelPreset, { type: 'preset' }) const applyCommonJs = babel.createConfigItem( require('../../babel/plugins/commonjs'), { type: 'plugin' } ) const commonJsItem = babel.createConfigItem( require('@babel/plugin-transform-modules-commonjs'), { type: 'plugin' } ) const configs = new Set() return { customOptions (opts) { const custom = { isServer: opts.isServer, isModern: opts.isModern, pagesDir: opts.pagesDir, hasModern: opts.hasModern } const filename = join(opts.cwd, 'noop.js') const loader = Object.assign( opts.cache ? { cacheCompression: false, cacheDirectory: join(opts.distDir, 'cache', 'next-babel-loader'), cacheIdentifier: cacheKey + (opts.isServer ? '-server' : '') + (opts.isModern ? '-modern' : '') + (opts.hasModern ? '-has-modern' : '') + JSON.stringify( babel.loadPartialConfig({ filename, cwd: opts.cwd, sourceFileName: filename }).options ) } : { cacheDirectory: false }, opts ) delete loader.isServer delete loader.cache delete loader.distDir delete loader.isModern delete loader.hasModern delete loader.pagesDir return { loader, custom } }, config ( cfg, { source, customOptions: { isServer, isModern, hasModern, pagesDir } } ) { const filename = this.resourcePath const options = Object.assign({}, cfg.options) const isPageFile = filename.startsWith(pagesDir) if (cfg.hasFilesystemConfig()) { for (const file of [cfg.babelrc, cfg.config]) { // We only log for client compilation otherwise there will be double output if (file && !isServer && !configs.has(file)) { configs.add(file) console.log(`> Using external babel configuration`) console.log(`> Location: "${file}"`) } } } else { // Add our default preset if the no "babelrc" found. options.presets = [...options.presets, presetItem] } options.caller.isServer = isServer options.caller.isModern = isModern options.plugins = options.plugins || [] if (!isServer && isPageFile) { const pageConfigPlugin = babel.createConfigItem( [require('../../babel/plugins/next-page-config')], { type: 'plugin' } ) options.plugins.push(pageConfigPlugin) } if (isServer && source.indexOf('next/data') !== -1) { const nextDataPlugin = babel.createConfigItem( [ require('../../babel/plugins/next-data'), { key: basename(filename) + '-' + hash(filename) } ], { type: 'plugin' } ) options.plugins.push(nextDataPlugin) } if (isModern) { const nextPreset = options.presets.find( preset => preset && preset.value === nextBabelPreset ) || { options: {} } const additionalPresets = options.presets.filter( preset => preset !== nextPreset ) const presetItemModern = babel.createConfigItem( nextBabelPresetModern(nextPreset.options), { type: 'preset' } ) options.presets = [...additionalPresets, presetItemModern] } // If the file has `module.exports` we have to transpile commonjs because Babel adds `import` statements // That break webpack, since webpack doesn't support combining commonjs and esmodules if (!hasModern && source.indexOf('module.exports') !== -1) { options.plugins.push(applyCommonJs) } options.plugins.push([ require.resolve('babel-plugin-transform-define'), { 'typeof window': isServer ? 'undefined' : 'object' }, 'next-js-transform-define-instance' ]) // As next-server/lib has stateful modules we have to transpile commonjs options.overrides = [ ...(options.overrides || []), { test: [ /next[\\/]dist[\\/]next-server[\\/]lib/, /next[\\/]dist[\\/]client/, /next[\\/]dist[\\/]pages/ ], plugins: [commonJsItem] } ] return options } } })
/** * Created by Administrator on 2017/4/29. */ var comName = GetQueryString("comName"); $("#entry_unit").click(function () { var comName = GetQueryString("comName"); // alert(comName); var entryType = "UNIT" var workState = "KEEP" var state = "1" var condition = { comName:comName, entryType:entryType, workState:workState, state:state } addEntireUnit(condition) }); var addEntireUnit = function (condition) { // alert(condition) $.ajax({ url: "/entire/addEntire", type: 'POST', async: true, data: condition, dataType: 'json', error: function (obj, msg) { alert("服务器异常!") }, success: function (result) { if (result != null) { // alert(result); // alert(comName) window.location.href = "/unitCreate?entireId=" + result+"&comName="+comName; // comId = result; } } }); } $("#entry_team").click(function () { var comName = GetQueryString("comName"); // alert(comName); var entryType = "TEAM" var workState = "KEEP" var state = "1" var condition = { comName:comName, entryType:entryType, workState:workState, state:state } addEntireTeam(condition) }); var addEntireTeam = function (condition) { // alert(condition) $.ajax({ url: "/entire/addEntire", type: 'POST', async: true, data: condition, dataType: 'json', error: function (obj, msg) { alert("服务器异常!") }, success: function (result) { if (result != null) { // alert(result); // location.href = 'a.asp?d_id=' + d + '&d_name=' + name; window.location.href = "/teamCreate?entireId=" + result+"&comName="+comName; // comId = result; } } }); }
//비동기 데이터 수신 등에 사용 function RequestData (ctx) { } RequestData.prototype.readKey = function (keys, callback) { this.readKeyRoutine(typeof keys == "string" ? [keys] : keys, callback); } RequestData.prototype.getValue = function (key, defaultValue) { } RequestData.prototype.readKeyRoutine = function (keys, callback) { callback(); } module.exports = RequestData;
describe('Utilities and RNG', function () { var number; describe('standard rng', function () { beforeEach(function () { // Loops in tests... don't judge me. }); it('should create a number', function () { expect(randomNumberGenerator()).toEqual(jasmine.any(Number)); }); it('in range should create a number', function () { expect(randomNumberGeneratorInRange()).toEqual(jasmine.any(Number)); }); it('in range should create a number less than max and more than min', function () { expect(randomNumberGeneratorInRange(0, 100)).toEqual(jasmine.any(Number)); }); it('in range should create a number less than max and more than min', function () { for (let i = 0; i < 1000; i++ ) { let number = randomNumberGeneratorInRange(50, 100); expect(number).toBeLessThan(101); expect(number).toBeGreaterThan(49); number = randomNumberGeneratorInRange(20, 25); expect(number).toBeLessThan(26); expect(number).toBeGreaterThan(19); } }); it('in sequence should create a number with min and max jumps', function () { for (let i = 0; i < 1000; i++ ) { let seed = 5; let number = randomNumberGeneratorInSequence(1, 50, seed); expect(number).toBeLessThan(56); expect(number).toBeGreaterThan(5); number = randomNumberGeneratorInSequence(1, 50, number); expect(number).toBeLessThan(106); expect(number).toBeGreaterThan(6); number = randomNumberGeneratorInSequence(1, 50, number); expect(number).toBeLessThan(156); expect(number).toBeGreaterThan(7); } }); }); });
var EasyAssess = require('../easyassess.application'); EasyAssess.app.IqcClosedFormController = function($scope,$state,$stateParams) { this.initialize.apply(this, arguments); }; EasyAssess.app.IqcClosedFormController .prototype = EasyAssess.extend({ _initialize: function($scope,$state,$stateParams) { formAll = $stateParams.result; $scope.form = { values: formAll['values'], codes:formAll['codes'], formName:formAll['formName'] }; $scope.template = formAll.plan.template; } }, EasyAssess.app.MaintenanceController.prototype); EasyAssess.app.registerController("closed_iqcformController", EasyAssess.app.IqcClosedFormController);
/* * Copyright (c) 2017, Feedeo AB <hugo@feedeo.io>. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ describe('Server', () => { let subject let serverful before(() => { serverful = td.object([]) serverful.Serverful = td.constructor([]) }) describe('when exporting', () => { beforeEach(() => { td.replace('serverful', serverful) subject = require('../src/server') }) it('should be instance of serverful', () => { subject.should.be.instanceOf(serverful.Serverful) }) }) })
TestCase("Croaker.MappingAdvancedParses.Tests", { testParseWithoutMembers: function() { var mapper = new croaker.Mapper(), module = mapper.map(this.entryNoMembers); assertThat(module.namespaces[0].types[0].members, empty()); assertThat(module.namespaces[0].types[0].members.length, 0); }, testParseWithMultipleNamespaces: function() { var mapper = new croaker.Mapper(), module = mapper.map(this.entryMultipleNS); assertThat(module.namespaces[0].name, 'Sample.Core' ); assertThat(module.namespaces[1].name, 'Other.Core' ); assertThat(module.namespaces[1].metrics[0].value, 11 ); }, testParseWithMultipleTypes: function() { var mapper = new croaker.Mapper(), module = mapper.map(this.entryMultipleTypes); assertThat(module.namespaces[0].types[0].name, 'SampleType.Core' ); assertThat(module.namespaces[0].types[0].metrics[1].value, 498 ); assertThat(module.namespaces[0].types[1].metrics[2].value, 7 ); }, testParseWithMultipleMembers: function() { var mapper = new croaker.Mapper(), module = mapper.map(this.entryMultipleTypes); assertThat(module.namespaces[1].types[0].members[1].name, 'weard.Core' ); assertThat(module.namespaces[1].types[0].members[0].metrics[1].value, 98 ); assertThat(module.namespaces[1].types[0].members[1].metrics[2].value, 193 ); }, setUp: function () { JsHamcrest.Integration.JsTestDriver(); this.entryNoMembers = new croaker.NodeEntry('CodeMetricsReport', {}, [ new croaker.NodeEntry('Targets', {}, [ new croaker.NodeEntry('Target', {}, [ new croaker.NodeEntry('Modules', {}, [ new croaker.NodeEntry('Module', {Name:'Some.dll', AssemblyVersion:'1.0.2.3'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'1'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'4'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'5'}, []) ]), new croaker.NodeEntry('NameSpaces', {}, [ new croaker.NodeEntry('Namespace', {Name:'Sample.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'10'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'40'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'50'}, []) ]), new croaker.NodeEntry('Types', {}, [ new croaker.NodeEntry('Type', {Name: 'SampleType.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'Mantain', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'42'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'7'}, []) ]), new croaker.NodeEntry('Members', {}, [ ]) ]) ]) ]) ]) ]) ]) ]) ]) ]); this.entryMultipleNS = new croaker.NodeEntry('CodeMetricsReport', {}, [ new croaker.NodeEntry('Targets', {}, [ new croaker.NodeEntry('Target', {}, [ new croaker.NodeEntry('Modules', {}, [ new croaker.NodeEntry('Module', {Name:'Some.dll', AssemblyVersion:'1.0.2.3'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'1'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'4'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'5'}, []) ]), new croaker.NodeEntry('NameSpaces', {}, [ new croaker.NodeEntry('Namespace', {Name:'Sample.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'10'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'40'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'50'}, []) ]), new croaker.NodeEntry('Types', {}, []) ]), new croaker.NodeEntry('Namespace', {Name:'Other.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'43'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'4'}, []) ]), new croaker.NodeEntry('Types', {}, [ new croaker.NodeEntry('Type', {Name: 'SampleType.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'Mantain', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'42'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'7'}, []) ]), new croaker.NodeEntry('Members', {}, [ new croaker.NodeEntry('Member', {Name: 'Thisis.Core', File:'50982.jkalhfksdl', Line:'5'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'metricly', Value:'43'}, []), new croaker.NodeEntry('Metric', {Name:'FoulPlay', Value:'98'}, []), new croaker.NodeEntry('Metric', {Name:'Rajo-Rajey', Value:'793'}, []) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]); this.entryMultipleTypes = new croaker.NodeEntry('CodeMetricsReport', {}, [ new croaker.NodeEntry('Targets', {}, [ new croaker.NodeEntry('Target', {}, [ new croaker.NodeEntry('Modules', {}, [ new croaker.NodeEntry('Module', {Name:'Some.dll', AssemblyVersion:'1.0.2.3'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'1'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'4'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'5'}, []) ]), new croaker.NodeEntry('NameSpaces', {}, [ new croaker.NodeEntry('Namespace', {Name:'Sample.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'10'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'40'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'50'}, []) ]), new croaker.NodeEntry('Types', {}, [ new croaker.NodeEntry('Type', {Name: 'SampleType.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'Mantain', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'498'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'7'}, []) ]), new croaker.NodeEntry('Members', {}, []) ]), new croaker.NodeEntry('Type', {Name: 'OtherType.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'Mantain', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value: '2'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'7'}, []) ]), new croaker.NodeEntry('Members', {}, []) ]) ]) ]), new croaker.NodeEntry('Namespace', {Name:'Other.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'MaintainabilityIndex', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'43'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'4'}, []) ]), new croaker.NodeEntry('Types', {}, [ new croaker.NodeEntry('Type', {Name: 'SampleType.Core'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'Mantain', Value:'11'}, []), new croaker.NodeEntry('Metric', {Name:'CyclomaticComplexifail', Value:'42'}, []), new croaker.NodeEntry('Metric', {Name:'BadabaBadabioom', Value:'7'}, []) ]), new croaker.NodeEntry('Members', {}, [ new croaker.NodeEntry('Member', {Name: 'Thisis.Core', File:'50982.jkalhfksdl', Line:'5'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'metricly', Value:'43'}, []), new croaker.NodeEntry('Metric', {Name:'FoulPlay', Value:'98'}, []), new croaker.NodeEntry('Metric', {Name:'Rajo-Rajey', Value:'793'}, []) ]) ]), new croaker.NodeEntry('Member', {Name: 'weard.Core', File:'50982.jkalhfksdl', Line:'5'}, [ new croaker.NodeEntry('Metrics', {}, [ new croaker.NodeEntry('Metric', {Name:'metricly', Value:'3'}, []), new croaker.NodeEntry('Metric', {Name:'FoulPlay', Value:'328'}, []), new croaker.NodeEntry('Metric', {Name:'Rajo-Rajey', Value:'193'}, []) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]) ]); } });