code
stringlengths
2
1.05M
const express = require('express'); const router = express.Router(); const url = require('url'); module.exports = (server) => { router.post('/auth/login', (req, res, next) => { let users = server.db.getState().users, matchedUser = users.find((user) => { return user.login.toUpperCase() === req.body.login.toUpperCase(); }); if(!matchedUser) { res.status(401).send('Wrong username'); } else if(matchedUser.password === req.body.password) { res.json({ token: matchedUser.fakeToken}); } else { res.status(401).send("Wrong password"); } }); router.post('/auth/logout', (req, res, next) => { res.json({ }); }); router.post('/auth/userinfo', (req, res, next) => { let users = server.db.getState().users, matchedUser = users.find((user) => { return user.fakeToken === req.header('Authorization'); }); if(!matchedUser) { res.status(401).send('Unauthorized'); } else { res.json(matchedUser); } }); return router; };
(function registerCloseWindowEvent(){ var hotcodepush = false; Meteor._reload.onMigrate(function () { hotcodepush = true; return [true]; }); window.addEventListener('beforeunload', function(e) { if (!hotcodepush && $('#message').val() && $('#message').val().length) { e.returnValue = "Discard your current message?"; } }); })(); Template.write.rendered = function() { $('#datetimepicker').datetimepicker({sideBySide: true}); $('#datetimepicker').data("DateTimePicker").date(moment()); // http://silviomoreto.github.io/bootstrap-select/ $('#message').autosize(); $('#mood').selectpicker(); if (Meteor.user().draft){ $('#message').text(Meteor.user().draft.message); } }; Template.write.helpers({ getColor: function(mood){ switch (mood){ case 'happy': return 'success'; case 'ok': return 'info'; case 'neutral': return 'primary'; case 'dangerous': return 'warning'; case 'angry': return 'danger'; default: return 'primary'; } }, getGlyphName: function(mood){ switch (mood){ case 'happy': return 'heart'; case 'ok': return 'thumbs-up'; case 'neutral': return 'user'; case 'dangerous': return 'screenshot'; case 'angry': return 'fire'; default: return 'user'; } }, getDateFormat: function(date){ return moment(date).format('ddd, DD. MMMM YYYY, HH:mm'); }}); Template.write.events = { 'keyup #message, change #message': function(){ if ($('#message').val().length){ $('#createMessage').removeClass('disabled'); } else{ $('#createMessage').addClass('disabled'); } // TODO: don't do that all the time, only after a certain treshhold + timeout Meteor.call('saveDraft', {message: $('#message').val()}, function(error, result){ if (error){ alert(error); } else{ // TODO: show that the draft was saved! } }); }, 'click #logout': function(){ Meteor.logout(function(){ Router.go('home'); }); }, 'click #createMessage': function(){ var message = $('#message').val(), timestamp = $('#datetimepicker').data("DateTimePicker").date().toDate(), mood = $('#mood').val(), post; post = {message: message, timestamp: timestamp, mood: mood}; Meteor.call('createPost', post, function(error, result){ if (error){ alert(error); } else{ $('#datetimepicker').data("DateTimePicker").date(moment()); $('#mood').val('neutral').selectpicker('refresh'); $('#createMessage').addClass('disabled'); $('#message').val('').focus(); $('#message').autosize().trigger('autosize.resize'); } }); }, 'click .toggle-post': function(e){ $(e.target).closest('.panel').find('.panel-body').toggle(); } }; Template.navigation.helpers({version: getVersion}); Template.export.helpers({ printPosts: function(posts){ var postObjects = posts.fetch(), modifiedPosts = postObjects.map(function(item){return _.pick(item, 'message', 'timestamp', 'mood')}); return JSON.stringify(modifiedPosts, null, 2); } });
'use strict' var path = require('path') module.exports = function (grunt) { grunt.initConfig({ clean: [ 'snippets/*' ], wrap: { files: { dest: 'snippets', src: [ 'templates/*.js' ] }, header: 'sublime/snippet-header.txt', footer: 'sublime/snippet-footer.txt' } }) grunt.loadNpmTasks('grunt-contrib-clean') grunt.registerTask('default', [ 'clean', 'wrap' ]) grunt.registerTask('wrap', 'Wraps source files with specified header and footer', function () { var data = grunt.config('wrap') var files = grunt.file.expand(data.files.src) var dest = path.resolve(grunt.template.process(data.files.dest)) var rawHeader = grunt.file.read(data.header) var rawFooter = grunt.file.read(data.footer) var sep = grunt.util.linefeed files.forEach(function (f) { var header = grunt.template.process(rawHeader, { data: { fileName: f, date: grunt.template.today('dd mmmm yyyy') } }) var footer = grunt.template.process(rawFooter, { data: { trigger: path.basename(f, path.extname(f, '.js')) } }) var file = path.join(dest, path.basename(f, path.extname(f, '.js')) + '.sublime-snippet') var contents = grunt.file.read(f) grunt.file.write(file, header + sep + contents + sep + footer) var displayF = path.join(data.files.dest, path.relative(dest, file)) grunt.log.write('Creating file ' + displayF.cyan + '... ') grunt.log.ok() }) }) }
import React from 'react'; import { shallow } from 'enzyme'; import PieSeries from '../../../src/components/PieSeries/PieSeries'; import Series from '../../../src/components/Series'; describe('<PieSeries />', function () { it('renders a <Series />', function () { const wrapper = shallow(<PieSeries id="mySeries" />); expect(wrapper).to.have.type(Series); }); it('renders a <Series type="pie" />', function () { const wrapper = shallow(<PieSeries id="mySeries" />); expect(wrapper).to.have.prop('type').equal('pie'); }); it('passes other props through to <Series />', function () { const wrapper = shallow(<PieSeries id="myOtherSeries" data={[1, 2, 3, 4]} />); expect(wrapper).to.have.prop('data').eql([1, 2, 3, 4]); }); });
"use strict"; let Bedrock = Object.create (null); Bedrock.version = "1.6.4"; Bedrock.Enum = { create: function () { let _ = Object.create (null); // function to create an enumerated object let make = function (name, value) { //console.log ("enumerate '" + name + "' = " + value); let enumeratedValue = Object.create (_); Object.defineProperty(enumeratedValue, "name", { value: name }); Object.defineProperty(enumeratedValue, "value", { value: value }); return enumeratedValue; }; // create the enumerated values, which are Objects of this type already populated let names = [].slice.call (arguments); let enumeratedValues = []; for (let name of names) { let enumeratedValue = make (name, enumeratedValues.length); enumeratedValues.push(enumeratedValue); Object.defineProperty (_, name, { value: enumeratedValue, enumerable: true }); } // save the names and values independently Object.defineProperty (_, "names", { value: names }); Object.defineProperty (_, "values", { value: enumeratedValues }); // the toString property so that we can implicitly treat this thing as a string Object.defineProperty (_, "toString", { value: function () { return this.name; } }); return _; } }; Bedrock.LogLevel = function () { let _ = Bedrock.Enum.create ("TRACE", "INFO", "WARNING", "ERROR"); // default let logLevel = _.ERROR; _.set = function (newLogLevel) { logLevel = newLogLevel; }; let formatStrings = ["TRC", "INF", "WRN", "ERR"]; _.say = function (messageLogLevel, message) { if (messageLogLevel >= logLevel) { console.log (formatStrings[messageLogLevel.value] + ": " + message) } }; return _; } (); Bedrock.LogLevel.set (Bedrock.LogLevel.INFO); Bedrock.Base = function () { let _ = Object.create (null); _.new = function (parameters) { // TODO could add some validation here... return Object.create (this).init (parameters); }; return _; } (); Bedrock.Utility = function () { let _ = Object.create (null); _.copyIf = function (key, leftObject, rightObject) { if (key in leftObject) { rightObject[key] = leftObject[key]; } }; _.randomString = function (length, chars) { let result = ""; for (let i = 0; i < length; ++i) { result += chars[Math.floor (Math.random () * chars.length)]; } return result; }; _.defaultTrue = function (value) { return ((typeof (value) === "undefined") || (value !== false)); }; _.defaultFalse = function (value) { return ((typeof (value) !== "undefined") && (value !== false)); }; _.ucFirst = function (str) { return ((typeof (str) !== "undefined") && (str.length > 0)) ? (str.charAt(0).toUpperCase() + str.slice(1)) : ""; }; return _; } (); Bedrock.Http = function () { let $ = Object.create (null); $.get = function (queryString, onSuccess) { let request = new XMLHttpRequest (); request.overrideMimeType ("application/json"); request.open ("GET", queryString, true); request.onload = function (event) { if (request.status === 200) { let response = JSON.parse (this.responseText); onSuccess (response); } }; request.send (); }; $.post = function (queryString, postData, onSuccess) { let request = new XMLHttpRequest (); request.overrideMimeType ("application/json"); request.open ("POST", queryString, true); request.onload = function (event) { if (request.status === 200) { let response = JSON.parse (this.responseText); onSuccess (response); } }; request.send (postData); }; return $; } (); Bedrock.Cookie = function () { let $ = Object.create (null); $.set = function (name, value, expireDays = 30) { let date = new Date (); date.setTime (date.getTime () + (expireDays * 24 * 60 * 60 * 1000)); let expires = "expires=" + date.toUTCString (); document.cookie = name + "=" + value + "; " + expires + "; SameSite=strict; path=/"; }; $.get = function (name) { let find = name + "="; let decodedCookie = decodeURIComponent (document.cookie); let cookieArray = decodedCookie.split (";"); for (let cookie of cookieArray) { cookie = cookie.trim(); let index = cookie.indexOf (find); if (index >= 0) { return cookie.substring (index + find.length); } } return ""; }; $.remove = function (name) { this.set (name, "", -1); }; $.replace = function (name, value, expireDays) { this.set (name, "", -1); this.set (name, value, expireDays); }; $.resetAll = function () { let decodedCookie = decodeURIComponent (document.cookie); let cookieArray = decodedCookie.split (";"); for (let cookie of cookieArray) { let name = cookie.split ("=")[0]; name = name.replace (/^\s*/, ""); name = name.replace (/\s*$/, ""); this.set (name, "", -1); } }; return $; } (); Bedrock.ServiceBase = function () { let $ = Object.create (null); $.getQuery = function (parameters) { let contextPath = Bedrock.Cookie.get ("full-context-path"); let query = contextPath + "api"; let divider = "?"; for (let name of Object.keys (parameters)) { let parameter = parameters[name]; query += divider + name + "=" + parameter; divider = "&" } return query; }; $.getFromQuery = function (query, onSuccess, onFailure) { Bedrock.Http.get (query, function (response) { Bedrock.LogLevel.say (Bedrock.LogLevel.INFO, query + " (status: " + response.status + ")"); if (response.status === "ok") { onSuccess (("response" in response) ? response.response : response.status); } else if (typeof (onFailure) !== "undefined") { onFailure (response.error); } else { // default on failure, alert... alert (response.error); } }); }; $.get = function (parameters, onSuccess, onFailure) { $.getFromQuery ($.getQuery (parameters), onSuccess, onFailure); }; $.postFromQuery = function (query, postData, onSuccess, onFailure) { Bedrock.Http.post (query, postData, function (response) { Bedrock.LogLevel.say (Bedrock.LogLevel.INFO, query + " (status: " + response.status + ")"); if (response.status === "ok") { onSuccess (("response" in response) ? response.response : response.status); } else if (typeof (onFailure) !== "undefined") { onFailure (response.error); } else { // default on failure, alert... alert (response.error); } }); }; $.post = function (parameters, postData, onSuccess, onFailure) { $.postFromQuery ($.getQuery (parameters), postData, onSuccess, onFailure); }; return $; } (); Bedrock.ServiceDescriptor = function () { let $ = Object.create (null); $.get = function (queryString, onSuccess) { let request = new XMLHttpRequest (); request.overrideMimeType ("application/json"); request.open ("GET", queryString, true); request.onload = function (event) { if (request.status === 200) { let response = JSON.parse (this.responseText); onSuccess (response); } }; request.send (); }; $.tryExample = function (exampleName) { // show the result let hoverBoxRoot = document.getElementById ("bedrock-service-descriptor-hover-box"); let hoverBoxBufferElement = document.getElementById ("bedrock-service-descriptor-hover-box-buffer"); let Html = Bedrock.Html; Html.removeAllChildren(hoverBoxBufferElement); hoverBoxRoot.style.visibility = "visible"; event.stopPropagation(); Bedrock.ServiceBase.get ({ event : "help" }, function (response) { // get the example and explicitly set the event in it (it's typically omitted for simplicity in the configurations) let example = response.events[exampleName].example; example.event = exampleName; let url; let postData = null; let handleExampleResponse = function (exampleResponse) { let innerHTML = Html.Builder.begin ("div"); innerHTML.add("h2", { style: { margin: 0 }, innerHTML: "Example for " + exampleName }); if (postData != null) { innerHTML .begin ("div", { style: { margin: "16px 0" }}) .add ("div", { style: { fontWeight: "bold", display: "inline-block", width: "80px" }, innerHTML: "URL: " }) .add ("div", { style: { display: "inline-block" }, innerHTML: url.replace (/&/g, "&amp;") }) .end () .add ("div", { style: { margin: "16px 0 8px 0", fontWeight: "bold" }, innerHTML: "Post JSON: " }) .add ("pre", { class: "code-pre", innerHTML: postData }) } else { innerHTML .begin ("div", { style: { margin: "16px 0" }}) .add ("div", { style: { fontWeight: "bold", display: "inline-block", width: "80px" }, innerHTML: "URL: " }) .add ("a", { style: { display: "inline-block", textDecoration: "none" }, innerHTML: url.replace (/&/g, "&amp;"), href: url, target: "_blank" }) .end (); } innerHTML .add ("div", { style: { margin: "16px 0 8px 0", fontWeight: "bold" }, innerHTML: "Response JSON: " }) .add ("pre", { class: "code-pre", innerHTML: JSON.stringify (exampleResponse, null, 4) }) hoverBoxBufferElement.appendChild(innerHTML.end ()); }; // if the example includes post data... if ("post-data" in example) { // separate the post data and issue the example request as a post postData = JSON.stringify (example["post-data"], null, 4); delete example["post-data"]; url = Bedrock.ServiceBase.getQuery (example); Bedrock.Http.post (url, postData, handleExampleResponse); } else { // issue the example request as a get url = Bedrock.ServiceBase.getQuery (example); Bedrock.Http.get(url, handleExampleResponse); } }, function (error) { hoverBoxBufferElement.appendChild (Html.Builder.begin ("div", { innerHTML: "ERROR: " + error}).end ()); }); }; $.displaySpecification = function (specification) { // start with an empty build let innerHTML = ""; if ("description" in specification) { innerHTML += block ("h2", {}, "Description") + div ("description-div", specification.description); } if ("events" in specification) { innerHTML += block ("h2", {}, "Events"); let events = specification.events; let eventNames = Object.keys (events); let eventsHTML = ""; for (let eventName of eventNames) { let event = events[eventName]; // events are assumed to be published, but if they have a p"published: false" // attribute, we will skip it if (! (("published" in event) && ((event.published === false) || (event.published === "false")))) { let eventHTML = ""; // if there is an example if ("example" in event) { eventHTML = block ("div", { class: "try-it", onclick: 'Bedrock.ServiceDescriptor.tryExample (&quot;' + eventName + '&quot;);' }, "[example]"); } eventHTML = div ("event-name", eventName + eventHTML); // if there is a description if ("description" in event) { eventHTML += div ("event-description", event.description); } let odd; let evenOddTitle = function (title) { odd = true; eventHTML += div ("even-odd-title", title); return odd; }; let evenOdd = function (title, object) { odd = true; let names = Object.keys (object); if (names.length > 0) { eventHTML += div ("even-odd-title", title); for (let name of names) { let element = object[name]; let required = ("required" in element) ? ((element.required === true) || (element.required === "true")) : false; eventHTML += div ("even-odd-div" + (odd ? " odd" : ""), div ("even-odd-name", name) + div ("even-odd-required", required ? "REQUIRED" : "OPTIONAL") + div ("even-odd-description", element.description)); odd = !odd; } } return odd; }; let listParameters = function (title, object) { // parameters if ("parameters" in object) { evenOdd (title, object.parameters); } if (("strict" in object) && ((object.strict === false) || (object.strict === "false"))) { if (!("parameters" in object)) { evenOddTitle (title); } eventHTML += div ("even-odd-div" + (odd ? " odd" : ""), div ("even-odd-name", "(any)") + div ("even-odd-required", "OPTIONAL") + div ("even-odd-description", "Event allows unspecified parameters.")); } }; // parameters listParameters ("Parameters:", event); // post-data if (("parameters" in event) && ("post-data" in event.parameters)) { listParameters ("Post Data:", event.parameters["post-data"]); } // response if ("response" in event) { let response = event.response; // return specification might be an array, indicating this event returns an // array of something if (Array.isArray (response)) { // return specification might be an empty array, or an array with a single // proto object if (response.length > 0) { evenOdd ("Response (Array):", response[0]); } else { evenOddTitle ("Response (Array):"); eventHTML += div ("even-odd-div" + (odd ? " odd" : ""), div ("even-odd-name", "(any)") + div ("even-odd-required", "OPTIONAL") + div ("even-odd-description", "Unspecified.")); } } else { evenOdd ("Response:", response); } } eventsHTML += div ("event-div", eventHTML); } } innerHTML += div("events-div", eventsHTML); } if ("name" in specification) { document.title = specification.name; innerHTML = block ("h1", {}, specification.name) + div("container-div", innerHTML); } innerHTML += div ("content-center footer", "Built with " + a ("footer-link", "http://bedrock.brettonw.com", "Bedrock")); // now add a floating pane that is invisible and install the click handler to hide it innerHTML += block ("div", { id: "bedrock-service-descriptor-hover-box" }, block ("div", {id: "bedrock-service-descriptor-hover-box-buffer"},"") ); document.addEventListener('click', function(event) { let hoverBoxElement = document.getElementById ("bedrock-service-descriptor-hover-box"); if (!hoverBoxElement.contains(event.target)) { hoverBoxElement.style.visibility = "hidden"; } }); return innerHTML; }; // a little black raincloud, of course $.display = function (displayInDivId) { Bedrock.ServiceBase.get ({event: "help"}, function (response) { response = (response.response !== undefined) ? response.response : response; document.getElementById(displayInDivId).innerHTML = Bedrock.ServiceDescriptor.displaySpecification (response); }); }; // convert the names into camel-case names (dashes are removed and the following character is uppercased) let makeName = function (input) { return input.replace (/-([^-])/g, function replacer (match, p1, offset, string) { return p1.toUpperCase(); }); }; $.translateResponse = function (response) { // internal function to copy the object as a response let copyAsResponse = function (object) { let copy = {}; let keys = Object.keys (object); for (let key of keys) { copy[makeName(key)] = object[key]; } return copy; }; // make a decision based on the type if (Array.isArray(response)) { let copy = []; for (let entry of response) { copy.push (copyAsResponse(entry)); } return copy; } else { return copyAsResponse(response); } }; // create a client side object with all of the api's $.api = function (onSuccess, baseUrl = "", apiSource = "") { // condition the inputs baseUrl = (baseUrl === "") ? location.href.substr(0,location.href.lastIndexOf("/")) : baseUrl; baseUrl = baseUrl.replace (/\/$/g, ""); // get the api const API_EVENT_HELP = "api?event=help"; let url = (apiSource === "") ? (baseUrl + "/" + API_EVENT_HELP) : apiSource; $.get (url, function (response) { // if we retrieved the api.json from the service base, get the actual response response = (response.response !== undefined) ? response.response : response; // start with an empty build let api = Object.create (null); api.specification = response; // check that we got a response with events if ("events" in response) { let events = response.events; let eventNames = Object.keys (events); for (let eventName of eventNames) { let event = events[eventName]; // set up the function name and an empty parameter list let functionName = makeName (eventName); let functionParameters = "("; let functionBody = ' let url = "' + baseUrl + '/api?event=' + eventName + '";\n'; // if there are parameters, add them let first = true; if ("parameters" in event) { let names = Object.keys (event.parameters); if (names.length > 0) { for (let name of names) { let parameterName = makeName (name); functionParameters += ((first !== true) ? ", " : "") + parameterName; functionBody += ' url += "' + name + '=" + ' + parameterName + ';\n'; first = false; } } } functionParameters += ((first !== true) ? ", " : "") + "onSuccess"; functionBody += ' Bedrock.ServiceDescriptor.get (url, function (response) {\n'; functionBody += ' if (response.status === "ok") {\n'; functionBody += ' response = Bedrock.ServiceDescriptor.translateResponse (response.response);\n'; functionBody += ' onSuccess (response);\n'; functionBody += ' }\n'; functionBody += ' });\n'; functionParameters += ")"; Bedrock.LogLevel.say (Bedrock.LogLevel.INFO, functionName + " " + functionParameters + ";\n"); let functionString = "return function " + functionParameters + " {\n" +functionBody + "};\n"; api[functionName] = new Function (functionString) (); } } // call the completion routine onSuccess (api); }); }; return $; } (); // Helper functions for emitting HTML from Javascript let valid = function (value = null) { return (value !== null); }; let block = function (block, attributes, content) { let result = "<" + block; if (valid (attributes)) { let attributeNames = Object.keys (attributes); for (let attributeName of attributeNames) { if (valid (attributes[attributeName])) { result += " " + attributeName + "=\"" + attributes[attributeName] + "\""; } } } return result + (valid (content) ? (">" + content + "</" + block + ">") : ("/>")); }; let div = function (cssClass, content) { return block ("div", { "class": cssClass }, content); }; let a = function (cssClass, href, content) { return block ("a", { "class": cssClass, "href": href, "target": "_top" }, content); }; Bedrock.Html = function () { let $ = Object.create (null); $.removeAllChildren = function (element) { while (element.firstChild) { element.removeChild (element.firstChild); } }; $.makeElement = function (tag, options) { // check to see if tag includes a namespace url, we allow separation by semicolon let tagSplit = tag.split(";", 2); let uri = ""; if (tagSplit.length == 2) { // figure out which one has a ":" in it - that's the namespace if (tagSplit[0].indexOf(":") > 0) { uri = tagSplit[0]; tag = tagSplit[1]; } else if (tagSplit[1].indexOf(":") > 0) { uri = tagSplit[1]; tag = tagSplit[0]; } } // create the tag and add the options, appropriately let element = (uri.length > 0) ? document.createElementNS(uri, tag) : document.createElement (tag); let optionNames = Object.keys (options); for (let optionName of optionNames) { switch (optionName) { case "class": case "classes": { let cssClasses = options[optionName]; if (! Array.isArray (cssClasses)) { cssClasses = cssClasses.split (","); } for (let cssClass of cssClasses) { element.classList.add (cssClass); } break; } case "style": { for (let styleName of Object.keys (options.style)) { element.style[styleName] = options.style[styleName]; } break; } case "attribute": case "attributes":{ // the .attribute form of access is preferred, but for non-standard elements, as // in SVG node attributes, this is the supported method let attributes = options[optionName]; for (let attributeName of Object.keys (attributes)) { element.setAttribute (attributeName, attributes[attributeName]); } break; } case "event": case "events":{ // firefox and chrome handle these things differently, so this is an // effort to provide common handling let events = options[optionName]; for (let eventName of Object.keys (events)) { element.addEventListener(eventName, events[eventName], false); } break; } default: { element[optionName] = options[optionName]; break; } } } return element; }; $.addElement = function (parent, tag, options, before = null) { let element = $.makeElement(tag, options); parent.insertBefore (element, before); return element; }; /** * Utility function to tell if an element is in view in the scrolling region of a container * @param element * @param view * @returns {boolean} */ $.elementIsInView = function (element, view) { let viewTop = view.scrollTop; let viewBottom = view.offsetHeight + viewTop; let elementTop = element.offsetTop; let elementBottom = elementTop + element.offsetHeight; return ((elementBottom <= viewBottom) && (elementTop >= viewTop)); }; /** * Utility function to retrieve a style value from the stylesheets collection. * Note: this only works if the stylesheet was loaded locally or securely * @param selector the name of the class to fetch a style value from * @param style the name of the style to fetch * @returns {string} the found style value, or undefined */ $.getCssSelectorStyle = function (selector, style) { for (let styleSheet of document.styleSheets) { try { if (styleSheet.cssRules !== null) { for (let cssRule of styleSheet.cssRules) { if (cssRule.selectorText && (cssRule.selectorText === selector)) { return cssRule.style[style]; } } } } catch (exception) { // really, just trap this since it's a security problem that chrome fixed by // throwing an exception } } return undefined; }; $.Builder = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.parentBuilder = ("parentBuilder" in parameters) ? parameters.parentBuilder : null; this.elementType = parameters.elementType; this.elementParameters = (parameters.elementParameters !== undefined) ? parameters.elementParameters : {}; this.builders = []; return this; }; _.addBuilder = function (builder) { this.builders.push (builder); return this; }; _.add = function (elementType, elementParameters) { // if this method is called as a static, this is creating a new builder return (Object.is (this, _)) ? _.new ({ elementType: elementType, elementParameters: elementParameters }).build () : this.addBuilder (_.new ( { parentBuilder: this, elementType: elementType, elementParameters: elementParameters })); }; _.beginBuilder = function (builder) { this.builders.push (builder); return builder; }; _.begin = function (elementType, elementParameters) { // if this method is called as a static, this is creating a new builder return (Object.is (this, _)) ? _.new ({ elementType: elementType, elementParameters: elementParameters }) : this.beginBuilder (_.new ({ parentBuilder: this, elementType: elementType, elementParameters: elementParameters })); }; _.end = function () { return (this.parentBuilder !== null) ? this.parentBuilder : this.build (); }; _.build = function () { // create my element let element = $.makeElement (this.elementType, this.elementParameters); // walk down the builders, building in turn for (let builder of this.builders) { element.appendChild(builder.build ()); } return element; }; return _; } (); return $; } (); Bedrock.PagedDisplay = function () { let $ = Object.create (null); // using let Html = Bedrock.Html; let Enum = Bedrock.Enum; /* $.Select = function () { let _ = Object.create(Bedrock.Base); _.init = function (parameters) { this.name = parameters.name; }; return _; }; */ // 2 - encapsulate // 3 - dynamically compute the column widths // 3.5 - allow columns to be individually styled, including column widths // 4 - user selectable style classes based on input parameters let getAllFieldNames = $.getAllFieldNames = function (records) { let fields = Object.create (null); for (let record of records) { let keys = Object.keys (record); for (let key of keys) { fields[key] = key; } } return Object.keys (fields).sort (); }; // entry types const EntryType = $.EntryType = Enum.create ( "LEFT_JUSTIFY", // left-justified "CENTER_JUSTIFY", // centered "RIGHT_JUSTIFY", // right-justified "IMAGE" // a url for an image (center justified) ); // style names and the default style names object const Style = $.Style = Enum.create ( "HEADER", "HEADER_ROW", "HEADER_ENTRY", "HEADER_ENTRY_TEXT", "TABLE", "TABLE_ROW", "TABLE_ROW_ENTRY", "TABLE_ROW_ENTRY_TEXT", "ODD", "HOVER" ); const defaultStyles = Object.create (null); defaultStyles[Style.HEADER] = "bedrock-paged-display-header"; defaultStyles[Style.HEADER_ROW] = "bedrock-paged-display-header-row"; defaultStyles[Style.HEADER_ENTRY] = "bedrock-paged-display-header-entry"; defaultStyles[Style.HEADER_ENTRY_TEXT] = "bedrock-paged-display-header-entry-text"; defaultStyles[Style.TABLE] = "bedrock-paged-display-table"; defaultStyles[Style.TABLE_ROW] = "bedrock-paged-display-table-row"; defaultStyles[Style.TABLE_ROW_ENTRY] = "bedrock-paged-display-table-row-entry"; defaultStyles[Style.TABLE_ROW_ENTRY_TEXT] = "bedrock-paged-display-table-row-entry-text"; defaultStyles[Style.ODD] = "bedrock-paged-display-odd"; defaultStyles[Style.HOVER] = "bedrock-paged-display-hover"; defaultStyles[EntryType.LEFT_JUSTIFY] = "bedrock-paged-display-entry-left-justify"; defaultStyles[EntryType.CENTER_JUSTIFY] = "bedrock-paged-display-entry-center-justify"; defaultStyles[EntryType.RIGHT_JUSTIFY] = "bedrock-paged-display-entry-right-justify"; defaultStyles[EntryType.IMAGE] = "bedrock-paged-display-entry-image"; $.Table = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { const records = this.records = parameters.records; // save the container that is passed in - it could be an element or // a valid elementId, which we reduce to an element (can get its id // from it at any time thereafter if we need it) if (parameters.container !== undefined) { const container = this.container = (typeof (parameters.container) === "string") ? document.getElementById (parameters.container) : parameters.container; if ((container.tagName.toLowerCase () === "div") && (container.id !== undefined)) { // "select" should be an array of objects specifying the name // of the field, its display name, and its type (in desired // display order) - the user either supplies all columns, or // none let select; if (parameters.select === undefined) { select = this.select = []; for (let selectName of getAllFieldNames (records)) { select.push ({ name: selectName }); } } else { select = this.select = parameters.select; } // validate the entry names and the types for (let entry of select) { if (entry.displayName === undefined) { entry.displayName = entry.name; } if ((entry.type === undefined) || (EntryType[entry.type] === undefined)) { entry.type = EntryType.CENTER_JUSTIFY; } if (entry.width === undefined) { entry.width = 1.0 / select.length; } entry.width = Math.floor (entry.width * 100) + "%"; } // "styles" should be an object containing style names that will be // applied to the components - it's treated as an override of a default // set of values, so not all values must be supplied this.styles = Object.create (defaultStyles); if (parameters.styles !== undefined) { for (let style of Object.keys (defaultStyles)) { if (parameters.styles[style] !== undefined) { this.styles[style] = parameters.styles[style]; } } } // "callback" is a way for the display to send an event if a row is // clicked on or selected by the user if (parameters.onclick !== undefined) { this.onclick = parameters.onclick; } // start off with no selected row, allowing mouseover this.currentRow = null; this.allowMouseover = true; } else { Bedrock.LogLevel.say (Bedrock.LogLevel.ERROR, "'container' must be a valid element with an id (which is used as the base name for rows)."); } } else { Bedrock.LogLevel.say (Bedrock.LogLevel.ERROR, "'container' is a required parameter. it may be an element or a valid element id."); } return this; }; _.makeTable = function () { const container = this.container; const select = this.select; const styles = this.styles; const self = this; // utility function to compute the container height, just helps keep // the code a bit cleaner when I use it - this is a bit stilted code- // wise because the actual return value from some of these styles // might not be a number at all let getContainerHeight = (minHeight) => { let containerHeight = container.offsetHeight; if ((parseInt (containerHeight.toString ()) >= minHeight) === false) { containerHeight = window.getComputedStyle (container).getPropertyValue ("height"); } if ((parseInt (containerHeight.toString ()) >= minHeight) === false) { containerHeight = window.getComputedStyle (container).getPropertyValue ("max-height"); } if ((parseInt (containerHeight.toString ()) >= minHeight) === false) { containerHeight = minHeight; } return parseInt (containerHeight.toString ()); }; // size the pages a bit larger than the actual view so that there can't be // more than two pages visible at any one time. this is also a bit of a // compromise as larger pages means more populated lines for display per // page, so we don't want to just blow the size way up. const records = this.records; const recordCount = records.length; const rowHeight = parseInt (Html.getCssSelectorStyle ("." + styles[Style.TABLE_ROW], "height")); const containerHeight = getContainerHeight (rowHeight); const pageSize = Math.max (Math.floor ((containerHeight / rowHeight) * 1.25), 1); const pageHeight = rowHeight * pageSize; const pageCount = Math.floor (recordCount / pageSize) + (((recordCount % pageSize) > 0) ? 1 : 0); // reset everything Html.removeAllChildren (container); container.scrollTop = 0; // utility functions that use special knowledge of the size of a // page to decide if the page or row is visible const Visible = Enum.create ( "NOT_VISIBLE", "PARTIALLY_VISIBLE", "COMPLETELY_VISIBLE" ); let rangeIsVisible = function (start, end) { const scrollTop = container.scrollTop; start = (start * rowHeight) - scrollTop; end = (end * rowHeight) - scrollTop; return ((end >= 0) && (start <= container.clientHeight)) ? (((start >= 0) && (end < container.clientHeight)) ? Visible.COMPLETELY_VISIBLE : Visible.PARTIALLY_VISIBLE) : Visible.NOT_VISIBLE; }; let getRowInfo = function (rowId) { return parseInt (rowId.toString ().split (/-/).slice(-1)[0]); }; let rowIsVisible = function (rowId) { let row = getRowInfo (rowId); return (rangeIsVisible (row, row + 1) === Visible.COMPLETELY_VISIBLE); }; let getPageInfo = function (pageId) { // extract the page range that we encoded into the id, like // this:"blah-blah-32-85" let pageInfo = pageId.toString ().split (/-/); return { start: parseInt (pageInfo[pageInfo.length - 2]), end: parseInt (pageInfo[pageInfo.length - 1]) }; }; let pageIsVisible = function (page) { let pageInfo = getPageInfo (page.id); return (rangeIsVisible(pageInfo.start, pageInfo.end) !== Visible.NOT_VISIBLE); }; let go = function (defaultRowId, add, scroll) { // default to row 0 let rowId = defaultRowId; // deselect the current row if there is one if (self.currentRow !== null) { // update the next row... rowId = ((getRowInfo (self.currentRow.id) + add) + records.length) % records.length; self.currentRow.classList.remove (styles[Style.HOVER]); } // what page is the new element on, and is it populated? let pageId = Math.floor (rowId / pageSize); let page = container.children[0].children[pageId]; if (page.children.length === 0) { populatePage(page); } // get the relative offset and get the actual row let relativeIndex = rowId - (pageId * pageSize); self.currentRow = page.children[0].children[relativeIndex]; self.currentRow.classList.add (styles[Style.HOVER]); // and finally, check to see if the row is visible if (! rowIsVisible (rowId)) { // gotta scroll to make it visible, and tell the rows not // to respond to mouseover events until the mouse moves self.allowMouseover = false; container.scrollTop = scroll (rowId); } }; // go next, go prev... for key-press access self.goNext = function () { go (0, 1, function (rowId) { // optionsElement.scrollTop = (self.currentOption.offsetTop - optionsElement.offsetHeight) + self.currentOption.offsetHeight; return ((rowId + 1) * rowHeight) - container.clientHeight //return rowId * rowHeight; }); }; self.goPrev = function () { go (records.length - 1, -1, function (rowId) { return rowId * rowHeight; }); }; self.select = function () { if (self.currentRow !== null) { self.currentRow.onmousedown(); } }; // the main worker function - when the container is scrolled, figure out which // pages are visible and make sure they are populated. we try to do this in an // intelligent way, rather than iterate over all the pages. the point is to // reduce the amount of DOM manipulation we do, as those operations are VERY // slow. let lastVisiblePages = []; container.onscroll = function (/* event */) { let visiblePages = []; // clear the lastVisiblePages for (let page of lastVisiblePages) { if (pageIsVisible (page)) { visiblePages.push (page); } else { Html.removeAllChildren (page); } } // figure out which pages to make visible let start = Math.floor (container.scrollTop / pageHeight); let end = Math.min (pageCount, start + 2); let pages = container.children[0].children; for (let i = start; i < end; ++i) { let page = pages[i]; if ((page.children.length === 0) && pageIsVisible (page)) { visiblePages.push (page); populatePage (page); } } // reset the visible pages for the next time lastVisiblePages = visiblePages; }; // function to populate a page - build it out from the records let populatePage = function (pageElement) { // create a filler object to make add/remove quick let pageBuilder = Html.Builder.begin ("div"); // extract the page range that we encoded into the id, like // this:"blah-blah-32-85" let pageInfo = getPageInfo (pageElement.id); for (let j = pageInfo.start, end = pageInfo.end; j < end; ++j) { let record = records[j]; let rowBuilder = pageBuilder.begin ("div", { id: container.id + "-row-" + j, class: ((j & 0x01) === 1) ? [styles[Style.TABLE_ROW], styles[Style.ODD]] : [styles[Style.TABLE_ROW]], onmousedown: function () { if (self.onclick !== undefined) { if (self.onclick (self.records[j])) { // if the called function returns true, we reset the // selected element this.classList.remove (styles[Style.HOVER]); self.currentRow = null; } return true; } return false; }, onmouseover: function () { //LOG (INFO, "onmouseover (" + ((self.allowMouseover === true) ? "YES" : "NO") + ")"); if (self.allowMouseover === true) { if (self.currentRow !== null) { self.currentRow.classList.remove (styles[Style.HOVER]); } self.currentRow = this; self.currentRow.classList.add (styles[Style.HOVER]); } }, onmousemove: function () { //LOG (INFO, "onmousemove (" + ((self.allowMouseover === true) ? "YES" : "NO") + ")"); self.allowMouseover = true; } }); // populate the row entries for (let entry of select) { let value = (entry.name in record) ? record[entry.name] : ""; let entryClass = [styles[entry.type], styles[Style.TABLE_ROW_ENTRY_TEXT]]; if (entry.class !== undefined) { entryClass = entryClass.concat(Array.isArray(entry.class) ? entry.class : entry.class.split (",")); } let entryTextParams = { class: entryClass, innerHTML: (value !== undefined) ? value : "" }; if (entry.style !== undefined) { entryTextParams.style = entry.style; } rowBuilder .begin ("div", { class: styles[Style.TABLE_ROW_ENTRY], style: { width: entry.width } }) .add ("div", entryTextParams) .end (); } pageBuilder.end (); } pageElement.appendChild (pageBuilder.end ()); }; // loop over all of the records, page by page let pageContainerBuilder = Html.Builder.begin ("div"); for (let pageIndex = 0; pageIndex < pageCount; ++pageIndex) { let start = pageIndex * pageSize; let end = Math.min (start + pageSize, recordCount); pageContainerBuilder.add ("div", { id: container.id + "-page-" + start + "-" + end, style: { height: ((end - start) * rowHeight) + "px" } }); } container.appendChild (pageContainerBuilder.end ()); container.onscroll (null); return this; }; _.makeTableHeader = function () { const container = this.container; const select = this.select; const styles = this.styles; let headerBuilder = Html.Builder.begin ("div", { class: styles[Style.HEADER] }); let headerRowBuilder = headerBuilder.begin ("div", { class: styles[Style.HEADER_ROW] }); for (let entry of select) { headerRowBuilder .begin ("div", { class: styles[Style.HEADER_ENTRY], style: { width: entry.width } }) .add ("div", { class: styles[Style.HEADER_ENTRY_TEXT], innerHTML: entry.displayName }) .end (); } container.appendChild (headerBuilder.end ()); }; _.makeTableWithHeader = function () { Html.removeAllChildren (this.container); // add the header this.makeTableHeader (); // add the table to a sub element this.container = Html.addElement (this.container, "div", { id: this.container.id + "-table", class: this.styles[Style.TABLE] }); return this.makeTable (); }; return _; } (); return $; } (); Bedrock.ComboBox = function () { let _ = Object.create(Bedrock.Base); let Html = Bedrock.Html; let PagedDisplay = Bedrock.PagedDisplay; let Style = PagedDisplay.Style; let EntryType = PagedDisplay.EntryType; let Utility = Bedrock.Utility; const defaultStyles = Object.create (null); defaultStyles[Style.TABLE] = "bedrock-combobox-paged-display-table"; defaultStyles[Style.TABLE_ROW] = "bedrock-combobox-paged-display-table-row"; defaultStyles[Style.TABLE_ROW_ENTRY] = "bedrock-combobox-paged-display-table-row-entry"; defaultStyles[Style.TABLE_ROW_ENTRY_TEXT] = "bedrock-combobox-paged-display-table-row-entry-text"; defaultStyles[Style.ODD] = "bedrock-combobox-paged-display-odd"; defaultStyles[Style.HOVER] = "bedrock-combobox-paged-display-hover"; let indexById = {}; _.getById = function (inputElementId) { return indexById[inputElementId]; }; _.init = function (parameters) { // input element id is required if ("inputElementId" in parameters) { // scope "this" as self so I can use it in closures let self = this; // if the user starts pressing keys to navigate the options list, then we don't // want to automagically incur mouseover events while the list scrolls. This flag // is used to tell the options not to highlight from mouseover events when the // reason for the event is a keypress this.allowMouseover = true; // set up the option for regexp in matching, default is false this.useRegExp = ("useRegExp" in parameters) ? parameters.useRegExp : false; // if there are styles, copy them in... this.styles = Object.create (defaultStyles); if (parameters.styles !== undefined) { for (let style of Object.keys (defaultStyles)) { if (parameters.styles[style] !== undefined) { this.styles[style] = parameters.styles[style]; } } } // we will need the parentElement, this is a placeholder for it let inputElement, parentElement; // the user must specify an inputElementId, or inputElement that we can get the // inputElementId from // XXX NOTE TODO - this is obviated by the code 20 lines before let inputElementId = ("inputElementId" in parameters) ? parameters.inputElementId : ("inputElement" in parameters) ? parameters.inputElement.id : null; if (inputElementId !== null) { // we know we have an id, now try to get the inputElement inputElement = ("inputElement" in parameters) ? parameters.inputElement : document.getElementById (inputElementId); if (inputElement === null) { // have to create the inputElement, the user must specify a // parentElementId, or parentElement that we can get the // parentElementId from let parentElementId = ("parentElementId" in parameters) ? parameters.parentElementId : ("parentElement" in parameters) ? parameters.parentElement.id : null; if (parentElementId !== null) { // get the parent element parentElement = ("parentElement" in parameters) ? parameters.parentElement : document.getElementById (parentElementId); // setup the creation parameters for the input element let inputElementParameters = { classes: ["combobox-input"], id: inputElementId, placeholder: inputElementId, // a reasonable default type: "text", autocomplete: "off" }; // depending on whether there is "class" in the parameters if ("class" in parameters) { inputElementParameters.classes.push (parameters.class); } // copy a few optional values if they are present Utility.copyIf ("placeholder", parameters, inputElementParameters); Utility.copyIf ("style", parameters, inputElementParameters); Utility.copyIf ("onchange", parameters, inputElementParameters); Utility.copyIf ("event", parameters, inputElementParameters); Utility.copyIf ("events", parameters, inputElementParameters); // now create the input element inputElement = Html.addElement (parentElement, "input", inputElementParameters); } else { // fatal error, don't know where to create the input Bedrock.LogLevel.say (Bedrock.LogLevel.ERROR, "expected 'parentElementId' or 'parentElement'."); return null; } } else { // the inputElement was found, let's retrieve its parent parentElement = inputElement.parentNode; } } else { // fatal error, no id was supplied, and none was findable Bedrock.LogLevel.say (Bedrock.LogLevel.ERROR, "ERROR: expected 'inputElementId' or 'inputElement'."); return null; } // now store the results so we can work with them, and set the value this.inputElement = inputElement; if ("value" in parameters) { this.inputElement.value = parameters.value } // put a pseudo-parent down so the popup will always be under the input, but not // in the document flow, and create our options container inside that - the pseudo- // parent has position relative with sizes of 0, and the child is placed with // absolute position under that. See the CSS file for details. let pseudoParentElement = Html.addElement (parentElement, "div", { class: "combobox-pseudo-parent" }, inputElement.nextSibling); let optionsElement = this.optionsElement = Html.addElement (pseudoParentElement, "div", { id: inputElementId + "-options", class: "combobox-options" }); // set the options this.setOptions (parameters.options); // subscribe to various events on the input element to do our thing { // capture the mousedown, and if it's on the far right of the input element, // clear the text before proceeding inputElement.onmousedown = function (event) { let x = (event.pageX - this.offsetLeft) / this.offsetWidth; let arrowPlacement = (this.offsetWidth - parseFloat (getComputedStyle (this).backgroundSize)) / this.offsetWidth; if (x > arrowPlacement) { inputElement.value = ""; // if the element is already focused, we need to update the options if (this === document.activeElement) { self.updateOptions (); } self.callOnChange (); } //console.log (this.id + " - mousedown (" + x + "/" + arrowPlacement + ")"); }; // capture some keys (up/down, for instance) inputElement.onkeydown = function (event) { switch (event.key) { case "ArrowUp": { self.optionsTable.goPrev(); break; } case "ArrowDown": { self.optionsTable.goNext(); break; } case "Enter": { self.optionsTable.select(); self.callOnChange (); inputElement.blur (); break; } case "Escape": { inputElement.blur (); break; } default: return true; } return false; }; // in case the user changes by pasting, does this not fire oninput? inputElement.onpaste = function () { this.oninput (); }; // oninput fires immediately when the value changes inputElement.oninput = function () { self.updateOptions (); self.callOnChange (); }; // when the control gains focus (in this order: onmousedown, focus, click) inputElement.onfocus = function (event) { //console.log (this.id + " - focus"); self.updateOptions (); optionsElement.scrollTop = 0; optionsElement.style.display = "block"; }; // when the user moves away from the control inputElement.onblur = function () { //console.log (this.id + " - blur"); self.optionsElement.style.display = "none"; }; } } else { // error out Bedrock.LogLevel.say (Bedrock.LogLevel.ERROR, "ERROR: 'inputElementId' is required."); return null; } return this; }; _.callOnChange = function () { if (("onchange" in this.inputElement) && (typeof this.inputElement.onchange === "function")) { this.inputElement.onchange (); } else { this.inputElement.dispatchEvent (new Event ("change")); } }; _.updateOptions = function () { // scope "this" as self so I can use it in closures let self = this; // there should be no currently selected option self.currentOption = null; // get the elements let inputElement = this.inputElement; let optionsElement = this.optionsElement; // clear out the options (fragment, should be one op) Html.removeAllChildren(optionsElement); // get the current value as a regex object for rapid matching - note that // if we don't want regexp, all regexp characters must be escaped let inputElementValue = this.useRegExp ? this.inputElement.value : this.inputElement.value.replace (/[\-\[\]\{\}\(\)\*\+\?\.,\\\^\$\|#\s]/g, "\\$&"); let regExp = new RegExp (inputElementValue, 'i'); // take the inputElement value and use it to filter the list let optionList = []; for (let option of this.options) { if (option.matchTarget.match (regExp)) { optionList.push ({ "value": option.value, "display": (option.value.length > 32) ? (option.value.substr (0, 30) + "...") : option.value, "label": option.label }); } } // now create the paged display this.optionsTable = PagedDisplay.Table.new ({ container: optionsElement, records: optionList, select: [ { name: "display", type: PagedDisplay.EntryType.LEFT_JUSTIFY, class: "combobox-option" }, { name: "label", type: PagedDisplay.EntryType.RIGHT_JUSTIFY, class: "combobox-option-label" } ], styles: this.styles, onclick: function (record) { inputElement.value = record.value; self.callOnChange(); return true; } }).makeTable (); return this; }; _.setOptions = function (options) { this.options = options; // get the list of options from the parameters, convert it to the expected format: // { value: "v", label: "m", alt:"xxx" }, and we create { value: "v", label: "m", matchTarget: "v, m, xxx" } let conditionedOptions = this.options = []; for (let option of options) { if (option === Object (option)) { let conditionedOption = { value: option.value, matchTarget: option.value }; if ("label" in option) { conditionedOption.label = option.label; conditionedOption.matchTarget += ", " + option.label; } if ("alt" in option) { conditionedOption.matchTarget += ", " + option.alt; } conditionedOptions.push (conditionedOption); } else { conditionedOptions.push ({ value: option, matchTarget: option }); } } // and start with the current option set to null this.currentOption = null; return this; }; // properties, to allow the combobox object to be used as a drop-in replacement for an // input element // "value" property Object.defineProperty (_, "value", { get: function () { return this.inputElement.value; }, set: function (value) { this.inputElement.value = value; } }); // onchange... Object.defineProperty (_, "onchange", { set: function (onchange) { this.inputElement.onchange = onchange; } }); // dispatchEvent // XXX this probably needs a little more thought _.dispatchEvent = function (event) { this.inputElement.dispatchEvent(event); }; return _; } (); Bedrock.Forms = function () { let _ = Object.create (Bedrock.Base); // import a few things let Html = Bedrock.Html; // strings used internally const INPUT = "-input-"; const ERROR = "-error-"; // strings for input types _.LIST = "list"; _.SELECT = "select"; _.TEXT = "text"; _.PASSWORD = "password"; _.SECRET = "secret"; _.CHECKBOX = "checkbox"; _.WILDCARD = "*"; _.init = function (parameters) { // scope "this" as self so I can use it in closures let scope = this; // parameters.name - name of the form (and the event to use when submitting) let formName = this.name = parameters.name; // parameters.onEnter - function to call when the user hits the enter key on an input // the default behavior is to call onClickSubmit if the callback returns true this.onEnter = ("onEnter" in parameters) ? parameters.onEnter : function () { return true; } // parameters.onCompletion - function to call when the user clicks submit and all the // input values pass validation this.onCompletion = parameters.onCompletion; // parameters.onUpdate - function to call when any value changes in the form if ("onUpdate" in parameters) { this.onUpdate = parameters.onUpdate; } // parameters.div - where to put the form let divElement = document.getElementById(parameters.div); divElement = Html.addElement(divElement, "div", { class : "form-container" }); // parameters.inputs - array of input names, with prompt, type, default value, template, and required flag // input = { name: "nm", type: "text|checkbox|select", label: "blah", required: true, (...values appropriate for input type...) } let inputs = this.inputs = {}; for (let input of parameters.inputs) { // create the div and set the title let formDivElement = Html.addElement (divElement, "div", { class: "form-div" }); Html.addElement (formDivElement, "div", { class: "form-title-div", innerHTML: input.label }); let parentDiv = Html.addElement (formDivElement, "div", { class: "form-input-div"}); // now add the actual input let inputObject = inputs[input.name] = { name: input.name, type: input.type, required: ("required" in input) ? input.required : false, visible: true }; let makeTextField = function(textType, style) { let value = ("value" in input) ? input.value : ""; inputObject.inputElement = Html.addElement (parentDiv, "input", { id: inputElementId, type: textType, class: "form-input", style: (typeof (style) !== "undefined") ? style : {}, placeholder: input.placeholder, value: value, events: { change: function () { scope.handleOnUpdate (input.name); }, keyup: function (event) { if (event.keyCode === 13) scope.handleEnterKey (); } } }); // this is a value stored for reset inputObject.originalValue = value; if ("pattern" in input) { inputObject.pattern = input.pattern; } }; // and the input element depending on the type let inputElementId = formName + "-" + Bedrock.Utility.randomString (8, "0123456789ABCDEF") + INPUT + input.name; switch (input.type) { case _.TEXT: case _.PASSWORD: { makeTextField(input.type); break; } case _.SECRET: { makeTextField(_.TEXT, { "-webkit-text-security" : "disc"}); break; } case _.CHECKBOX: { let checked = ("checked" in input) ? input.checked : false; inputObject.inputElement = Html.addElement (parentDiv, "input", { id: inputElementId, type: _.CHECKBOX, class: "form-input", checked: checked, events: { change: function () { scope.handleOnUpdate (input.name); }, keyup: function (event) { if (event.keyCode === 13) scope.handleEnterKey (); } } }); // this is a value stored for reset inputObject.originalValue = checked; break; } case _.SELECT: { let inputElement = inputObject.inputElement = Html.addElement (parentDiv, _.SELECT, { id: inputElementId, class: "form-input", events: { change: function () { scope.handleOnUpdate (input.name); }, keyup: function (event) { if (event.keyCode === 13) scope.handleEnterKey (); } } }); for (let option of input.options) { let value = (option === Object (option)) ? option.value : option; let label = ((option === Object (option)) && ("label" in option)) ? option.label : value; Html.addElement (inputElement, "option", { value: value, innerHTML: label }); } let value = ("value" in input) ? input.value : inputObject.inputElement.value; inputObject.inputElement.value = inputObject.originalValue = value; break; } case _.LIST: { let value = ("value" in input) ? input.value : ""; inputObject.inputElement = Bedrock.ComboBox.new ({ class: "form-input", parentElement: parentDiv, placeholder: input.placeholder, inputElementId: inputElementId, options: input.options, value: value, events: { change: function () { scope.handleOnUpdate (input.name); }, keyup: function (event) { if (event.keyCode === 13) scope.handleEnterKey (); } } }); // this is a value stored for reset inputObject.originalValue = value; if ("pattern" in input) { inputObject.pattern = input.pattern; } break; } } // and now add the error element inputObject.errorElement = Html.addElement (formDivElement, "div", { id: (formName + "-" + Bedrock.Utility.randomString (8, "0123456789ABCDEF") + ERROR + input.name), class: "form-error", innerHTML: inputObject.required ? "REQUIRED" : "" }); } // now add the submit button let formDivElement = Html.addElement (divElement, "div", { classes: ["form-div", "form-button-wrapper"] }); let submitButtonTitle = ("submitButtonValue" in parameters) ? parameters.submitButtonValue : "SUBMIT"; Html.addElement (formDivElement, "input", { type: "button", value: submitButtonTitle, class: "form-submit-button", onclick: function () { scope.handleClickSubmit (); } }); // and call the onUpdate the first time through this.handleOnUpdate (_.WILDCARD); return this; }; _.handleOnUpdate = function (updatedName) { if ("onUpdate" in this) { this.onUpdate (updatedName, this); } return this; }; _.handleEnterKey = function () { // call the onEnter handler, and if it returns true, call the click submit handler if (this.onEnter ()) { this.handleClickSubmit (); } }; _.handleClickSubmit = function () { // define the error condition let allValid = true; // check if all the required inputs are set correctly let inputNames = Object.keys(this.inputs); for (let inputName of inputNames) { let input = this.inputs[inputName]; if (input.required && input.visible) { let valid = true; switch (input.type) { case _.TEXT: case _.SECRET: case _.SELECT: case _.LIST: { if ("pattern" in input) { valid = (input.inputElement.value.match (input.pattern) !== null); } else { valid = (input.inputElement.value.length > 0); } break; } case _.CHECKBOX: { valid = input.inputElement.checked; break; } } input.errorElement.style.visibility = valid ? "hidden" : "visible"; allValid = allValid && valid; } } // call onCompletion if everything passes if (allValid === true) { this.onCompletion (this); } }; _.getValues = function (addEvent, includeInvisible) { let result = {}; if (Bedrock.Utility.defaultFalse(addEvent)) { result.event = this.name; } let keys = Object.keys (this.inputs); for (let key of keys) { let input = this.inputs[key]; if (input.visible || Bedrock.Utility.defaultFalse (includeInvisible)) { switch (input.type) { case _.CHECKBOX: result[input.name] = input.inputElement.checked; break; case _.TEXT: case _.SECRET: case _.SELECT: case _.LIST: if (input.inputElement.value.trim().length > 0) { result[input.name] = input.inputElement.value; } break; } } } return result; }; _.privateSetValue = function (key, value, callHandleOnUpdate) { let input = this.inputs[key]; switch (input.type) { case _.CHECKBOX: input.inputElement.checked = value; break; case _.TEXT: case _.SECRET: case _.SELECT: case _.LIST: input.inputElement.value = value; break; } // call on update defaults to true return Bedrock.Utility.defaultTrue (callHandleOnUpdate) ? this.handleOnUpdate (key) : this; }; _.setValue = function (key, value, callHandleOnUpdate) { if (key in this.inputs) { this.privateSetValue (key, value, callHandleOnUpdate); } return this; }; _.setValues = function (values, callHandleOnUpdate, strictSet) { // strictSet defaults to true strictSet = Bedrock.Utility.defaultTrue (strictSet); let keys = Object.keys (this.inputs); for (let key of Object.keys (this.inputs)) { if (key in values) { this.privateSetValue(key, values[key], false); } else if (strictSet) { this.privateSetValue(key, this.inputs[key].originalValue, false); } } // call on update defaults to true return Bedrock.Utility.defaultTrue (callHandleOnUpdate) ? this.handleOnUpdate (_.WILDCARD) : this; }; _.reset = function () { for (let inputName of Object.keys (this.inputs)) { this.privateSetValue(inputName, this.inputs[inputName].originalValue, false); } return this.handleOnUpdate(_.WILDCARD); }; _.showInput = function (key, show) { let input = this.inputs[key]; let elementStyle = input.inputElement.parentElement.parentElement.style; // all elements are visible when created, so this should happen the first time through if ((!("display" in input)) && (elementStyle.display !== "none")) { input.display = elementStyle.display; } // set the state show = Bedrock.Utility.defaultTrue (show); input.visible = show; elementStyle.display = show ? input.display : "none"; return this; }; _.hideInput = function (key) { return this.showInput(key, false); }; _.showOnlyInputs = function (keys, show) { // make an object out of the keys array let showHide = {}; for (let key of keys) { showHide[key] = 0; } // loop over all the inputs to show or hide them as requested for (let key in this.inputs) { this.showInput(key, (key in showHide) ? show : !show); } }; _.hideOnlyInputs = function (keys) { return this.showOnlyInputs(keys, false); }; return _; } (); // CompareFunctions are interfaces that take two values (a, b), and return a number as // follows: // a < b : negative // a = b : zero // a > b : positive Bedrock.CompareFunctions = function () { let $ = Bedrock.Enum.create ("NUMERIC", "ALPHABETIC", "CHRONOLOGIC", "AUTO"); // this is repeated several times, but I don't want it to be a function call let compareNumeric = function (a, b, asc) { // compare the values as numeric entities return asc ? (a - b) : (b - a); }; $.numeric = function (a = null, b = null, asc = true) { if (a === null) { return (b !== null) ? (asc ? -1 : 1) : 0; } if (b === null) { return (asc ? 1 : -1); }; return compareNumeric (a, b, asc); }; let compareAlphabetic = function (a, b, asc) { // compare case-insensitive strings with no spaces let ra = a.replace (/\s*/g, "").toLowerCase (); let rb = b.replace (/\s*/g, "").toLowerCase (); return asc ? ra.localeCompare (rb) : rb.localeCompare (ra); }; $.alphabetic = function (a = null, b = null, asc = true) { if (a === null) { return (b !== null) ? (asc ? -1 : 1) : 0; } if (b === null) { return (asc ? 1 : -1); }; return compareAlphabetic (a, b, asc); }; $.chronologic = function (a = null, b = null, asc = true) { if (a === null) { return (b !== null) ? (asc ? -1 : 1) : 0; } if (b === null) { return (asc ? 1 : -1); }; // convert the dates/timestamps to numerical values for comparison return compareNumeric (new Date (a).valueOf (), new Date (b).valueOf (), asc); }; $.auto = function (a = null, b = null, asc = true) { if (a === null) { return (b !== null) ? (asc ? -1 : 1) : 0; } if (b === null) { return (asc ? 1 : -1); }; // try to compare the values as numerical if we can let na = Number (a), nb = Number (b); if ((na.toString () === a.toString ()) && (nb.toString () === b.toString ())) { return compareNumeric (na, nb, asc); } // otherwise do it alphabetic return compareAlphabetic (a, b, asc); }; $.get = function (type = $.AUTO) { switch (type) { case $.NUMERIC: return this.numeric; case $.ALPHABETIC: return this.alphabetic; case $.CHRONOLOGIC: return this.chronologic; default: case $.AUTO: return this.auto; } throw "Unknown type (" + type + ")"; }; $.compare = function (a, b, asc, type) { return this.get (type) (a, b, asc); }; $.mask = function (compareResult) { return (compareResult < 0) ? 0b0001 : (compareResult > 0) ? 0b0100 : 0b0010; }; $.operationMask = function (operation) { switch (operation.toLowerCase ()) { case "lt": case "<": return 0b0001; case "lte": case "<=": return 0b0011; case "eq": case "=": case "==": return 0b0010; case "gte": case ">=": return 0b0110; case "gt": case ">": return 0b0100; case "ne": case "neq": case "<>": case "!=": case "!": return 0b0101; } throw "Unknown operation (" + operation + ")"; }; return $; } (); Bedrock.Comparable = function () { let $ = Object.create(null); $.FieldComparable = function () { let _ = Object.create(Bedrock.Base); _.init = function (parameters) { this.compareFunction = Bedrock.CompareFunctions.get(parameters.type); // allow the user to specify either ascending or descending this.ascending = ("ascending" in parameters) ? parameters.ascending : true; this.ascending = ("descending" in parameters) ? (! parameters.descending) : this.ascending; this.name = parameters.name; return this; }; _.compare = function (recordA, recordB) { return this.compareFunction(recordA[this.name], recordB[this.name], this.ascending); }; return _; }(); $.RecordComparable = function () { let _ = Object.create(Bedrock.Base); _.init = function (parameters) { let fc = this.fieldComparables = []; for (let field of parameters.fields) { fc.push(Bedrock.Comparable.FieldComparable.new(field)); } return this; }; _.compare = function (recordA, recordB) { for (let fieldComparable of this.fieldComparables) { let sortResult = fieldComparable.compare(recordA, recordB); if (sortResult != 0) { return sortResult; } } return 0; }; return _; }(); return $; } (); Bedrock.DatabaseOperations = function () { let $ = Object.create (null); // "using" let CompareFunctions = Bedrock.CompareFunctions; let maskFunction = CompareFunctions.mask; //------------------------------------------------------------------------------------ // Filter is an interface specification for something that takes an array of objects // (AKA a database) as input, and returns a new database. Typical operations performed // by filters are "select" and "sort". More complex operations are accomplished by // hierarchical combinations of these basic filters. Filters do their work lazily, // when the user calls the "perform" method. The default filter implementation is a // passthrough for a "source". $.Filter = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { return this; }; _.perform = function (database) { return database; }; return _; } (); //------------------------------------------------------------------------------------ // Match is a filter that does a linear time walk over the rows of the database and // checks every record to see if the requested field matches a given pattern. The // result can be inverted to flip the sense of the match operation. $.Match = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.field = parameters.field; // initialize the shouldMatch property let invert = "invert" in parameters ? parameters.invert : false; this.shouldMatch = ! parameters.invert; // compile the match paramter... we assume the user doesn't intend this to be // a regular expression if it fails to compile. try { this.regExp = new RegExp (parameters.match, "i"); } catch (error) { // replace regexp characters with escaped versions of themselves // XXX We might want to give the option to ignore case in the future. this.regExp = new RegExp (parameters.match.replace (/[\-\[\]{}()*+?.,\\\^$\|#\s]/g, "\\$&"), "i"); } return this; }; _.perform = function (database) { let result = []; // hoist the frequently used fields into the current context let field = this.field; let regExp = this.regExp; let shouldMatch = this.shouldMatch; // create the individual filter function... let matchValue = function (value) { let matchResult = value.toString().match (regExp); return ((matchResult != null) === true); }; // loop over all the records to see what passes for (let record of database) { // only pass records that contain the search field let match = (field in record); if (match === true) { // get the value from the record, it might be a value, or an array of // values, so we have to check and handle accordingly let values = record[field]; if (values instanceof Array) { match = false; for (let value of values) { match = match || matchValue (value); } } else { match = matchValue (values); } } // if we match, store the record into the result if (match === shouldMatch) { result.push (record); } } // return the result return result; }; return _; } (); //------------------------------------------------------------------------------------ // Compare is a filter that does a linear time walk over the rows of the database and // checks every record to see if the requested field compares favorably to a given // value. $.Compare = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.field = parameters.field; this.operationMask = CompareFunctions.operationMask (("operation" in parameters) ? parameters.operation : "="); this.compareFunction = CompareFunctions.get (("type" in parameters) ? parameters.type : "auto"); this.value = parameters.value; return this; }; _.perform = function (database) { let result = []; // hoist the frequently used parameters into the current context let field = this.field; let operationMask = this.operationMask; let compareFunction = this.compareFunction; let value = this.value; // loop over all the records to see what passes for (let record of database) { if (field in record) { let compareResult = compareFunction (record[field], value); let maskedCompareResult = mask (compareResult); if ((maskedCompareResult & operationMask) != 0) { result.push (record); } } } // return the result return result; }; return _; } (); //------------------------------------------------------------------------------------ // CompareSorted is a filter that does a log (n) time traversal of a database sorted // on the requested field, to find where the given value divides the sorted list. // NOTE: the database must already be sorted when it comes in. $.CompareSorted = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.field = parameters.field; this.operationMask = CompareFunctions.operationMask (("operation" in parameters) ? parameters.operation : "="); this.compareFunction = CompareFunctions.get (("type" in parameters) ? parameters.type : "auto"); this.value = parameters.value; return this; }; _.perform = function (database) { // hoist the frequently used parameters into the current context let field = this.field; let operationMask = this.operationMask; let compareFunction = this.compareFunction; let value = this.value; let end = database.length; // find the lower bound of the search region let findLowerBound = function (low, high) { while (low <= high) { let mid = (low + high) >>> 1; let cmp = (mid < end) ? compareFunction (database[mid][field], value, true) : 1; if (cmp < 0) { low = mid + 1; } else { high = mid - 1; } } return low; }; // find the upper bound of the search region let findUpperBound = function (low, high) { while (low <= high) { let mid = (low + high) >>> 1; let cmp = (mid < end) ? compareFunction (database[mid][field], value, true) : 1; if (cmp <= 0) { low = mid + 1; } else { high = mid - 1; } } return low; }; // find where the comparison points are, then decide how to slice the result let upperBound; switch (operationMask) { case 0b0001: // < // take from 0 to lower bound return database.slice (0, findLowerBound (0, end)); case 0b0011: // <= // take from 0 to upper bound return database.slice (0, findUpperBound (0, end)); case 0b0010: // = // take from lower bound to upper bound upperBound = findUpperBound (0, end); return database.slice (findLowerBound (0, upperBound), upperBound); case 0b0110: // >= // take from lower bound to end return database.slice (findLowerBound (0, end)); case 0b0100: // > // take from upper bound to end return database.slice (findUpperBound (0, end)); case 0b0101: // <> // take from 0 to lower bound, and upper bound to end upperBound = findUpperBound (0, end); return database.slice (0, findLowerBound (0, upperBound)).concat (database.slice (upperBound)); } // return the result return result; }; return _; } (); //------------------------------------------------------------------------------------ // And is a filter that runs each filter in a list in turn. Same as "Intersect". $.And = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.filters = parameters.filters; return this; }; _.perform = function (database) { for (let filter of this.filters) { database = filter.perform (database); } return database; }; return _; } (); //------------------------------------------------------------------------------------ // Or is a filter that runs each filter in a list, and then merges the results on a // given field. Same as "Union" or "Unique". NOTE, this assumes the given field is a // unique identifier for each record, like an "identity". $.Or = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.filters = parameters.filters; this.field = parameters.field; return this; }; _.perform = function (database) { let resultKey = {}; let result = []; // hoist frequently used variables to the current context let field = this.field; // loop over all of the filters for (let filter of this.filters) { let filteredDatabase = filter.perform (database); for (let record of filteredDatabase) { // only store records that have the requested field if (field in record) { // and now, only store this record in the result if it's not // already in there... let key = record[field]; if (!(key in resultKey)) { resultKey[key] = key; result.push (record); // XXX I wonder if there is an optimization to be made by // XXX removing the found record from the source database, so // XXX we don't bother to filter it through the next one in // XXX the list } } } } return result; }; return _; } (); //------------------------------------------------------------------------------------ // Sort is a filter that sorts the database according to its parameters. $.Sort = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.recordComparable = Bedrock.Comparable.RecordComparable.new (parameters); return this; }; _.perform = function (database) { let newDatabase = database.slice (); let that = this; newDatabase.sort (function (recordA, recordB) { return that.recordComparable.compare (recordA, recordB); }); return newDatabase; }; return _; } (); //------------------------------------------------------------------------------------ // Range is a filter that composes a Sort and two CompareSorted filters into an AND // filter. $.Range = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.field = parameters.field; this.type = parameters.type; // numeric, alphabetic, chronologic, auto this.min = parameters.min; this.max = parameters.max; let sort = $.Sort.new ({ fields: [ { name: parameters.field, type: parameters.type }] }); let min = $.CompareSorted.new ({ field: parameters.field, operation: "gte", type: parameters.type, value: parameters.min }); let max = $.CompareSorted.new ({ field: parameters.field, operation: "lte", type: parameters.type, value: parameters.max }); let and = $.And.new ({ filters: [sort, min, max] }); this.filter = and; return this; }; _.perform = function (database) { return this.filter.perform (database); }; return _; } (); //------------------------------------------------------------------------------------ // Select is a reduction filter that performs a linear time walk over the records of // the database and selects only the requested fields for the new database. $.Select = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { return this; }; _.perform = function (database) { return database; }; return _; } (); return $; } (); Bedrock.Database = function () { let $ = Object.create (null); let Html = Bedrock.Html; // getAllFields - traverses an array of objects to produce an object that contains all // the field names, and all the associated values of each field $.getAllFields = function (database) { let allFields = {}; for (let record of database) { let fields = Object.keys (record).sort (); for (let field of fields) { // make sure there is a field collector if (!(field in allFields)) { allFields[field] = Object.create (null); } // put the value in, all the individual values if it's an array let values = record[field]; if (values instanceof Array) { for (let value of values) { allFields[field][value] = value; } } else { allFields[field][values] = values; } } } // now replace each entry with a sorted array of its keys, and then save it let fields = Object.keys (allFields); for (let field of fields) { allFields[field] = Object.keys (allFields[field]).sort (); } return allFields; }; //------------------------------------------------------------------------------------ // Source is an interface declaration for something that returns a database $.Source = function () { let _ = Object.create (Bedrock.Base); _.init = function (database) { this.database = database; return this; }; _.getDatabase = function () { return this.database; }; return _; } (); //------------------------------------------------------------------------------------ // database filter element is a single part of a deep tree query, they are grouped // together to build complex AND-based reduction operations $.FilterElement = function () { let _ = Object.create (Bedrock.Base); let doFilter = function (database, filterField, filterValue, shouldMatch = true) { let result = []; // if the search key is not specified, this is a pass-through filter, just return // what we started with if (filterField.length === 0) { return database; } // the individual filter function... we assume the user doesn't intend this to // be a regexp if it fails to compile let regExp; try { regExp = new RegExp (filterValue, 'i'); } catch (error) { regExp = new RegExp (filterValue.replace (/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"), 'i') } let matchValue = function (value) { let matchResult = value.toString().match (regExp); return ((matchResult != null) === shouldMatch); }; // otherwise, loop over all the records to see what passes for (let record of database) { // only pass records that contain the search key let match = (filterField in record); if (match === true) { // get the value from the record, it might be a value, or an array of // values, so we have to check and handle accordingly let values = record[filterField]; if (values instanceof Array) { let anyMatches = false; for (let value of values) { anyMatches = anyMatches || matchValue (value); } match = match && anyMatches; } else { match = match && matchValue (values); } } // if we match, store the record into the result if (match === true) { result.push (record); } } // return the result return result; }; const FILTER_ELEMENT_FIELD = "filter-element-field"; const FILTER_ELEMENT_VALUE = "filter-element-value"; _.init = function (parameters) { // scope this so I can use it in closures let scope = this; let index = this.index = parameters.index; this.databaseSource = parameters.databaseSource; this.owner = parameters.owner; let filterField = parameters.initialValue.field; let filterValue = parameters.initialValue.value; let fieldKeys = parameters.fieldKeys; // create the element container this.elementContainer = Html.addElement (parameters.div, "div", { class: "bedrock-database-element-container", id: "filterElementContainer" + index }); // create the select and editing elements inside the container this.countDiv = Html.addElement (this.elementContainer, "div", { class: "bedrock-database-element-text-div" }); //this.fieldComboBox = addComboBoxElement (this.elementContainer, FILTER_ELEMENT_FIELD + index, fieldKeys, filterField, "FILTER FIELD"); let fieldComboBox = this.fieldComboBox = Bedrock.ComboBox.new ({ style: { width: "100%" }, parentElementId: this.elementContainer.id, placeholder: "(FILTER FIELD)", inputElementId: FILTER_ELEMENT_FIELD + index, options: fieldKeys, value: filterField, onchange: function () { scope.valueComboBox.value = ""; scope.update (); } }); let database = this.databaseSource.getDatabase (); let allFields = $.getAllFields (database); //this.valueElement = addComboBoxElement(this.elementContainer, FILTER_ELEMENT_VALUE + index, (filterField in allFields) ? allFields[filterField] : [], filterValue, "FILTER VALUE"); let valueComboBox = this.valueComboBox = Bedrock.ComboBox.new ({ style: { width: "100%" }, parentElementId: this.elementContainer.id, placeholder: "(FILTER VALUE)", inputElementId: FILTER_ELEMENT_VALUE + index, options: (filterField in allFields) ? allFields[filterField] : [], value: filterValue, onchange: function () { scope.finishUpdate (); } }); this.filteredDatabase = doFilter (database, filterField, filterValue, true); this.countDiv.innerHTML = this.filteredDatabase.length + "/" + database.length; return this; }; _.update = function () { // rebuild the value options let database = this.databaseSource.getDatabase (); let allFields = $.getAllFields (database); this.valueComboBox.setOptions ((this.fieldComboBox.value in allFields) ? allFields[this.fieldComboBox.value] : []); this.finishUpdate (); }; _.finishUpdate = function () { let database = this.databaseSource.getDatabase (); this.filteredDatabase = doFilter (database, this.fieldComboBox.value, this.valueComboBox.value, true); this.countDiv.innerHTML = this.filteredDatabase.length + "/" + database.length; this.owner.push (this.index); }; _.onValueChange = function (updatedControl) { this.update (); }; _.getDatabase = function () { return this.filteredDatabase; }; _.setFieldValue = function (filterField, filterValue) { // set the filter field value this.fieldComboBox.value = filterField; // rebuild the value select let database = this.databaseSource.getDatabase (); let allFields = $.getAllFields (database); this.valueComboBox .setOptions ((this.fieldComboBox.value in allFields) ? allFields[this.fieldComboBox.value] : []) .value = filterValue; }; return _; } (); //------------------------------------------------------------------------------------ $.SortElement = function () { let _ = Object.create (Bedrock.Base); let makeControls = function (index, field, type, asc, fieldKeys) { let innerHTML = div ("bedrock-element-div", makeSelectHTML ("sortElementSelectKey" + index, fieldKeys, field, "SORT FIELD")) + div ("bedrock-element-div", makeSelectHTML ("sortElementSelectType" + index, ["AUTO", "NUMERIC", "ALPHABETIC", "DATE"], type, "SORT TYPE")) + div ("bedrock-element-div", makeSelectHTML ("sortElementSelectAsc" + index, ["ASCENDING", "DESCENDING"], asc, "SORT ASC")); return innerHTML; }; _.init = function (parameters) { this.index = parameters.index; this.owner = parameters.owner; this.sortField = parameters.sortField; this.sortType = parameters.sortType; this.sortAsc = parameters.sortAsc; // create the select and editing elements inside the supplied div id document.getElementById ("sortElementContainer" + parameters.index).innerHTML = makeControls (parameters.index, this.sortField, this.sortType, this.sortAsc, parameters.fieldKeys); return this; }; return _; } (); //------------------------------------------------------------------------------------ $.Filter = function () { let _ = Object.create (Bedrock.Base); let conditionValues = function (values = [], elementCount = 0) { for (let i = values.length; i < elementCount; ++i) { values.push ({}); } for (let value of values) { value.field = ("field" in value) ? value.field : ""; value.value = ("value" in value) ? value.value : ""; } return values; }; _.init = function (parameters) { this.databaseSource = parameters.databaseSource; this.elementCount = parameters.elementCount; this.owner = parameters.owner; this.fieldKeys = parameters.fieldKeys; this.initialValues = conditionValues (parameters.initialValues, parameters.elementCount); return this.reset (); }; _.finish = function () { // hide unused filter elements and call out to the parent let filters = this.filters; let length = filters.length; let index = length - 1; // this was the last one, reverse up the list looking for the last full filter while ((filters[index].fieldComboBox.value.length == 0) && (index > 0)) { --index; } if (filters[index].fieldComboBox.value.length > 0) { ++index; } if (index < length) { filters[index].elementContainer.style.display = "inline-block"; while (++index < length) { filters[index].elementContainer.style.display = "none"; } } // and finally call the outbound push this.owner.push (this.getDatabase ()); }; _.push = function (index) { let filters = this.filters; let length = filters.length; if ((index + 1) < length) { filters[index + 1].update (); } else { // notify the receiver we've finished updating this.finish (); } return this; }; _.update = function () { return this.push (-1); }; _.onValueChange = function (updatedControl) { let index = updatedControl.id.match (/\d+$/)[0]; this.filters[index].onValueChange (updatedControl); }; _.getDatabase = function () { return this.filters[this.filters.length - 1].getDatabase (); }; _.setValues = function (values) { let elementCount = this.elementCount; let filters = this.filters; values = conditionValues (values, elementCount); for (let i = 0; i < elementCount; ++i) { filters[i].setFieldValue (values[i].field, values[i].value); } return this.update (); }; _.reset = function () { // scope this so I can use it in closures let scope = this; // get the filter container and clean it out let filterContainer = document.getElementById ("filterContainer"); while (filterContainer.firstChild) { filterContainer.removeChild (filterContainer.firstChild); } // now create the filter elements this.filters = []; for (let index = 0; index < this.elementCount; ++index) { this.filters.push ($.FilterElement.new ({ div: filterContainer, index: index, fieldKeys: this.fieldKeys, initialValue: this.initialValues[index], databaseSource: (index > 0) ? this.filters[index - 1] : this.databaseSource, owner: this })); } // drop in the clear button let clearButtonElementContainer = Html.addElement (filterContainer, "div", { class: "bedrock-database-element-container" }); Html.addElement (clearButtonElementContainer, "div", { class: "bedrock-database-element-text-div" }); Html.addElement (clearButtonElementContainer, "button", { class: "bedrock-database-clear-button", onclick: function () { scope.reset (); } }).innerHTML = "CLEAR"; // and notify the receiver that we've finished setting up this.finish (); return this; }; return _; } (); //------------------------------------------------------------------------------------ $.Sort = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.elementCount = parameters.elementCount; this.owner = parameters.owner; this.fieldKeys = parameters.fieldKeys; // create the select and editing elements let sortContainerHTML = ""; for (let index = 0; index < this.elementCount; ++index) { sortContainerHTML += block ("div", { class: "bedrock-database-element-container", id: "sortElementContainer" + index }, ""); } // drop in the clear button sortContainerHTML += div ("bedrock-database-element-container", div ("bedrock-database-element-text-div", "") + div ("bedrock-element-div", block ("button", { class: "bedrockClearButton", type: "button", onclick: "theBedrock.sort.reset ();" }, "CLEAR") ) ); document.getElementById ("sortContainer").innerHTML = sortContainerHTML; this.sorts = []; for (let index = 0; index < this.elementCount; ++index) { this.sorts.push ($.SortElement.new ({ index: index, fieldKeys: this.fieldKeys, owner: this, sortField: "", sortType: "", sortAsc: "" })); } return this; }; return _; } (); $.Container = function () { let _ = Object.create (Bedrock.Base); _.init = function (parameters) { this.databaseSource = $.Source.new (parameters.database); this.fieldKeys = Object.keys ($.getAllFields (parameters.database)).sort (); this.onUpdate = parameters.onUpdate; // get the top level container let bedrockContainerId = ("div" in parameters) ? parameters.div : "bedrock-database-container"; let bedrockContainer = document.getElementById (bedrockContainerId); Html.addElement (bedrockContainer, "div", { class: "bedrock-database-group-container", id: "filterContainer" }); Html.addElement (bedrockContainer, "div", { class: "bedrock-database-group-container", id: "sortContainer" }); // create the filter this.filter = $.Filter.new ({ databaseSource: this.databaseSource, fieldKeys: this.fieldKeys, owner: this, elementCount: (parameters.filterElementCount !== undefined) ? parameters.filterElementCount : 4, initialValues: parameters.filterValues }); /* // create the sort control this.sort = $.Sort.new ({ databaseSource: this.databaseSource, fieldKeys: this.fieldKeys, owner: this, elementCount: (typeof parameters.sortElementCount !== "undefined") ? parameters.sortElementCount : 2, initialValues: parameters.sortValues, }); */ return this; }; _.push = function (db) { // do the sort // pass the result on to the update handler this.onUpdate (db); }; return _; } (); return $; } ();
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var NumberField_1 = require("../field/NumberField"); var Relation_1 = require("./Relation"); var Appliable_1 = require("../field/Appliable"); var Joins_1 = require("./Joins"); var QNumberManyToOneRelation = (function (_super) { __extends(QNumberManyToOneRelation, _super); function QNumberManyToOneRelation(q, qConstructor, entityName, fieldName, relationEntityConstructor, relationQEntityConstructor) { _super.call(this, q, qConstructor, entityName, fieldName, Appliable_1.JSONClauseObjectType.MANY_TO_ONE_RELATION); this.q = q; this.qConstructor = qConstructor; this.entityName = entityName; this.fieldName = fieldName; this.relationEntityConstructor = relationEntityConstructor; this.relationQEntityConstructor = relationQEntityConstructor; this.relationType = Relation_1.EntityRelationType.MANY_TO_ONE; } QNumberManyToOneRelation.prototype.getInstance = function (qEntity) { if (qEntity === void 0) { qEntity = this.q; } var relation = new QNumberManyToOneRelation(qEntity, this.qConstructor, this.entityName, this.fieldName, this.relationEntityConstructor, this.relationQEntityConstructor); return this.copyFunctions(relation); }; QNumberManyToOneRelation.prototype.innerJoin = function () { return this.getNewQEntity(Joins_1.JoinType.INNER_JOIN); }; QNumberManyToOneRelation.prototype.leftJoin = function () { return this.getNewQEntity(Joins_1.JoinType.LEFT_JOIN); }; QNumberManyToOneRelation.prototype.getNewQEntity = function (joinType) { var newQEntity = new this.relationQEntityConstructor(this.relationQEntityConstructor, this.relationEntityConstructor, this.entityName, Relation_1.QRelation.getNextChildJoinPosition(this.q), this.fieldName, joinType); newQEntity.parentJoinEntity = this.q; return newQEntity; }; return QNumberManyToOneRelation; }(NumberField_1.QNumberField)); exports.QNumberManyToOneRelation = QNumberManyToOneRelation; //# sourceMappingURL=NumberManyToOneRelation.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:3096a1d89f03cd96c92b7a90b529301ac52bc0659b9023a53da136376bd2e932 size 12754
!function(o){o.TheaterJS.prototype.keyboards.pt=["qwertyuiop","asdfghjklç","zxcvbnm"]}(window);
'use strict'; var fs = require('fs'); module.exports = { secure: { ssl: false, // it was true by default privateKey: './config/sslcerts/key.pem', certificate: './config/sslcerts/cert.pem', caBundle: './config/sslcerts/cabundle.crt' }, port: process.env.PORT || 3001, // Binding to 127.0.0.1 is safer in production. host: process.env.HOST || '0.0.0.0', domain: 'http://rastemoh.ir', sessionSecret: process.env.SESSION_SECRET || '6cbeaa03a726bb4ed7fca0c8a9a28632', db: { uri: process.env.MONGOHQ_URL || process.env.MONGODB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean', options: { user: '', pass: '' /** * Uncomment to enable ssl certificate based authentication to mongodb * servers. Adjust the settings below for your specific certificate * setup. server: { ssl: true, sslValidate: false, checkServerIdentity: false, sslCA: fs.readFileSync('./config/sslcerts/ssl-ca.pem'), sslCert: fs.readFileSync('./config/sslcerts/ssl-cert.pem'), sslKey: fs.readFileSync('./config/sslcerts/ssl-key.pem'), sslPass: '1234' } */ }, // Enable mongoose debug mode debug: process.env.MONGODB_DEBUG || false }, log: { // logging with Morgan - https://github.com/expressjs/morgan // Can specify one of 'combined', 'common', 'dev', 'short', 'tiny' format: process.env.LOG_FORMAT || 'combined', fileLogger: { directoryPath: process.env.LOG_DIR_PATH || process.cwd(), fileName: process.env.LOG_FILE || 'app.log', maxsize: 10485760, maxFiles: 2, json: false } }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/api/auth/facebook/callback' }, twitter: { username: '@TWITTER_USERNAME', clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/api/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/api/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/api/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/api/auth/github/callback' }, paypal: { clientID: process.env.PAYPAL_ID || 'CLIENT_ID', clientSecret: process.env.PAYPAL_SECRET || 'CLIENT_SECRET', callbackURL: '/api/auth/paypal/callback', sandbox: false }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } }, seedDB: { seed: process.env.MONGO_SEED === 'true', options: { logResults: process.env.MONGO_SEED_LOG_RESULTS !== 'false', seedUser: { username: process.env.MONGO_SEED_USER_USERNAME || 'seeduser', provider: 'local', email: process.env.MONGO_SEED_USER_EMAIL || 'user@localhost.com', firstName: 'User', lastName: 'Local', displayName: 'User Local', roles: ['user'] }, seedAdmin: { username: process.env.MONGO_SEED_ADMIN_USERNAME || 'seedadmin', provider: 'local', email: process.env.MONGO_SEED_ADMIN_EMAIL || 'admin@localhost.com', firstName: 'Admin', lastName: 'Local', displayName: 'Admin Local', roles: ['user', 'admin'] } } } };
'use strict' // Default configuration module.exports = { model: { iterations: 100 }, watch: false, filepath: null, minifyify: { map: false } }
var debug = function () {}; /*! * refs */ var SLICE = Array.prototype.slice; var CONCAT = Array.prototype.concat; var ALL_EVENT = '__all__'; /** * EventProxy. An implementation of task/event based asynchronous pattern. * A module that can be mixed in to *any object* in order to provide it with custom events. * You may `bind` or `unbind` a callback function to an event; * `trigger`-ing an event fires all callbacks in succession. * Examples: * ```js * var render = function (template, resources) {}; * var proxy = new EventProxy(); * proxy.assign("template", "l10n", render); * proxy.trigger("template", template); * proxy.trigger("l10n", resources); * ``` */ var EventProxy = function () { if (!(this instanceof EventProxy)) { return new EventProxy(); } this._callbacks = {}; this._fired = {}; }; /** * Bind an event, specified by a string name, `ev`, to a `callback` function. * Passing __ALL_EVENT__ will bind the callback to all events fired. * Examples: * ```js * var proxy = new EventProxy(); * proxy.addListener("template", function (event) { * // TODO * }); * ``` * @param {String} eventname Event name. * @param {Function} callback Callback. */ EventProxy.prototype.addListener = function (ev, callback) { debug('Add listener for %s', ev); this._callbacks[ev] = this._callbacks[ev] || []; this._callbacks[ev].push(callback); return this; }; /** * `addListener` alias, `bind` */ EventProxy.prototype.bind = EventProxy.prototype.addListener; /** * `addListener` alias, `on` */ EventProxy.prototype.on = EventProxy.prototype.addListener; /** * `addListener` alias, `subscribe` */ EventProxy.prototype.subscribe = EventProxy.prototype.addListener; /** * Bind an event, but put the callback into head of all callbacks. * @param {String} eventname Event name. * @param {Function} callback Callback. */ EventProxy.prototype.headbind = function (ev, callback) { debug('Add listener for %s', ev); this._callbacks[ev] = this._callbacks[ev] || []; this._callbacks[ev].unshift(callback); return this; }; /** * Remove one or many callbacks. * * - If `callback` is null, removes all callbacks for the event. * - If `eventname` is null, removes all bound callbacks for all events. * @param {String} eventname Event name. * @param {Function} callback Callback. */ EventProxy.prototype.removeListener = function (eventname, callback) { var calls = this._callbacks; if (!eventname) { debug('Remove all listeners'); this._callbacks = {}; } else { if (!callback) { debug('Remove all listeners of %s', eventname); calls[eventname] = []; } else { var list = calls[eventname]; if (list) { var l = list.length; for (var i = 0; i < l; i++) { if (callback === list[i]) { debug('Remove a listener of %s', eventname); list[i] = null; } } } } } return this; }; /** * `removeListener` alias, unbind */ EventProxy.prototype.unbind = EventProxy.prototype.removeListener; /** * Remove all listeners. It equals unbind() * Just add this API for as same as Event.Emitter. * @param {String} event Event name. */ EventProxy.prototype.removeAllListeners = function (event) { return this.unbind(event); }; /** * Bind the ALL_EVENT event */ EventProxy.prototype.bindForAll = function (callback) { this.bind(ALL_EVENT, callback); }; /** * Unbind the ALL_EVENT event */ EventProxy.prototype.unbindForAll = function (callback) { this.unbind(ALL_EVENT, callback); }; /** * Trigger an event, firing all bound callbacks. Callbacks are passed the * same arguments as `trigger` is, apart from the event name. * Listening for `"all"` passes the true event name as the first argument. * @param {String} eventname Event name * @param {Mix} data Pass in data */ EventProxy.prototype.trigger = function (eventname, data) { var list, ev, callback, i, l; var both = 2; var calls = this._callbacks; debug('Emit event %s with data %j', eventname, data); while (both--) { ev = both ? eventname : ALL_EVENT; list = calls[ev]; if (list) { for (i = 0, l = list.length; i < l; i++) { if (!(callback = list[i])) { list.splice(i, 1); i--; l--; } else { var args = []; var start = both ? 1 : 0; for (var j = start; j < arguments.length; j++) { args.push(arguments[j]); } callback.apply(this, args); } } } } return this; }; /** * `trigger` alias */ EventProxy.prototype.emit = EventProxy.prototype.trigger; /** * `trigger` alias */ EventProxy.prototype.fire = EventProxy.prototype.trigger; /** * Bind an event like the bind method, but will remove the listener after it was fired. * @param {String} ev Event name * @param {Function} callback Callback */ EventProxy.prototype.once = function (ev, callback) { var self = this; var wrapper = function () { callback.apply(self, arguments); self.unbind(ev, wrapper); }; this.bind(ev, wrapper); return this; }; var later = typeof process !== 'undefined' && process.nextTick || function (fn) { setTimeout(fn, 0); }; /** * emitLater * make emit async */ EventProxy.prototype.emitLater = function () { var self = this; var args = arguments; later(function () { self.trigger.apply(self, args); }); }; /** * Bind an event, and trigger it immediately. * @param {String} ev Event name. * @param {Function} callback Callback. * @param {Mix} data The data that will be passed to calback as arguments. */ EventProxy.prototype.immediate = function (ev, callback, data) { this.bind(ev, callback); this.trigger(ev, data); return this; }; /** * `immediate` alias */ EventProxy.prototype.asap = EventProxy.prototype.immediate; var _assign = function (eventname1, eventname2, cb, once) { var proxy = this; var argsLength = arguments.length; var times = 0; var flag = {}; // Check the arguments length. if (argsLength < 3) { return this; } var events = SLICE.call(arguments, 0, -2); var callback = arguments[argsLength - 2]; var isOnce = arguments[argsLength - 1]; // Check the callback type. if (typeof callback !== "function") { return this; } debug('Assign listener for events %j, once is %s', events, !!isOnce); var bind = function (key) { var method = isOnce ? "once" : "bind"; proxy[method](key, function (data) { proxy._fired[key] = proxy._fired[key] || {}; proxy._fired[key].data = data; if (!flag[key]) { flag[key] = true; times++; } }); }; var length = events.length; for (var index = 0; index < length; index++) { bind(events[index]); } var _all = function (event) { if (times < length) { return; } if (!flag[event]) { return; } var data = []; for (var index = 0; index < length; index++) { data.push(proxy._fired[events[index]].data); } if (isOnce) { proxy.unbindForAll(_all); } debug('Events %j all emited with data %j', events, data); callback.apply(null, data); }; proxy.bindForAll(_all); }; /** * Assign some events, after all events were fired, the callback will be executed once. * * Examples: * ```js * proxy.all(ev1, ev2, callback); * proxy.all([ev1, ev2], callback); * proxy.all(ev1, [ev2, ev3], callback); * ``` * @param {String} eventname1 First event name. * @param {String} eventname2 Second event name. * @param {Function} callback Callback, that will be called after predefined events were fired. */ EventProxy.prototype.all = function (eventname1, eventname2, callback) { var args = CONCAT.apply([], arguments); args.push(true); _assign.apply(this, args); return this; }; /** * `all` alias */ EventProxy.prototype.assign = EventProxy.prototype.all; /** * Assign the only one 'error' event handler. * @param {Function(err)} callback */ EventProxy.prototype.fail = function (callback) { var that = this; that.once('error', function (err) { that.unbind(); // put all arguments to the error handler // fail(function(err, args1, args2, ...){}) callback.apply(null, arguments); }); return this; }; /** * Assign some events, after all events were fired, the callback will be executed first time. * Then any event that predefined be fired again, the callback will executed with the newest data. * Examples: * ```js * proxy.tail(ev1, ev2, callback); * proxy.tail([ev1, ev2], callback); * proxy.tail(ev1, [ev2, ev3], callback); * ``` * @param {String} eventname1 First event name. * @param {String} eventname2 Second event name. * @param {Function} callback Callback, that will be called after predefined events were fired. */ EventProxy.prototype.tail = function () { var args = CONCAT.apply([], arguments); args.push(false); _assign.apply(this, args); return this; }; /** * `tail` alias, assignAll */ EventProxy.prototype.assignAll = EventProxy.prototype.tail; /** * `tail` alias, assignAlways */ EventProxy.prototype.assignAlways = EventProxy.prototype.tail; /** * The callback will be executed after the event be fired N times. * @param {String} eventname Event name. * @param {Number} times N times. * @param {Function} callback Callback, that will be called after event was fired N times. */ EventProxy.prototype.after = function (eventname, times, callback) { if (times === 0) { callback.call(null, []); return this; } var proxy = this, firedData = []; this._after = this._after || {}; var group = eventname + '_group'; this._after[group] = { index: 0, results: [] }; debug('After emit %s times, event %s\'s listenner will execute', times, eventname); var all = function (name, data) { if (name === eventname) { times--; firedData.push(data); if (times < 1) { debug('Event %s was emit %s, and execute the listenner', eventname, times); proxy.unbindForAll(all); callback.apply(null, [firedData]); } } if (name === group) { times--; proxy._after[group].results[data.index] = data.result; if (times < 1) { debug('Event %s was emit %s, and execute the listenner', eventname, times); proxy.unbindForAll(all); callback.call(null, proxy._after[group].results); } } }; proxy.bindForAll(all); return this; }; /** * The `after` method's helper. Use it will return ordered results. * If you need manipulate result, you need callback * Examples: * ```js * var ep = new EventProxy(); * ep.after('file', files.length, function (list) { * // Ordered results * }); * for (var i = 0; i < files.length; i++) { * fs.readFile(files[i], 'utf-8', ep.group('file')); * } * ``` * @param {String} eventname Event name, shoule keep consistent with `after`. * @param {Function} callback Callback function, should return the final result. */ EventProxy.prototype.group = function (eventname, callback) { var that = this; var group = eventname + '_group'; var index = that._after[group].index; that._after[group].index++; return function (err, data) { if (err) { // put all arguments to the error handler return that.emit.apply(that, ['error'].concat(SLICE.call(arguments))); } that.emit(group, { index: index, // callback(err, args1, args2, ...) result: callback ? callback.apply(null, SLICE.call(arguments, 1)) : data }); }; }; /** * The callback will be executed after any registered event was fired. It only executed once. * @param {String} eventname1 Event name. * @param {String} eventname2 Event name. * @param {Function} callback The callback will get a map that has data and eventname attributes. */ EventProxy.prototype.any = function () { var proxy = this, callback = arguments[arguments.length - 1], events = SLICE.call(arguments, 0, -1), _eventname = events.join("_"); debug('Add listenner for Any of events %j emit', events); proxy.once(_eventname, callback); var _bind = function (key) { proxy.bind(key, function (data) { debug('One of events %j emited, execute the listenner'); proxy.trigger(_eventname, {"data": data, eventName: key}); }); }; for (var index = 0; index < events.length; index++) { _bind(events[index]); } }; /** * The callback will be executed when the event name not equals with assigned event. * @param {String} eventname Event name. * @param {Function} callback Callback. */ EventProxy.prototype.not = function (eventname, callback) { var proxy = this; debug('Add listenner for not event %s', eventname); proxy.bindForAll(function (name, data) { if (name !== eventname) { debug('listenner execute of event %s emit, but not event %s.', name, eventname); callback(data); } }); }; /** * Success callback wrapper, will handler err for you. * * ```js * fs.readFile('foo.txt', ep.done('content')); * * // equal to => * * fs.readFile('foo.txt', function (err, content) { * if (err) { * return ep.emit('error', err); * } * ep.emit('content', content); * }); * ``` * * ```js * fs.readFile('foo.txt', ep.done('content', function (content) { * return content.trim(); * })); * * // equal to => * * fs.readFile('foo.txt', function (err, content) { * if (err) { * return ep.emit('error', err); * } * ep.emit('content', content.trim()); * }); * ``` * @param {Function|String} handler, success callback or event name will be emit after callback. * @return {Function} */ EventProxy.prototype.done = function (handler, callback) { var that = this; return function (err, data) { if (err) { // put all arguments to the error handler return that.emit.apply(that, ['error'].concat(SLICE.call(arguments))); } // callback(err, args1, args2, ...) var args = SLICE.call(arguments, 1); if (typeof handler === 'string') { // getAsync(query, ep.done('query')); // or // getAsync(query, ep.done('query', function (data) { // return data.trim(); // })); if (callback) { // only replace the args when it really return a result return that.emit(handler, callback.apply(null, args)); } else { // put all arguments to the done handler //ep.done('some'); //ep.on('some', function(args1, args2, ...){}); return that.emit.apply(that, [handler].concat(args)); } } // speed improve for mostly case: `callback(err, data)` if (arguments.length <= 2) { return handler(data); } // callback(err, args1, args2, ...) handler.apply(null, args); }; }; /** * make done async * @return {Function} delay done */ EventProxy.prototype.doneLater = function (handler, callback) { var _doneHandler = this.done(handler, callback); return function (err, data) { var args = arguments; later(function () { _doneHandler.apply(null, args); }); }; }; /** * Create a new EventProxy * Examples: * ```js * var ep = EventProxy.create(); * ep.assign('user', 'articles', function(user, articles) { * // do something... * }); * // or one line ways: Create EventProxy and Assign * var ep = EventProxy.create('user', 'articles', function(user, articles) { * // do something... * }); * ``` * @return {EventProxy} EventProxy instance */ EventProxy.create = function () { var ep = new EventProxy(); var args = CONCAT.apply([], arguments); if (args.length) { var errorHandler = args[args.length - 1]; var callback = args[args.length - 2]; if (typeof errorHandler === 'function' && typeof callback === 'function') { args.pop(); ep.fail(errorHandler); } ep.assign.apply(ep, args); } return ep; }; // Backwards compatibility EventProxy.EventProxy = EventProxy;
import { App } from '../index'; import Footer from 'components/Footer'; import ProgressBar from 'components/ProgressBar'; import expect from 'expect'; import { shallow, mount } from 'enzyme'; import React from 'react'; describe('<App />', () => { it('should render the logo', () => { const renderedComponent = shallow( <App /> ); expect(renderedComponent.find('Img').length).toEqual(1); }); it('should render its children', () => { const children = (<h1>Test</h1>); const renderedComponent = shallow( <App> {children} </App> ); expect(renderedComponent.contains(children)).toEqual(true); }); it('should render the footer', () => { const renderedComponent = shallow( <App /> ); expect(renderedComponent.find(Footer).length).toEqual(1); }); it('should render <ProgressBar />', () => { const renderedComponent = shallow( <App /> ); expect(renderedComponent.find(ProgressBar).length).toEqual(1); }); });
/** * MailDev - mailserver.js */ // NOTE - simplesmtp is for backwards compatibility with 0.10.x var simplesmtp = require('simplesmtp'); var SMTPServer = require('smtp-server').SMTPServer; var MailParser = require('mailparser').MailParser; var events = require('events'); var fs = require('fs'); var os = require('os'); var path = require('path'); var logger = require('./logger'); var outgoing = require('./outgoing'); var version = process.version.replace(/v/, '') .split(/\./) .map(function(n) { return parseInt(n, 10); }); var legacy = version[0] === 0 && version[1] <= 10; var defaultPort = 1025; var defaultHost = '0.0.0.0'; var config = {}; var store = []; var tempDir = path.join(os.tmpdir(), 'maildev', process.pid.toString()); var eventEmitter = new events.EventEmitter(); var smtp; /** * Mail Server exports */ var mailServer = module.exports = {}; mailServer.store = store; /** * SMTP Server stream and helper functions */ // Clone object function clone(object){ return JSON.parse(JSON.stringify(object)); } // Create an unique id, length 8 characters function makeId(){ var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < 8; i++){ text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } // Save an email object on stream end function saveEmail(id, envelope, mailObject){ var object = clone(mailObject); object.id = id; object.time = new Date(); object.read = false; object.envelope = envelope; object.source = path.join(tempDir, id + '.eml'); store.push(object); logger.log('Saving email: ', mailObject.subject); if (outgoing.isAutoRelayEnabled()) { mailServer.relayMail(object, true, function (err) { if (err) logger.error('Error when relaying email', err); }); } eventEmitter.emit('new', object); } // Save an attachment function saveAttachment(attachment){ var output = fs.createWriteStream(path.join(tempDir, attachment.contentId)); attachment.stream.pipe(output); } function createSaveStream(id, emailData) { var parseStream = new MailParser({ streamAttachments: true }); parseStream.on('end', saveEmail.bind(null, id, emailData)); parseStream.on('attachment', saveAttachment); return parseStream; } function createRawStream(id) { return fs.createWriteStream(path.join(tempDir, id + '.eml')); } // Legacy methods are used with the Node 0.10 compatible smtpserver function handleLegacyDataStream(connection) { var id = makeId(); connection.saveStream = createSaveStream(id, { from: connection.from, to: connection.to, host: connection.host, remoteAddress: connection.remoteAddress }); connection.saveRawStream = createRawStream(id); } function handleLegacyChunk(connection, chunk) { connection.saveStream.write(chunk); connection.saveRawStream.write(chunk); } function handleLegacyDataStreamEnd(connection, done) { connection.saveStream.end(); connection.saveRawStream.end(); // ABC is the queue id to be advertised to the client // There is no current significance to this. done(null, 'ABC'); } function handleDataStream(stream, session, callback) { var id = makeId(); session.saveStream = createSaveStream(id, { from: session.envelope.mailFrom, to: session.envelope.rcptTo, host: session.hostNameAppearsAs, remoteAddress: session.remoteAddress }); session.saveRawStream = createRawStream(id); stream.pipe(session.saveStream); stream.pipe(session.saveRawStream); stream.on('end', function(){ session.saveRawStream.end(); callback(null, 'Message queued as ' + id); }); } /** * Delete everything in the temp folder */ function clearTempFolder(){ fs.readdir(tempDir, function(err, files){ if (err) throw err; files.forEach(function(file){ fs.unlink( path.join(tempDir, file), function(err) { if (err) throw err; }); }); }); } /** * Delete a single email's attachments */ function deleteAttachments(attachments) { attachments.forEach(function(attachment){ fs.unlink( path.join(tempDir, attachment.contentId), function (err) { if (err) logger.error(err); }); }); } /** * Create temp folder */ function createTempFolder() { if (fs.existsSync(tempDir)) { clearTempFolder(); return; } if (!fs.existsSync(path.dirname(tempDir))) { fs.mkdirSync(path.dirname(tempDir)); logger.log('Temporary directory created at %s', path.dirname(tempDir)); } if (!fs.existsSync(tempDir)) { fs.mkdirSync(tempDir); logger.log('Temporary directory created at %s', tempDir); } } /** * Authorize callback for smtp server */ function authorizeUser(auth, session, callback) { var username = auth.username; var password = auth.password; // conn, username, password, callback if (legacy) { username = arguments[1]; password = arguments[2]; callback = arguments[3]; } if (this.options.incomingUser && this.options.incomingPassword) { if (username !== this.options.incomingUser || password !== this.options.incomingPassword) { return callback(new Error('Invalid username or password')); } } callback(null, { user: this.options.incomingUser }); } /** * Create and configure the mailserver */ mailServer.create = function(port, host, user, password) { // Start the server & Disable DNS checking if (legacy) { smtp = simplesmtp.createServer({ disableDNSValidation: true, requireAuthentication: !!(user && password), incomingUser: user, incomingPassword: password }); smtp.on('startData', handleLegacyDataStream); smtp.on('data', handleLegacyChunk); smtp.on('dataReady', handleLegacyDataStreamEnd); if (user && password) { smtp.on('authorizeUser', authorizeUser); } } else { smtp = new SMTPServer({ incomingUser: user, incomingPassword: password, onAuth: authorizeUser, onData: handleDataStream, logger: false, disabledCommands: !!(user && password)?['STARTTLS']:['AUTH'] }); } // Setup temp folder for attachments createTempFolder(); mailServer.port = port || defaultPort; mailServer.host = host || defaultHost; }; /** * Start the mailServer */ mailServer.listen = function(callback) { if (typeof callback !== 'function') callback = null; // Listen on the specified port smtp.listen(mailServer.port, mailServer.host, function(err) { if (err) { if (callback) { callback(err); } else { throw err; } } if (callback) callback(); logger.info('MailDev SMTP Server running at %s:%s', mailServer.host, mailServer.port); }); }; /** * Stop the mailserver */ mailServer.end = function(done){ var method = legacy ? 'end' : 'close'; smtp[method](done); }; /** * Extend Event Emitter methods * events: * 'new' - emitted when new email has arrived */ mailServer.on = eventEmitter.on.bind(eventEmitter); mailServer.emit = eventEmitter.emit.bind(eventEmitter); mailServer.removeListener = eventEmitter.removeListener.bind(eventEmitter); mailServer.removeAllListeners = eventEmitter.removeAllListeners.bind(eventEmitter); /** * Get an email by id */ mailServer.getEmail = function(id, done){ var email = store.filter(function(element){ return element.id === id; })[0]; if (email) { done(null, email); } else { done(new Error('Email was not found')); } }; /** * Returns a readable stream of the raw email */ mailServer.getRawEmail = function(id, done){ mailServer.getEmail(id, function(err, email){ if (err) return done(err); done(null, fs.createReadStream( path.join(tempDir, id + '.eml') ) ); }); }; /** * Returns the html of a given email */ mailServer.getEmailHTML = function(id, done) { mailServer.getEmail(id, function(err, email) { if (err) return done(err); var html = email.html; if (!email.attachments) return done(null, html); var embeddedAttachments = email.attachments.filter(function(attachment) { return attachment.contentId; }); var getFileUrl = function(id, filename) { return '/email/' + id + '/attachment/' + filename; }; if (embeddedAttachments.length) { embeddedAttachments.forEach(function(attachment) { var regex = new RegExp('src="cid:' + attachment.contentId + '"'); var replacement = 'src="' + getFileUrl(id, attachment.generatedFileName) + '"'; html = html.replace(regex, replacement); }); } done(null, html); }); }; /** * Get all email */ mailServer.getAllEmail = function(done){ done(null, store); }; /** * Delete an email by id */ mailServer.deleteEmail = function(id, done){ var email = null; var emailIndex = null; store.forEach(function(element, index){ if (element.id === id){ email = element; emailIndex = index; } }); if (emailIndex === null){ return done(new Error('Email not found')); } //delete raw email fs.unlink( path.join(tempDir, id + '.eml'), function (err) { if (err) { logger.error(err); } else { eventEmitter.emit('delete', {id:id, index:emailIndex}); } }); if (email.attachments){ deleteAttachments(email.attachments); } logger.warn('Deleting email - %s', email.subject); store.splice(emailIndex, 1); done(null, true); }; /** * Delete all emails in the store */ mailServer.deleteAllEmail = function(done){ logger.warn('Deleting all email'); clearTempFolder(); store.length = 0; eventEmitter.emit('delete', {id:'all'}); done(null, true); }; /** * Returns the content type and a readable stream of the file */ mailServer.getEmailAttachment = function(id, filename, done){ mailServer.getEmail(id, function(err, email){ if (err) return done(err); if (!email.attachments || !email.attachments.length) { return done(new Error('Email has no attachments')); } var match = email.attachments.filter(function(attachment){ return attachment.generatedFileName === filename; })[0]; if (!match) { return done(new Error('Attachment not found')); } done(null, match.contentType, fs.createReadStream( path.join(tempDir, match.contentId) ) ); }); }; /** * Setup outgoing */ mailServer.setupOutgoing = function(host, port, user, pass, secure) { outgoing.setup(host, port, user, pass, secure); }; mailServer.isOutgoingEnabled = function() { return outgoing.isEnabled(); }; mailServer.getOutgoingHost = function() { return outgoing.getOutgoingHost(); }; /** * Set Auto Relay Mode, automatic send email to recipient */ mailServer.setAutoRelayMode = function(enabled, rules) { outgoing.setAutoRelayMode(enabled, rules); }; /** * Relay a given email, accepts a mail id or a mail object */ mailServer.relayMail = function(idOrMailObject, isAutoRelay, done) { if (!outgoing.isEnabled()) return done(new Error('Outgoing mail not configured')); // isAutoRelay is an option argument if (typeof isAutoRelay === 'function') { done = isAutoRelay; isAutoRelay = false; } // If we receive a email id, get the email object if (typeof idOrMailObject === 'string') { mailServer.getEmail(idOrMailObject, function(err, email) { if (err) return done(err); mailServer.relayMail(email, done); }); return; } var mail = idOrMailObject; mailServer.getRawEmail(mail.id, function(err, rawEmailStream) { if (err) { logger.error('Mail Stream Error: ', err); return done(err); } outgoing.relayMail(mail, rawEmailStream, isAutoRelay, done); }); }; /** * Download a given email */ mailServer.getEmailEml = function(id, done) { mailServer.getEmail(id, function(err, email){ if (err) return done(err); var filename = email.id + '.eml'; done(null, 'message/rfc822', filename, fs.createReadStream(path.join(tempDir, id + '.eml'))); }); };
/* * 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. * */ /*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */ /*global define, $, doReplace */ /* * Adds Find and Replace commands * * Originally based on the code in CodeMirror2/lib/util/search.js. * * Define search commands. Depends on dialog.js or another * implementation of the openDialog method. * * Replace works a little oddly -- it will do the replace on the next findNext press. * You prevent a replace by making sure the match is no longer selected when hitting * findNext. * */ define(function (require, exports, module) { "use strict"; var CommandManager = require("command/CommandManager"), Commands = require("command/Commands"), Strings = require("strings"), EditorManager = require("editor/EditorManager"); function SearchState() { this.posFrom = this.posTo = this.query = null; this.marked = []; } function getSearchState(cm) { if (!cm._searchState) { cm._searchState = new SearchState(); } return cm._searchState; } function getSearchCursor(cm, query, pos) { // Heuristic: if the query string is all lowercase, do a case insensitive search. return cm.getSearchCursor(query, pos, typeof query === "string" && query === query.toLowerCase()); } function dialog(cm, text, shortText, f) { if (cm.openDialog) { cm.openDialog(text, f); } else { f(prompt(shortText, "")); } } function confirmDialog(cm, text, shortText, fs) { if (cm.openConfirm) { cm.openConfirm(text, fs); } else if (confirm(shortText)) { fs[0](); } } function getDialogTextField() { return $(".CodeMirror-dialog input[type='text']"); } function parseQuery(query) { var isRE = query.match(/^\/(.*)\/([a-z]*)$/); $(".CodeMirror-dialog .alert-message").remove(); try { return isRE ? new RegExp(isRE[1], isRE[2].indexOf("i") === -1 ? "" : "i") : query; } catch (e) { $(".CodeMirror-dialog div").append("<div class='alert-message' style='margin-bottom: 0'>" + e.message + "</div>"); return ""; } } function findNext(cm, rev) { var found = true; cm.operation(function () { var state = getSearchState(cm); var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo); if (!cursor.find(rev)) { // If no result found before hitting edge of file, try wrapping around cursor = getSearchCursor(cm, state.query, rev ? {line: cm.lineCount() - 1} : {line: 0, ch: 0}); // No result found, period: clear selection & bail if (!cursor.find(rev)) { cm.setCursor(cm.getCursor()); // collapses selection, keeping cursor in place to avoid scrolling found = false; return; } } cm.setSelection(cursor.from(), cursor.to()); state.posFrom = cursor.from(); state.posTo = cursor.to(); }); return found; } function clearSearch(cm) { cm.operation(function () { var state = getSearchState(cm), i; if (!state.query) { return; } state.query = null; // Clear highlights for (i = 0; i < state.marked.length; ++i) { state.marked[i].clear(); } state.marked.length = 0; }); } var queryDialog = Strings.CMD_FIND + ': <input type="text" style="width: 10em"/> <span style="color: #888">(' + Strings.SEARCH_REGEXP_INFO + ')</span>'; /** * If no search pending, opens the search dialog. If search is already open, moves to * next/prev result (depending on 'rev') */ function doSearch(cm, rev) { var state = getSearchState(cm); if (state.query) { return findNext(cm, rev); } var searchStartPos = cm.getCursor(); // Called each time the search query changes while being typed. Jumps to the first matching // result, starting from the original cursor position function findFirst(query) { cm.operation(function () { if (!query) { return; } if (state.query) { clearSearch(cm); // clear highlights from previous query } state.query = parseQuery(query); // Highlight all matches // FUTURE: if last query was prefix of this one, could optimize by filtering existing result set if (cm.lineCount() < 2000) { // This is too expensive on big documents. var cursor = getSearchCursor(cm, query); while (cursor.findNext()) { state.marked.push(cm.markText(cursor.from(), cursor.to(), "CodeMirror-searching")); } } state.posFrom = state.posTo = searchStartPos; var foundAny = findNext(cm, rev); getDialogTextField().toggleClass("no-results", !foundAny); }); } dialog(cm, queryDialog, Strings.CMD_FIND, function (query) { // If the dialog is closed and the query string is not empty, // make sure we have called findFirst at least once. This way // if the Find dialog is opened with pre-populated text, pressing // enter will find the next occurance of the text and store // the query for subsequent "Find Next" commands. if (query && !state.query) { findFirst(query); } }); getDialogTextField().on("input", function () { findFirst(getDialogTextField().attr("value")); }); } var replaceQueryDialog = Strings.CMD_REPLACE + ': <input type="text" style="width: 10em"/> <span style="color: #888">(' + Strings.SEARCH_REGEXP_INFO + ')</span>'; var replacementQueryDialog = Strings.WITH + ': <input type="text" style="width: 10em"/>'; // style buttons to match height/margins/border-radius of text input boxes var style = ' style="padding:5px 15px;border:1px #999 solid;border-radius:3px;margin:2px 2px 5px;"'; var doReplaceConfirm = Strings.CMD_REPLACE + '? <button' + style + '>' + Strings.BUTTON_YES + '</button> <button' + style + '>' + Strings.BUTTON_NO + '</button> <button' + style + '>' + Strings.BUTTON_STOP + '</button>'; function replace(cm, all) { dialog(cm, replaceQueryDialog, Strings.CMD_REPLACE, function (query) { if (!query) { return; } query = parseQuery(query); dialog(cm, replacementQueryDialog, Strings.WITH, function (text) { var match, fnMatch = function (w, i) { return match[i]; }; if (all) { cm.compoundChange(function () { cm.operation(function () { var cursor = getSearchCursor(cm, query); while (cursor.findNext()) { if (typeof query !== "string") { match = cm.getRange(cursor.from(), cursor.to()).match(query); cursor.replace(text.replace(/\$(\d)/, fnMatch)); } else { cursor.replace(text); } } }); }); } else { clearSearch(cm); var cursor = getSearchCursor(cm, query, cm.getCursor(true)); var advance = function () { var start = cursor.from(), match = cursor.findNext(); if (!match) { cursor = getSearchCursor(cm, query); match = cursor.findNext(); if (!match || (start && cursor.from().line === start.line && cursor.from().ch === start.ch)) { return; } } cm.setSelection(cursor.from(), cursor.to()); confirmDialog(cm, doReplaceConfirm, Strings.CMD_REPLACE + "?", [function () { doReplace(match); }, advance]); }; var doReplace = function (match) { cursor.replace(typeof query === "string" ? text : text.replace(/\$(\d)/, fnMatch)); advance(); }; advance(); } }); }); // Prepopulate the replace field with the current selection, if any getDialogTextField() .attr("value", cm.getSelection()) .get(0).select(); } function _launchFind() { var editor = EditorManager.getActiveEditor(); if (editor) { var codeMirror = editor._codeMirror; // Bring up CodeMirror's existing search bar UI clearSearch(codeMirror); doSearch(codeMirror); // Prepopulate the search field with the current selection, if any getDialogTextField() .attr("value", codeMirror.getSelection()) .get(0).select(); } } function _findNext() { var editor = EditorManager.getActiveEditor(); if (editor) { doSearch(editor._codeMirror); } } function _findPrevious() { var editor = EditorManager.getActiveEditor(); if (editor) { doSearch(editor._codeMirror, true); } } function _replace() { var editor = EditorManager.getActiveEditor(); if (editor) { replace(editor._codeMirror); } } CommandManager.register(Strings.CMD_FIND, Commands.EDIT_FIND, _launchFind); CommandManager.register(Strings.CMD_FIND_NEXT, Commands.EDIT_FIND_NEXT, _findNext); CommandManager.register(Strings.CMD_REPLACE, Commands.EDIT_REPLACE, _replace); CommandManager.register(Strings.CMD_FIND_PREVIOUS, Commands.EDIT_FIND_PREVIOUS, _findPrevious); });
exports.ok_test = function(test){ test.ok(true, "this assertion should pass"); test.done(); };
var strftime = require("strftime").utc(); var fs = require("fs"); require("colors"); module.exports = function (config) { config = config || {}; var exports = {}; config.levels = config.levels || { "trace": 0, "debug": 1, "log": 2, "info": 3, "warn": 4, "error": 5, "fatal": 6 } config.filename = config.filename || __dirname + "/logs.log"; config.errorLevel = config.errorLevel || "log"; var log_file = fs.createWriteStream(config.filename, { flags: "a" }); exports.setLevel = function (errorLevel) { config.errorLevel = errorLevel; } Object.keys(config.levels).forEach(function (name) { function log(caption, data) { var log = { "level": name, "message": caption, "timestamp": strftime("%F %T", new Date()) } data && (log["data"] = data); if (config.levels[config.errorLevel] <= config.levels[log.level]) { log_file.write(JSON.stringify(log) + "\n"); } if (config.echo && config.levels[config.echo] <= config.levels[log.level]) { try { console.log(log.level.bgYellow.black, log.timestamp.grey, log.message, log.data ? log.data : ""); }catch (e){ console.log(e) } } } exports[name] = log; }) return exports; }
import { applyMiddleware, createStore } from 'redux'; import reducer from '../reducers/reducer'; import thunkMiddleware from 'redux-thunk'; const createStoreWithMiddleware = applyMiddleware( thunkMiddleware )(createStore); export default createStoreWithMiddleware(reducer);
function DatasetTable() { this.connection = new Connection(); this.ops = new Options(this); this.dataset = new CollectionManager(this, {name: 'dataset', flag_sidebar: false}); this.tooltip = new Tooltip(); this.contextmenu = new ContextMenu(); this.modal = new Modal(); this.hierarchy = ['Event Type', 'Event', 'Rumor', 'Feature', 'Subset']; this.event_types = {}; this.event_types_arr = []; this.events = {}; this.events_arr = []; this.rumors = {}; this.rumors_arr = []; this.features = {}; this.features_arr = []; this.subsets = {}; this.subsets_arr = []; this.quantities = ['Tweets', 'DistinctTweets', 'Originals', 'DistinctOriginals', 'Retweets', 'DistinctRetweets', 'Replies', 'DistinctReplies', 'Quotes', 'DistinctQuotes', 'Minutes', 'Users', 'Users2orMoreTweets', 'Users10orMoreTweets']; this.column_headers = [ {Label: 'ID', ID: 'ID', Group: '', sortable: true, always_display: true}, {Label: 'Collection', ID: 'Collection', Group: '', sortable: true, always_display: true}, {Label: 'Tweets', ID: 'Tweets', Group: 'Tweets', count: true, sortable: true, always_display: true}, {Label: 'Distinct', ID: 'DistinctTweets', Group: 'Tweets', count: true, sortable: true}, {Label: 'Originals', ID: 'Originals', Group: 'Tweets', count: true, sortable: true}, {Label: 'Retweets', ID: 'Retweets', Group: 'Tweets', count: true, sortable: true}, {Label: 'Replies', ID: 'Replies', Group: 'Tweets', count: true, sortable: true}, {Label: 'Quotes', ID: 'Quotes', Group: 'Tweets', count: true, sortable: true}, {Label: 'First Tweet', ID: 'FirstTweet', Group: 'Time', sortable: true}, {Label: 'Last Tweet', ID: 'LastTweet', Group: 'Time', sortable: true}, {Label: 'Timeseries<br />Minutes', ID: 'Minutes', Group: 'Time', count: true, sortable: true, always_display: true}, {Label: 'Users', ID: 'Users', Group: 'Users', count: true, sortable: true, always_display: true}, {Label: 'w/ 2+ Tweets', ID: 'Users2orMoreTweets', Group: 'Users', count: true, sortable: true}, {Label: 'w/ 10+ Tweets', ID: 'Users10orMoreTweets', Group: 'Users', count: true, sortable: true}, {Label: 'Dataset', ID: 'DatasetActions', Group: 'Actions'}, {Label: 'Tweets', ID: 'TweetsActions', Group: 'Actions'}, {Label: 'Timeseries', ID: 'TimeseriesActions', Group: 'Actions'}, {Label: 'Users', ID: 'UsersActions', Group: 'Actions'}, // {Label: 'Open', Quantity: '', Group: 'Standard'} ]; this.download = { stream: false, dataset: false, data: [], datatype: '', page: 1 }; } DatasetTable.prototype = { init: function() { this.setTriggers(); this.getData(); this.tooltip.init(); this.contextmenu.init(); }, setTriggers: function() { triggers.on('sort_elements', function() { this.clickSort(false, 'maintain_direction'); }.bind(this)); triggers.on('new_counts', this.computeAggregates.bind(this)); triggers.on('update_counts', this.updateTableCounts.bind(this)); triggers.on('refresh_visibility', this.setVisibility_Rows.bind(this)); triggers.on('toggle columns', this.setVisibility_Columns.bind(this)); triggers.on('dataset table:build', this.buildTable.bind(this)); triggers.on('new dataset:build', this.buildNewDatasetOption.bind(this)); // d3.select('#body').on('scroll', this.perserveHeader.bind(this)); $(window).on('scroll', this.perserveHeader.bind(this)); }, getData: function() { var datasets = 3; this.connection.php('collection/getEvent', {}, function(d) { try { this.events_arr = JSON.parse(d); } catch(err) { console.error(d); return; } datasets--; if(datasets == 0) this.configureData(); }.bind(this)); this.connection.php('collection/getRumor', {}, function(d) { try { this.rumors_arr = JSON.parse(d); } catch(err) { console.error(d); return; } datasets--; if(datasets == 0) this.configureData(); }.bind(this)); this.connection.php('collection/getSubset', {}, function(d) { try { this.subsets_arr = JSON.parse(d); } catch(err) { console.error(d); return; } datasets--; if(datasets == 0) this.configureData(); }.bind(this)); }, configureData: function() { // Clear any old data this.events = {}; this.rumors = {}; this.subsets = {}; this.event_types = {}; this.event_types_arr = []; this.features_arr = []; // Link all of the data this.events_arr.forEach(this.configureRawEventObject, this); this.rumors_arr.forEach(this.configureRawRumorObject, this); this.subsets_arr.forEach(this.configureRawSubsetObject, this); // Add children columns this.event_types_arr.sort(function(a, b) { if (a.Label < b.Label) return -1; if (a.Label > b.Label) return 1; return 0; }); this.event_types_arr.forEach(function(event_type, i) { event_type.CollectionType = 'EventType'; event_type.ID = i; event_type.children = event_type.events_arr; }); this.events_arr.forEach(function(event) { event.children = event.rumors_arr; event.rumors_arr.sort(function(a, b) { if (a.ID < b.ID) return -1; if (a.ID > b.ID) return 1; return 0; }); }); this.rumors_arr.forEach(function(rumor) { rumor.children = rumor.features_arr.filter(f => f.Label != 'Rumor'); rumor.features_arr.sort(function(a, b) { if (a.ID < b.ID) return -1; if (a.ID > b.ID) return 1; return 0; }); }); this.features_arr.forEach(function(feature, i) { feature.CollectionType = 'Feature'; feature.children = feature.subsets_arr; feature.ID = feature.Event.ID * 100 + i; feature.subsets_arr.sort(function(a, b) { if (a.ID < b.ID) return -1; if (a.ID > b.ID) return 1; return 0; }); }); this.buildOptions(); }, configureRawEventObject: function(event) { // Add fields event.ID = parseInt(event.ID); event.Label = event.DisplayName || event.Name; event.Level = 1; event.CollectionType = 'Event'; this.quantities.forEach(function (quantity) { event[quantity] = parseInt(event[quantity]) || 0; }); event['FirstTweet'] = event['FirstTweet'] ? new BigNumber(event['FirstTweet']) : new BigNumber('0'); event['LastTweet'] = event['LastTweet'] ? new BigNumber(event['LastTweet']) : new BigNumber('0'); // Add to event type list (or make new event type list) var type = event.Type; var event_type; if(type in this.event_types) { event_type = this.event_types[type]; event_type.events_arr.push(event); } else { event_type = { Level: 0, Label: type, events_arr: [event] } event_type['Event Type'] = event_type; this.event_types[type] = event_type; this.event_types_arr.push(event_type); } // Add children var event_rumor = { Event: event.ID, ID: event.ID - 10000, Name: 'All Tweets in Event', Definition: '', Query: '', StartTime: event.StartTime, StopTime: event.StopTime, Active: '1' } event.rumors = {}; event.rumors[(event.ID - 10000)] = event_rumor; event.rumors_arr = [event_rumor]; this.rumors_arr.push(event_rumor); event.subsets_arr = []; this.quantities.forEach(function (quantity) { event_rumor[quantity] = event[quantity]; }); event_rumor['FirstTweet'] = event['FirstTweet']; event_rumor['LastTweet'] = event['LastTweet']; // Add ancestors event['Event'] = event; // weird but makes things easier event['Event Type'] = event_type; // Add to indiced object this.events[event.ID] = event; }, configureRawRumorObject: function(rumor) { rumor.ID = parseInt(rumor.ID); rumor.Level = 2; rumor.CollectionType = rumor.ID > 0 ? 'Rumor' : 'DefaultRumor'; rumor.Label = rumor.Name; rumor.features = {}; rumor.features_arr = []; rumor.subsets_arr = []; // Add rumor to Event rumor.Event_ID = rumor.Event; var event = this.events[rumor.Event_ID]; if(!(rumor.ID in event.rumors)) { event.rumors[rumor.ID] = rumor; event.rumors_arr.push(rumor); } // Add ancestors rumor['Rumor'] = rumor; rumor['Event'] = event; rumor['Event Type'] = event['Event Type']; // Add to indiced object this.rumors[rumor.ID] = rumor; }, configureRawSubsetObject: function(subset) { // Add fields subset.ID = parseInt(subset.ID); subset.Label = util.subsetName(subset); subset.CollectionType = 'Subset'; subset.FeatureMatch = util.subsetName({ feature: subset.Feature, match: subset.Match, includeFeature: true }); // subset.Label = subset.Match.replace(/\\W/g, '<span style="color:#ccc">_</span>'); subset.Level = 4; this.quantities.forEach(function (quantity) { subset[quantity] = parseInt(subset[quantity]) || 0; }); subset['FirstTweet'] = subset['FirstTweet'] ? new BigNumber(subset['FirstTweet']) : new BigNumber('0'); subset['LastTweet'] = subset['LastTweet'] ? new BigNumber(subset['LastTweet']) : new BigNumber('0'); // Get ancestors subset.Event_ID = subset.Event; var event = this.events[subset.Event_ID]; var rumor_ID = subset.Rumor != "0" ? subset.Rumor : (parseInt(subset.Event_ID) - 10000); var rumor = event.rumors[rumor_ID]; // If it is actually a rumor subset, add data to the rumor if(subset.Feature == 'Rumor') { if(this.Match in this.rumors) { subset.Label = this.rumors[this.Match].Label; subset.FeatureMatch = 'Rumor: ' + subset.Label } var actual_rumor = event.rumors[subset.Match]; this.quantities.forEach(function (quantity) { actual_rumor[quantity] = parseInt(subset[quantity]) || 0; }); actual_rumor['FirstTweet'] = subset['FirstTweet'] ? new BigNumber(subset['FirstTweet']) : new BigNumber('0'); actual_rumor['LastTweet'] = subset['LastTweet'] ? new BigNumber(subset['LastTweet']) : new BigNumber('0'); actual_rumor['Subset_ID'] = subset.ID; } else if(subset.Feature == 'Event') { if(this.Match in this.events) { subset.Label = this.events[this.Match].Label; } } // Add to feature in rumor var feature; if(subset.Feature in rumor.features) { feature = rumor.features[subset.Feature]; feature.subsets[subset.Match] = subset; feature.subsets_arr.push(subset); } else { feature = { Level: 3, Label: subset.Feature, Rumor: rumor, Event: event, 'Event Type': event['Event Type'], subsets: {}, subsets_arr: [subset] } feature['Feature'] = feature; feature.subsets[subset.Match] = subset; rumor.features[subset.Feature] = feature; rumor.features_arr.push(feature); this.features_arr.push(feature); } // Add to subset list in event rumor.subsets_arr.push(subset); event.subsets_arr.push(subset); // Add to ancestors subset['Subset'] = subset; subset['Feature'] = feature; subset['Rumor'] = rumor; subset['Event'] = event; subset['Event Type'] = event['Event Type']; // Add to indiced object this.subsets[subset.ID] = subset; }, computeAggregates: function() { this.features_arr.forEach(function(d) { var children = d.children; if(d.Label == 'Code') { children = [d.subsets['Uncodable'], d.subsets['Codable']]; } this.aggregateSetChildrenCounts(d); }, this); this.event_types_arr.forEach(this.aggregateSetChildrenCounts.bind(this)); triggers.emit('update_counts'); }, aggregateSetChildrenCounts: function(d) { this.quantities.forEach(function(count) { d[count] = d3.sum(d.children, e => e[count] || 0); }); d.FirstTweet_Min = d3.min(d.children, e => !e.FirstTweet || e.FirstTweet == 0 ? new BigNumber(1e20) : e.FirstTweet); d.LastTweet_Min = d3.min(d.children, e => !e.LastTweet || e.LastTweet == 0 ? new BigNumber(1e20) : e.LastTweet ); d.FirstTweet_Max = d3.max(d.children, e => e.FirstTweet || new BigNumber(0)); d.LastTweet_Max = d3.max(d.children, e => e.LastTweet || new BigNumber(0)); d.FirstTweet = d.FirstTweet_Min; d.LastTweet = d.LastTweet_Max; d.ID_Min = d3.min(d.children, e => parseInt(e.ID) || 0); d.ID_Max = d3.max(d.children, e => parseInt(e.ID) || 1e10); }, buildOptions: function() { this.ops.updateCollectionCallback = this.getData; var columns_sortable = this.column_headers.filter(d => d.sortable); this.ops['Columns'] = { 'Tweet Type Counts': new Option({ title: 'Tweet Types', labels: ['Hidden', 'Shown'], ids: ['hidden', 'shown'], default: 0, type: "toggle", tooltip: "Show or hide columns with the count of each specific type of tweet", callback: triggers.emitter('toggle columns') }), 'Dates': new Option({ title: 'Dates', labels: ['Hidden', 'Shown'], ids: ['hidden', 'shown'], default: 0, type: "toggle", tooltip: "Show or hide columns the start & end dates of the datasets", callback: triggers.emitter('toggle columns') }), 'Repeat Users': new Option({ title: 'Repeat Users', labels: ['Hidden', 'Shown'], ids: ['hidden', 'shown'], default: 0, type: "toggle", tooltip: "Show or hide columns listing how many users tweeted more than once, and 10 or more times", callback: triggers.emitter('toggle columns') }), 'Actions': new Option({ title: 'Actions', labels: ['Hidden', 'Shown'], ids: ['hidden', 'shown'], default: 0, type: "toggle", tooltip: "Show or hide columns with buttons for actions on events & subsets", callback: triggers.emitter('toggle columns') }), 'Show Deletion': new Option({ title: 'Deletion', labels: ['Hidden', 'Shown'], ids: ['hidden', 'shown'], default: 0, type: "toggle", tooltip: "In Action columns, display option to clear timeseries and user list. Default: off to prevent accidents.", callback: triggers.emitter('toggle columns') }), Distinct: new Option({ title: 'Distinct?', labels: ['Show All', 'Only Distinct'], ids: ['', 'Distinct'], default: 0, type: "dropdown", callback: triggers.emitter('update_counts') }), Relative: new Option({ title: 'Relative to', labels: ['-', 'Event', 'Event\'s Tweet Types', 'Match', 'Distinct/Not'], ids: ['raw', 'event', 'type', 'match', 'distinct'], default: 0, type: "dropdown", callback: triggers.emitter('update_counts') }), 'Date Format': new Option({ title: 'First/Last Tweet', labels: ['Tweet ID', 'Date'], ids: ['id', 'date'], default: 1, type: "dropdown", callback: triggers.emitter('update_counts') }), 'Minutes Format': new Option({ title: 'Minutes', labels: ['Count', 'Day/Hour/Min'], ids: ['count', 'minutes'], default: 0, type: "dropdown", callback: triggers.emitter('update_counts') }), }; this.ops['Rows'] = { Hierarchical: new Option({ title: 'Maintain Hierarchy', labels: ['Yes', 'No'], ids: ["true", "false"], default: 0, type: "dropdown", callback: triggers.emitter('sort_elements') }), Order: new Option({ title: 'Order', labels: columns_sortable.map(d => d.Label), ids: columns_sortable.map(d => d.ID), default: 1, type: "dropdown", callback: triggers.emitter('sort_elements') }), Ascending: new Option({ title: 'Ascending', labels: ['Ascending', 'Descending'], ids: ['true', 'false'], default: 0, type: "dropdown", callback: triggers.emitter('sort_elements') }), Empties: new Option({ title: 'Uncounted Rows', labels: ['Hidden', 'Shown'], ids: ['none', 'table-row'], default: 0, type: "toggle", callback: triggers.emitter('refresh_visibility') }), // Deactivated: new Option({ // title: 'Deactivated Rows', // labels: ['Hidden', 'Shown'], // ids: ['none', 'table-row'], // default: 0, // type: "toggle", // callback: triggers.emitter('refresh_visibility') // }), // Unopened: new Option({ // title: 'Unopened Rows', // labels: ['Hidden', 'Shown'], // ids: ['none', 'table-row'], // default: 0, // type: "toggle", // callback: triggers.emitter('refresh_visibility') // }), 'Level 0 Showing Children': new Option({ title: 'Event Types Showing Events', labels: ['List'], ids: [[]], render: false, custom_entries_allowed: true, callback: triggers.emitter('refresh_visibility') }), 'Level 1 Showing Children': new Option({ title: 'Events Showing Features', labels: ['List'], ids: [[]], render: false, custom_entries_allowed: true, callback: triggers.emitter('refresh_visibility') }), 'Level 2 Showing Children': new Option({ title: 'Rumors Showing Features', labels: ['List'], ids: [[]], render: false, custom_entries_allowed: true, callback: triggers.emitter('refresh_visibility') }), 'Level 3 Showing Children': new Option({ title: 'Features Showing Matches', labels: ['List'], ids: [[]], render: false, custom_entries_allowed: true, callback: triggers.emitter('refresh_visibility') }) } this.ops.panels = ['Rows', 'Columns']; // Start drawing options this.ops.init(); // Also make the modal triggers.emit('modal:build'); triggers.emit('dataset table:build'); triggers.emit('new dataset:build'); }, buildTable: function() { d3.select('#table-container').selectAll('*').remove(); var table = d3.select('#table-container') .append('table') .attr('id', 'status_table') .attr('class', 'table table-sm'); table.append('thead') .append('tr') .selectAll('th') .data(this.column_headers) .enter() .append('th') .append('div') .attr('class', d => 'col-sortable col-' + d.ID) .html(d => d.Label); table.selectAll('.col-sortable') .on('click', this.clickSort.bind(this)) .append('span') .attr('class', 'glyphicon glyphicon-sort glyphicon-hiddenclick'); var table_body = table.append('tbody'); // Add table rows this.event_types_arr.forEach(function(event_type) { event_type.row = table_body.append('tr') .data([event_type]) .attr('class', d => 'row_eventtype row_haschildren row_eventtype_' + d.ID); event_type.events_arr.forEach(function(event) { event.row = table_body.append('tr') .data([event]) .attr('class', d => 'row_event row_haschildren row_event_' + d.ID); event.rumors_arr.forEach(function(rumor) { rumor.row = table_body.append('tr') .data([rumor]) .attr('class', d => 'row_rumor row_haschildren row_rumor_' + d.ID + (d.CollectionType == 'Rumor' ? ' row_rumorwithsubset row_subset_' + d.Subset_ID : '')); rumor.features_arr.forEach(function(feature, feature_ichild) { if(feature.Label != 'Rumor') { feature.row = table_body.append('tr') .data([feature]) .attr('class', d => 'row_feature row_haschildren row_feature_' + d.ID); // .attr('class', d => 'row_feature row_haschildren row_feature-' + (feature_ichild % 2 ? 'odd' : 'even')); feature.subsets_arr.forEach(function(subset, subset_ichild) { subset.row = table_body.append('tr') .data([subset]) .attr('class', d => 'row_subset row_subset_' + d.ID + ' row_feature-' + (feature_ichild % 2 ? 'odd' : 'even') + '-subset-' + (subset_ichild % 2 ? 'odd' : 'even')); }); } }); }); }); }) // // Add right click context menu to event & subset rows // this.contextmenu.attach('.row_event, .row_subset', this.prepareCollectionContextMenu.bind(this)); // Add all of the cells this.column_headers.forEach(function(column) { table_body.selectAll('tr') .append('td') .append('div') .attr('class', 'cell-' + column.ID + (column.count ? ' cell-count' : '')); }) // ID & Label table_body.selectAll('.cell-ID') .html(dataset => [1, 2, 4].includes(dataset.Level) && dataset.CollectionType != 'DefaultRumor' ? dataset.ID : '') table_body.selectAll('.cell-Collection') .append('span') .attr('class', 'value') .html(dataset => dataset.Label); var level_names = ['events', 'rumors', 'features', 'matches', 'N/A']; table_body.selectAll('.row_haschildren .cell-Collection') .on('click', this.setVisibility_Rows_children.bind(this)) .append('small') .attr('class', 'glyphicon-hiddenclick') .html(function(d) { return d.children.length + (d.Level == 1 ? -1 : 0) + ' ' + level_names[d.Level]; }); table_body.selectAll('.row_haschildren .cell-Collection') .append('span') .attr('class', 'glyphicon glyphicon-chervon-left glyphicon-hiddenclick') .style('margin-left', '0px'); // Add tool tips this.tooltip.attach('.cell-Collection', this.prepareCollectionTooltip.bind(this)); // Values table_body.selectAll('.cell-count') .append('span').attr('class', 'value'); // Attach Tooltips // To Tweet & Tweet Types ['Tweets', 'DistinctTweets', 'Originals', 'Retweets', 'Replies', 'Quotes'].forEach(function(type) { // Tooltip with summary starts this.tooltip.attach('.cell-' + type, function(set) { var value = set[type]; var info = {}; if(value == undefined) return info; var event = set['Event'] || set; // var feature = set['Feature'] || set; info[type] = util.formatThousands(value); if(set.Level >= 2 || type != 'Tweets') { info['% of Event'] = (value / event['Tweets'] * 100).toFixed(1) + '%'; } if(set.Level >= 2 && type != 'Tweets') { info['% of Type'] = (value / event[type] * 100).toFixed(1) + '%'; // info['% of Feature'] = (value / feature['Tweets'] * 100).toFixed(1) + '%'; if(set.Level >= 4) { info['% of Subset'] = (value / set['Tweets'] * 100).toFixed(1) + '%'; } } var distinct = set['Distinct' + type]; info['Distinct ' + type] = util.formatThousands(distinct); info['% Distinct'] = (distinct / value * 100).toFixed(1) + '%'; if(set.Level >= 2 || type != 'Tweets') { info['% D of Event'] = (distinct / event['Tweets'] * 100).toFixed(1) + '%'; } if(set.Level >= 2 && type != 'Tweets') { info['% D of Type '] = (distinct / event['Distinct' + type] * 100).toFixed(1) + '%'; // info['% D of Feature'] = (value / feature['Tweets'] * 100).toFixed(1) + '%'; if(set.Level >= 4) { info['% D of Subset'] = (value / set['Tweets'] * 100).toFixed(1) + '%'; } } return info; }); }, this); // Tooltip with user starts this.tooltip.attach('.cell-Users, .cell-Users2orMoreTweets, .cell-Users10orMoreTweets', function(dataset) { return { Users: dataset['Users'], '2+ Tweets': dataset['Users2orMoreTweets'], '10+ Tweets': dataset['Users10orMoreTweets'], '% 2+ Tweets': Math.floor(dataset['Users2orMoreTweets'] / dataset['Users'] * 10000) / 100 + '%', '% 10+ Tweets': Math.floor(dataset['Users10orMoreTweets'] / dataset['Users'] * 10000) / 100 + '%' } }); this.tooltip.attach('.cell-FirstTweet, .cell-LastTweet', function(set) { return { 'First Tweet': set['FirstTweet'], 'Last Tweet': set['LastTweet'], 'Start Time': util.formatDate(util.twitterID2Timestamp(set['FirstTweet'])), 'End Time': util.formatDate(util.twitterID2Timestamp(set['LastTweet'])), }; }); // Add action buttons this.addAllDatasetActions(); // Add borders between dataset actions table_body.selectAll('.cell-DatasetActions').each(function(d) { d3.select(this.parentNode).style('border-right', 'solid 1px gray'); }); table_body.selectAll('.cell-TweetsActions').each(function(d) { d3.select(this.parentNode).style('border-right', 'solid 1px gray'); }); table_body.selectAll('.cell-TimeseriesActions').each(function(d) { d3.select(this.parentNode).style('border-right', 'solid 1px gray'); }); // Set initial visibility this.event_types_arr.forEach(function(d) { this.setVisibility_Rows_children(d, 'perserve'); }.bind(this), this); this.makeScrollHeader(); // Set the counts triggers.emit('new_counts'); triggers.emit('toggle columns'); }, addAllDatasetActions: function() { this.addDatasetAction('DatasetActions', 'edit', this.edit, 'Edit the dataset', ['event', 'subset']); this.addDatasetAction('DatasetActions', 'remove action-deletion', this.deleteCollection, 'Delete Collection (warning: inreversible)', ['subset']); this.addDatasetAction('TweetsActions', 'refresh', this.countTweets, 'Recount Tweets, Tweet Types, and Start/End Tweet', ['eventtype', 'event', 'subset', 'rumor','feature']); this.addDatasetAction('TweetsActions', 'scissors action-deletion', dataset => this.clearItems('tweets', dataset), 'Clear Tweet to Collection Mapping'); this.addDatasetAction('TweetsActions', 'download-alt', dataset => this.fetchDataToDownload(dataset, 'tweets'), 'Download Tweets'); this.addDatasetAction('TweetsActions', 'download', dataset => this.fetchDataToDownload(dataset, 'tweets_userprofiles'), 'Download Tweets & User Profiles'); // this.addDatasetAction('TweetsActions', 'new-window', this.openCodingReport, 'Open Coding Report'); // this.addDatasetAction('TweetsActions', 'new-window', this.openFeatureReport, 'Open Feature Report'); this.addDatasetAction('TimeseriesActions', 'list', this.computeTimeseries, 'Build Timeseries Data'); this.addDatasetAction('TimeseriesActions', 'refresh', this.countTimeseriesMinutes, 'Recount Timeseries Datapoints (Minutes)'); this.addDatasetAction('TimeseriesActions', 'scissors action-deletion', dataset => this.clearItems('timeseries', dataset), 'Clear Saved Timeseries'); this.addDatasetAction('TimeseriesActions', 'download-alt', dataset => this.fetchDataToDownload(dataset, 'timeseries'), 'Download Timeseries'); this.addDatasetAction('TimeseriesActions', 'new-window', this.openTimeseries, 'Open timeseries chart in new window'); this.addDatasetAction('UsersActions', 'list', this.computeUserList, 'Build User List'); this.addDatasetAction('UsersActions', 'refresh', this.countUsers, 'Recount Users'); this.addDatasetAction('UsersActions', 'scissors action-deletion', dataset => this.clearItems('users', dataset), 'Clear Saved User List'); this.addDatasetAction('UsersActions', 'download-alt', dataset => this.fetchDataToDownload(dataset, 'users'), 'Download User List'); this.addDatasetAction('UsersActions', 'download', dataset => this.fetchDataToDownload(dataset, 'users_userprofiles'), 'Download User List & User Profiles'); this.addDatasetAction('UsersActions', 'user', this.enqueueUsersToFetchData.bind(this), 'Fetch followers, friends, and recent tweets for users in this dataset by adding them to the queue for the FetchUserData python script to download using the Twitter API', ['rumorwithsubset', 'subset']); }, addDatasetAction: function(action_group, glyphicon, action, tooltip, dataset_types) { if(dataset_types == undefined) dataset_types = ['subset', 'rumorwithsubset', 'event']; var selector = dataset_types.map(d => '.row_' + d + ' .cell-' + action_group).join(', '); d3.select('tbody').selectAll(selector).append('span') .attr('class', 'glyphicon glyphicon-' + glyphicon + ' glyphicon-hoverclick action_button') .on('click', action.bind(this)) .on('mouseover', function(d) { this.tooltip.setData(tooltip); this.tooltip.on(); }.bind(this)) .on('mousemove', function(d) { this.tooltip.move(d3.event.x, d3.event.y); }.bind(this)) .on('mouseout', function(d) { this.tooltip.off(); }.bind(this));; }, prepareCollectionContextMenu: function(set) { var collectionType = (set.Level == 1 ? 'Event' : 'Subset'); var menu_options = [{ label: collectionType + ' ' + set.ID },{ label: '<span class="glyphicon glyphicon-edit"></span> Edit', action: this.edit.bind(this, set) // Gets the original db collection object, as opposed to our modified version }]; return menu_options; }, prepareCollectionTooltip: function(collection) { if(collection['CollectionType'] == 'EventType') { return { 'Click': 'to expand', 'Event Type': collection['Label'], Events: collection['events_arr'] ? collection['events_arr'].map(function(event) { return event['Label']; }) : null }; } else if(collection['CollectionType'] == 'Event') { return { ID: collection['ID'], Event: collection['Label'], 'Event Type': collection['Event Type']['Label'], Rumors: collection['rumors_arr'] ? collection['rumors_arr'].map(function(event) { return event['Label']; }) : null }; } else if(collection['CollectionType'] == 'Rumor') { return { 'Collection Type': 'Rumor', 'Rumor ID': collection['ID'], 'Subset ID': collection['Subset_ID'], 'Label': collection['Label'], Event: collection['Event']['Label'], 'Event Type': collection['Event Type']['Label'], Features: collection['features_arr'] ? collection['features_arr'].map(function(event) { return event['Label']; }) : null }; } else if(collection['CollectionType'] == 'Feature') { return { ID: collection['ID'], Feature: collection['Label'], Rumor: collection['Rumor']['Label'], Event: collection['Event']['Label'], 'Event Type': collection['Event Type']['Label'] }; } else if(collection['CollectionType'] == 'Subset') { return { ID: collection['ID'], Match: collection['Match'], Feature: collection['Feature']['Label'], Rumor: collection['Rumor']['Label'], Event: collection['Event']['Label'], 'Event Type': collection['Event Type']['Label'] }; } else { return "These subsets don't belong to any specific rumor."; } }, setVisibility_Rows_children: function(d, show_children) { var list_op = this.ops['Rows']['Level ' + d.Level + ' Showing Children']; var list = list_op.get(); // Toggle showing children or not if(show_children == undefined || typeof(show_children) == 'number') { // Not hard-coded, so just toggle show_children = !list.includes(d.ID); } else if (show_children == 'perserve') { // Only occurs during first initialization show_children = list.includes(d.ID) ? 'perserve' : false; } // Set the option if(show_children) { if(!list.includes(d.ID)) list.push(d.ID); } else { list = list.filter(function(set) { return set != d.ID; }); } list_op.set(list); this.ops.recordState(false); // Set the chevron to point the right direction d.row.select('.cell-Collection .glyphicon') .classed('glyphicon-chevron-down', show_children) .classed('glyphicon-chevron-left', !show_children); // Add/remove not shown class to subsets as appropriate var show_empties = this.ops['Rows']['Empties'].is('table-row'); d.children.forEach(function(child) { var show_child = show_children && (show_empties || !child.row.classed('row-zero')); child.row.classed('not_shown', !show_children) .style('display', show_child ? 'table-row' : 'none'); if('children' in child) this.setVisibility_Rows_children(child, show_children ? 'perserve' : false); }, this) }, setVisibility_Rows: function() { var table_body = d3.select('tbody'); table_body.selectAll('tr') .style('display', 'table-row'); if(this.ops['Rows']['Empties'].is('none')) { table_body.selectAll('tr.row-zero') .style('display', 'none'); } table_body.selectAll('tr.not_shown') .style('display', 'none'); triggers.emit('sort_elements'); }, setVisibility_Columns: function() { var table_head = d3.select('thead'); var table_body = d3.select('tbody'); var column_group_visibility = { Tweets: this.ops['Columns']['Tweet Type Counts'].is('shown'), Time: this.ops['Columns']['Dates'].is('shown'), Users: this.ops['Columns']['Repeat Users'].is('shown'), Actions: this.ops['Columns']['Actions'].is('shown') }; this.column_headers.forEach(function(column, i) { var column_display = column.always_display || column_group_visibility[column.Group] ? null : 'none'; table_head.select('tr th:nth-child(' + (i+1) + ')') .style('display', column_display); table_body.selectAll('tr td:nth-child(' + (i+1) + ')') .style('display', column_display); }, this); // Turn on/off deletion of data table_body.selectAll('.action-deletion') .style('display', this.ops['Columns']['Show Deletion'].is('shown') ? null : 'none') }, updateTableCounts: function(selector) { selector = selector || 'tbody'; var table_body = d3.select(selector); var distinct = this.ops['Columns']['Distinct'].get(); var relative = this.ops['Columns']['Relative'].get(); var date_format = this.ops['Columns']['Date Format'].get(); var minutes_format = this.ops['Columns']['Minutes Format'].get(); // Update the text of rows with the counts ['Tweets', 'Originals', 'Retweets', 'Replies', 'Quotes'].forEach(function(type) { var quantity = distinct + type; table_body.selectAll('.cell-' + type + ' .value') .html(function(d) { var value = d[quantity]; if(!value) return ''; if(relative == 'raw') { d[type + 'Display'] = value; return util.formatThousands(value); } var denom = relative == 'event' ? (d['Level'] >= 2 ? d['Event']['Tweets'] : d['Tweets']) : relative == 'type' ? (d['Level'] >= 2 ? d['Event'][quantity] : d[quantity]) : // relative == 'feature' ? (d['Level'] >= 3 ? d['Feature Set'][quantity] : d[quantity]): relative == 'subset' ? d['Tweets'] : relative == 'distinct' ? d[type] : 1; d[type + 'Display'] = value / denom; return (value / denom * 100).toFixed(1); }); }); table_body.selectAll('.cell-DistinctTweets .value') .html(function(dataset) { var quantity = 'DistinctTweets'; var value = dataset[quantity]; if(!value) return ''; if(relative == 'raw') { return util.formatThousands(value); } var denom = relative == 'event' ? (dataset['Level'] >= 2 ? dataset['Event']['Tweets'] : dataset['Tweets']) : relative == 'type' ? (dataset['Level'] >= 2 ? dataset['Event'][quantity] : dataset[quantity]) : // relative == 'feature' ? (dataset['Level'] >= 3 ? dataset['Feature Set'][quantity] : dataset[quantity]): relative == 'subset' ? dataset['Tweets'] : relative == 'distinct' ? dataset[quantity] : 1; return (value / denom * 100).toFixed(1); }); // Set visibility of zero/non-zero rows table_body.selectAll('tr') .classed('row-zero', function(d) { return !(d.Tweets || d.Minutes) ; }); // Dates table_body.selectAll('.cell-FirstTweet') .html(function(d) { if(!('FirstTweet') in d || d['FirstTweet'] == 0 || d['FirstTweet'] == 1e20) return ''; if(date_format == 'date') { var date = d.FirstTweet; date = util.twitterID2Timestamp(date); return util.formatDate(date); } return d.FirstTweet; }); table_body.selectAll('.cell-LastTweet') .html(function(d) { if(!('LastTweet') in d || d['LastTweet'] == 0 || d['LastTweet'] == 1e20) return ''; if(date_format == 'date') { var date = d.LastTweet; date = util.twitterID2Timestamp(date); return util.formatDate(date); } return d.LastTweet; // return 'LastTweet' in d && d.LastTweet ? d.LastTweet || '-' : ''; }); // Minutes table_body.selectAll(".cell-Minutes .value") .transition() .duration(1000) .tween("text", function (d) { var start = this.textContent; if(typeof(start) == 'string') { if(start.includes('m')) { start = util.deformatMinutes(start); } else { start = parseInt(start.replace(/ /g, '')); } } var interpol = d3.interpolate(start || 0, d['Minutes'] || 0); return function (value) { if(typeof(value) == 'string') { if(value.includes('m')) { value = util.deformatMinutes(value); } else { value = parseInt(value.replace(/ /g, '')); } } value = Math.round(interpol(value)); if(minutes_format == 'minutes') { this.textContent = util.formatMinutes(value); } else { this.textContent = util.formatThousands(value); } }; }); // Update regular integer counts ['Users','Users2orMoreTweets', 'Users10orMoreTweets'].forEach(function(quantity) { table_body.selectAll(".cell-" + quantity + " .value") .transition() .duration(1000) .tween("text", function (d) { var start = this.textContent; if(typeof(start) == 'string') { start = parseInt(start.replace(/ /g, '')); } var interpol = d3.interpolate(start || 0, d[quantity] || 0); return function (value) { if(typeof(value) == 'string') { value = parseInt(value.replace(/ /g, '')); } value = Math.round(interpol(value)); this.textContent = util.formatThousands(value); }; }); }, this); triggers.emit('refresh_visibility'); }, edit: function(collection) { if(collection.Level == 1) { // Event this.dataset.event = collection; triggers.emit('edit collection:open', 'event'); } else if(collection.Level == 4) { // Subset // If the object is modified, change how some of the fields are handled if('Event_ID' in collection) { collection = { ID: collection.ID, Event: collection.Event.ID, Rumor: collection.Rumor.ID, Superset: collection.Superset, Feature: collection.Feature.Label, Match: collection.Match, Notes: collection.Notes }; } this.dataset.subset = collection; triggers.emit('edit collection:open', 'subset'); } }, clickSort: function(order, option) { var table_body = d3.select('tbody'); if(!order) order = this.ops['Rows']['Order'].get(); var header = d3.select('.col-' + util.simplify(order)); var clicked = header.data()[0]; var order = this.ops['Rows']['Order'].get(); var ascending = this.ops['Rows']['Ascending'].get(); if(clicked) { d3.selectAll('.col-sortable span') .attr('class', 'glyphicon glyphicon-sort glyphicon-hiddenclick'); } // If it is clicked on what it is currently doing, flip it if(clicked == order && option != 'maintain_direction') { ascending = ascending == "true" ? "false" : "true"; this.ops['Rows']['Ascending'].updateInInterface_id(ascending); } else if (clicked) { // Otherwise it's a new order order = clicked; this.ops['Rows']['Order'].updateInInterface_id(order); if(option != 'maintain_direction') { ascending = order == 'Collection' ? 'true' : 'false'; this.ops['Rows']['Ascending'].updateInInterface_id(ascending); } } // Sort the columns if(this.ops['Rows']['Hierarchical'].is('true')) { var quantity = order.replace(' ', ''); if(quantity == 'Collection') quantity = 'Label'; if(['Tweets', 'Originals', 'Retweets', 'Replies', 'Quotes'].includes(quantity)) { quantity = quantity + 'Display'; } // var ascending_minmax = ascending == 'true' ? 'Min' : 'Max'; var ascending_bin = ascending == 'true' ? 1 : -1; table_body.selectAll('tr').sort(function(a, b) { var lA = a['Level']; var lB = b['Level']; // Compare up hierarchy for(var level = 0; level < 5; level++) { var type = this.hierarchy[level]; var A = a[type][quantity]; var B = b[type][quantity]; if(!A) return 1; if(!B) return -1; if(A < B) return -1 * ascending_bin; if(A > B) return 1 * ascending_bin; if(lA == level && lB == level) return a['ID'] - b['ID']; if(lA == level && lB > level) return -1; if(lA > level && lB == level) return 1; } return 0; }.bind(this)); } else { // var ascending_minmax = ascending == 'true' ? 'Max' : 'Min'; var ascending_bin = ascending == 'true' ? 1 : -1; if(order == 'ID') { table_body.selectAll('tr').sort(function(a, b) { var A = parseInt(a.ID); var B = parseInt(b.ID); if(a.Level == 0) { A = A || a['ID']; //_' + ascending_minmax]; } if(b.Level == 0) { B = B || b['ID']; //_' + ascending_minmax]; } var cmp = A - B; return ascending_bin * cmp || a.Level - b.Level; }); } else if(order == 'Collection') { table_body.selectAll('tr').sort(function(a, b) { var A = a.Label; var B = b.Label; return ascending_bin * d3.ascending(B, A); }); } else { var quantity = order.replace(' ', ''); if(['Tweets', 'Originals', 'Retweets', 'Replies', 'Quotes'].includes(quantity)) { quantity = quantity + 'Display'; } table_body.selectAll('tr').sort(function(a, b) { var A = parseFloat(a[quantity]); var B = parseFloat(b[quantity]); if(a.Level == 0) { A = A || parseFloat(a[quantity]); // + '_' + ascending_minmax]); } if(b.Level == 0) { B = B || parseFloat(b[quantity]); // + '_' + ascending_minmax]); } if(!A && !B) return 0; if(!A) return 1; if(!B) return -1; var cmp = d3.ascending(A, B); return ascending_bin * cmp || a.Level - b.Level; }); } } // Set the header's glyphicon class to reflect the order if(clicked) { if(ascending == 'true' && order == 'Collection') { header.select('span').attr('class', 'glyphicon glyphicon-sort-by-alphabet glyphicon-hoverclick'); } else if(ascending == 'false' && order == 'Collection') { header.select('span').attr('class', 'glyphicon glyphicon-sort-by-alphabet-alt glyphicon-hoverclick'); } else if(ascending == 'true') { header.select('span').attr('class', 'glyphicon glyphicon-sort-by-attributes glyphicon-hoverclick'); } else if(ascending == 'false') { header.select('span').attr('class', 'glyphicon glyphicon-sort-by-attributes-alt glyphicon-hoverclick'); } } }, deleteCollection: function(dataset) { // Refuse to delete rumors right now since that will affect multiple tables if(dataset.CollectionType == 'Rumor') { triggers.emit('alert', 'Unable to remove rumors'); return; } this.connection.phpjson( 'collection/delete', { collection_type: dataset.Level == 1 ? 'Event' : 'Subset', collection_id: dataset.Subset_ID || dataset.ID }, function(result) { d3.select(this.datasetRowID(dataset)).remove(); console.log('Deleted ' + dataset.CollectionType + ' ' + dataset.ID + ' (' + dataset.Label + ')'); }.bind(this) ); }, countTweets: function(dataset) { // If aggregate, then re-aggregate if(['EventType', 'Feature'].includes(dataset.CollectionType)) { this.aggregateSetChildrenCounts(dataset); this.updateTableCounts(this.datasetRowID(dataset)); // make labels for event features return; } // Prepare statement var post = { Collection: dataset.Level == 1 ? 'event' : 'subset', ID: dataset.Subset_ID || dataset.ID, } // Start loading sign var prog_bar = new Progress({ 'initial': 100, 'parent_id': this.datasetRowID(dataset) + ' .cell-Tweets', style: 'full', text: ' ' }); prog_bar.start(); // Start the recount this.connection.phpjson('collection/recount', post, function(result) { result = result[0]; this.quantities.forEach(function (quantity) { dataset[quantity] = parseInt(result[quantity]) || 0; }); dataset['FirstTweet'] = result['FirstTweet'] ? new BigNumber(result['FirstTweet']) : new BigNumber('0'); dataset['LastTweet'] = result['LastTweet'] ? new BigNumber(result['LastTweet']) : new BigNumber('0'); triggers.emit('update_counts', this.datasetRowID(dataset)); // Remove loading sign prog_bar.end(); }.bind(this), function(badresult) { console.log(badresult); prog_bar.update(100, 'Error'); }); }, clearItems: function(item_type, dataset) { this.connection.phpjson( 'collection/clearItems', { collection_type: dataset.Level == 1 ? 'Event' : 'Subset', collection_id: dataset.Subset_ID || dataset.ID, item_type: item_type }, function(result) { if(item_type == 'tweets') this.countTweets(dataset); else if(item_type == 'timeseries') this.countTimeseriesMinutes(dataset); else if(item_type == 'users') this.countUsers(dataset); console.log('Cleared ' + result[0]['Items Cleared'] + ' ' + item_type + ' from ' + dataset.CollectionType + ' ' + dataset.ID + ' (' + dataset.Label + ')'); }.bind(this) ); }, countTimeseriesMinutes: function(dataset) { this.connection.phpjson( 'timeseries/count', { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, }, this.updateTimeseriesMinutesDisplay.bind(this, dataset) ); }, computeTimeseries: function(dataset) { var args = { url: 'timeseries/compute', post: { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, json: true, }, quantity: 'tweet', min: dataset.FirstTweet, max: dataset.LastTweet, progress_div: this.datasetRowID(dataset) + ' .cell-Minutes', progress_text: ' ', progress_style: 'full', on_chunk_finish: this.updateTimeseriesMinutesDisplay.bind(this, dataset) } var conn = new Connection(args); conn.startStream(); }, updateTimeseriesMinutesDisplay: function(dataset, result) { dataset['Minutes'] = parseInt(result[0]['Minutes']); triggers.emit('update_counts', this.datasetRowID(dataset)); }, countUsers: function(dataset) { this.connection.phpjson( 'users/countInCollection', { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, }, this.updateUserCountDisplay.bind(this, dataset) ); }, computeUserList: function(dataset) { this.connection.phpjson( 'users/getUserLastCounted', { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, }, this.computeUserStream.bind(this, dataset) ); }, computeUserStream: function(dataset, lastTweet) { var firstTweet = lastTweet != undefined && lastTweet[0] && 'MAX(LastTweetID)' in lastTweet[0] && lastTweet[0]['MAX(LastTweetID)'] ? new BigNumber(lastTweet[0]['MAX(LastTweetID)']) : dataset.FirstTweet; var args = { url: 'users/computeUsersInCollection', post: { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, json: true, }, quantity: 'tweet', min: firstTweet, max: dataset.LastTweet, resolution: 0.25, progress_div: this.datasetRowID(dataset) + ' .cell-Users', progress_text: ' ', progress_style: 'full', on_chunk_finish: function(result) { dataset['Users'] = parseInt(result[0]['Users']); dataset['Users2orMoreTweets'] = parseInt(result[0]['Users2orMoreTweets']); dataset['Users10orMoreTweets'] = parseInt(result[0]['Users10orMoreTweets']); triggers.emit('update_counts', this.datasetRowID(dataset)); }.bind(this) } var conn = new Connection(args); conn.startStream(); }, updateUserCountDisplay: function(dataset, queryResult) { dataset['Users'] = parseInt(queryResult[0]['Users']); dataset['Users2orMoreTweets'] = parseInt(queryResult[0]['Users2orMoreTweets']); dataset['Users10orMoreTweets'] = parseInt(queryResult[0]['Users10orMoreTweets']); console.log('updating', this.datasetRowID(dataset), dataset); triggers.emit('update_counts', this.datasetRowID(dataset)); }, enqueueUsersToFetchData: function(dataset) { this.connection.phpjson( 'users/enqueueToFetchData', { Collection: dataset.Level == 1 ? 'Event' : 'Subset', ID: dataset.Subset_ID || dataset.ID, }, triggers.emitter('alert', { text: 'Sent ' + dataset.Users + ' Users to the Follower, Friend, & Tweet Fetching Queue. May take awhile.', style_class: 'info' }) ); }, datasetRowID: function(dataset) { return '.row_' + dataset.CollectionType.toLowerCase() + '_' + dataset.ID; }, openTimeseries: function(d) { var state = JSON.stringify({Dataset: {Event: d.ID}}); window.open('timeseries.html#' + state); }, openCodingReport: function(d) { var state = JSON.stringify({subset: d.ID}); window.open('coding.html#' + state); }, setInfo: function(set) { var distinct = this.ops['Columns']['Distinct'].get(); console.log(this); var type = 'Tweets'; var value = set[distinct + type]; var info = {}; if(value == undefined) return info; var event = set['Event'] || set; info[(distinct ? distinct + ' ' : '') + type] = util.formatThousands(value); info['% of Event' ] = (value / event['Tweets'] * 100).toFixed(1) + '%'; info['% of Type in Event' ] = (value / event[distinct + type] * 100).toFixed(1) + '%'; info['% of Subset' ] = (value / set['Tweets'] * 100).toFixed(1) + '%'; info['% of Distinct + Repeats'] = (value / set[type] * 100).toFixed(1) + '%'; console.log(info); return info; }, buildNewDatasetOption: function() { var div = d3.select('#body').append('div'); div.append('button') .attr('class', 'btn btn-default new-collection-button') .data(['Create a new event. This function is in still being worked on.']) .text('New Event') .on('click', triggers.emitter('edit collection:new', 'event')); div.append('button') .attr('class', 'btn btn-default new-collection-button') .data(['Create a new subset. This function is in still being worked on.']) .text('New Subset') .on('click', triggers.emitter('edit collection:new', 'subset')); // div.append('button') // .attr('class', 'btn btn-default new-collection-button') // .text('Add Tweets to Event') // .on('click', triggers.emitter('alert', 'Sorry this button doesn\'t work yet')); // // div.append('button') // .attr('class', 'btn btn-default new-collection-button') // .text('Add Tweets to Subset') // .on('click', triggers.emitter('alert', 'Sorry this button doesn\'t work yet')); div.append('button') .attr('class', 'btn btn-default new-collection-button') .data(['End any downloads in progress']) .text('End Download') .on('click', this.endDownload.bind(this)); // Only here to move tweets from old version of the tweet table to new version if necessary // div.append('button') // .attr('id', 'tweet-transfer') // .attr('class', 'btn btn-default new-collection-button') // .data(['Transfer tweets from Old Table to New Table. Only Conrad should press this']) // .text('Transfer Tweets') // .on('click', this.transferTweets.bind(this)); this.tooltip.attach('.new-collection-button', d => d); }, transferTweets: function () { var connection = new Connection({ url: 'tweets/transferTweets', post: {}, min : 0, max: 1000, quantity: 'count', progress_text: '{cur} / {max}', on_chunk_finish: function(d) { console.log(d); } }); connection.startStream(); }, fetchDataToDownload: function(dataset, dataType) { var collection_type = dataset.Level == 1 ? 'Event' : 'Subset'; // Since rumors are considered subsets var collection_id = dataset.Subset_ID || dataset.ID; var url = dataType.includes('tweets') ? 'tweets/get' : dataType.includes('timeseries') ? 'timeseries/get' : dataType.includes('users') ? 'users/get' : 'tweets/getUsers'; var pk_query = dataType.includes('tweets') ? 'tweet_min' : dataType.includes('timeseries') ? 'time_min' : dataType.includes('users') ? 'user_min' : 'tweet_min'; var pk_table = dataType.includes('tweets') ? 'ID' : dataType.includes('timeseries') ? 'Time' : dataType.includes('users') ? 'UserID' : 'ID'; var nEntries = dataType.includes('tweets') ? dataset.Tweets : dataType.includes('timeseries') ? dataset.Minutes : dataType.includes('users') ? dataset.Users : dataset.Tweets; if(this.download.stream) { triggers.emit('alert', 'Cannot download data, existing download stream is running'); } this.download = { stream: false, dataset: dataset, data: [], datatype: dataType, filename: dataType + '_' + dataset.CollectionType + '_' + collection_id + '.csv', page: 0, entries: nEntries, limit: 5000, entries_in_cache:0 }; var post = { collection: collection_type, collection_id: collection_id, extradata: '', json: true, }; if(dataType.includes('profiles')) post.extradata += 'u'; if(dataType.includes('parents')) post.extradata += 'p'; // Initialize the connection this.download.stream = new Connection({ url: url, post: post, quantity: 'count', resolution: this.download.limit, max: nEntries, pk_query: pk_query, pk_table: pk_table, on_chunk_finish: this.mergeDownloadData.bind(this), on_finish: this.endDownload.bind(this), progress_text: '{cur}/{max} Fetched for Download', }); // Start the connection this.download.stream.startStream(); }, mergeDownloadData: function(newData) { // End early if no more data if(newData.length == 0) { this.endDownload(); } // // Estimate CSV size // this.download.entries_in_cache += this.download.limit; $.merge(this.download.data, newData); // Save file if we already have 200k entries, otherwise it starts to slow down significantly if(this.download.data.length >= 100000) { this.submitDownloadedDataToUser(true); } }, submitDownloadedDataToUser: function(paged) { var filename = this.download.filename; if(paged) { filename = filename.split(".")[0] + "_page" + this.download.page + ".csv"; this.download.page++; } // Fix any formatting problems with the data var data = this.download.data; data.forEach(function(datum) { if('Text' in datum) datum.Text = datum.Text.replace(/(?:\r\n|\r|\n)/g, ' '); if('Description' in datum && datum.Description) datum.Description = datum.Description.replace(/(?:\r\n|\r|\n)/g, ' '); // var text_no_url = tweet.Text.replace(/(?:http\S+)/g, ' '); // // if(tweet_text_unique.has(text_no_url)) { // tweet.Distinct = 0; // } else { // tweet_text_unique.add(text_no_url); // if(tweets_unique.length < 100) { // tweets_unique.push(tweet); // } // } }); // Send data to user data = d3.csv.format(data); if(this.download.datatype == "tweets") // The first column should NOT start with the word ID data = "Tweet " + data; this.fileDownload(data, filename, 'text/csv'); this.download.data = []; }, endDownload: function() { this.download.stream.stop(); this.download.stream.progress.end(); if(this.download.data.length == 0) { triggers.emitter('alert','Unable to download ' + this.download.datatype); } else { this.submitDownloadedDataToUser(this.download.page > 0); } // Erase local data this.download = { stream: false, dataset: false, data: [], datatype: '', filename: '', page: 0, entries: 0, limit: 5000, entries_in_cache:0 }; }, fileDownload: function(content, fileName, mimeType) { // var a = document.createElement('a'); var fileName = fileName || 'data.csv'; var mimeType = mimeType || 'text/csv'; // 'application/octet-stream'; // "application/csv;charset=utf-8;" var blob = new Blob([ content ], {type : mimeType}); if (window.navigator.msSaveBlob) { // FOR IE BROWSER navigator.msSaveBlob(blob, fileName); } else { // FOR OTHER BROWSERS var link = document.createElement("a"); var csvUrl = URL.createObjectURL(blob); link.href = csvUrl; link.style = "visibility:hidden"; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); } // if (navigator.msSaveBlob) { // IE10 // return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName); // } else if ('download' in a) { //html5 A[download] // a.href = 'data:' + mimeType + ',' + encodeURIComponent(content); // a.setAttribute('download', fileName); // document.body.appendChild(a); // setTimeout(function() { // a.click(); // document.body.removeChild(a); // }, 66); // return true; // } else { //do iframe dataURL download (old ch+FF): // var f = document.createElement('iframe'); // document.body.appendChild(f); // f.src = 'data:' + mimeType + ',' + encodeURIComponent(content); // // setTimeout(function() { // document.body.removeChild(f); // }, 333); // return true; // } }, makeScrollHeader: function() { this.floating_header = d3.select('body').append('div') .attr('class', 'thead-floating'); this.floating_header.selectAll('div') .data(this.column_headers) .enter() .append('div') .attr('class', 'col-floating') .style('display', 'none') .html(dataset => dataset.Label) .each(function(dataset) { dataset.static_header = d3.select('.col-' + dataset.ID).node().parentNode; dataset.floating_header = d3.select(this); }); }, perserveHeader: function() { var scrollTop = $(window).scrollTop(); var scrollLeft = $(window).scrollLeft(); var tableTop = $('thead').offset().top; this.floating_header .style('opacity', scrollTop > tableTop ? 1 : 0) .style('left', '-' + scrollLeft + 'px'); if(scrollTop > tableTop) { // Turn on the floating header this.floating_header .style('opacity', 1); // Fix inner cells TODO this doesn't need to be redone every time this.floating_header.selectAll('div') .each(function(dataset, i) { var box = dataset.static_header.getBoundingClientRect(); if(box.width > 0) { dataset.floating_header.style({ width: box.width + 'px', display: 'inline-block' }); } else { dataset.floating_header.style({ left: '0px', display: 'none' }) } }); } } }; function initialize() { DT = new DatasetTable(); DT.init(); } window.onload = initialize;
/** * -------------------------------------------------------------------------- * Bootstrap (v5.1.3): collapse.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ import { defineJQueryPlugin, getElement, getElementFromSelector, getSelectorFromElement, reflow } from './util/index' import EventHandler from './dom/event-handler' import SelectorEngine from './dom/selector-engine' import BaseComponent from './base-component' /** * Constants */ const NAME = 'collapse' const DATA_KEY = 'bs.collapse' const EVENT_KEY = `.${DATA_KEY}` const DATA_API_KEY = '.data-api' const EVENT_SHOW = `show${EVENT_KEY}` const EVENT_SHOWN = `shown${EVENT_KEY}` const EVENT_HIDE = `hide${EVENT_KEY}` const EVENT_HIDDEN = `hidden${EVENT_KEY}` const EVENT_CLICK_DATA_API = `click${EVENT_KEY}${DATA_API_KEY}` const CLASS_NAME_SHOW = 'show' const CLASS_NAME_COLLAPSE = 'collapse' const CLASS_NAME_COLLAPSING = 'collapsing' const CLASS_NAME_COLLAPSED = 'collapsed' const CLASS_NAME_DEEPER_CHILDREN = `:scope .${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}` const CLASS_NAME_HORIZONTAL = 'collapse-horizontal' const WIDTH = 'width' const HEIGHT = 'height' const SELECTOR_ACTIVES = '.collapse.show, .collapse.collapsing' const SELECTOR_DATA_TOGGLE = '[data-bs-toggle="collapse"]' const Default = { toggle: true, parent: null } const DefaultType = { toggle: 'boolean', parent: '(null|element)' } /** * Class definition */ class Collapse extends BaseComponent { constructor(element, config) { super(element, config) this._isTransitioning = false this._triggerArray = [] const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE) for (const elem of toggleList) { const selector = getSelectorFromElement(elem) const filterElement = SelectorEngine.find(selector) .filter(foundElem => foundElem === this._element) if (selector !== null && filterElement.length) { this._triggerArray.push(elem) } } this._initializeChildren() if (!this._config.parent) { this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()) } if (this._config.toggle) { this.toggle() } } // Getters static get Default() { return Default } static get DefaultType() { return DefaultType } static get NAME() { return NAME } // Public toggle() { if (this._isShown()) { this.hide() } else { this.show() } } show() { if (this._isTransitioning || this._isShown()) { return } let activeChildren = [] // find active children if (this._config.parent) { activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES) .filter(element => element !== this._element) .map(element => Collapse.getOrCreateInstance(element, { toggle: false })) } if (activeChildren.length && activeChildren[0]._isTransitioning) { return } const startEvent = EventHandler.trigger(this._element, EVENT_SHOW) if (startEvent.defaultPrevented) { return } for (const activeInstance of activeChildren) { activeInstance.hide() } const dimension = this._getDimension() this._element.classList.remove(CLASS_NAME_COLLAPSE) this._element.classList.add(CLASS_NAME_COLLAPSING) this._element.style[dimension] = 0 this._addAriaAndCollapsedClass(this._triggerArray, true) this._isTransitioning = true const complete = () => { this._isTransitioning = false this._element.classList.remove(CLASS_NAME_COLLAPSING) this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW) this._element.style[dimension] = '' EventHandler.trigger(this._element, EVENT_SHOWN) } const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1) const scrollSize = `scroll${capitalizedDimension}` this._queueCallback(complete, this._element, true) this._element.style[dimension] = `${this._element[scrollSize]}px` } hide() { if (this._isTransitioning || !this._isShown()) { return } const startEvent = EventHandler.trigger(this._element, EVENT_HIDE) if (startEvent.defaultPrevented) { return } const dimension = this._getDimension() this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px` reflow(this._element) this._element.classList.add(CLASS_NAME_COLLAPSING) this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW) for (const trigger of this._triggerArray) { const elem = getElementFromSelector(trigger) if (elem && !this._isShown(elem)) { this._addAriaAndCollapsedClass([trigger], false) } } this._isTransitioning = true const complete = () => { this._isTransitioning = false this._element.classList.remove(CLASS_NAME_COLLAPSING) this._element.classList.add(CLASS_NAME_COLLAPSE) EventHandler.trigger(this._element, EVENT_HIDDEN) } this._element.style[dimension] = '' this._queueCallback(complete, this._element, true) } _isShown(element = this._element) { return element.classList.contains(CLASS_NAME_SHOW) } // Private _configAfterMerge(config) { config.toggle = Boolean(config.toggle) // Coerce string values config.parent = getElement(config.parent) return config } _getDimension() { return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT } _initializeChildren() { if (!this._config.parent) { return } const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE) for (const element of children) { const selected = getElementFromSelector(element) if (selected) { this._addAriaAndCollapsedClass([element], this._isShown(selected)) } } } _getFirstLevelChildren(selector) { const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent) // remove children if greater depth return SelectorEngine.find(selector, this._config.parent).filter(elem => !children.includes(elem)) } _addAriaAndCollapsedClass(triggerArray, isOpen) { if (!triggerArray.length) { return } for (const elem of triggerArray) { if (isOpen) { elem.classList.remove(CLASS_NAME_COLLAPSED) } else { elem.classList.add(CLASS_NAME_COLLAPSED) } elem.setAttribute('aria-expanded', isOpen) } } // Static static jQueryInterface(config) { return this.each(function () { const _config = {} if (typeof config === 'string' && /show|hide/.test(config)) { _config.toggle = false } const data = Collapse.getOrCreateInstance(this, _config) if (typeof config === 'string') { if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`) } data[config]() } }) } } /** * Data API implementation */ EventHandler.on(document, EVENT_CLICK_DATA_API, SELECTOR_DATA_TOGGLE, function (event) { // preventDefault only for <a> elements (which change the URL) not inside the collapsible element if (event.target.tagName === 'A' || (event.delegateTarget && event.delegateTarget.tagName === 'A')) { event.preventDefault() } const selector = getSelectorFromElement(this) const selectorElements = SelectorEngine.find(selector) for (const element of selectorElements) { Collapse.getOrCreateInstance(element, { toggle: false }).toggle() } }) /** * jQuery */ defineJQueryPlugin(Collapse) export default Collapse
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; module.exports = { moduleType: 'locale', name: 'ar', dictionary: {}, format: { days: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'], shortDays: [ 'الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت' ], months: [ 'كانون الثاني', 'شباط', 'آذار', 'نيسان', 'آذار', 'حزيران', 'تموز', 'آب', 'أيلول', 'تشرين الأول', 'تشرين الثاني', 'كانون الأول' ], shortMonths: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], date: '%d/%m/%Y' } };
particlesJS('particles-js', { particles: { color: '#000', // Color del vertice color_random: false, shape: 'edge', // "circle", "edge" or "triangle" // Establecemos cual de las 3 figuras queremos para vertice opacity: { opacity: 1, // Opacidad del vertice anim: { enable: true, speed: 1.5, opacity_min: 0, sync: false } }, size: 4, size_random: true, nb: 150, line_linked: { enable_auto: true, distance: 100, color: '#000', // Color de la arista opacity: 1, // Opacidad de la arista width: 1, condensed_mode: { enable: false, rotateX: 600, rotateY: 600 } }, anim: { enable: true, speed: 1 // Velocidad a la que se mueven las aristas } }, interactivity: { enable: true, mouse: { distance: 300 }, detect_on: 'canvas', // "canvas" or "window" mode: 'grab', // "grab" of false line_linked: { opacity: .5 }, events: { onclick: { enable: true, mode: 'push', // "push" or "remove" nb: 4 }, onresize: { enable: true, mode: 'out', // "out" or "bounce" density_auto: false, density_area: 800 // nb_particles = particles.nb * (canvas width * canvas height / 1000) / density_area } } }, /* Retina Display Support */ retina_detect: true });
{ babelHelpers.inherits(Test, _Foo); function Test() { var _ref, _babelHelpers$get; var _this; babelHelpers.classCallCheck(this, Test); woops.super.test(); _this = babelHelpers.possibleConstructorReturn( this, (Test.__proto__ || Object.getPrototypeOf(Test)).call(this) ); babelHelpers .get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", _this ) .call(_this); _this = babelHelpers.possibleConstructorReturn( this, (Test.__proto__ || Object.getPrototypeOf(Test)).apply(this, arguments) ); _this = babelHelpers.possibleConstructorReturn( this, (_ref = Test.__proto__ || Object.getPrototypeOf(Test)).call.apply( _ref, [this, "test"].concat(Array.prototype.slice.call(arguments)) ) ); babelHelpers .get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", _this ) .apply(_this, arguments); (_babelHelpers$get = babelHelpers.get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", _this )).call.apply( _babelHelpers$get, [_this, "test"].concat(Array.prototype.slice.call(arguments)) ); return _this; } babelHelpers.createClass( Test, [ { key: "test", value: function test() { var _babelHelpers$get2; babelHelpers .get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", this ) .call(this); babelHelpers .get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", this ) .apply(this, arguments); (_babelHelpers$get2 = babelHelpers.get( Test.prototype.__proto__ || Object.getPrototypeOf(Test.prototype), "test", this )).call.apply( _babelHelpers$get2, [this, "test"].concat(Array.prototype.slice.call(arguments)) ); } } ], [ { key: "foo", value: function foo() { var _babelHelpers$get3; babelHelpers .get(Test.__proto__ || Object.getPrototypeOf(Test), "foo", this) .call(this); babelHelpers .get(Test.__proto__ || Object.getPrototypeOf(Test), "foo", this) .apply(this, arguments); (_babelHelpers$get3 = babelHelpers.get( Test.__proto__ || Object.getPrototypeOf(Test), "foo", this )).call.apply( _babelHelpers$get3, [this, "test"].concat(Array.prototype.slice.call(arguments)) ); } } ] ); return Test; }
import Ember from 'ember'; export default function aggregateQuery (store, config, type, query) { var url = config.host + '/api/' + type + '/aggregate?query=' + JSON.stringify(query); return Ember.$.ajax(url, 'GET'); };
"use strict"; module.exports = { //copy all the files from the various locations (src, dependencies) into the build folder copy: { // Copy the local files found in the assets folder to the assets folder in the build directory. //The build directory is a staging area where we can freely manuliplate the files without changing the source local_assets_to_build:{ files:[ { cwd:'src/assets', src:['**', '!**/*.md'], dest:'<%= build_directory %>/assets/', expand:true } ] }, //copy all the dependencies defined in the build.config.js into the build assets directory dependencies_assets_to_build_assets: { files: [ { src: [ '<%= dependencies.assets %>' ], dest: '<%= build_directory %>/assets/', cwd: '.', expand: true, flatten: true } ] }, //copy all the app javascript files into the build directory. Keeping the folder structure in place. app_javascript_to_build_javascript: { files: [ { src: [ '<%= app.js %>' ], dest: '<%= build_directory %>/', cwd: '.', expand: true } ] }, //copy all the app javascript files into the build directory. Keeping the folder structure in place. app_styles_to_build_styles: { files: [ { src: [ 'src/**/*.css', 'src/**/*.less', 'src/**/*.otf', 'src/**/*.eot', 'src/**/*.svg', 'src/**/*.ttf', 'src/**/*.woff', '!**/*.md' ], dest: '<%= build_directory %>/', cwd: '.', expand: true } ] }, //copy the declared dependencies in the build.config.js to the build directory dependencies_javascript_to_build_javascript: { files: [ { src: [ '<%= dependencies.js %>' ], dest: '<%= build_directory %>/', cwd: '.', expand: true } ] }, dependencies_css_to_build_css: { files: [ { src: [ '<%= dependencies.css %>' ], dest: '<%= build_directory %>/', cwd: '.', expand: true } ] }, dependencies_artifacts_to_build_artifacts: { files: [ { src: [ '<%= dependencies.artifacts %>' ], dest: '<%= build_directory %>/', cwd: '.', expand: true } ] }, //We are not doing anything (compiling) with the assets, copy them into the bin/assets directory. copy_assets_to_bin: { files: [ { src: [ '**','!**/*.less', '!**/*.js', '!**/*.css', '!**/*.md' ], dest: '<%= bin_directory %>/assets', cwd: 'src/assets', expand: true } ] }, copy_common_to_bin: { files: [ { src: [ '**','!**/*.less', '!**/*.js', '!**/*.css', '!**/*.md' ], dest: '<%= bin_directory %>/common', cwd: 'src/common', expand: true } ] }, copy_all_to_bin: { files: [ { src: [ '**', '!**/*.less','!src/less', '!**/*.md'], dest: '<%= bin_directory %>/', cwd: '<%= build_directory %>/', expand: true } ] } } };
// Copyright (C) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * Parses a string of well-formed JSON text. * * If the input is not well-formed, then behavior is undefined, but it is * deterministic and is guaranteed not to modify any object other than its * return value. * * This does not use `eval` so is less likely to have obscure security bugs than * json2.js. * It is optimized for speed, so is much faster than json_parse.js. * * This library should be used whenever security is a concern (when JSON may * come from an untrusted source), speed is a concern, and erroring on malformed * JSON is *not* a concern. * * Pros Cons * +-----------------------+-----------------------+ * json_sans_eval.js | Fast, secure | Not validating | * +-----------------------+-----------------------+ * json_parse.js | Validating, secure | Slow | * +-----------------------+-----------------------+ * json2.js | Fast, some validation | Potentially insecure | * +-----------------------+-----------------------+ * * json2.js is very fast, but potentially insecure since it calls `eval` to * parse JSON data, so an attacker might be able to supply strange JS that * looks like JSON, but that executes arbitrary javascript. * If you do have to use json2.js with untrusted data, make sure you keep * your version of json2.js up to date so that you get patches as they're * released. * * @param {string} json per RFC 4627 * @return {Object|Array} * @author Mike Samuel <mikesamuel@gmail.com> */ var jsonParse = (function () { var number = '(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)'; var oneChar = '(?:[^\\0-\\x08\\x0a-\\x1f\"\\\\]' + '|\\\\(?:[\"/\\\\bfnrt]|u[0-9A-Fa-f]{4}))'; var string = '(?:\"' + oneChar + '*\")'; // Will match a value in a well-formed JSON file. // If the input is not well-formed, may match strangely, but not in an unsafe // way. // Since this only matches value tokens, it does not match whitespace, colons, // or commas. var jsonToken = new RegExp( '(?:false|true|null|[\\{\\}\\[\\]]' + '|' + number + '|' + string + ')', 'g'); // Matches escape sequences in a string literal var escapeSequence = new RegExp('\\\\(?:([^u])|u(.{4}))', 'g'); // Decodes escape sequences in object literals var escapes = { '"': '"', '/': '/', '\\': '\\', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t' }; function unescapeOne(_, ch, hex) { return ch ? escapes[ch] : String.fromCharCode(parseInt(hex, 16)); } // A non-falsy value that coerces to the empty string when used as a key. var EMPTY_STRING = new String(''); var SLASH = '\\'; // Constructor to use based on an open token. var firstTokenCtors = { '{': Object, '[': Array }; return function (json) { // Split into tokens var toks = json.match(jsonToken); // Construct the object to return var result; var tok = toks[0]; if ('{' === tok) { result = {}; } else if ('[' === tok) { result = []; } else { throw new Error(tok); } // If undefined, the key in an object key/value record to use for the next // value parsed. var key; // Loop over remaining tokens maintaining a stack of uncompleted objects and // arrays. var stack = [result]; for (var i = 1, n = toks.length; i < n; ++i) { tok = toks[i]; var cont; switch (tok.charCodeAt(0)) { default: // sign or digit cont = stack[0]; cont[key || cont.length] = +(tok); key = void 0; break; case 0x22: // '"' tok = tok.substring(1, tok.length - 1); if (tok.indexOf(SLASH) !== -1) { tok = tok.replace(escapeSequence, unescapeOne); } cont = stack[0]; if (!key) { if (cont instanceof Array) { key = cont.length; } else { key = tok || EMPTY_STRING; // Use as key for next value seen. break; } } cont[key] = tok; key = void 0; break; case 0x5b: // '[' cont = stack[0]; stack.unshift(cont[key || cont.length] = []); key = void 0; break; case 0x5d: // ']' stack.shift(); break; case 0x66: // 'f' cont = stack[0]; cont[key || cont.length] = false; key = void 0; break; case 0x6e: // 'n' cont = stack[0]; cont[key || cont.length] = null; key = void 0; break; case 0x74: // 't' cont = stack[0]; cont[key || cont.length] = true; key = void 0; break; case 0x7b: // '{' cont = stack[0]; stack.unshift(cont[key || cont.length] = {}); key = void 0; break; case 0x7d: // '}' stack.shift(); break; } } // Fail if we've got an uncompleted object. if (stack.length) { throw new Error(); } return result; }; })();
import { Meteor } from 'meteor/meteor'; import md5 from 'md5'; import { ValidatedMethod } from 'meteor/mdg:validated-method'; import { setAdminSchema, removeAdminSchema, setNameSchema, setAvatarSchema, } from './schema.js'; export const setAdmin = new ValidatedMethod({ name: 'users.setAdmin', validate: setAdminSchema.validator({ clean: true }), run({ userId }) { const user = Meteor.user(); if (user && user.isAdmin) { return Meteor.users.update(userId, { $set: { isAdmin: true } }); } throw new Meteor.Error( 'no-permissions-to-set-admin', 'You do not have permission to set admin', ); }, }); export const removeAdmin = new ValidatedMethod({ name: 'users.removeAdmin', validate: removeAdminSchema.validator({ clean: true }), run({ userId }) { const user = Meteor.user(); if (user && user.isAdmin) { return Meteor.users.update(userId, { $set: { isAdmin: false } }); } throw new Meteor.Error( 'no-permissions-to-remove-admin', 'You do not have permission to remove admin', ); }, }); export const setProfileName = new ValidatedMethod({ name: 'users.setName', validate: setNameSchema.validator({ clean: true }), run({ name }) { const userId = Meteor.userId(); if (userId) { return Meteor.users.update(userId, { $set: { 'profile.name': name, }, }); } return undefined; }, }); export const setAvatar = new ValidatedMethod({ name: 'users.setAvatar', validate: setAvatarSchema.validator({ clean: true }), run({ service, address }) { const user = Meteor.user(); const userId = user._id; if (address && service === 'gravatar') { const emailHash = md5(address); return Meteor.users.update(userId, { $set: { 'profile.avatar': `https://s.gravatar.com/avatar/${emailHash}`, }, }); } if (user.services.github && service === 'github') { const username = user.services.github.username; return Meteor.users.update(userId, { $set: { 'profile.avatar': `https://github.com/${username}.png`, }, }); } return undefined; }, });
'use strict'; /** * @ngdoc function * @name cpWebApp.controller:SigninCtrl * @description * # SigninCtrl * Controller of the cpWebApp */ angular.module('cpWebApp') .controller('ProfileCtrl', function ($scope, $rootScope, $location, authService, growl) { $scope.currentPassword = ""; $scope.newPassword = ""; $scope.newLogin = ""; $scope.name = $rootScope.user.name; $scope.email = $rootScope.user.email; $scope.deleteAccount = function () { console.log("delete Account"); authService.deleteAccount( function (res) { $location.path('/'); growl.info("Account removed", {ttl: 5000}); }, function (err) { growl.error("Failed to login, check your username and password"); } ); }; $scope.changePassword = function () { console.log("changePassword"); authService.changeUserPassword( $scope.currentPassword, $scope.newPassword, function (res) { growl.success("Password changed"); $scope.currentPassword = ""; $scope.newPassword = ""; automaticLogoutToCheckPwd(); }, function (err) { growl.error("Failed to change your password: " + err); } ); }; $scope.linkToAccount = function () { console.log("linkToAccount"); var user = {login: $scope.newLogin, password: $scope.newPassword}; authService.addLoginAndPasswordForExistingUser( user, function (res) { growl.success("Account linked"); $scope.newPassword = ""; $scope.newLogin = ""; automaticLogoutToCheckPwd(); }, function (err) { growl.error("Failed to link account: " + err); } ); }; $scope.updatePersonalInfo = function () { console.log("updatePersonalInfo"); var user = {name: $scope.name, email: $scope.email}; authService.updateUserInfo( user, function (res) { growl.success("Personal info updated"); }, function (err) { growl.error("Failed to update personal info: " + err); } ); }; var automaticLogoutToCheckPwd = function () { authService.logout( function (res) { $location.path('/signin'); growl.info("Automatic logged out, check your password", {ttl: 5000}); }, function (err) { growl.error("System error: failed to logout"); } ); }; });
/** * 标尺线 * * @author zhangq * @date 2017-06-20 */ Ext.define('Brick.portal.layout.RulerLine', { extend: 'Ext.Component', /** * 方向(`v` 或 `h`) */ dir: 'v', x: 0, y: 0, renderTo: document.body, initComponent: function () { this.autoEl = { tag: 'div', cls: 'p-layout-rulerline-' + this.dir }; this.callParent(); }, draw: function (min, max) { if (this.dir === 'v') { this.setXY([this.x, min]); this.setHeight(max - min); } else if (this.dir === 'h') { this.setXY([min, this.y]); this.setWidth(max - min); } } });
lychee.define('game.scene.Overlay').includes([ 'lychee.ui.Graph' ]).exports(function(lychee, global) { var Class = function(game, settings) { this.game = game; this.__loop = game.loop; this.__root = null; this.__visible = true; lychee.ui.Graph.call(this, game.renderer); this.reset(settings); }; Class.prototype = { reset: function(data) { if (this.__root === null) { this.__root = this.add(new lychee.ui.Tile({ color: '#222222', width: data.width, height: data.height, position: { x: data.position.x, y: data.position.y } })); this.__intro = this.add(new lychee.ui.Text({ text: '3', font: this.game.fonts.headline, position: { x: 0, y: 0 } }), this.__root).entity; } else { this.__root.width = data.width; this.__root.height = data.height; this.__root.setPosition(data.position); } }, enter: function() { if (this.game.settings.sound === true) { this.game.jukebox.play('countdown'); } this.__visible = true; this.__loop.timeout(0, function(clock, delta) { this.__intro.set('3'); }, this); this.__loop.timeout(1000, function() { this.__intro.set('2'); }, this); this.__loop.timeout(2000, function() { this.__intro.set('1'); }, this); this.__loop.timeout(3000, function() { this.__intro.set('Go!'); }, this); this.__loop.timeout(4000, function() { this.__visible = false; }, this); }, leave: function() { }, render: function() { if (this.__visible === true) { this.__renderNode( this.__tree, this.__offset.x, this.__offset.y ); } }, isVisible: function() { return this.__visible === true; }, /* * PRIVATE API */ __renderNode: function(node, offsetX, offsetY) { if (node.entity !== null) { if (node === this.__root) { this.__renderer.setAlpha(0.5); } this.__renderer.renderUIEntity(node.entity, offsetX, offsetY); offsetX += node.entity.getPosition().x; offsetY += node.entity.getPosition().y; if (node === this.__root) { this.__renderer.setAlpha(1); } } for (var c = 0, l = node.children.length; c < l; c++) { this.__renderNode(node.children[c], offsetX, offsetY); } } }; return Class; });
import React from 'react' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' const SelectTypeExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Select' description='Default Select.' examplePath='addons/Select/Types/SelectExample' /> </ExampleSection> ) export default SelectTypeExamples
// Regular expression that matches all symbols in the `Miao` script as per Unicode v10.0.0: /\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]/;
var gulp = require('gulp'); var gutil = require('gulp-util'); var bower = require('bower'); var sass = require('gulp-sass'); var cleanCss = require('gulp-clean-css'); var rename = require('gulp-rename'); var sh = require('shelljs'); var fs = require('fs'); var shell = require('gulp-shell'); var deleteLines = require('gulp-delete-lines'); var json = JSON.parse(fs.readFileSync('./tw.package.json')); var BILLING_KEY = process.env.BILLING_KEY || '111'; var SENDER_ID = process.env.SENDER_ID || '111'; var FABRIC_API_KEY = process.env.FABRIC_API_KEY || '111'; var FABRIC_API_SECRET = process.env.FABRIC_API_SECRET || '111'; var paths = { sass: ['./scss/**/*.scss'] }; gulp.task('default', ['sass']); gulp.task('sass', function(done) { gulp.src('./scss/ionic.app.scss') .pipe(sass({ errLogToConsole: true })) .pipe(gulp.dest('./www/css/')) .pipe(cleanCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('./www/css/')) .on('end', done); }); gulp.task('watch', ['sass'], function() { gulp.watch(paths.sass, ['sass']); }); gulp.task('install', ['git-check'], function() { return bower.commands.install() .on('log', function(data) { gutil.log('bower', gutil.colors.cyan(data.id), data.message); }); }); gulp.task('build', shell.task([ 'ionic state reset', 'cp -a ../ios platforms/', 'ionic state restore --plugins', 'yarn install', 'bower install', 'gulp sass', 'ionic build' ])); gulp.task('build_tw_ios', shell.task([ 'cp tw.package.json package.json', 'cp tw.config.xml config.xml', 'cp tw.ads.client.config.js www/client.config.js', 'rm -rf resources;cp -a tw.resources resources', 'cp package.json import_today_ext/package.json.backup', 'cp import_today_ext/tw.empty.package.json package.json', 'ionic state reset', 'cp -a ../tw.ios/* platforms/ios/', 'mv import_today_ext/package.json.backup package.json', 'ionic state restore --plugins', 'cordova plugin add cordova-plugin-inapppurchase', 'cp -f www/js/controller.purchase.alexdisler.js www/js/controller.purchase.js', 'yarn install', 'bower install', 'gulp sass', 'ionic build ios' ])); gulp.task('build_ta_ios', shell.task([ 'cp ta.package.json package.json', 'cp ta.config.xml config.xml', 'cp ta.ads.client.config.js www/client.config.js', 'rm -rf resources;cp -a ta.resources resources', 'cp package.json import_today_ext/package.json.backup', 'cp import_today_ext/ta.empty.package.json package.json', 'ionic state reset', 'cp -a ../ta.ios/* platforms/ios/', 'mv import_today_ext/package.json.backup package.json', 'ionic state restore --plugins', 'cordova plugin add cordova-plugin-inapppurchase', 'cp -f www/js/controller.purchase.alexdisler.js www/js/controller.purchase.js', 'yarn install', 'bower install', 'gulp sass', 'ionic build ios' ])); gulp.task('build_tw_android', shell.task([ 'cp tw.package.json package.json', 'cp tw.config.xml config.xml', 'cp tw.ads.client.config.js www/client.config.js', 'rm -rf resources;cp -a tw.resources resources', 'ionic state reset', 'cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="'+BILLING_KEY+'"', 'cp -f www/js/controller.purchase.j3k0.js www/js/controller.purchase.js', 'yarn install', 'bower install', 'gulp sass', 'ionic build android' ])); gulp.task('build_ta_android', shell.task([ 'cp ta.package.json package.json', 'cp ta.config.xml config.xml', 'cp ta.ads.client.config.js www/client.config.js', 'rm -rf resources;cp -a ta.resources resources', 'ionic state reset', 'cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="'+BILLING_KEY+'"', 'cp -f www/js/controller.purchase.j3k0.js www/js/controller.purchase.js', 'yarn install', 'bower install', 'gulp sass', 'ionic build android' ])); gulp.task('release-tw-min20-android-nonpaid', shell.task([ 'ionic state reset', 'cordova platform rm ios', 'cordova plugin rm cordova-plugin-console', 'cordova plugin add https://github.com/WizardFactory/phonegap-plugin-push.git#1.11.1 --variable SENDER_ID="'+SENDER_ID+'"', 'cordova plugin add cordova-fabric-plugin --variable FABRIC_API_KEY="'+FABRIC_API_KEY+'" --variable FABRIC_API_SECRET="'+FABRIC_API_SECRET+'"', 'cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="'+BILLING_KEY+'"', 'yarn install', //'cd node_modules/cordova-uglify/;yarn install', 'bower install', 'gulp sass', //'cp ads.playstore.tw.client.config.js www/tw.client.config.js', 'cp -f www/js/controller.purchase.j3k0.js www/js/controller.purchase.js', 'cp config-androidsdk20.xml config.xml', 'ionic build android --release', 'cp platforms/android/build/outputs/apk/android-release.apk ./TodayWeather_ads_playstore_v'+json.version+'_min20.apk' ])); gulp.task('release-tw-min16-android-nonpaid', shell.task([ 'ionic state reset', 'cordova platform rm ios', 'cordova plugin rm cordova-plugin-console', 'cordova plugin add https://github.com/WizardFactory/phonegap-plugin-push.git#1.11.1 --variable SENDER_ID="'+SENDER_ID+'"', 'cordova plugin add cordova-fabric-plugin --variable FABRIC_API_KEY="'+FABRIC_API_KEY+'" --variable FABRIC_API_SECRET="'+FABRIC_API_SECRET+'"', 'cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="'+BILLING_KEY+'"', 'yarn install', //'cd node_modules/cordova-uglify/;yarn install', 'bower install', 'gulp sass', //'cp ads.playstore.tw.client.config.js www/tw.client.config.js', 'cp -f www/js/controller.purchase.j3k0.js www/js/controller.purchase.js', 'cp config-androidsdk16.xml config.xml', 'cordova plugin add cordova-plugin-crosswalk-webview', 'ionic build android --release', 'cp -a platforms/android/build/outputs/apk/android-armv7-release.apk ./TodayWeather_ads_playstore_v'+json.version+'_min16.apk' ])); gulp.task('release-tw-android-nonpaid', shell.task([ 'ionic state reset', 'cordova plugin rm cordova-plugin-console', 'cordova plugin add https://github.com/WizardFactory/phonegap-plugin-push.git#1.11.1 --variable SENDER_ID="'+SENDER_ID+'"', 'cordova plugin add cordova-fabric-plugin --variable FABRIC_API_KEY="'+FABRIC_API_KEY+'" --variable FABRIC_API_SECRET="'+FABRIC_API_SECRET+'"', 'cordova plugin add cc.fovea.cordova.purchase --variable BILLING_KEY="'+BILLING_KEY+'"', 'yarn install', 'bower install', 'gulp sass', //'cp ads.playstore.tw.client.config.js www/tw.client.config.js', 'cp -f www/js/controller.purchase.j3k0.js www/js/controller.purchase.js', 'cp config-androidsdk20.xml config.xml', 'ionic build android --release', 'cp platforms/android/build/outputs/apk/android-release.apk ./TodayWeather_ads_playstore_v'+json.version+'_min20.apk', 'cp config-androidsdk16.xml config.xml', 'cordova plugin add cordova-plugin-crosswalk-webview', 'ionic build android --release', 'cp -a platforms/android/build/outputs/apk/android-armv7-release.apk ./TodayWeather_ads_playstore_v'+json.version+'_min16.apk', //'cp config-androidsdk14.xml config.xml', //'cordova plugin add cordova-plugin-crosswalk-webview@1.8.0', //'ionic build android --release', //'cp -f platforms/android/build/outputs/apk/android-armv7-release.apk ./', //'~/Library/Android/sdk/build-tools/23.0.3/zipalign -v 4 android-armv7-release.apk TodayWeather_ads_playstore_v'+json.version+'_min14.apk', ])); gulp.task('release-tw-ios-nonpaid', shell.task([ 'cp package.json import_today_ext/package.json.backup', 'cp import_today_ext/tw.empty.package.json package.json', 'ionic state reset', 'cp -a ../ios platforms/', 'mv import_today_ext/package.json.backup package.json', 'ionic state restore --plugins', 'cordova plugin rm cordova-plugin-console', 'cordova plugin add phonegap-plugin-push@1.8.4 --variable SENDER_ID="'+SENDER_ID+'"', 'cordova plugin add cordova-fabric-plugin --variable FABRIC_API_KEY="'+FABRIC_API_KEY+'" --variable FABRIC_API_SECRET="'+FABRIC_API_SECRET+'"', 'cordova plugin add cordova-plugin-inapppurchase', 'cp -f www/js/controller.purchase.alexdisler.js www/js/controller.purchase.js', 'yarn install', 'bower install', 'gulp sass', //'cp ads.ios.tw.client.config.js www/tw.client.config.js', 'ionic build ios --release' //'xcodebuild -project TodayWeather.xcodeproj -scheme TodayWeather -configuration Release clean archive' //'xcodebuild -exportArchive -archivePath ~/Library/Developer/Xcode/Archives/2016-10-27/TodayWeather\ 2016.\ 10.\ 27.\ 13.48.xcarchive -exportPath TodayWeather.ipa'' //'/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool --validate-app -f TodayWeather.ipa -u kimalec7@gmail.com' //'/Applications/Xcode.app/Contents/Applications/Application\ Loader.app/Contents/Frameworks/ITunesSoftwareService.framework/Versions/A/Support/altool --upload-app -f TodayWeather.ipa -u kimalec7@gmail.com' ])); /** * it does not works perfectly */ gulp.task('rmplugins', function () { var pluginList = json.cordovaPlugins; pluginList = pluginList.map(function (plugin) { if (typeof plugin === 'string') { var index = plugin.indexOf('@'); if (index != -1) { return plugin.slice(0,index); } else { return plugin; } } else { if (plugin.hasOwnProperty('id')) { return plugin.id; } } }); //console.log(pluginList); var shellLists=[]; for (var i=pluginList.length-1; i>=0; i--) { shellLists.push('cordova plugin rm '+pluginList[i]); } return gulp.src('./').pipe(shell(shellLists)); }); gulp.task('git-check', function(done) { if (!sh.which('git')) { console.log( ' ' + gutil.colors.red('Git is not installed.'), '\n Git, the version control system, is required to download Ionic.', '\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.', '\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.' ); process.exit(1); } done(); });
'use strict'; var lrSnippet = require('connect-livereload')({port: 35729}); var mountFolder = function (connect, dir) { return connect.static(require('path').resolve(dir)); }; module.exports = function (grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ watch: { less: { files: ['app/style/*.less'], tasks: ['less:server'] }, livereload: { options: { livereload: 35729 }, files: [ 'app/*.htm', 'app/style/*.less', 'app/script/*.js', ] } }, connect: { options: { port: 8080, hostname: 'localhost' }, livereload: { options: { middleware: function (connect) { return [ mountFolder(connect, 'app'), lrSnippet ]; } } } }, open: { server: { path: 'http://localhost:<%= connect.options.port %>/index.htm' } }, less: { server: { options: { paths: ['app/components/bootstrap/less', 'app/style'] }, files:{ 'app/style/main.css': 'app/style/main.less' } } } }); grunt.registerTask('server', function (target) { grunt.task.run([ 'less:server', 'connect:livereload', 'open', 'watch' ]); }); };
App.Pin = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), user: DS.belongsTo('user'), createdAt: DS.attr('date'), updatedAt: DS.attr('date'), });
features["DOM.Element.exists"] = !!(window.Element);
const webpack = require('webpack') const merge = require('webpack-merge') const common = require('./webpack.common.js') const UglifyJSPlugin = require('uglifyjs-webpack-plugin') module.exports = merge(common, { plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }), new UglifyJSPlugin() ] })
import getElements from '../utilities/getElements'; const resetTabs = (tabs, tabpanels, activeClass) => { tabs.forEach((tab) => { tab.classList.remove(activeClass || 'sprk-c-Tabs__button--active'); tab.removeAttribute('tabindex'); tab.setAttribute('aria-selected', 'false'); tabpanels.forEach((panel) => { panel.classList.add('sprk-u-HideWhenJs'); }); }); }; const setActiveTab = (tab, tabpanel, activeClass) => { tab.classList.add(activeClass || 'sprk-c-Tabs__button--active'); tab.setAttribute('tabindex', '0'); tab.setAttribute('aria-selected', 'true'); if (tabpanel) { tabpanel.classList.remove('sprk-u-HideWhenJs'); } tab.focus(); }; const getActiveTabIndex = (tabs, activeClass) => { let activeIndex = null; tabs.forEach((tab, index) => { if (tab.classList.contains(activeClass || 'sprk-c-Tabs__button--active')) { activeIndex = index; } }); return activeIndex; }; const advanceTab = (tabs, tabpanels, activeClass) => { const activeIndex = getActiveTabIndex(tabs, activeClass); resetTabs(tabs, tabpanels, activeClass); if (activeIndex + 1 <= tabs.length - 1) { setActiveTab( tabs[activeIndex + 1], tabpanels[activeIndex + 1], activeClass, ); } else { setActiveTab(tabs[0], tabpanels[0], activeClass); } }; const retreatTab = (tabs, tabpanels, activeClass) => { const activeIndex = getActiveTabIndex(tabs, activeClass); resetTabs(tabs, tabpanels, activeClass); if (activeIndex - 1 === -1) { setActiveTab( tabs[tabs.length - 1], tabpanels[tabs.length - 1], activeClass, ); } else { setActiveTab( tabs[activeIndex - 1], tabpanels[activeIndex - 1], activeClass, ); } }; const ariaOrientation = (width, element) => { // switch aria-orientation on mobile (based on _tabs.scss breakpoint) if (width <= 736) { element.setAttribute('aria-orientation', 'vertical'); } else { element.setAttribute('aria-orientation', 'horizontal'); } }; const bindUIEvents = (element) => { ariaOrientation(window.innerWidth, element); const tabContainer = element.querySelector('.sprk-c-Tabs__buttons'); const tabs = element.querySelectorAll('[role="tab"]'); const tabpanels = element.querySelectorAll('[role="tabpanel"]'); tabs.forEach((tab, index) => { tab.addEventListener('click', () => { resetTabs(tabs, tabpanels); setActiveTab(tab, tabpanels[index]); }); }); tabContainer.addEventListener('keydown', (event) => { const keys = { end: 35, home: 36, left: 37, right: 39, tab: 9, up: 38, down: 40, }; if (event.keyCode === keys.left || event.keyCode === keys.up) { retreatTab(tabs, tabpanels); } else if (event.keyCode === keys.right || event.keyCode === keys.down) { advanceTab(tabs, tabpanels); } else if (event.keyCode === keys.tab) { event.preventDefault(); tabpanels[getActiveTabIndex(tabs)].focus(); } else if (event.keyCode === keys.home) { resetTabs(tabs, tabpanels); setActiveTab(tabs[0], tabpanels[0]); } else if (event.keyCode === keys.end) { resetTabs(tabs, tabpanels); setActiveTab(tabs[tabs.length - 1], tabpanels[tabpanels.length - 1]); } }); }; const tabs = () => { getElements('[data-sprk-navigation="tabs"]', bindUIEvents); }; export { tabs, bindUIEvents, ariaOrientation, resetTabs, setActiveTab, advanceTab, retreatTab, getActiveTabIndex, };
/** * Manages Mongo DB database connection. */ 'use strict'; var mongo = require('mongodb'); var databaseConfig = require('../config/database.config.json'); var MongoClient = mongo.MongoClient; var bcrypt = require('bcryptjs'); var env = require('../../.env.json'); var that = {}; var url = env.MONGO_URI; // Get Mongo DB status var getStats = function(callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } db.stats(function (err, stats) { if (err) { throw err; } callback(stats); db.close(); }); }) }; // Retrieve database collection by name var getCollection = function(collectionName, start, rows, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(collectionName); collection.find({}).count(function (err, count) { if (err) { throw err; } collection.find({}).skip(start).limit(rows).toArray(function(err, result) { if (err) { throw err; } callback(result, count); db.close(); }); }); }); }; // Retrieve multiple documents from Mongo DB collection by query var getDocuments = function(collectionName, query, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(collectionName); collection.find(query).toArray(function(err, result) { if (err) { throw err; } callback(result); db.close(); }); }); }; // Retrieve single documents from Mongo DB collection by query var getDocument = function(collectionName, query, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(collectionName); collection.find(query).limit(1).toArray(function(err, result) { if (err) { throw err; } callback(result.pop()); db.close(); }); }); }; // Add user to database var addUser = function(username, password, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.users); collection.findOneAndUpdate( { username: username }, { username: username, hash: bcrypt.hashSync(password, 10) }, { upsert: true, returnOriginal: false }, function(err, result) { if (err) { throw err; } callback(result); db.close(); } ); }); }; // Retrieve setting var getSetting = function(field, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.settings); collection.find({key: field}).limit(1).next(function(err, result){ if (err) { throw err; } callback(result); db.close(); }) }) }; // Update or create setting var setSetting = function(field, value, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.settings); collection.findOneAndUpdate( { key: field }, { $set: { value: value }, $currentDate: { lastUpdated: true } }, { upsert: true, returnOriginal: false }, function(err, result) { if (err) { return err; } callback(result); db.close(); } ) }) }; // Get statistic by mode var getStatistics = function(mode, callback) { that.getDocument(databaseConfig.collections.statistics, { mode: mode}, callback); }; // Update statistics in database var updateStatistics = function(mode, songsheetsCount, data, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.statistics); collection.findOneAndUpdate( { mode: mode }, { mode: mode, songsheetsCount: songsheetsCount, data: data, lastUpdated: new Date() }, { upsert: true, returnOriginal: false }, function(err, result) { if (err) { throw err; } callback(result); db.close(); } ) }); }; // Get similarity data by songsheet number var getSimilarity = function(signature, callback) { that.getDocument(databaseConfig.collections.similarity, {signature: signature}, callback); }; // Update similarity data for given songsheet var updateSimilarity = function(signature, distances, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.similarity); collection.findOneAndUpdate( { signature: signature }, { signature: signature, distances: distances }, { upsert: true, returnOriginal: false }, function(err, result) { if (err) { throw err; } callback(result); db.close(); } ) }); }; // Add songsheet to database var addDocument = function(data, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(databaseConfig.collections.songsheets); collection.findOneAndUpdate( { signature: data.signature }, { signature: data.signature, name: data.name, json: data.json }, { upsert: true, returnOriginal: false }, function(err, result) { if (err) { throw err; } callback({ value: result.value, ok: result.ok, signature: result.value.signature }); db.close(); } ) }); }; // Remove single document from Mongo DB collection by query var deleteDocument = function(collectionName, query, callback) { MongoClient.connect(url, function(err, db) { if (err) { throw err; } var collection = db.collection(collectionName); collection.deleteOne(query, function(err, result) { if (err) { throw err; } callback(result, query); db.close(); }); }); }; that.getStats = getStats; that.getCollection = getCollection; that.getDocuments = getDocuments; that.getDocument = getDocument; that.addUser = addUser; that.getSetting = getSetting; that.setSetting = setSetting; that.getStatistics = getStatistics; that.updateStatistics = updateStatistics; that.getSimilarity = getSimilarity; that.updateSimilarity = updateSimilarity; that.addDocument = addDocument; that.deleteDocument = deleteDocument; module.exports = that;
'use strict'; var ExampleCtrl = function($rootScope, $document, $scope) { $scope.animation = {}; $scope.animation.current = 'fadeInLeft'; $scope.animation.previous = $scope.animation.current; // only required for dynamic animations $scope.changeAnimation = function() { var elements = document.getElementsByClassName('car-container'); var $elements = angular.element(elements); $elements.removeClass('animated ' + $scope.animation.previous); $elements.addClass('not-visible'); $scope.animation.previous = $scope.animation.current; $document[0].dispatchEvent(new CustomEvent('scroll')); }; $scope.cars = [ { name: '2013 Toyota RAV4 GX Sports Automatic AWD', description: "Massive Post Budget Main Event Sale now on! This car has been drastically reduced! Hurry, ends this Saturday! This RAV4 GX all wheel drive automatic SUV is in excellent condition." }, { name: '2015 Nissan X-Trail T32 ST-L X-tronic 2WD', description: '*** PLUS Up To 3 YEARS FREE SERVICING***. We are a family owned and operated franchise which has been looking after clients since 1982. We are located 30 mins southeast of Brisbane CBD.' }, { name: '2010 Suzuki Kizashi XLS', description: 'END OF FINACIAL YEAR CLEARANCE SALE !!!!! LOVELY 2010 SUZUKI KIZASHI XLS.2.4LT PETROL AUTOMATIC SEDAN,ONE OWNER WITH EXCEPTIONAL SERVICE HISTORY,COMFY LEATHER SEATS,ELECTRIC SUNROOF,' }, { name: '2007 MINI Hatch Cooper Chilli Sports Automatic', description: "Supplied with the vehicle is a current Victorian Roadworthy and the price includes all Victorian Government Stamp duties and transfer fees in the drive away price." }, { name: '2014 Ford Territory SZ Titanium Sequential Sports Shift', description: "WIN a trip to Hawaii. End of Financial Year Clearance sale is on this Thursday to Sunday! Take advantage of red hot prices across our extensive range and go into the draw to WIN a trip to Hawaii." }, { name: "2015 Ford Ranger PX XLT", description: "WIN a trip to Hawaii. End of Financial Year Clearance sale is on this Thursday to Sunday! Take advantage of red hot prices across our extensive range and go into the draw to WIN a trip to Hawaii." } ]; $scope.animateElementIn = function($el) { $el.removeClass('not-visible'); $el.addClass('animated ' + $scope.animation.current); }; $scope.animateElementOut = function($el) { $el.addClass('not-visible'); $el.removeClass('animated ' + $scope.animation.current); }; }; angular.module('example').controller('ExampleCtrl', ExampleCtrl);
var AngleMode = "dms"; var RegExp_Float = /^\d+(\.\d*)?([eE][\+\-]?\d+)?$/; function $(id) { return document.getElementById (id); } function HtmlRightAscension (ra, mode) { if (mode == null) { mode = AngleMode; } switch (mode) { case "dms": // 23<sup>h</sup>14<sup>m</sup>16<sup>s</sup> var dms = Angle.DMS (ra); if (dms.negative) { throw "Encountered negative right ascension! " + ra; } var hours = (dms.degrees < 10 ? "0" : "") + dms.degrees.toString(); var minutes = (dms.minutes < 10 ? "0" : "") + dms.minutes.toString(); var seconds = (dms.seconds < 10 ? "0" : "") + dms.seconds.toFixed(1); var s = hours + "<sup class='UnitSup'>h</sup>&nbsp;" + minutes + "<sup class='UnitSup'>m</sup>&nbsp;" + seconds + "<sup class='UnitSup'>s</sup>"; return s; case "dmm": // 23<sup>h</sup>14.27<sup>m</sup> var dms = Angle.DMM (ra); if (dms.negative) { throw "Encountered negative right ascension! " + ra; } var hours = (dms.degrees < 10 ? "0" : "") + dms.degrees.toString(); var minutes = (dms.minutes < 10 ? "0" : "") + dms.minutes.toFixed(2); var s = hours + "<sup class='UnitSup'>h</sup>&nbsp;" + minutes + "<sup class='UnitSup'>m</sup>"; return s; case "decimal": return ra.toFixed(5) + "<sup class='UnitSup'>h</sup>"; default: throw "HtmlRightAscension: Unknown angle mode '" + mode + "'"; } } function HtmlDeclination (dec, mode) { if (mode == null) { mode = AngleMode; } switch (mode) { case "dms": var dms = Angle.DMS (dec); var s = dms.negative ? "&minus;" : "&nbsp;"; if (dms.degrees < 100) { s += "0"; } var hours = (dms.degrees < 10 ? "0" : "") + dms.degrees.toString(); var minutes = (dms.minutes < 10 ? "0" : "") + dms.minutes.toString(); var seconds = (dms.seconds < 10 ? "0" : "") + dms.seconds.toFixed(1); s += hours + "&deg;&nbsp;" + minutes + "'&nbsp;" + seconds + "&quot;"; return s; case "dmm": var dms = Angle.DMM (dec); var s = dms.negative ? "&minus;" : "&nbsp;"; if (dms.degrees < 100) { s += "0"; } var hours = (dms.degrees < 10 ? "0" : "") + dms.degrees.toString(); var minutes = (dms.minutes < 10 ? "0" : "") + dms.minutes.toFixed(2); s += hours + "&deg;&nbsp;" + minutes + "'&nbsp;"; return s; case "decimal": return dec.toFixed(5) + "&deg;"; default: throw "HtmlDeclination: Unknown angle mode '" + mode + "'"; } } function HtmlConstellation (eq) { var c = Astronomy.FindConstellation (eq); if (c == null) { return "<span title='Cannot determine constellation'>???</span>"; } else { var verboseName = ConstellationByConciseName[c.ConciseName].FullName; return "<span title='" + verboseName + "'>" + c.ConciseName + "</span>"; } } function ShowAngleFeedback (divName, value, editName) { var isDMS = ($(editName).value.indexOf(":") >= 0); var feedback; if (isDMS) { // user entered dd:mm:ss, so show feedback in pure decimal feedback = HtmlDeclination (value, "decimal"); } else { // user entered pure decimal, so show feedback in dd:mm:ss feedback = HtmlDeclination (value, "dms"); } $(divName).innerHTML = '&nbsp;=&nbsp;' + feedback; } function CommitGeographicCoordinates() { var lat = ParseAngle ($('GeoLat_Value').value); var lon = ParseAngle ($('GeoLong_Value').value); if (lat == null) { alert ("The geographic latitude you have entered is not valid. It must be between 0 and 90 degrees. You may enter it with a decimal fraction, or in ddd:mm:ss notation."); $('GeoLat_Value').focus(); } if (lon == null) { alert ("The geographic longitude you have entered is not valid. It must be between 0 and 180 degrees. You may enter it with a decimal fraction, or in dd:mm:ss notation."); $('GeoLong_Value').focus(); } if ((lat != null) && (lon != null)) { if ($('GeoLat_NS').selectedIndex == 1) { lat *= -1.0; } if ($('GeoLong_EW').selectedIndex == 0) { lon *= -1.0; } GeographicLatitude = lat; GeographicLongitude = lon; ShowAngleFeedback ('GeoLat_Feedback', lat, 'GeoLat_Value'); ShowAngleFeedback ('GeoLong_Feedback', lon, 'GeoLong_Value'); return true; // valid } else { return false; // not valid } } function SaveGeographicCoordinates() { if (CommitGeographicCoordinates()) { var expiration = 3650; // 10 years WriteCookie ("GeographicLatitudeValue", $('GeoLat_Value').value, expiration); WriteCookie ("GeographicLongitudeValue", $('GeoLong_Value').value, expiration); WriteCookie ("GeographicLatitudeDirection", (($('GeoLat_NS') .selectedIndex == 0) ? "N" : "S"), expiration); WriteCookie ("GeographicLongitudeDirection", (($('GeoLong_EW').selectedIndex == 0) ? "W" : "E"), expiration); $('SaveButton').disabled = true; } } function LoadGeographicCoordinates() { $('GeoLat_Value').value = ReadCookie ("GeographicLatitudeValue", "27.41305"); $('GeoLong_Value').value = ReadCookie ("GeographicLongitudeValue", "82.66034"); $('GeoLat_NS').selectedIndex = ReadCookie("GeographicLatitudeDirection","N") == "N" ? 0 : 1; $('GeoLong_EW').selectedIndex = ReadCookie("GeographicLongitudeDirection","W") == "W" ? 0 : 1; CommitGeographicCoordinates(); } function OnGeoLatLongChange() { $('SaveButton').disabled = false; } function ParseAngle (s, max) { // Look for 1..3 floating pointer numbers, delimited by colons. // For example: 37.35 or 43:15.373 or 23:44:55.7 // These represent degrees[:minutes[:seconds]]. // We ignore any white space outside the floating point numbers. var angle = null; var array = s.split(/\s*:\s*/); if (array.length >= 1 && array.length <= 3) { var denom = 1.0; angle = 0.0; for (var i=0; i < array.length; ++i) { if (!RegExp_Float.test(array[i])) { return null; // does not look like a valid floating point number } var x = parseFloat (array[i]); if (isNaN(x)) { return null; // could not parse a floating point number } if (x < 0) { return null; // user must specify direction by using E/W, N/S controls, not '+' or '-'. } if (i > 0) { if (x >= 60.0) { return null; // not a valid minute or second value } } angle += x / denom; denom *= 60.0; } if (angle < 0.0 || angle > max) { return null; } } return angle; } /* $Log: astro_helper.js,v $ Revision 1.3 2009/03/08 00:02:10 Don.Cross My C# astro.exe (compiled as sun.exe) now has a "javascript" option that generates constellation.js. This new constellation.js file contains the data needed for constellation calculation based on equatorial coordinates. I updated my astronomy.js code to allow use of this data to determine a constellation. The page solar_system.html uses this now to show the concise constellation symbol for each celestial body. Revision 1.2 2008/04/06 21:16:09 Don.Cross Users seem confused when confronted with the colon-notation the first time entering geographic coordinates. I am changing the default to a real location (Cambridge, MA) but making it decimal instead of dd:mm:ss. Revision 1.1 2008/02/22 23:11:29 Don.Cross Starting to work on graphical sky view in JavaScript. Factored out some code for managing user's geographic location in cookies and form elements from solar_system.html into new file astro_helper.js. Adding star_catalog.js, which was translated from text file by my GenStarMapJS.exe program. */
import assert from 'assert'; import {sub} from '.'; describe('sub operation', () => { it('can sub', () => { assert(sub(1, 1) === 0); assert(sub(2, 2) === 0); assert(sub(3, 5) === -2); }); });
import React from 'react'; import ReactDOM from 'react-dom'; import PropTypes from 'prop-types'; import {default as Component} from '../Common/plugs/index.js'; //提供style, classname方法 import { EventRegister } from '../Common/internal' import Input from '../Input/Input'; import { PLACEMENT_MAP, HAVE_TRIGGER_TYPES, TYPE_VALUE_RESOLVER_MAP, DEFAULT_FORMATS } from './constants' import { Errors, require_condition, IDGenerator } from '../Common/utils'; import { MountBody } from './MountBody' const idGen = new IDGenerator() const haveTriggerType = (type) => { return HAVE_TRIGGER_TYPES.indexOf(type) !== -1 } const isValidValue = (value) => { if (value instanceof Date) return true if (Array.isArray(value) && value.length !== 0 && value[0] instanceof Date) return true return false } // only considers date-picker's value: Date or [Date, Date] const valueEquals = function (a, b) { const aIsArray = Array.isArray(a) const bIsArray = Array.isArray(b) let isEqual = (a, b)=>{ // equal if a, b date is equal or both is null or undefined let equal = false if (a && b) equal = a.getTime() === b.getTime() else equal = a === b && a == null return equal } if (aIsArray && bIsArray) { return isEqual(a[0], b[0]) && isEqual(a[1], b[1]) } if (!aIsArray && !bIsArray) { return isEqual(a, b) } return false; }; export default class BasePicker extends Component { //state: any; static get propTypes() { return { align: PropTypes.oneOf(['left', 'center', 'right']), format: PropTypes.string, isShowTrigger: PropTypes.bool, isReadOnly: PropTypes.bool, isDisabled: PropTypes.bool, placeholder: PropTypes.string, onFocus: PropTypes.func, onBlur: PropTypes.func, // (Date|Date[]|null)=>(), null when click on clear icon onChange: PropTypes.func, // time select pannel: value: PropTypes.oneOfType([ PropTypes.instanceOf(Date), PropTypes.arrayOf(PropTypes.instanceOf(Date)) ]), } } static get defaultProps() { return { value: new Date(), // (thisReactElement)=>Unit onFocus() { }, onBlur() { }, } } constructor(props, _type, state = {}) { require_condition(typeof _type === 'string') super(props); this.type = _type// type need to be set first this.state = Object.assign({}, state, { pickerVisible: false, }, this.propsToState(props)) this.clickOutsideId = 'clickOutsideId_' + idGen.next() } // ---: start, abstract methods // (state, props)=>ReactElement pickerPanel(state, props) { throw new Errors.MethodImplementationRequiredError(props) } getFormatSeparator() { return undefined } // ---: end, abstract methods componentWillReceiveProps(nextProps) { this.setState(this.propsToState(nextProps)) } /** * onPicked should only be called from picker pannel instance * and should never return a null date instance * * @param value: Date|Date[]|null * @param isKeepPannel: boolean = false */ onPicked(value, isKeepPannel = false) {//only change input value on picked triggered let hasChanged = !valueEquals(this.state.value, value) this.setState({ pickerVisible: isKeepPannel, value, text: this.dateToStr(value) }) if (hasChanged) { this.props.onChange(value); this.context.form && this.context.form.onFieldChange(); } } dateToStr(date) { if (!isValidValue(date)) return '' const tdate = date const formatter = ( TYPE_VALUE_RESOLVER_MAP[this.type] || TYPE_VALUE_RESOLVER_MAP['default'] ).formatter; const result = formatter(tdate, this.getFormat(), this.getFormatSeparator()); return result; } // (string) => Date | null parseDate(dateStr) { if (!dateStr) return null const type = this.type; const parser = ( TYPE_VALUE_RESOLVER_MAP[type] || TYPE_VALUE_RESOLVER_MAP['default'] ).parser; return parser(dateStr, this.getFormat(), this.getFormatSeparator()); } getFormat() { return this.props.format || DEFAULT_FORMATS[this.type] } propsToState(props) { const state = {} if (this.isDateValid(props.value)) { state.text = this.dateToStr(props.value) state.value = props.value } else { state.text = '' state.value = null } // if (state.value == null) { // state.value = new Date() // } return state } triggerClass() { return this.type.includes('time') ? 'ishow-icon-time' : 'ishow-icon-date'; } calcIsShowTrigger() { if (this.props.isShowTrigger != null) { return !!this.props.isShowTrigger; } else { return haveTriggerType(this.type); } } handleFocus() { this.isInputFocus = true if (haveTriggerType(this.type) && !this.state.pickerVisible) { this.setState({ pickerVisible: true }, () => { this.props.onFocus(this); }) } } handleBlur() { this.isInputFocus = false this.props.onBlur(this); } handleKeydown(evt) { const keyCode = evt.keyCode; // tab if (keyCode === 9 || keyCode === 27) { this.setState({ pickerVisible: false }) evt.stopPropagation() } } togglePickerVisible() { this.setState({ pickerVisible: !this.state.pickerVisible }) } isDateValid(date) { return date == null || isValidValue(date) } // return true on condition // * input is parsable to date // * also meet your other condition isInputValid(value) { const parseable = this.parseDate(value) if (!parseable) { return false } const isdatevalid = this.isDateValid(parseable) if (!isdatevalid) { return false } return true } handleClickOutside(evt) { const { value, pickerVisible } = this.state if (!this.isInputFocus && !pickerVisible) { return } if (this.domRoot.contains(evt.target)) return if (this.pickerProxy && this.pickerProxy.contains(evt)) return if (this.isDateValid(value)) { this.setState({ pickerVisible: false }) this.props.onChange(value) this.context.form && this.context.form.onFieldChange(); } else { this.setState({ pickerVisible: false, text: this.dateToStr(value) }) } } handleClickIcon() { const { isReadOnly, isDisabled } = this.props const { text } = this.state if (isReadOnly || isDisabled) return if (!text) { this.togglePickerVisible() } else { this.setState({ text: '', value: null, pickerVisible: false }) this.props.onChange(null) this.context.form && this.context.form.onFieldChange(); } } render() { const { isReadOnly, placeholder, isDisabled } = this.props; const { pickerVisible, value, text, isShowClose } = this.state; const createIconSlot = () => { if (this.calcIsShowTrigger()) { const cls = isShowClose ? 'ishow-icon-close' : this.triggerClass() return ( <i className={this.classNames('ishow-input__icon', cls)} onClick={this.handleClickIcon.bind(this)} onMouseEnter={() => { if (isReadOnly || isDisabled) return if (text) { this.setState({ isShowClose: true }) } }} onMouseLeave={() => { this.setState({ isShowClose: false }) }} ></i> ) } else { return null } } const createPickerPanel = () => { if (pickerVisible) { /* eslint-disable */ let {placeholder, onFocus, onBlur, onChange, ...others} = this.props /* eslint-enable */ return ( <MountBody ref={e => this.pickerProxy = e}> { this.pickerPanel( this.state, { ...others, ...{ getPopperRefElement: () => ReactDOM.findDOMNode(this.refs.inputRoot), popperMixinOption: { placement: PLACEMENT_MAP[this.props.align] || PLACEMENT_MAP.left } } } ) } </MountBody> ) } else { return null } } return ( <span className={this.classNames('ishow-date-editor', { 'is-have-trigger': this.calcIsShowTrigger(), 'is-active': pickerVisible, 'is-filled': !!value })} ref={v => this.domRoot = v} > <EventRegister id={this.clickOutsideId} target={document} eventName="click" func={this.handleClickOutside.bind(this)} /> <Input className={this.classNames(`ishow-date-editor ishow-date-editor--${this.type}`)} readOnly={isReadOnly} disabled={isDisabled} type="text" placeholder={placeholder} onFocus={this.handleFocus.bind(this)} onBlur={this.handleBlur.bind(this)} onKeyDown={this.handleKeydown.bind(this)} onChange={value => { const iptxt = value const nstate = { text: iptxt } if (iptxt.trim() === '' || !this.isInputValid(iptxt)) { nstate.value = null } else {//only set value on a valid date input nstate.value = this.parseDate(iptxt) } this.setState(nstate) }} ref="inputRoot" value={text} icon={createIconSlot()} /> {createPickerPanel()} </span> ) } } BasePicker.contextTypes = { form: PropTypes.any };
import EventEmitter from 'events'; export default class Observer extends EventEmitter { constructor() { super(); this._name = null; this._model = null; this._value = null; this._format = (v) => v; this._handleSet = (e) => this._set(e); } destroy() { this._unbindModel(); } name(value) { if (value === null) { return this._name; } this._name = value; this._preset(); return this; } model(value = null) { if (value === null) { return this._model; } this._model = value; this._bindModel(); return this; } format(value = null) { if (value === null) { return this._format; } this._format = value; return this; } value(itemValue = null) { if (itemValue === null) { return this._value; } this._value = itemValue; this._preset(); return this; } _bindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() + 1); this._model.on('set', this._handleSet); } } _unbindModel() { if (this._model) { this._model.setMaxListeners(this._model.getMaxListeners() - 1); this._model.removeListener('set', this._handleSet); } } _preset() { if (this._model === null) { return; } this._set({ changed: false, name: this._name, value: this._model.get(this._name) }); } _set() {} }
'use strict'; describe('Controller: RepomessageCtrl', function () { // load the controller's module beforeEach(module('namsaiEditorApp')); var RepomessageCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); RepomessageCtrl = $controller('RepomessageCtrl', { $scope: scope // place here mocked dependencies }); })); it('should attach a list of awesomeThings to the scope', function () { expect(RepomessageCtrl.awesomeThings.length).toBe(3); }); });
/** * Development Environment Settings开发环境设置 * 该模块主要针对预先定义的开发环境进行配置,需要确保开发环境和生产环境的不同; * 确保该文件在部署最后进行.gitignore的过滤; * 该文件可以被提交到版本库,相对应的pro.js在部署时做相应的调整。 * @author: 王利华 * @time: 2015-5-7 * @email:lh_wang@ctrip.com */ /******************************************************************** * 主要一些开发环境的配置信息 * * db connect in connection.js * *******************************************************************/ module.exports = { //production port change to 80 port: 3000, //log path in server log: 'server path', //session key //cookie key };
//filter: /*! FileSaver.js * A saveAs() FileSaver implementation. * 2014-01-24 * * By Eli Grey, http://eligrey.com * License: X11/MIT * See LICENSE.md */ /*global self */ /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ var saveAs = saveAs // IE 10+ (native saveAs) || (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator)) // Everyone else || (function(view) { "use strict"; // IE <10 is explicitly unsupported if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { return; } var doc = view.document // only get URL when necessary in case BlobBuilder.js hasn't overridden it yet , get_URL = function() { return view.URL || view.webkitURL || view; } , URL = view.URL || view.webkitURL || view , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") , can_use_save_link = !view.externalHost && "download" in save_link , click = function(node) { var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); node.dispatchEvent(event); } , webkit_req_fs = view.webkitRequestFileSystem , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem , throw_outside = function(ex) { (view.setImmediate || view.setTimeout)(function() { throw ex; }, 0); } , force_saveable_type = "application/octet-stream" , fs_min_size = 0 , deletion_queue = [] , process_deletion_queue = function() { var i = deletion_queue.length; while (i--) { var file = deletion_queue[i]; if (typeof file === "string") { // file is an object URL URL.revokeObjectURL(file); } else { // file is a File file.remove(); } } deletion_queue.length = 0; // clear queue } , dispatch = function(filesaver, event_types, event) { event_types = [].concat(event_types); var i = event_types.length; while (i--) { var listener = filesaver["on" + event_types[i]]; if (typeof listener === "function") { try { listener.call(filesaver, event || filesaver); } catch (ex) { throw_outside(ex); } } } } , FileSaver = function(blob, name) { // First try a.download, then web filesystem, then object URLs var filesaver = this , type = blob.type , blob_changed = false , object_url , target_view , get_object_url = function() { var object_url = get_URL().createObjectURL(blob); deletion_queue.push(object_url); return object_url; } , dispatch_all = function() { dispatch(filesaver, "writestart progress write writeend".split(" ")); } // on any filesys errors revert to saving with object URLs , fs_error = function() { // don't create more object URLs than needed if (blob_changed || !object_url) { object_url = get_object_url(blob); } if (target_view) { target_view.location.href = object_url; } else { window.open(object_url, "_blank"); } filesaver.readyState = filesaver.DONE; dispatch_all(); } , abortable = function(func) { return function() { if (filesaver.readyState !== filesaver.DONE) { return func.apply(this, arguments); } }; } , create_if_not_found = {create: true, exclusive: false} , slice ; filesaver.readyState = filesaver.INIT; if (!name) { name = "download"; } if (can_use_save_link) { object_url = get_object_url(blob); // FF for Android has a nasty garbage collection mechanism // that turns all objects that are not pure javascript into 'deadObject' // this means `doc` and `save_link` are unusable and need to be recreated // `view` is usable though: doc = view.document; save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"); save_link.href = object_url; save_link.download = name; var event = doc.createEvent("MouseEvents"); event.initMouseEvent( "click", true, false, view, 0, 0, 0, 0, 0 , false, false, false, false, 0, null ); save_link.dispatchEvent(event); filesaver.readyState = filesaver.DONE; dispatch_all(); return; } // Object and web filesystem URLs have a problem saving in Google Chrome when // viewed in a tab, so I force save with application/octet-stream // http://code.google.com/p/chromium/issues/detail?id=91158 if (view.chrome && type && type !== force_saveable_type) { slice = blob.slice || blob.webkitSlice; blob = slice.call(blob, 0, blob.size, force_saveable_type); blob_changed = true; } // Since I can't be sure that the guessed media type will trigger a download // in WebKit, I append .download to the filename. // https://bugs.webkit.org/show_bug.cgi?id=65440 if (webkit_req_fs && name !== "download") { name += ".download"; } if (type === force_saveable_type || webkit_req_fs) { target_view = view; } if (!req_fs) { fs_error(); return; } fs_min_size += blob.size; req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) { var save = function() { dir.getFile(name, create_if_not_found, abortable(function(file) { file.createWriter(abortable(function(writer) { writer.onwriteend = function(event) { target_view.location.href = file.toURL(); deletion_queue.push(file); filesaver.readyState = filesaver.DONE; dispatch(filesaver, "writeend", event); }; writer.onerror = function() { var error = writer.error; if (error.code !== error.ABORT_ERR) { fs_error(); } }; "writestart progress write abort".split(" ").forEach(function(event) { writer["on" + event] = filesaver["on" + event]; }); writer.write(blob); filesaver.abort = function() { writer.abort(); filesaver.readyState = filesaver.DONE; }; filesaver.readyState = filesaver.WRITING; }), fs_error); }), fs_error); }; dir.getFile(name, {create: false}, abortable(function(file) { // delete file if it already exists file.remove(); save(); }), abortable(function(ex) { if (ex.code === ex.NOT_FOUND_ERR) { save(); } else { fs_error(); } })); }), fs_error); }), fs_error); } , FS_proto = FileSaver.prototype , saveAs = function(blob, name) { return new FileSaver(blob, name); } ; FS_proto.abort = function() { var filesaver = this; filesaver.readyState = filesaver.DONE; dispatch(filesaver, "abort"); }; FS_proto.readyState = FS_proto.INIT = 0; FS_proto.WRITING = 1; FS_proto.DONE = 2; FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null; view.addEventListener("unload", process_deletion_queue, false); saveAs.unload = function() { process_deletion_queue(); view.removeEventListener("unload", process_deletion_queue, false); }; return saveAs; }( typeof self !== "undefined" && self || typeof window !== "undefined" && window || this.content )); // `self` is undefined in Firefox for Android content script context // while `this` is nsIContentFrameMessageManager // with an attribute `content` that corresponds to the window if (typeof module !== "undefined") module.exports = saveAs;
const run = require("./steps/index"); module.exports = [ run.changeDirectory, run.setFilePaths, run.fetchUpstream, run.checkoutDefaultBranch, run.gitMergeUpstreamDefaultBranch, run.getCurrentBranchVersion, run.gitMergeUpstreamDevelop, run.gitShortLog, run.updateVersion, run.updateChangelog, run.updatePackageLockJson, run.gitAdd, run.gitCommit, run.gitTag, run.gitPushUpstreamDefaultBranch, run.checkoutDevelop, run.gitMergeDevelopWithDefaultBranch, run.gitPushUpstreamDevelop, run.gitPushOriginDefaultBranch, run.githubUpstream, run.githubRelease ];
'use strict'; var objectAssign = require('object-assign'); var _ = require('lodash'); var ExecutionEnvironment = require('./ExecutionEnvironment'); /** * Helper to work with cookie on isomorphic apps * * Server side: * * Use the API of Express Response Cookie (http://expressjs.com/api.html#res.cookie) * res.clearCookie(name [, options]) * res.cookie(name, value [, options]) * Options: * domain String Domain name for the cookie. Defaults to the domain name of the app. * expires Date Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie. * httpOnly Boolean Flags the cookie to be accessible only by the web server. * maxAge String Convenient option for setting the expiry time relative to the current time in milliseconds. * path String Path for the cookie. Defaults to “/”. * secure Boolean Marks the cookie to be used with HTTPS only. * signed Boolean Indicates if the cookie should be signed. * * Client side: * * Based on the module cookies-js * Cookies.set(key, value [, options]) * Cookies.get(key) * Cookies.expire(key [, options]) * Options: * path A string value of the path of the cookie (default "/") * domain A string value of the domain of the cookie * expires A number (of seconds), a date parsable string, or a Date object of when the cookie will expire * secure A boolean value of whether or not the cookie should only be available over SSL (default false) */ var _res; var _req; var _reqCookies; var _default = { path: '/', isJson: false }; var _isClientSide = ExecutionEnvironment.canUseDOM; var _clientCookie; if (_isClientSide) { _clientCookie = require('cookies-js'); } var get = function(key, options) { options = objectAssign(_default, options); var value; if (_isClientSide) { value = _clientCookie.get(key); } else { value = _.has(_reqCookies, key) ? _reqCookies[key] : null; } return options.isJson ? JSON.parse(value) : value; }; var set = function(key, value, options) { options = objectAssign(_default, options); if (options.isJson) { value = JSON.stringify(value); } if (_isClientSide) { _clientCookie.set(key, value, options); } else { _reqCookies[key] = value; _res.cookie(key, value, options); } }; var expire = function(key, options) { options = objectAssign(_default, options); if (_isClientSide) { _clientCookie.expire(key, options); } else { _res.clearCookie(key, options); if (_.has(_reqCookies, key)) { _reqCookies[key] = null; } } }; var expressMiddleware = function(req, res, next) { console.log('cookie.expressMiddleware'); _res = res; _req = req; // Clone req.cookies if (_req.cookies) { _reqCookies = JSON.parse(JSON.stringify(req.cookies)); } else { _reqCookies = {}; } next(); }; module.exports = { get: get, set: set, expire: expire, expressMiddleware: expressMiddleware };
exports.modifyWebpackConfig = function(config, env) { config.merge({ postcss (wp) { return [ require('postcss-import')({ addDependencyTo: wp }), require('postcss-cssnext')({ browsers: 'last 2 versions', features: {customProperties: false} }), require('postcss-browser-reporter'), require('postcss-reporter'), ] }, }) config.loader('url-loader', function(cfg) { cfg.test = /\.(mp4|webm|wav|mp3|m4a|aac|oga|pdf)(\?.*)?$/, cfg.loader = 'url' return cfg }) return config }
var TALK , controller module.exports = function(_TALK) { TALK = _TALK controller = require('./controller')(TALK) // General Use TALK.server.get('/', reset, controller.index) TALK.server.error(controller.error) // Chat Routes TALK.server.get ('/:name' , controller.chat_show) TALK.server.get ('/:name/rm' , controller.chat_rm ) TALK.server.post('/new' , controller.chat_new ) TALK.server.post('/join' , reset, controller.chat_join) TALK.server.post('/:name/post', reset, controller.chat_post) TALK.server.post('/:name/load', controller.chat_load) } // Reset Main Variables function reset(req, res, next) { if (req.query.reset || (new Date()).getDay() !== TALK.settings.today) { TALK.settings.today = (new Date()).getDay() TALK.collections.flush() TALK.stats.flush() } return next() }
import React from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; class ScrollDialog extends React.Component { state = { open: false, scroll: 'paper', }; handleClickOpen = scroll => () => { this.setState({ open: true, scroll }); }; handleClose = () => { this.setState({ open: false }); }; render() { return ( <div> <Button onClick={this.handleClickOpen('paper')}>scroll=paper</Button> <Button onClick={this.handleClickOpen('body')}>scroll=body</Button> <Dialog open={this.state.open} onClose={this.handleClose} scroll={this.state.scroll} aria-labelledby="scroll-dialog-title" > <DialogTitle id="scroll-dialog-title">Subscribe</DialogTitle> <DialogContent> <DialogContentText> Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. Cras mattis consectetur purus sit amet fermentum. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor. Aenean lacinia bibendum nulla sed consectetur. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Donec sed odio dui. Donec ullamcorper nulla non metus auctor fringilla. </DialogContentText> </DialogContent> <DialogActions> <Button onClick={this.handleClose} color="primary"> Cancel </Button> <Button onClick={this.handleClose} color="primary"> Subscribe </Button> </DialogActions> </Dialog> </div> ); } } export default ScrollDialog;
(function (app) { 'use strict'; app.registerModule('customquestions'); }(ApplicationConfiguration));
// @flow weak import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import MobileStepper from 'material-ui/MobileStepper'; const styles = { root: { maxWidth: 400, flexGrow: 1, }, }; class DotsMobileStepper extends Component { state = { activeStep: 0, }; handleNext = () => { this.setState({ activeStep: this.state.activeStep + 1, }); }; handleBack = () => { this.setState({ activeStep: this.state.activeStep - 1, }); }; render() { const classes = this.props.classes; return ( <MobileStepper type="dots" steps={6} position="static" activeStep={this.state.activeStep} className={classes.root} onBack={this.handleBack} onNext={this.handleNext} disableBack={this.state.activeStep === 0} disableNext={this.state.activeStep === 5} /> ); } } DotsMobileStepper.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(DotsMobileStepper);
/*global __dirname*/ export const ROOT = __dirname; export const SRC_DIR = `${ROOT}/src`; export const BUNDLE_DIR = `${ROOT}/bundles`;
var CompilerExample = function () { neutrino.Application.call (this); } neutrino.inherits (CompilerExample, neutrino.Application);
'use strict'; const menu = require('../common/menu'); const banner = require('../common/banner') /* A controller for the home page. */ function controller(app) { app.get('/hostafundraiser', function (req, res) { banner(app).then(function(banner) { let data = { menu: menu(), showBanner: false, banner: banner, showSidebar: true }; res.render('get-involved/fundraiser', data); }); }); } module.exports = controller;
import cx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import { useMediaSources } from '../../context/MediaSourceContext'; function Player({ enabled, size, volume, isMuted, media, seek, onPlay, }) { const { getAllMediaSources } = useMediaSources(); if (!media) { return <div className="Player" />; } const props = { enabled, media, seek, mode: size, volume: isMuted ? 0 : volume, onPlay, }; const sources = getAllMediaSources(); const players = Object.keys(sources).map((sourceType) => { const SourcePlayer = sources[sourceType].Player; if (!SourcePlayer) { return null; } return ( <SourcePlayer key={sourceType} {...props} active={media.sourceType === sourceType} /> ); }).filter((player) => player !== null); return ( <div className={cx('Player', `Player--${media.sourceType}`, `Player--${size}`)}> {players} </div> ); } Player.propTypes = { enabled: PropTypes.bool, size: PropTypes.string, volume: PropTypes.number, isMuted: PropTypes.bool, media: PropTypes.object, seek: PropTypes.number, onPlay: PropTypes.func, }; export default Player;
import { Pointer } from './pointer'; import { compare } from './equal'; import { MissingError, TestError } from './errors'; function _add(object, key, value) { if (Array.isArray(object)) { // `key` must be an index if (key == '-') { object.push(value); } else { object.splice(key, 0, value); } } else { object[key] = value; } } function _remove(object, key) { if (Array.isArray(object)) { // '-' syntax doesn't make sense when removing object.splice(key, 1); } else { // not sure what the proper behavior is when path = '' delete object[key]; } } /** > o If the target location specifies an array index, a new value is > inserted into the array at the specified index. > o If the target location specifies an object member that does not > already exist, a new member is added to the object. > o If the target location specifies an object member that does exist, > that member's value is replaced. */ export function add(object, operation) { var endpoint = Pointer.fromJSON(operation.path).evaluate(object); // it's not exactly a "MissingError" in the same way that `remove` is -- more like a MissingParent, or something if (endpoint.parent === undefined) { return new MissingError(operation.path); } _add(endpoint.parent, endpoint.key, operation.value); return null; } /** > The "remove" operation removes the value at the target location. > The target location MUST exist for the operation to be successful. */ export function remove(object, operation) { // endpoint has parent, key, and value properties var endpoint = Pointer.fromJSON(operation.path).evaluate(object); if (endpoint.value === undefined) { return new MissingError(operation.path); } // not sure what the proper behavior is when path = '' _remove(endpoint.parent, endpoint.key); return null; } /** > The "replace" operation replaces the value at the target location > with a new value. The operation object MUST contain a "value" member > whose content specifies the replacement value. > The target location MUST exist for the operation to be successful. > This operation is functionally identical to a "remove" operation for > a value, followed immediately by an "add" operation at the same > location with the replacement value. Even more simply, it's like the add operation with an existence check. */ export function replace(object, operation) { var endpoint = Pointer.fromJSON(operation.path).evaluate(object); if (endpoint.value === undefined) return new MissingError(operation.path); endpoint.parent[endpoint.key] = operation.value; return null; } /** > The "move" operation removes the value at a specified location and > adds it to the target location. > The operation object MUST contain a "from" member, which is a string > containing a JSON Pointer value that references the location in the > target document to move the value from. > This operation is functionally identical to a "remove" operation on > the "from" location, followed immediately by an "add" operation at > the target location with the value that was just removed. > The "from" location MUST NOT be a proper prefix of the "path" > location; i.e., a location cannot be moved into one of its children. TODO: throw if the check described in the previous paragraph fails. */ export function move(object, operation) { var from_endpoint = Pointer.fromJSON(operation.from).evaluate(object); if (from_endpoint.value === undefined) return new MissingError(operation.from); var endpoint = Pointer.fromJSON(operation.path).evaluate(object); if (endpoint.parent === undefined) return new MissingError(operation.path); _remove(from_endpoint.parent, from_endpoint.key); _add(endpoint.parent, endpoint.key, from_endpoint.value); return null; } /** > The "copy" operation copies the value at a specified location to the > target location. > The operation object MUST contain a "from" member, which is a string > containing a JSON Pointer value that references the location in the > target document to copy the value from. > The "from" location MUST exist for the operation to be successful. > This operation is functionally identical to an "add" operation at the > target location using the value specified in the "from" member. Alternatively, it's like 'move' without the 'remove'. */ export function copy(object, operation) { var from_endpoint = Pointer.fromJSON(operation.from).evaluate(object); if (from_endpoint.value === undefined) return new MissingError(operation.from); var endpoint = Pointer.fromJSON(operation.path).evaluate(object); if (endpoint.parent === undefined) return new MissingError(operation.path); _remove(from_endpoint.parent, from_endpoint.key); _add(endpoint.parent, endpoint.key, from_endpoint.value); return null; } /** > The "test" operation tests that a value at the target location is > equal to a specified value. > The operation object MUST contain a "value" member that conveys the > value to be compared to the target location's value. > The target location MUST be equal to the "value" value for the > operation to be considered successful. */ export function test(object, operation) { var endpoint = Pointer.fromJSON(operation.path).evaluate(object); var result = compare(endpoint.value, operation.value); if (!result) return new TestError(endpoint.value, operation.value); return null; }
ReactionCore.MethodHooks.beforeMethods({ "orders/inventoryAdjust": function (options) { check(options.arguments, [Match.Any]); const orderId = options.arguments[0]; if (!orderId) { return true; } Meteor.call("rentalProducts/inventoryAdjust", orderId); return options; // Returned false before, but there is no longer an `adjust inventory method in core` // so this is probably never called any more. } }); ReactionCore.MethodHooks.afterMethods({ "cart/addToCart": function (options) { check(options.arguments[0], String); check(options.arguments[1], String); const variantId = options.arguments[1]; const cart = ReactionCore.Collections.Cart.findOne({ userId: Meteor.userId() }); if (!cart) { return options; } if (cart.items && cart.items.length > 0) { _.map(cart.items, function (item) { if (item.variants._id === variantId && (item.variants.functionalType === "rentalVariant" || item.variants.functionalType === "bundleVariant") // TODO: future if item.type === rental && cart.rentalDays) { // TODO: update qty to verified rental qty available // Set price to calculated rental price; let priceBucket = _.find(item.variants.rentalPriceBuckets, (bucket) => { return bucket.duration === cart.rentalDays; }); if (priceBucket) { item.variants.price = priceBucket.price; } else { // remove from cart // Throw error } } return item; }); } else { cart.items = []; } ReactionCore.Collections.Cart.update({ _id: cart._id }, { $set: { items: cart.items } }); return options; // Continue with other hooks; // was returning true before. After chatting with @paulgrever we decided it was proabably better to return // the options object } });
(function(nx){ // application class nx.define('App',nx.ui.Application,{ 'methods': { 'start': function(divId){ // assign to an object if(divId != undefined){ this.container(document.getElementById(divId)); } // define topology var topologyContainer = new TopologyContainer(); var topology = topologyContainer.topology(); // define topology data var topologyData = new TopologyData(); topology.data(topologyData.get('topology')); // define the scene (for nodeset tooltip customization) topology.registerScene('nodeSetScene', 'NodeSetScene'); topology.activateScene('nodeSetScene'); topology.attach(app); } } }); // define app var app = new App(); app.start('next-app'); })(nx);
(function () { "use strict"; /* @ngInject */ function config($routeProvider) { $routeProvider .when("/products", { name: "products", templateUrl: "app/catalog/partials/products.html", controller: "productController", controllerAs: "vm" }) .when("/products/add", { name: "add-product", templateUrl: "app/catalog/partials/add-product.html", controller: "addProductController", controllerAs: "vm" }) ; } angular .module("catalogModule") .config(["$routeProvider", config]) ; })();
'use strict'; import React from 'react-native'; const { Image, TouchableOpacity, View, } = React; import StyleSheet from '../../styles/CarlyStyleSheet.js' import Animated from 'Animated'; import NativeModules from 'NativeModules'; import Dimensions from 'Dimensions'; import Header from './Header'; import ParallaxBackground from './ParallaxBackground'; import { Text } from '../../styles/text.js'; import Platform from 'Platform'; import PageView from './PageView.js'; import type {Item as HeaderItem} from 'Header'; type Props = { title: string; leftItem?: HeaderItem; rightItem?: HeaderItem; extraItems?: Array<HeaderItem>; selectedSegment?: number; selectedSectionColor: string; backgroundImage: number; backgroundColor: string; parallaxContent: ?ReactElement; stickyHeader?: ?ReactElement; onSegmentChange?: (segment: number) => void; children: any; }; type State = { idx: number; anim: Animated.Value; stickyHeaderHeight: number; }; const EMPTY_CELL_HEIGHT = Dimensions.get('window').height > 600 ? 200 : 150; var ActivityIndicatorIOS = require('ActivityIndicatorIOS'); var ProgressBarAndroid = require('ProgressBarAndroid'); const ActivityIndicator = ActivityIndicatorIOS; //Renders scrolling list class RelayLoading extends React.Component { render() { const child = React.Children.only(this.props.children); if (!child.type.getFragmentNames) { return child; } } } class ListContainer extends React.Component { props: Props; _refs: Array<any>; _pinned: any; constructor(props: Props) { super(props); this.state = ({ idx: this.props.selectedSegment || 0, anim: new Animated.Value(0), stickyHeaderHeight: 0, }: State); this.renderFakeHeader = this.renderFakeHeader.bind(this); this.handleStickyHeaderLayout = this.handleStickyHeaderLayout.bind(this); this.handleSelectSegment = this.handleSelectSegment.bind(this); this._refs = []; } render() { var leftItem = this.props.leftItem; const segments = []; const content = React.Children.map(this.props.children, (child, idx) => { segments.push(child.props.title); // determines animation properties within the view return <RelayLoading>{React.cloneElement(child, { ref: (ref) => this._refs[idx] = ref, onScroll: (e) => this.handleScroll(idx, e), style: styles.listView, showsVerticalScrollIndicator: true, scrollEventThrottle: 16, contentInset: {bottom: 49, top: 0}, automaticallyAdjustContentInsets: false, renderHeader: this.renderFakeHeader, scrollsToTop: idx === this.state.idx, })}</RelayLoading>; }); let {stickyHeader} = this.props; if (segments.length > 1) { stickyHeader = ( <View> {stickyHeader} </View> ); } const backgroundShift = segments.length === 1 ? 0 : this.state.idx / (segments.length - 1); return ( <View style={styles.container}> <View style={styles.headerWrapper}> <ParallaxBackground minHeight={this.state.stickyHeaderHeight + Header.height} maxHeight={EMPTY_CELL_HEIGHT + this.state.stickyHeaderHeight + Header.height} offset={this.state.anim} backgroundImage={this.props.backgroundImage} backgroundShift={backgroundShift} backgroundColor={this.props.backgroundColor}> {this.renderParallaxContent()} </ParallaxBackground> <Header title={this.props.title} leftItem={leftItem} rightItem={this.props.rightItem} extraItems={this.props.extraItems}> {this.renderHeaderTitle()} </Header> {this.renderFixedStickyHeader(stickyHeader)} </View> <PageView count={segments.length} selectedIndex={this.state.idx}> {content} </PageView> {this.renderFloatingStickyHeader(stickyHeader)} </View> ); } renderParallaxContent() { if (this.props.parallaxContent) { return this.props.parallaxContent; } return ( <Text style={styles.parallaxText}> {this.props.title} </Text> ); } renderHeaderTitle(): ?ReactElement { var transform; if (!this.props.parallaxContent) { var distance = EMPTY_CELL_HEIGHT - this.state.stickyHeaderHeight; transform = { opacity: this.state.anim.interpolate({ inputRange: [distance - 20, distance], outputRange: [0, 1], extrapolate: 'clamp', }) }; } return ( <Animated.Text style={[styles.headerTitle, transform]}> {this.props.title} </Animated.Text> ); } handleScroll(idx: number, e: any) { if (idx !== this.state.idx) { return; } let y = 0; this.state.anim.setValue(e.nativeEvent.contentOffset.y); const height = EMPTY_CELL_HEIGHT- this.state.stickyHeaderHeight; y = Math.min(e.nativeEvent.contentOffset.y, height); this._refs.forEach((ref, ii) => { if (ii !== idx && ref) { ref.scrollTo && ref.scrollTo({y, animated: false}); } }); } renderFakeHeader() { const height = EMPTY_CELL_HEIGHT - this.state.stickyHeaderHeight; return ( <View style={{height}} /> ); } renderFixedStickyHeader(stickyHeader: ?ReactElement) { <View style={{height: this.state.stickyHeaderHeight}} /> } renderFloatingStickyHeader(stickyHeader: ?ReactElement) { var opacity = this.state.stickyHeaderHeight === 0 ? 0 : 1; var transform; // If native pinning is not available, fallback to Animated if (!NativeModules.F8Scrolling) { var distance = EMPTY_CELL_HEIGHT - this.state.stickyHeaderHeight; var translateY = 0; this.state.anim.interpolate({ inputRange: [0, distance], outputRange: [distance, 0], extrapolateRight: 'clamp', }); transform = [{translateY}]; } return ( <Animated.View ref={(ref) => this._pinned = ref} onLayout={this.handleStickyHeaderLayout} style={[styles.stickyHeader, {opacity}, {transform}]}> {stickyHeader} </Animated.View> ); } handleStickyHeaderLayout({nativeEvent: { layout, target }}: any) { this.setState({stickyHeaderHeight: layout.height}); } componentWillReceiveProps(nextProps: Props) { if (typeof nextProps.selectedSegment === 'number' && nextProps.selectedSegment !== this.state.idx) { this.setState({idx: nextProps.selectedSegment}); } } componentDidUpdate(prevProps: Props, prevState: State) { if (!NativeModules.F8Scrolling) { return; } if (this.state.idx !== prevState.idx || this.state.stickyHeaderHeight !== prevState.stickyHeaderHeight) { var distance = EMPTY_CELL_HEIGHT - this.state.stickyHeaderHeight; if (this._refs[prevState.idx] && this._refs[prevState.idx].getScrollResponder) { const oldScrollViewTag = React.findNodeHandle( this._refs[prevState.idx].getScrollResponder() ); NativeModules.F8Scrolling.unpin(oldScrollViewTag); } if (this._refs[this.state.idx] && this._refs[this.state.idx].getScrollResponder) { const newScrollViewTag = React.findNodeHandle( this._refs[this.state.idx].getScrollResponder() ); const pinnedViewTag = React.findNodeHandle(this._pinned); NativeModules.F8Scrolling.pin(newScrollViewTag, pinnedViewTag, distance); } } } handleSelectSegment(idx: number) { if (this.state.idx !== idx) { const {onSegmentChange} = this.props; this.setState({idx}, () => onSegmentChange && onSegmentChange(idx)); } } } ListContainer.defaultProps = { selectedSectionColor: 'white', }; ListContainer.contextTypes = { openDrawer: React.PropTypes.func, hasUnreadNotifications: React.PropTypes.number, }; var styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', }, headerWrapper: { android: { elevation: 2, backgroundColor: 'transparent', // FIXME: elevation doesn't seem to work without setting border borderRightWidth: 1, marginRight: -1, borderRightColor: 'transparent', } }, listView: { ios: { backgroundColor: 'transparent', }, android: { backgroundColor: 'white', } }, headerTitle: { color: 'white', fontWeight: 'bold', fontSize: 20, }, parallaxText: { color: 'white', fontSize: 42, fontWeight: 'bold', letterSpacing: -1, }, stickyHeader: { position: 'absolute', top: Header.height, left: 0, right: 0, }, }); module.exports = ListContainer;
var core = require('./controllers/core'); var api = require('./controllers/api'); module.exports = function(app){ app.get('/', core.home); app.get('/top', core.top); app.get('/results', core.results); app.get('/api/results', api.results); }
define('sub',{ name: 'sub' }); require.config({ baseUrl: 'js' }); require(['sub'], function (sub) { console.log(sub.name); }); define("main", function(){});
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import initializer from "ilios/instance-initializers/ember-i18n"; import startMirage from '../../helpers/start-mirage'; import Ember from 'ember'; const { Object } = Ember; moduleForComponent('school-list', 'Integration | Component | school list', { integration: true, beforeEach(){ initializer.initialize(this); startMirage(this.container); } }); test('it renders', function(assert) { let school1 = server.create('school'); let school2 = server.create('school'); const schools = [school1, school2].map(obj => Object.create(obj)); this.set('schools', schools); this.render(hbs`{{school-list schools=schools}}`); assert.equal(this.$('tr:eq(1) td:eq(0)').text().trim(), 'school 0'); assert.equal(this.$('tr:eq(2) td:eq(0)').text().trim(), 'school 1'); });
"use strict"; /** * Created by DuanG on 2016/11/23. */ var express = require('express'); var cookieKey_1 = require("../../common/cookieKey"); var keyMemberCK_1 = require("../../common/keyMemberCK"); var cookie_1 = require("../../common/cookie"); var ResponseTool_1 = require("../../common/ResponseTool"); var ResponseModel_1 = require("../../ResponseModel"); exports.requireAuthorization = express.Router(); exports.requireAuthorization.use(function (req, res, next) { try { var result = keyMemberCK_1.keyMemberCK().decrypt(cookie_1.getCookie(cookieKey_1.MemberCK, req), 'utf-8'); if (result) { next(); } } catch (e) { cookie_1.clearCookie(cookieKey_1.MemberCK, res); ResponseTool_1.response(res, JSON.stringify(ResponseModel_1.ResponseModel.getErrorResponseModel('请先登录', ResponseModel_1.ApiStateEnum.AuthFail)), 401); } });
import WardenModel from 'resources/models/warden-model'; import UserModel from 'resources/models/user-model'; export default class OrganizationModel { constructor(data) { // { // "id": "a295aa48-af69-4fcb-9feb-c4ea9c350d80", // "owner": { // "userId": "dbac93f106724ab7a576598b63c12962", // "email": "snicky700@gmail.com", // "role": "owner", // "createdAt": "2017-04-01T18:52:42.898Z" // }, // "name": "default", // "description": null, // "users": [ // { // "userId": "dbac93f106724ab7a576598b63c12962", // "email": "snicky700@gmail.com", // "role": "owner", // "createdAt": "2017-04-01T18:52:42.898Z" // } // ], // "wardens": [] // } this.data = data; const DIRECT_PROPS = ['id', 'name', 'description', 'status']; for (let prop of DIRECT_PROPS) { this[prop] = data[prop]; } this.wardens = (data.wardens || []).map((wardenData) => new WardenModel(wardenData)); this.users = (data.users || []).map((userData) => new UserModel(userData)); this.owner = new UserModel(data.owner); this.setStatusWaiting(); } selectWarden(wardenId) { return this.wardens.find((warden) => warden.id == wardenId); } createOrUpdateWatcher(wardenId, watcherData) { this.selectWarden(wardenId).createOrUpdateWatcher(watcherData); if (this.wardens.every((warden) => warden.isStatusOk)) { this.setStatusOk(); } else { this.setStatusFail(); } } setStatusFail() { this.status = 'fail'; } setStatusOk() { this.status = 'ok'; } setStatusWaiting() { this.status = 'waiting'; } }
import angular from 'angular'; // angular modules import constants from './constants'; import onConfig from './on_config'; import onRun from './on_run'; import 'foundation-sites'; import 'angular-route'; import 'angular-load'; import 'angular-truncate-2'; import 'angular-masonry'; import 'angular-material-icons' import 'angular-sanitize'; import './templates'; import './filters'; import './controllers'; import './services'; import './directives'; // create and bootstrap application const requires = [ 'ngRoute', 'angularLoad', 'truncate', 'wu.masonry', 'ngMdIcons', 'ngSanitize', 'templates', 'app.filters', 'app.controllers', 'app.services', 'app.directives', ]; // mount on window for testing window.app = angular.module('app', requires); angular.module('app').constant('AppSettings', constants); angular.module('app').config(onConfig); angular.module('app').run(onRun); angular.bootstrap(document, ['app'], { strictDi: true });
import React from 'react'; import ReactDOM from 'react-dom'; import Root from './containers/Root'; import createBrowserHistory from 'history/lib/createBrowserHistory'; import './stylesheets/application.sass'; const history = createBrowserHistory(); ReactDOM.render( <Root history={history} />, document.getElementById('root') );
// import Mantissa.LiveForm Quotient.Spam.PostiniSettings = Mantissa.LiveForm.FormWidget.subclass("Quotient.Spam.PostiniSettings"); /** * FormWidget used by L{xquotient.spam.HamFilterFragment} for editing Postini * settings. */ Quotient.Spam.PostiniSettings.methods( /** * When the form is submitted successfully, populate the form's fields with * the new values. */ function submitSuccess(self, result) { var formValues = self.gatherInputs(); var d = Quotient.Spam.PostiniSettings.upcall(self, "submitSuccess", result); return d.addCallback( function (result) { self.setInputValues(formValues); return result; }); });
var LayoutEngine = {} LayoutEngine.generateRectangles = function (options) { if (!options.dimensions) throw new Error('No dimensions option given for Masonry Layout') options.gutter = options.gutter || 0 options.gutterX = options.gutterX || options.gutter options.gutterY = options.gutterY || options.gutter options.width = options.width || 800 options.columns = options.columns || 3 options.maxHeight = options.maxHeight || 0 options.customize = options.customize || function (r) { return r } if (typeof options.collapsing === 'undefined') { options.collapsing = true } if (typeof options.centering === 'undefined') { options.centering = false } return options.dimensions .map(LayoutEngine.__scaleRectangles(options.columns, options.width, options.gutterX, options.maxHeight)) .map(LayoutEngine.__prepareCustomize(options.customize, options)) .map(LayoutEngine.__translateRectanglesForNColumns(options.columns, options.width, options.gutterX, options.gutterY, options.collapsing)) .map(LayoutEngine.__centerRectangles(options.centering, options.columns, options.width, options.gutterX)) } LayoutEngine.__prepareCustomize = function (customizeFunction, options) { return function (rectangle, i, allRects) { return customizeFunction(rectangle, i, allRects, options) } } LayoutEngine.__translateRectanglesForNColumns = function (numColumns, totalWidth, gutterX, gutterY, collapsing, centering) { /* Translate rectangles into position */ return function (rectangle, i, allRects) { if (!i) { // first round rectangle = LayoutEngine.__placeRectangleAt(rectangle, 0, 0, gutterY) return rectangle } else if (i < numColumns) { // first row rectangle = LayoutEngine.__placeRectangleAt(rectangle, (LayoutEngine.__widthSingleColumn(numColumns, totalWidth, gutterX) * i) + (gutterX * i), 0) return rectangle } else { // Pass array of all previous rectangles, give back leading rectangle if (collapsing) { var placeAfter = LayoutEngine.__placeAfterRectangle(allRects.slice(0, i), gutterY, collapsing, numColumns, i) } else { // only use the rectangles from te previous row var placeAfter = LayoutEngine.__placeAfterRectangle(allRects.slice(0, i - i % numColumns), gutterY, collapsing, numColumns, i) } rectangle = LayoutEngine.__placeRectangleAt(rectangle, placeAfter.x, (placeAfter.height)) return rectangle } } } /* Scale all rectangles to fit into a single column */ LayoutEngine.__scaleRectangles = function (numColumns, totalWidth, gutterX, maxHeight) { return function (rectangle) { var w = rectangle.width var h = rectangle.height var factor = w / h var width = LayoutEngine.__widthSingleColumn(numColumns, totalWidth, gutterX) var height = width / factor // Set max height if (maxHeight && maxHeight < height) { height = maxHeight } return { width: Math.floor(width), height: Math.floor(height), x: 0, y: 0 } } } LayoutEngine.__centerRectangles = function (centering, columns, width, gutterX) { var widthSingleColumn = LayoutEngine.__widthSingleColumn(columns, width, gutterX) return function (rectangle, i, allRects) { if (columns <= allRects.length || !centering) { // No need to center anything return rectangle } else { // Shift each rectangle rectangle.x += ((columns - allRects.length) * widthSingleColumn / 2) + ((columns - allRects.length) * gutterX / 2) return rectangle } } } LayoutEngine.__placeRectangleAt = function (rectangle, x, y) { return Object.assign(rectangle, {x: x, y: y}) } LayoutEngine.__rectanglesToColumns = function (rectArray, gutterY) { // reduce rectangles into larger column sized rectangles function findValue (match) { return function (value) { return (value === match) } } var xValues = rectArray .reduce(function (values, rectangle, i, array) { if (!~values.findIndex(findValue(rectangle.x))) { values.push(rectangle.x) } return values }, []) var columns = rectArray .reduce(function (rectangles, rectangle, i, array) { var index = xValues.findIndex(findValue(rectangle.x)) if (rectangles[index]) { rectangles[index]['height'] = rectangle.y + rectangle.height + gutterY } else { // start new column rectangles[index] = Object.assign({}, rectangle) rectangles[index]['height'] += gutterY } return rectangles }, []) return columns } LayoutEngine.__placeAfterRectangle = function (rectArray, gutterY, collapsing, numColumns, index) { var columns = LayoutEngine.__rectanglesToColumns(rectArray, gutterY) var columnsByHeightAsc = columns.sort(function (columnA, columnB) { return columnA.height - columnB.height }).map(function (r) { return Object.assign({}, r) }) var columnsByHeightDesc = columns.sort(function (columnA, columnB) { return columnB.height - columnA.height }).map(function (r) { return Object.assign({}, r) }) var columnsByXDesc = columns.sort(function (columnA, columnB) { return columnA.x - columnB.x }).map(function (r) { return Object.assign({}, r) }) if (collapsing) { // return the smallest column return columnsByHeightAsc[0] } else { return { x: columns[(index % numColumns)]['x'], y: 0, width: columnsByHeightDesc[(index % numColumns)]['width'], height: columnsByHeightDesc[0]['height'] } } } LayoutEngine.__widthSingleColumn = function (numColumns, totalWidth, gutter) { totalWidth += gutter return (totalWidth / numColumns) - gutter } if (typeof module === 'object' && module.exports) { module.exports = LayoutEngine } else { window.SimpleMasonry = LayoutEngine }
var expect = require('chai').expect; var setup = require(__dirname + '/lib/setup'); var fs = require('fs'); var objects = null; var states = null; var connected = false; describe('epson_stylus_px830: test adapter', function() { before('epson_stylus_px830: Start js-controller', function (_done) { this.timeout(600000); // because of first install from npm setup.setupController(function () { var config = setup.getAdapterConfig(); // enable adapter config.common.enabled = true; config.common.loglevel = 'debug'; setup.setAdapterConfig(config.common, config.native); setup.startController(function (_objects, _states) { objects = _objects; states = _states; _done(); }); }); }); it('epson_stylus_px830: wait', function (done) { this.timeout(5000); setTimeout(function () { done(); }, 3000); }); /* it('epson_stylus_px830: feeds to be parsed', function (done) { this.timeout(20000); states.getState('epson_stylus_px830.0.ip', function (err, fileName) { expect(err).to.be.not.ok; expect(fileName).to.be.ok; expect(fileName.ack).to.be.true; states.getState('epson_stylus_px830.0.inks.black.level', function (err, fileName) { expect(err).to.be.not.ok; expect(fileName).to.be.ok; expect(fileName.ack).to.be.true; states.getState('epson_stylus_px830.0.inks.cyan.cartridge', function (err, fileName) { expect(err).to.be.not.ok; expect(fileName).to.be.ok; expect(fileName.ack).to.be.true; states.getState('epson_stylus_px830.0.UNREACH', function (err, fileName) { expect(err).to.be.not.ok; expect(fileName).to.be.ok; expect(fileName.ack).to.be.true; done(); }); }); }); }); }); */ after('epson_stylus_px830: Stop js-controller', function (done) { this.timeout(5000); setup.stopController(function () { done(); }); }); });
export * from './firebase-storage'; export * from './firebase-storage-directive'; export * from './aspect-ratio';
/** * @fileoverview Rule to flag when using constructor without parentheses * @author Ilya Volodin */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "layout", docs: { description: "enforce or disallow parentheses when invoking a constructor with no arguments", recommended: false, url: "https://eslint.org/docs/rules/new-parens" }, fixable: "code", schema: { anyOf: [ { type: "array", items: [ { enum: ["always", "never"] } ], minItems: 0, maxItems: 1 } ] }, messages: { missing: "Missing '()' invoking a constructor.", unnecessary: "Unnecessary '()' invoking a constructor with no arguments." } }, create(context) { const options = context.options; const always = options[0] !== "never"; // Default is always const sourceCode = context.getSourceCode(); return { NewExpression(node) { if (node.arguments.length !== 0) { return; // if there are arguments, there have to be parens } const lastToken = sourceCode.getLastToken(node); const hasLastParen = lastToken && astUtils.isClosingParenToken(lastToken); // `hasParens` is true only if the new expression ends with its own parens, e.g., new new foo() does not end with its own parens const hasParens = hasLastParen && astUtils.isOpeningParenToken(sourceCode.getTokenBefore(lastToken)) && node.callee.range[1] < node.range[1]; if (always) { if (!hasParens) { context.report({ node, messageId: "missing", fix: fixer => fixer.insertTextAfter(node, "()") }); } } else { if (hasParens) { context.report({ node, messageId: "unnecessary", fix: fixer => [ fixer.remove(sourceCode.getTokenBefore(lastToken)), fixer.remove(lastToken), fixer.insertTextBefore(node, "("), fixer.insertTextAfter(node, ")") ] }); } } } }; } };
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports,require("@angular/core"),require("@angular/common")):"function"==typeof define&&define.amd?define(["exports","@angular/core","@angular/common"],r):r((e.vervaljs=e.vervaljs||{},e.vervaljs.charts={}),e.ng.core,e.ng.common)}(this,function(e,r,o){"use strict";var n=function(){function e(){}return e.prototype.ngOnInit=function(){},e.decorators=[{type:r.Component,args:[{selector:"bar",template:"<h1>Gráfica de barras</h1>"}]}],e.ctorParameters=function(){return[]},e}(),t=function(){function e(){}return e.decorators=[{type:r.NgModule,args:[{imports:[o.CommonModule],declarations:[n],exports:[n]}]}],e.ctorParameters=function(){return[]},e}();e.ChartsModule=t,e.BarComponent=n,Object.defineProperty(e,"__esModule",{value:!0})});
import React, { Component } from 'react' import { Menu } from 'shengnian-ui-react' export default class MenuExampleVerticalFitted extends Component { state = {} handleItemClick = (e, { name }) => this.setState({ activeItem: name }) render() { const { activeItem } = this.state return ( <Menu vertical> <Menu.Item name='default' active={activeItem === 'default'} fitted onClick={this.handleItemClick} > No padding whatsoever </Menu.Item> <Menu.Item name='horizontally' active={activeItem === 'horizontally'} fitted='horizontally' onClick={this.handleItemClick} > No horizontal padding </Menu.Item> <Menu.Item name='vertically' active={activeItem === 'vertically'} fitted='vertically' onClick={this.handleItemClick} > No vertical padding </Menu.Item> </Menu> ) } }
(function($, window, document) { // The $ is now locally scoped // The rest of your code goes here! $(document).ready(function() { $(".js-lead-sigup-form").on("submit", function(event) { var form = event.currentTarget; event.preventDefault(); $.ajax({ url: form.action, dataType: "json", type: 'POST', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')); }, data: $(form).serialize(), success: function(data) { var thankyouMessage = "<div class='thank-you-note alert alert-success'>Thank you for subscribing</div>"; $(".js-lead-sigup-form-wrapper").html(thankyouMessage); }, error: function(xhr) { var errors = $.parseJSON(xhr.responseText).errors var errorsWrapper = $("<ul class='js-form-errors alert alert-danger'></ul>"); $(".js-lead-sigup-form-errors").html(errorsWrapper); $.each(errors, function(key, value) { var attr = key.toLowerCase().replace(/\b[a-z]/g, function(letter) { return letter.toUpperCase(); }); $(".js-lead-sigup-form-errors .js-form-errors").append("<li class='error'>" + attr + " " + value + "</li>"); }); } }) }); }); }(window.jQuery, window, document));
$LAB // write each test in a seperate .script function // all tests are run simultaneously/asynchronously .script(function(){ if (document.querySelectorAll("#main").length) {return ["js/jquery.smoothState.js", "js/smooth.css.js"]; } else {return null;} }) .script(function(){ // load script if the the class *-col-* exists if (document.querySelectorAll('[class*="-col-"]').length) {return "//rawgit.com/Paul-Browne/jaygrid/master/js/jquery.jaygrid.min.js"; } // otherwise do nothing else {return null;} }) .script(function(){ if (document.querySelectorAll('table').length) {return ["//cdnjs.cloudflare.com/ajax/libs/stupidtable/0.0.1/stupidtable.js", "js/table.css.js"]; } else {return null;} }) .script(function(){ // add stylesheets by including a .js file, that will inturn create a <link> with your stylesheets. if (document.querySelectorAll('.fontface [class*="icon-"]').length) {return "js/iconfont.css.js"; } else if (document.querySelectorAll('.no-fontface [class*="icon-"]').length) {return "js/iconfont-fallback.css.js"; } else {return null;} }) .script(function(){ if (document.querySelectorAll('.desktop').length) {return "//rawgit.com/addyosmani/visibly.js/master/visibly.js"; } else {return null;} }) .script(function(){ if (document.querySelectorAll('[data-sr]').length) {return "js/scrollReveal.min.js"; } else {return null;} }) .script(function(){ if (document.querySelectorAll('pre code').length) {return ["js/highlight.js", "js/highlight.css.js"]; } else {return null;} }) .script(function(){ if (document.querySelectorAll('#test-4').length) {return "//cdnjs.cloudflare.com/ajax/libs/jquery-parallax/1.1.3/jquery-parallax-min.js"; } else {return null;} }) // write each inline initialization script in a seperate .wait function // these init. scripts are chained, they DON'T run simultaneously/asynchronously .wait(function(){ $.jaygrid(); }) .wait(function(){ $("#test-4").parallax("50%", 0.3); }) .wait(function(){ $("table").stupidtable(); }) .wait(function(){ hljs.initHighlighting(); }) .wait(function(){ window.sr = new scrollReveal({ reset: true, move: '222px', mobile: true }); }) .wait(function(){ $('#main').smoothState({ prefetch: true, pageCacheSize: 4, callback : function(){ $.getScript("https://rawgit.com/Paul-Browne/LALT/master/smooth-state-test/js/tests.js"); } }); }) .wait(function(){ visibly.onHidden(function (){ $("body").css({"opacity":"0"}) }); visibly.onVisible(function (){ $("body").velocity({ opacity: 1 }, { duration: 600 }) }); }); // <-- remember to end with a semi-colon
import AsyncEventEmitter from 'marsdb/dist/AsyncEventEmitter'; /** * Manages a heartbeat with a client */ export default class HeartbeatManager extends AsyncEventEmitter { constructor(pingTimeout = 17500, pongTimeout = 10000) { super(); this.pingTimeout = pingTimeout; this.pongTimeout = pongTimeout; } waitPing() { this._clearTimers(); this.waitPingTimer = setTimeout( () => { this.emit('sendPing'); this.waitPong(); }, this.pingTimeout ); } waitPong() { this._clearTimers(); this.waitPongTimer = setTimeout( () => this.emit('timeout'), this.pongTimeout ); } handlePing(id) { this._clearTimers(); this.emit('sendPong', id); this.waitPing(); } handlePong() { this._clearTimers(); this.waitPing(); } _clearTimers() { clearTimeout(this.waitPingTimer); clearTimeout(this.waitPongTimer); } }
'use strict'; var IndexController = angular.module('myApp.IndexController', []); /** * IndexController controls the index-template. */ IndexController.controller('IndexController', ['$scope', '$location', 'IndexService', function ($scope, $location, IndexService) { /** * Initializes the main menu sections */ $scope.initNavbar = function () { var sectionLink = $location.path().split("/")[1]; IndexService.setSelected(IndexService.getSectionFromLink(sectionLink)); }; /** * Returns true if section is selected, false otherwise * @param section The section to check if selected * @returns {boolean} True if selected, false otherwise */ $scope.isSelected = function (section) { return IndexService.isSelected(section); }; /** * Sets a section as the current one * @param section The section to set as selected */ $scope.setSelected = function (section) { IndexService.setSelected(section); }; /* Initialize the main menu */ $scope.initNavbar(); $scope.sections = IndexService.sections; $scope.helpSections = IndexService.helpSections; }]);
"use strict"; var rio = require("../lib/rio"); rio.e({command: "# ห\n2+2"}); rio.e({command: "# แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช " + "พระปกเกศกองบู๊กู้ขึ้นใหม่\n65+4"}); rio.e({command: "# แผ่องบู๊กู้ขึ้นใหม่\n2*3"});
//ESEMPIO UTILIZZO PER options map + defaults function doSomething(opt) { var defaults = { enable: false, count: 0, title: "", values: [1,2,3] }; var options = mixIn({}, defaults, opt); //opzioni correnti con //ovverride in base all'opt passate //... logica della funzione che usa TUTTE le options console.dir(options); } //UNITTEST doSomething(); //non passando niente ottengo i defaults doSomething({enable: true, count: 9}); //caso tipico di utilizzo doSomething({title: "Sovrascrivo e aggiungo TAG", tag: "MERGIATO!"}); doSomething({title: "Attenzione sovrascrivo l'array NON FA MERGE!" , values: [4,5,6,7,8,9]}); doSomething({title: "Fare molta attenzione pechè posso anche ELIMINARE con undefined!!!" , count: null, values: undefined}); function mixIn(target /*, ...mixins*/ ) { var i, k, mixin, n = arguments.length; //numero di argomenti passati mixins* if (n<=1) return target; //se passo solo target lo ritorno subito invariato for(i=0; i<n; i++) { mixin = arguments[i]; //elaboro ogni singolo oggetto mixin passato for(k in mixin) { //copiando tutti i membri in target (sovrascivendo) if (mixin.hasOwnProperty(k)) target[k] = mixin[k]; } } return target; //ritorno l'oggetto "aumentato" }
import fs from 'fs'; import path from 'path'; import url from 'url'; import hbs from 'handlebars'; import wrench from 'wrench'; import extend from './extend'; import Renderer from './Renderer'; /** * Provides methods for querying, loading and rendering templates * from the filesystem. * * @extends Renderer */ class Templates extends Renderer { /** * Construct the class * * @param {boolean} options.debug - Whether or not to render out debug comments * @param {object} options.log - An object that provides logging capability * @param {string} options.dir - Path to the blocks directory * @param {string} options.url - URL that blocks should be served from */ constructor(options) { super(options); } /** * Render a template from a given URL * * @param {string} templateUrl - URL of the template * @returns {*} */ renderFromUrl(templateUrl, req, res) { let urlParts = url.parse(templateUrl, true); let templatePath = urlParts.pathname; if (templatePath.slice(-1) === '/') { templatePath = templatePath.slice(0, -1); } templatePath = templatePath.substr(this.url.length + 1); return this.getByName(templatePath); } /** * Get the template by it's name * * @param {string} name - Name of the template * @returns {string|boolean} The HBS file content of the template, or false on error */ getByName(name) { let filePath = this.dir + path.sep + name.split('/').join(path.sep) + '.hbs'; try { this.log.debug('Using template:', filePath); return fs.readFileSync(filePath, 'utf8'); } catch (e) { this.log.error(`Unable to find template: ${name}`); return false; } } /** * * @param {string} name - Name of the template to render * @param {object} data - Data to be passed to the template * @returns {string} HTML output of the template */ render(name, data) { let templateHbsFunc = hbs.compile(this.getByName(name)); let markup; extend(data, { site: this.site }); this.log.debug(`Rendering template: ${name}`); this.log.debug('Template data:', data); markup = templateHbsFunc(data); if (this.debug) { markup += '\n<!-- template: ' + name + ' -->\n'; } return markup; } /** * Get a list of templates * * The returned array is list of objects, where each object has two * properties: 'url' and 'name'. * * @returns {array} */ getListOfTemplates() { let files = []; try { files = wrench.readdirSyncRecursive(this.dir); } catch (e) { this.log.error(`Unable to find templates directory: ${this.dir}`); } if (files) { files.forEach((item, index) => { if (item.substr(0, 1) === '.' || item.substr(-4) !== '.hbs') { delete files[index]; } else { let name = item.split(path.sep).join('/').slice(0, -4); files[index] = { url: this.url + '/' + name, name: name }; } }); this.log.debug(`Template list: ${files}`); return files; } this.log.debug('Template list: no files found'); return []; } } export default Templates;
'use strict'; var React = require('react'); var SvgIcon = require('../../svg-icon'); var DeviceAccessAlarm = React.createClass({ displayName: 'DeviceAccessAlarm', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: "M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z" }) ); } }); module.exports = DeviceAccessAlarm;
import $ from 'jquery'; import Dropzone from 'dropzone'; import request from '../../utils/request'; import { config, translations } from 'grav-config'; // translations const Dictionary = { dictCancelUpload: translations.PLUGIN_ADMIN.DROPZONE_CANCEL_UPLOAD, dictCancelUploadConfirmation: translations.PLUGIN_ADMIN.DROPZONE_CANCEL_UPLOAD_CONFIRMATION, dictDefaultMessage: translations.PLUGIN_ADMIN.DROPZONE_DEFAULT_MESSAGE, dictFallbackMessage: translations.PLUGIN_ADMIN.DROPZONE_FALLBACK_MESSAGE, dictFallbackText: translations.PLUGIN_ADMIN.DROPZONE_FALLBACK_TEXT, dictFileTooBig: translations.PLUGIN_ADMIN.DROPZONE_FILE_TOO_BIG, dictInvalidFileType: translations.PLUGIN_ADMIN.DROPZONE_INVALID_FILE_TYPE, dictMaxFilesExceeded: translations.PLUGIN_ADMIN.DROPZONE_MAX_FILES_EXCEEDED, dictRemoveFile: translations.PLUGIN_ADMIN.DROPZONE_REMOVE_FILE, dictResponseError: translations.PLUGIN_ADMIN.DROPZONE_RESPONSE_ERROR }; Dropzone.autoDiscover = false; Dropzone.options.gravPageDropzone = {}; Dropzone.confirm = (question, accepted, rejected) => { let doc = $(document); let modalSelector = '[data-remodal-id="delete-media"]'; let removeEvents = () => { doc.off('confirmation', modalSelector, accept); doc.off('cancellation', modalSelector, reject); $(modalSelector).find('.remodal-confirm').removeClass('pointer-events-disabled'); }; let accept = () => { accepted && accepted(); removeEvents(); }; let reject = () => { rejected && rejected(); removeEvents(); }; $.remodal.lookup[$(modalSelector).data('remodal')].open(); doc.on('confirmation', modalSelector, accept); doc.on('cancellation', modalSelector, reject); }; const DropzoneMediaConfig = { createImageThumbnails: { }, thumbnailWidth: 150, thumbnailHeight: 100, addRemoveLinks: false, dictDefaultMessage: translations.PLUGIN_ADMIN.DROP_FILES_HERE_TO_UPLOAD, dictRemoveFileConfirmation: '[placeholder]', previewTemplate: ` <div class="dz-preview dz-file-preview"> <div class="dz-details"> <div class="dz-filename"><span data-dz-name></span></div> <div class="dz-size" data-dz-size></div> <img data-dz-thumbnail /> </div> <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div> <div class="dz-success-mark"><span>✔</span></div> <div class="dz-error-mark"><span>✘</span></div> <div class="dz-error-message"><span data-dz-errormessage></span></div> <a class="dz-remove file-thumbnail-remove" href="javascript:undefined;" data-dz-remove><i class="fa fa-fw fa-close"></i></a> </div>`.trim() }; export default class FilesField { constructor({ container = '.dropzone.files-upload', options = {} } = {}) { this.container = $(container); if (!this.container.length) { return; } this.urls = {}; this.options = Object.assign({}, Dictionary, DropzoneMediaConfig, { klass: this, url: this.container.data('file-url-add') || config.current_url, acceptedFiles: this.container.data('media-types'), init: this.initDropzone }, this.container.data('dropzone-options'), options); this.dropzone = new Dropzone(container, this.options); this.dropzone.on('complete', this.onDropzoneComplete.bind(this)); this.dropzone.on('success', this.onDropzoneSuccess.bind(this)); this.dropzone.on('removedfile', this.onDropzoneRemovedFile.bind(this)); this.dropzone.on('sending', this.onDropzoneSending.bind(this)); this.dropzone.on('error', this.onDropzoneError.bind(this)); } initDropzone() { let files = this.options.klass.container.find('[data-file]'); let dropzone = this; if (!files.length) { return; } files.each((index, file) => { file = $(file); let data = file.data('file'); let mock = { name: data.name, size: data.size, type: data.type, status: Dropzone.ADDED, accepted: true, url: this.options.url, removeUrl: data.remove }; dropzone.files.push(mock); dropzone.options.addedfile.call(dropzone, mock); if (mock.type.match(/^image\//)) { dropzone.options.thumbnail.call(dropzone, mock, data.path); dropzone.createThumbnailFromUrl(mock, data.path); } file.remove(); }); } onDropzoneSending(file, xhr, formData) { formData.append('name', this.options.dotNotation); formData.append('admin-nonce', config.admin_nonce); formData.append('task', 'filesupload'); } onDropzoneSuccess(file, response, xhr) { if (this.options.reloadPage) { global.location.reload(); } // store params for removing file from session before it gets saved if (response.session) { file.sessionParams = response.session; file.removeUrl = this.options.url; // Touch field value to force a mutation detection const input = this.container.find('[name][type="hidden"]'); const value = input.val(); input.val(value + ' '); } return this.handleError({ file, data: response, mode: 'removeFile', msg: `<p>${translations.PLUGIN_ADMIN.FILE_ERROR_UPLOAD} <strong>${file.name}</strong></p> <pre>${response.message}</pre>` }); } onDropzoneComplete(file) { if (!file.accepted && !file.rejected) { let data = { status: 'error', message: `${translations.PLUGIN_ADMIN.FILE_UNSUPPORTED}: ${file.name.match(/\..+/).join('')}` }; return this.handleError({ file, data, mode: 'removeFile', msg: `<p>${translations.PLUGIN_ADMIN.FILE_ERROR_ADD} <strong>${file.name}</strong></p> <pre>${data.message}</pre>` }); } if (this.options.reloadPage) { global.location.reload(); } } b64_to_utf8(str) { str = str.replace(/\s/g, ''); return decodeURIComponent(escape(window.atob(str))); } onDropzoneRemovedFile(file, ...extra) { if (!file.accepted || file.rejected) { return; } let url = file.removeUrl || this.urls.delete; let path = (url || '').match(/path:(.*)\//); let body = { filename: file.name }; if (file.sessionParams) { body.task = 'filessessionremove'; body.session = file.sessionParams; } request(url, { method: 'post', body }, () => { if (!path) { return; } path = this.b64_to_utf8(path[1]); let input = this.container.find('[name][type="hidden"]'); let data = JSON.parse(input.val() || '{}'); delete data[path]; input.val(JSON.stringify(data)); }); } onDropzoneError(file, response, xhr) { let message = xhr ? response.error.message : response; $(file.previewElement).find('[data-dz-errormessage]').html(message); return this.handleError({ file, data: { status: 'error' }, msg: `<pre>${message}</pre>` }); } handleError(options) { let { file, data, mode, msg } = options; if (data.status !== 'error' && data.status !== 'unauthorized') { return; } switch (mode) { case 'addBack': if (file instanceof File) { this.dropzone.addFile.call(this.dropzone, file); } else { this.dropzone.files.push(file); this.dropzone.options.addedfile.call(this.dropzone, file); this.dropzone.options.thumbnail.call(this.dropzone, file, file.extras.url); } break; case 'removeFile': default: if (~this.dropzone.files.indexOf(file)) { file.rejected = true; this.dropzone.removeFile.call(this.dropzone, file, { silent: true }); } break; } let modal = $('[data-remodal-id="generic"]'); modal.find('.error-content').html(msg); $.remodal.lookup[modal.data('remodal')].open(); } } export function UriToMarkdown(uri) { uri = uri.replace(/@3x|@2x|@1x/, ''); uri = uri.replace(/\(/g, '%28'); uri = uri.replace(/\)/g, '%29'); return uri.match(/\.(jpe?g|png|gif|svg)$/i) ? `![](${uri})` : `[${decodeURI(uri)}](${uri})`; } let instances = []; let cache = $(); const onAddedNodes = (event, target/* , record, instance */) => { let files = $(target).find('.dropzone.files-upload'); if (!files.length) { return; } files.each((index, file) => { file = $(file); if (!~cache.index(file)) { addNode(file); } }); }; const addNode = (container) => { container = $(container); let input = container.find('input[type="file"]'); let settings = container.data('grav-file-settings') || {}; if (settings.accept && ~settings.accept.indexOf('*')) { settings.accept = ['']; } let options = { url: container.data('file-url-add') || (container.closest('form').attr('action') || config.current_url) + '.json', paramName: settings.paramName || 'file', dotNotation: settings.name || 'file', acceptedFiles: settings.accept ? settings.accept.join(',') : input.attr('accept') || container.data('media-types'), maxFilesize: typeof settings.filesize !== 'undefined' ? settings.filesize : 256, maxFiles: settings.limit || null }; cache = cache.add(container); container = container[0]; instances.push(new FilesField({ container, options })); }; export let Instances = (() => { $('.dropzone.files-upload').each((i, container) => addNode(container)); $('body').on('mutation._grav', onAddedNodes); return instances; })();
positron.provide ("ChangeLensAction"); ChangeLensAction = function () { positron.action.Action.call (this); console.log ("registering ChangeLensAction"); } positron.inherits (ChangeLensAction, positron.action.Action); ChangeLensAction.prototype.fire = function (inEvent) { positron.action.Action.prototype.fire.call (this, inEvent); console.log("change lense action firing with arg:"); console.log(this.actionArgs [0]); var direction = inEvent.detail.direction; var type = inEvent.detail.type; var position = inEvent.detail.position; var startPosition = inEvent.detail.startPosition; var centerDistance = inEvent.detail.centerDistance; var centerDistanceDelta = inEvent.detail.centerDistanceDelta; var moveDelta = Math.abs(startPosition - position); console.log ("change lens with " + position); console.log ("move delta is: " + moveDelta); console.log ("Center distance delta is: " + centerDistanceDelta); console.log ("START TOP LEFT? " + inEvent.detail.START_TOP_LEFT); if (inEvent.detail.START_TOP_LEFT && moveDelta < 20 && centerDistanceDelta > 30 && gApplication.canCollapse) { gApplication.canCollapse = false; console.log ("!!!!!! COLLAPSE!"); var runningLenses = document.querySelector("#running-lenses:not(.offscreen)"); if (runningLenses) { document.querySelector("#detached-lens-blocker").classList.remove("blocking"); runningLenses.classList.remove("detached"); runningLenses.classList.add("offscreen"); var closeLensButtons = document.querySelectorAll(".close-lens"); console.log ("found close buttons"); console.log (closeLensButtons); [].forEach.call( document.querySelectorAll(".close-lens"), function(el){ el.classList.remove("visible"); } ); } } else if (inEvent.detail.START_TOP_LEFT && moveDelta < 10 && centerDistanceDelta > 5 && gApplication.canDetach) { gApplication.canDetach = false; console.log ("!!!!!! DETACH!"); var runningLenses = document.querySelector("#running-lenses:not(.offscreen)"); if (runningLenses) { runningLenses.classList.add ("detached"); document.querySelector("#detached-lens-blocker").classList.add("blocking"); } [].forEach.call( document.querySelectorAll(".close-lens"), function(el){ el.classList.add("visible"); } ); } };
var Type = require("@kaoscript/runtime").Type; module.exports = function() { class Foobar { constructor() { this.__ks_init(); this.__ks_cons(arguments); } __ks_init() { } __ks_cons(args) { if(args.length !== 0) { throw new SyntaxError("Wrong number of arguments"); } } __ks_func_toString_0() { return "foobar"; } toString() { if(arguments.length === 0) { return Foobar.prototype.__ks_func_toString_0.apply(this); } throw new SyntaxError("Wrong number of arguments"); } } function foobar(x) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(x === void 0 || x === null) { throw new TypeError("'x' is not nullable"); } else if(!Type.isString(x)) { throw new TypeError("'x' is not of type 'String'"); } return new Foobar(); } return { foobar: foobar }; };
/** * myLupus - Erweitere Anbindung der Lupusec XT2 Alarmanlage * * Author: @devius_lupus * Source: tbd * */ /** * Todo: * IP, Software Versionen: http://<ip>/action/welcomeGet * Historie: http://<ip>/action/recordListGet (max_count:int) * */ var http = require("http"); var https = require("https"); var config = require('../config'); exports.getJSON = function(options, onResult){ var prot = options.port == 443 ? https : http; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; var req = prot.request(options, function(res) { var output = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { output += chunk; }); res.on('end', function() { // JSON aufräumen ... // Im JSON sind Tabs - indikation für die Singalstärke var obj = JSON.parse(output.replace(/\u0009/g," ")); onResult(res.statusCode, obj); }); req.on('error', function(err) { console.log("Got error: " + err.message); res.send('error: ' + err.message); }); }); req.end(); }; exports.status_param = function() { var options = { host: config.lupusec.ip, port: 443, path: '/action/panelCondGet', headers: { 'Authorization': 'Basic ' + new Buffer(config.lupusec.user + ':' + config.lupusec.pw).toString('base64'), 'Content-Type': 'application/json' } }; return options; } exports.list_param = function() { var options = { host: config.lupusec.ip, port: 443, path: '/action/deviceListGet', headers: { 'Authorization': 'Basic ' + new Buffer(config.lupusec.user + ':' + config.lupusec.pw).toString('base64'), 'Content-Type': 'application/json' } }; return options; } exports.arm_param = function() { var options = { host: config.lupusec.ip, port: 443, path: '/action/panelCondPost?area=1&mode=1', headers: { 'Authorization': 'Basic ' + new Buffer(config.lupusec.user + ':' + config.lupusec.pw).toString('base64'), 'Content-Type': 'application/json' } }; return options; } exports.disarm_param = function() { var options = { host: config.lupusec.ip, port: 443, path: '/action/panelCondPost?area=1&mode=0', headers: { 'Authorization': 'Basic ' + new Buffer(config.lupusec.user + ':' + config.lupusec.pw).toString('base64'), 'Content-Type': 'application/json' } }; return options; } exports.return_relevant = function(options, onResult){ module.exports.getJSON(module.exports.list_param(), function(statusCode, result){ var result_alarm = ""; var result_open = ""; for(var sensorrow in result.senrows) { if(result.senrows[sensorrow].alarm_status == "1"){ result_alarm += result.senrows[sensorrow].name + ", "; } if(result.senrows[sensorrow].type == 4){ if(result.senrows[sensorrow].status == "{WEB_MSG_DC_OPEN}"){ result_open += result.senrows[sensorrow].name +", " ; } } } var return_value = ""; if(result_alarm !== "" ){ return_value = "Alarm bei: " + result_alarm; } if(result_open !== ""){ return_value += "Offen: " + result_open; } if(!return_value){ return_value = "Keine Meldungen"; } if(statusCode !== 200){ return_value = "Status Code: " + statusCode + " Wert: " + JSON.stringify(result) } onResult(return_value); }); } exports.get_status = function(options, onResult){ module.exports.getJSON(module.exports.status_param(), function(statusCode, result){ var return_value = "Area 1: " + result.updates.mode_a1 + ", Batterie: "+result.updates.battery_ok + ", Interferenz: "+ result.updates.interference_ok + ", GSM Signal: " + result.updates.sig_gsm_ok + ", Stromverbauch: " + result.updates.ac_activation_ok; if(!return_value){ return_value = "Keine Meldungen"; } if(statusCode !== 200){ return_value = "Status Code: " + statusCode + " Wert: " + JSON.stringify(result) } onResult(return_value); }); }
var fs = require('fs'), path = require('path'), Sequelize = require('sequelize'), config = require('../config'), db = {} var sequelize = new Sequelize(config.db, { pool: { max: 10, min: 0, idle: 10000 }, // logging: false, define: { underscored: true } }) fs.readdirSync(__dirname).filter(function (file) { return (file.indexOf('.') !== 0) && (file !== 'index.js') }).forEach(function (file) { var model = sequelize['import'](path.join(__dirname, file)) db[model.name] = model }) Object.keys(db).forEach(function (modelName) { if ('associate' in db[modelName]) { db[modelName].associate(db) } }) sequelize.sync() db.sequelize = sequelize db.Sequelize = Sequelize module.exports = db
/** * Kebab AboutMe Application Bootstrap Class * * @category Kebab * @package Applications * @namespace KebabOS.applications.aboutMe.application * @author Tayfun Öziş ERİKAN <tayfun.ozis.erikan@lab2023.com> * @copyright Copyright (c) 2010-2011 lab2023 - internet technologies TURKEY Inc. (http://www.lab2023.com) * @license http://www.kebab-project.com/cms/licensing */ Ext.extend(KebabOS.applications.aboutMe.application.Bootstrap, Kebab.OS.Application, { constructor: function() { KebabOS.applications.aboutMe.application.Bootstrap.superclass.constructor.call(this); }, createApplication : function(){ var desktop = this.app.getDesktop(); var app = desktop.getApplication(this.id); if(!app){ var winWidth = 500; var winHeight = 350; // Default layout this.layout = new KebabOS.applications.aboutMe.application.layouts.Layout({ bootstrap: this }); // Default controller this.defaultController = new KebabOS.applications.aboutMe.application.controllers.Index({ bootstrap: this }); app = desktop.createApplication({ id: this.id, title: this.title.text, description: this.title.description, iconCls: 'aboutMe-application-gui-icon', width: winWidth, resizable: true, height: winHeight, maximizable: false, border: false, items: this.layout }); } app.show(); } });
import config from '../../config.babel' import env from '../../lib/env.babel' import gulp from 'gulp' import gulpif from 'gulp-if' import changed from 'gulp-changed' import browserSync from 'browser-sync' import imagemin from 'gulp-imagemin' import pngquant from 'imagemin-pngquant' const dev = env !== config.build.prod const dest = gulp.dest let copyImagemin = () => { gulp.src( config.copyImg.src ) .pipe(changed( config.copyImg.dest )) .pipe(imagemin({ progressive: true, interlaced: true, svgoPlugins: config.copyImg.svgoPlugins, use: [ pngquant( config.copyImg.pngquant ) ] })) .pipe(dest( config.copyImg.dest )) .pipe(gulpif(!dev, browserSync.reload( config.browserSync.reload ))) } gulp.task('copy-imagemin', copyImagemin)
import { css } from "../../src/literals.js"; export default css` #container { display: flex; position: fixed; top: 0; bottom: 0; left: -300px; width: 90vw; height: 100vh; max-width: 300px; z-index: 10001; background: white; font-family: var(--magnon-font); transition: left 0.15s ease-out; } #main-nav > ::slotted(a) { color: var(--magnon-dark-teal); text-decoration: none; display: block; text-align: left; font-size: 20px; margin: 30px 30px; flex-grow: 1; } #blackout { position: fixed; top: 0; right: 0; bottom: 0; left: 0; width: 100vw; height: 100vh; z-index: 10000; background: var(--magnon-black-blue); opacity: 0; pointer-events: none; transition: opacity 0.2s ease-in-out; } `;
/** @module ember-metal */ /* JavaScript (before ES6) does not have a Map implementation. Objects, which are often used as dictionaries, may only have Strings as keys. Because Ember has a way to get a unique identifier for every object via `Ember.guidFor`, we can implement a performant Map with arbitrary keys. Because it is commonly used in low-level bookkeeping, Map is implemented as a pure JavaScript object for performance. This implementation follows the current iteration of the ES6 proposal for maps (http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets), with one exception: as we do not have the luxury of in-VM iteration, we implement a forEach method for iteration. Map is mocked out to look like an Ember object, so you can do `Ember.Map.create()` for symmetry with other Ember classes. */ import { guidFor } from "ember-metal/utils"; import { indexOf } from "ember-metal/array"; import { create } from "ember-metal/platform"; import { deprecateProperty } from "ember-metal/deprecate_property"; function missingFunction(fn) { throw new TypeError('' + Object.prototype.toString.call(fn) + " is not a function"); } function missingNew(name) { throw new TypeError("Constructor " + name + "requires 'new'"); } function copyNull(obj) { var output = create(null); for (var prop in obj) { // hasOwnPropery is not needed because obj is Object.create(null); output[prop] = obj[prop]; } return output; } function copyMap(original, newObject) { var keys = original._keys.copy(); var values = copyNull(original._values); newObject._keys = keys; newObject._values = values; newObject.size = original.size; return newObject; } /** This class is used internally by Ember and Ember Data. Please do not use it at this time. We plan to clean it up and add many tests soon. @class OrderedSet @namespace Ember @constructor @private */ function OrderedSet() { if (this instanceof OrderedSet) { this.clear(); this._silenceRemoveDeprecation = false; } else { missingNew("OrderedSet"); } } /** @method create @static @return {Ember.OrderedSet} */ OrderedSet.create = function() { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = { constructor: OrderedSet, /** @method clear */ clear: function() { this.presenceSet = create(null); this.list = []; this.size = 0; }, /** @method add @param obj @param guid (optional, and for internal use) @return {Ember.OrderedSet} */ add: function(obj, _guid) { var guid = _guid || guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] !== true) { presenceSet[guid] = true; this.size = list.push(obj); } return this; }, /** @deprecated @method remove @param obj @param _guid (optional and for internal use only) @return {Boolean} */ remove: function(obj, _guid) { Ember.deprecate('Calling `OrderedSet.prototype.remove` has been deprecated, please use `OrderedSet.prototype.delete` instead.', this._silenceRemoveDeprecation); return this.delete(obj, _guid); }, /** @since 1.8.0 @method delete @param obj @param _guid (optional and for internal use only) @return {Boolean} */ delete: function(obj, _guid) { var guid = _guid || guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { delete presenceSet[guid]; var index = indexOf.call(list, obj); if (index > -1) { list.splice(index, 1); } this.size = list.length; return true; } else { return false; } }, /** @method isEmpty @return {Boolean} */ isEmpty: function() { return this.size === 0; }, /** @method has @param obj @return {Boolean} */ has: function(obj) { if (this.size === 0) { return false; } var guid = guidFor(obj); var presenceSet = this.presenceSet; return presenceSet[guid] === true; }, /** @method forEach @param {Function} fn @param self */ forEach: function(fn /*, thisArg*/) { if (typeof fn !== 'function') { missingFunction(fn); } if (this.size === 0) { return; } var list = this.list; var length = arguments.length; var i; if (length === 2) { for (i = 0; i < list.length; i++) { fn.call(arguments[1], list[i]); } } else { for (i = 0; i < list.length; i++) { fn(list[i]); } } }, /** @method toArray @return {Array} */ toArray: function() { return this.list.slice(); }, /** @method copy @return {Ember.OrderedSet} */ copy: function() { var Constructor = this.constructor; var set = new Constructor(); set._silenceRemoveDeprecation = this._silenceRemoveDeprecation; set.presenceSet = copyNull(this.presenceSet); set.list = this.toArray(); set.size = this.size; return set; } }; deprecateProperty(OrderedSet.prototype, 'length', 'size'); /** A Map stores values indexed by keys. Unlike JavaScript's default Objects, the keys of a Map can be any JavaScript object. Internally, a Map has two data structures: 1. `keys`: an OrderedSet of all of the existing keys 2. `values`: a JavaScript Object indexed by the `Ember.guidFor(key)` When a key/value pair is added for the first time, we add the key to the `keys` OrderedSet, and create or replace an entry in `values`. When an entry is deleted, we delete its entry in `keys` and `values`. @class Map @namespace Ember @private @constructor */ function Map() { if (this instanceof this.constructor) { this._keys = OrderedSet.create(); this._keys._silenceRemoveDeprecation = true; this._values = create(null); this.size = 0; } else { missingNew("OrderedSet"); } } Ember.Map = Map; /** @method create @static */ Map.create = function() { var Constructor = this; return new Constructor(); }; Map.prototype = { constructor: Map, /** This property will change as the number of objects in the map changes. @since 1.8.0 @property size @type number @default 0 */ size: 0, /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or `undefined` */ get: function(key) { if (this.size === 0) { return; } var values = this._values; var guid = guidFor(key); return values[guid]; }, /** Adds a value to the map. If a value for the given key has already been provided, the new value will replace the old value. @method set @param {*} key @param {*} value @return {Ember.Map} */ set: function(key, value) { var keys = this._keys; var values = this._values; var guid = guidFor(key); // ensure we don't store -0 var k = key === -0 ? 0 : key; keys.add(k, guid); values[guid] = value; this.size = keys.size; return this; }, /** @deprecated see delete Removes a value from the map for an associated key. @method remove @param {*} key @return {Boolean} true if an item was removed, false otherwise */ remove: function(key) { Ember.deprecate('Calling `Map.prototype.remove` has been deprecated, please use `Map.prototype.delete` instead.'); return this.delete(key); }, /** Removes a value from the map for an associated key. @since 1.8.0 @method delete @param {*} key @return {Boolean} true if an item was removed, false otherwise */ delete: function(key) { if (this.size === 0) { return false; } // don't use ES6 "delete" because it will be annoying // to use in browsers that are not ES6 friendly; var keys = this._keys; var values = this._values; var guid = guidFor(key); if (keys.delete(key, guid)) { delete values[guid]; this.size = keys.size; return true; } else { return false; } }, /** Check whether a key is present. @method has @param {*} key @return {Boolean} true if the item was present, false otherwise */ has: function(key) { return this._keys.has(key); }, /** Iterate over all the keys and values. Calls the function once for each key, passing in value, key, and the map being iterated over, in that order. The keys are guaranteed to be iterated over in insertion order. @method forEach @param {Function} callback @param {*} self if passed, the `this` value inside the callback. By default, `this` is the map. */ forEach: function(callback /*, thisArg*/) { if (typeof callback !== 'function') { missingFunction(callback); } if (this.size === 0) { return; } var length = arguments.length; var map = this; var cb, thisArg; if (length === 2) { thisArg = arguments[1]; cb = function(key) { callback.call(thisArg, map.get(key), key, map); }; } else { cb = function(key) { callback(map.get(key), key, map); }; } this._keys.forEach(cb); }, /** @method clear */ clear: function() { this._keys.clear(); this._values = create(null); this.size = 0; }, /** @method copy @return {Ember.Map} */ copy: function() { return copyMap(this, new Map()); } }; deprecateProperty(Map.prototype, 'length', 'size'); /** @class MapWithDefault @namespace Ember @extends Ember.Map @private @constructor @param [options] @param {*} [options.defaultValue] */ function MapWithDefault(options) { this._super$constructor(); this.defaultValue = options.defaultValue; } /** @method create @static @param [options] @param {*} [options.defaultValue] @return {Ember.MapWithDefault|Ember.Map} If options are passed, returns `Ember.MapWithDefault` otherwise returns `Ember.Map` */ MapWithDefault.create = function(options) { if (options) { return new MapWithDefault(options); } else { return new Map(); } }; MapWithDefault.prototype = create(Map.prototype); MapWithDefault.prototype.constructor = MapWithDefault; MapWithDefault.prototype._super$constructor = Map; MapWithDefault.prototype._super$get = Map.prototype.get; /** Retrieve the value associated with a given key. @method get @param {*} key @return {*} the value associated with the key, or the default value */ MapWithDefault.prototype.get = function(key) { var hasValue = this.has(key); if (hasValue) { return this._super$get(key); } else { var defaultValue = this.defaultValue(key); this.set(key, defaultValue); return defaultValue; } }; /** @method copy @return {Ember.MapWithDefault} */ MapWithDefault.prototype.copy = function() { var Constructor = this.constructor; return copyMap(this, new Constructor({ defaultValue: this.defaultValue })); }; export default Map; export { OrderedSet, Map, MapWithDefault };
var core; module.export = function(){ };
var foodRowID; function fillInvoiceData(rowData, rowId) { //Assigning row's id foodRowID = rowId; //Showing invoce card and background show("#invoice-card"); show(background); //Deleting elements $("#delete-row").remove() $("#checkout").remove(); }
'use strict'; import http from 'http'; import https from 'https'; import express from 'express'; import winston from 'winston'; import bodyParser from 'body-parser'; import helmet from 'helmet'; import consolidate from 'consolidate'; import path from 'path'; import globby from 'globby'; import config from 'modernMean/config'; import enableDestroy from 'server-destroy'; import morgan from 'morgan'; import livereload from 'connect-livereload'; import fs from 'fs'; import forceSSL from 'express-force-ssl'; //Store Express server let httpServer, httpsServer, expressApp; function variables(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Variables::Start'); app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.logo = config.logo; app.locals.favicon = config.favicon; winston.verbose('Express::Variables::Success'); return resolve(app); }); } function middleware(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Middleware::Start'); app.use(morgan(config.logs.morgan.format, config.logs.morgan.options)); if (process.env.NODE_ENV === 'development') { app.use(livereload()); } app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); if (config.express.https.enable) { app.set('forceSSLOptions', { httpsPort: config.express.https.port }); app.use(forceSSL); } winston.verbose('Express::Middleware::Success'); return resolve(app); }); } /** * Configure view engine */ function engine(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Engine::Start'); // Set swig as the template engine app.engine('server.view.html', consolidate[config.express.engine]); // Set views path and view engine app.set('view engine', 'server.view.html'); app.set('views', './'); winston.verbose('Express::Engine::Success'); return resolve(app); }); } function headers(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Headers::Start'); app.use(helmet()); winston.verbose('Express::Headers::Success'); return resolve(app); }); } function modules(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Modules::Start'); let promises = []; globby(config.files.serve.modules.custom) .then(files => { files.forEach(file => { winston.debug('Express::Module::Match::' + file); let promise = require(path.resolve(file)).default.init(app); promises.push(promise); }); Promise.all(promises) .then(function () { winston.verbose('Express::Modules::Success'); resolve(app); }) .catch(function (err) { winston.error(err); reject(err); }); }); }); } function core(app) { return new Promise(function (resolve, reject) { winston.debug('Express::Core::Start'); //TODO Change to System.import when its available require(path.resolve(config.files.serve.modules.core)).default.init(app) .then(function () { winston.verbose('Express::Core::Success'); return resolve(app); }) .catch(function (err) { winston.error(err); return reject(err); }); }); } function listen(app) { winston.debug('Express::Listen::Start'); let httpServerPromise = new Promise(function (resolve, reject) { httpServer.listen(config.express.http.port, config.express.host, () => { /* istanbul ignore else: cant test this since production server cant be destroyed */ if(process.env.NODE_ENV !== 'production') { enableDestroy(httpServer); } resolve(app); }); }); let httpsServerPromise = new Promise(function (resolve, reject) { if (!config.express.https.enable) { return resolve(); } httpsServer.listen(config.express.https.port, config.express.host, () => { /* istanbul ignore else: cant test this since production server cant be destroyed */ if(process.env.NODE_ENV !== 'production') { enableDestroy(httpsServer); } resolve(app); }); }); return Promise.all([httpServerPromise, httpsServerPromise]) .then(promises => { winston.info('--'); winston.info(config.app.title); winston.info('Environment: ' + process.env.NODE_ENV); winston.info('App version: ' + config.app.version); winston.info('Database: ' + config.db.uri); winston.info('HTTP Server: http://' + httpServer.address().address + ':' + httpServer.address().port); if (config.express.https.enable) { winston.info('HTTPS Server: https://' + httpsServer.address().address + ':' + httpsServer.address().port); } winston.info('--'); return app; }); } function init() { return new Promise(function (resolve, reject) { winston.debug('Express::Init::Start'); if (expressApp !== undefined || httpsServer !== undefined || httpServer !== undefined) { return reject('Express::Init::Error::Server is still running.'); } expressApp = express(); httpServer = http.createServer(expressApp); if (config.express.https.enable) { let httpsOptions = { key: fs.readFileSync(config.express.https.options.key), cert: fs.readFileSync(config.express.https.options.cert) }; httpsServer = https.createServer(httpsOptions, expressApp); } winston.verbose('Express::Init::Success'); return resolve(expressApp); }); } function destroy() { expressApp = undefined; let httpServerPromise = new Promise(function (resolve, reject) { if (!httpServer || !httpServer.listening) { httpServer = undefined; return resolve(); } httpServer.destroy(function () { httpServer = undefined; resolve(); }); }); let httpsServerPromise = new Promise(function (resolve, reject) { if (!httpsServer || !httpsServer.listening) { httpsServer = undefined; return resolve(); } httpsServer.destroy(function () { httpsServer = undefined; return resolve(); }); }); return Promise.all([httpServerPromise, httpsServerPromise]) .then(() => { winston.info('Express::Destroy::Success'); }); } function getHttpServer() { return httpServer; } function getHttpsServer() { return httpsServer; } function getExpressApp() { return expressApp; } let service = { core: core, engine: engine, headers: headers, init: init, listen: listen, middleware: middleware, modules: modules, variables: variables, destroy: destroy, httpServer: getHttpServer, httpsServer: getHttpsServer, expressApp: getExpressApp }; export default service; export { core, engine, headers, init, listen, middleware, modules, variables, getHttpServer as httpServer, getHttpsServer as httpsServer, getExpressApp as expressApp, destroy };
// Copyright (c) Dyoub Applications. All rights reserved. // Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE). (function (JQLite) { JQLite.prototype.number = function (options) { var $element = this; function mask(newValue, oldValue) { var digits = newValue.replace(/[^\d]/g, '').replace(/^0+/, ''), precision = options.precision, scale = options.scale, decimalSeparator = options.decimalSeparator, integerPart = digits.length > scale ? digits.slice(0, digits.length - scale) : '0', fractionalPart = '', formatedValue = ''; if (digits.length > precision) { return oldValue; } if (newValue === '') { return ''; } formatedValue = integerPart; if (scale > 0) { var fractionalPart = digits.length > scale ? digits.slice(digits.length - scale) : digits, leadingZeros = new Array((scale + 1) - fractionalPart.length).join(0); formatedValue += decimalSeparator + leadingZeros + fractionalPart; } return formatedValue; }; $element.on('paste', function (e) { e.preventDefault(); // TODO: Do something better than this }); $element.keypress(function (e) { if (e.isNumber) { var caret = $element.caret(), oldValue = $element.val(), newValue = oldValue.insert(e.char, caret.selectionStart, caret.selectionEnd), formatedValue = mask(newValue, oldValue); caret.selectionStart += (1 + (formatedValue.length - newValue.length)); caret.selectionEnd = caret.selectionStart; $element.val(formatedValue); $element.triggerHandler('input'); $element.caret(caret); } if (e.isEnter) return; e.preventDefault(); }); $element.keydown(function (e) { if (e.isBackspace || e.isDelete) { var caret = $element.caret(), oldValue = $element.val(), newValue = oldValue.remove(caret.selectionStart, caret.selectionEnd, e.isDelete), formatedValue = mask(newValue, oldValue); if (e.isBackspace) { if (caret.selectionStart > 0 && caret.selectionStart === caret.selectionEnd && formatedValue.charAt(0) !== '0') { caret.selectionStart--; } } if (e.isDelete) { var nextCharIsZero = formatedValue.charAt(caret.selectionStart) === '0', nextCharIsDecimalSeparator = formatedValue.charAt(caret.selectionStart) === options.decimalSeparator; if (nextCharIsZero || nextCharIsDecimalSeparator) { caret.selectionStart++ } } if (oldValue === '' || oldValue === mask('0')) { formatedValue = ''; } caret.selectionEnd = caret.selectionStart; $element.val(formatedValue); $element.triggerHandler('input'); $element.caret(caret); e.preventDefault(); } }); return $element; }; })(angular.element);
import chai from 'chai'; import chaiHttp from 'chai-http'; import app from '../src/index'; chai.use(chaiHttp); var server = chai.request(app); const { expect } = chai; /* server.get('/login/') .send({ account : 'timas', pwd : '123456' }); */ describe('demo test', () => { it('should get array', (done) => { done(); }) });
var express = require('express'); var app = express(); app.set('port', (process.env.PORT || 8200)); app.use(express.static(__dirname + '/app')); app.listen(app.get('port'), function () { console.log('binary tree app is running on port', app.get('port')); });
// jshint ignore: start (function() { var browser = false; var is_iOS = /iP(hone|od|ad)/.test(navigator.platform) && /Apple Computer/.test(navigator.vendor); var isIE10 = (Function('/*@cc_on return document.documentMode===10@*/')()); var isIE11 = (!(window.ActiveXObject) && "ActiveXObject" in window); var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor); var isFirefox = /Mozilla/.test(navigator.userAgent) && navigator.vendor === ''; browser = (browser === false && ( is_iOS )) ? 'ios' : false; browser = (browser === false && ( isIE10 )) ? 'ie10' : browser; browser = (browser === false && ( isIE11 )) ? 'ie11' : browser; browser = (browser === false && ( isChrome )) ? 'chrome' : browser; browser = (browser === false && ( isSafari )) ? 'safari' : browser; browser = (browser === false && ( isFirefox )) ? 'firefox' : browser; var addBrowserClass = function(browser) { $("html").addClass(browser); }; var iOS_Browser = function(browser) { var ver; (function() { var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/); ver = [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)]; })(); browser = "ios" + ver[0]; if (browser === 'ios7') { window.addEventListener("resize", function() { $('.entry').hide().fadeIn(1); }, false); // iOS 8 Simulator returns '10' } else if (browser === 'ios10') { browser = 'ios8'; } addBrowserClass(browser); }; var browserActions = { 'ie10': addBrowserClass, 'ie11': addBrowserClass, 'chrome': addBrowserClass, 'safari': addBrowserClass, 'firefox': addBrowserClass, 'ios': iOS_Browser, }; function processBrowser(browser) { if (typeof browserActions[browser] !== 'function') { return; } //console.log('browser processed!'); //console.log('browser: ' + browser); return browserActions[browser](browser); }; processBrowser(browser); }()); // jshint ignore: end