code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/* eslint-disable */ // not run locally - here for reference function pageFunction(context) { // called on every page the crawler visits, use it to extract data from it var $ = context.jQuery; var result = { constituency: $('#commons-constituency').text(), fullName: $('#commons-biography-header h1').text(), party: $('#commons-party').text(), email: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addParliamentaryAddress_rptAddresses_ctl00_hypEmailAddress').text(), parlTel: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addParliamentaryAddress_rptAddresses_ctl00_pnlTelephone').text(), conAddress: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addConstituencyAddress_rptAddresses_ctl00_pnlAddress').text(), conTel: $('#ctl00_ctl00_FormContent_SiteSpecificPlaceholder_PageContent_addConstituencyAddress_rptAddresses_ctl00_pnlTelephone').text().slice(5) }; $('.social-media li').each(function() { const type = $(this).find('span').text().slice(0,-1).toLowerCase(); console.log(type); const link = $(this).find('a').attr('href'); console.log(link); result[type] = link; }); return result; }
peedeerich/revolution2
seed/scrapers/scrapeMps.js
JavaScript
apache-2.0
1,235
Ext.data.JsonP.controller_open_remoteCtrl({"tagname":"class","name":"controller.open_remoteCtrl","autodetected":{},"files":[{"filename":"open_remoteCtrl.js","href":"open_remoteCtrl.html#controller-open_remoteCtrl"}],"author":[{"tagname":"author","name":"GadflyBSD","email":null}],"members":[],"alternateClassNames":[],"aliases":{},"id":"class-controller.open_remoteCtrl","component":false,"superclasses":[],"subclasses":[],"mixedInto":[],"mixins":[],"parentMixins":[],"requires":[],"uses":[],"html":"<div><pre class=\"hierarchy\"><h4>Files</h4><div class='dependency'><a href='source/open_remoteCtrl.html#controller-open_remoteCtrl' target='_blank'>open_remoteCtrl.js</a></div></pre><div class='doc-contents'><h1>AngularJS Controller App远程开门控制器</h1>\n</div><div class='members'></div></div>","meta":{}});
GadflyBSD/thinkAPP
docs/app_www/output/controller.open_remoteCtrl.js
JavaScript
apache-2.0
818
import difference from 'lodash/difference'; export const ActionTypes = { PERFORM_ACTION: 'PERFORM_ACTION', RESET: 'RESET', ROLLBACK: 'ROLLBACK', COMMIT: 'COMMIT', SWEEP: 'SWEEP', TOGGLE_ACTION: 'TOGGLE_ACTION', JUMP_TO_STATE: 'JUMP_TO_STATE', IMPORT_STATE: 'IMPORT_STATE' }; /** * Action creators to change the History state. */ export const ActionCreators = { performAction(action) { if (typeof action.type === 'undefined') { throw new Error( 'Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?' ); } return { type: ActionTypes.PERFORM_ACTION, action, timestamp: Date.now() }; }, reset() { return { type: ActionTypes.RESET, timestamp: Date.now() }; }, rollback() { return { type: ActionTypes.ROLLBACK, timestamp: Date.now() }; }, commit() { return { type: ActionTypes.COMMIT, timestamp: Date.now() }; }, sweep() { return { type: ActionTypes.SWEEP }; }, toggleAction(id) { return { type: ActionTypes.TOGGLE_ACTION, id }; }, jumpToState(index) { return { type: ActionTypes.JUMP_TO_STATE, index }; }, importState(nextLiftedState) { return { type: ActionTypes.IMPORT_STATE, nextLiftedState }; } }; const INIT_ACTION = { type: '@@INIT' }; /** * Computes the next entry in the log by applying an action. */ function computeNextEntry(reducer, action, state, error) { if (error) { return { state, error: 'Interrupted by an error up the chain' }; } let nextState = state; let nextError; try { nextState = reducer(state, action); } catch (err) { nextError = err.toString(); if (typeof window === 'object' && typeof window.chrome !== 'undefined') { // In Chrome, rethrowing provides better source map support setTimeout(() => { throw err; }); } else { console.error(err); } } return { state: nextState, error: nextError }; } /** * Runs the reducer on invalidated actions to get a fresh computation log. */ function recomputeStates( computedStates, minInvalidatedStateIndex, reducer, committedState, actionsById, stagedActionIds, skippedActionIds ) { // Optimization: exit early and return the same reference // if we know nothing could have changed. if ( minInvalidatedStateIndex >= computedStates.length && computedStates.length === stagedActionIds.length ) { return computedStates; } const nextComputedStates = computedStates.slice(0, minInvalidatedStateIndex); for (let i = minInvalidatedStateIndex; i < stagedActionIds.length; i++) { const actionId = stagedActionIds[i]; const action = actionsById[actionId].action; const previousEntry = nextComputedStates[i - 1]; const previousState = previousEntry ? previousEntry.state : committedState; const previousError = previousEntry ? previousEntry.error : undefined; const shouldSkip = skippedActionIds.indexOf(actionId) > -1; const entry = shouldSkip ? previousEntry : computeNextEntry(reducer, action, previousState, previousError); nextComputedStates.push(entry); } return nextComputedStates; } /** * Lifts an app's action into an action on the lifted store. */ function liftAction(action) { return ActionCreators.performAction(action); } /** * Creates a history state reducer from an app's reducer. */ function liftReducerWith(reducer, initialCommittedState, monitorReducer) { const initialLiftedState = { monitorState: monitorReducer(undefined, {}), nextActionId: 1, actionsById: { 0: liftAction(INIT_ACTION) }, stagedActionIds: [0], skippedActionIds: [], committedState: initialCommittedState, currentStateIndex: 0, computedStates: [] }; /** * Manages how the history actions modify the history state. */ return (liftedState = initialLiftedState, liftedAction) => { let { monitorState, actionsById, nextActionId, stagedActionIds, skippedActionIds, committedState, currentStateIndex, computedStates } = liftedState; // By default, agressively recompute every state whatever happens. // This has O(n) performance, so we'll override this to a sensible // value whenever we feel like we don't have to recompute the states. let minInvalidatedStateIndex = 0; switch (liftedAction.type) { case ActionTypes.RESET: { // Get back to the state the store was created with. actionsById = { 0: liftAction(INIT_ACTION) }; nextActionId = 1; stagedActionIds = [0]; skippedActionIds = []; committedState = initialCommittedState; currentStateIndex = 0; computedStates = []; break; } case ActionTypes.COMMIT: { // Consider the last committed state the new starting point. // Squash any staged actions into a single committed state. actionsById = { 0: liftAction(INIT_ACTION) }; nextActionId = 1; stagedActionIds = [0]; skippedActionIds = []; committedState = computedStates[currentStateIndex].state; currentStateIndex = 0; computedStates = []; break; } case ActionTypes.ROLLBACK: { // Forget about any staged actions. // Start again from the last committed state. actionsById = { 0: liftAction(INIT_ACTION) }; nextActionId = 1; stagedActionIds = [0]; skippedActionIds = []; currentStateIndex = 0; computedStates = []; break; } case ActionTypes.TOGGLE_ACTION: { // Toggle whether an action with given ID is skipped. // Being skipped means it is a no-op during the computation. const { id: actionId } = liftedAction; const index = skippedActionIds.indexOf(actionId); if (index === -1) { skippedActionIds = [actionId, ...skippedActionIds]; } else { skippedActionIds = skippedActionIds.filter(id => id !== actionId); } // Optimization: we know history before this action hasn't changed minInvalidatedStateIndex = stagedActionIds.indexOf(actionId); break; } case ActionTypes.JUMP_TO_STATE: { // Without recomputing anything, move the pointer that tell us // which state is considered the current one. Useful for sliders. currentStateIndex = liftedAction.index; // Optimization: we know the history has not changed. minInvalidatedStateIndex = Infinity; break; } case ActionTypes.SWEEP: { // Forget any actions that are currently being skipped. stagedActionIds = difference(stagedActionIds, skippedActionIds); skippedActionIds = []; currentStateIndex = Math.min(currentStateIndex, stagedActionIds.length - 1); break; } case ActionTypes.PERFORM_ACTION: { if (currentStateIndex === stagedActionIds.length - 1) { currentStateIndex++; } const actionId = nextActionId++; // Mutation! This is the hottest path, and we optimize on purpose. // It is safe because we set a new key in a cache dictionary. actionsById[actionId] = liftedAction; stagedActionIds = [...stagedActionIds, actionId]; // Optimization: we know that only the new action needs computing. minInvalidatedStateIndex = stagedActionIds.length - 1; break; } case ActionTypes.IMPORT_STATE: { // Completely replace everything. ({ monitorState, actionsById, nextActionId, stagedActionIds, skippedActionIds, committedState, currentStateIndex, computedStates } = liftedAction.nextLiftedState); break; } case '@@redux/INIT': { // Always recompute states on hot reload and init. minInvalidatedStateIndex = 0; break; } default: { // If the action is not recognized, it's a monitor action. // Optimization: a monitor action can't change history. minInvalidatedStateIndex = Infinity; break; } } computedStates = recomputeStates( computedStates, minInvalidatedStateIndex, reducer, committedState, actionsById, stagedActionIds, skippedActionIds ); monitorState = monitorReducer(monitorState, liftedAction); return { monitorState, actionsById, nextActionId, stagedActionIds, skippedActionIds, committedState, currentStateIndex, computedStates }; }; } /** * Provides an app's view into the state of the lifted store. */ function unliftState(liftedState) { const { computedStates, currentStateIndex } = liftedState; const { state } = computedStates[currentStateIndex]; return state; } /** * Provides an app's view into the lifted store. */ function unliftStore(liftedStore, liftReducer) { let lastDefinedState; return { ...liftedStore, liftedStore, dispatch(action) { liftedStore.dispatch(liftAction(action)); return action; }, getState() { const state = unliftState(liftedStore.getState()); if (state !== undefined) { lastDefinedState = state; } return lastDefinedState; }, replaceReducer(nextReducer) { liftedStore.replaceReducer(liftReducer(nextReducer)); } }; } /** * Redux instrumentation store enhancer. */ export default function instrument(monitorReducer = () => null) { return createStore => (reducer, initialState, enhancer) => { function liftReducer(r) { if (typeof r !== 'function') { if (r && typeof r.default === 'function') { throw new Error( 'Expected the reducer to be a function. ' + 'Instead got an object with a "default" field. ' + 'Did you pass a module instead of the default export? ' + 'Try passing require(...).default instead.' ); } throw new Error('Expected the reducer to be a function.'); } return liftReducerWith(r, initialState, monitorReducer); } const liftedStore = createStore(liftReducer(reducer), enhancer); if (liftedStore.liftedStore) { throw new Error( 'DevTools instrumentation should not be applied more than once. ' + 'Check your store configuration.' ); } return unliftStore(liftedStore, liftReducer); }; }
Maxwelloff/react-football
node_modules/redux-devtools/src/instrument.js
JavaScript
apache-2.0
10,577
// Sanity test for removing documents with adjacent index keys. SERVER-2008 t = db.jstests_removec; t.drop(); t.ensureIndex({a: 1}); /** @return an array containing a sequence of numbers from i to i + 10. */ function runStartingWith(i) { ret = []; for (j = 0; j < 11; ++j) { ret.push(i + j); } return ret; } // Insert some documents with adjacent index keys. for (i = 0; i < 1100; i += 11) { t.save({a: runStartingWith(i)}); } // Remove and then reinsert random documents in the background. s = startParallelShell('t = db.jstests_removec;' + 'Random.setRandomSeed();' + 'for( j = 0; j < 1000; ++j ) {' + ' o = t.findOne( { a:Random.randInt( 1100 ) } );' + ' t.remove( { _id:o._id } );' + ' t.insert( o );' + '}'); // Find operations are error free. Note that the cursor throws if it detects the $err // field in the returned document. for (i = 0; i < 200; ++i) { t.find({a: {$gte: 0}}).hint({a: 1}).itcount(); } s(); t.drop();
christkv/mongo-shell
test/jstests/core/removec.js
JavaScript
apache-2.0
1,114
"use strict"; var cases = module.exports = []; cases[0] = {}; cases[0].resources = [{ "resource": { "id": "Condition/c-0-0", "resourceType": "Condition", "status": "confirmed", "onsetDateTime": "2012-08-05", "dateAsserted": "2012-08-05", "abatementBoolean": true, "code": { "coding": [{ "code": "233604007", "system": "http://snomed.info/sct", "display": "Pneumonia" }] } } }]; cases[0].input = cases[0].resources[0]; cases[0].result = { "problem": { "code": { "name": "Pneumonia", "code": "233604007", "code_system_name": "SNOMED CT" }, "date_time": { "low": { "date": "2012-08-05T00:00:00.000Z", "precision": "day" } } }, "status": { "name": "Resolved" } }; cases[1] = {}; cases[1].resources = [{ "resource": { "id": "Condition/c-1-0", "resourceType": "Condition", "status": "confirmed", "onsetDateTime": "2007-01-03", "dateAsserted": "2007-01-03", "code": { "coding": [{ "code": "195967001", "system": "http://snomed.info/sct", "display": "Asthma" }] } } }]; cases[1].input = cases[1].resources[0]; cases[1].result = { "problem": { "code": { "name": "Asthma", "code": "195967001", "code_system_name": "SNOMED CT" }, "date_time": { "low": { "date": "2007-01-03T00:00:00.000Z", "precision": "day" } } } }; cases[2] = {}; cases[2].resources = [{ "resource": { "id": "Condition/c-2-0", "resourceType": "Condition", "status": "confirmed", "onsetDateTime": "2007-01-03", "dateAsserted": "2007-01-03", "abatementDate": "2012-09-05", "code": { "coding": [{ "code": "195967001", "system": "http://snomed.info/sct", "display": "Asthma" }] } } }]; cases[2].input = cases[2].resources[0]; cases[2].result = { "problem": { "code": { "name": "Asthma", "code": "195967001", "code_system_name": "SNOMED CT" }, "date_time": { "low": { "date": "2007-01-03T00:00:00.000Z", "precision": "day" }, "high": { "date": "2012-09-05T00:00:00.000Z", "precision": "day" } } } };
amida-tech/blue-button-fhir
test/fixtures/unit/condition.js
JavaScript
apache-2.0
2,758
app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) { $scope.stats = {}; $scope.getUrlLanguages = function(gitUrlId){ globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){ $scope.stats[gitUrlId] = response.data.languages; }); } $scope.addForReview = function () { $scope.showWarning = false; $scope.showGithubWarning = false; if (!$scope.newName || !$scope.newUrl) { $scope.showWarning = true; return; } var _new_name = $scope.newName.trim(); var _new = $scope.newUrl.trim(); if (!_new || !_new_name) { $scope.showWarning = true; return; } if (!_new || !_new_name) { $scope.showWarning = true; return; } var _newUrl = globalHelpers.getLocation(_new); var pathArray = _newUrl.pathname.split('/'); isCommit = pathArray.indexOf('commit') > -1; isPR = pathArray.indexOf('pull') > -1; if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){ $scope.showGithubWarning = true; return; } var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}'); for (var i=0; i < $scope.existing.length; i++){ if (Object.keys($scope.existing[i])[0] == _new){ return; } } $scope.existing.push(obj); $http({ method: "post", url: "/add_for_review", headers: {'Content-Type': "application/json"}, data: obj }).success(function () { // console.log("success!"); }); $scope.showUWarning = false; $scope.showGithubWarning = false; $scope._new = ''; $rootScope.$broadcast('urlEntryChange', 'args'); }; $scope.removeUrl = function (url) { if(confirm("Are you sure you want to delete entry \"" + url["name"] + "\"?")){ for (var i=0; i < $scope.existing.length; i++){ if ($scope.existing[i]["url"] == url['url']){ $scope.existing.splice(i, 1) $http({ method: "post", url: "/remove_from_list", headers: {'Content-Type': "application/json"}, data: url }).success(function () { console.log("success!"); }); $rootScope.$broadcast('urlEntryChange', 'args'); } } } }; }]);
trobert2/gitRoulette
static/controllers/submissions.js
JavaScript
apache-2.0
2,774
function loadText() { var txtLang = document.getElementsByName("txtLang"); txtLang[0].innerHTML = "St\u00F8rrelse"; txtLang[1].innerHTML = "Egenskaber"; txtLang[2].innerHTML = "Typografi"; txtLang[3].innerHTML = "Bredde"; txtLang[4].innerHTML = "Bredde styret af indhold"; txtLang[5].innerHTML = "Tabelbredde"; txtLang[6].innerHTML = "Tilpas til vindue"; txtLang[7].innerHTML = "H\u00F8jde"; txtLang[8].innerHTML = "Bredde styret af indhold"; txtLang[9].innerHTML = "Tabelbredde"; txtLang[10].innerHTML = "Tilpas til vindue"; txtLang[11].innerHTML = "Justering"; txtLang[12].innerHTML = "Margen"; txtLang[13].innerHTML = "Venstre"; txtLang[14].innerHTML = "H\u00F8jre"; txtLang[15].innerHTML = "Top"; txtLang[16].innerHTML = "Nederst"; txtLang[17].innerHTML = "Ramme"; txtLang[18].innerHTML = "Collapse"; txtLang[19].innerHTML = "Baggrund"; txtLang[20].innerHTML = "Celle afstand"; txtLang[21].innerHTML = "Celle margen"; txtLang[22].innerHTML = "Typografi"; var optLang = document.getElementsByName("optLang"); optLang[0].text = "pixels" optLang[1].text = "procent" optLang[2].text = "pixels" optLang[3].text = "procent" optLang[4].text = "Venstre" optLang[5].text = "Centrer" optLang[6].text = "H\u00F8jre" optLang[7].text = "Ingen" optLang[8].text = "Ja" optLang[9].text = "Nej" document.getElementById("btnPick").value="V\u00E6lg"; document.getElementById("btnImage").value="Billede"; document.getElementById("btnCancel").value = "Annuller"; document.getElementById("btnApply").value = "Opdater"; document.getElementById("btnOk").value = " Ok "; } function getText(s) { switch(s) { case "Custom Colors": return "Egne farver"; case "More Colors...": return "Flere farver..."; default:return ""; } } function writeTitle() { document.write("<title>Tabel egenskaber</title>") }
studiodev/archives
2009 - Team D4 (IxGamer)/include/Editor/scripts/language/danish/table_edit.js
JavaScript
apache-2.0
2,072
db = connect(mserver); db = db.getSiblingDB('kynetx'); db.schedev.ensureIndex({cron_id : 1}); db.schedev.ensureIndex({ken : 1}); db.schedev.ensureIndex({expired : 1},{expireAfterSeconds : 120});
kre/kre_standalone
kre01/dist/files/mongo08.js
JavaScript
apache-2.0
195
class TabList { constructor (tabs, parentTaskList) { this.tabs = tabs || [] this.parentTaskList = parentTaskList } //tab properties that shouldn't be saved to disk static temporaryProperties = ['hasAudio', 'previewImage', 'loaded'] add (tab = {}, options = {}) { var tabId = String(tab.id || Math.round(Math.random() * 100000000000000000)) // you can pass an id that will be used, or a random one will be generated. var newTab = { url: tab.url || '', title: tab.title || '', id: tabId, lastActivity: tab.lastActivity || Date.now(), secure: tab.secure, private: tab.private || false, readerable: tab.readerable || false, themeColor: tab.themeColor, backgroundColor: tab.backgroundColor, scrollPosition: tab.scrollPosition || 0, selected: tab.selected || false, muted: tab.muted || false, loaded: tab.loaded || false, hasAudio: false, previewImage: '', isFileView: false, } if (options.atEnd) { this.tabs.push(newTab) } else { this.tabs.splice(this.getSelectedIndex() + 1, 0, newTab) } this.parentTaskList.emit('tab-added', tabId) return tabId } update (id, data) { if (!this.has(id)) { throw new ReferenceError('Attempted to update a tab that does not exist.') } const index = this.getIndex(id) for (var key in data) { if (data[key] === undefined) { throw new ReferenceError('Key ' + key + ' is undefined.') } this.tabs[index][key] = data[key] this.parentTaskList.emit('tab-updated', id, key) // changing URL erases scroll position if (key === 'url') { this.tabs[index].scrollPosition = 0 this.parentTaskList.emit('tab-updated', id, 'scrollPosition') } } } destroy (id) { const index = this.getIndex(id) if (index < 0) return false tasks.getTaskContainingTab(id).tabHistory.push(this.toPermanentState(this.tabs[index])) this.tabs.splice(index, 1) this.parentTaskList.emit('tab-destroyed', id) return index } destroyAll () { // this = [] doesn't work, so set the length of the array to 0 to remove all of the itemss this.tabs.length = 0 } get (id) { if (!id) { // no id provided, return an array of all tabs // it is important to copy the tab objects when returning them. Otherwise, the original tab objects get modified when the returned tabs are modified (such as when processing a url). var tabsToReturn = [] for (var i = 0; i < this.tabs.length; i++) { tabsToReturn.push(Object.assign({}, this.tabs[i])) } return tabsToReturn } for (var i = 0; i < this.tabs.length; i++) { if (this.tabs[i].id === id) { return Object.assign({}, this.tabs[i]) } } return undefined } has (id) { return this.getIndex(id) > -1 } getIndex (id) { for (var i = 0; i < this.tabs.length; i++) { if (this.tabs[i].id === id) { return i } } return -1 } getSelected () { for (var i = 0; i < this.tabs.length; i++) { if (this.tabs[i].selected) { return this.tabs[i].id } } return null } getSelectedIndex () { for (var i = 0; i < this.tabs.length; i++) { if (this.tabs[i].selected) { return i } } return null } getAtIndex (index) { return this.tabs[index] || undefined } setSelected (id) { if (!this.has(id)) { throw new ReferenceError('Attempted to select a tab that does not exist.') } for (var i = 0; i < this.tabs.length; i++) { if (this.tabs[i].id === id) { this.tabs[i].selected = true this.tabs[i].lastActivity = Date.now() } else if (this.tabs[i].selected) { this.tabs[i].selected = false this.tabs[i].lastActivity = Date.now() } } this.parentTaskList.emit('tab-selected', id) } moveBy (id, offset) { var currentIndex = this.getIndex(id) var newIndex = currentIndex + offset var newIndexTab = this.getAtIndex(newIndex) if (newIndexTab) { var currentTab = this.getAtIndex(currentIndex) this.splice(currentIndex, 1, newIndexTab) this.splice(newIndex, 1, currentTab) } } count () { return this.tabs.length } isEmpty () { if (!this.tabs || this.tabs.length === 0) { return true } if (this.tabs.length === 1 && !this.tabs[0].url) { return true } return false } forEach (fun) { return this.tabs.forEach(fun) } splice (...args) { return this.tabs.splice.apply(this.tabs, args) } toPermanentState (tab) { //removes temporary properties of the tab that are lost on page reload let result = {} Object.keys(tab) .filter(key => !TabList.temporaryProperties.includes(key)) .forEach(key => result[key] = tab[key]) return result } getStringifyableState () { return this.tabs.map(tab => this.toPermanentState(tab)) } } module.exports = TabList
minbrowser/min
js/tabState/tab.js
JavaScript
apache-2.0
5,074
/* * ! JSRT JavaScript Library 0.1.1 lico.atom@gmail.com * * Copyright 2008, 2014 Atom Union, Inc. Released under the MIT license * * Date: Feb 11, 2014 */ Class.forName({ name: "class js.util.Iterator extends Object", "private _element": null, "private _cursor": 0, "private _lastRet": -1, Iterator: function(element) { this._element = element || []; }, hasNext: function() { return this._cursor < this._element.size(); }, next: function() { try { var next = this._element.get(this._cursor); this._lastRet = this._cursor++; return next; } catch (e) { throw new js.lang.IndexOutOfBoundsException("Index: " + this._cursor + ", Size: " + this._element.size() + ",Message:" + e.getMessage()); } }, remove: function() { if (this._lastRet === -1) throw new js.lang.IllegalStateException(); try { this._element.removeAt(this._lastRet); if (this._lastRet < this._cursor) this._cursor--; this._lastRet = -1; } catch (e) { throw new js.lang.IndexOutOfBoundsException(); } } });
ctripcorp/tars
tars/surface/static/jre/src/main/js/js/util/Iterator.js
JavaScript
apache-2.0
1,103
import React from 'react'; import { within, userEvent } from '@storybook/testing-library'; import { action } from '@storybook/addon-actions'; import { Badge } from '@talend/react-components'; import { useTranslation } from 'react-i18next'; import set from 'lodash/set'; import cloneDeep from 'lodash/cloneDeep'; import times from 'lodash/times'; import FacetedSearch from '../src'; import { FacetedSearchIcon } from '../src/components'; import { BadgeFacetedProvider } from '../src/components/context/badgeFaceted.context'; import { BadgesGenerator } from '../src/components/BadgesGenerator'; import { createBadgesDict, getBadgesFromDict } from '../src/dictionary/badge.dictionary'; import { badgeConnectionType, badgeName, badgeConnectionName, badgeAuthor, badgeAll, badgePrice, badgeValid, badgeEmpty, badgeInvalid, badgeTags, badgeCreationDate, badgeWithVeryLongName, badgeEnumWithLotOfValues, badgeTextAsCategory, badgeTextAsCustomAttribute, badgeEnumsAsCustomAttribute, badgePriceAsCustomAttribute, badgeEmptyLabel, } from './badgesDefinitions'; const badgesDefinitions = [ badgeAll, badgeName, badgeConnectionName, badgeAuthor, badgeConnectionType, badgeTags, badgePrice, badgeValid, badgeEmpty, badgeInvalid, badgeCreationDate, ]; const callbacks = { getTags: () => new Promise(resolve => setTimeout(resolve, 2000, [ 'clean', 'production', 'last chunk', 'salesforce', 'outdated', 'extracted', 'security', 'in processing', 'deep learning', 'sql', 'cluster', 'visualization', 'analytics', 'users', 'warehouse', 'api', ]), ), }; const badgesFaceted = { badges: [ { properties: { attribute: 'connection.type', initialOperatorOpened: false, initialValueOpened: false, label: 'Connection Type', operator: { label: 'In', name: 'in', }, operators: [ { label: 'In', name: 'in', }, ], type: 'checkbox', value: [ { id: 'amazon_s3', label: 'Amazon S3', checked: true, }, ], }, metadata: { badgePerFacet: '1', entitiesPerBadge: 'N', values: [ { id: 'amazon_s3', label: 'Amazon S3' }, { id: 'hdfs', label: 'HDFS' }, { id: 'kafka', label: 'Kafka' }, { id: 'localcon', label: 'Local connection' }, { id: 'salesforce', label: 'Salesforce' }, { id: 'aws_kinesis', label: 'AWS kinesis' }, ], operators: ['in'], badgeId: 'connection.type-9f0e5bc7-c687-4198-9635-d0fc7724dfd1', isInCreation: false, }, }, ], }; const badgesWithAll = { badges: [ { properties: { attribute: 'all', initialOperatorOpened: false, initialValueOpened: false, label: 'All', operator: { label: 'Contains', name: 'containsIgnoreCase', iconName: 'contains' }, operators: [], type: 'text', value: 'test', }, metadata: { isAvailableForFacetList: false, badgePerFacet: 'N', entitiesPerBadge: '1', operators: ['containsIgnoreCase'], badgeId: 'all-b6c04e3d-1d72-4aca-9565-09d206f76d88', isInCreation: false, }, }, ], }; export default { title: 'Faceted search', component: FacetedSearch.Faceted, parameters: { docs: { description: { component: 'Faceted search is a technique that involves augmenting traditional search techniques with a faceted navigation system, allowing users to narrow down search results by applying multiple filters based on faceted classification of the items. The user can look for any value, even if the field is not currently visible.', }, }, }, decorators: [ (Story, context) => ( <div> <style> {` #talend-pie-charts path[class^='ti-slice-'] { fill: #C6C6C6; } #talend-pie-charts path.ti-slice-right { fill: currentColor; } .tc-badge-slider-form .invalid { color: #EA8330; } .tc-badge-slider-form .valid { color: #82BD41; } .tc-badge-slider-form .empty { color: #202020; } `} </style> <Story {...context} /> </div> ), ], }; export const Default = () => ( <FacetedSearch.Faceted id="my-faceted-search"> {currentFacetedMode => (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.ADVANCED && ( <FacetedSearch.AdvancedSearch onSubmit={action('onSubmit')} /> )) || (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.BASIC && ( <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} callbacks={callbacks} onSubmit={action('onSubmit')} /> )) } </FacetedSearch.Faceted> ); export const IconDefaultActiveAndLoading = () => ( <div style={{ display: 'flex', gap: '1rem' }}> <div> <FacetedSearchIcon loading onClick={action('onClick')} /> </div> <div> <FacetedSearchIcon active onClick={action('onClick')} /> </div> <div> <FacetedSearchIcon onClick={action('onClick')} /> </div> </div> ); export const Initialized = () => ( <FacetedSearch.Faceted id="my-faceted-search"> {currentFacetedMode => (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.ADVANCED && ( <FacetedSearch.AdvancedSearch onSubmit={action('onSubmit')} /> )) || (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.BASIC && ( <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} badgesFaceted={badgesFaceted} onSubmit={action('onSubmit')} callbacks={callbacks} /> )) } </FacetedSearch.Faceted> ); export const InitializedWithABadgeWhichIsNotVisibleInTheList = () => ( <FacetedSearch.Faceted id="my-faceted-search"> {currentFacetedMode => (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.ADVANCED && ( <FacetedSearch.AdvancedSearch onSubmit={action('onSubmit')} /> )) || (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.BASIC && ( <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} badgesFaceted={badgesWithAll} callbacks={callbacks} onSubmit={action('onSubmit')} /> )) } </FacetedSearch.Faceted> ); export const Colored = () => ( <FacetedSearch.Faceted id="my-faceted-search"> {currentFacetedMode => (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.ADVANCED && ( <FacetedSearch.AdvancedSearch onSubmit={action('onSubmit')} /> )) || (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.BASIC && ( <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} badgesFaceted={set( cloneDeep(badgesFaceted), 'badges[0].properties.displayType', Badge.TYPES.VALUE, )} onSubmit={action('onSubmit')} callbacks={callbacks} /> )) } </FacetedSearch.Faceted> ); export const WithSpecialChars = () => { const { t } = useTranslation(); const badgesDictionary = createBadgesDict(); const badge = cloneDeep(badgesFaceted.badges[0]); Object.assign(badge.properties, { value: ' text ', type: 'text', displayType: Badge.TYPES.PATTERN, }); return ( <BadgeFacetedProvider value={{}}> <BadgesGenerator badges={[badge]} badgesDictionary={badgesDictionary} getBadgeFromDict={getBadgesFromDict} t={t} /> </BadgeFacetedProvider> ); }; export const DatePicker = () => { const { t } = useTranslation(); const badgesDictionary = createBadgesDict(); const badge = cloneDeep(badgesFaceted.badges[0]); Object.assign(badge.properties, { value: Date.now(), type: 'date', }); return ( <BadgeFacetedProvider value={{}}> <BadgesGenerator badges={[badge]} badgesDictionary={badgesDictionary} getBadgeFromDict={getBadgesFromDict} t={t} /> </BadgeFacetedProvider> ); }; export const ReadOnly = () => { const { t } = useTranslation(); const badgesDictionary = createBadgesDict(); return ( <BadgeFacetedProvider value={{}}> <BadgesGenerator badges={[ set(cloneDeep(badgesFaceted.badges[0]), 'properties.readOnly', true), set(cloneDeep(badgesFaceted.badges[0]), 'properties.removable', false), ]} badgesDictionary={badgesDictionary} getBadgeFromDict={getBadgesFromDict} t={t} /> </BadgeFacetedProvider> ); }; export const WithExternalState = () => { const [state, setState] = React.useState(badgesFaceted); const onSubmit = React.useCallback( (_, badges) => setState(previousState => ({ ...previousState, badges })), [setState], ); return ( <div> <button onClick={() => setState(badgesFaceted)}>Reset state</button> <FacetedSearch.Faceted id="my-faceted-search"> {currentFacetedMode => (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.ADVANCED && ( <FacetedSearch.AdvancedSearch onSubmit={action('onSubmit')} /> )) || (currentFacetedMode === FacetedSearch.constants.FACETED_MODE.BASIC && ( <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} badgesFaceted={state} onSubmit={onSubmit} callbacks={callbacks} /> )) } </FacetedSearch.Faceted> </div> ); }; export const WithoutLabelOrOperatorButton = () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={badgesDefinitions} badgesFaceted={set(cloneDeep(badgesFaceted), 'badges[0].properties.label', '')} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> ); const lotsOfBadgesDefinitions = Array(50).fill(badgeName); export const BasicSearchWithLotOfBadgeDefinitions = { render: () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={lotsOfBadgesDefinitions} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> ), play: async ({ canvasElement }) => { await userEvent.type(within(canvasElement).getByRole('searchbox'), 'lorem ipsum'); }, }; export const BasicSearchWithBadgeWithVeryLongName = { render: () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={[badgeWithVeryLongName, badgeConnectionType, badgeName, badgePrice]} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> ), play: async ({ canvasElement }) => { await userEvent.type(within(canvasElement).getByRole('searchbox'), 'lorem ipsum'); }, }; export const BasicSearchInABadgeWithALotOfValues = () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={[badgeEnumWithLotOfValues]} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> ); export const BasicSearchWithBadgesCategories = () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={[ badgeConnectionType, badgeName, badgePrice, badgeTags, badgeTextAsCustomAttribute, badgePriceAsCustomAttribute, badgeEnumsAsCustomAttribute, ...times(2, () => badgeTextAsCategory), ]} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> ); export const BasicSearchWithAnEmptyLabelBadge = () => ( <FacetedSearch.Faceted id="my-faceted-search"> <FacetedSearch.BasicSearch badgesDefinitions={[badgeName, badgeEmptyLabel]} onSubmit={action('onSubmit')} callbacks={callbacks} /> </FacetedSearch.Faceted> );
Talend/ui
packages/faceted-search/stories/facetedSearch.stories.js
JavaScript
apache-2.0
11,370
/* * ../../../..//localization/cy/FontWarnings.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. */ /************************************************************* * * MathJax/localization/cy/FontWarnings.js * * Copyright (c) 2009-2018 The MathJax Consortium * * 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. * */ MathJax.Localization.addTranslation("cy", "FontWarnings", { version: "2.7.5", isLoaded: true, strings: {} }); MathJax.Ajax.loadComplete("[MathJax]/localization/cy/FontWarnings.js");
GerHobbelt/MathJax
localization/cy/FontWarnings.js
JavaScript
apache-2.0
1,604
/*! * ${copyright} */ // Provides control sap.ui.commons.Tree. sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control'], function(jQuery, library, Control) { "use strict"; /** * Constructor for a new Tree. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * * @class * Simple tree to display item in a hierarchical way * @extends sap.ui.core.Control * @version ${version} * * @constructor * @public * @deprecated Since version 1.38. * @alias sap.ui.commons.Tree * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var Tree = Control.extend("sap.ui.commons.Tree", /** @lends sap.ui.commons.Tree.prototype */ { metadata : { library : "sap.ui.commons", properties : { /** * Tree title */ title : {type : "string", group : "Misc", defaultValue : null}, /** * Tree width */ width : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : 'auto'}, /** * Tree height */ height : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : 'auto'}, /** * Tree Header is display. If false, the tree will be in a transparent mode */ showHeader : {type : "boolean", group : "Misc", defaultValue : true}, /** * Show Header icons (e.g. Expand/Collapse all). Only consider if showHeader is true */ showHeaderIcons : {type : "boolean", group : "Misc", defaultValue : true}, /** * Display horizontal scrollbar. If false, the overflow content will be hidden */ showHorizontalScrollbar : {type : "boolean", group : "Misc", defaultValue : false}, /** * Minimal width for the Tree. Can be useful when, for example, the width is specified in percentage, to avoid the tree to become too narrow when container is resize */ minWidth : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : null}, /** * Selection mode of the Tree. */ selectionMode : {type : "sap.ui.commons.TreeSelectionMode", group : "Behavior", defaultValue : sap.ui.commons.TreeSelectionMode.Legacy} }, defaultAggregation : "nodes", aggregations : { /** * First level nodes */ nodes : {type : "sap.ui.commons.TreeNode", multiple : true, singularName : "node", bindable : "bindable"} }, events : { /** * Event is fired when a tree node is selected. */ select : {allowPreventDefault : true, parameters : { /** * The node which has been selected. */ node : {type : "sap.ui.commons.TreeNode"}, /** * The binding context of the selected node. */ nodeContext : {type : "object"} } }, /** * fired when the selection of the tree has been changed */ selectionChange : { parameters : { /** * The nodes which has been selected. */ nodes : {type : "sap.ui.commons.TreeNode[]"}, /** * The binding context of the selected nodes. */ nodeContexts : {type : "object[]"} } } } }}); Tree.prototype.resizeListenerId; Tree.prototype.init = function(){ this.bAllCollapsed = false; this.allowTextSelection(false); this.iOldScrollTop = null; this.mSelectedNodes = {}; this.mSelectedContexts = {}; this.aLeadSelection = null; //Create Buttons for Header var oResourceBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.commons"); this.oCollapseAllButton = new sap.ui.commons.Button(this.getId() + "-CollapseAll", { icon: this.getIconPrefix() + "CollapseAll.png", tooltip: oResourceBundle.getText("TREE_COLLAPSE_ALL"), lite: true }); this.oExpandAllButton = new sap.ui.commons.Button(this.getId() + "-ExpandAll", { icon: this.getIconPrefix() + "ExpandAll.png", tooltip: oResourceBundle.getText("TREE_EXPAND_ALL"), lite: true }); this.oCollapseAllButton.attachPress(this.onCollapseAll,this); this.oExpandAllButton.attachPress(this.onExpandAll,this); this.oCollapseAllButton.addStyleClass("sapUiTreeCol"); this.oExpandAllButton.addStyleClass("sapUiTreeExp"); }; /** * Does all the cleanup when the Tree is to be destroyed. * Called from the element's destroy() method. * @private */ Tree.prototype.exit = function(){ if ( this.oCollapseAllButton ) { this.oCollapseAllButton.destroy(); this.oCollapseAllButton = null; } if ( this.oExpandAllButton ) { this.oExpandAllButton.destroy(); this.oExpandAllButton = null; } }; // Enumeration for different types of selection in the tree Tree.SelectionType = { Select: "Select", Toggle: "Toggle", Range: "Range" }; /*********************************************************************************** * EVENTS HANDLING ***********************************************************************************/ /** Handler for "Theme Changed" event. * @private */ Tree.prototype.onThemeChanged = function(){ if (this.oCollapseAllButton && this.oExpandAllButton) { this.oCollapseAllButton.setIcon(this.getIconPrefix() + "CollapseAll.png"); this.oExpandAllButton.setIcon(this.getIconPrefix() + "ExpandAll.png"); } }; /** Handler for "Expand All" button. * @private */ Tree.prototype.onExpandAll = function(){ this.expandAll(); }; /**Handler for "Collapse All" button. * @private */ Tree.prototype.onCollapseAll = function(){ this.collapseAll(); }; /*"********************************************************************************* * PUBLIC METHODS ***********************************************************************************/ /** * Expands all nodes in the tree * * @type void * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ Tree.prototype.expandAll = function(){ var aNodes = this._getNodes(); for (var i = 0;i < aNodes.length;i++) { aNodes[i].expand(true, true); this._adjustSelectionOnExpanding(aNodes[i]); } }; /** * Collapses all nodes in the tree * * @type void * @public * @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel */ Tree.prototype.collapseAll = function(){ var aNodes = this._getNodes(); for (var i = 0;i < aNodes.length;i++) { aNodes[i].collapse(true, true); this._adjustSelectionOnCollapsing(aNodes[i]); } this._adjustFocus(); }; /*********************************************************************************** * KEYBOARD NAVIGATION ***********************************************************************************/ /** * DOWN key behavior * Opens the section or activates the UI element on DOWN key * @private * @param oEvent Browser event */ Tree.prototype.onsapdown = function(oEvent){ this.moveFocus(false); oEvent.preventDefault(); }; /** * UP key behavior * Opens the section or activates the UI element on UP key * @private * @param oEvent Browser event */ Tree.prototype.onsapup = function(oEvent){ this.moveFocus(true); oEvent.preventDefault(); }; /** * The general HOME key event of the tree * @private * @param {jQuery.Event} oEvent The saphome event object */ Tree.prototype.onsaphome = function(oEvent) { this.placeFocus(this.getFirstSibling(oEvent.target)); oEvent.preventDefault(); }; /** * The general CTRL+HOME key event of the tree * @private * @param {jQuery.Event} oEvent The saphome event object */ Tree.prototype.onsaphomemodifiers = function(oEvent) { this.placeFocus(this.getFirst()); oEvent.preventDefault(); }; /** * The general END key event of the tree * @private * @param {jQuery.Event} oEvent The sapend event object */ Tree.prototype.onsapend = function(oEvent) { this.placeFocus(this.getLastSibling(oEvent.target)); oEvent.preventDefault(); }; /** * The general CTRL+END key event of the tree * @private * @param {jQuery.Event} oEvent The sapend event object */ Tree.prototype.onsapendmodifiers = function(oEvent) { this.placeFocus(this.getLast()); oEvent.preventDefault(); }; /** * The numpad STAR(*) key event of the tree * @private * @param {jQuery.Event} oEvent The sapcollapseall event object */ Tree.prototype.onsapcollapseall = function(oEvent) { if (this.bAllCollapsed ) { this.expandAll(); } else { this.collapseAll(); } this.bAllCollapsed = !this.bAllCollapsed; }; /*********************************************************************************** * HELPER METHODS - DOM NAVIGATION ***********************************************************************************/ /** * Determine the icon prefix for the embedded button icons * @private */ Tree.prototype.getIconPrefix = function() { var sIconPrefix = "themes/" + sap.ui.getCore().getConfiguration().getTheme() + "/"; if (!sap.ui.getCore().getConfiguration().getRTL()) { sIconPrefix += "img/tree/"; } else { sIconPrefix += "img-RTL/tree/"; } return sap.ui.resource("sap.ui.commons", sIconPrefix); }; /**Returns the first Sibling tree node based on DOM Tree node provided * @param oDomNode The DOM Tree node from which calculate the first sibling * @returns The first sibling tree node * @private */ Tree.prototype.getFirstSibling = function(oDomNode) { var aDomFirstSiblingNode = jQuery(oDomNode).siblings(".sapUiTreeNode:visible").first(); if (aDomFirstSiblingNode.length) { return aDomFirstSiblingNode[0]; } return null; }; /**Returns the last Sibling tree node based on DOM Tree node provided * @param oDomNode The DOM Tree node from which calculate the last sibling * @returns The last sibling tree node * @private */ Tree.prototype.getLastSibling = function(oDomNode) { var aDomLastSiblingNode = jQuery(oDomNode).siblings(".sapUiTreeNode:visible").last(); if (aDomLastSiblingNode.length) { return aDomLastSiblingNode[0]; } return null; }; /**Returns the first tree node of the tree. Children of collapsed nodes (hidden) are not considered. * @returns The first tree node * @private */ Tree.prototype.getFirst = function() { var aDomFirstNode = this.$().find(".sapUiTreeNode:visible").first(); if (aDomFirstNode.length) { return aDomFirstNode[0]; } return null; }; /**Returns the last tree node of the tree. Children of collapsed nodes (hidden) are not considered. * @returns The last tree node * @private */ Tree.prototype.getLast = function() { var aDomLastNode = this.$().find(".sapUiTreeNode:visible").last(); if (aDomLastNode.length) { return aDomLastNode[0]; } return null; }; /*********************************************************************************** * HELPER METHODS - FOCUS MANAGEMENT ***********************************************************************************/ /** * Move the focus by one position, either UP or DOWN depending of "bMoveUp" * @param bMoveUp When true the focus is move up. Otherwise, it's moved down * @private */ Tree.prototype.moveFocus = function(bMoveUp){ var afocusedNodeDom = jQuery(".sapUiTreeNode:focus"); if (afocusedNodeDom.length) { var oCurrNode = sap.ui.getCore().byId(afocusedNodeDom[0].id); var aDomAllNodes = this.$().find(".sapUiTreeNode:visible"); var currIndex = aDomAllNodes.index(afocusedNodeDom[0]); var nextIndex = currIndex; if (bMoveUp) { nextIndex--; } else { nextIndex++; } if (nextIndex >= 0 && nextIndex < aDomAllNodes.length) { var oDomNextNode = aDomAllNodes.eq( nextIndex ); var oNextNode = sap.ui.getCore().byId(oDomNextNode[0].id); oCurrNode.blur(); oNextNode.focus(); } } }; /**Adjusts the focus after a node is collapsed. This is necessary as the currently focused node can then be hidden, * leading the tree not being focusable anymore. * * When the focusable is being hid by the collapsing of its parent, the focus is then set on this parent. * * @private */ Tree.prototype._adjustFocus = function(){ var oFocusableNode = this.$().find('.sapUiTreeNode[tabIndex="0"]'); if (!oFocusableNode.is(':visible')) { var aDomAllNodes = this.$().find(".sapUiTreeNode"); var focusIndex = aDomAllNodes.index(oFocusableNode[0]); var aDomPrecedingNodes = aDomAllNodes.filter(":lt(" + focusIndex + ")"); var aDomVisiblePrecedingNodes = aDomPrecedingNodes.filter(":visible"); var oNewFocusNode = aDomVisiblePrecedingNodes[aDomVisiblePrecedingNodes.length - 1]; if (oNewFocusNode) { oNewFocusNode.setAttribute("tabindex", "0"); if ( jQuery(".sapUiTreeNode:focus").is(":not(:visible)")) { oNewFocusNode.focus(); } } } }; /**Places the focus on the node corresponding to given DOM Tree Node * @param oDomTargetNode The DOM Tree Node corresponding to the node to focus * @private */ Tree.prototype.placeFocus = function(oDomTargetNode){ if (!oDomTargetNode) { return; //No Target node provided! } var oDomfocusedNode = this.$().find(".sapUiTreeNode[tabIndex='0']"); if (oDomfocusedNode.length) { oDomfocusedNode[0].setAttribute("tabindex", "-1"); } oDomTargetNode.setAttribute("tabindex", "0"); var oTargetNode = sap.ui.getCore().byId(oDomTargetNode.id); oTargetNode.focus(); }; /*********************************************************************************** * HELPER METHODS - SELECTION MANAGEMENT ***********************************************************************************/ /** * Adjusts the selection, when expanding, by re-selecting a children node when the expanded node was * selected only to represented the selection of a children node. * @param {sap.ui.commons.TreeNode} oExpandingNode The Node being expanded * @private */ Tree.prototype._adjustSelectionOnExpanding = function(oExpandingNode) { if (!oExpandingNode) { return; } var aExpandingParents = []; if (oExpandingNode.getSelectedForNodes().length) { aExpandingParents.push(oExpandingNode); } restoreSelectedChildren(oExpandingNode, aExpandingParents, null); //update dom if necessary var $ExpandingNode = oExpandingNode.$(); if ($ExpandingNode && $ExpandingNode.hasClass('sapUiTreeNodeSelectedParent')) { $ExpandingNode.removeClass('sapUiTreeNodeSelectedParent'); } //remove the remaining selectedparent classes from all expanded subnodes var $SelectedChildrenForTheirChildren = oExpandingNode.$('children').find('.sapUiTreeNodeExpanded.sapUiTreeNodeSelectedParent'); $SelectedChildrenForTheirChildren.removeClass('sapUiTreeNodeSelectedParent'); }; /** * Removes the references inside the expanded node of its selected children, because * they are no longer needed. * @param {sap.ui.commons.TreeNode} oNode The current node to look at * @param {object} aExpandingParents Array of parents of the current node that have selectedForNodes references * @param {sap.ui.commons.TreeNode} oFirstCollapsedParent The topmost collapsed parent node of the current node */ function restoreSelectedChildren(oNode, aExpandingParents, oFirstCollapsedParent) { var bIsExpanded = oNode.getExpanded(), bNodeReferredInParents = false, bIncludeInExpandingParents = bIsExpanded && !!oNode.getSelectedForNodes().length, oFirstCollapsedParentNode = (oFirstCollapsedParent || bIsExpanded) ? oFirstCollapsedParent : oNode, i; //check if any of the expanded parents, that have references, refers the current node //if so - remove the reference for (i = 0; i < aExpandingParents.length; i++) { if (aExpandingParents[i].getSelectedForNodes().indexOf(oNode.getId()) !== -1) { bNodeReferredInParents = true; aExpandingParents[i].removeAssociation("selectedForNodes", oNode, true); } } //if the node is referred somewhere in its parents and it has a collapsed parent //add a reference to the node in the first collapsed parent (if it is not already there) if (oFirstCollapsedParentNode && bNodeReferredInParents && oFirstCollapsedParentNode !== oNode) { if (oFirstCollapsedParentNode.getSelectedForNodes().indexOf(oNode.getId()) === -1) { oFirstCollapsedParentNode.addAssociation("selectedForNodes", oNode, true); } oFirstCollapsedParentNode.$().addClass('sapUiTreeNodeSelectedParent'); } //include the node in the expanding parents only if it has references to selected child nodes if (bIncludeInExpandingParents) { aExpandingParents.push(oNode); } var aNodes = oNode._getNodes(); for (i = 0; i < aNodes.length; i++) { restoreSelectedChildren(aNodes[i], aExpandingParents, oFirstCollapsedParentNode); } //exclude the node from the expanding parents if (bIncludeInExpandingParents) { aExpandingParents.pop(oNode); } } /** * Adds references inside the collapsed node of all its selected children recursively. * @param {sap.ui.commons.TreeNode} oNode The current node to look at * @param {sap.ui.commons.TreeNode} oRootNode The root node that was collapsed */ function rememberSelectedChildren(oNode, oRootNode) { var aNodes = oNode._getNodes(), oCurrentNode; for (var i = 0; i < aNodes.length; i++) { oCurrentNode = aNodes[i]; if (oCurrentNode.getIsSelected()) { oRootNode.addAssociation("selectedForNodes", oCurrentNode, true); } rememberSelectedChildren(oCurrentNode, oRootNode); } } /** * Adjusts the selection, when collapsing, selecting a parent when the actual selected node is * not visible. * @param {sap.ui.commons.TreeNode} oCollapsingNode The Node being collapsed * @private */ Tree.prototype._adjustSelectionOnCollapsing = function(oCollapsingNode) { if (!oCollapsingNode) { return; } // the root node, which needs to update references for selected children, // is also the first node to look at rememberSelectedChildren(oCollapsingNode, oCollapsingNode); //update dom if necessary if (oCollapsingNode.getSelectedForNodes().length) { var $CollapsingNode = oCollapsingNode.$(); if ($CollapsingNode && !$CollapsingNode.hasClass('sapUiTreeNodeSelectedParent')) { $CollapsingNode.addClass('sapUiTreeNodeSelectedParent'); } } }; /** * override this method on Element.js and return true if tree binding * @private */ Tree.prototype.isTreeBinding = function(sName) { return (sName == "nodes"); }; /** * override element updateAggregation method with this one and update the tree node bindings * @private */ Tree.prototype.updateNodes = function(sReason) { var aNodes, oNode, sKey, iNodesLength, i; // Delete all old node instances if (sReason === "filter") { aNodes = this.getAggregation("nodes"); iNodesLength = aNodes.length; for (i = 0; i < iNodesLength; i++) { aNodes[i].destroy(); } // We reset here mSelectedNodes as it collects id's and after filtering // the tree nodes they are recreated with new id's which can be the same as // the old ones and to result of false positives for node selection. this.mSelectedNodes = {}; } this.updateAggregation("nodes"); for (sKey in this.mSelectedContexts) { oNode = this.getNodeByContext(this.mSelectedContexts[sKey]); if (oNode) { oNode.setIsSelected(true); } else { this.mSelectedContexts = this._removeItemFromObject(this.mSelectedContexts, sKey); } } }; /** * Clones a flat object removing a key/value pair from the old one * @param {object} oObject The object from which the key shall be removed * @param {string} sKeyToRemove Key to be removed from the object * @returns {object} The new object without the removed key * @private */ Tree.prototype._removeItemFromObject = function (oObject, sKeyToRemove) { var sKey, oReturn = {}; for (sKey in oObject) { if (sKey !== sKeyToRemove) { oReturn[sKey] = oObject[sKey]; } } return oReturn; }; /** * Determine the binding context of the given node (dependent on the model name used * for the nodes binding) * * @param {sap.ui.commons.TreeNode} oNode * @private */ Tree.prototype.getNodeContext = function(oNode) { var oBindingInfo = this.getBindingInfo("nodes"), sModelName = oBindingInfo && oBindingInfo.model; return oNode.getBindingContext(sModelName); }; /** * Returns the node with the given context, or null if no such node currently exists * * @param {sap.ui.model.Context} oContext the context of the node to be retrieved * @public * @since 1.19 */ Tree.prototype.getNodeByContext = function(oContext){ var oBindingInfo = this.getBindingInfo("nodes"), sModelName = oBindingInfo && oBindingInfo.model; return this.findNode(this, function(oNode) { var oBindingContext = oNode.getBindingContext(sModelName); return (oContext && oBindingContext && oContext.getPath() === oBindingContext.getPath()); }); }; /** * Search through all existing nodes and return the first node which matches using * the given matching function * * @param {function} fnMatch the matching function * @param {sap.ui.commons.Tree|sap.ui.commons.TreeNode} oNode the node to check * @returns The found node * @private */ Tree.prototype.findNode = function(oNode, fnMatch) { var oFoundNode, that = this; if (fnMatch(oNode)) { return oNode; } jQuery.each(oNode._getNodes(), function(i, oNode) { oFoundNode = that.findNode(oNode, fnMatch); if (oFoundNode) { return false; } }); return oFoundNode; }; Tree.prototype.setSelectionMode = function(oMode){ oMode = this.validateProperty("selectionMode", oMode); if (this.getSelectionMode() != oMode) { this.setProperty("selectionMode", oMode); // Clear current selection, whenever the selectionmode changes this._delSelection(); } }; /**Returns the selected node in the tree. If not selection, returns false. * @returns The selected node * @private */ Tree.prototype.getSelection = function(){ for (var sId in this.mSelectedNodes) { return this.mSelectedNodes[sId]; } return null; }; /**Sets the selected node reference of the Tree * @private */ Tree.prototype.setSelection = function(oNode, bSuppressEvent, sType, bDeselectOtherNodes){ var bDoSelect = true; if (!bSuppressEvent) { bDoSelect = this.fireSelect({node: oNode, nodeContext: this.getNodeContext(oNode)}); } if (bDoSelect) { switch (this.getSelectionMode()) { case sap.ui.commons.TreeSelectionMode.Legacy: case sap.ui.commons.TreeSelectionMode.Single: this._setSelectedNode(oNode, bSuppressEvent); break; case sap.ui.commons.TreeSelectionMode.Multi: if (sType == Tree.SelectionType.Range) { this._setSelectedNodeMapRange(oNode, bSuppressEvent); } else if (sType == Tree.SelectionType.Toggle) { this._setSelectedNodeMapToggle(oNode, bSuppressEvent); } else { this._setSelectedNode(oNode, bSuppressEvent); } break; case sap.ui.commons.TreeSelectionMode.None: break; } } }; /**Rerendering handling. Sets the scroll position so that the selected node stays on the position it * was before rerendering, for example after the expand and adding the nodes dynamically. * @private */ Tree.prototype.onAfterRendering = function () { if (this.iOldScrollTop) { this.$("TreeCont").scrollTop(this.iOldScrollTop); } }; /** * Whenever nodes are added ore removed from the tree, the selection needs to be adapted, * so that the selected node map is in sync with the isSelected properties of the contained * nodes * @private */ Tree.prototype.invalidate = function () { var that = this; Control.prototype.invalidate.apply(this, arguments); if (this.iSelectionUpdateTimer) { return; } this.iSelectionUpdateTimer = setTimeout(function() { that.mSelectedNodes = {}; that.mSelectedContexts = []; that.updateSelection(that, true); that.iSelectionUpdateTimer = null; }, 0); }; /** * Add's node context to the internal mSelectedContexts object. * Taking care if TreeSelectionMode === Multi to not duplicate the node context in mSelectedContexts. * @param oContext The binding context of the node * @private */ Tree.prototype._addSelectedNodeContext = function (oContext) { var sPath; if (oContext && oContext.sPath) { sPath = oContext.sPath; if (this.getSelectionMode() === sap.ui.commons.TreeSelectionMode.Multi) { if (!(sPath in this.mSelectedContexts)) { this.mSelectedContexts[sPath] = oContext; } } else { this.mSelectedContexts = {}; this.mSelectedContexts[sPath] = oContext; } } }; /** * Loop through all tree nodes and collect the selected state * @private */ Tree.prototype.updateSelection = function (oNode, bExpanded) { var that = this; jQuery.each(oNode._getNodes(), function(i, oNode) { if (oNode.getIsSelected()) { switch (that.getSelectionMode()) { case sap.ui.commons.TreeSelectionMode.None: jQuery.sap.log.warning("Added selected nodes in a tree with disabled selection"); oNode.setIsSelected(false); break; case sap.ui.commons.TreeSelectionMode.Legacy: if (jQuery.isEmptyObject(that.mSelectedNodes)) { that.mSelectedNodes[oNode.getId()] = oNode; that._addSelectedNodeContext(that.getNodeContext(oNode)); } break; case sap.ui.commons.TreeSelectionMode.Single: if (jQuery.isEmptyObject(that.mSelectedNodes) == false) { jQuery.sap.log.warning("Added multiple selected nodes in single select tree"); oNode.setIsSelected(false); } else { that.mSelectedNodes[oNode.getId()] = oNode; that._addSelectedNodeContext(that.getNodeContext(oNode)); } break; case sap.ui.commons.TreeSelectionMode.Multi: if (!bExpanded) { jQuery.sap.log.warning("Added selected node inside collapsed node in multi select tree"); oNode.setIsSelected(false); } else { that.mSelectedNodes[oNode.getId()] = oNode; that._addSelectedNodeContext(that.getNodeContext(oNode)); } break; } } that.updateSelection(oNode, bExpanded && oNode.getExpanded()); }); }; /**Rerendering handling. Remembers the scroll position of the selected node. * @private */ Tree.prototype.onBeforeRendering = function() { this.iOldScrollTop = this.$("TreeCont").scrollTop(); }; Tree.prototype._setSelectedNode = function(oNode, bSuppressEvent) { var that = this, oContext = this.getNodeContext(oNode); jQuery.each(this.mSelectedNodes, function(sId, oNode){ that._delMultiSelection(oNode, bSuppressEvent); }); oNode._select(bSuppressEvent, true); this.mSelectedNodes[oNode.getId()] = oNode; this._addSelectedNodeContext(oContext); this.oLeadSelection = oNode; if (!bSuppressEvent) { this.fireSelectionChange({nodes: [oNode], nodeContexts: [oContext]}); } }; Tree.prototype._setSelectedNodeMapToggle = function(oNode, bSuppressEvent) { this._setNodeSelection(oNode, !oNode.getIsSelected(), bSuppressEvent); }; Tree.prototype._setSelectedNodeMapRange = function(oNode, bSuppressEvent) { var aSelectableNodes, aSelectedNodes = [], aSelectedNodeContexts = [], iStartIndex, iEndIndex, iFrom, iTo; if (this.mSelectedNodes[oNode.getId()] == oNode) { return; //Nothing to do! } else { if (this._getNodes().length > 0) { aSelectableNodes = this._getSelectableNodes(); iStartIndex = aSelectableNodes.indexOf(this.oLeadSelection); iEndIndex = aSelectableNodes.indexOf(oNode); iFrom = iStartIndex < iEndIndex ? iStartIndex : iEndIndex; iTo = iStartIndex < iEndIndex ? iEndIndex : iStartIndex; for (var i = iFrom; i <= iTo; i++) { this._setMultiSelection(aSelectableNodes[i], bSuppressEvent); } } } if (!bSuppressEvent) { jQuery.map(this.mSelectedNodes, function(oNode) {aSelectedNodes.push(oNode);}); jQuery.map(this.mSelectedContexts, function(oContext) {aSelectedNodeContexts.push(oContext);}); this.fireSelectionChange({nodes: aSelectedNodes, nodeContexts: aSelectedNodeContexts}); } }; Tree.prototype._getSelectableNodes = function(aNodes) { var aSelectableNodes = []; function collectSelectableNodes(aNodes) { jQuery.each(aNodes, function(i, oNode) { if (oNode.getSelectable()) { aSelectableNodes.push(oNode); } if (oNode.getExpanded()) { collectSelectableNodes(oNode._getNodes()); } }); } collectSelectableNodes(this._getNodes()); return aSelectableNodes; }; Tree.prototype._setNodeSelection = function(oNode, bIsSelected, bSuppressEvent) { var aSelectedNodes = [], aSelectedNodeContexts = [], oVisibleNode; if (this.getSelectionMode() == sap.ui.commons.TreeSelectionMode.Single) { if (bIsSelected) { var oSelectedNode = this.getSelection(); this._setSelectedNode(oNode, bSuppressEvent); if (!oNode.isVisible()) { oVisibleNode = this._getVisibleNode(oNode); this._adjustSelectionOnCollapsing(oVisibleNode); } if (oSelectedNode && !oSelectedNode.isVisible()) { oVisibleNode = this._getVisibleNode(oSelectedNode); this._adjustSelectionOnExpanding(oVisibleNode); } return; } else { this._delMultiSelection(oNode, bSuppressEvent); if (!oNode.isVisible()) { oVisibleNode = this._getVisibleNode(oNode); this._adjustSelectionOnExpanding(oVisibleNode); } } } if (bIsSelected) { this._setMultiSelection(oNode, bSuppressEvent); this.oLeadSelection = oNode; } else { this._delMultiSelection(oNode, bSuppressEvent); this.oLeadSelection = oNode; } if (!bSuppressEvent) { jQuery.map(this.mSelectedNodes, function(oNode) {aSelectedNodes.push(oNode);}); jQuery.map(this.mSelectedContexts, function(oContext) {aSelectedNodeContexts.push(oContext);}); this.fireSelectionChange({nodes: aSelectedNodes, nodeContexts: aSelectedNodeContexts}); } }; Tree.prototype._setMultiSelection = function(oSelNode, bSuppressEvent) { if (!oSelNode) { return; } oSelNode._select(bSuppressEvent); this.mSelectedNodes[oSelNode.getId()] = oSelNode; this._addSelectedNodeContext(this.getNodeContext(oSelNode)); }; Tree.prototype._delMultiSelection = function(oSelNode) { var oContext; if (!oSelNode) { return; } oSelNode._deselect(); this.mSelectedNodes = this._removeItemFromObject(this.mSelectedNodes, oSelNode.getId()); oContext = oSelNode.getBindingContext(); if (oContext && oContext.sPath) { if (oContext.sPath in this.mSelectedContexts) { this.mSelectedContexts = this._removeItemFromObject(this.mSelectedContexts, oContext.sPath); } } }; Tree.prototype._delSelection = function() { var that = this; if (this.oSelectedNode) { this.oSelectedNode._deselect(); } if (jQuery.isEmptyObject(this.mSelectedNodes) == false) { jQuery.each(this.mSelectedNodes, function(sId, oNode){ that._delMultiSelection(oNode); }); } }; Tree.prototype._getNodes = function() { return this.mAggregations.nodes || []; }; Tree.prototype._getVisibleNode = function(oNode) { var oParentNode = oNode.getParent(); if (oParentNode.isVisible()) { var oVisibleNode = oParentNode; } else { oVisibleNode = this._getVisibleNode(oParentNode); } return oVisibleNode; }; return Tree; }, /* bExport= */ true);
olirogers/openui5
src/sap.ui.commons/src/sap/ui/commons/Tree.js
JavaScript
apache-2.0
31,259
var parentchild = require('../'), assert = require('assert'); assert.deepEqual(parentchild('foo'), []); assert.deepEqual(parentchild({}), []); assert.deepEqual(parentchild([1, 2, 3]), [['inarray', undefined, 1], ['inarray', undefined, 2], ['inarray', undefined, 3]]); assert.deepEqual(parentchild({ a: { b: 'foo' }, c: ['a', 'b'] }), [['child', undefined, 'a'], ['child', 'a', 'b'], ['value', 'b', 'foo'], ['child', undefined, 'c'], ['inarray', 'c', 'a'], ['inarray', 'c', 'b']]); assert.deepEqual(parentchild({ a: { b: 'foo' }, c: { f: 'baz', d: { e: 'bar' }, g: 'darp', h: { i: 'derp', o: { p: { q: 'qak' }, r: 'rez' } }, j: 'gar' }, k: { l: 'one', m: 'two', n: 'three', s: [1, 2, 3] } }), [['child', undefined, 'a'], ['child', 'a', 'b'], ['value', 'b', 'foo'], ['child', undefined, 'c'], ['child', 'c', 'f'], ['value', 'f', 'baz'], ['child', 'c', 'd'], ['child', 'd', 'e'], ['value', 'e', 'bar'], ['child', 'c', 'g'], ['value', 'g', 'darp'], ['child', 'c', 'h'], ['child', 'h', 'i'], ['value', 'i', 'derp'], ['child', 'h', 'o'], ['child', 'o', 'p'], ['child', 'p', 'q'], ['value', 'q', 'qak'], ['child', 'o', 'r'], ['value', 'r', 'rez'], ['child', 'c', 'j'], ['value', 'j', 'gar'], ['child', undefined, 'k'], ['child', 'k', 'l'], ['value', 'l', 'one'], ['child', 'k', 'm'], ['value', 'm', 'two'], ['child', 'k', 'n'], ['value', 'n', 'three'], ['child', 'k', 's'], ['inarray', 's', 1], ['inarray', 's', 2], ['inarray', 's', 3]]); console.log('ok');
emitdb/parentchild
test/index.js
JavaScript
apache-2.0
1,671
$('#confirmacaoExclusaoModal').on('show.bs.modal', function(event) { var button = $(event.relatedTarget); var codigoVinho = button.data('codigo'); var nomeVinho = button.data('nome'); var modal = $(this); var form = modal.find('form'); var action = form.data('url-base'); if (!action.endsWith('/')) { action += '/'; } form.attr('action', action + codigoVinho); modal.find('.modal-body span').html('Tem certeza que deseja excluir o vinho <strong>' + nomeVinho + '</strong>?'); });
EliasMG/wine
src/main/resources/static/layout/javascripts/exclusao.js
JavaScript
apache-2.0
497
/* Copyright 2015 Mozilla Foundation * * 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. */ import { assert, BaseException, isString, removeNullCharacters, stringToBytes, Util, warn, } from "../shared/util.js"; import { BaseCanvasFactory, BaseCMapReaderFactory, BaseStandardFontDataFactory, BaseSVGFactory, } from "./base_factory.js"; const DEFAULT_LINK_REL = "noopener noreferrer nofollow"; const SVG_NS = "http://www.w3.org/2000/svg"; class DOMCanvasFactory extends BaseCanvasFactory { constructor({ ownerDocument = globalThis.document } = {}) { super(); this._document = ownerDocument; } _createCanvas(width, height) { const canvas = this._document.createElement("canvas"); canvas.width = width; canvas.height = height; return canvas; } } async function fetchData(url, asTypedArray = false) { if ( (typeof PDFJSDev !== "undefined" && PDFJSDev.test("MOZCENTRAL")) || isValidFetchUrl(url, document.baseURI) ) { const response = await fetch(url); if (!response.ok) { throw new Error(response.statusText); } return asTypedArray ? new Uint8Array(await response.arrayBuffer()) : stringToBytes(await response.text()); } // The Fetch API is not supported. return new Promise((resolve, reject) => { const request = new XMLHttpRequest(); request.open("GET", url, /* asTypedArray = */ true); if (asTypedArray) { request.responseType = "arraybuffer"; } request.onreadystatechange = () => { if (request.readyState !== XMLHttpRequest.DONE) { return; } if (request.status === 200 || request.status === 0) { let data; if (asTypedArray && request.response) { data = new Uint8Array(request.response); } else if (!asTypedArray && request.responseText) { data = stringToBytes(request.responseText); } if (data) { resolve(data); return; } } reject(new Error(request.statusText)); }; request.send(null); }); } class DOMCMapReaderFactory extends BaseCMapReaderFactory { _fetchData(url, compressionType) { return fetchData(url, /* asTypedArray = */ this.isCompressed).then(data => { return { cMapData: data, compressionType }; }); } } class DOMStandardFontDataFactory extends BaseStandardFontDataFactory { _fetchData(url) { return fetchData(url, /* asTypedArray = */ true); } } class DOMSVGFactory extends BaseSVGFactory { _createSVG(type) { return document.createElementNS(SVG_NS, type); } } /** * @typedef {Object} PageViewportParameters * @property {Array<number>} viewBox - The xMin, yMin, xMax and * yMax coordinates. * @property {number} scale - The scale of the viewport. * @property {number} rotation - The rotation, in degrees, of the viewport. * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset. The * default value is `0`. * @property {number} [offsetY] - The vertical, i.e. y-axis, offset. The * default value is `0`. * @property {boolean} [dontFlip] - If true, the y-axis will not be flipped. * The default value is `false`. */ /** * @typedef {Object} PageViewportCloneParameters * @property {number} [scale] - The scale, overriding the one in the cloned * viewport. The default value is `this.scale`. * @property {number} [rotation] - The rotation, in degrees, overriding the one * in the cloned viewport. The default value is `this.rotation`. * @property {number} [offsetX] - The horizontal, i.e. x-axis, offset. * The default value is `this.offsetX`. * @property {number} [offsetY] - The vertical, i.e. y-axis, offset. * The default value is `this.offsetY`. * @property {boolean} [dontFlip] - If true, the x-axis will not be flipped. * The default value is `false`. */ /** * PDF page viewport created based on scale, rotation and offset. */ class PageViewport { /** * @param {PageViewportParameters} */ constructor({ viewBox, scale, rotation, offsetX = 0, offsetY = 0, dontFlip = false, }) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation const centerX = (viewBox[2] + viewBox[0]) / 2; const centerY = (viewBox[3] + viewBox[1]) / 2; let rotateA, rotateB, rotateC, rotateD; // Normalize the rotation, by clamping it to the [0, 360) range. rotation %= 360; if (rotation < 0) { rotation += 360; } switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; case 0: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; default: throw new Error( "PageViewport: Invalid rotation, must be a multiple of 90 degrees." ); } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } let offsetCanvasX, offsetCanvasY; let width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY, ]; this.width = width; this.height = height; } /** * Clones viewport, with optional additional properties. * @param {PageViewportCloneParameters} [params] * @returns {PageViewport} Cloned viewport. */ clone({ scale = this.scale, rotation = this.rotation, offsetX = this.offsetX, offsetY = this.offsetY, dontFlip = false, } = {}) { return new PageViewport({ viewBox: this.viewBox.slice(), scale, rotation, offsetX, offsetY, dontFlip, }); } /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param {number} x - The x-coordinate. * @param {number} y - The y-coordinate. * @returns {Object} Object containing `x` and `y` properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); } /** * Converts PDF rectangle to the viewport coordinates. * @param {Array} rect - The xMin, yMin, xMax and yMax coordinates. * @returns {Array} Array containing corresponding coordinates of the * rectangle in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle(rect) { const topLeft = Util.applyTransform([rect[0], rect[1]], this.transform); const bottomRight = Util.applyTransform([rect[2], rect[3]], this.transform); return [topLeft[0], topLeft[1], bottomRight[0], bottomRight[1]]; } /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param {number} x - The x-coordinate. * @param {number} y - The y-coordinate. * @returns {Object} Object containing `x` and `y` properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } } class RenderingCancelledException extends BaseException { constructor(msg, type) { super(msg, "RenderingCancelledException"); this.type = type; } } const LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; /** * @typedef ExternalLinkParameters * @typedef {Object} ExternalLinkParameters * @property {string} url - An absolute URL. * @property {LinkTarget} [target] - The link target. The default value is * `LinkTarget.NONE`. * @property {string} [rel] - The link relationship. The default value is * `DEFAULT_LINK_REL`. * @property {boolean} [enabled] - Whether the link should be enabled. The * default value is true. */ /** * Adds various attributes (href, title, target, rel) to hyperlinks. * @param {HTMLLinkElement} link - The link element. * @param {ExternalLinkParameters} params */ function addLinkAttributes(link, { url, target, rel, enabled = true } = {}) { assert( url && typeof url === "string", 'addLinkAttributes: A valid "url" parameter must provided.' ); const urlNullRemoved = removeNullCharacters(url); if (enabled) { link.href = link.title = urlNullRemoved; } else { link.href = ""; link.title = `Disabled: ${urlNullRemoved}`; link.onclick = () => { return false; }; } let targetStr = ""; // LinkTarget.NONE switch (target) { case LinkTarget.NONE: break; case LinkTarget.SELF: targetStr = "_self"; break; case LinkTarget.BLANK: targetStr = "_blank"; break; case LinkTarget.PARENT: targetStr = "_parent"; break; case LinkTarget.TOP: targetStr = "_top"; break; } link.target = targetStr; link.rel = typeof rel === "string" ? rel : DEFAULT_LINK_REL; } function isDataScheme(url) { const ii = url.length; let i = 0; while (i < ii && url[i].trim() === "") { i++; } return url.substring(i, i + 5).toLowerCase() === "data:"; } function isPdfFile(filename) { return typeof filename === "string" && /\.pdf$/i.test(filename); } /** * Gets the filename from a given URL. * @param {string} url * @returns {string} */ function getFilenameFromUrl(url) { const anchor = url.indexOf("#"); const query = url.indexOf("?"); const end = Math.min( anchor > 0 ? anchor : url.length, query > 0 ? query : url.length ); return url.substring(url.lastIndexOf("/", end) + 1, end); } /** * Returns the filename or guessed filename from the url (see issue 3455). * @param {string} url - The original PDF location. * @param {string} defaultFilename - The value returned if the filename is * unknown, or the protocol is unsupported. * @returns {string} Guessed PDF filename. */ function getPdfFilenameFromUrl(url, defaultFilename = "document.pdf") { if (typeof url !== "string") { return defaultFilename; } if (isDataScheme(url)) { warn('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'); return defaultFilename; } const reURI = /^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/; // SCHEME HOST 1.PATH 2.QUERY 3.REF // Pattern to get last matching NAME.pdf const reFilename = /[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i; const splitURI = reURI.exec(url); let suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]); if (suggestedFilename) { suggestedFilename = suggestedFilename[0]; if (suggestedFilename.includes("%")) { // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf try { suggestedFilename = reFilename.exec( decodeURIComponent(suggestedFilename) )[0]; } catch (ex) { // Possible (extremely rare) errors: // URIError "Malformed URI", e.g. for "%AA.pdf" // TypeError "null has no properties", e.g. for "%2F.pdf" } } } return suggestedFilename || defaultFilename; } class StatTimer { constructor() { this.started = Object.create(null); this.times = []; } time(name) { if (name in this.started) { warn(`Timer is already running for ${name}`); } this.started[name] = Date.now(); } timeEnd(name) { if (!(name in this.started)) { warn(`Timer has not been started for ${name}`); } this.times.push({ name, start: this.started[name], end: Date.now(), }); // Remove timer from started so it can be called again. delete this.started[name]; } toString() { // Find the longest name for padding purposes. const outBuf = []; let longest = 0; for (const time of this.times) { const name = time.name; if (name.length > longest) { longest = name.length; } } for (const time of this.times) { const duration = time.end - time.start; outBuf.push(`${time.name.padEnd(longest)} ${duration}ms\n`); } return outBuf.join(""); } } function isValidFetchUrl(url, baseUrl) { try { const { protocol } = baseUrl ? new URL(url, baseUrl) : new URL(url); // The Fetch API only supports the http/https protocols, and not file/ftp. return protocol === "http:" || protocol === "https:"; } catch (ex) { return false; // `new URL()` will throw on incorrect data. } } /** * @param {string} src * @param {boolean} [removeScriptElement] * @returns {Promise<void>} */ function loadScript(src, removeScriptElement = false) { return new Promise((resolve, reject) => { const script = document.createElement("script"); script.src = src; script.onload = function (evt) { if (removeScriptElement) { script.remove(); } resolve(evt); }; script.onerror = function () { reject(new Error(`Cannot load script at: ${script.src}`)); }; (document.head || document.documentElement).appendChild(script); }); } // Deprecated API function -- display regardless of the `verbosity` setting. function deprecated(details) { console.log("Deprecated API usage: " + details); } let pdfDateStringRegex; class PDFDateString { /** * Convert a PDF date string to a JavaScript `Date` object. * * The PDF date string format is described in section 7.9.4 of the official * PDF 32000-1:2008 specification. However, in the PDF 1.7 reference (sixth * edition) Adobe describes the same format including a trailing apostrophe. * This syntax in incorrect, but Adobe Acrobat creates PDF files that contain * them. We ignore all apostrophes as they are not necessary for date parsing. * * Moreover, Adobe Acrobat doesn't handle changing the date to universal time * and doesn't use the user's time zone (effectively ignoring the HH' and mm' * parts of the date string). * * @param {string} input * @returns {Date|null} */ static toDateObject(input) { if (!input || !isString(input)) { return null; } // Lazily initialize the regular expression. if (!pdfDateStringRegex) { pdfDateStringRegex = new RegExp( "^D:" + // Prefix (required) "(\\d{4})" + // Year (required) "(\\d{2})?" + // Month (optional) "(\\d{2})?" + // Day (optional) "(\\d{2})?" + // Hour (optional) "(\\d{2})?" + // Minute (optional) "(\\d{2})?" + // Second (optional) "([Z|+|-])?" + // Universal time relation (optional) "(\\d{2})?" + // Offset hour (optional) "'?" + // Splitting apostrophe (optional) "(\\d{2})?" + // Offset minute (optional) "'?" // Trailing apostrophe (optional) ); } // Optional fields that don't satisfy the requirements from the regular // expression (such as incorrect digit counts or numbers that are out of // range) will fall back the defaults from the specification. const matches = pdfDateStringRegex.exec(input); if (!matches) { return null; } // JavaScript's `Date` object expects the month to be between 0 and 11 // instead of 1 and 12, so we have to correct for that. const year = parseInt(matches[1], 10); let month = parseInt(matches[2], 10); month = month >= 1 && month <= 12 ? month - 1 : 0; let day = parseInt(matches[3], 10); day = day >= 1 && day <= 31 ? day : 1; let hour = parseInt(matches[4], 10); hour = hour >= 0 && hour <= 23 ? hour : 0; let minute = parseInt(matches[5], 10); minute = minute >= 0 && minute <= 59 ? minute : 0; let second = parseInt(matches[6], 10); second = second >= 0 && second <= 59 ? second : 0; const universalTimeRelation = matches[7] || "Z"; let offsetHour = parseInt(matches[8], 10); offsetHour = offsetHour >= 0 && offsetHour <= 23 ? offsetHour : 0; let offsetMinute = parseInt(matches[9], 10) || 0; offsetMinute = offsetMinute >= 0 && offsetMinute <= 59 ? offsetMinute : 0; // Universal time relation 'Z' means that the local time is equal to the // universal time, whereas the relations '+'/'-' indicate that the local // time is later respectively earlier than the universal time. Every date // is normalized to universal time. if (universalTimeRelation === "-") { hour += offsetHour; minute += offsetMinute; } else if (universalTimeRelation === "+") { hour -= offsetHour; minute -= offsetMinute; } return new Date(Date.UTC(year, month, day, hour, minute, second)); } } /** * NOTE: This is (mostly) intended to support printing of XFA forms. */ function getXfaPageViewport(xfaPage, { scale = 1, rotation = 0 }) { const { width, height } = xfaPage.attributes.style; const viewBox = [0, 0, parseInt(width), parseInt(height)]; return new PageViewport({ viewBox, scale, rotation, }); } export { addLinkAttributes, DEFAULT_LINK_REL, deprecated, DOMCanvasFactory, DOMCMapReaderFactory, DOMStandardFontDataFactory, DOMSVGFactory, getFilenameFromUrl, getPdfFilenameFromUrl, getXfaPageViewport, isDataScheme, isPdfFile, isValidFetchUrl, LinkTarget, loadScript, PageViewport, PDFDateString, RenderingCancelledException, StatTimer, };
xavier114fch/pdf.js
src/display/display_utils.js
JavaScript
apache-2.0
19,246
import { IconPathDetails } from '../config'; class ReactIcon { constructor(name, component) { this.name = name; this.file = `${IconPathDetails.iconDir}${name}.jsx`; this.component = component; } } export default ReactIcon;
cerner/terra-consumer
packages/terra-consumer-icon/scripts/src/generate-icon/ReactIcon.js
JavaScript
apache-2.0
241
const crypto = require('crypto') module.exports = function (doc) { doc._source.bar = crypto .createHash('md5') .update(String(doc._source.foo)) .digest('hex') }
taskrabbit/elasticsearch-dump
test/test-resources/transform.js
JavaScript
apache-2.0
176
$(function() { var search = $("#search"); var submissions = $("#submissions tbody tr"); search.on('keyup', function(event) { var filter = search.val(); submissions.each(function(index, elem) { var $elem = $(elem); $elem.toggle($elem.data("student").indexOf(filter) !== -1); }); }) });
josalmi/lapio-stats
app/assets/javascripts/submissions.js
JavaScript
apache-2.0
318
/******************************************************************************* * Copyright [2017] [Quirino Brizi (quirino.brizi@gmail.com)] * * 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. ******************************************************************************/ 'use strict' module.exports = { handleError: function(eventEmitter, err, req, res) { console.error("received error %j", err); var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode, message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error; eventEmitter.emit('event', {message: message, payload: err}); res.status(statusCode).send(message); }, handleSuccess: function(eventEmitter, res, message, payload) { eventEmitter.emit('event', {message: message, payload: payload}); res.status(200).json(payload); }, handleApiError: function(err, req, res) { console.error("received error: ", err.stack); var statusCode = (!err.statusCode || err.statusCode == 0) ? 500 : err.statusCode, message = !err.error ? !err.body ? { message: "Internal Server Error" } : err.body : err.error; res.status(statusCode).send(message); }, };
quirinobrizi/buckle
src/interfaces/api/api-helper.js
JavaScript
apache-2.0
1,728
/* eslint-disable */ var webpack = require('webpack'); var path = require('path'); var nodeExternals = require('webpack-node-externals'); module.exports = { entry: './index.js', output: { path: path.join(__dirname, '..', '..', 'build'), filename: 'app.js' }, resolve: { modulesDirectories: ['shared', 'node_modules'], extensions: ['', '.js', '.jsx', '.json'] }, externals: [nodeExternals()], plugins: [ new webpack.BannerPlugin('require("source-map-support").install();', { raw: true, entryOnly: false }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('development') } }) ], target: 'node', node: { // webpack strangely doesn't do this when you set `target: 'node'` console: false, global: false, process: false, Buffer: false, __filename: false, __dirname: false, setImmediate: false }, devtool: 'sourcemap', module: { loaders: [ { test: /\.(js|jsx)$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, presets: ['react', 'es2015', 'stage-0'], plugins: ['transform-decorators-legacy', ['react-transform', { transforms: [ { transform: 'react-transform-catch-errors', imports: ['react', 'redbox-react'] } ] }]] } }, { test: /\.(css|less)$/, loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!less' }, { test: /\.(woff|woff2|ttf|eot|svg|png|jpg|jpeg|gif)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url' } ] } };
SmallShrimp/node-tpl
webpack/dev/webpack.node.config.js
JavaScript
apache-2.0
1,756
var searchData= [ ['checksyscall_2eh',['CheckSysCall.h',['../db/d19/_check_sys_call_8h.html',1,'']]], ['classid_2eh',['ClassID.h',['../dc/d14/_class_i_d_8h.html',1,'']]], ['comparator_2eh',['Comparator.h',['../d7/d0c/_comparator_8h.html',1,'']]] ];
AubinMahe/AubinMahe.github.io
doxygen/html/search/files_2.js
JavaScript
apache-2.0
255
sap.ui.define(['exports', './asset-registries/i18n', './asset-registries/LocaleData', './asset-registries/Themes', './asset-registries/Icons'], function (exports, i18n, LocaleData, Themes, Icons) { 'use strict'; exports.registerI18nLoader = i18n.registerI18nLoader; exports.registerLocaleDataLoader = LocaleData.registerLocaleDataLoader; exports.registerThemePropertiesLoader = Themes.registerThemePropertiesLoader; exports.registerIconLoader = Icons.registerIconLoader; Object.defineProperty(exports, '__esModule', { value: true }); });
SAP/openui5
src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/base/AssetRegistry.js
JavaScript
apache-2.0
548
import { connect } from 'react-redux' import { increment, doubleAsync,callApiAsync } from '../modules/Login' /* This is a container component. Notice it does not contain any JSX, nor does it import React. This component is **only** responsible for wiring in the actions and state necessary to render a presentational component - in this case, the counter: */ import Login from '../views/LoginView' /* Object of action creators (can also be function that returns object). Keys will be passed as props to presentational components. Here we are implementing our wrapper around increment; the component doesn't care */ const mapDispatchToProps = { increment : () => increment(1), doubleAsync, callApiAsync } const mapStateToProps = (state) => ({ counter : state.counter, jsonResult: state.jsonResult }) /* Note: mapStateToProps is where you should use `reselect` to create selectors, ie: import { createSelector } from 'reselect' const counter = (state) => state.counter const tripleCount = createSelector(counter, (count) => count * 3) const mapStateToProps = (state) => ({ counter: tripleCount(state) }) Selectors can compute derived data, allowing Redux to store the minimal possible state. Selectors are efficient. A selector is not recomputed unless one of its arguments change. Selectors are composable. They can be used as input to other selectors. https://github.com/reactjs/reselect */ export default connect(mapStateToProps, mapDispatchToProps)(Login)
vio-lets/Larkyo-Client
src/components/login/controllers/LoginController.js
JavaScript
apache-2.0
1,549
function getFunction(f,b){ return function myNextTick(){ console.log(f + " " + b); }; } process.nextTick(getFunction("foo", "bar"));
marcos-goes/livro_node
04/next-tick-gambi.js
JavaScript
apache-2.0
146
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // == Global variables start // -- screen info var _wh = getScreenSize(); var gDevWidth = 1920; var gDevHeight = 1080; var gTargetWidth = 960; var gTargetHeight = 540; var gDeviceWidth = Math.max(_wh.width, _wh.height); var gDeviceHeight = Math.min(_wh.width, _wh.height); var gGameWidth = gDeviceWidth; var gGameHeight = gDeviceHeight; var gGameOffsetX = 0; var gGameOffsetY = 0; if (gDeviceWidth / gDeviceHeight > 1.78) { gGameWidth = Math.round(gGameHeight * 1.777778); gGameOffsetX = (gDeviceWidth - gGameWidth) / 2; } else if (gDeviceWidth / gDeviceHeight < 1.77) { gGameHeight = Math.round(gGameWidth / 1.777778); gGameOffsetY = (gDeviceHeight - gGameHeight) / 2; } var gRatioTarget = gTargetWidth / gDevWidth; var gRatioDevice = gGameWidth / gDevWidth; // -- others var gZeroColor = { r: 0, g: 0, b: 0 }; // == Global variables en // Utils for sending message var gUserPlan = -1; var gLastSendingTime = 0; var Utils = function () { function Utils() { _classCallCheck(this, Utils); } _createClass(Utils, null, [{ key: 'checkCanSendMessage', value: function checkCanSendMessage() { gUserPlan = -1; if (getUserPlan !== undefined && sendNormalMessage !== undefined) { gUserPlan = getUserPlan(); } } }, { key: 'canSendMessage', value: function canSendMessage() { if (gUserPlan == -1) { return; } var during = Date.now() - gLastSendingTime; if (gUserPlan >= 0 && during > 60 * 60 * 1000) { return true; } } }, { key: 'sendMessage', value: function sendMessage(topMsg, msg, force) { if (force || Utils.canSendMessage()) { gLastSendingTime = Date.now(); if (force) { console.log(sendUrgentMessage(topMsg, msg)); } else { console.log(sendNormalMessage(topMsg, msg)); } } } }, { key: 'nearColor', value: function nearColor(c, c1, c2) { var d1 = Math.abs(c1.r - c.r) + Math.abs(c1.g - c.g) + Math.abs(c1.b - c.b); var d2 = Math.abs(c2.r - c.r) + Math.abs(c2.g - c.g) + Math.abs(c2.b - c.b); return d1 - d2; } }, { key: 'mergeColor', value: function mergeColor(c1, c2) { return { r: Math.round((c1.r + c2.r) / 2), g: Math.round((c1.g + c2.g) / 2), b: Math.round((c1.b + c2.b) / 2) }; } }, { key: 'diffColor', value: function diffColor(c, c1) { return Math.abs(c1.r - c.r) + Math.abs(c1.g - c.g) + Math.abs(c1.b - c.b); } }, { key: 'minMaxDiff', value: function minMaxDiff(c) { var max = Math.max(Math.max(c.r, c.g), c.b); var min = Math.min(Math.min(c.r, c.g), c.b); return max - min; } }, { key: 'isSameColor', value: function isSameColor(c1, c2) { var d = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 25; if (Math.abs(c1.r - c2.r) < d && Math.abs(c1.g - c2.g) < d && Math.abs(c1.b - c2.b) < d) { return true; } return false; } }, { key: 'targetToDevice', value: function targetToDevice(xy) { var r = gRatioDevice / gRatioTarget; return { x: gGameOffsetX + xy.x * r, y: gGameOffsetY + xy.y * r }; } }]); return Utils; }(); Utils.checkCanSendMessage(); var Rect = function () { function Rect(x1, y1, x2, y2) { _classCallCheck(this, Rect); this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.w = x2 - x1; this.h = y2 - y1; this.tx = this.x1 * gRatioTarget; this.ty = this.y1 * gRatioTarget; this.tw = (this.x2 - this.x1) * gRatioTarget; this.th = (this.y2 - this.y1) * gRatioTarget; } _createClass(Rect, [{ key: 'crop', value: function crop(img) { return cropImage(img, this.tx, this.ty, this.tw, this.th); } }]); return Rect; }(); var Point = function () { function Point(x, y) { _classCallCheck(this, Point); this.x = x; this.y = y; this.tx = this.x * gRatioTarget; this.ty = this.y * gRatioTarget; this.dx = gGameOffsetX + this.x * gRatioDevice; this.dy = gGameOffsetY + this.y * gRatioDevice; } _createClass(Point, [{ key: 'tap', value: function (_tap) { function tap() { return _tap.apply(this, arguments); } tap.toString = function () { return _tap.toString(); }; return tap; }(function () { var times = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; while (times > 0) { if (delay > 0) { sleep(delay); } tap(this.dx, this.dy, 20); times--; } }) }, { key: 'tapDown', value: function (_tapDown) { function tapDown() { return _tapDown.apply(this, arguments); } tapDown.toString = function () { return _tapDown.toString(); }; return tapDown; }(function () { tapDown(this.dx, this.dy, 20); }) }, { key: 'tapUp', value: function (_tapUp) { function tapUp() { return _tapUp.apply(this, arguments); } tapUp.toString = function () { return _tapUp.toString(); }; return tapUp; }(function () { tapUp(this.dx, this.dy, 20); }) }, { key: 'moveTo', value: function (_moveTo) { function moveTo() { return _moveTo.apply(this, arguments); } moveTo.toString = function () { return _moveTo.toString(); }; return moveTo; }(function () { moveTo(this.dx, this.dy, 20); }) }]); return Point; }(); var FeaturePoint = function (_Point) { _inherits(FeaturePoint, _Point); // need: true => should exist, false => should not exist function FeaturePoint(x, y, r, g, b, need) { var diff = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 25; _classCallCheck(this, FeaturePoint); var _this = _possibleConstructorReturn(this, (FeaturePoint.__proto__ || Object.getPrototypeOf(FeaturePoint)).call(this, x, y)); _this.r = r; _this.g = g; _this.b = b; _this.d = diff; _this.need = need; return _this; } _createClass(FeaturePoint, [{ key: 'check', value: function check(img) { var c = getImageColor(img, this.tx, this.ty); if (this.need && !Utils.isSameColor(c, this, this.d)) { return false; } else if (!this.need && Utils.isSameColor(c, this)) { return false; } return true; } }, { key: 'print', value: function print(img) { var c = getImageColor(img, this.tx, this.ty); console.log('target', this.tx, this.ty, 'param', this.x + ', ' + this.y + ', ' + c.r + ', ' + c.g + ', ' + c.b + ', true'); } }]); return FeaturePoint; }(Point); var PageFeature = function () { function PageFeature(name, featurPoints) { _classCallCheck(this, PageFeature); this.name = name || 'Unknown'; this.featurPoints = featurPoints || []; } _createClass(PageFeature, [{ key: 'check', value: function check(img) { for (var i = 0; i < this.featurPoints.length; i++) { var _p = this.featurPoints[i]; if (!_p.check(img)) { return false; } } return true; } }, { key: 'print', value: function print(img) { for (var i = 0; i < this.featurPoints.length; i++) { var _p2 = this.featurPoints[i]; _p2.print(img); } } }, { key: 'tap', value: function tap() { var idx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; this.featurPoints[idx].tap(); } }]); return PageFeature; }(); var GameInfo = function GameInfo() { _classCallCheck(this, GameInfo); this.hpBarRect = new Rect(122, 30, 412, 51); this.mpBarRect = new Rect(122, 58, 412, 72); this.expBarRect = new Rect(16, 1070, 1904, 1072); this.zeroRect = new Rect(0, 0, 1, 1); this.mapRect = new Rect(384, 217, 1920, 937); // 1536, 720 this.regionTypeRect = new Rect(1710, 470, 1816, 498); this.storeHpRect = new Rect(78, 274, 80 + 122, 276 + 122); this.mapSelector = new Rect(56, 339, 350, 937); // h 112 this.moneyRect = new Rect(990, 40, 1150, 80); this.centerRect = new Rect(600, 200, 1400, 800); this.storeOther = new Point(510, 220); this.store10 = new Point(670, 970); this.store100 = new Point(900, 970); this.store1000 = new Point(1100, 970); this.storeMax = new Point(1300, 970); this.storeHp = new Point(150, 330); this.storeArrow = new Point(260, 560); this.storeBuy = new Point(1600, 970); this.storeBuy2 = new Point(1130, 882); this.storeSelfOrder = new Point(200, 970); this.storeBuyOrder = new Point(1500, 970); this.storeBuyOrder2 = new Point(1750, 970); this.storeSpecial = new Point(1140, 340); this.getReward = new Point(1680, 320); this.signAlliance = new Point(1820, 252); this.itemBtns = [new Point(730, 960), new Point(840, 960), new Point(960, 960), new Point(1060, 960), new Point(1180, 960), new Point(1400, 960), new Point(1510, 960), new Point(1620, 960), new Point(1730, 960), new Point(1840, 960), new Point(1280, 960)]; this.unknownBtn = new Point(1100, 800); this.mapBtn = new Point(1740, 300); this.mapDetailBtn = new Point(700, 160); this.mapController = new Point(290, 860); this.mapControllerL = new Point(190, 860); this.mapControllerR = new Point(390, 860); this.mapControllerT = new Point(290, 760); this.mapControllerB = new Point(290, 960); this.mapMoveBtn = new Point(1588, 986); this.mapFloorBtn = new Point(1120, 886); this.storeMode = new PageFeature('storeMode', [new FeaturePoint(116, 862, 224, 155, 46, true, 32), new FeaturePoint(223, 862, 28, 45, 70, true, 32), new FeaturePoint(196, 946, 43, 33, 17, true, 32), new FeaturePoint(692, 710, 0, 0, 0, true, 32), new FeaturePoint(830, 710, 0, 0, 0, true, 32), new FeaturePoint(1487, 944, 25, 22, 16, true, 32)]); this.menuOffEvent = new PageFeature('menuOffEvent', [new FeaturePoint(1850, 56, 173, 166, 147, true, 80), new FeaturePoint(1850, 66, 173, 166, 147, true, 80), new FeaturePoint(1860, 76, 173, 166, 147, true, 80), new FeaturePoint(1880, 42, 242, 30, 26, true, 30)]); this.menuSign = new PageFeature('menuOpenSign', [new FeaturePoint(1652, 250, 242, 30, 26, true, 80)]); this.menuMail = new PageFeature('menuOpenMail', [new FeaturePoint(1652, 466, 242, 30, 26, true, 80)]); this.menuAlliance = new PageFeature('menuOpenAlliance', [new FeaturePoint(1418, 360, 242, 30, 26, true, 80)]); this.menuOnBtn = new PageFeature('menuOn', [new FeaturePoint(1844, 56, 245, 245, 241, true, 30), new FeaturePoint(1844, 66, 128, 70, 56, true, 30), new FeaturePoint(1844, 76, 245, 220, 215, true, 30)]); this.menuOffBtn = new PageFeature('menuOff', [new FeaturePoint(1850, 56, 173, 166, 147, true, 80), new FeaturePoint(1850, 66, 173, 166, 147, true, 80), new FeaturePoint(1860, 76, 173, 166, 147, true, 80)]); this.autoPlayBtn = new PageFeature('autoPlayOff', [new FeaturePoint(1430, 768, 140, 154, 127, true, 60), new FeaturePoint(1476, 772, 140, 157, 130, true, 60)]); this.killNumber = new PageFeature('killNumber', [new FeaturePoint(1678, 538, 65, 62, 45, true, 60), new FeaturePoint(1780, 554, 235, 83, 44, true, 40), new FeaturePoint(1810, 554, 220, 59, 39, true, 40), new FeaturePoint(1804, 532, 255, 186, 142, true, 40)]); this.selfSkillBtn = new PageFeature('selfSkillOff', [new FeaturePoint(1594, 601, 141, 147, 137, true, 60), new FeaturePoint(1591, 624, 117, 128, 114, true, 60)]); this.attackBtn = new PageFeature('attackOff', [new FeaturePoint(1634, 769, 165, 180, 170, true, 60)]); this.disconnectBtn = new PageFeature('disconnect', [new FeaturePoint(840, 880, 34, 51, 79, true, 20), new FeaturePoint(1080, 880, 34, 51, 79, true, 20), new FeaturePoint(1170, 880, 31, 20, 14, true, 20), new FeaturePoint(1150, 916, 31, 24, 14, true, 20)]); this.loginBtn = new PageFeature('login', [new FeaturePoint(335, 310, 236, 175, 110, true, 40), new FeaturePoint(430, 415, 161, 123, 78, true, 40), new FeaturePoint(140, 145, 60, 55, 55, true, 40), new FeaturePoint(280, 191, 140, 100, 90, true, 40)]); this.enterBtn = new PageFeature('enter', [new FeaturePoint(1480, 990, 31, 47, 70, true, 20), new FeaturePoint(1750, 990, 31, 47, 70, true, 20), new FeaturePoint(1690, 990, 31, 47, 70, true, 20)]); this.beAttacked = new PageFeature('beAttacked', [new FeaturePoint(1616, 744, 210, 90, 50, true, 45), new FeaturePoint(1676, 744, 210, 90, 50, true, 45), new FeaturePoint(1666, 756, 210, 90, 50, true, 45), new FeaturePoint(1624, 750, 210, 90, 50, true, 45), new FeaturePoint(1800, 818, 240, 160, 140, true, 30), new FeaturePoint(1634, 769, 165, 180, 170, false, 50)]); this.storeExceed = new PageFeature('storeExceed', [new FeaturePoint(1102, 812, 33, 23, 0, true, 40)]); }; var RoleState = function () { function RoleState(gi) { _classCallCheck(this, RoleState); this.gi = gi; this.lastHP = 0; this.lastMP = 0; this.hp = 0; this.mp = 0; this.exp = 0; this.isDisconnect = false; this.isLogin = false; this.isEnter = false; this.isMenuOn = false; this.isMenuOff = false; this.lastSafeRegion = false; this.isSafeRegion = false; this.isAutoPlay = false; this.isAttacking = false; this.isSelfSkill = false; this.isAttacked = false; this.hasKillNumber = false; this.autoPlayOffCount = 5; this.isPoison = false; this.movingScore = 0.9; this.isMovingCount = 0; this.shouldTapMiddle = true; // determine to tap middle or tap back } _createClass(RoleState, [{ key: 'print', value: function print() { if (Math.abs(this.lastHP - this.hp) > 5 || Math.abs(this.lastMP - this.mp) > 5) { console.log('\u8840\u91CF\uFF1A' + this.hp + '\uFF0C\u9B54\u91CF\uFF1A' + this.mp); this.lastHP = this.hp; this.lastMP = this.mp; } } }]); return RoleState; }(); var LineageM = function () { function LineageM(config) { _classCallCheck(this, LineageM); this.config = config || { conditions: [] }; this.gi = new GameInfo(); this.rState = new RoleState(this.gi); this.localPath = getStoragePath() + '/scripts/com.r2studio.LineageM/images'; this._loop = false; this._img = 0; this.refreshScreen(); // load images this.images = { safeRegion: openImage(this.localPath + '/safeRegionType.png'), normalRegion: openImage(this.localPath + '/normalRegionType.png'), hpWater: openImage(this.localPath + '/hp.png'), store: openImage(this.localPath + '/store.png'), store2: openImage(this.localPath + '/store2.png'), arrow: openImage(this.localPath + '/arrow.png'), floor1: openImage(this.localPath + '/floor1.png'), floor2: openImage(this.localPath + '/floor2.png') }; // this.gi.menuOffEvent.print(this._img); this.tmpExp = 0; this.isRecordLocation = false; } _createClass(LineageM, [{ key: 'safeSleep', value: function safeSleep(t) { while (this._loop && t > 0) { t -= 100; sleep(100); } } }, { key: 'refreshScreen', value: function refreshScreen() { var startTime = Date.now(); var newImg = getScreenshotModify(gGameOffsetX, gGameOffsetY, gGameWidth, gGameHeight, gTargetWidth, gTargetHeight, 80); if (this._img !== 0) { if (this.config.grabMonster) { var s = getIdentityScore(this._img, newImg); if (this.rState.movingScore - s > 0.05) { this.rState.isMovingCount++; } else { this.rState.isMovingCount = 0; } this.rState.movingScore = this.rState.movingScore * 0.95 + s * 0.05; } releaseImage(this._img); this._img = 0; } this._img = newImg; if (Date.now() - startTime < 120) { sleep(120); } return this._img; } }, { key: 'checkIsSystemPage', value: function checkIsSystemPage() { if (this.rState.isLogin) { console.log('登入遊戲,等待 2 秒'); this.gi.loginBtn.tap(); this.safeSleep(2 * 1000); return true; } if (this.rState.isEnter) { console.log('進入遊戲,等待 10 秒'); this.gi.enterBtn.tap(); this.safeSleep(10 * 1000); return true; } if (this.rState.isDisconnect) { console.log('重新連線中,等待 10 秒'); this.gi.disconnectBtn.tap(); this.safeSleep(10 * 1000); return true; } if (!this.rState.isMenuOn && !this.rState.isMenuOff) { if (this.rState.shouldTapMiddle) { console.log('未知狀態,隨便點看看,等待 5 秒'); this.gi.enterBtn.tap(); this.safeSleep(5 * 1000); this.rState.shouldTapMiddle = false; return true; } else { console.log('未知狀態,等待 5 秒'); keycode('BACK', 100); this.safeSleep(5 * 1000); this.rState.shouldTapMiddle = true; return true; } } return false; } }, { key: 'checkBeAttacked', value: function checkBeAttacked() { if (this.config.beAttackedRandTeleport && this.gi.beAttacked.check(this._img)) { var c = getImageColor(this._img, this.gi.zeroRect.tx, this.gi.zeroRect.ty); if (c.r > (c.g + c.b) / 2) { console.log('警告!你被攻擊了,使用按鈕 7'); this.gi.itemBtns[6].tap(); this.safeSleep(2000); return true; } } return false; } }, { key: 'updateGlobalState', value: function updateGlobalState() { this.rState.isDisconnect = this.gi.disconnectBtn.check(this._img); this.rState.isLogin = this.gi.loginBtn.check(this._img); this.rState.isEnter = this.gi.enterBtn.check(this._img); if (this.rState.isDisconnect || this.rState.isLogin || this.rState.isEnter) { return; } this.rState.isMenuOn = this.gi.menuOnBtn.check(this._img); this.rState.isMenuOff = this.gi.menuOffBtn.check(this._img); // console.log(this.rState.isMenuOn, this.rState.isMenuOff); if (!this.rState.isMenuOn && !this.rState.isMenuOff) { return; } if (this.rState.isMenuOn) { return; } this.rState.hp = this.getHpPercent(); if (this.rState.hp < 30 && this.rState.hp > 0.1) { sleep(300); this.refreshScreen(); this.rState.hp = this.getHpPercent(); } this.rState.mp = this.getMpPercent(); // this.rState.exp = this.getExpPercent(); this.rState.isSafeRegion = this.isSafeRegionState(); this.rState.isAttacking = !this.gi.attackBtn.check(this._img); this.rState.isSelfSkill = !this.gi.selfSkillBtn.check(this._img); this.rState.hasKillNumber = this.gi.killNumber.check(this._img); if (this.gi.autoPlayBtn.check(this._img)) { this.rState.autoPlayOffCount++; } else { this.rState.autoPlayOffCount = 0; } if (this.rState.autoPlayOffCount > 4) { this.rState.isAutoPlay = false; } else { this.rState.isAutoPlay = true; } this.rState.print(); } }, { key: 'checkCondiction', value: function checkCondiction() { for (var i = 0; i < this.config.conditions.length && this._loop; i++) { var cd = this.config.conditions[i]; if (cd.useTime === undefined) { cd.useTime = 0; } if (!cd.enabled) { continue; } if (Date.now() - cd.useTime < cd.interval) { continue; } var value = this.rState[cd.type]; if (value < 0.1) { continue; } if (cd.type === 'exp') { if (this.rState.exp !== this.tmpExp) { this.gi.itemBtns[cd.btn].tap(1, 50); console.log('\u4F7F\u7528\u6309\u9215 ' + (cd.btn + 1) + '\uFF0C\u689D\u4EF6 ' + cd.type + ' ' + (cd.op === 1 ? '大於' : '小於') + ' ' + cd.value + ' (' + value + ')'); cd.useTime = Date.now(); break; } } else if (value * cd.op > cd.value * cd.op) { if (cd.btn >= 0 && cd.btn < this.gi.itemBtns.length) { if (cd.btn === 7 && this.rState.isSafeRegion && !this.rState.isAttacking) { continue; } this.gi.itemBtns[cd.btn].tap(1, 50); console.log('\u4F7F\u7528\u6309\u9215 ' + (cd.btn + 1) + '\uFF0C\u689D\u4EF6 ' + cd.type + ' ' + (cd.op === 1 ? '大於' : '小於') + ' ' + cd.value + ' (' + value + ')'); cd.useTime = Date.now(); break; } } } } }, { key: 'start', value: function start() { this._loop = true; var goBackTime = Date.now(); var useHomeTime = Date.now(); var poisonTime = Date.now(); var tmpTime = Date.now(); var noMonsterTime = Date.now(); var isBuy = false; var receiveTime = 0; while (this._loop) { sleep(100); this.refreshScreen(); if (this.checkBeAttacked()) { this.sendDangerMessage('你被攻擊了,使用順卷'); continue; } this.updateGlobalState(); if (this.checkIsSystemPage()) { continue; } if (this.rState.isMenuOn) { console.log('關閉選單'); this.gi.menuOnBtn.tap(); this.safeSleep(500); continue; } // go home (8th btn), rand teleport (7th btn) if (this.rState.isSafeRegion && !this.rState.isAttacking) { var isAttacking = true; for (var i = 0; i < 2; i++) { this.safeSleep(1000); this.refreshScreen(); this.rState.isAttacking = !this.gi.attackBtn.check(this._img); if (!this.rState.isAttacking) { isAttacking = false; break; } } if (this.rState.isAutoPlay) { console.log('安全區域,關閉自動攻擊', this.rState.autoPlayOffCount); this.gi.autoPlayBtn.tap(); sleep(1000); continue; } if (!isAttacking) { if (!isBuy && this.config.autoBuyFirstSet) { this.checkAndBuyItems(); isBuy = true; } else if (this.config.inHomeUseBtn && Date.now() - useHomeTime > 4000) { this.gi.itemBtns[6].tap(); useHomeTime = Date.now(); } else if (this.config.mapSelect > 0 && this.rState.hp > 40) { console.log('移動到地圖', this.config.mapSelect); this.goToMapPage(); this.slideMapSelector(this.config.mapSelect); } } } else { if (this.rState.isAttacking) { noMonsterTime = Date.now(); } isBuy = false; if (this.config.dangerousGoHome && this.rState.hp < 25 && this.rState.hp > 0.1) { this.gi.itemBtns[7].tap(1, 100); this.safeSleep(1000); console.log('危險,血量少於 25%,使用按鈕 8'); this.sendDangerMessage('危險,血量少於25%,回家'); continue; } if (!this.rState.isAutoPlay && this.config.autoAttack) { console.log('開啟自動攻擊'); this.gi.autoPlayBtn.tap(); this.rState.autoPlayOffCount = 0; sleep(600); continue; } if (this.config.autoUseAntidote && this.gi.isPoison && Date.now() - poisonTime > 1500) { console.log('中毒,使用解毒劑,使用按鈕 6'); sleep(500); this.gi.itemBtns[5].tap(); poisonTime = Date.now(); continue; } var cd = this.config.conditions[0]; if (this.config.grabMonster && this.rState.isAttacking && this.rState.isMovingCount > 0 && Date.now() - tmpTime > cd.interval) { tmpTime = Date.now(); var value = this.rState[cd.type]; if (value > 0.1 && value * cd.op > cd.value * cd.op) { this.gi.itemBtns[cd.btn].tap(1, 50); console.log('尋找怪物, 使用按鈕 1'); this.gi.itemBtns[0].tap(); } else { console.log('尋找怪物, HP/MP 不滿足'); } continue; } if (this.config.autoTeleport && Date.now() - noMonsterTime > 6000) { console.log('沒有怪物, 使用按鈕 7'); noMonsterTime = Date.now(); this.gi.itemBtns[7 - 1].tap(2, 200); continue; } } // console.log('Check conditions'); this.checkCondiction(); if (this.config.autoReceiveReward && Date.now() - receiveTime > 300 * 1000) { this.checkAndAutoGetReward(); receiveTime = Date.now(); } this.sendMoneyInfo(); if (this.rState.lastSafeRegion != this.rState.isSafeRegion) { this.rState.lastSafeRegion = this.rState.isSafeRegion; if (this.rState.lastSafeRegion) { console.log('安全區域'); } } if (this.rState.isSafeRegion) { continue; } if (this.config.goBackInterval != 0 && !this.isRecordLocation) { console.log('記錄現在位置'); this.goToMapPage(); this.recordCurrentLocation(); this.gi.menuOnBtn.tap(); this.isRecordLocation = true; continue; } // go back to record location if (this.config.goBackInterval != 0 && Date.now() - goBackTime > this.config.goBackInterval) { console.log('嘗試走回紀錄點'); this.goToMapPage(); var diffXY = this.getDiffRecordLocation(); this.gi.menuOnBtn.tap(); sleep(1000); console.log(JSON.stringify(diffXY)); if (diffXY !== undefined) { this.goMap(-diffXY.x, -diffXY.y); } goBackTime = Date.now(); } } } }, { key: 'waitForChangeScreen', value: function waitForChangeScreen() { var score = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0.8; var maxSleep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000; var oriImg = clone(this._img); for (var i = 0; i < maxSleep / 500 && this._loop; i++) { sleep(400); this.refreshScreen(); var s = getIdentityScore(this._img, oriImg); if (s < score) { break; } } releaseImage(oriImg); } }, { key: 'goToMapPage', value: function goToMapPage() { this.gi.mapBtn.tap(); this.waitForChangeScreen(); this.gi.mapDetailBtn.tap(); this.waitForChangeScreen(0.8, 2000); console.log('地圖畫面'); } }, { key: 'stop', value: function stop() { this._loop = false; releaseImage(this._img); for (var k in this.images) { releaseImage(this.images[k]); } } }, { key: 'sendDangerMessage', value: function sendDangerMessage(msg) { console.log('送危險訊息中...'); var centerImg = this.gi.centerRect.crop(this._img); var rmi = resizeImage(centerImg, this.gi.centerRect.w / 2, this.gi.centerRect.h / 2); var base64 = getBase64FromImage(rmi); releaseImage(rmi); releaseImage(centerImg); Utils.sendMessage('天堂M 危險', base64, true); } }, { key: 'sendMoneyInfo', value: function sendMoneyInfo() { if (Utils.canSendMessage()) { console.log('送錢訊息中...'); var moneyImg = this.gi.moneyRect.crop(this._img); var rmi = resizeImage(moneyImg, this.gi.moneyRect.w / 2, this.gi.moneyRect.h / 2); var base64 = getBase64FromImage(rmi); releaseImage(rmi); releaseImage(moneyImg); Utils.sendMessage('天堂M', base64); } } }, { key: 'checkAndBuyItems', value: function checkAndBuyItems() { var tryTimes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; console.log('嘗試購買物品');sleep(500); this.refreshScreen(); for (var i = 0; i < tryTimes && this._loop; i++) { if (i == 4) { console.log('移動到綠洲,確保有商人等待4秒'); this.goToMapPage(); this.slideMapSelector(41); this.safeSleep(3000); console.log('移動到綠洲,往上移動一些'); this.gi.mapController.tapDown(); this.safeSleep(1500); this.gi.mapControllerT.moveTo(); this.safeSleep(1500); this.gi.mapControllerT.tapUp(); this.safeSleep(2200); this.refreshScreen(); console.log('尋找商店'); var _storeType = this.findStore(); console.log('storeType', _storeType); if (_storeType === 1) { this.buyItems(); this.refreshScreen(); this.gi.itemBtns[7].tap(); this.safeSleep(2000); break; } this.gi.itemBtns[7].tap(); this.safeSleep(2000); } var storeType = this.findStore(); if (storeType === 1) { this.safeSleep(1000); this.buyItems(); this.refreshScreen(); break; } else if (storeType === 2) { this.buyItems(); this.refreshScreen(); // this.gi.itemBtns[7].tap(); // this.safeSleep(4000); // this.refreshScreen(); } else if (i < tryTimes - 1) { console.log('找不到商店,再試一次'); this.gi.itemBtns[7].tap(); this.safeSleep(4000); this.refreshScreen(); } } } // 0 = no store, 1 = 雜貨電. 2 = others }, { key: 'findStore', value: function findStore() { var stores1 = findImages(this._img, this.images.store, 0.89, 4, true); var stores2 = findImages(this._img, this.images.store2, 0.89, 4, true); var stores = stores1.concat(stores2); for (var k in stores) { if (!this._loop) { return false; } var blueCount = 0; var sx = stores[k].x; var sy = stores[k].y; if (sx < 280 && sy < 144) { continue; } if (sx > 790 && sy < 260) { continue; } // for check is right store for (var i = 0; i < 10; i++) { if (sx + 10 >= gTargetWidth || sy + 67 + i >= gTargetHeight) { break; } var color = getImageColor(this._img, sx + 10, sy + 67 + i); if (color.b * 2 > color.g + color.r && color.b > color.r + 30) { blueCount++; } } if (blueCount < 4) { continue; } var dXY = Utils.targetToDevice(stores[k]); console.log('可能是商店,打開看看'); tap(dXY.x + 5, dXY.y + 5, 50); this.waitForChangeScreen(0.7, 7000);if (!this._loop) { return false; } this.safeSleep(2000); this.refreshScreen(); if (this.gi.storeMode.check(this._img)) { var testHpImg = this.gi.storeHpRect.crop(this._img); var results = findImages(testHpImg, this.images.hpWater, 0.88, 1); releaseImage(testHpImg); console.log('是雜貨店嗎', results.length > 0 ? results[0].score : 0); if (results.length > 0 && results[0].score > 0.88) { console.log('找到雜貨店1'); return 1; } else { // find method 2 var redCount = 0; for (var y = 160; y < 176; y++) { var _color = getImageColor(this._img, 70, y); if (1.2 * _color.r > _color.g + _color.b) { redCount++; } } if (redCount > 10) { console.log('找到雜貨店2'); return 1; } } } else { console.log('不是商店,換下一個'); } if (this.gi.menuOnBtn.check(this._img)) { this.gi.menuOnBtn.tap(); } this.safeSleep(2000); continue; } return 0; } }, { key: 'buyItems', value: function buyItems() { console.log('購買自訂清單'); this.gi.storeSelfOrder.tap(); sleep(2000);if (!this._loop) { return false; } this.gi.storeBuyOrder.tap(); sleep(2000);if (!this._loop) { return false; } this.gi.storeBuyOrder2.tap(); sleep(2000);if (!this._loop) { return false; } this.gi.storeBuy2.tap(); sleep(2000);if (!this._loop) { return false; } console.log('購買自訂清單完成'); this.gi.menuOnBtn.tap(); return true; } // utils }, { key: 'cropAndSave', value: function cropAndSave(filename, rect) { var img = rect.crop(this._img); saveImage(img, this.localPath + '/lineageM/' + filename); releaseImage(img); } // globalState 764 240 812 240 }, { key: 'isSafeRegionState', value: function isSafeRegionState() { var bColor = 0; var rColor = 0; var gColor = 0; //gray for (var x = 850; x < 900; x += 2) { var color = getImageColor(this._img, x, 241); if (color.b > color.g + color.r) { // 18 bColor++; continue; } if (color.r > color.g + color.b) { // 20 rColor++; continue; } if (color.r > 80 && color.g > 80 && color.b > 80) { // 12 gColor++; } } if (gColor > bColor || rColor > bColor) { return false; } var greenColor = 0; var orangeColor = 0; for (var _x9 = 764; _x9 < 812; _x9++) { var _color2 = getImageColor(this._img, _x9, 240); if (_color2.b > 86 && _color2.b < 110 && _color2.r < 60 && _color2.g > 140 && _color2.g < 200) { greenColor++; } if (_color2.b < 30 && _color2.r > 200 && _color2.g > 90 && _color2.g < 130) { orangeColor++; } } if (greenColor > 6 || orangeColor > 6) { return false; } return true; } }, { key: 'checkAndAutoGetReward', value: function checkAndAutoGetReward() { if (!this.gi.menuOffEvent.check(this._img)) { return; } this.gi.menuOffEvent.tap(); this.waitForChangeScreen(0.95, 3000); if (!this._loop) { return; } if (this.gi.menuMail.check(this._img)) { console.log('自動收取獎勵:信箱'); this.gi.menuMail.tap(); this.waitForChangeScreen(0.9, 5000); if (!this._loop) { return; } this.gi.getReward.tap();this.safeSleep(1000); this.gi.getReward.tap();this.safeSleep(1000); this.gi.getReward.tap();this.safeSleep(1000); this.gi.getReward.tap();this.safeSleep(1000); this.gi.menuOnBtn.tap(); this.waitForChangeScreen(0.95, 5000); } if (this.gi.menuSign.check(this._img)) { console.log('自動收取獎勵:登入'); this.gi.menuSign.tap(); this.waitForChangeScreen(0.95, 5000); if (!this._loop) { return; } this.gi.getReward.tap();this.safeSleep(500); this.safeSleep(5000); if (!this._loop) { return; } this.gi.getReward.tap();this.safeSleep(500); this.gi.menuOnBtn.tap(); this.waitForChangeScreen(0.95, 5000); } if (this.gi.menuAlliance.check(this._img)) { console.log('自動收取獎勵:血盟'); this.gi.menuAlliance.tap(); this.waitForChangeScreen(0.9, 5000); if (!this._loop) { return; } this.gi.signAlliance.tap(); this.safeSleep(3000); if (!this._loop) { return; } this.gi.menuOnBtn.tap(); this.waitForChangeScreen(0.95, 5000); } } // HP MP EXP }, { key: 'getHpPercent', value: function getHpPercent() { return this.getBarPercent(this.gi.hpBarRect, 70, 14, true); } }, { key: 'getMpPercent', value: function getMpPercent() { return this.getBarPercent(this.gi.mpBarRect, 70, 70); } }, { key: 'getExpPercent', value: function getExpPercent() { return this.getBarPercent(this.gi.expBarRect, 70, 70); } }, { key: 'getBarPercent', value: function getBarPercent(barRect, b1, b2) { var poison = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var bar = cropImage(this._img, barRect.tx, barRect.ty, barRect.tw, barRect.th); var y1 = barRect.th / 3; var y2 = barRect.th / 3 * 2; var fc = Utils.mergeColor(getImageColor(bar, 0, y1), getImageColor(bar, 0, y2)); var bright1 = 0; var bright2 = 0; for (var x = 0; x < barRect.tw; x += 1) { var c = Utils.mergeColor(getImageColor(bar, x, y1), getImageColor(bar, x, y2)); var d = Utils.minMaxDiff(c); if (d > b1) { bright1++; } if (d > b2) { bright2++; } } releaseImage(bar); if (fc.g > fc.r) { if (poison) { this.gi.isPoison = true; } return (bright2 / barRect.tw * 100).toFixed(0); } else { if (poison) { this.gi.isPoison = false; } return (bright1 / barRect.tw * 100).toFixed(0); } } // MAP }, { key: 'goMap', value: function goMap(disX, disY) { var max = 20000; if (Math.abs(disX) < 30 && Math.abs(disY) < 30) { return; } var timeL = 3000;var timeR = 3000;var timeT = 3000;var timeB = 3000; if (disX >= 0 && disX > 30) { timeR += Math.min(1600 * Math.abs(disX) / 10, max); } else if (disX < 0 && disX < -30) { timeL += Math.min(1600 * Math.abs(disX) / 10, max); } if (disY >= 0 && disY > 30) { timeB += Math.min(1600 * Math.abs(disY) / 10, max); } else if (disY < 0 && disY < -30) { timeT += Math.min(1600 * Math.abs(disY) / 10, max); } var times = Math.ceil((timeL + timeR + timeT + timeB) / 24000); console.log('左', timeL, '右', timeR, '上', timeT, '下', timeB, times); var tl = Math.ceil(timeL / times); var tr = Math.ceil(timeR / times); var tt = Math.ceil(timeT / times); var tb = Math.ceil(timeB / times); this.gi.mapController.tapDown(); for (var t = 0; t < times && this._loop; t++) { if (timeL > 100) { console.log('往左移動', tl); this.gi.mapControllerL.moveTo(); this.gi.mapControllerL.moveTo(); this.safeSleep(tl); timeL -= tl; } if (timeT > 100) { console.log('往上移動', tt); this.gi.mapControllerT.moveTo(); this.gi.mapControllerT.moveTo(); this.safeSleep(tt); timeT -= tt; } if (timeR > 100) { console.log('往右移動', tr); this.gi.mapControllerR.moveTo(); this.gi.mapControllerR.moveTo(); this.safeSleep(tr); timeR -= tr; } if (timeB > 100) { console.log('往下移動', tb); this.gi.mapControllerB.moveTo(); this.gi.mapControllerB.moveTo(); this.safeSleep(tb); timeB -= tb; } } this.gi.mapController.tapUp(); } }, { key: 'recordCurrentLocation', value: function recordCurrentLocation() { var p = new Point(768, 360); var rect1 = new Rect(p.x - 120, p.y - 90, p.x - 30, p.y - 30); // left top var rect2 = new Rect(p.x + 30, p.y - 90, p.x + 120, p.y - 30); // right top var rect3 = new Rect(p.x - 120, p.y + 30, p.x - 30, p.y + 90); // left bottom var rect4 = new Rect(p.x + 30, p.y + 30, p.x + 120, p.y + 90); // right bottom var img1 = cropImage(this._img, rect1.tx, rect1.ty, rect1.tw, rect1.th); var img2 = cropImage(this._img, rect2.tx, rect2.ty, rect2.tw, rect2.th); var img3 = cropImage(this._img, rect3.tx, rect3.ty, rect3.tw, rect3.th); var img4 = cropImage(this._img, rect4.tx, rect4.ty, rect4.tw, rect4.th); saveImage(img1, this.localPath + '/mapRecord1.png'); saveImage(img2, this.localPath + '/mapRecord2.png'); saveImage(img3, this.localPath + '/mapRecord3.png'); saveImage(img4, this.localPath + '/mapRecord4.png'); releaseImage(img1);releaseImage(img2);releaseImage(img3);releaseImage(img4); } }, { key: 'getDiffRecordLocation', value: function getDiffRecordLocation() { var result = undefined; for (var i = 0; i < 3; i++) { result = this.findDiffRecordLocation(); if (result !== undefined) { break; } sleep(1000); this.refreshScreen(); } if (result === undefined) { console.log('無法找到紀錄點'); return { x: 0, y: 0 }; } return result; } }, { key: 'findDiffRecordLocation', value: function findDiffRecordLocation() { var p = new Point(768, 360); var images = [openImage(this.localPath + '/mapRecord1.png'), openImage(this.localPath + '/mapRecord2.png'), openImage(this.localPath + '/mapRecord3.png'), openImage(this.localPath + '/mapRecord4.png')]; var findXYs = []; for (var i = 0; i < images.length; i++) { if (images[i] === 0) { console.log('無法記錄地圖位置'); return; } var xy = findImage(this._img, images[i]); switch (i) { case 0: xy.x = p.x - xy.x / gRatioTarget - 120; xy.y = p.y - xy.y / gRatioTarget - 90; break; case 1: xy.x = p.x - xy.x / gRatioTarget + 30; xy.y = p.y - xy.y / gRatioTarget - 90; break; case 2: xy.x = p.x - xy.x / gRatioTarget - 120; xy.y = p.y - xy.y / gRatioTarget + 30; break; case 3: xy.x = p.x - xy.x / gRatioTarget + 30; xy.y = p.y - xy.y / gRatioTarget + 30; break; } findXYs.push(xy); releaseImage(images[i]); } var finalXY = undefined; for (var _i = 0; _i < findXYs.length; _i++) { var count = 0; for (var j = 0; j < findXYs.length; j++) { if (Math.abs(findXYs[_i].x - findXYs[j].x) < 30 && Math.abs(findXYs[_i].y - findXYs[j].y) < 30) { count++; } } if (count > 1) { finalXY = findXYs[_i]; } } if (finalXY !== undefined) { // console.log(JSON.stringify(findXYs)); console.log('\u4F4D\u7F6E\u76F8\u5DEE x\uFF1A' + finalXY.x + '\uFF0Cy\uFF1A' + finalXY.y); } return finalXY; } }, { key: 'slideMapSelector', value: function slideMapSelector(nth) { var itemHeight = 112 * gRatioDevice; // dev 1920 * 1080 => device item height var sDCX = gGameOffsetX + (this.gi.mapSelector.x1 + this.gi.mapSelector.x2) / 2 * gRatioDevice; var sDCY = gGameOffsetY + this.gi.mapSelector.y1 * gRatioDevice; var itemsY = [sDCY + itemHeight * 0.5, sDCY + itemHeight * 1.5, sDCY + itemHeight * 2.5, sDCY + itemHeight * 3.5, sDCY + itemHeight * 4.5]; // move to top var move2Top = function move2Top() { for (var i = 0; i < 3; i++) { tapDown(sDCX, itemsY[0], 10); tapUp(sDCX, itemsY[4], 10); sleep(1000); } }; var move4down = function move4down() { tapDown(sDCX, itemsY[4], 20); moveTo(sDCX, itemsY[4], 20); moveTo(sDCX, itemsY[3], 20); moveTo(sDCX, itemsY[2], 20); moveTo(sDCX, itemsY[1], 20); sleep(150); moveTo(sDCX, itemsY[0], 20); sleep(1500); tapUp(sDCX, itemsY[0], 20); }; move2Top(); sleep(500); for (var i = 0; i < Math.floor((nth - 1) / 4) && this._loop; i++) { move4down(); } tap(sDCX, itemsY[(nth - 1) % 4], 20); sleep(500); this.refreshScreen(); this.gi.mapMoveBtn.tap(); // this.waitForChangeScreen(0.92, 5000); // this.safeSleep(3000); if (!this._loop) { return; } // this.refreshScreen(); // const floorXY1 = findImage(this._img, this.images.floor1); // if (floorXY1.score > 0.8) { // const dXY = Utils.targetToDevice(floorXY1); // tap(dXY.x + 5, dXY.y + 5, 50); // sleep(1000); // this.gi.mapFloorBtn.tap(); // sleep(1000); // return; // } // const floorXY2 = findImage(this._img, this.images.floor2); // if (floorXY2.score > 0.8) { // const dXY = Utils.targetToDevice(floorXY2); // tap(dXY.x + 5, dXY.y + 5, 50); // sleep(1000); // this.gi.mapFloorBtn.tap(); // sleep(1000); // return; // } } }, { key: 'getImageNumber', value: function getImageNumber(img, numbers) { var maxLength = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 8; if (numbers.length != 10) { console.log('圖片數量應為 10'); return 0; } var results = []; for (var i = 0; i < 10; i++) { var nImg = numbers[i]; if (nImg == 0) { console.log('\u5716\u7247 ' + i + ' \u4E0D\u5B58\u5728'); return 0; } var rs = findImages(img, nImg, 0.95, maxLength, true); for (var k in rs) { rs[k].number = i; results.push(rs[k]); } } results.sort(function (a, b) { return b.score - a.score; }); results = results.slice(0, Math.min(maxLength, results.length)); results.sort(function (a, b) { return a.x - b.x; }); var numberSize = getImageSize(numbers[0]); var nw = numberSize.width; var imgSize = getImageSize(img); var iw = imgSize.width; var px = 0; var numberStr = ''; for (var _i2 in results) { var r = results[_i2]; if (r.x > p) { numberStr += r.number.toString(); p = r.x - 2; } } console.log('\u5716\u7247\u5927\u5C0F\u70BA ' + numberStr); return numberStr; } }]); return LineageM; }(); var DefaultConfig = { conditions: [ // {type: 'hp', op: -1, value: 80, btn: 0, interval: 1000}, // if hp < 60% use 3th button, like 瞬移 // {type: 'mp', op: 1, value: 50, btn: 1, interval: 1000}, // if hp < 30% use 8th button, like 回卷 // {type: 'mp', op: -1, value: 80, btn: 2, interval: 2000}, // if hp < 75% use 4th button, like 高治 // {type: 'mp', op: -1, value: 70, btn: 4, interval: 2000}, // if mp < 70% use 5th button, like 魂體 // {type: 'mp', op: 1, value: 50, btn: 1, interval: 8000}, // if mp > 80% use th button, like 三重矢, 光箭, 火球等 ], inHomeUseBtn: false, // if in safe region use 3th button, like 瞬移. beAttackedRandTeleport: true, dangerousGoHome: true, // if hp < 25%, go home, use button 8th autoAttack: false, autoReceiveReward: false, autoUseAntidote: false, // take an antidote for the poison, use six button goBackInterval: 0, // whether to go back to origin location, check location every n min autoBuyFirstSet: false, // 1 * 100, -1 => max mapSelect: 0, // move to nth map in safe region grabMonster: false, autoTeleport: true }; var lm = undefined; function testSpecialScreen() { // for special screen if (gDeviceWidth / gDeviceHeight > 1.78) { var _blackX = 0; var _img = getScreenshot(); for (var x = 0; x < gDeviceWidth; x++) { var color = getImageColor(_img, x, gDeviceHeight - 1); if (color.r === 0 && color.g === 0 && color.b === 0) { _blackX++; } else { break; } } releaseImage(_img); _blackX++; if (Math.abs(_blackX - gGameOffsetX) >= 2) { gGameOffsetX = _blackX; console.log("修正特殊螢幕位置", _blackX); sleep(1000); } } } function start(config) { console.log('📢 啟動腳本 📢'); testSpecialScreen(); console.log('螢幕位移', gGameOffsetX, gGameWidth); sleep(2000); if (typeof config === 'string') { config = JSON.parse(config); } if (lm !== undefined) { console.log('📢 腳本已啟動 📢'); return; } lm = new LineageM(config); lm.start(); lm.stop(); lm = undefined; console.log('📢 腳本已停止 📢'); } function stop() { if (lm == undefined) { return; } lm._loop = false; lm = undefined; console.log('📢 停止腳本中 📢'); } // start(DefaultConfig); // lm = new LineageM(DefaultConfig); // lm._loop = true; // lm.checkAndBuyItems(); // console.log(lm.isSafeRegionState()); // lm.goToMapPage(); // lm.slideMapSelector(5); // lm.buyItems(); // lm.checkAndAutoGetReward(); // for (var i= 0; i < 1; i++) { // lm.refreshScreen(); // const a = lm.gi.attackBtn.check(lm._img); // const b = lm.gi.killNumber.check(lm._img); // // lm.gi.killNumber.print(lm._img); // // console.log(b) // const c = lm.gi.autoPlayBtn.check(lm._img); // lm.gi.autoPlayBtn.print(lm._img); // console.log('attack Off', a, 'has kn', b, 'autoOff', c); // } // lm.findStore(); // for (let i = 0; i < 5; i++) { // const hp = lm.getHpPercent(); // // const mp = lm.getMpPercent(); // // const exp = lm.getExpPercent(); // lm.refreshScreen(); // console.log(hp); // } // lm.checkAndBuyItems(1); // lm.goToMapPage(); // const hp = lm.getHpPercent(); // const mp = lm.getMpPercent(); // const exp = lm.getExpPercent(); // console.log(hp, mp, exp); // lm.goToMapPage(); // lm._loop = true; // lm.recordCurrentLocation(); // var xy = lm.getDiffRecordLocation(); // lm.gi.menuOnBtn.tap(); // sleep(1000); // lm.goMap(-xy.x, -xy.y); // lm.cropAndSave('safeRegionType.png', lm.gi.regionTypeRect); // lm.updateGlobalState(); // lm.stop();
r2-studio/robotmon-scripts
scripts/com.r2studio.LineageM/index.js
JavaScript
apache-2.0
51,799
var CLIENT_ID = ''; var CLIENT_SECRET = ''; var OWNER = ""; var REPO = ""; /** * Manage Form Answer * Create a trigger by going to Resources > Current projet's triggers * Select function manageAnswer() and create a trigger at form submission */ function manageAnswer(e) { var form = e.source; var rep = { "Title":"", "Message":"", "Email":"" }; var itemResponses = e.response.getItemResponses(); for (var i = 0; i < itemResponses.length; i++) { var itemTitle = itemResponses[i].getItem().getTitle(); var itemResponse = itemResponses[i].getResponse(); rep[itemTitle] = itemResponse; Logger.log(itemTitle + ': ' + itemResponse ); } try{ var issue = submitIssue(rep); var body = "<p>Hi,</p>" +"<p>Thank you for submitting your issue, you can follow it on this page : <a href='"+issue.html_url+"'>link</a>.</p>" +"<p>Title : "+rep.Title+"<br>" +"Message : "+rep.Message+"</p>" +"Regards"; GmailApp.sendEmail(rep.Email, 'Issue posted on GitHub', '', { htmlBody:body, }); }catch(e){ GmailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Error issue submission', '', { htmlBody:JSON.stringify(rep), }); } } /** * Function to send issue to GitHub */ function submitIssue(data){ var service = getService(); if (service.hasAccess()) { var url = 'https://api.github.com/repos/'+OWNER+'/'+REPO+'/issues'; var bodyRequest = { "title":data.Title, "body":"_## Issue created anonymously for a user ##_\n"+data.Message }; var response = UrlFetchApp.fetch(url, { method : "post", headers: { Authorization: 'Bearer ' + service.getAccessToken() }, payload : JSON.stringify(bodyRequest) }); var result = JSON.parse(response.getContentText()); Logger.log(JSON.stringify(result, null, 2)); return result; } else { var authorizationUrl = service.getAuthorizationUrl(); Logger.log('Open the following URL and re-run the script: %s', authorizationUrl); } } /** * Authorizes and makes a request to the GitHub API. */ function run() { var service = getService(); if (service.hasAccess()) { var url = 'https://api.github.com/user/repos'; var response = UrlFetchApp.fetch(url, { headers: { Authorization: 'Bearer ' + service.getAccessToken() } }); var result = JSON.parse(response.getContentText()); Logger.log(JSON.stringify(result, null, 2)); } else { var authorizationUrl = service.getAuthorizationUrl(); Logger.log('Open the following URL and re-run the script: %s', authorizationUrl); } } /** * Configures the service. */ function getService() { return OAuth2.createService('GitHub') // Set the endpoint URLs. .setAuthorizationBaseUrl('https://github.com/login/oauth/authorize') .setTokenUrl('https://github.com/login/oauth/access_token') // Set the client ID and secret. .setClientId(CLIENT_ID) .setClientSecret(CLIENT_SECRET) // Set the name of the callback function that should be invoked to complete // the OAuth flow. .setCallbackFunction('authCallback') //scope for app .setScope('repo') // Set the property store where authorized tokens should be persisted. .setPropertyStore(PropertiesService.getUserProperties()) } /** * Handles the OAuth callback. */ function authCallback(request) { var service = getService(); var authorized = service.handleCallback(request); if (authorized) { return HtmlService.createHtmlOutput('Success!'); } else { return HtmlService.createHtmlOutput('Denied'); } }
St3ph-fr/my-apps-script-utils
anonymous-issues-github/Code.js
JavaScript
apache-2.0
3,674
"use strict"; let User = require("../../../../persistence").models.User; let debug = require("debug")("app:auth"); module.exports = (findUserEntity, createUserEntity, methodName) => { return (tokenA, tokenB, profile, done) => { return User.findOneQ(findUserEntity(profile)) .then((found) => found || User.createQ(createUserEntity(profile))) .then((user) => done(null, user)) .catch((err) => { debug(`error authenticating via ${methodName}`, err); done(err, null); }); }; };
atsid/drugfax-18f
server/initialization/sections/passport/strategies/common_oauth_callback.js
JavaScript
apache-2.0
571
/* Copyright 2016 ElasticBox All rights reserved. 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. */ class InstanceFiltersController { constructor($scope) { 'ngInject'; this.instancesFilteredByState = []; this.selectedOwners = []; this.filteredInstances = []; $scope.$watch('ctrl.selectedState', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.instancesToFilter', () => this.filterInstancesByState()); $scope.$watchCollection('ctrl.selectedOwners', () => this.filterInstancesByOwners()); $scope.$watchCollection('ctrl.instancesFilteredByState', () => this.filterInstancesByOwners()); } filterInstancesByState() { this.instancesFilteredByState = _.chain(this.instancesToFilter) .filter((x) => { return _.isUndefined(this.selectedState) || this.selectedState.state.kind === 'all' || this.selectedState.state.kind.toLowerCase() === (x.kind || '').toLowerCase() && _.isUndefined(this.selectedState.substate) || !_.isUndefined(this.selectedState.substate) && _.get(x, 'status.phase') === this.selectedState.substate.state; }) .value(); } filterInstancesByOwners() { this.filteredInstances = _.isEmpty(this.selectedOwners) ? this.instancesFilteredByState : _.filter(this.instancesFilteredByState, (x) => _.includes(this.selectedOwners, x.owner)); } } export default InstanceFiltersController;
ElasticBox/elastickube
src/ui/app/instances/ek-instance-filters/ek-instance-filters.controller.js
JavaScript
apache-2.0
2,031
var fs = require('fs'); fs.readFile('data/file1.txt', function (err, data) { console.log('Second'); }); console.log('First');
acoburn/interterm2014
async/async1.js
JavaScript
apache-2.0
130
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function drawSctDiagram(concept, parentDiv) { parentDiv.svg({settings: {width: '600px', height: '500px'}}); var svg = parentDiv.svg('get'); loadDefs(svg); rect1 = drawSctBox(parentDiv, 10, 10, "<span class='sct-box-id'>12676007<br></span>Fracture of radius", "sct-defined-concept"); circle1 = drawEquivalentNode(svg, 120,130); drawSubsumedByNode(svg, 120,230); drawSubsumesNode(svg, 120,330); drawSctBox(parentDiv, 100, 400, "&lt;slot&gt;", "sct-slot"); connectElements(svg, rect1, circle1, 'center', 'left'); circle2 = drawConjunctionNode(svg, 200, 130); connectElements(svg, circle1, circle2, 'right', 'left'); rect2 = drawSctBox(parentDiv, 250, 100, "<span class='sct-box-id'>65966004<br></span>Fracture of forearm", "sct-defined-concept"); connectElements(svg, circle2, rect2, 'bottom', 'left', 'ClearTriangle'); rect3 = drawSctBox(parentDiv, 250, 200, "<span class='sct-box-id'>429353004<br></span>Injury of radius", "sct-defined-concept"); connectElements(svg, circle2, rect3, 'bottom', 'left', 'ClearTriangle'); circle3 = drawAttributeGroupNode(svg, 250, 330); connectElements(svg, circle2, circle3, 'bottom', 'left'); circle4 = drawConjunctionNode(svg, 300, 330); connectElements(svg, circle3, circle4, 'right', 'left'); rect4 = drawSctBox(parentDiv, 350, 300, "<span class='sct-box-id'>116676008<br></span>Associated morphology", "sct-attribute"); connectElements(svg, circle4, rect4, 'right', 'left'); rect5 = drawSctBox(parentDiv, 550, 300, "<span class='sct-box-id'>72704001<br></span>Fracture", "sct-primitive-concept"); connectElements(svg, rect4, rect5, 'right', 'left'); rect6 = drawSctBox(parentDiv, 350, 400, "<span class='sct-box-id'>363698007<br></span>Finding site", "sct-attribute"); connectElements(svg, circle4, rect6, 'bottom', 'left'); rect7 = drawSctBox(parentDiv, 550, 400, "<span class='sct-box-id'>62413002<br></span>Bone structure of radius", "sct-primitive-concept"); connectElements(svg, rect6, rect7, 'right', 'left'); } function toggleIds() { $('.sct-box-id').toggle(); }
termMed/ihtsdo-daily-build-browser
js/diagramsTest.js
JavaScript
apache-2.0
2,348
var win = Ti.UI.createWindow({ backgroundColor:'white' }); win.open(); var GA = require('analytics.google'); //GA.optOut = true; GA.debug = true; GA.trackUncaughtExceptions = true; var tracker = GA.getTracker("UA-XXXXXX-X"); tracker.trackEvent({ category: "category", action: "test", label: "label", value: 1 }); tracker.trackSocial({ network: "facebook", action: "action", target: "target" }); tracker.trackTiming({ category: "", time: 10, name: "", label: "" }); tracker.trackScreen("Home"); var transaction = GA.makeTransaction({ id: "hi", tax: 0.6, shipping: 0, revenue: 24.99 * 0.7 }); transaction.addItem({ sku: "ABC123", name: "My Alphabet", category: "product category", price: 24.99, quantity: 1 }); tracker.trackTransaction(transaction);
Tipasha/DivinityCraft
modules/iphone/analytics.google/1.0/example/app.js
JavaScript
apache-2.0
772
var __window = window; var destringify = function(date) { if (date != null && 'string' === typeof(date)) return new Date(date); return date; } var stringify = function(date) { if (!date) return null; return dateFormat(date, "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"); } var stringreplaceall = function(target, search, replacement) { return target.split(search).join(replacement); }; var grabiframecontentdocument = function(id) { return document.getElementById(id).contentWindow.document; }; var grabcontentdocument = function(selector, parent) { return jQuery(selector, parent).get(0).contentWindow.document; };
KritikalFabric/corefabric.io
a2/static/vendor/unclassified/destringify.js
JavaScript
apache-2.0
629
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {PostOptions} from '@support/ui/component'; import {isAndroid} from '@support/utils'; class EditPostScreen { testID = { editPostScreen: 'edit_post.screen', closeEditPostButton: 'close.edit_post.button', messageInput: 'edit_post.message.input', saveButton: 'edit_post.save.button', }; editPostScreen = element(by.id(this.testID.editPostScreen)); closeEditPostButton = element(by.id(this.testID.closeEditPostButton)); messageInput = element(by.id(this.testID.messageInput)); saveButton = element(by.id(this.testID.saveButton)); toBeVisible = async () => { if (isAndroid()) { await expect(this.editPostScreen).toBeVisible(); } else { await expect(this.editPostScreen).toExist(); } return this.editPostScreen; }; open = async () => { // # Swipe up panel on Android if (isAndroid()) { await PostOptions.slideUpPanel.swipe('up'); } // # Open edit post screen await PostOptions.editAction.tap(); return this.toBeVisible(); }; close = async () => { await this.closeEditPostButton.tap(); await expect(this.editPostScreen).not.toBeVisible(); }; } const editPostScreen = new EditPostScreen(); export default editPostScreen;
mattermost/mattermost-mobile
detox/e2e/support/ui/screen/edit_post.js
JavaScript
apache-2.0
1,454
/*! * ${copyright} */ sap.ui.define([ "sap/base/Log", "sap/ui/model/odata/v4/lib/_GroupLock" ], function (Log, _GroupLock) { "use strict"; //********************************************************************************************* QUnit.module("sap.ui.model.odata.v4.lib._GroupLock", { beforeEach : function () { this.oLogMock = this.mock(Log); this.oLogMock.expects("warning").never(); this.oLogMock.expects("error").never(); } }); //********************************************************************************************* QUnit.test("unlocked, initialized", function (assert) { var oOwner = {/*owner*/}, oGroupLock = new _GroupLock("foo", oOwner); assert.strictEqual(oGroupLock.isCanceled(), false); assert.strictEqual(oGroupLock.getGroupId(), "foo"); assert.strictEqual(oGroupLock.oOwner, oOwner); assert.strictEqual(oGroupLock.isLocked(), false); assert.strictEqual(oGroupLock.waitFor("foo"), undefined); assert.strictEqual(oGroupLock.waitFor("bar"), undefined); }); //********************************************************************************************* QUnit.test("owner is mandatory", function (assert) { assert.throws(function () { return new _GroupLock("group"); }, new Error("Missing owner")); }); //********************************************************************************************* QUnit.test("locked", function (assert) { var oGroupLock, oOwner = {/*owner*/}, oPromise1, oPromise2; // code under test oGroupLock = new _GroupLock("foo", oOwner, true); assert.strictEqual(oGroupLock.getGroupId(), "foo"); assert.strictEqual(oGroupLock.oOwner, oOwner); assert.strictEqual(oGroupLock.isLocked(), true); // code under test oPromise1 = oGroupLock.waitFor("foo"); oPromise2 = oGroupLock.waitFor("foo"); assert.ok(oPromise1.isPending()); assert.ok(oPromise2.isPending()); // code under test assert.strictEqual(oGroupLock.waitFor("bar"), undefined); // code under test oGroupLock.unlock(); assert.ok(oPromise1.isFulfilled()); assert.ok(oPromise2.isFulfilled()); assert.notOk(oGroupLock.isLocked()); }); //********************************************************************************************* QUnit.test("multiple unlocks", function (assert) { var oGroupLock = new _GroupLock("group", {/*owner*/}); oGroupLock.unlock(); assert.throws(function () { oGroupLock.unlock(); }, new Error("GroupLock unlocked twice")); oGroupLock.unlock(true); // no error! }); //********************************************************************************************* QUnit.test("getUnlockedCopy", function (assert) { var oGroupLock1 = new _GroupLock("group", {/*owner*/}, true, true, 42), oGroupLock2; // code under test oGroupLock2 = oGroupLock1.getUnlockedCopy(); assert.strictEqual(oGroupLock2.getGroupId(), oGroupLock1.getGroupId()); assert.strictEqual(oGroupLock2.oOwner, oGroupLock1.oOwner); assert.strictEqual(oGroupLock2.isLocked(), false); assert.strictEqual(oGroupLock2.isModifying(), false); assert.strictEqual(oGroupLock2.getSerialNumber(), oGroupLock1.getSerialNumber()); }); //********************************************************************************************* QUnit.test("owner & toString", function (assert) { var oGroupLock, oOwner = { toString : function () { return "owner"; } }; oGroupLock = new _GroupLock("group", oOwner, true); assert.strictEqual(oGroupLock.toString(), "sap.ui.model.odata.v4.lib._GroupLock(group=group, owner=owner, locked)"); oGroupLock = new _GroupLock("group", oOwner, true, true); assert.strictEqual(oGroupLock.toString(), "sap.ui.model.odata.v4.lib._GroupLock(group=group, owner=owner, locked, modifying)"); oGroupLock = new _GroupLock("group", oOwner, false); assert.strictEqual(oGroupLock.oOwner, oOwner); assert.strictEqual(oGroupLock.toString(), "sap.ui.model.odata.v4.lib._GroupLock(group=group, owner=owner)"); oGroupLock = new _GroupLock("group", oOwner, false, undefined, 0); assert.strictEqual(oGroupLock.toString(), "sap.ui.model.odata.v4.lib._GroupLock(group=group, owner=owner, serialNumber=0)"); oGroupLock = new _GroupLock("group", oOwner, true, true, 0); assert.strictEqual(oGroupLock.toString(), "sap.ui.model.odata.v4.lib._GroupLock(group=group, owner=owner, locked, modifying," + " serialNumber=0)"); }); //********************************************************************************************* QUnit.test("constants", function (assert) { assert.strictEqual(_GroupLock.$cached.getGroupId(), "$cached"); assert.strictEqual(_GroupLock.$cached.isLocked(), false); assert.strictEqual(_GroupLock.$cached.isModifying(), false); assert.strictEqual(_GroupLock.$cached.oOwner, "sap.ui.model.odata.v4.lib._GroupLock"); // ensure that $cached can be unlocked several times _GroupLock.$cached.unlock(); _GroupLock.$cached.unlock(); }); //********************************************************************************************* QUnit.test("serial number", function (assert) { var oOwner = {/*owner*/}; assert.strictEqual(new _GroupLock("group", oOwner, true, true, 42).getSerialNumber(), 42); assert.strictEqual(new _GroupLock("group", oOwner, true).getSerialNumber(), Infinity); assert.strictEqual(new _GroupLock("group", oOwner, true, false, 0).getSerialNumber(), 0); }); //********************************************************************************************* [undefined, false, true].forEach(function (bModifying, i) { QUnit.test("modifying: " + bModifying, function (assert) { assert.strictEqual(new _GroupLock("group", {/*owner*/}, true, bModifying, 42).isModifying(), i === 2); }); }); //********************************************************************************************* QUnit.test("modifying: throws if not locked", function (assert) { assert.throws(function () { return new _GroupLock("group", {/*owner*/}, false, true, 42); }, new Error("A modifying group lock has to be locked")); }); //********************************************************************************************* QUnit.test("cancel w/o function", function (assert) { var oGroupLock = new _GroupLock("group", {/*owner*/}, true); this.mock(oGroupLock).expects("unlock").withExactArgs(true); // code under test oGroupLock.cancel(); assert.ok(oGroupLock.isCanceled()); }); //********************************************************************************************* QUnit.test("cancel w/ function", function (assert) { var fnCancel = sinon.spy(), oGroupLock = new _GroupLock("group", {/*owner*/}, true, false, undefined, fnCancel); assert.strictEqual(oGroupLock.fnCancel, fnCancel); sinon.assert.notCalled(fnCancel); this.mock(oGroupLock).expects("unlock").withExactArgs(true); // code under test oGroupLock.cancel(); assert.ok(oGroupLock.isCanceled()); sinon.assert.calledOnce(fnCancel); sinon.assert.calledWithExactly(fnCancel); oGroupLock.cancel(); sinon.assert.calledOnce(fnCancel); // cancel function must not be called again }); });
SAP/openui5
src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/lib/_GroupLock.qunit.js
JavaScript
apache-2.0
7,157
/*分页JS*/ var rsss = false; $(function () { $(".leftNav_side").css("min-height", $(".leftNav_side").height()); $(window).resize(function () { $(".leftNav_side").height($(window).height()); }).trigger("resize");//左侧菜单高度自适应,但是保留内容最小高度 //切换左导航一级菜单 $(".Nav_lvl dt").click(function () { $(this).parent().siblings().find("dd").hide(); $(this).siblings().slideDown(300); }); //切换左导航二级菜单 $(".Nav_lvl dd").click(function () { $(".Nav_lvl dd").removeClass(); $(this).addClass("Nav_lvl_dd_on"); }); //切换顶部导航 $(".topNav_ul li").click(function () { $(this).addClass("topNav_li_on").siblings().removeClass(); }); if(Number($("[name='totalCount']").val()) > 0){ var pages = [], totalPage = Number($("[name='totalPage']").val()), totalCount = Number($("[name='totalCount']").val()), currentPage = Number($("[name='pageNum']").val())==0 ? 1 :Number($("[name='pageNum']").val()); pages[pages.length] = ' <th colspan="100"><i>当前第'+currentPage+'页/共'+totalPage+'页</i><i>共'+totalCount+'条记录</i>'; if (currentPage == 1) { pages[pages.length] = ' <span>首页</span><span>上一页</span>'; } else { pages[pages.length] = ' <a class="first" href="#">首页</a><a class="prev" href="#">上一页</a>'; } if (currentPage < 5) { for (var i = 1; i <= (totalPage > 10 ? 10 : totalPage); i++) { if (currentPage == i) pages[pages.length] = '<span class="sel">' + i + '</span>'; else pages[pages.length] = '<a href="#">' + i + '</a>'; } } else if (currentPage >= totalPage - 5) for (var i = totalPage - 9; i <= totalPage; i++) { if (currentPage == i) pages[pages.length] = '<span class="sel">' + i + '</span>'; else pages[pages.length] = '<a href="#">' + i + '</a>'; } else { for (var i = currentPage - 5; i <= currentPage + 4; i++) { if (currentPage == i) pages[pages.length] = '<span class="sel">' + i + '</span>'; else pages[pages.length] = '<a href="#">' + i + '</a>'; } } if (currentPage < totalPage) { pages[pages.length] = '<a class="next" href="#">下一页</a><a class="last" href="#">尾页</a>'; } else { pages[pages.length] = '<span>下一页</span><span>尾页</span>'; } pages[pages.length] = '<input type="text" name="page" value="'+currentPage+'"/>'; pages[pages.length] = '<input type="button" value="跳转" class="btn_violet" />'; $(".pager").html(pages.join("")).find("a:not(.next):not(.prev)").click(function(){ $("[name='currentPage']").val($(this).text()); $("#pagerForm").submit(); }); $(".pager").find("a.first").click(function(){ num = 1; $("[name='currentPage']").val(num); $("#pagerForm").submit(); }); $(".pager").find("a.prev").click(function(){ num = Number($("[name='currentPage']").val()) - 1 < 0 ? 0 :Number($("[name='currentPage']").val()) - 1; $("[name='currentPage']").val(num); $("#pagerForm").submit(); }); $(".pager").find("a.next").click(function(){ $("[name='currentPage']").val(Number($("[name='currentPage']").val()) + 1); $("#pagerForm").submit(); }); $(".pager").find("a.last").click(function(){ num = Number($("[name='totalPage']").val()); $("[name='currentPage']").val(num); $("#pagerForm").submit(); }); $(".pager").find("input.btn_violet").click(function(){ num = Number($("[name='page']").val()); if(num > totalPage){ num = totalPage; } else if(num < 1){ num = 1; } $("[name='currentPage']").val(num); $("#pagerForm").submit(); }); } });
iminto/baicai
src/main/webapp/manage/js/navleft.js
JavaScript
apache-2.0
4,114
import { store } from '../store.js'; import { selectGameCurrentState, selectGameChest, selectGameName } from '../selectors.js'; import { deepCopy, getProperty, setPropertyInClone } from '../util.js'; export const UPDATE_GAME_ROUTE = 'UPDATE_GAME_ROUTE'; export const UPDATE_GAME_STATIC_INFO = "UPDATE_GAME_STATIC_INFO"; export const UPDATE_GAME_CURRENT_STATE = "UPDATE_GAME_CURRENT_STATE"; export const updateGameRoute = (pageExtra) => { const pieces = pageExtra.split("/"); //remove the trailing slash if (!pieces[pieces.length - 1]) pieces.pop(); if (pieces.length != 2) { console.warn("URL for game didn't have expected number of pieces"); return null; } return { type: UPDATE_GAME_ROUTE, name: pieces[0], id: pieces[1], } } export const updateGameStaticInfo = (chest, playersInfo, hasEmptySlots, open, visible, isOwner) => { return { type: UPDATE_GAME_STATIC_INFO, chest, playersInfo, hasEmptySlots, open, visible, isOwner } } //currentState should be the unexpanded state (as passed in from server). Timer //infos should be game.ActiveTimers. originalWallClockTime should be the time //the state was received from the server (so that we can compute how much time //has elapsed from what the server reported). This will install the currentState //in, but also set up callbacks to update timer.TimeLeft for any timers in the //state automatically. export const installGameState = (currentState, timerInfos, originalWallClockTime) => (dispatch, getState) => { const state = getState(); const chest = selectGameChest(state); const gameName = selectGameName(state); let [expandedState, pathsToTick] = expandState(currentState, timerInfos, chest, gameName); dispatch(updateGameState(expandedState, pathsToTick, originalWallClockTime)); if (pathsToTick.length) window.requestAnimationFrame(doTick); } const updateGameState = (expandedCurrentState, pathsToTick, originalWallClockTime) => { return { type: UPDATE_GAME_CURRENT_STATE, currentState: expandedCurrentState, pathsToTick, originalWallClockTime } } //return [expandedState, pathsToTick] const expandState = (currentState, timerInfos, chest, gameName) => { //Takes the currentState and returns an object where all of the Stacks are replaced by actual references to the component they reference. var pathsToTick = []; let newState = deepCopy(currentState); expandLeafState(newState, newState.Game, ["Game"], pathsToTick, timerInfos, chest, gameName) for (var i = 0; i < newState.Players.length; i++) { expandLeafState(newState, newState.Players[i], ["Players", i], pathsToTick, timerInfos, chest, gameName) } return [newState, pathsToTick]; } const expandLeafState = (wholeState, leafState, pathToLeaf, pathsToTick, timerInfos, chest, gameName) => { //Returns an expanded version of leafState. leafState should have keys that are either bools, floats, strings, or Stacks. var entries = Object.entries(leafState); for (var i = 0; i < entries.length; i++) { let item = entries[i]; let key = item[0]; let val = item[1]; //Note: null is typeof "object" if (val && typeof val == "object") { if (val.Deck) { expandStack(val, wholeState, chest, gameName); } else if (val.IsTimer) { expandTimer(val, pathToLeaf.concat([key]), pathsToTick, timerInfos); } } } //Copy in Player computed state if it exists, for convenience. Do it after expanding properties if (pathToLeaf && pathToLeaf.length == 2 && pathToLeaf[0] == "Players") { if (wholeState.Computed && wholeState.Computed.Players && wholeState.Computed.Players.length) { leafState.Computed = wholeState.Computed.Players[pathToLeaf[1]]; } } } const expandStack = (stack, wholeState, chest, gameName) => { if (!stack.Deck) { //Meh, I guess it's not a stack return; } let components = Array(stack.Indexes.length).fill(null); for (var i = 0; i < stack.Indexes.length; i++) { let index = stack.Indexes[i]; if (index == -1) { components[i] = null; continue; } //TODO: this should be a constant if(index == -2) { //TODO: to handle this appropriately we'd need to know how to //produce a GenericComponent for each Deck clientside. components[i] = {}; } else { components[i] = componentForDeckAndIndex(stack.Deck, index, wholeState, chest); } if (stack.IDs) { components[i].ID = stack.IDs[i]; } components[i].Deck = stack.Deck; components[i].GameName = gameName; } stack.GameName = gameName; stack.Components = components; } const expandTimer = (timer, pathToLeaf, pathsToTick, timerInfo) => { //Always make sure these default to a number so databinding can use them. timer.TimeLeft = 0; timer.originalTimeLeft = 0; if (!timerInfo) return; let info = timerInfo[timer.ID]; if (!info) return; timer.TimeLeft = info.TimeLeft; timer.originalTimeLeft = timer.TimeLeft; pathsToTick.push(pathToLeaf); } const componentForDeckAndIndex = (deckName, index, wholeState, chest) => { let deck = chest.Decks[deckName]; if (!deck) return null; let result = {...deck[index]}; if (wholeState && wholeState.Components) { if (wholeState.Components[deckName]) { result.DynamicValues = wholeState.Components[deckName][index]; } } return result } const doTick = () => { tick(); const state = store.getState(); const pathsToTick = state.game ? state.game.pathsToTick : []; if (pathsToTick.length > 0) { window.requestAnimationFrame(doTick); } } const tick = () => { const state = store.getState(); const currentState = selectGameCurrentState(state); if (!currentState) return; const pathsToTick = state.game ? state.game.pathsToTick : []; const originalWallClockStartTime = state.game ? state.game.originalWallClockTime : 0; if (pathsToTick.length == 0) return; let newPaths = []; //We'll use util.setPropertyInClone, so the newState will diverge from //currentState as we write to it, but can start out the same. let newState = currentState; for (let i = 0; i < pathsToTick.length; i++) { let currentPath = pathsToTick[i]; let timer = getProperty(newState, currentPath); let now = Date.now(); let difference = now - originalWallClockStartTime; let result = Math.max(0, timer.originalTimeLeft - difference); newState = setPropertyInClone(newState, currentPath.concat(["TimeLeft"]), result); //If we still have time to tick on this, then make sure it's still //in the list of things to tick. if (timer.TimeLeft > 0) { newPaths.push(currentPath); } } if (newPaths.length == pathsToTick.length) { //If the length of pathsToTick didn't change, don't change it, so that //strict equality matches in the new state will work. newPaths = pathsToTick; } store.dispatch(updateGameState(newState, newPaths, originalWallClockStartTime)); }
jkomoros/boardgame
server/static/src/actions/game.js
JavaScript
apache-2.0
7,052
/** * Copyright 2015 Wouter van Heeswijk * * 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. */ define( ["geometries/loader", "json!assets/triangle.json"], function (loader, asset) { return loader.load(asset); } );
woutervh-/csgjson
js/assets/triangle.js
JavaScript
apache-2.0
740
import React from 'react'; import PropTypes from 'prop-types'; import Preselect from 'material-ui-icons/ThumbUp'; import IconWithTooltipButton from '../../common/iconWithTooltipButton'; import withApplicationStatusChange from '../../common/hoc/withApplicationStatusChange'; import { APPLICATION_STATUSES } from '../../../helpers/constants'; const messages = { text: 'Preselect', }; const PreselectButton = (props) => { const { id, status, changeStatus, ...other } = props; return ( <IconWithTooltipButton icon={<Preselect />} name="preselect" text={messages.text} onClick={(event) => { event.stopPropagation(); changeStatus(id); }} {...other} /> ); }; PreselectButton.propTypes = { id: PropTypes.oneOfType([ PropTypes.array, PropTypes.string, ]), status: PropTypes.string, changeStatus: PropTypes.func, }; export default withApplicationStatusChange(APPLICATION_STATUSES.PRE)(PreselectButton);
unicef/un-partner-portal
frontend/src/components/eois/buttons/preselectButton.js
JavaScript
apache-2.0
981
define([ "less!theme/textmate.less" ], function(cssContent) { return { 'isDark': false, 'cssClass': "ace-tm", 'cssText': cssContent } });
cethap/cbcompiled
addons/cb.files.editor/theme/textmate.js
JavaScript
apache-2.0
174
function PreferencesAssistant() { /* this is the creator function for your scene assistant object. It will be passed all the additional parameters (after the scene name) that were passed to pushScene. The reference to the scene controller (this.controller) has not be established yet, so any initialization that needs the scene controller should be done in the setup function below. */ this.cookie = new Mojo.Model.Cookie('prefs'); this.model = this.cookie.get(); if (!this.model) { this.model = { useOldInterface: false }; this.cookie.put(this.model); } } PreferencesAssistant.prototype.setup = function() { /* this function is for setup tasks that have to happen when the scene is first created */ /* use Mojo.View.render to render view templates and add them to the scene, if needed */ /* setup widgets here */ this.controller.setupWidget( 'oldInterfaceToggle', { modelProperty: 'useOldInterface', disabledProperty: 'oldInterfaceToggleDisabled' }, this.model ); /* add event handlers to listen to events from widgets */ Mojo.Event.listen( this.controller.get('oldInterfaceToggle'), Mojo.Event.propertyChange, this.handlePrefsChange.bind(this) ); }; PreferencesAssistant.prototype.handlePrefsChange = function(event) { this.cookie.put(this.model); }; PreferencesAssistant.prototype.activate = function(event) { /* put in event handlers here that should only be in effect when this scene is active. For example, key handlers that are observing the document */ }; PreferencesAssistant.prototype.deactivate = function(event) { /* remove any event handlers you added in activate and do any other cleanup that should happen before this scene is popped or another scene is pushed on top */ }; PreferencesAssistant.prototype.cleanup = function(event) { /* this function should do any cleanup needed before the scene is destroyed as a result of being popped off the scene stack */ Mojo.Event.stopListening( this.controller.get('oldInterfaceToggle'), Mojo.Event.propertyChange, this.handlePrefsChange.bind(this) ); };
brettcannon/oplop
WebOS/app/assistants/preferences-assistant.js
JavaScript
apache-2.0
2,299
"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 q = require('q'); var util = require('util'); var events_1 = require('events'); var helper = require('./util'); var logger2_1 = require('./logger2'); var driverProviders_1 = require('./driverProviders'); var plugins_1 = require('./plugins'); var protractor = require('./protractor'), webdriver = require('selenium-webdriver'); var logger = new logger2_1.Logger('runner'); /* * Runner is responsible for starting the execution of a test run and triggering * setup, teardown, managing config, etc through its various dependencies. * * The Protractor Runner is a node EventEmitter with the following events: * - testPass * - testFail * - testsDone * * @param {Object} config * @constructor */ var Runner = (function (_super) { __extends(Runner, _super); function Runner(config) { _super.call(this); /** * Responsible for cleaning up test run and exiting the process. * @private * @param {int} Standard unix exit code */ this.exit_ = function (exitCode) { return helper .runFilenameOrFn_(this.config_.configDir, this.config_.onCleanUp, [exitCode]) .then(function (returned) { if (typeof returned === 'number') { return returned; } else { return exitCode; } }); }; this.config_ = config; if (config.v8Debug) { // Call this private function instead of sending SIGUSR1 because Windows. process['_debugProcess'](process.pid); } if (config.nodeDebug) { process['_debugProcess'](process.pid); var flow = webdriver.promise.controlFlow(); flow.execute(function () { var nodedebug = require('child_process').fork('debug', ['localhost:5858']); process.on('exit', function () { nodedebug.kill('SIGTERM'); }); nodedebug.on('exit', function () { process.exit(1); }); }, 'start the node debugger'); flow.timeout(1000, 'waiting for debugger to attach'); } if (config.capabilities && config.capabilities.seleniumAddress) { config.seleniumAddress = config.capabilities.seleniumAddress; } this.loadDriverProvider_(config); this.setTestPreparer(config.onPrepare); } /** * Registrar for testPreparers - executed right before tests run. * @public * @param {string/Fn} filenameOrFn */ Runner.prototype.setTestPreparer = function (filenameOrFn) { this.preparer_ = filenameOrFn; }; /** * Executor of testPreparer * @public * @return {q.Promise} A promise that will resolve when the test preparers * are finished. */ Runner.prototype.runTestPreparer = function () { return helper.runFilenameOrFn_(this.config_.configDir, this.preparer_); }; /** * Grab driver provider based on type * @private * * Priority * 1) if directConnect is true, use that * 2) if seleniumAddress is given, use that * 3) if a Sauce Labs account is given, use that * 4) if a seleniumServerJar is specified, use that * 5) try to find the seleniumServerJar in protractor/selenium */ Runner.prototype.loadDriverProvider_ = function (config) { this.config_ = config; if (this.config_.directConnect) { this.driverprovider_ = new driverProviders_1.Direct(this.config_); } else if (this.config_.seleniumAddress) { if (this.config_.seleniumSessionId) { this.driverprovider_ = new driverProviders_1.AttachSession(this.config_); } else { this.driverprovider_ = new driverProviders_1.Hosted(this.config_); } } else if (this.config_.browserstackUser && this.config_.browserstackKey) { this.driverprovider_ = new driverProviders_1.BrowserStack(this.config_); } else if (this.config_.sauceUser && this.config_.sauceKey) { this.driverprovider_ = new driverProviders_1.Sauce(this.config_); } else if (this.config_.seleniumServerJar) { this.driverprovider_ = new driverProviders_1.Local(this.config_); } else if (this.config_.mockSelenium) { this.driverprovider_ = new driverProviders_1.Mock(this.config_); } else { this.driverprovider_ = new driverProviders_1.Local(this.config_); } }; /** * Getter for the Runner config object * @public * @return {Object} config */ Runner.prototype.getConfig = function () { return this.config_; }; /** * Get the control flow used by this runner. * @return {Object} WebDriver control flow. */ Runner.prototype.controlFlow = function () { return webdriver.promise.controlFlow(); }; /** * Sets up convenience globals for test specs * @private */ Runner.prototype.setupGlobals_ = function (browser_) { // Keep $, $$, element, and by/By under the global protractor namespace protractor.browser = browser_; protractor.$ = browser_.$; protractor.$$ = browser_.$$; protractor.element = browser_.element; protractor.by = protractor.By; if (!this.config_.noGlobals) { // Export protractor to the global namespace to be used in tests. global.browser = browser_; global.$ = browser_.$; global.$$ = browser_.$$; global.element = browser_.element; global.by = global.By = protractor.By; } global.protractor = protractor; if (!this.config_.skipSourceMapSupport) { // Enable sourcemap support for stack traces. require('source-map-support').install(); } // Required by dart2js machinery. // https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/sdk/lib/js/dart2js/js_dart2js.dart?spec=svn32943&r=32943#487 global.DartObject = function (o) { this.o = o; }; }; /** * Create a new driver from a driverProvider. Then set up a * new protractor instance using this driver. * This is used to set up the initial protractor instances and any * future ones. * * @param {?Plugin} The plugin functions * * @return {Protractor} a protractor instance. * @public */ Runner.prototype.createBrowser = function (plugins) { var _this = this; var config = this.config_; var driver = this.driverprovider_.getNewDriver(); var browser_ = protractor.wrapDriver(driver, config.baseUrl, config.rootElement, config.untrackOutstandingTimeouts); browser_.params = config.params; if (plugins) { browser_.plugins_ = plugins; } if (config.getPageTimeout) { browser_.getPageTimeout = config.getPageTimeout; } if (config.allScriptsTimeout) { browser_.allScriptsTimeout = config.allScriptsTimeout; } if (config.debuggerServerPort) { browser_.debuggerServerPort_ = config.debuggerServerPort; } if (config.useAllAngular2AppRoots) { browser_.useAllAngular2AppRoots(); } browser_.ready = driver.manage().timeouts().setScriptTimeout(config.allScriptsTimeout); browser_.getProcessedConfig = function () { return webdriver.promise.fulfilled(config); }; browser_.forkNewDriverInstance = function (opt_useSameUrl, opt_copyMockModules) { var newBrowser = _this.createBrowser(plugins); if (opt_copyMockModules) { newBrowser.mockModules_ = browser_.mockModules_; } if (opt_useSameUrl) { browser_.driver.getCurrentUrl().then(function (url) { newBrowser.get(url); }); } return newBrowser; }; browser_.restart = function () { // Note: because tests are not paused at this point, any async // calls here are not guaranteed to complete before the tests resume. _this.driverprovider_.quitDriver(browser_.driver); // Copy mock modules, but do not navigate to previous URL. browser_ = browser_.forkNewDriverInstance(false, true); _this.setupGlobals_(browser_); }; return browser_; }; /** * Final cleanup on exiting the runner. * * @return {q.Promise} A promise which resolves on finish. * @private */ Runner.prototype.shutdown_ = function () { return q.all(this.driverprovider_.getExistingDrivers().map(this.driverprovider_.quitDriver.bind(this.driverprovider_))); }; /** * The primary workhorse interface. Kicks off the test running process. * * @return {q.Promise} A promise which resolves to the exit code of the tests. * @public */ Runner.prototype.run = function () { var _this = this; var testPassed; var plugins = new plugins_1.Plugins(this.config_); var pluginPostTestPromises; var browser_; var results; if (this.config_.framework !== 'explorer' && !this.config_.specs.length) { throw new Error('Spec patterns did not match any files.'); } // 1) Setup environment // noinspection JSValidateTypes return this.driverprovider_.setupEnv() .then(function () { // 2) Create a browser and setup globals browser_ = _this.createBrowser(plugins); _this.setupGlobals_(browser_); return browser_.ready.then(browser_.getSession) .then(function (session) { logger.debug('WebDriver session successfully started with capabilities ' + util.inspect(session.getCapabilities())); }, function (err) { logger.error('Unable to start a WebDriver session.'); throw err; }); // 3) Setup plugins }) .then(function () { return plugins.setup(); // 4) Execute test cases }) .then(function () { // Do the framework setup here so that jasmine and mocha globals are // available to the onPrepare function. var frameworkPath = ''; if (_this.config_.framework === 'jasmine' || _this.config_.framework === 'jasmine2') { frameworkPath = './frameworks/jasmine.js'; } else if (_this.config_.framework === 'mocha') { frameworkPath = './frameworks/mocha.js'; } else if (_this.config_.framework === 'debugprint') { // Private framework. Do not use. frameworkPath = './frameworks/debugprint.js'; } else if (_this.config_.framework === 'explorer') { // Private framework. Do not use. frameworkPath = './frameworks/explorer.js'; } else if (_this.config_.framework === 'custom') { if (!_this.config_.frameworkPath) { throw new Error('When config.framework is custom, ' + 'config.frameworkPath is required.'); } frameworkPath = _this.config_.frameworkPath; } else { throw new Error('config.framework (' + _this.config_.framework + ') is not a valid framework.'); } if (_this.config_.restartBrowserBetweenTests) { var restartDriver = function () { browser_.restart(); }; _this.on('testPass', restartDriver); _this.on('testFail', restartDriver); } // We need to save these promises to make sure they're run, but we // don't // want to delay starting the next test (because we can't, it's just // an event emitter). pluginPostTestPromises = []; _this.on('testPass', function (testInfo) { pluginPostTestPromises.push(plugins.postTest(true, testInfo)); }); _this.on('testFail', function (testInfo) { pluginPostTestPromises.push(plugins.postTest(false, testInfo)); }); logger.debug('Running with spec files ' + _this.config_.specs); return require(frameworkPath).run(_this, _this.config_.specs); // 5) Wait for postTest plugins to finish }) .then(function (testResults) { results = testResults; return q.all(pluginPostTestPromises); // 6) Teardown plugins }) .then(function () { return plugins.teardown(); // 7) Teardown }) .then(function () { results = helper.joinTestLogs(results, plugins.getResults()); _this.emit('testsDone', results); testPassed = results.failedCount === 0; if (_this.driverprovider_.updateJob) { return _this.driverprovider_.updateJob({'passed': testPassed}) .then(function () { return _this.driverprovider_.teardownEnv(); }); } else { return _this.driverprovider_.teardownEnv(); } // 8) Let plugins do final cleanup }) .then(function () { return plugins.postResults(); // 9) Exit process }) .then(function () { var exitCode = testPassed ? 0 : 1; return _this.exit_(exitCode); }) .fin(function () { return _this.shutdown_(); }); }; return Runner; }(events_1.EventEmitter)); exports.Runner = Runner;
ionutbarau/petstore
petstore-app/src/main/resources/static/node_modules/protractor/built/runner.js
JavaScript
apache-2.0
15,123
'use strict'; import React, {Component, PropTypes} from 'react'; import ReactNative, {Animated, Easing} from 'react-native'; var Animation = require('../Popover/Animation'); class TooltipAnimation extends Animation { prepareStyle() { const { placement, open, } = this.props; const tooltipPlacement = placement.split('-'); const verticalPlacement = tooltipPlacement [0]; const horizontalPlacement = tooltipPlacement[1]; const offset = verticalPlacement === 'bottom' ? 5 : -5; const {anim} = this.state; return { opacity: this.interpolate(1), transform: [ {translateY: open ? this.interpolate(offset, -offset) : -10000}, ], }; } } module.exports = TooltipAnimation;
glinjy/react-native-apex-ui
src/Tooltip/TooltipAnimation.js
JavaScript
apache-2.0
728
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateService', 'ProjectsService', 'QuotaService', 'SecurityCheckService', 'TaskList', 'keyValueEditorUtils', ProcessTemplate ], controllerAs: '$ctrl', bindings: { template: '<', project: '<', onProjectSelected: '<', availableProjects: '<', prefillParameters: '<', isDialog: '<' }, templateUrl: 'views/directives/process-template.html' }); function ProcessTemplate($filter, $q, $scope, $uibModal, APIDiscovery, APIService, DataService, Navigate, NotificationsService, ProcessedTemplateService, ProjectsService, QuotaService, SecurityCheckService, TaskList, keyValueEditorUtils) { var ctrl = this; var context; var displayName = $filter('displayName'); var humanize = $filter('humanize'); ctrl.noProjectsCantCreate = false; function getHelpLinks(template) { var helpLinkName = /^helplink\.(.*)\.title$/; var helpLinkURL = /^helplink\.(.*)\.url$/; var helpLinks = {}; for (var attr in template.annotations) { var match = attr.match(helpLinkName); var link; if (match) { link = helpLinks[match[1]] || {}; link.title = template.annotations[attr]; helpLinks[match[1]] = link; } else { match = attr.match(helpLinkURL); if (match) { link = helpLinks[match[1]] || {}; link.url = template.annotations[attr]; helpLinks[match[1]] = link; } } } return helpLinks; } ctrl.$onInit = function() { ctrl.labels = []; // Make a copy of the template to avoid modifying the original if it's cached. ctrl.template = angular.copy(ctrl.template); ctrl.templateDisplayName = displayName(ctrl.template); ctrl.selectedProject = ctrl.project; $scope.$watch('$ctrl.selectedProject.metadata.name', function() { ctrl.projectNameTaken = false; }); $scope.$on('no-projects-cannot-create', function() { ctrl.noProjectsCantCreate = true; }); setTemplateParams(); }; var processedResources; var createResources = function() { var titles = { started: "Creating " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject), success: "Created " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject), failure: "Failed to create " + ctrl.templateDisplayName + " in project " + displayName(ctrl.selectedProject) }; var helpLinks = getHelpLinks(ctrl.template); TaskList.clear(); TaskList.add(titles, helpLinks, ctrl.selectedProject.metadata.name, function() { var chain = $q.when(); var alerts = []; var hasErrors = false; _.each(processedResources, function(obj) { var groupVersionKind = APIDiscovery.toResourceGroupVersion(obj); chain = chain.then(function() { return DataService.create(groupVersionKind, null, obj, context) .then(function() { alerts.push({ type: "success", message: "Created " + humanize(obj.kind).toLowerCase() + " \"" + obj.metadata.name + "\" successfully. " }); }) .catch(function(failure) { hasErrors = true; alerts.push({ type: "error", message: "Cannot create " + humanize(obj.kind).toLowerCase() + " \"" + obj.metadata.name + "\". ", details: failure.message }); }); }); }); return chain.then(function() { return { alerts: alerts, hasErrors: hasErrors }; }); }); if (ctrl.isDialog) { $scope.$emit('templateInstantiated', { project: ctrl.selectedProject, template: ctrl.template }); } else { Navigate.toNextSteps(ctrl.templateDisplayName, ctrl.selectedProject.metadata.name); } }; var launchConfirmationDialog = function(alerts) { var modalInstance = $uibModal.open({ templateUrl: 'views/modals/confirm.html', controller: 'ConfirmModalController', resolve: { modalConfig: function() { return { alerts: alerts, title: "Confirm Creation", details: "We checked your application for potential problems. Please confirm you still want to create this application.", okButtonText: "Create Anyway", okButtonClass: "btn-danger", cancelButtonText: "Cancel" }; } } }); modalInstance.result.then(createResources); }; var alerts = {}; var hideNotificationErrors = function() { NotificationsService.hideNotification("process-template-error"); _.each(alerts, function(alert) { if (alert.id && (alert.type === 'error' || alert.type === 'warning')) { NotificationsService.hideNotification(alert.id); } }); }; var showWarningsOrCreate = function(result) { // Hide any previous notifications when form is resubmitted. hideNotificationErrors(); alerts = SecurityCheckService.getSecurityAlerts(processedResources, ctrl.selectedProject.metadata.name); // Now that all checks are completed, show any Alerts if we need to var quotaAlerts = result.quotaAlerts || []; alerts = alerts.concat(quotaAlerts); var errorAlerts = _.filter(alerts, {type: 'error'}); if (errorAlerts.length) { ctrl.disableInputs = false; _.each(alerts, function(alert) { alert.id = _.uniqueId('process-template-alert-'); NotificationsService.addNotification(alert); }); } else if (alerts.length) { launchConfirmationDialog(alerts); ctrl.disableInputs = false; } else { createResources(); } }; var createProjectIfNecessary = function() { if (_.has(ctrl.selectedProject, 'metadata.uid')) { return $q.when(ctrl.selectedProject); } var newProjName = ctrl.selectedProject.metadata.name; var newProjDisplayName = ctrl.selectedProject.metadata.annotations['new-display-name']; var newProjDesc = $filter('description')(ctrl.selectedProject); return ProjectsService.create(newProjName, newProjDisplayName, newProjDesc); }; var getProcessTemplateVersionForTemplate = function(template) { var rgv = APIService.objectToResourceGroupVersion(template); rgv.resource = 'processedtemplates'; return rgv; }; ctrl.createFromTemplate = function() { ctrl.disableInputs = true; createProjectIfNecessary().then(function(project) { ctrl.selectedProject = project; context = { namespace: ctrl.selectedProject.metadata.name }; ctrl.template.labels = keyValueEditorUtils.mapEntries(keyValueEditorUtils.compactEntries(ctrl.labels)); var rgv = getProcessTemplateVersionForTemplate(ctrl.template); DataService.create(rgv, null, ctrl.template, context).then( function(config) { // success // Cache template parameters and message so they can be displayed in the nexSteps page ProcessedTemplateService.setTemplateData(config.parameters, ctrl.template.parameters, config.message); processedResources = config.objects; QuotaService.getLatestQuotaAlerts(processedResources, context).then(showWarningsOrCreate); }, function(result) { // failure ctrl.disableInputs = false; var details; if (result.data && result.data.message) { details = result.data.message; } NotificationsService.addNotification({ id: "process-template-error", type: "error", message: "An error occurred processing the template.", details: details }); } ); }, function(result) { ctrl.disableInputs = false; if (result.data.reason === 'AlreadyExists') { ctrl.projectNameTaken = true; } else { var details; if (result.data && result.data.message) { details = result.data.message; } NotificationsService.addNotification({ id: "process-template-error", type: "error", message: "An error occurred creating the project.", details: details }); } }); }; // Only called when not in a dialog. ctrl.cancel = function() { hideNotificationErrors(); Navigate.toProjectOverview(ctrl.project.metadata.name); }; // When the process-template component is displayed in a dialog, the create // button is outside the component since it is in the wizard footer. Listen // for an event for when the button is clicked. $scope.$on('instantiateTemplate', ctrl.createFromTemplate); $scope.$on('$destroy', hideNotificationErrors); var shouldAddAppLabel = function() { // If the template defines its own app label, we don't need to add one at all if (_.get(ctrl.template, 'labels.app')) { return false; } // Otherwise check if an object in the template has an app label defined return !_.some(ctrl.template.objects, "metadata.labels.app"); }; function setTemplateParams() { if(ctrl.prefillParameters) { _.each(ctrl.template.parameters, function(parameter) { if (ctrl.prefillParameters[parameter.name]) { parameter.value = ctrl.prefillParameters[parameter.name]; } }); } ctrl.labels = _.map(ctrl.template.labels, function(value, key) { return { name: key, value: value }; }); if (shouldAddAppLabel()) { ctrl.labels.push({ name: 'app', value: ctrl.template.metadata.name }); } } } })();
openshift/origin-web-console
app/scripts/directives/processTemplate.js
JavaScript
apache-2.0
10,871
var zz = { Internal: { Local: { FS: { File: {}, Directory: {} } } } }; zz.Internal.Local.FS.File.read = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.read"); Ti.API.debug("ZZ.Internal.Local.FS.File.read [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var blob = file.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.read unable to read file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.read readed file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.write = function(path, content, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.write"); Ti.API.debug("ZZ.Internal.Local.FS.File.write [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); file.write(content); var blob = file.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.write unable to write file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.write written file [name : " + file.name + ", nativePath : " + file.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.copy = function(from, to, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.copy"); Ti.API.debug("ZZ.Internal.Local.FS.File.copy [from : " + from + ", to : " + to + "]"); var fromFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, from); var toFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, to); toFile.write(fromFile.read()); var blob = toFile.read(); if (null == blob) { var errorMessage = "ZZ.Internal.Local.FS.File.copy unable to copy file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return null; } Ti.API.debug("ZZ.Internal.Local.FS.File.copy copied to file [name : " + toFile.name + ", nativePath : " + toFile.nativePath + ", blob.mimeType : " + blob.mimeType + "]"); null != successCallback && successCallback(blob); return blob; }; zz.Internal.Local.FS.File.delete = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.File.delete"); Ti.API.debug("ZZ.Internal.Local.FS.File.delete [path : " + path + "]"); var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = file.deleteFile(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.File.delete unable to delete file [name : " + file.name + ", nativePath : " + file.nativePath + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.File.delete deleted file [name : " + file.name + ", nativePath : " + file.nativePath + "]"); null != successCallback && successCallback(); return true; }; zz.Internal.Local.FS.Directory.make = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.Directory.make"); Ti.API.debug("ZZ.Internal.Local.FS.Directory.make [path : " + path + "]"); var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = dir.createDirectory(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.Directory.make unable to create directory [name : " + dir.name + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.Directory.make created directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"); null != successCallback && successCallback(); return true; }; zz.Internal.Local.FS.Directory.remove = function(path, successCallback, errorCallback) { Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove"); var dir = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, path); var done = dir.deleteDirectory(); if (!done) { var errorMessage = "ZZ.Internal.Local.FS.Directory.remove unable to remove directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"; _manageError({ errorMessage: errorMessage }, errorCallback); return false; } Ti.API.debug("ZZ.Internal.Local.FS.Directory.remove removed directory [name : " + dir.name + ", nativePath : " + dir.nativePath + "]"); null != successCallback && successCallback(); return true; }; exports.ZZ = zz; exports.version = .2; var _manageError = function(error, errorCallback) { Ti.API.trace("ZZ.Internal.Local.FS._manageError"); Ti.API.error(error.errorMessage); null != errorCallback && errorCallback(error); };
Adriano72/ZiriZiri-Daniele
Resources/android/zz.api/zz.internal.local.fs.js
JavaScript
apache-2.0
5,650
/** Copyright 2011-2013 Here's A Hand Limited 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. **/ $(function() { $("input.yes").mouseover(function(){ $(this).attr('value','No'); $(this).removeClass('yes') $(this).addClass('no') }); $("input.yes").mouseout(function(){ $(this).attr('value','Yes'); $(this).removeClass('no') $(this).addClass('yes') }); $("input.no").mouseover(function(){ $(this).attr('value','Yes'); $(this).removeClass('no') $(this).addClass('yes') }); $("input.no").mouseout(function(){ $(this).attr('value','No'); $(this).removeClass('yes') $(this).addClass('no') }); });
Heres-A-Hand/Heres-A-Hand-Web
public_html/js/rollovers.js
JavaScript
apache-2.0
1,099
/** * @license Copyright 2018 Google Inc. All Rights Reserved. * 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. */ 'use strict'; const Runner = require('../../../../runner'); const EstimatedInputLatency = require('../../../../gather/computed/metrics/estimated-input-latency'); // eslint-disable-line const assert = require('assert'); const trace = require('../../../fixtures/traces/progressive-app-m60.json'); const devtoolsLog = require('../../../fixtures/traces/progressive-app-m60.devtools.log.json'); /* eslint-env jest */ describe('Metrics: EIL', () => { it('should compute a simulated value', async () => { const artifacts = Runner.instantiateComputedArtifacts(); const settings = {throttlingMethod: 'simulate'}; const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings}); expect({ timing: Math.round(result.timing), optimistic: Math.round(result.optimisticEstimate.timeInMs), pessimistic: Math.round(result.pessimisticEstimate.timeInMs), }).toMatchSnapshot(); }); it('should compute an observed value', async () => { const artifacts = Runner.instantiateComputedArtifacts(); const settings = {throttlingMethod: 'provided'}; const result = await artifacts.requestEstimatedInputLatency({trace, devtoolsLog, settings}); assert.equal(Math.round(result.timing * 10) / 10, 17.1); }); describe('#calculateRollingWindowEIL', () => { it('uses a 5s rolling window', async () => { const events = [ {start: 7500, end: 10000, duration: 2500}, {start: 10000, end: 15000, duration: 5000}, ]; assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 4516); }); it('handles continuous tasks', async () => { const events = []; const longTaskDuration = 100; const longTaskNumber = 1000; const shortTaskDuration = 1.1; const shortTaskNumber = 10000; for (let i = 0; i < longTaskNumber; i++) { const start = i * longTaskDuration; events.push({start: start, end: start + longTaskDuration, duration: longTaskDuration}); } const baseline = events[events.length - 1].end; for (let i = 0; i < shortTaskNumber; i++) { const start = i * shortTaskDuration + baseline; events.push({start: start, end: start + shortTaskDuration, duration: shortTaskDuration}); } assert.equal(EstimatedInputLatency.calculateRollingWindowEIL(events), 106); }); }); });
mixed/lighthouse
lighthouse-core/test/gather/computed/metrics/estimated-input-latency-test.js
JavaScript
apache-2.0
2,976
/******************************************************************************\ | | | package-version-file-types-view.js | | | |******************************************************************************| | | | This defines an dialog that is used to select directories within | | package versions. | | | |******************************************************************************| | Copyright (c) 2013 SWAMP - Software Assurance Marketplace | \******************************************************************************/ define([ 'jquery', 'underscore', 'backbone', 'marionette', 'text!templates/packages/info/versions/info/source/dialogs/package-version-file-types.tpl', 'scripts/registry', 'scripts/views/dialogs/error-view', 'scripts/views/files/file-types-list/file-types-list-view' ], function($, _, Backbone, Marionette, Template, Registry, ErrorView, FileTypesListView) { return Backbone.Marionette.LayoutView.extend({ // // attributes // regions: { fileTypes: '#file-types' }, events: { 'click #ok': 'onClickOk', 'keypress': 'onKeyPress' }, // // rendering methods // template: function() { return _.template(Template, { title: this.options.title, packagePath: this.options.packagePath }); }, onRender: function() { this.showFileTypes(); }, showFileTypes: function() { // fetch package version file types // var self = this; this.model.fetchFileTypes({ data: { 'dirname': this.options.packagePath }, // callbacks // success: function(data) { var collection = new Backbone.Collection(); for (var key in data) { collection.add(new Backbone.Model({ 'extension': key, 'count': data[key] })); } self.fileTypes.show( new FileTypesListView({ collection: collection }) ); }, error: function() { // show error dialog // Registry.application.modal.show( new ErrorView({ message: "Could not fetch file types for this package version." }) ); } }); }, // // event handling methods // onClickOk: function() { // apply callback // if (this.options.accept) { this.options.accept(); } }, onKeyPress: function(event) { // respond to enter key press // if (event.keyCode === 13) { this.onClickOk(); this.hide(); } } }); });
OWASP/open-swamp
registry-web-server/var/www/html/scripts/views/packages/info/versions/info/source/dialogs/package-version-file-types-view.js
JavaScript
apache-2.0
2,896
define(function (require) { var app = angular.module('easyCodeApp', ['ngRoute', 'ui.bootstrap', 'ui.codemirror', 'vtortola.ng-terminal', 'flow']); // controller for header actions app.controller('headerController', function($scope){ // add header properties for phone support $scope.header = { isCollapsed : true }; }); /** * lazy loading configuration */ var config = require('routes'); var dependencyResolverFor = require('appDir/services/dependencyResolverFor'); /** * lazy routing configuration */ app.config( [ '$routeProvider', '$locationProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', function($routeProvider, $locationProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, terminalConfigurationProvider) { // allow blob link $compileProvider.aHrefSanitizationWhitelist(/^\s*(blob):/); app.controller = function(name, constructor) { $controllerProvider.register(name, constructor); return this; } app.directive = function(name, constructor) { $compileProvider.directive(name, constructor); return this; } app.filter = function(name, constructor) { $filterProvider.register(name, constructor); return this; } app.factory = function(name, constructor) { $provide.factory(name, constructor); return this; } app.service = function (name, constructor) { $provide.service(name, constructor); return this; } // $locationProvider.html5Mode(true); if(config.routes !== undefined) { angular.forEach(config.routes, function(route, path) { // default template has the same name as the controller route.templateUrl = route.templateUrl || route.controller+'.html'; $routeProvider.when( path, { templateUrl:route.templateUrl, resolve:dependencyResolverFor(route.dependencies), controller : route.controller } ); }); } if(config.defaultRoutePaths !== undefined) { $routeProvider.otherwise({redirectTo:config.defaultRoutePaths}); } } ]); /** * configuration for terminal emlator */ app.config([ 'terminalConfigurationProvider', function(terminalConfigurationProvider){ terminalConfigurationProvider.config('vintage').outputDelay = 10; terminalConfigurationProvider.config('vintage').allowTypingWriteDisplaying = false; } ]); app.init = function(){ // lancement de l'application angular.bootstrap(document, ['easyCodeApp']); } return app; });
deblockt/deblockt.github.io
javascripts/app.js
JavaScript
apache-2.0
3,056
(function() { var port = 8080; if (window.location.search) { var params = window.location.search.match(/port=(\d+)/); if (params) { port = params[1]; } // How often to poll params = window.location.search.match(/pollInterval=(\d+)/); if (params) { window.JOLOKIA_POLL_INTERVAL = parseInt(params[1]); } } window.JOLOKIA_URL = "http://localhost:" + port + "/jolokia"; })();
jolokia-org/jolokia-client-javascript
test/qunit/js/jolokia-env.js
JavaScript
apache-2.0
470
/** * Symbol Art Editor * * @author malulleybovo (since 2021) * @license GNU General Public License v3.0 * * @licstart The following is the entire license notice for the * JavaScript code in this page. * * Copyright (C) 2021 Arthur Malulley B. de O. * * * The JavaScript code in this page is free software: you can * redistribute it and/or modify it under the terms of the GNU * General Public License (GNU GPL) as published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. The code is distributed WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details. * * As additional permission under GNU GPL version 3 section 7, you * may distribute non-source (e.g., minimized or compacted) forms of * that code without the copy of the GNU GPL normally required by * section 4, provided you include this license notice and a URL * through which recipients can access the Corresponding Source. * * @licend The above is the entire license notice * for the JavaScript code in this page. * */ class UIAsset extends UIView { get viewPath() { return 'res/templates/asset.html' } _onTap = null; get onTap() { return this._onTap } set onTap(value) { if (typeof value !== 'function' && value !== null) return; this._onTap = value; } get assetFilePath() { return this.view.attr('src'); } _resourceLoaded = false; get loaded() { return this.view instanceof jQuery && this.view[0] instanceof HTMLElement && this._resourceLoaded; } constructor({ filePath = null } = {}) { super(); let path = filePath; this.didLoad(_ => { this.view.on('load', _ => { this._resourceLoaded = true; }); this.view.attr('src', path); this.gestureRecognizer = new UITapGestureRecognizer({ targetHtmlElement: this.view[0], onTap: () => { if (this._onTap) { this._onTap(this); } } }); }); } }
malulleybovo/SymbolArtEditorOnline
src/components/ui/UIAsset.js
JavaScript
apache-2.0
2,250
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * 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. */ 'use strict'; const argv = require('minimist')(process.argv.slice(2)); const colors = require('ansi-colors'); const log = require('fancy-log'); const wrappers = require('./compile-wrappers'); const {VERSION: internalRuntimeVersion} = require('./internal-version'); /** * @enum {string} */ const TYPES = (exports.TYPES = { AD: '_base_ad', MEDIA: '_base_media', MISC: '_base_misc', }); /** * Used to generate top-level JS build targets */ exports.jsBundles = { 'polyfills.js': { srcDir: './src/', srcFilename: 'polyfills.js', destDir: './build/', minifiedDestDir: './build/', }, 'alp.max.js': { srcDir: './ads/alp/', srcFilename: 'install-alp.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'alp.max.js', includePolyfills: true, minifiedName: 'alp.js', }, }, 'examiner.max.js': { srcDir: './src/examiner/', srcFilename: 'examiner.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'examiner.max.js', includePolyfills: true, minifiedName: 'examiner.js', }, }, 'ww.max.js': { srcDir: './src/web-worker/', srcFilename: 'web-worker.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'ww.max.js', minifiedName: 'ww.js', includePolyfills: true, }, }, 'integration.js': { srcDir: './3p/', srcFilename: 'integration.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'f.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: true, }, }, 'ampcontext-lib.js': { srcDir: './3p/', srcFilename: 'ampcontext-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'ampcontext-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'iframe-transport-client-lib.js': { srcDir: './3p/', srcFilename: 'iframe-transport-client-lib.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'iframe-transport-client-v0.js', externs: ['./ads/ads.extern.js'], include3pDirectories: true, includePolyfills: false, }, }, 'recaptcha.js': { srcDir: './3p/', srcFilename: 'recaptcha.js', destDir: './dist.3p/current', minifiedDestDir: './dist.3p/' + internalRuntimeVersion, options: { minifiedName: 'recaptcha.js', externs: [], include3pDirectories: true, includePolyfills: true, }, }, 'amp-viewer-host.max.js': { srcDir: './extensions/amp-viewer-integration/0.1/examples/', srcFilename: 'amp-viewer-host.js', destDir: './dist/v0/examples', minifiedDestDir: './dist/v0/examples', options: { toName: 'amp-viewer-host.max.js', minifiedName: 'amp-viewer-host.js', incudePolyfills: true, extraGlobs: ['extensions/amp-viewer-integration/**/*.js'], skipUnknownDepsCheck: true, }, }, 'video-iframe-integration.js': { srcDir: './src/', srcFilename: 'video-iframe-integration.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'video-iframe-integration-v0.js', includePolyfills: false, }, }, 'amp-story-entry-point.js': { srcDir: './src/amp-story-player/amp-story-entry-point/', srcFilename: 'amp-story-entry-point.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'amp-story-entry-point-v0.js', includePolyfills: false, }, }, 'amp-story-player.js': { srcDir: './src/amp-story-player/', srcFilename: 'amp-story-player.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'amp-story-player-v0.js', includePolyfills: false, }, }, 'amp-inabox-host.js': { srcDir: './ads/inabox/', srcFilename: 'inabox-host.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox-host.js', minifiedName: 'amp4ads-host-v0.js', includePolyfills: false, }, }, 'amp.js': { srcDir: './src/', srcFilename: 'amp.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'v0.js', includePolyfills: true, wrapper: wrappers.mainBinary, esmPassCompilation: argv.esm, includeOnlyESMLevelPolyfills: argv.esm, }, }, 'amp-shadow.js': { srcDir: './src/', srcFilename: 'amp-shadow.js', destDir: './dist', minifiedDestDir: './dist', options: { minifiedName: 'shadow-v0.js', includePolyfills: true, }, }, 'amp-inabox.js': { srcDir: './src/inabox/', srcFilename: 'amp-inabox.js', destDir: './dist', minifiedDestDir: './dist', options: { toName: 'amp-inabox.js', minifiedName: 'amp4ads-v0.js', includePolyfills: true, extraGlobs: ['src/inabox/*.js', '3p/iframe-messaging-client.js'], }, }, }; /** * Used to generate extension build targets */ exports.extensionBundles = [ { name: 'amp-3d-gltf', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-3q-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-access', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-laterpay', version: ['0.1', '0.2'], latestVersion: '0.2', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-scroll', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-access-poool', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-accordion', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-action-macro', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ad', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-ad-custom', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adsense-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-adzerk-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-doubleclick-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-network-fake-impl', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-ad-exit', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-addthis', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-analytics', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-anim', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-apester-media', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-app-banner', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-audio', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-auto-ads', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-autocomplete', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-auto-lightbox', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-base-carousel', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-beopinion', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bind', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-bodymovin-animation', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-brid-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-delight-player', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-brightcove', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-byside-content', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-kaltura-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-call-tracking', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-carousel', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-consent', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-connatix-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-crypto-polyfill', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dailymotion', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-date-countdown', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-display', version: ['0.1', '1.0'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-google-document-embed', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-dynamic-css-classes', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-embedly-card', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-experiment', version: ['0.1', '1.0'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-comments', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-like', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-facebook-page', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fit-text', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-fit-text', version: '1.0', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-font', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-form', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-fx-collection', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-fx-flying-carpet', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-geo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gfycat', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-gist', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-gwd-animation', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-hulu', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-ima-video', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-image-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-image-slider', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-imgur', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-inline-gallery', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-inline-gallery', 'amp-inline-gallery-pagination', 'amp-inline-gallery-thumbnails', ], }, type: TYPES.MISC, }, { name: 'amp-inputmask', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, postPrepend: ['third_party/inputmask/bundle.js'], }, { name: 'amp-instagram', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-install-serviceworker', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-intersection-observer-polyfill', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-izlesene', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-jwplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-lightbox', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-lightbox-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-live-list', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-loader', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mathml', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-mega-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-megaphone', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mustache', version: ['0.1', '0.2'], latestVersion: '0.2', type: TYPES.MISC, }, { name: 'amp-nested-menu', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-next-page', version: ['0.1', '1.0'], latestVersion: '1.0', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-nexxtv-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-o2-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-ooyala-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-pinterest', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-playbuzz', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-reach-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-redbull-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-reddit', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-riddle-quiz', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-script', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-sidebar', version: ['0.1', '0.2'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-skimlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-smartlinks', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-soundcloud', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-springboard-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-standalone', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-sticky-ad', version: '1.0', latestVersion: '1.0', options: {hasCss: true}, type: TYPES.AD, }, { name: 'amp-story', version: '1.0', latestVersion: '1.0', options: { hasCss: true, cssBinaries: [ 'amp-story-bookend', 'amp-story-consent', 'amp-story-draggable-drawer-header', 'amp-story-hint', 'amp-story-info-dialog', 'amp-story-interactive', 'amp-story-interactive-binary-poll', 'amp-story-interactive-quiz', 'amp-story-share', 'amp-story-share-menu', 'amp-story-system-layer', 'amp-story-tooltip', 'amp-story-unsupported-browser-layer', 'amp-story-viewport-warning-layer', ], }, type: TYPES.MISC, }, { name: 'amp-story-auto-ads', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: [ 'amp-story-auto-ads-ad-badge', 'amp-story-auto-ads-attribution', ], }, type: TYPES.MISC, }, { name: 'amp-story-education', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-stream-gallery', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-selector', version: ['0.1', '1.0'], latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-web-push', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-wistia-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-position-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-orientation-observer', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-date-picker', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: ['third_party/react-dates/bundle.js'], }, { name: 'amp-image-viewer', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-subscriptions-google', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-pan-zoom', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-recaptcha-input', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, /** * @deprecated `amp-slides` is deprecated and will be deleted before 1.0. * Please see {@link AmpCarousel} with `type=slides` attribute instead. */ { name: 'amp-slides', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-social-share', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-social-share', version: '1.0', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-timeago', version: ['0.1', '1.0'], latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-truncate-text', version: '0.1', latestVersion: '0.1', options: { hasCss: true, cssBinaries: ['amp-truncate-text', 'amp-truncate-text-shadow'], }, type: TYPES.MISC, }, { name: 'amp-twitter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-user-notification', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, }, { name: 'amp-vimeo', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vine', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viz-vega', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MISC, postPrepend: [ 'third_party/d3/d3.js', 'third_party/d3-geo-projection/d3-geo-projection.js', 'third_party/vega/vega.js', ], }, { name: 'amp-google-vrview-image', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-assistance', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-viewer-integration', version: '0.1', latestVersion: '0.1', options: { // The viewer integration code needs to run asap, so that viewers // can influence document state asap. Otherwise the document may take // a long time to learn that it should start process other extensions // faster. loadPriority: 'high', }, type: TYPES.MISC, }, { name: 'amp-video', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-video-docking', version: '0.1', latestVersion: '0.1', options: {hasCss: true}, type: TYPES.MEDIA, }, { name: 'amp-video-iframe', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-viqeo-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-vk', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-yotpo', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-youtube', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mowplayer', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-powr-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, { name: 'amp-mraid', version: '0.1', latestVersion: '0.1', type: TYPES.AD, }, { name: 'amp-link-rewriter', version: '0.1', latestVersion: '0.1', type: TYPES.MISC, }, { name: 'amp-minute-media-player', version: '0.1', latestVersion: '0.1', type: TYPES.MEDIA, }, ].sort((a, b) => a.name.localeCompare(b.name)); /** * Used to alias a version of an extension to an older deprecated version. */ exports.extensionAliasBundles = { 'amp-sticky-ad': { version: '1.0', aliasedVersion: '0.1', }, 'amp-story': { version: '1.0', aliasedVersion: '0.1', }, }; /** * @param {boolean} condition * @param {string} field * @param {string} message * @param {string} name * @param {string} found */ function verifyBundle_(condition, field, message, name, found) { if (!condition) { log( colors.red('ERROR:'), colors.cyan(field), message, colors.cyan(name), '\n' + found ); process.exit(1); } } exports.verifyExtensionBundles = function () { exports.extensionBundles.forEach((bundle) => { const bundleString = JSON.stringify(bundle, null, 2); verifyBundle_( 'name' in bundle, 'name', 'is missing from', '', bundleString ); verifyBundle_( 'version' in bundle, 'version', 'is missing from', bundle.name, bundleString ); verifyBundle_( 'latestVersion' in bundle, 'latestVersion', 'is missing from', bundle.name, bundleString ); const duplicates = exports.extensionBundles.filter( (duplicate) => duplicate.name === bundle.name ); verifyBundle_( duplicates.every( (duplicate) => duplicate.latestVersion === bundle.latestVersion ), 'latestVersion', 'is not the same for all versions of', bundle.name, JSON.stringify(duplicates, null, 2) ); verifyBundle_( 'type' in bundle, 'type', 'is missing from', bundle.name, bundleString ); const validTypes = Object.keys(TYPES).map((x) => TYPES[x]); verifyBundle_( validTypes.some((validType) => validType === bundle.type), 'type', `is not one of ${validTypes.join(',')} in`, bundle.name, bundleString ); }); };
yandex-pcode/amphtml
build-system/compile/bundles.config.js
JavaScript
apache-2.0
26,113
// @flow /* eslint-env node */ /* global Restivus */ // Import Meteor :3 and Mongo :3 import { Meteor } from 'meteor/meteor' // Import fs and path to access the filesystem. And mime to get MIMETypes. import { readdirSync, lstatSync, readFileSync } from 'fs' import { join, sep, basename } from 'path' import { lookup } from 'mime' // Create the Meteor methods. Meteor.methods({ // This method enables the client to get the contents of any folder. getFolderContents (folder: string): Array<{ name: string, type: string }> { // Get folder contents and create initial variables the loop will write to. const folderContents: Array<string> = readdirSync(folder) const folderContentsWithTypes = [] let i // Define the function to get the type of a directory item. const getType = () => { if (lstatSync(`${folder}/${folderContents[i]}`).isDirectory()) { return 'folder' } return 'file' } // Start the loop to push folderContents. for (i = 0; i < folderContents.length; i += 1) { // Push objects to folderContentsWithTypes. folderContentsWithTypes.push({ name: folderContents[i], type: getType() }) } // Return folderContentsWithTypes. return folderContentsWithTypes }, // Pass it some paths and get a combination of those paths. joinPaths (...paths): string { return join(...paths) }, goUpOneDirectory (pathy: string): string { const pathyArray: Array<string> = pathy.split(sep) if (pathyArray[0] === '') { pathyArray[0] = '/' } const newArray = [] for (let x = 0; x < pathyArray.length - 1; x += 1) { newArray.push(pathyArray[x]) } return join(...newArray) } }) // Create a Restivus API. // flow-disable-next-line const Api = new Restivus({ prettyJson: true }) Api.addRoute('/file/:_filePath', { get () { // Get basename. const filename = basename(this.urlParams._filePath) const mimetype = lookup(this.urlParams._filePath) // Set em' headers. this.response.writeHead({ // Filename. 'Content-disposition': `attachment; filename=${filename}`, // Type of file. 'Content-type': mimetype }) // Read the file and write data to response to client. const file = readFileSync(this.urlParams._filePath) this.response.write(file) // this.done() is quite self-explanatory. this.done() } })
ibujs/Area51
server/main.js
JavaScript
apache-2.0
2,481
/* * Copyright 2017-present Open Networking Foundation * * 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. */ /* ONOS GUI -- Widget -- Table Detail Panel Service */ (function () { 'use strict'; // injected refs var $log, $interval, $timeout, fs, wss; // constants // var refreshInterval = 2000; function noop() {} // TODO: describe the input object for the main function // example params to (functionX): // { // ... // } function buildBasePanel(opts) { var popTopF = fs.isF(opts.popTop) || noop, popMidF = fs.isF(opts.popMid) || noop, popBotF = fs.isF(opts.popBot) || noop; $log.debug('options are', opts); // TODO use panel service to create base panel // TODO: create divs, and pass into invocations of popTopF(div), etc. } // more functions // TODO: add ref to PanelService angular.module('onosWidget') .factory('TableDetailService', ['$log', '$interval', '$timeout', 'FnService', 'WebSocketService', function (_$log_, _$interval_, _$timeout_, _fs_, _wss_) { $log = _$log_; $interval = _$interval_; $timeout = _$timeout_; fs = _fs_; wss = _wss_; return { buildBasePanel: buildBasePanel }; }]); }());
sdnwiselab/onos
web/gui/src/main/webapp/app/fw/widget/tableDetail.js
JavaScript
apache-2.0
1,833
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _url = require('url'); var _url2 = _interopRequireDefault(_url); var _qs = require('qs'); var _qs2 = _interopRequireDefault(_qs); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Request is generated each time the user navigates. * @param {string} path * @param {object} query * @param {object} params * * @property {string} path - The request path. * @property {object} query - If the hash contains a query part, it is treated as a query string. * @property {object} params - An object containing properties mapped to the named route “parameters”. */ var Request = function () { function Request(path, query, params) { _classCallCheck(this, Request); this.path = path; this.query = query; this.params = params; } /** * create a new Request object * @param {string} path * @param {string} query * @param {array} keys * @param {array} results */ _createClass(Request, null, [{ key: 'create', value: function create(path, query, keys, results) { var params = Object.create(null); keys.forEach(function (key, index) { return params[key.name] = results[index + 1]; }); return new Request(path, _qs2.default.parse(query), params); } }]); return Request; }(); exports.default = Request; //# sourceMappingURL=Request.js.map
metasansana/arouca
lib/Request.js
JavaScript
apache-2.0
2,283
import content from "./content.md" import image from "./image.png" export default function() { return content + image }
sebastian-software/rollup-plugin-rebase
test/flat-multi/index.js
JavaScript
apache-2.0
123
// jQuery List DragSort v0.4 // Website: http://dragsort.codeplex.com/ // License: http://dragsort.codeplex.com/license (function($) { $.fn.dragsort = function(options) { var opts = $.extend({}, $.fn.dragsort.defaults, options); var lists = []; var list = null, lastPos = null; if (this.selector) $("head").append("<style type='text/css'>" + (this.selector.split(",").join(" " + opts.dragSelector + ",") + " " + opts.dragSelector) + " { cursor: pointer; }</style>"); this.each(function(i, cont) { if ($(cont).is("table") && $(cont).children().size() == 1 && $(cont).children().is("tbody")) cont = $(cont).children().get(0); var newList = { draggedItem: null, placeHolderItem: null, pos: null, offset: null, offsetLimit: null, scroll: null, container: cont, init: function() { $(this.container).attr("data-listIdx", i).mousedown(this.grabItem).find(opts.dragSelector).css("cursor", "pointer"); $(this.container).children(opts.itemSelector).each(function(j) { $(this).attr("data-itemIdx", j); }); }, grabItem: function(e) { if (e.which != 1 || $(e.target).is(opts.dragSelectorExclude)) return; var elm = e.target; while (!$(elm).is("[data-listIdx='" + $(this).attr("data-listIdx") + "'] " + opts.dragSelector)) { if (elm == this) return; elm = elm.parentNode; } if (list != null && list.draggedItem != null) list.dropItem(); $(e.target).css("cursor", "move"); list = lists[$(this).attr("data-listIdx")]; list.draggedItem = $(elm).closest(opts.itemSelector); var mt = parseInt(list.draggedItem.css("marginTop")); var ml = parseInt(list.draggedItem.css("marginLeft")); list.offset = list.draggedItem.offset(); list.offset.top = e.pageY - list.offset.top + (isNaN(mt) ? 0 : mt) - 1; list.offset.left = e.pageX - list.offset.left + (isNaN(ml) ? 0 : ml) - 1; if (!opts.dragBetween) { var containerHeight = $(list.container).outerHeight() == 0 ? Math.max(1, Math.round(0.5 + $(list.container).children(opts.itemSelector).size() * list.draggedItem.outerWidth() / $(list.container).outerWidth())) * list.draggedItem.outerHeight() : $(list.container).outerHeight(); list.offsetLimit = $(list.container).offset(); list.offsetLimit.right = list.offsetLimit.left + $(list.container).outerWidth() - list.draggedItem.outerWidth(); list.offsetLimit.bottom = list.offsetLimit.top + containerHeight - list.draggedItem.outerHeight(); } var h = list.draggedItem.height(); var w = list.draggedItem.width(); var orig = list.draggedItem.attr("style"); list.draggedItem.attr("data-origStyle", orig ? orig : ""); if (opts.itemSelector == "tr") { list.draggedItem.children().each(function() { $(this).width($(this).width()); }); list.placeHolderItem = list.draggedItem.clone().attr("data-placeHolder", true); list.draggedItem.after(list.placeHolderItem); list.placeHolderItem.children().each(function() { $(this).css({ borderWidth:0, width: $(this).width() + 1, height: $(this).height() + 1 }).html("&nbsp;"); }); } else { list.draggedItem.after(opts.placeHolderTemplate); list.placeHolderItem = list.draggedItem.next().css({ height: h, width: w }).attr("data-placeHolder", true); } list.draggedItem.css({ position: "absolute", opacity: 0.8, "z-index": 999, height: h, width: w }); $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); }); list.scroll = { moveX: 0, moveY: 0, maxX: $(document).width() - $(window).width(), maxY: $(document).height() - $(window).height() }; list.scroll.scrollY = window.setInterval(function() { if (opts.scrollContainer != window) { $(opts.scrollContainer).scrollTop($(opts.scrollContainer).scrollTop() + list.scroll.moveY); return; } var t = $(opts.scrollContainer).scrollTop(); if (list.scroll.moveY > 0 && t < list.scroll.maxY || list.scroll.moveY < 0 && t > 0) { $(opts.scrollContainer).scrollTop(t + list.scroll.moveY); list.draggedItem.css("top", list.draggedItem.offset().top + list.scroll.moveY + 1); } }, 10); list.scroll.scrollX = window.setInterval(function() { if (opts.scrollContainer != window) { $(opts.scrollContainer).scrollLeft($(opts.scrollContainer).scrollLeft() + list.scroll.moveX); return; } var l = $(opts.scrollContainer).scrollLeft(); if (list.scroll.moveX > 0 && l < list.scroll.maxX || list.scroll.moveX < 0 && l > 0) { $(opts.scrollContainer).scrollLeft(l + list.scroll.moveX); list.draggedItem.css("left", list.draggedItem.offset().left + list.scroll.moveX + 1); } }, 10); list.setPos(e.pageX, e.pageY); $(document).bind("selectstart", list.stopBubble); //stop ie text selection $(document).bind("mousemove", list.swapItems); $(document).bind("mouseup", list.dropItem); if (opts.scrollContainer != window) $(window).bind("DOMMouseScroll mousewheel", list.wheel); return false; //stop moz text selection }, setPos: function(x, y) { var top = y - this.offset.top; var left = x - this.offset.left; if (!opts.dragBetween) { top = Math.min(this.offsetLimit.bottom, Math.max(top, this.offsetLimit.top)); left = Math.min(this.offsetLimit.right, Math.max(left, this.offsetLimit.left)); } this.draggedItem.parents().each(function() { if ($(this).css("position") != "static" && (!$.browser.mozilla || $(this).css("display") != "table")) { var offset = $(this).offset(); top -= offset.top; left -= offset.left; return false; } }); if (opts.scrollContainer == window) { y -= $(window).scrollTop(); x -= $(window).scrollLeft(); y = Math.max(0, y - $(window).height() + 5) + Math.min(0, y - 5); x = Math.max(0, x - $(window).width() + 5) + Math.min(0, x - 5); } else { var cont = $(opts.scrollContainer); var offset = cont.offset(); y = Math.max(0, y - cont.height() - offset.top) + Math.min(0, y - offset.top); x = Math.max(0, x - cont.width() - offset.left) + Math.min(0, x - offset.left); } list.scroll.moveX = x == 0 ? 0 : x * opts.scrollSpeed / Math.abs(x); list.scroll.moveY = y == 0 ? 0 : y * opts.scrollSpeed / Math.abs(y); this.draggedItem.css({ top: top, left: left }); }, wheel: function(e) { if (($.browser.safari || $.browser.mozilla) && list && opts.scrollContainer != window) { var cont = $(opts.scrollContainer); var offset = cont.offset(); if (e.pageX > offset.left && e.pageX < offset.left + cont.width() && e.pageY > offset.top && e.pageY < offset.top + cont.height()) { var delta = e.detail ? e.detail * 5 : e.wheelDelta / -2; cont.scrollTop(cont.scrollTop() + delta); e.preventDefault(); } } }, buildPositionTable: function() { var item = this.draggedItem == null ? null : this.draggedItem.get(0); var pos = []; $(this.container).children(opts.itemSelector).each(function(i, elm) { if (elm != item) { var loc = $(elm).offset(); loc.right = loc.left + $(elm).width(); loc.bottom = loc.top + $(elm).height(); loc.elm = elm; pos.push(loc); } }); this.pos = pos; }, dropItem: function() { if (list.draggedItem == null) return; $(list.container).find(opts.dragSelector).css("cursor", "pointer"); list.placeHolderItem.before(list.draggedItem); //list.draggedItem.attr("style", "") doesn't work on IE8 and jQuery 1.5 or lower //list.draggedItem.removeAttr("style") doesn't work on chrome and jQuery 1.6 (works jQuery 1.5 or lower) var orig = list.draggedItem.attr("data-origStyle"); list.draggedItem.attr("style", orig); if (orig == "") list.draggedItem.removeAttr("style"); list.draggedItem.removeAttr("data-origStyle"); list.placeHolderItem.remove(); $("[data-dropTarget]").remove(); window.clearInterval(list.scroll.scrollY); window.clearInterval(list.scroll.scrollX); var changed = false; $(lists).each(function() { $(this.container).children(opts.itemSelector).each(function(j) { if (parseInt($(this).attr("data-itemIdx")) != j) { changed = true; $(this).attr("data-itemIdx", j); } }); }); if (changed) opts.dragEnd.apply(list.draggedItem); list.draggedItem = null; $(document).unbind("selectstart", list.stopBubble); $(document).unbind("mousemove", list.swapItems); $(document).unbind("mouseup", list.dropItem); if (opts.scrollContainer != window) $(window).unbind("DOMMouseScroll mousewheel", list.wheel); return false; }, stopBubble: function() { return false; }, swapItems: function(e) { if (list.draggedItem == null) return false; list.setPos(e.pageX, e.pageY); var ei = list.findPos(e.pageX, e.pageY); var nlist = list; for (var i = 0; ei == -1 && opts.dragBetween && i < lists.length; i++) { ei = lists[i].findPos(e.pageX, e.pageY); nlist = lists[i]; } if (ei == -1 || $(nlist.pos[ei].elm).attr("data-placeHolder")) return false; if (lastPos == null || lastPos.top > list.draggedItem.offset().top || lastPos.left > list.draggedItem.offset().left) $(nlist.pos[ei].elm).before(list.placeHolderItem); else $(nlist.pos[ei].elm).after(list.placeHolderItem); $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); }); lastPos = list.draggedItem.offset(); return false; }, findPos: function(x, y) { for (var i = 0; i < this.pos.length; i++) { if (this.pos[i].left < x && this.pos[i].right > x && this.pos[i].top < y && this.pos[i].bottom > y) return i; } return -1; }, createDropTargets: function() { if (!opts.dragBetween) return; $(lists).each(function() { var ph = $(this.container).find("[data-placeHolder]"); var dt = $(this.container).find("[data-dropTarget]"); if (ph.size() > 0 && dt.size() > 0) dt.remove(); else if (ph.size() == 0 && dt.size() == 0) { //list.placeHolderItem.clone().removeAttr("data-placeHolder") crashes in IE7 and jquery 1.5.1 (doesn't in jquery 1.4.2 or IE8) $(this.container).append(list.placeHolderItem.removeAttr("data-placeHolder").clone().attr("data-dropTarget", true)); list.placeHolderItem.attr("data-placeHolder", true); } }); } }; newList.init(); lists.push(newList); }); return this; }; $.fn.dragsort.defaults = { itemSelector: "li", dragSelector: "li", dragSelectorExclude: "input, textarea, a[href]", dragEnd: function() { }, dragBetween: false, placeHolderTemplate: "<li>&nbsp;</li>", scrollContainer: window, scrollSpeed: 5 }; })(jQuery);
coraldane/ops-meta
static/javascript/jquery.plugin/jquery.dragsort.js
JavaScript
apache-2.0
11,046
setTimeout(function() { $('.color-box').colpick({ layout:'hex', submit:0, colorScheme:'dark', onChange:function(hsb,hex,rgb,el,bySetColor) { $(el).css('background','#'+hex); // Fill the text box just if the color was set using the picker, and not the colpickSetColor function. if(!bySetColor) $(el).val(hex); } }); $("#batch-input").click(function () { $("#batch").fadeIn("fast"); $(".popup-background").fadeIn("fast"); }); $(".close-popup").click(function () { $(".popup").fadeOut("fast"); $(".popup-background").fadeOut("fast"); }); $("a.debug").click(function () { $("#debug").css("visibility", "visible"); }); $("a.save-version").click(function () { $("#save").fadeIn("fast"); $(".popup-background").fadeIn("fast"); }); $("a.leave").click(function () { $("#message").fadeIn("fast"); $(".popup-background").fadeIn("fast"); }); $("a.topline").click(function () { $("#topline").fadeIn("fast"); $("#topline").delay( 5000 ).fadeOut("fast"); }); $("a.win-edit").click(function () { $("#markdown").fadeIn("fast"); $(".popup-background").fadeIn("fast"); }) $("a.search-button").click(function () { $("#search").css("visibility", "visible"); }) },1000);
emksaz/choicefrom
development/de-app/script/popup.js
JavaScript
apache-2.0
1,411
(function () { 'use strict'; angular.module('Pedal2Play') .directive('logoutModal', function () { return { restrict: 'E', templateUrl: 'partials/logout.modal.html' }; }); })();
kaelvofraga/Pedal-to-Play-App
www/js/directives/logout-modal.js
JavaScript
apache-2.0
230
'use strict'; angular.module('angularPHP') .controller('CreateorganizationCtrl', function ($scope, Session, Organizations, $timeout, $location) { Session.require(); $scope.name = ""; $scope.msg = ""; $scope.error = ""; $scope.create = function() { $scope.error = ""; $scope.msg = ""; Organizations.create($scope.name,function(){ $scope.msg = "The organization was created successfully"; $scope.$apply; $timeout(function(){ $location.path("/organizations"); },2000); },function(error){ $scope.error = error; $scope.$apply; }); }; });
smwa/angular-momentum
app/scripts/controllers/main/createorganization.js
JavaScript
apache-2.0
690
//# sourceMappingURL=audio.component.js.map
reTHINK-project/dev-smart-contextual-assistance-app
src/app/components/rethink/hypertyResource/audio/audio.component.js
JavaScript
apache-2.0
43
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ $(function() { var obtainFormMeta = function(formId) { return $(formId).data(); }; $('#form-asset-update').ajaxForm({ beforeSubmit:function(){ PublisherUtils.blockButtons({ container:'updateButtons', msg:'Updating '+PublisherUtils.resolveCurrentPageAssetType()+' instance' }); }, success: function() { alert('Updated the '+PublisherUtils.resolveCurrentPageAssetType()+ ' successfully'); PublisherUtils.unblockButtons({ container:'updateButtons' }); }, error: function() { alert('Unable to update the '+PublisherUtils.resolveCurrentPageAssetType()); PublisherUtils.unblockButtons({ container:'updateButtons' }); } }); var initDatePicker = function(){ console.info('init date picker'); if($(this).attr('data-render-options') == "date-time"){ var dateField = this; $(this).DatePicker({ mode: 'single', position: 'right', onBeforeShow: function(el){ if($(dateField).val().replace(/^\s+|\s+$/g,"")){ $(dateField).DatePickerSetDate($(dateField).val(), true); } }, onChange: function(date, el) { $(el).val((date.getMonth()+1)+'/'+date.getDate()+'/'+date.getFullYear()); if($('#closeOnSelect input').attr('checked')) { $(el).DatePickerHide(); } } }); } }; $('#form-asset-update input[type="text"]').each(initDatePicker); var removeUnboundRow = function(link){ var table = link.closest('table'); if($('tr',table).length == 2){ table.hide(); } link.closest('tr').remove(); }; $('.js-add-unbounded-row').click(function(){ var tableName = $(this).attr('data-name'); var table = $('#table_'+tableName); var referenceRow = $('#table_reference_'+tableName); var newRow = referenceRow.clone().removeAttr('id'); table.show().append(newRow); $('input[type="text"]',newRow).each(initDatePicker); }); $('.js-unbounded-table').on('click','a',function(event){ removeUnboundRow($(event.target)); }); $('#tmp_refernceTableForUnbounded').detach().attr('id','refernceTableForUnbounded').appendTo('body'); $('#tmp_refernceTableForUnbounded').remove(); });
srsharon/carbon-store
apps/publisher/themes/default/js/update_asset.js
JavaScript
apache-2.0
3,312
'use strict'; var React = require('react'), coreViews = require('../../core/views'), mixins = require('../mixins'); var Map = React.createBackboneClass({ mixins: [ mixins.LayersMixin() ], componentDidMount: function() { this.mapView = new coreViews.MapView({ el: '#map' }); }, componentWillUnmount: function() { this.mapView.destroy(); }, componentDidUpdate: function() { var model = this.getActiveLayer(); this.mapView.clearLayers(); if (model) { this.mapView.addLayer(model.getLeafletLayer(), model.getBounds()); this.mapView.fitBounds(model.getBounds()); } }, render: function() { return ( <div id="map-container"> <div id="map"></div> </div> ); } }); module.exports = Map;
kdeloach/raster-foundry
src/rf/js/src/home/components/map.js
JavaScript
apache-2.0
888
const FormatNumber = (value) => { return value.toLocaleString("en-GB", { minimumFractionDigits: 2 }); }; export default FormatNumber;
martincostello/credit-card-splitter
src/Helpers.js
JavaScript
apache-2.0
137
// This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved. var mldb = require('mldb') var unittest = require('mldb/unittest') function expectEmpty(query) { var expected = []; var resp = mldb.query(query); mldb.log(resp); unittest.assertEqual(resp, expected); } function expectFound(query) { var expected = [ { "columns" : [ [ "x", 1, "-Inf" ] ], "rowName" : "\"msnbc.com\"" } ]; var resp = mldb.query(query); mldb.log(resp); unittest.assertEqual(resp, expected); } // Defeat optimization to use slow path expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() + '' = 'msnbc.com'"); // Fast path for rowName = ... expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() = 'msnbc.com'"); // Fast path for rowName = ... expectFound("select * from (select 1 as x named 'msnbc.com') where rowName() = '\"msnbc.com\"'"); // Check no exception when invalid rowName (unbalanced quotes) expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() = '\"msnbc.com'"); // Check no exception when invalid rowName (empty) expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() = ''"); // Check in (...) expectFound("select * from (select 1 as x named 'msnbc.com') where rowName() in ('\"msnbc.com\"')"); expectFound("select * from (select 1 as x named 'msnbc.com') where rowName() in ('\"msnbc.com\"', 'msnbc.com', '\"')"); expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() in ('msnbc.com', '\"')"); expectFound("select * from (select 1 as x named 'msnbc.com') where true and rowName() != 'msnbc.com'"); expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowName() != '\"msnbc.com\"' + ''"); expectEmpty("select * from (select 1 as x named 'msnbc.com') where true and rowName() != '\"msnbc.com\"'"); // rowPath() expectFound("select * from (select 1 as x named 'msnbc.com') where rowPath() = 'msnbc.com'"); expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowPath() = '\"msnbc.com\"'"); expectFound("select * from (select 1 as x named 'msnbc.com') where rowPath() = 'msnbc.com' + ''"); // Check no exception when invalid rowPath (empty) expectEmpty("select * from (select 1 as x named 'msnbc.com') where rowPath() = ''"); // Check in (...) expectFound("select * from (select 1 as x named 'msnbc.com') where rowPath() in ('msnbc.com')"); expectFound("select * from (select 1 as x named 'msnbc.com') where rowPath() in ('msnbc.com', null, [ 1.2, 3.4, 5.6])"); expectEmpty("select * from (select 1 as x named 'msnbc.com') where true and rowPath() != 'msnbc.com'"); expectFound("select * from (select 1 as x named 'msnbc.com') where rowPath() != '\"msnbc.com\"'"); // Tests to add // rowName() in (keys of xxx) // rowName() in (values of xxx) // rowPath() in (keys of xxx) // rowPath() in (values of xxx) // Non-canonical rowName() should return no rows, eg '...' should not match "".""."" since we match as strings on rowName, not structured "success"
mldbai/mldb
testing/MLDB-1678-rowname-optimizations.js
JavaScript
apache-2.0
3,118
import React, { Component } from 'react'; import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'; import { connectStyle } from 'native-base-shoutem-theme'; import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames'; class Content extends Component { render() { return ( <KeyboardAwareScrollView automaticallyAdjustContentInsets={false} resetScrollToCoords={(this.props.disableKBDismissScroll) ? null : { x: 0, y: 0 }} ref={(c) => { this._scrollview = c; this._root = c; }} {...this.props} > {this.props.children} </KeyboardAwareScrollView> ); } } Content.propTypes = { ...KeyboardAwareScrollView.propTypes, style: React.PropTypes.object, padder: React.PropTypes.bool, disableKBDismissScroll: React.PropTypes.bool, enableResetScrollToCoords: React.PropTypes.bool }; const StyledContent = connectStyle('NativeBase.Content', {}, mapPropsToStyleNames)(Content); export { StyledContent as Content, };
sampsasaarela/NativeBase
src/basic/Content.js
JavaScript
apache-2.0
1,015
/** * Malay translation for bootstrap-datetimepicker * Ateman Faiz <noorulfaiz@gmail.com> */ ;(function ($) { $.fn.datetimepicker.dates['ms'] = { days: ["Ahad", "Isnin", "Selasa", "Rabu", "Khamis", "Jumaat", "Sabtu", "Ahad"], daysShort: ["Aha", "Isn", "Sel", "Rab", "Kha", "Jum", "Sab", "Aha"], daysMin: ["Ah", "Is", "Se", "Ra", "Kh", "Ju", "Sa", "Ah"], months: ["Januari", "Februari", "Mac", "April", "Mei", "Jun", "Julai", "Ogos", "September", "Oktober", "November", "Disember"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Ogo", "Sep", "Okt", "Nov", "Dis"], today: "Hari Ini", suffix: [], meridiem: [] }; }(jQuery));
txterm/txsprider
public/static/js/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.ms.js
JavaScript
apache-2.0
715
/* jquery±íµ¥ÑéÖ¤²å¼þ¡£last edit by rongrong 2011.03.29 */ var __check_form_last_error_info = []; var check_form = function (formname, opt) { var formobj; //Ö¸¶¨µ±Ç°±íµ¥ var e_error = ""; var focus_obj = ""; //µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏñ var error = []; var _temp_ajax = new Array; //ajaxУÑéÇëÇóµÄ»º´æ var opt = opt || {}; //Ñ¡Ïî opt = $.extend({ type: 'form', //УÑé¶ÔÏó form ,elem trim: true, //×Ô¶¯trim errtype: 0, //·µ»Ø´íÎóÐÅÏ¢£º0 È«²¿ 1 ×îºóÒ»Ìõ 2 µÚÒ»Ìõ showtype: 0 //´íÎóÏÔʾ·½Ê½ 0 µ¯³ö 1 ²»µ¯³ö }, opt); if (opt['type'] == 'elem') { formobj = $(formname); formname = $('body'); } else { formobj = $('input,textarea,select,button', formname); } formobj.each(function (i) { var formobj_i = $(this); var jscheckflag = formobj_i.attr("jscheckflag"); var obj_tag = formobj_i.attr("tagName"); jscheckflag = jscheckflag == undefined ? 1 : jscheckflag; if (jscheckflag == 0) return true; var jscheckrule = formobj_i.attr("jscheckrule") || ''; var jscheckerror = formobj_i.attr("jscheckerror"); var jschecktitle = formobj_i.attr("jschecktitle") || '±íµ¥'; var jsmaxlen = formobj_i.attr("maxLength"); //Ö´ÐÐ×Ô¶¯trim if (jscheckrule.indexOf('trim=0') == -1 && opt['trim']) { cf_trim(formobj_i, 1); } //³õʼ»¯jscheckrule //УÑéHTML if (jscheckrule.indexOf('html=') == -1) { jscheckrule += ';html=0'; } var jsvalue = formobj_i.val(); var errflag = 0;//´íÎó±ê¼Ç if (obj_tag == 'TEXTAREA' && (jsmaxlen > 0 ? (jsvalue.length > jsmaxlen ? 1 : 0) : 0)) { jscheckerror = (jschecktitle ? jschecktitle : formobj_i.attr('name')) + " ²»µÃ³¬¹ý " + jsmaxlen + " ×Ö"; errflag = 1; } else if (jscheckrule) { errflag = docheck(formobj_i, jscheckrule) ? errflag : 1; } if (errflag) { e_error = jscheckerror ? jscheckerror : jschecktitle + ' ' + formobj_i.data('jscheckerror'); error.push(e_error); if (focus_obj == "") focus_obj = formobj_i; //¾Û½¹µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏó if (this.oldback == undefined) this.oldback = this.style.backgroundColor; //¼Ç¼ԭµ×É« this.style.backgroundColor = '#FFFF00'; //¸ßÁÁ´íÎó±íµ¥¶ÔÏó } else { if (this.oldback != undefined) this.style.backgroundColor = this.oldback; //»¹Ô­µ×É« } }); //´¦ÀíajaxУÑé if (!error) { for (var i in _temp_ajax) { var obj = _temp_ajax[i].obj; var str = _temp_ajax[i].str; var jscheckerror = obj.attr('jscheckerror'); var jschecktitle = obj.attr('jschecktitle'); if (_cf_ajax.call(obj.get(0), obj, str) != true) { e_error = jscheckerror ? jscheckerror : jschecktitle + ' ' + obj.data('jscheckerror'); error.push(e_error); if (focus_obj == "") focus_obj = obj; //¾Û½¹µÚÒ»¸ö³öÏÖ´íÎó¶ÔÏó if (obj.get(0).oldback == undefined) obj.get(0).oldback = obj.get(0).style.backgroundColor; //¼Ç¼ԭµ×É« obj.get(0).style.backgroundColor = '#FFFF00'; //¸ßÁÁ´íÎó±íµ¥¶ÔÏó break; } } } if (error.length > 0) { __check_form_last_error_info = error; if (opt.showtype == 0) alert("±íµ¥´æÔÚÒÔÏ´íÎó:\n" + error.join("\n")); try { focus_obj.focus() } catch (e) { } ; return false; } return true; //УÑéÖ÷º¯Êý function docheck(el, jscheckrule) { var jscheckrule = jscheckrule || el.attr("jscheckrule"); var e_rules = jscheckrule.split(";"); var e_rule, e_rules_len = e_rules.length; for (var k = 0; k < e_rules_len; k++) { var rule_index = e_rules[k].indexOf("="); if (rule_index > -1) { e_rule = [e_rules[k].substr(0, rule_index), e_rules[k].substr(rule_index + 1)]; if (e_rule.length == 2) { //e_rule_para = e_rule_para.replace(new RegExp("\'","gm"),"\\'"); var cf_func = "cf_" + e_rule[0] + "(el,e_rule[1])"; try { if (!eval(cf_func)) return false; } catch (e) { return false; } } } } return true; } //¼ì²âÖÐÓ¢ÎÄ»ìºÏ³¤¶È function strLen(s) { var i, str1, str2, str3, nLen; str1 = s; nLen = 0; for (i = 1; i <= str1.length; i++) { str2 = str1.substring(i - 1, i) str3 = escape(str2); if (str3.length > 3) { nLen = nLen + 2; } else { nLen = nLen + 1; } } return nLen; } //////////////////////////////////////////**** ¼ì²â¹¦Äܺ¯Êý×é****/////////////////////////////////// //×Ô¶¯trimµô¿Õ¸ñ£¬Ò»°ã¼ÓÔÚ¹æÔò×îÇ°Ãætrim=1 function cf_trim(obj, flag) { if (flag == 1) { var str = obj.val(); str = $.trim(str); try { obj.val(str); } catch (e) { } ;//fileʱ»á³ö´í } return true; } //ÅжÏÊÇ·ñΪ¿Õ function cf_null(obj, cannull) { if (cannull == 1) return true; var obj_type = obj.attr('type'), str; if (obj_type == 'checkbox' || obj_type == 'radio') { var objname = obj.attr('name'); str = formobj.filter(':' + obj_type + '[name=' + objname + '][checked]').map(function () { return this.value; }).get().join(','); } else { str = obj.val(); } str = str && typeof(str) == 'object' ? str.join(',') : str; if (cannull == 0) { str = $.trim(str); } if (cannull == 1 || str != "") return true; obj.data('jscheckerror', '²»ÄÜΪ¿Õ'); return false; } //×î´ó³¤¶È function cf_maxlen(obj, num) { var str = obj.val(); if (str == "" || strLen(str) <= num) return true; obj.data('jscheckerror', '³¤¶È²»ÄÜ´óÓÚ ' + num + ' ×Ö½Ú'); return false; } //×îС³¤¶È function cf_minlen(obj, num) { var str = obj.val(); if (str == "" || strLen(str) >= num) return true; obj.data('jscheckerror', '³¤¶È²»ÄÜСÓÚ ' + num + ' ×Ö½Ú'); return false; } //×î´óÖµ function cf_maxnum(obj, num) { var str = obj.val(); if (str * 1 <= num * 1) return true; obj.data('jscheckerror', '²»ÄÜ´óÓÚ ' + num); return false; } //×î´ó×ÖÊý function cf_maxlencn(obj, num) { var str = obj.val(); if (str == "" || str.length <= num) return true; obj.data('jscheckerror', '×ÖÊý²»ÄÜ´óÓÚ ' + num + ' ×Ö'); return false; } //×îС×ÖÊý function cf_minlencn(obj, num) { var str = obj.val(); if (str == "" || str.length >= num) return true; obj.data('jscheckerror', '×ÖÊý²»ÄÜСÓÚ ' + num + ' ×Ö'); return false; } //Ö¸¶¨×ÖÊý function cf_lencn(obj, num) { var str = obj.val(); if (str == "" || str.length == num) return true; obj.data('jscheckerror', '×ÖÊý±ØÐëµÈÓÚ ' + num + ' ×Ö'); } //×îСֵ function cf_minnum(obj, num) { var str = obj.val(); if (str == "" || str * 1 >= num * 1) return true; obj.data('jscheckerror', '²»ÄÜСÓÚ ' + num); return false; } //Ö¸¶¨³¤¶È function cf_len(obj, num) { var str = obj.val(); if (str == "" || strLen(str) == num) return true; obj.data('jscheckerror', '³¤¶È±ØÐëµÈÓÚ ' + num + ' ×Ö½Ú'); } //ÊÇ·ñÓʼþµØÖ· function cf_email(obj, mustcheck) { var str = obj.val(); if (str == "" || !mustcheck) return true; rx = "^([\\w\\_\\.])+@([\\w]+\\.)+([\\w])+$"; if (cf_regexp(obj, rx)) return true; obj.data('jscheckerror', '±ØÐëΪ EMAIL ¸ñʽ'); return false; } //ÓëÁíÒ»¶ÔÏóµÄÖµÒ»Ö function cf_sameto(obj, el) { var str = obj.val(); if (str == "" || str == formobj.filter("#" + el).val()) return true; el = formobj.filter("#" + el).attr('jschecktitle') || el; obj.data('jscheckerror', '±ØÐëµÈÓÚ ' + el + ' µÄÖµ'); return false; } //ÓëÁíÒ»¶ÔÏóµÄÖµ²»Ò»Ö function cf_differentto(obj, el) { var str = obj.val(); if (str == "" || str == formobj.filter("#" + e1).val()) return true; obj.data('jscheckerror', '±ØÐë²»µÈÓÚ ' + el + ' µÄÖµ'); return false; } //²»ÄÜΪijЩֵ function cf_nosame(obj, para) { var str = obj.val(); if (str == "") return true; var p_arr = para.split(","); var p_arrlen = p_arr.length; for (var l = 0; l < p_arrlen; l++) { if (p_arr[l] == str) { obj.data('jscheckerror', '²»ÄܵÈÓÚ ' + para.join(' »ò ')); return false; break; } } return true; } //ÔÊÐí×Ö·û·¶Î§ function cf_charset(obj, para) { var str = obj.val(); if (str == "") return true; var c_rule = ''; var p_arr = para.split(","); var p_arrlen = p_arr.length; var para_arr = []; for (var l = 0; l < p_arrlen; l++) { if (p_arr[l] == 'en') { c_rule += "a-zA-Z"; para_arr[l] = '×Öĸ'; } else if (p_arr[l] == 'num') { c_rule += "0-9"; para_arr[l] = 'Êý×Ö'; } else if (p_arr[l] == 'fl') { c_rule += "0-9\\.0-9"; para_arr[l] = 'СÊý'; } else if (p_arr[l] == 'cn') { c_rule += "\\u4E00-\\u9FA5"; para_arr[l] = 'ÖÐÎÄ'; } else if (p_arr[l] == 'ul') { c_rule += "_"; para_arr[l] = 'Ï»®Ïß'; } } if (c_rule == "") return true; else { var t_rule = "^[" + c_rule + "]*$"; if (cf_regexp(obj, t_rule)) return true; obj.data('jscheckerror', '±ØÐëΪ[' + para_arr.join(',') + ']'); return false; } } //×Ô¶¨ÒåÕýÔòÆ¥Åä function cf_regexp(obj, rx) { var str = obj.val(); if (str == "") return true; if (rx == "")return true; var r_exp = new RegExp(rx, "ig"); if (r_exp.test(str)) return true; obj.data('jscheckerror', 'º¬ÓзǷ¨×Ö·û'); return false; } //УÑéHTML±êÇ©<HTML> function cf_html(obj, flag) { var str = obj.val(); if (str == "" || str == null) return true; if (flag == 1) return true; if (str.indexOf('<') == -1 && str.indexOf('>') == -1) return true; obj.data('jscheckerror', 'º¬ÓÐhtml×Ö·û'); return false; } //ajaxУÑé function cf_ajax(obj, str) { _temp_ajax = _temp_ajax.concat({obj: obj, str: str}); return true; //return _cf_ajax.call(obj.get(0),obj,str); } function _cf_ajax(obj, str) { var str_obj = eval('(' + str + ')'); var resp = $.ajax({ url: str_obj.url, async: false, data: str_obj.data }).responseText; if (resp === 'true') return true; obj.data('jscheckerror', resp); return false; } function get_param(str) { return eval('(' + str + ')'); } //µ÷º¯Êý call = {func:[this.value,1,2,3]} function cf_call(obj, str) { var str_obj = get_param.call(obj.get(0), str); for (var func in str_obj) { var resp = window[func].apply(undefined, str_obj[func]); if (resp !== true) { obj.data('jscheckerror', resp); return false; } } return true; } } check_form.get_error = function () { return __check_form_last_error_info; };
DullSky/his
WebRoot/Js/ckform.js
JavaScript
apache-2.0
12,288
/* * Copyright 2020 Verizon Media * * 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. */ import React from 'react'; import Header from '../components/header/Header'; import UserDomains from '../components/domain/UserDomains'; import API from '../api.js'; import styled from '@emotion/styled'; import Head from 'next/head'; import Search from '../components/search/Search'; import RequestUtils from '../components/utils/RequestUtils'; import Error from './_error'; import createCache from '@emotion/cache'; import { CacheProvider } from '@emotion/react'; const HomeContainerDiv = styled.div` flex: 1 1; `; const HomeContentDiv = styled.div` align-items: center; height: 100%; justify-content: flex-start; width: 100%; display: flex; flex-direction: column; `; const Logo = ({ className }) => ( <img src='/static/athenz-logo.png' className={className} /> ); const LogoStyled = styled(Logo)` height: 100px; width: 100px; `; const MainLogoDiv = styled.div` padding-top: 20px; `; const DetailsDiv = styled.div` align-items: flex-start; line-height: 1.3; padding: 20px 0; text-align: center; width: 650px; `; const SearchContainerDiv = styled.div` padding: 20px 0 0 0; width: 600px; `; const AppContainerDiv = styled.div` align-items: stretch; flex-flow: row nowrap; height: 100%; display: flex; justify-content: flex-start; `; const MainContentDiv = styled.div` flex: 1 1 calc(100vh - 60px); overflow: hidden; font: 300 14px HelveticaNeue-Reg, Helvetica, Arial, sans-serif; `; const StyledAnchor = styled.a` color: #3570f4; text-decoration: none; cursor: pointer; `; export default class PageHome extends React.Component { static async getInitialProps({ req }) { let api = API(req); let reload = false; let error = null; const domains = await Promise.all([ api.listUserDomains(), api.getHeaderDetails(), api.getPendingDomainMembersList(), ]).catch((err) => { let response = RequestUtils.errorCheckHelper(err); reload = response.reload; error = response.error; return [{}, {}, {}]; }); return { api, reload, error, domains: domains[0], headerDetails: domains[1], pending: domains[2], nonce: req.headers.rid, }; } constructor(props) { super(props); this.api = props.api || API(); this.cache = createCache({ key: 'athenz', nonce: this.props.nonce, }); } render() { if (this.props.reload) { window.location.reload(); return <div />; } if (this.props.error) { return <Error err={this.props.error} />; } return ( <CacheProvider value={this.cache}> <div data-testid='home'> <Head> <title>Athenz</title> </Head> <Header showSearch={false} headerDetails={this.props.headerDetails} pending={this.props.pending} /> <MainContentDiv> <AppContainerDiv> <HomeContainerDiv> <HomeContentDiv> <MainLogoDiv> <LogoStyled /> </MainLogoDiv> <DetailsDiv> <span> Athenz is an open source platform which provides secure identity in the form of X.509 certificate to every workload for service authentication (mutual TLS authentication) and provides fine-grained Role Based Access Control (RBAC) for authorization. </span> <StyledAnchor rel='noopener' target='_blank' href='https://git.ouroath.com/pages/athens/athenz-guide/' > Learn more </StyledAnchor> </DetailsDiv> <SearchContainerDiv> <Search /> </SearchContainerDiv> </HomeContentDiv> </HomeContainerDiv> <UserDomains domains={this.props.domains} api={this.api} /> </AppContainerDiv> </MainContentDiv> </div> </CacheProvider> ); } }
yahoo/athenz
ui/src/pages/home.js
JavaScript
apache-2.0
5,975
(function () { 'use strict'; angular .module('brew_journal.layout', [ 'brew_journal.layout.controllers' ]); angular .module('brew_journal.layout.controllers', []); })();
moonboy13/brew-journal
brew_journal/static/js/layout/layout.module.js
JavaScript
apache-2.0
205
import React from 'react'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; import _ from 'lodash'; import { api } from './Api'; import { formatJSON } from './utils'; export default createReactClass({ propTypes: { params: PropTypes.object, }, getInitialState() { return { data_container: null, }; }, componentDidMount() { const id = this.props.params.id; const payload = { aggregate: [ { $match: { _id: id } }, ], }; api.getDataContainers(payload) .then(response => this.setState({ data_container: _.get(response, 'data_containers[0]', {}) })); }, render() { if (this.state.data_container == null) { return (<h1>Loading Data Container<span className="loading" /></h1>); } if (_.isEmpty(this.state.data_container)) { return (<div className="alert alert-error">Data not available</div>); } return ( <div> <h1>Data Container</h1> <pre className="scroll"> {formatJSON(this.state.data_container)} </pre> </div> ); }, });
curious-containers/cc-ui
src/DataContainer.js
JavaScript
apache-2.0
1,124
var NAVTREEINDEX88 = { "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimplePacketStore.html#acb74742b2981e7511bb15cefa1ba69d3":[2,0,29,3,56,24,20,0], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html":[2,0,29,3,56,24,21], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#a22121826f3b9fbea414e00ced785a82e":[2,0,29,3,56,24,21,2], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#a59125283629193ec835127dab62060c4":[2,0,29,3,56,24,21,6], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#a9b7e258fc839196ad2b0776b0be26261":[2,0,29,3,56,24,21,4], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#ab1103e8153a9651510fdd55964ea9aa1":[2,0,29,3,56,24,21,5], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#ab437fc42833f566b8dc6468aa9bbe566":[2,0,29,3,56,24,21,0], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#abf97a1773ed2f9db9b14d3368c54a065":[2,0,29,3,56,24,21,3], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleStatisticStore.html#ad2a402831cfecc7d4aed5a703f206a69":[2,0,29,3,56,24,21,1], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html":[2,0,29,3,56,24,22], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a148f452f146e3cb7636f2ec68cdd3c43":[2,0,29,3,56,24,22,1], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a269ad29d4f7ccc5e20490e383270d64e":[2,0,29,3,56,24,22,10], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a2866ee9427f028032b75383a17a20d0d":[2,0,29,3,56,24,22,6], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a3ad2c5073e05190319fb9f46114fd2d1":[2,0,29,3,56,24,22,9], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a3ae207797b72f05c5112d01403998adb":[2,0,29,3,56,24,22,0], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a413c33beafeeccbc021b78ebaf0172f2":[2,0,29,3,56,24,22,15], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a63c4d39f6bdbcbc3247943aa86716f9e":[2,0,29,3,56,24,22,4], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a6d97ca4697aa1d47a0d8b4645b8e6718":[2,0,29,3,56,24,22,14], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a70220924d62c5dc74d9f1758aa2d2017":[2,0,29,3,56,24,22,3], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a77854282e35086e8455a44ccc7109821":[2,0,29,3,56,24,22,13], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a7aa268c6cf8f98c404f5763d08c7550b":[2,0,29,3,56,24,22,16], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a7d696d1c0a1a7cfbe5538297e426d725":[2,0,29,3,56,24,22,7], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a82ff20cc234ffb478d516129350ba6cf":[2,0,29,3,56,24,22,11], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#a8f2f93aa1531e10e96c012dcb237265d":[2,0,29,3,56,24,22,5], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#aa47b7669189fba22a1437e893106e974":[2,0,29,3,56,24,22,8], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#aaef43b258c42df79c6431aa8c5dd7c4e":[2,0,29,3,56,24,22,17], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#ab75bb226b7d6ab6f5d1e0f9e265ab5c4":[2,0,29,3,56,24,22,12], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SimpleTopologyStore.html#abe8ac1397ccfa61631136de92fed0ae3":[2,0,29,3,56,24,22,2], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html":[2,0,29,3,56,24,23], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#a3d2963d2365f8c9b829c2af7ae923af1":[2,0,29,3,56,24,23,5], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#a4cb2a0eb952e035df0d91fe79c78d50a":[2,0,29,3,56,24,23,6], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#a766e63ab3c149500788d90f84bb0b72e":[2,0,29,3,56,24,23,4], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#ace22dd8c27fafb304d0155c0395dbde2":[2,0,29,3,56,24,23,1], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#ad46f07d860d926fe5c6e2d8f41ac6cc8":[2,0,29,3,56,24,23,2], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#ad5a25cb431c9198fda24f99c775c5af8":[2,0,29,3,56,24,23,0], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#ad9cddf50ea87193c4c5d8da1d20eeb4e":[2,0,29,3,56,24,23,3], "classorg_1_1onosproject_1_1store_1_1trivial_1_1SystemClockTimestamp.html#afd24bfd9580a07240d27ef72624fb783":[2,0,29,3,56,24,23,7], "classorg_1_1onosproject_1_1ui_1_1JsonUtils.html":[2,0,29,3,57,3], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html":[2,0,29,3,57,4], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a18e0856e53473e97384a70daa0b44e07":[2,0,29,3,57,4,4], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a264c13e222cd47fe827b42d8264de8ad":[2,0,29,3,57,4,1], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a67c038c3c22bedf685342eb9e136c668":[2,0,29,3,57,4,7], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a6a1b99f1c0535f1eec55a55c943484d3":[2,0,29,3,57,4,2], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a6b6b637c1951f01b38fd2c529147abce":[2,0,29,3,57,4,6], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#a7d7615e4c9776e10bafa001052388e7c":[2,0,29,3,57,4,3], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#aa5fbb6d5077a89186396e38181f03a4b":[2,0,29,3,57,4,5], "classorg_1_1onosproject_1_1ui_1_1RequestHandler.html#ad60b294ba179db388ec98fda23fd329e":[2,0,29,3,57,4,0], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html":[2,0,29,3,57,6], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#a1b69e9ee63d9cb9fbb82866b271d199b":[2,0,29,3,57,6,4], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#a38ea8aa8b5d334d75fd40e17cc0aa90c":[2,0,29,3,57,6,3], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#a5b0d5f7d18139ff3093c9e52ed863648":[2,0,29,3,57,6,1], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#ae659c8cf89d537bad9cbd693fddaa7fc":[2,0,29,3,57,6,5], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#af087fa620e73360ab920368ace69879a":[2,0,29,3,57,6,2], "classorg_1_1onosproject_1_1ui_1_1UiExtension.html#af9f1cf507076f110f4bf703da4af9a81":[2,0,29,3,57,6,0], "classorg_1_1onosproject_1_1ui_1_1UiExtensionServiceAdapter.html":[2,0,29,3,57,14], "classorg_1_1onosproject_1_1ui_1_1UiExtensionServiceAdapter.html#a023ff0d52dca10bd87c83769077b5d6b":[2,0,29,3,57,14,2], "classorg_1_1onosproject_1_1ui_1_1UiExtensionServiceAdapter.html#a1f6b9cf88a9287489f50f7b32a1fdee7":[2,0,29,3,57,14,1], "classorg_1_1onosproject_1_1ui_1_1UiExtensionServiceAdapter.html#ad81d8f132c6d7905a9354c04de85521b":[2,0,29,3,57,14,3], "classorg_1_1onosproject_1_1ui_1_1UiExtensionServiceAdapter.html#af579e1fb47f95c444b67a705dfdb4beb":[2,0,29,3,57,14,0], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html":[2,0,29,3,57,15], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html#a12693b647d3c7e5b7e40ce3e1bd759e4":[2,0,29,3,57,15,2], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html#a4a16d01b9d10679b1fa219946fc1f465":[2,0,29,3,57,15,0], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html#a53f7540135e7b5ad1645f3683201d561":[2,0,29,3,57,15,1], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html#a60cce0c2b955a79c0f954c09f067df3c":[2,0,29,3,57,15,4], "classorg_1_1onosproject_1_1ui_1_1UiExtensionTest.html#add0fbc8dac3e611a410ab2ac73cc072c":[2,0,29,3,57,15,3], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html":[2,0,29,3,57,8], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a0771e4fa16b1d692631ad178948ba9f7":[2,0,29,3,57,8,2], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a2c5fdf5ce1207f4a7163869c29ed81ba":[2,0,29,3,57,8,8], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a3107e2a1dac33613077986efcd932483":[2,0,29,3,57,8,3], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a7617c90302e540fc9c97c02e17ae9901":[2,0,29,3,57,8,6], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a78c6ccbd7e789686c8a1d311144fbc46":[2,0,29,3,57,8,9], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a7b18d3a1dd628946be78b68a8eb09802":[2,0,29,3,57,8,4], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#a8b50402f0debaf694cd6b0ed988befe7":[2,0,29,3,57,8,5], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#aaaf90662953fc72690f0881e329399d6":[2,0,29,3,57,8,1], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#aaf334e1c31cce2f4373597c2a4722b60":[2,0,29,3,57,8,0], "classorg_1_1onosproject_1_1ui_1_1UiMessageHandler.html#af64452cb19bbbef28c4044ffdb606595":[2,0,29,3,57,8,7], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html":[2,0,29,3,57,10], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a0a05d831027e94427e787bb18699aa96":[2,0,29,3,57,10,7], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a2a0e226e470edc2c2d5ae0d710398646":[2,0,29,3,57,10,8], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a43c86c702c5426f0519ed3c6c6ff2f5d":[2,0,29,3,57,10,4], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a4e3dcae0fbf294f5b5879ea46ee93e34":[2,0,29,3,57,10,3], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a601d83f1dd9ee8cdbbefc20079e2beb5":[2,0,29,3,57,10,9], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a6a8cf882b826d6c3cd3796521459d361":[2,0,29,3,57,10,10], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#a8042f87ef99c58f30d0083b26915057a":[2,0,29,3,57,10,2], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#ab6bad29e68b0b6f7d73a6f0abf2e4264":[2,0,29,3,57,10,6], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#acf6446ec750695795ee79ae872fce5e1":[2,0,29,3,57,10,5], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#ad8901e394a39afae1057dd6c3eea12b8":[2,0,29,3,57,10,1], "classorg_1_1onosproject_1_1ui_1_1UiTopoOverlay.html#adfa53b27ac8a910a92ec82005eeef6fa":[2,0,29,3,57,10,0], "classorg_1_1onosproject_1_1ui_1_1UiView.html":[2,0,29,3,57,12], "classorg_1_1onosproject_1_1ui_1_1UiView.html#a2339a61dd095279bb74cd02f402f3694":[2,0,29,3,57,12,8], "classorg_1_1onosproject_1_1ui_1_1UiView.html#a2cab06925b0c9de297809d787a7cf6db":[2,0,29,3,57,12,4], "classorg_1_1onosproject_1_1ui_1_1UiView.html#a357d8ec3778cc443cd9083a46984ea14":[2,0,29,3,57,12,1], "classorg_1_1onosproject_1_1ui_1_1UiView.html#a47ee32280b38478981090f4bddf924d4":[2,0,29,3,57,12,7], "classorg_1_1onosproject_1_1ui_1_1UiView.html#a9a469d292054b0566672a3034fd75636":[2,0,29,3,57,12,3], "classorg_1_1onosproject_1_1ui_1_1UiView.html#abf6028406b9e4837cfbdffd45f16ea09":[2,0,29,3,57,12,9], "classorg_1_1onosproject_1_1ui_1_1UiView.html#ac3b18a813e91d1e0211e2d339dd28e52":[2,0,29,3,57,12,5], "classorg_1_1onosproject_1_1ui_1_1UiView.html#ae2c6fde97db7a11b4068353e2e604a1e":[2,0,29,3,57,12,6], "classorg_1_1onosproject_1_1ui_1_1UiView.html#aedbd7689ae515da34fb7bc5a210712dc":[2,0,29,3,57,12,2], "classorg_1_1onosproject_1_1ui_1_1UiViewHidden.html":[2,0,29,3,57,13], "classorg_1_1onosproject_1_1ui_1_1UiViewHidden.html#aa562d716758d1239dd777c687a89953e":[2,0,29,3,57,13,1], "classorg_1_1onosproject_1_1ui_1_1UiViewHidden.html#ac0f0c84033e119bb882ebe98320f4c5c":[2,0,29,3,57,13,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ApplicationResource.html":[2,0,29,3,57,0,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ApplicationResource.html#a7663d9fbd853acda2749c5aba22de47e":[2,0,29,3,57,0,1,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ApplicationViewMessageHandler.html":[2,0,29,3,57,0,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ApplicationViewMessageHandler.html#a6af28e372639a8855314d13bdb270b65":[2,0,29,3,57,0,2,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ClusterViewMessageHandler.html":[2,0,29,3,57,0,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ClusterViewMessageHandler.html#af623d5b0a852807294470a2176b1265a":[2,0,29,3,57,0,3,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1DeviceViewMessageHandler.html":[2,0,29,3,57,0,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1DeviceViewMessageHandler.html#a33ddeb91295f16c1b3799ca13cc0d6d9":[2,0,29,3,57,0,4,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1FlowViewMessageHandler.html":[2,0,29,3,57,0,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1FlowViewMessageHandler.html#ab039f5e077beef2c739cda6561494e55":[2,0,29,3,57,0,5,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1GroupViewMessageHandler.html":[2,0,29,3,57,0,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1GroupViewMessageHandler.html#aaee578c2bc7875463f6bb9a95ea2396b":[2,0,29,3,57,0,6,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1HostViewMessageHandler.html":[2,0,29,3,57,0,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1HostViewMessageHandler.html#adae43d9223671981c0deb8e8001009cd":[2,0,29,3,57,0,7,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1IntentViewMessageHandler.html":[2,0,29,3,57,0,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1IntentViewMessageHandler.html#ac2fe4e31bc3bc75029e3994f8db9a3c5":[2,0,29,3,57,0,8,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1LinkViewMessageHandler.html":[2,0,29,3,57,0,9], "classorg_1_1onosproject_1_1ui_1_1impl_1_1LinkViewMessageHandler.html#ad92009432c30d534e922b7b500675d08":[2,0,29,3,57,0,9,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1LogoutResource.html":[2,0,29,3,57,0,10], "classorg_1_1onosproject_1_1ui_1_1impl_1_1LogoutResource.html#a9c821c95f8d47309f1f9dcd07c7bedb1":[2,0,29,3,57,0,10,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainIndexResource.html":[2,0,29,3,57,0,11], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainIndexResource.html#aca8f30e4ff3e9b79f22aacbc38c2ae4c":[2,0,29,3,57,0,11,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainModuleResource.html":[2,0,29,3,57,0,12], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainModuleResource.html#a2337a26706cf254502110a1a58225392":[2,0,29,3,57,0,12,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainNavResource.html":[2,0,29,3,57,0,13], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainNavResource.html#a4d3db775a743202c24f33ee330805d97":[2,0,29,3,57,0,13,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainViewResource.html":[2,0,29,3,57,0,14], "classorg_1_1onosproject_1_1ui_1_1impl_1_1MainViewResource.html#ac8be2976436c9189514dc866c052cc92":[2,0,29,3,57,0,14,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1PortViewMessageHandler.html":[2,0,29,3,57,0,15], "classorg_1_1onosproject_1_1ui_1_1impl_1_1PortViewMessageHandler.html#a960bc7e0fc348a5c9d63dd15f75aa6f6":[2,0,29,3,57,0,15,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ProcessorViewMessageHandler.html":[2,0,29,3,57,0,16], "classorg_1_1onosproject_1_1ui_1_1impl_1_1ProcessorViewMessageHandler.html#a83d3912ef721353f4f787910c6ffd0a4":[2,0,29,3,57,0,16,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1SettingsViewMessageHandler.html":[2,0,29,3,57,0,17], "classorg_1_1onosproject_1_1ui_1_1impl_1_1SettingsViewMessageHandler.html#a0328853018c843ea19788cad57fecb23":[2,0,29,3,57,0,17,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html":[2,0,29,3,57,0,22], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#a04ba4a2df889261690fa8ca1feb8ea55":[2,0,29,3,57,0,22,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#a1fb18c1a1b1657deb5d10199a5da1ef5":[2,0,29,3,57,0,22,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#a4d4890ad9e798ebea0b1a4fdf5f6cdd3":[2,0,29,3,57,0,22,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#a83b27b78622a754d339ce7f4893c5f33":[2,0,29,3,57,0,22,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#a93f3cfc2e99a23aafd0b8edef86fb6b8":[2,0,29,3,57,0,22,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#aaf6e0e898b3fe7a344936d93410cf920":[2,0,29,3,57,0,22,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopoOverlayCache.html#ac070aed4d8b0e28b103a0b6a4e158c1d":[2,0,29,3,57,0,22,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyResource.html":[2,0,29,3,57,0,19], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyResource.html#ac44cfdb0cb4adb0c4c2e35d3f4134ef0":[2,0,29,3,57,0,19,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyResource.html#ae5f2cbc1d5b9704efb79d757a049dd9d":[2,0,29,3,57,0,19,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandler.html":[2,0,29,3,57,0,20], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandler.html#a180b5772ebdf6614586a6b990c0db5fc":[2,0,29,3,57,0,20,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandler.html#a66f67775fa172f69f11cd2bd15b38627":[2,0,29,3,57,0,20,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandler.html#a898b17c92bc86ebd2a239c73f5fdda2f":[2,0,29,3,57,0,20,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandler.html#abfc12c3491cd200d2dc43c84ab75c866":[2,0,29,3,57,0,20,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html":[2,0,29,3,57,0,21], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a04d25b6cb365fbb211a2136d3f6977eb":[2,0,29,3,57,0,21,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a218de2cca2c5eba5555cc6f647b6e4b9":[2,0,29,3,57,0,21,21], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a27b7f7e495a1d1711f09ceebba8ab9ea":[2,0,29,3,57,0,21,9], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a34a978efdf029f1a75439aa5d4e1a2a4":[2,0,29,3,57,0,21,10], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a3a554c4f7ea4033f70e3d82364e79264":[2,0,29,3,57,0,21,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a4e0905459ced6ca5372ba7f617563afb":[2,0,29,3,57,0,21,17], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a5a981188490be0927ca5ec3f57f8a0ad":[2,0,29,3,57,0,21,16], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a5fcf561222a555770eb0439c8d37aff8":[2,0,29,3,57,0,21,22], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a6c4490c6981b10baddcad76cc4d6d67f":[2,0,29,3,57,0,21,24], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a6ce94b9cdd74354f7d0096c637f38b51":[2,0,29,3,57,0,21,15], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a706b3fe19b21add26e99fc6c74f70d69":[2,0,29,3,57,0,21,11], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a71344f228429de6c7a83acb048ecb27b":[2,0,29,3,57,0,21,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a77494efb18b229faa106b5abdcdd8877":[2,0,29,3,57,0,21,23], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a7c8822132a04cd3f8da37594fb0f59de":[2,0,29,3,57,0,21,25], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a7fd8bd158a712ff242d037d8cbd3b307":[2,0,29,3,57,0,21,19], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a87ced6bd275e9a41105c2d377caea2e5":[2,0,29,3,57,0,21,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a8dc27a01b9f5dbb0a8f98184a696b921":[2,0,29,3,57,0,21,26], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a90145d5a89b49303a0a4428497e05234":[2,0,29,3,57,0,21,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a969c9c98972b2bc6d3079cedcebece8a":[2,0,29,3,57,0,21,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a9b064a571e798f24453288a306ef2576":[2,0,29,3,57,0,21,13], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#a9dd43a1020a321cf927014e4815756d4":[2,0,29,3,57,0,21,20], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#aa3810be13e944fd38d7a3b3151166dde":[2,0,29,3,57,0,21,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#abb5470847573e2f18ecb81ecf5516cda":[2,0,29,3,57,0,21,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#ac2b8cc218cbac4e24454e163b2a75ba9":[2,0,29,3,57,0,21,18], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#ad13e6ba2ccb2af304b42a7049e6c4a8d":[2,0,29,3,57,0,21,12], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#ad4bb592c8548fccedbb3a7aa4dcb55ef":[2,0,29,3,57,0,21,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TopologyViewMessageHandlerBase.html#aea9ab2c0318113bf8272a31cc2026b64":[2,0,29,3,57,0,21,14], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html":[2,0,29,3,57,0,23], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#a00e0887fc91ed6bba2ec95743d8fefa1":[2,0,29,3,57,0,23,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#a196ad4d94021152c7533dde1baf00547":[2,0,29,3,57,0,23,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#a661496397151ed83b7d4d1f02d7d3cb6":[2,0,29,3,57,0,23,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#a6ba9aebc7ab0aade5f76ddbdacc631a0":[2,0,29,3,57,0,23,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#aa1080b0c8298a66d0dc84f4d9c060ce9":[2,0,29,3,57,0,23,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#abbfca2f407ef409dbf65ea6c2165cb8c":[2,0,29,3,57,0,23,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#abf6b8b4a21e0b28b5dde0e4c6f395a8e":[2,0,29,3,57,0,23,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficMonitor.html#ac19041dacd7b343777a26521ee6f082b":[2,0,29,3,57,0,23,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficOverlay.html":[2,0,29,3,57,0,24], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficOverlay.html#a2d17d4900b030052a833fe1a344ba1da":[2,0,29,3,57,0,24,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficOverlay.html#a712d2f5090f1b40ad464b195e898e5ef":[2,0,29,3,57,0,24,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficOverlay.html#a999730533bed7ffa1c364f315e27dbda":[2,0,29,3,57,0,24,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TrafficOverlay.html#ad8a2094ff5ea3443d1bb42a75a7c5a6b":[2,0,29,3,57,0,24,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TunnelViewMessageHandler.html":[2,0,29,3,57,0,25], "classorg_1_1onosproject_1_1ui_1_1impl_1_1TunnelViewMessageHandler.html#a5ec37ca6cf4b88b19388ceffb004900b":[2,0,29,3,57,0,25,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html":[2,0,29,3,57,0,26], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a0e0923ae379e5bb4b7694ecd62206691":[2,0,29,3,57,0,26,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a210f7d8ade2c738c30b1246cac97cacd":[2,0,29,3,57,0,26,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a25454679ded094f56ab9be5c11869e75":[2,0,29,3,57,0,26,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a5041ed63df8f2e6ff32752603e2bedbc":[2,0,29,3,57,0,26,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a7240e1803742751ee21958c683756612":[2,0,29,3,57,0,26,9], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a7fc183d08e93f1a389a0903a2f30ac5b":[2,0,29,3,57,0,26,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#a9011ae5c05f4befa9d11a4b637305b07":[2,0,29,3,57,0,26,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#ac2dfffc874290169c25a796e6e22e8f3":[2,0,29,3,57,0,26,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#ac38a7320d41122583beec7c0dcd8c510":[2,0,29,3,57,0,26,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiExtensionManager.html#afa15f75c15efffc1cfe6795d66650a15":[2,0,29,3,57,0,26,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html":[2,0,29,3,57,0,27], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#a40e80e83d5233195ecd6fad2ae62fb13":[2,0,29,3,57,0,27,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#a58edf8699603dd8e6ee557abed34531d":[2,0,29,3,57,0,27,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#a61065a53831eeb48d8189b03382e77a1":[2,0,29,3,57,0,27,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#a842df84684cd1be1451690837989a773":[2,0,29,3,57,0,27,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#a9524008a69b6fd49618ee18161f5e29d":[2,0,29,3,57,0,27,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#aa8c50c725d296e23b5f76feb882fc68e":[2,0,29,3,57,0,27,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocket.html#af72218d3bb832db266a408346274ce19":[2,0,29,3,57,0,27,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocketServlet.html":[2,0,29,3,57,0,28], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocketServlet.html#a033bd4fb20dcdac2d57ed6f1a4b846f9":[2,0,29,3,57,0,28,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1UiWebSocketServlet.html#a37b5ff689b8429b31356446af7d787dd":[2,0,29,3,57,0,28,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html":[2,0,29,3,57,0,0,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a187a5e3a8defd533cd09ce47c322e1a5":[2,0,29,3,57,0,0,0,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a22eb53d3cd6836fd0a6790d6830afa47":[2,0,29,3,57,0,0,0,11], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a26bf7b9b9e76c2147a6d78fbb03659a8":[2,0,29,3,57,0,0,0,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a53802c1b27c64fb1c9e66287e1926e7c":[2,0,29,3,57,0,0,0,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a5a4ca69614f2e52d15b0806c910eee83":[2,0,29,3,57,0,0,0,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a5e99a5a23dd4e0223f6d3d188977baf8":[2,0,29,3,57,0,0,0,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a644fbe487607ec18b24d2dcf98ff32e4":[2,0,29,3,57,0,0,0,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a6e0ea25be7971af7312670cfb194964d":[2,0,29,3,57,0,0,0,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a96cd56a36b876c69873badb5b44d1385":[2,0,29,3,57,0,0,0,9], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#a9f0dbfce0ff1e650365bb2899145cbab":[2,0,29,3,57,0,0,0,10], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#acc5c80721e88cec67815e51ae33fc7bf":[2,0,29,3,57,0,0,0,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1IntentSelection.html#ad84d1ecf521b61c978e3aa8365b1c45f":[2,0,29,3,57,0,0,0,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html":[2,0,29,3,57,0,0,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#a030fb4ad24ea296f88cd8f60971d2ebc":[2,0,29,3,57,0,0,1,7], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#a5eaef1f6a5f38d76d2d682be7c6c82f6":[2,0,29,3,57,0,0,1,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#a9b33860d16fc4177b8e86c3fa1dbc6fb":[2,0,29,3,57,0,0,1,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#ab69deed1dbe6234938b80260d0335a59":[2,0,29,3,57,0,0,1,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#abbb633f4658ef558c3e6f06b1acb2568":[2,0,29,3,57,0,0,1,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#abe96f972b4b067fb8f6553c58a45d368":[2,0,29,3,57,0,0,1,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#af041d0e51234c88dd3cfd795f5d426da":[2,0,29,3,57,0,0,1,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1ServicesBundle.html#af268deb1b96fc8e822e9afe530cdb7ca":[2,0,29,3,57,0,0,1,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TopoIntentFilter.html":[2,0,29,3,57,0,0,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TopoIntentFilter.html#a14751c299148c3a66d2edac9aa6df9ca":[2,0,29,3,57,0,0,2,1], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TopoIntentFilter.html#abe524a1b363cee49e870f0365d4ee063":[2,0,29,3,57,0,0,2,0], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html":[2,0,29,3,57,0,0,3], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a0bde945a114a91a8de3541831d955f10":[2,0,29,3,57,0,0,3,5], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a1c3f60add9d0ca3ac6486eb9822fdcf5":[2,0,29,3,57,0,0,3,2], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a308a3739fb77ced1ad2d6e4ceb405b16":[2,0,29,3,57,0,0,3,8], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a5972d63beb9d9160c4ea86b7fe14e0da":[2,0,29,3,57,0,0,3,4], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a5a648bfc9b7052d15d05e70cc7c4ce52":[2,0,29,3,57,0,0,3,6], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#a7659f154bc66afa89563f501ab431bf6":[2,0,29,3,57,0,0,3,9], "classorg_1_1onosproject_1_1ui_1_1impl_1_1topo_1_1TrafficLink.html#acd787ac47e5f9d4a3613bac543a91262":[2,0,29,3,57,0,0,3,3] };
onosfw/apis
onos/apis/navtreeindex88.js
JavaScript
apache-2.0
29,115
(function() { 'use strict'; function HomeController($scope, $q, $timeout) { var self = this; self.time = 50; self.message = "Mensagem para mostrar"; var promiseTimeout; var deferredToast; self.mostrarToast = function() { esconderToast(); deferredToast = $q.defer(); deferredToast.promise.then(toastResolved, toastRejected); self.activeShow = true; self.mensagemAtual = self.message; promiseTimeout = $timeout(timeoutToast, self.time * 1000); }; function timeoutToast() { deferredToast.reject(); esconderToast(); } function esconderToast() { if (promiseTimeout) { $timeout.cancel(promiseTimeout); promiseTimeout = undefined; } self.activeShow = false; } self.clickBotaoFechar = function() { if (deferredToast) { // verifica pra evitar problema com duplo clique rápido deferredToast.resolve(); deferredToast = undefined; } esconderToast(); }; self.clickNoToast = function() { if (deferredToast) { timeoutToast(); // clicar no toast equivale ao timeout } }; function toastResolved() { console.log('Resolved'); self.ultimaResposta = 'Resolved'; } function toastRejected() { console.log('Rejected'); self.ultimaResposta = 'Rejected'; } } angular .module('hotMilhasApp') .controller('HomeController', ['$scope', '$q', '$timeout', HomeController]); })();
fabiosandias/hotmilhas-recru
app/scripts/controllers/HomeController.js
JavaScript
apache-2.0
1,786
'use strict'; describe('GodHasAPlan.version module', function() { beforeEach(module('GodHasAPlan.version')); describe('interpolate filter', function() { beforeEach(module(function($provide) { $provide.value('version', 'TEST_VER'); })); it('should replace VERSION', inject(function(interpolateFilter) { expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after'); })); }); });
vargose/GodHasAPlan
app/components/version/interpolate-filter_test.js
JavaScript
apache-2.0
438
var BinaryWriter = require('./BinaryWriter'); function LeaderboardPosition(position) { this.place = position } module.exports = LeaderboardPosition; LeaderboardPosition.prototype.build = function() { var buf = new BinaryWriter(); buf.writeUInt8(0x30); buf.writeUInt16(this.place); return buf.toBuffer(); };
proxiemind/MultiOgar-Edited
src/packet/LeaderboardPosition.js
JavaScript
apache-2.0
330
define( ({ loadingInfo: "Carregando...", emptyInfo: "Nenhum item a exibir", loadFailInfo: "Falha ao carregar dados!" }) );
andrescabrera/gwt-dojo-toolkit
src/gwt/dojo/gridx/public/dojo/gridx/nls/pt/Body.js
JavaScript
apache-2.0
127
Polymer('x-foo')
jarrodek/feed-reader
paper/lib_new/polymer/workbench/styling/host.html.0.js
JavaScript
apache-2.0
16
import IPTTProgram, { forIPTT } from '../models/ipttProgram'; describe("bare iptt program", () => { const Program = forIPTT; it("handles frequencies", () => { let program = Program({frequencies: [3, 4]}); expect(program.validFrequency(3)).toBeTruthy(); expect(program.validFrequency(2)).toBeFalsy(); let program2 = Program({frequencies: []}); expect(program2.validFrequency(3)).toBeFalsy(); }); it("handles disaggregations", () => { let program = Program({disaggregations: [{pk: 4, name: 'Test Disaggregation', labels: [{pk: '10', name: "banana"}]}]}); expect(Array.from(program.disaggregations.values())).toStrictEqual([{pk: 4, name: 'Test Disaggregation', labels: [{pk: 10, name: "banana"}], country: null}]); }); it("doesn't show category-less disaggregations", () => { let program = Program({disaggregations: [{pk: 4, name: 'Test Disaggregation', labels: []}]}); expect(Array.from(program.disaggregations.values())).toStrictEqual([]); }); });
mercycorps/TolaActivity
js/pages/iptt_report/__tests__/ipttProgram.test.js
JavaScript
apache-2.0
1,047
import SectionUtilities from '../../transform/SectionUtilities' /** * Hide or unhide a section. * @param {!string} sectionId * @param {?boolean} hidden * @return {void} */ const setHidden = (sectionId, hidden) => { if (!document) { return } SectionUtilities.setHidden(document, sectionId, hidden) } export default { getOffsets: SectionUtilities.getSectionOffsets, setHidden }
wikimedia/mediawiki-services-mobileapps
pagelib/src/pcs/c1/Sections.js
JavaScript
apache-2.0
396
"use strict"; window.mushroom.state.play2 = { preload: function(){ console.log("loading play2 state"); }, create: function(){ console.log("starting play2 state"); this.game.camera.x = 1800; this.redsea = mt.create("redsea"); this.Pathway2 = mt.create("Pathway2"); this.player=mt.create("weirdmushroom1"); this.enemy=mt.create("evilmushroom1"); this.enemy2=mt.create("evilmushroom2"); this.coins2=mt.create("coins2"); this.score=mt.create("score"); this.timer1=mt.create("timer1"); this.seconds = 0; this.timer1_count = 0; this.score_count = 0; this.Lkey = this.input.keyboard.addKey(Phaser.Keyboard.LEFT); this.Rkey = this.input.keyboard.addKey(Phaser.Keyboard.RIGHT); this.Ukey = this.input.keyboard.addKey(Phaser.Keyboard.UP); }, update: function(){ //Increase time by one second this.timer1_count +=1; if(this.timer1_count == 60 ){ this.seconds +=1; this.timer1.text = this.seconds; this.timer1_count = 0; } //this.game.physics.arcade.collide(this.player, this.pathway); this.game.physics.arcade.collide(this.player, this.Pathway2); this.game.physics.arcade.collide(this.player, this.enemy.self,this.restartGame, null, this); this.game.physics.arcade.collide(this.player, this.enemy2.self,this.restartGame, null, this); this.game.physics.arcade.overlap(this.player, this.coins2.self, this.destroyObject, null, this); this.game.camera.x = this.player.position.x - 400; this.game.camera.y = this.player.position.y - 300; if(this.enemy.body.position.y > 820){ this.enemy.body.position.y = -100; this.enemy.body.position.x = 1800 + Math.random() * 1800; this.enemy.body.velocity.y = 0; } if(this.enemy2.body.position.y > 820){ this.enemy2.body.position.y = -100; this.enemy2.body.position.x = 1800 + Math.random() * 1800; this.enemy2.body.velocity.y = 0; } if(this.Lkey.isDown){ this.player.body.velocity.x -= 5; } else if(this.Rkey.isDown){ this.player.body.velocity.x += 5; } else if (this.Ukey.isDown && this.player.body.touching.down ){ this.player.body.velocity.y -=400; } else{ this.player.body.velocity.x = 0; } /*if(this.score_count == 10){ this.switchLevel(); }*/ }, destroyObject: function(player,coin){ this.score_count +=10; this.score.text = this.score_count; coin.destroy(); }, restartGame: function(){ this.game.state.start("play2"); }, switchLevel: function(){ this.game.state.start("play3"); } };
Byte-Camp/Website
static/best-ofs/2Dgame/Shengming - Mushroom/js/state/play2.js
JavaScript
apache-2.0
2,523
/****************************************************************************** * supplier.js * * Copyright 2016 Marcos Salomão * * 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. * * @version 1.0 * @author Marcos Salomão (salomao.marcos@gmail.com) *****************************************************************************/ /** * Objeto global relativo aos fornecedores da loja. */ ! function($) { /* * Inserindo o escopo de fornecedor. */ $.supplier = {}; /***************************************************************************** * Controller API *****************************************************************************/ /** * Métodos relativos à API do recurso fornecedor. */ $.supplier.api = { SERVICE_NAME : '/supplier', service : function(pathVariable) { return $.supplier.api.SERVICE_NAME + (pathVariable? '/' + pathVariable : ''); }, /** * Método persiste o fornecedor. */ save: function(_data) { // Execute custumers delete endpoint return $.api.request({ path : $.supplier.api.service(), method : 'POST', body : _data, dialogSuccess : { title : messages.supplier.save.dialog.title, message : messages.supplier.save.dialog.success }, dialogError : { title : messages.supplier.save.dialog.title, message : messages.supplier.save.dialog.errormessage } }).then(function(response) { $('form.supplier-form').populate(response.result); return response; }); }, // End save() /** * Método realiza a exclusão do fornecedor. */ delete: function(_id) { // Execute custumers delete endpoint return $.api.request({ path : $.supplier.api.service(_id), method : 'DELETE', dialogError : { title : messages.supplier.delete.dialog.title, message : messages.supplier.delete.dialog.errormessage } }); }, // End delete() }; // Fim API /***************************************************************************** * View components *****************************************************************************/ $.supplier.view = { /** * Método destinado à criar a tabela com os fornecedors. */ bindTable: function(_data) { // Construir tabela $('table.table-suppliers').dataTable({ service: $.supplier.api.service(), errorMessage: messages.supplier.list.dialog.errormessage, columns: [{ field: 'id', visible: false }, { field: 'name', title: messages.supplier.name, searchable: true }, { title: '', align: 'center', searchable: false, 'class': 'col-sm-2', formatter: $.common.view.tableactionbuttons, events: { 'click button.delete': function(e, value, row, index) { $.supplier.api.delete(row.id).then( function() { $('table.table-suppliers').bootstrapTable('remove', { field: 'id', values: [row.id] }); }); }, 'click button.update': function(e, value, row, index) { // Preencher form, precisa ser primeiro show tab // senão não atualiza o map $('form.supplier-form').populate(row); // mostar tab do form $('.nav-tabs a[href="#tab_2"]').tab('show'); } } }] }); }, // Fim bindTable /** * Método destinado à carregar a tabela com os fornecedors. */ loadTable: function() { $.supplier.view.bindTable(); }, // Fim loadTable /** * Load page event. */ loadPage : function() { // Aplicar i18n $('span.tab_list').text(messages.supplier.tab.list); $('span.tab_save').text(messages.supplier.tab.save); $('h3.supplier_save_title').text(messages.supplier.save.title); $('span.new-item').text(messages.action.new_item); $('small.supplier_save_subtitle').text(messages.supplier.save.subtitle); $('label.name').text(messages.supplier.name); $('input[name="name"]').attr('placeholder', messages.supplier.form.name.placeholder); $('label.email').text(messages.supplier.email); $('input[name="email"]').attr('placeholder', messages.supplier.form.email.placeholder); $('label.phone').text(messages.supplier.phone); $('input[name="phone"]').attr('placeholder', messages.supplier.form.phone.placeholder); $('label.location').text(messages.supplier.location); $('input[name="location"]').attr('placeholder', messages.supplier.form.location.placeholder); $('button.save').text(messages.action.save); // Carregar a lista de fornecedors $.supplier.view.loadTable(); // Criar a validação do formulário $('form.supplier-form').validate({ // initialize the plugin rules: { name: { required: true, minlength: 3 }, email : { email: true } }, messages: { name: messages.supplier.form.name.required, email: messages.supplier.form.email.valid }, /** * Ação ao submeter o formulário. */ submitHandler: function(form, event) { // não submete form event.preventDefault(); // Convert form to JSON Object var data = $(form).serializeObject(); // Submeter ao endpoint $.supplier.api.save(data).then(function(_data) { // Atualizar lista var row = $('table.table-suppliers').bootstrapTable( 'getRowByUniqueId', _data.id); // Insere se não existe ou atualiza caso já esteja inserida if (row == null) { $('table.table-suppliers').bootstrapTable('insertRow', { index: 0, row: _data }); } else { $('table.table-suppliers').bootstrapTable('updateByUniqueId', { id: _data.id, row: _data }); } }); } }); // Fim validate $('.nav-tabs-custom').on('shown.bs.tab', function(e) { if ($(e.target).attr('href') != '#tab_2') return; $('.map-canvas').maps({ autocomplete : $('input[name="location"]') }); }); } }; }(jQuery);
salomax/livremkt
src/main/resources/static/app/supplier/supplier.js
JavaScript
apache-2.0
8,615
'use strict'; angular.module('Home').controller('ModalDeleteAssetCtrl', function ($scope, $modalInstance, parentScope, HomeService, asset, name, token, typeId, menuId) { $scope.name = name; $scope.message = "Are you sure you want to delete this asset ?"; $scope.ok = function () { HomeService.deleteAsset( token, menuId, asset, function (response) { if (response) { if (response.error_description) { $scope.error = response.error_description + ". Please logout!"; } else { if (response.success) { parentScope.removeAssetFromTemplate(typeId, asset); } else { $scope.message = response.message; } } } else { $scope.error = "Invalid server response"; } } ); $modalInstance.close(); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; });
fixxit/MoknJ-WebUI
modules/templatetypes/asset/delete/controllers.js
JavaScript
apache-2.0
1,480
/** * guy * 异步树 * @class BI.TreeView * @extends BI.Pane */ BI.TreeView = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.TreeView.superclass._defaultConfig.apply(this, arguments), { _baseCls: "bi-tree", paras: { selectedValues: {} }, itemsCreator: BI.emptyFn }); }, _init: function () { BI.TreeView.superclass._init.apply(this, arguments); var o = this.options; this._stop = false; this._createTree(); this.tip = BI.createWidget({ type: "bi.loading_bar", invisible: true, handler: BI.bind(this._loadMore, this) }); BI.createWidget({ type: "bi.vertical", scrollable: true, scrolly: false, element: this, items: [this.tip] }); if(BI.isNotNull(o.value)) { this.setSelectedValue(o.value); } if (BI.isIE9Below && BI.isIE9Below()) { this.element.addClass("hack"); } }, _createTree: function () { this.id = "bi-tree" + BI.UUID(); if (this.nodes) { this.nodes.destroy(); } if (this.tree) { this.tree.destroy(); } this.tree = BI.createWidget({ type: "bi.layout", element: "<ul id='" + this.id + "' class='ztree'></ul>" }); BI.createWidget({ type: "bi.default", element: this.element, items: [this.tree] }); }, // 选择节点触发方法 _selectTreeNode: function (treeId, treeNode) { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this); this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this); }, // 配置属性 _configSetting: function () { var paras = this.options.paras; var self = this; var setting = { async: { enable: true, url: getUrl, autoParam: ["id", "name"], // 节点展开异步请求自动提交id和name otherParam: BI.cjkEncodeDO(paras) // 静态参数 }, check: { enable: true }, data: { key: { title: "title", name: "text" // 节点的name属性替换成text }, simpleData: { enable: true // 可以穿id,pid属性的对象数组 } }, view: { showIcon: false, expandSpeed: "", nameIsHTML: true, // 节点可以用html标签代替 dblClickExpand: false }, callback: { beforeExpand: beforeExpand, onAsyncSuccess: onAsyncSuccess, onAsyncError: onAsyncError, beforeCheck: beforeCheck, onCheck: onCheck, onExpand: onExpand, onCollapse: onCollapse, onClick: onClick } }; var className = "dark", perTime = 100; function onClick (event, treeId, treeNode) { // 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选 var checked = treeNode.checked; var status = treeNode.getCheckStatus(); if(status.half === true && status.checked === true) { checked = false; } // 更新此node的check状态, 影响父子关联,并调用beforeCheck和onCheck回调 self.nodes.checkNode(treeNode, !checked, true, true); } function getUrl (treeId, treeNode) { var parentNode = self._getParentValues(treeNode); treeNode.times = treeNode.times || 1; var param = "id=" + treeNode.id + "&times=" + (treeNode.times++) + "&parentValues= " + _global.encodeURIComponent(BI.jsonEncode(parentNode)) + "&checkState=" + _global.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus())); return "&" + param; } function beforeExpand (treeId, treeNode) { if (!treeNode.isAjaxing) { if (!treeNode.children) { treeNode.times = 1; ajaxGetNodes(treeNode, "refresh"); } return true; } BI.Msg.toast("Please Wait。", "warning"); // 不展开节点,也不触发onExpand事件 return false; } function onAsyncSuccess (event, treeId, treeNode, msg) { treeNode.halfCheck = false; if (!msg || msg.length === 0 || /^<html>[\s,\S]*<\/html>$/gi.test(msg) || self._stop) { return; } var zTree = self.nodes; var totalCount = treeNode.count || 0; // 尝试去获取下一组节点,若获取值为空数组,表示获取完成 // TODO by GUY if (treeNode.children.length > totalCount) { treeNode.count = treeNode.children.length; BI.delay(function () { ajaxGetNodes(treeNode); }, perTime); } else { // treeNode.icon = ""; zTree.updateNode(treeNode); zTree.selectNode(treeNode.children[0]); // className = (className === "dark" ? "":"dark"); } } function onAsyncError (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { var zTree = self.nodes; BI.Msg.toast("Error!", "warning"); // treeNode.icon = ""; // zTree.updateNode(treeNode); } function ajaxGetNodes (treeNode, reloadType) { var zTree = self.nodes; if (reloadType == "refresh") { zTree.updateNode(treeNode); // 刷新一下当前节点,如果treeNode.xxx被改了的话 } zTree.reAsyncChildNodes(treeNode, reloadType, true); // 强制加载子节点,reloadType === refresh为先清空再加载,否则为追加到现有子节点之后 } function beforeCheck (treeId, treeNode) { treeNode.halfCheck = false; if (treeNode.checked === true) { // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy // 所有的半选状态都需要取消halfCheck=true的情况 function track (children) { BI.each(children, function (i, ch) { if (ch.halfCheck === true) { ch.halfCheck = false; track(ch.children); } }); } track(treeNode.children); var treeObj = self.nodes; var nodes = treeObj.getSelectedNodes(); BI.$.each(nodes, function (index, node) { node.halfCheck = false; }); } var status = treeNode.getCheckStatus(); // 当前点击节点的状态是半选,且为true_part, 则将其改为false_part,使得点击半选后切换到的是全选 if(status.half === true && status.checked === true) { treeNode.checked = false; } } function onCheck (event, treeId, treeNode) { self._selectTreeNode(treeId, treeNode); } function onExpand (event, treeId, treeNode) { treeNode.halfCheck = false; } function onCollapse (event, treeId, treeNode) { } return setting; }, _getParentValues: function (treeNode) { if (!treeNode.getParentNode()) { return []; } var parentNode = treeNode.getParentNode(); var result = this._getParentValues(parentNode); result = result.concat([this._getNodeValue(parentNode)]); return result; }, _getNodeValue: function (node) { // 去除标红 return node.value == null ? BI.replaceAll(node.text.replace(/<[^>]+>/g, ""), "&nbsp;", " ") : node.value; }, // 获取半选框值 _getHalfSelectedValues: function (map, node) { var self = this; var checkState = node.getCheckStatus(); // 将未选的去掉 if (checkState.checked === false && checkState.half === false) { return; } // 如果节点已展开,并且是半选 if (BI.isNotEmptyArray(node.children) && checkState.half === true) { var children = node.children; BI.each(children, function (i, ch) { self._getHalfSelectedValues(map, ch); }); return; } var parent = node.parentValues || self._getParentValues(node); var path = parent.concat(this._getNodeValue(node)); // 当前节点是全选的,因为上面的判断已经排除了不选和半选 if (BI.isNotEmptyArray(node.children) || checkState.half === false) { this._buildTree(map, path); return; } // 剩下的就是半选不展开的节点,因为不知道里面是什么情况,所以借助selectedValues(这个是完整的选中情况) var storeValues = BI.deepClone(this.options.paras.selectedValues); var treeNode = this._getTree(storeValues, path); this._addTreeNode(map, parent, this._getNodeValue(node), treeNode); }, // 获取的是以values最后一个节点为根的子树 _getTree: function (map, values) { var cur = map; BI.any(values, function (i, value) { if (cur[value] == null) { return true; } cur = cur[value]; }); return cur; }, // 以values为path一路向里补充map, 并在末尾节点添加key: value节点 _addTreeNode: function (map, values, key, value) { var cur = map; BI.each(values, function (i, value) { if (cur[value] == null) { cur[value] = {}; } cur = cur[value]; }); cur[key] = value; }, // 构造树节点 _buildTree: function (map, values) { var cur = map; BI.each(values, function (i, value) { if (cur[value] == null) { cur[value] = {}; } cur = cur[value]; }); }, // 获取选中的值 _getSelectedValues: function () { var self = this; var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); // 可以看到这个方法没有递归调用,所以在_getHalfSelectedValues中需要关心全选的节点 function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === true || checkState.half === true) { if (checkState.half === true) { self._getHalfSelectedValues(hashMap, node); } else { var parentValues = node.parentValues || self._getParentValues(node); var values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); } } }); } return hashMap; }, // 处理节点 _dealWidthNodes: function (nodes) { var self = this, o = this.options; var ns = BI.Tree.arrayFormat(nodes); BI.each(ns, function (i, n) { n.title = n.title || n.text || n.value; n.isParent = n.isParent || n.parent; // 处理标红 if (BI.isKey(o.paras.keyword)) { n.text = BI.$("<div>").__textKeywordMarked__(n.text, o.paras.keyword, n.py).html(); } else { n.text = BI.htmlEncode(n.text + ""); } }); return nodes; }, _loadMore: function () { var self = this, o = this.options; this.tip.setLoading(); var op = BI.extend({}, o.paras, { times: ++this.times }); o.itemsCreator(op, function (res) { if (self._stop === true) { return; } var hasNext = !!res.hasNext, nodes = res.items || []; if (!hasNext) { self.tip.setEnd(); } else { self.tip.setLoaded(); } if (nodes.length > 0) { self.nodes.addNodes(null, self._dealWidthNodes(nodes)); } }); }, // 生成树内部方法 _initTree: function (setting) { var self = this, o = this.options; self.fireEvent(BI.Events.INIT); this.times = 1; var tree = this.tree; tree.empty(); this.loading(); this.tip.setVisible(false); var callback = function (nodes) { if (self._stop === true) { return; } self.nodes = BI.$.fn.zTree.init(tree.element, setting, nodes); }; var op = BI.extend({}, o.paras, { times: 1 }); o.itemsCreator(op, function (res) { if (self._stop === true) { return; } var hasNext = !!res.hasNext, nodes = res.items || []; if (nodes.length > 0) { callback(self._dealWidthNodes(nodes)); } self.setTipVisible(nodes.length <= 0); self.loaded(); if (!hasNext) { self.tip.invisible(); } else { self.tip.setLoaded(); } op.times === 1 && self.fireEvent(BI.Events.AFTERINIT); }); }, // 构造树结构, initTree: function (nodes, setting) { var setting = setting || { async: { enable: false }, check: { enable: false }, data: { key: { title: "title", name: "text" }, simpleData: { enable: true } }, view: { showIcon: false, expandSpeed: "", nameIsHTML: true }, callback: {} }; this.nodes = BI.$.fn.zTree.init(this.tree.element, setting, nodes); }, start: function () { this._stop = false; }, stop: function () { this._stop = true; }, // 生成树方法 stroke: function (config) { delete this.options.keyword; BI.extend(this.options.paras, config); var setting = this._configSetting(); this._createTree(); this.start(); this._initTree(setting); }, populate: function () { this.stroke.apply(this, arguments); }, hasChecked: function () { var treeObj = this.nodes; return treeObj.getCheckedNodes(true).length > 0; }, checkAll: function (checked) { function setNode (children) { BI.each(children, function (i, child) { child.halfCheck = false; setNode(child.children); }); } if (!this.nodes) { return; } BI.each(this.nodes.getNodes(), function (i, node) { node.halfCheck = false; setNode(node.children); }); this.nodes.checkAllNodes(checked); }, expandAll: function (flag) { this.nodes && this.nodes.expandAll(flag); }, // 设置树节点的状态 setValue: function (value, param) { this.checkAll(false); this.updateValue(value, param); this.refresh(); }, setSelectedValue: function (value) { this.options.paras.selectedValues = BI.deepClone(value || {}); }, updateValue: function (values, param) { if (!this.nodes) { return; } param || (param = "value"); var treeObj = this.nodes; BI.each(values, function (v, op) { var nodes = treeObj.getNodesByParam(param, v, null); BI.each(nodes, function (j, node) { BI.extend(node, {checked: true}, op); treeObj.updateNode(node); }); }); }, refresh: function () { this.nodes && this.nodes.refresh(); }, getValue: function () { if (!this.nodes) { return null; } return this._getSelectedValues(); }, destroyed: function () { this.stop(); this.nodes && this.nodes.destroy(); } }); BI.extend(BI.TreeView, { REQ_TYPE_INIT_DATA: 1, REQ_TYPE_ADJUST_DATA: 2, REQ_TYPE_SELECT_DATA: 3, REQ_TYPE_GET_SELECTED_DATA: 4 }); BI.TreeView.EVENT_CHANGE = "EVENT_CHANGE"; BI.TreeView.EVENT_INIT = BI.Events.INIT; BI.TreeView.EVENT_AFTERINIT = BI.Events.AFTERINIT; BI.shortcut("bi.tree_view", BI.TreeView);
fanruan/fineui
src/base/tree/ztree/treeview.js
JavaScript
apache-2.0
17,478
#!/usr/bin/env node /** * * Copyright 2014-2019 David Herron * * This file is part of AkashaCMS (http://akashacms.com/). * * 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. */ 'use strict'; const program = require('commander'); const ghpages = require('gh-pages'); const fs = require('fs'); const fsp = require('fs/promises'); const path = require('path'); const util = require('util'); const filez = require('./filez'); const data = require('./data'); // Note this is an ES6 module and to use it we must // use an async function along with the await keyword const _filecache = import('./cache/file-cache.mjs'); const _watchman = import('./cache/watchman.mjs'); process.title = 'akasharender'; program.version('0.7.5'); program .command('copy-assets <configFN>') .description('Copy assets into output directory') .action(async (configFN) => { try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupAssets(config); let filecache = await _filecache; await filecache.assets.isReady(); await config.copyAssets(); await akasha.closeCaches(); } catch (e) { console.error(`copy-assets command ERRORED ${e.stack}`); } }); program .command('document <configFN> <documentFN>') .description('Show information about a document') .action(async (configFN, documentFN) => { try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); const filecache = await _filecache; const documents = filecache.documents; await documents.isReady(); const doc = await documents.find(documentFN); // data: ${doc.data} // text: ${doc.text} console.log(` basedir: ${doc.basedir} docpath: ${doc.docpath} fspath: ${doc.fspath} renderer: ${util.inspect(doc.renderer)} renderpath: ${doc.renderpath} metadata: ${util.inspect(doc.metadata)} `); await akasha.closeCaches(); } catch (e) { console.error(`document command ERRORED ${e.stack}`); } }); program .command('render-document <configFN> <documentFN>') .description('Render a document into output directory') .action(async (configFN, documentFN) => { try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetupComplete(config); data.init(); console.log(`render-document before renderPath ${documentFN}`); let result = await akasha.renderPath(config, documentFN); console.log(result); await akasha.closeCaches(); } catch (e) { console.error(`render-document command ERRORED ${e.stack}`); } }); program .command('render <configFN>') .description('Render a site into output directory') .option('--quiet', 'Do not print the rendering report') .option('--results-to <resultFile>', 'Store the results into the named file') .option('--perfresults <perfResultsFile>', 'Store the time to render each document') .action(async (configFN, cmdObj) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetupComplete(config); data.init(); let results = await akasha.render(config); if (!cmdObj.quiet) { for (let result of results) { // TODO --- if AKASHARENDER_TRACE_RENDER then output tracing data // TODO --- also set process.env.GLOBFS_TRACE=1 if (result.error) { console.error(result.error); } else { console.log(result.result); // console.log(util.inspect(result.result)); } } } if (cmdObj.resultsTo) { const output = fs.createWriteStream(cmdObj.resultsTo); for (let result of results) { if (result.error) { output.write('****ERROR '+ result.error + '\n'); } else { output.write(result.result + '\n'); // console.log(util.inspect(result.result)); } } output.close(); } if (cmdObj.perfresults) { const output = fs.createWriteStream(cmdObj.perfresults); for (let result of results) { if (result.error) { // Ignore } else if (result.result.startsWith('COPY')) { // Ignore } else { let results = result.result.split('\n'); let perf = results[0]; let matches = perf.match(/.* ==> (.*) \(([0-9\.]+) seconds\)$/); if (!matches) continue; if (matches.length < 3) continue; let fn = matches[1]; let time = matches[2]; let report = `${time} ${fn}`; for (let i = 1; i < results.length; i++) { let stages = results[i].match(/(FRONTMATTER|FIRST RENDER|SECOND RENDER|MAHABHUTA|RENDERED) ([0-9\.]+) seconds$/); if (!stages || stages.length < 3) continue; report += ` ${stages[1]} ${stages[2]}`; } output.write(`${report}\n`); } } output.close(); } await akasha.closeCaches(); } catch (e) { console.error(`render command ERRORED ${e.stack}`); } }); program .command('explain <configFN>') .description('Explain a cache query') .action(async (configFN) => { try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); let filecache = await _filecache; await filecache.documents.isReady(); data.init(); let explanation = filecache.documents .getCollection(filecache.documents.collection) .explain( /* { $or: [ { vpath: { $eeq: "archive/java.net/2005/08/findbugs.html.md" } }, { renderPath: { $eeq: "archive/java.net/2005/08/findbugs.html" } } ] } */ { renderPath: /\.html$/, vpath: /^blog\/2019\//, docMetadata: { layout: { $in: [ "blog.html.ejs", "blog.html.njk", "blog.html.handlebars" ] }, blogtag: { $eeq: "news" } } } ); // console.log(JSON.stringify(explanation, undefined, ' ')); console.log(`EXPLAINING ${explanation.operation} results: ${explanation.results}`); console.log('Analysis ', explanation.analysis); console.log('Analysis - query ', explanation.analysis.query); console.log('Steps ', explanation.steps); console.log('Time ', explanation.time); console.log('Index ', explanation.index); console.log('Log ', explanation.log); await akasha.closeCaches(); } catch (e) { console.error(`render command ERRORED ${e.stack}`); } }); program .command('watch <configFN>') .description('Track changes to files in a site, and rebuild anything that changes') .action(async (configFN, cmdObj) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetupComplete(config); data.init(); // console.log('CALLING config.hookBeforeSiteRendered'); await config.hookBeforeSiteRendered(); const watchman = (await _watchman).watchman; await watchman(config); // await akasha.closeCaches(); } catch (e) { console.error(`watch command ERRORED ${e.stack}`); } }); program .command('gh-pages-publish <configFN>') .description('Publish a site using Github Pages. Takes the rendering destination, adds it into a branch, and pushes that to Github') .option('-b, --branch <branchName>', 'The branch to use for publishing to Github') .option('-r, --repo <repoURL>', 'The repository URL to use if it must differ from the URL of the local directory') .option('--remote <remoteName>', 'The Git remote name to use if it must differ from "origin"') .option('--tag <tag>', 'Any tag to add when pushing to Github') .option('--message <message>', 'Any Git commit message') .option('--username <username>', 'Github user name to use') .option('--email <email>', 'Github user email to use') .option('--nopush', 'Do not push to Github, only commit') .action(async (configFN, cmdObj) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; let options = { dotfiles: true }; if (cmdObj.branch) { options.branch = cmdObj.branch; } if (cmdObj.repoURL) { options.repo = cmdObj.repoURL; } if (cmdObj.remote) { options.remote = cmdObj.remote; } if (cmdObj.tag) { options.tag = cmdObj.tag; } if (cmdObj.message) { options.message = cmdObj.message; } if (cmdObj.username || cmdObj.email) { options.user = {}; } if (cmdObj.username) { options.user.name = cmdObj.username; } if (cmdObj.email) { options.user.email = cmdObj.email; } if (cmdObj.nopush) { options.push = false; } // console.log(`gh-pages-publish options ${config.renderDestination} cmdObj ${util.inspect(cmdObj)} options ${util.inspect(options)}`); ghpages.publish(config.renderDestination, options, function(err) { if (err) console.error(err); else console.log('OK'); }); } catch (e) { console.error(`gh-pages-publish command ERRORED ${e.stack}`); } }); program .command('config <configFN>') .description('Print a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; console.log(config); } catch (e) { console.error(`config command ERRORED ${e.stack}`); } }); program .command('docdirs <configFN>') .description('List the documents directories in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); console.log(config.documentDirs); } catch (e) { console.error(`docdirs command ERRORED ${e.stack}`); } }); program .command('assetdirs <configFN>') .description('List the assets directories in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); console.log(config.assetDirs); } catch (e) { console.error(`assetdirs command ERRORED ${e.stack}`); } }); program .command('partialdirs <configFN>') .description('List the partials directories in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); console.log(config.partialsDirs); } catch (e) { console.error(`partialdirs command ERRORED ${e.stack}`); } }); program .command('layoutsdirs <configFN>') .description('List the layouts directories in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); console.log(config.layoutDirs); } catch (e) { console.error(`layoutsdirs command ERRORED ${e.stack}`); } }); program .command('documents <configFN>') .description('List the documents in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.documents.isReady(); console.log(filecache.documents.paths()); await akasha.closeCaches(); } catch (e) { console.error(`documents command ERRORED ${e.stack}`); } }); program .command('docinfo <configFN> <docFN>') .description('Show information about a document in a site configuration') .action(async (configFN, docFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.documents.isReady(); console.log(`docFN ${docFN} `, filecache.documents.find(docFN)); await akasha.closeCaches(); } catch (e) { console.error(`docinfo command ERRORED ${e.stack}`); } }); program .command('tags <configFN>') .description('List the tags') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.documents.isReady(); console.log(filecache.documents.tags()); await akasha.closeCaches(); } catch (e) { console.error(`docinfo command ERRORED ${e.stack}`); } }); program .command('search <configFN>') .description('Search for documents') .option('--root <rootPath>', 'Select only files within the named directory') .option('--match <pathmatch>', 'Select only files matching the regular expression') .option('--glob <globmatch>', 'Select only files matching the glob expression') .option('--renderglob <globmatch>', 'Select only files rendering to the glob expression') .option('--layout <layout>', 'Select only files matching the layouts') .option('--mime <mime>', 'Select only files matching the MIME type') .option('--tag <tag>', 'Select only files with the tag') .action(async (configFN, cmdObj) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupDocuments(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.documents.isReady(); // console.log(cmdObj); let options = { }; if (cmdObj.root) options.rootPath = cmdObj.root; if (cmdObj.match) options.pathmatch = cmdObj.match; if (cmdObj.glob) options.glob = cmdObj.glob; if (cmdObj.renderglob) options.renderglob = cmdObj.renderglob; if (cmdObj.layout) options.layouts = cmdObj.layout; if (cmdObj.mime) options.mime = cmdObj.mime; if (cmdObj.tag) options.tag = cmdObj.tag; // console.log(options); let docs = filecache.documents.search(config, options); console.log(docs); await akasha.closeCaches(); } catch (e) { console.error(`search command ERRORED ${e.stack}`); } }); program .command('assets <configFN>') .description('List the assets in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupAssets(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.assets.isReady(); console.log(filecache.assets.paths()); await akasha.closeCaches(); } catch (e) { console.error(`assets command ERRORED ${e.stack}`); } }); program .command('assetinfo <configFN> <docFN>') .description('Show information about an asset in a site configuration') .action(async (configFN, assetFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupAssets(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.assets.isReady(); console.log(filecache.assets.find(assetFN)); await akasha.closeCaches(); } catch (e) { console.error(`assetinfo command ERRORED ${e.stack}`); } }); program .command('layouts <configFN>') .description('List the layouts in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupLayouts(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.layouts.isReady(); console.log(filecache.layouts.paths()); await akasha.closeCaches(); } catch (e) { console.error(`layouts command ERRORED ${e.stack}`); } }); // TODO both test.html and test.html.njk match // This is probably incorrect, since we do not render these files // The partials directory has the same problem // Some kind of flag on creating the FileCache to change the behavior program .command('layoutinfo <configFN> <docFN>') .description('Show information about a layout in a site configuration') .action(async (configFN, layoutFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupLayouts(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.layouts.isReady(); console.log(filecache.layouts.find(layoutFN)); await akasha.closeCaches(); } catch (e) { console.error(`layoutinfo command ERRORED ${e.stack}`); } }); program .command('partials <configFN>') .description('List the partials in a site configuration') .action(async (configFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; await akasha.cacheSetup(config); await akasha.setupPartials(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.partials.isReady(); await akasha.setupPluginCaches(config) console.log(filecache.partials.paths()); await akasha.closeCaches(); } catch (e) { console.error(`partials command ERRORED ${e.stack}`); } }); // TODO both test.html and test.html.njk match // This is probably incorrect, since we do not render these files program .command('partialinfo <configFN> <docFN>') .description('Show information about a partial in a site configuration') .action(async (configFN, partialFN) => { // console.log(`render: akasha: ${util.inspect(akasha)}`); try { const config = require(path.join(process.cwd(), configFN)); let akasha = config.akasha; // await akasha.cacheSetupComplete(config); await akasha.cacheSetup(config); await akasha.setupPartials(config); let filecache = await _filecache; // console.log(filecache.documents); await filecache.partials.isReady(); console.log(filecache.partials.find(partialFN)); await akasha.closeCaches(); } catch (e) { console.error(`partialinfo command ERRORED ${e.stack}`); } }); program.parse(process.argv);
akashacms/akasharender
cli.js
JavaScript
apache-2.0
24,258
cmapi.channel["map.view.clicked"].examples = [ { "title": "Map Clicked", "description": "Report that the map was clicked at a location", "valid": true, "payload": { "lat": 40.195659093364654, "lon": -74.28955078125, "button": "right", "type": "single", "keys": ["shift", "ctrl"] } }, { "title": "Map Clicked", "description": "Report that the map was clicked at a location", "valid": true, "payload": { "lat": 40.195659093364654, "lon": -74.28955078125, "button": "middle", "type": "double", "keys": ["none"] } }, { "title": "Map Clicked", "description": "Report that the map was clicked at a location", "valid": false, "payload": { "lat": 40.195659093364654, "lon": -74.28955078125, "button": "taco", "type": "single", "keys": ["shift", "ctrl"] } }, { "title": "Map Clicked", "description": "Report that the map was clicked at a location", "valid": false, "payload": { "lat": 40.195659093364654, "lon": -74.28955078125, "type": "single", "keys": ["shift", "ctrl"] } } ];
CMAPI/cmapi
channels/map.view.clicked.examples.js
JavaScript
apache-2.0
1,202
'use strict'; var _ = require('underscore'); var express = require('express'); var router = express.Router(); var ObjectId = require('mongoose').Types.ObjectId; var path = require('path'); /** * @apiDefine group Group based access * Resource access controlled by user's groups */ /** * @apiDefine access Authenticated user access only * User should sign in for the request */ /** * @api {get} / Get home page * @apiName GetHomePage * @apiGroup Home */ router.get('/', (req, res) => res.sendFile(path.join(__dirname, 'public', 'index.html'))); module.exports = router; module.exports.getCollection = function(req, res, model, condition) { let id = req.params.id; let cond = id ? { _id: new ObjectId(id) } : {}; condition = _.extend(cond, condition); model.find(condition, (err, result) => { if (err) { throw err; } res.send(result); }); };
vartomi/pmt-backend
routes/index.js
JavaScript
apache-2.0
886
/** * Websocket Client */ (function() { window.Socket = window.Socket || {} var PacketTypes = { Command : 0, Status : 1 } class Socket { constructor(uri, game) { uri = uri || "" if(uri.length <= 0) { let loc = window.location uri = 'ws:' if(loc.protocol === 'https:') { uri = 'wss:' } uri += '//' + loc.host uri += loc.pathname + 'ws' } this.game = game this.ready = false this.socket = new WebSocket(uri) this.socket.binaryType = "arraybuffer" this.socket.onopen = () => { this.onOpen() } this.socket.onmessage = (ev) => { this.onMessage(ev) } this.socket.onclose = () => { this.onClose() } } get closed() { this.socket.readyState == WebSocket.CLOSED } close() { this.socket.close() } onOpen() { this.ready = true } onMessage(ev) { let data = new Uint8Array(ev.data) let packetObject = msgpack.unpack(data) // If data is not correctly if(packetObject == null || packetObject.Type == "undefined") { return } switch(packetObject.Type) { case PacketTypes.Command: this.pushCommand(packetObject.Data) break case PacketTypes.Status: this.handleStatus(packetObject.Data) break } } send(type, data) { // Ignore send data if socket not open if(this.socket.readyState != WebSocket.OPEN) { return } let rawPacket = { Type: type, Data: data } // Should package as binary let packet = new Uint8Array(msgpack.pack(rawPacket)) this.socket.send(packet) } execCommand(name, team, params) { params = params || {} this.send( PacketTypes.Command, { Name: name, Team: team, Params: params } ) } pushCommand(data) { let CommandClass = Command[data.Name] if(!CommandClass) { // Invalid command return } let CommandInstance = new CommandClass(this.game, data.Team) CommandInstance.deserialize(data.Params) // Send command Command.Resolver.push(CommandInstance) } handleStatus(stat) { // TODO: the handler can improve more switch(stat.Name){ case "Register": if(stat.Value == 1) { Game.Status = GameStatus.Registered this.updateStatus("Match", 0) } break case "Match": if(stat.Value == 1) { Game.Status = GameStatus.Start } break case "Exit": Game.Status = GameStatus.End break } } updateStatus(name, value) { this.send( PacketTypes.Status, { Name: name, Value: value } ) } onClose() { } } window.Socket = Socket window.PacketType = PacketTypes }())
BasalticStudio/Walrus-vs-Slime
js/Socket.js
JavaScript
apache-2.0
3,768
 (function() { function getParentIndex(levels, level, index) { if (level > 0) { for (var i = index - 1; i >= 0; i--) { if (levels[i] == level - 1) { return i; } } } return -1; } function hasLittleBrother(levels, level, index) { if (index < levels.length - 1) { for (var i = index + 1; i < levels.length; i++) { if (levels[i] == level) { return true; } else if (levels[i] < level) { return false; } } } return false; } function getParentTempData(tempdatas, tempdata, prefixIndex) { for (var i = 0; i < prefixIndex - 1; i++) { tempdata = tempdatas[tempdata.parentIndex]; } return tempdata; } function getPrefixInner(tempdatas, tempdata, prefixIndex) { // If level = 3, then prefixIndex array will be: [3, 2, 1] // prefixIndex === 1 will always present the nearest prefix next to the Text. if (prefixIndex === 1) { if (tempdata.littleBrother) { return '<div class="x-elbow"></div>'; } else { return '<div class="x-elbow-end"></div>'; } } else { var parentdata = getParentTempData(tempdatas, tempdata, prefixIndex); if (parentdata.littleBrother) { return '<div class="x-elbow-line"></div>'; } else { return '<div class="x-elbow-empty"></div>'; } } return ""; } function getPrefix(tempdatas, index) { var tempdata = tempdatas[index]; var level = tempdata.level; var prefix = []; for (var i = level; i > 0; i--) { prefix.push(getPrefixInner(tempdatas, tempdata, i)); } return prefix.join(''); } F.simulateTree = { transform: function(datas) { if (!datas.length || datas[0].length < 4) { return datas; } //// store: new Ext.data.ArrayStore({ fields: ['value', 'text', 'enabled', 'prefix'] }) //// Sample data: //[ // ["0", "jQuery", 0, 0], // ["1", "Core", 0, 1], // ["2", "Selectors", 0, 1], // ["3", "Basic Filters", 1, 2], // ["4", "Content Filters", 1, 2], // ["41", "Contains", 1, 3], // ["5", "Attribute Filters", 1, 2], // ["6", "Traversing", 1, 1], // ["7", "Filtering", 1, 2], // ["8", "Finding", 1, 2], // ["9", "Events", 0, 1], // ["10", "Page Load", 1, 2], // ["11", "Event Handling", 1, 2], // ["12", "Interaction Helpers", 1, 2], // ["13", "Ajax", 1, 1] //] var levels = []; Ext.Array.each(datas, function (data, index) { levels.push(data[3]); }); var tempdatas = []; Ext.Array.each(levels, function (level, index) { tempdatas.push({ 'level': level, 'parentIndex': getParentIndex(levels, level, index), 'littleBrother': hasLittleBrother(levels, level, index) }); }); var newdatas = []; Ext.Array.each(datas, function (data, index) { newdatas.push([data[0], data[1], data[2], getPrefix(tempdatas, index)]); }); return newdatas; } }; })();
u0hz/FineUI
src/FineUI.Examples/extjs_builder/js/F/F.simulateTree.js
JavaScript
apache-2.0
3,857
/* @flow strict-local */ import React, { PureComponent } from 'react'; import { FlatList } from 'react-native'; import config from '../config'; import { Screen } from '../common'; import InfoItem from './InfoItem'; export default class VariablesScreen extends PureComponent<{||}> { render() { const variables = { enableReduxLogging: config.enableReduxLogging, enableReduxSlowReducerWarnings: config.enableReduxSlowReducerWarnings, 'process.env.NODE_ENV': process.env.NODE_ENV ?? '(not defined)', 'global.btoa': !!global.btoa, }; return ( <Screen title="Variables" scrollEnabled={false}> <FlatList data={Object.keys(variables)} keyExtractor={item => item} renderItem={({ item }) => <InfoItem label={item} value={variables[item]} />} /> </Screen> ); } }
vishwesh3/zulip-mobile
src/diagnostics/VariablesScreen.js
JavaScript
apache-2.0
857
import React from 'react'; import PropTypes from 'prop-types'; import ColumnChooserRow from '../ColumnChooserRow'; import { columnsPropTypes } from '../../columnChooser.propTypes'; const ColumnChooserTable = ({ columns = [], id, onChangeCheckbox, t }) => columns.map(column => ( <ColumnChooserRow key={column.key}> <ColumnChooserRow.Checkbox checked={column.visible} id={id} dataFeature="column-chooser.select" description={t('CHECKBOX_DISPLAY_COLUMN_DESCRIPTION', { defaultValue: 'display the column {{label}}', label: column.label, })} label={column.label} locked={column.locked} onChange={onChangeCheckbox} t={t} /> </ColumnChooserRow> )); ColumnChooserTable.propTypes = { columns: columnsPropTypes, id: PropTypes.string.isRequired, onChangeCheckbox: PropTypes.func.isRequired, t: PropTypes.func.isRequired, }; export default ColumnChooserTable;
Talend/ui
packages/components/src/List/Toolbar/ColumnChooserButton/ColumnChooser/ColumnChooserTable/ColumnChooserTable.component.js
JavaScript
apache-2.0
914
/** * Created by zura on 9/27/2016. */ (function () { 'use strict'; angular .module('app.pages', [ 'app.pages.auth.login' ]) .config(Config); /** @ngInject */ function Config(){ } })();
arboshiki/lobilist-angular
src/app/main/pages/pages.module.js
JavaScript
apache-2.0
246
var util = require('util'), querystring = require('querystring'), request = require('request'); function FacebookProvider(client_id, client_secret, redirect_uri) { this.client_id = client_id; this.client_secret = client_secret; this.redirect_uri = redirect_uri; } FacebookProvider.prototype.getAuthenticateURL = function (options) { return util.format('https://www.facebook.com/dialog/oauth?client_id=%s&response_type=%s&state=%s&redirect_uri=%s', (options && options.client_id) || this.client_id, 'code', String(Math.random() * 100000000), encodeURIComponent((options && options.redirect_uri) || this.redirect_uri)); }; FacebookProvider.prototype.getAuthentication = function (options, callback) { var that = this, qs = { client_id: this.client_id, client_secret: this.client_secret, grant_type: 'authorization_code', redirect_uri: options.redirect_uri || this.redirect_uri, code: options.code }; request({ method: 'GET', uri: 'https://graph.facebook.com/oauth/access_token', qs: qs, timeout: 5000 // 5 seconds }, function (err, res, body) { if (err) { return callback(err); } if (res.statusCode !== 200) { return callback(new Error('Bad response code: ' + res.statusCode)); } console.log('>>> ' + body); var r = querystring.parse(body); // get id & profile: that.requestAPI('GET', 'me', r.access_token, null, function (err, p) { if (err) { return callback(err); } callback(null, { access_token: r.access_token, refresh_token: '', expires_in: parseInt(r.expires, 10), auth_id: p.id, name: p.name, url: p.link, image_url: '' }); }); }); }; FacebookProvider.prototype.requestAPI = function (method, apiName, access_token, options, callback) { options = options || {}; options.access_token = access_token; var opts = { method: method, uri: 'https://graph.facebook.com/' + apiName, timeout: 5000 }; if (method === 'GET') { opts.qs = options; } if (method === 'POST') { opts.form = options; } request(opts, function (err, res, body) { if (err) { return callback(err); } if (res.statusCode !== 200) { return callback(new Error('Bad response code: ' + res.statusCode)); } var r; try { r = JSON.parse(body); } catch (e) { return callback(e); } if (r.error) { return callback(new Error(r.error.message)); } callback(null, r); }); }; module.exports = FacebookProvider;
michaelliao/oauth2-warp
providers/facebook.js
JavaScript
apache-2.0
2,957
define( ({ "sourceSetting": "搜索源设置", "instruction": "添加并配置地理编码服务或要素图层为搜索源。这些指定的源决定了搜索框中的可搜索内容。", "add": "添加搜索源", "addGeocoder": "添加地理编码器", "geocoder": "地理编码器", "setLayerSource": "设置图层源", "setGeocoderURL": "设置地理编码器 URL", "searchableLayer": "要素图层", "name": "名称", "countryCode": "国家代码或区域代码", "countryCodeEg": "例如 ", "countryCodeHint": "将此值留空可搜索所有国家和地区", "generalSetting": "常规设置", "allPlaceholder": "用于搜索全部内容的占位符文本: ", "showInfoWindowOnSelect": "显示已找到要素或位置的弹出窗口", "searchInCurrentMapExtent": "仅在当前地图范围内搜索", "zoomScale": "缩放比例", "locatorUrl": "地理编码器 URL", "locatorName": "地理编码器名称", "locatorExample": "示例", "locatorWarning": "不支持此版本的地理编码服务。该微件支持 10.0 及更高版本的地理编码服务。", "locatorTips": "由于地理编码服务不支持建议功能,因此建议不可用。", "layerSource": "图层源", "searchLayerTips": "由于要素服务不支持分页功能,因此建议不可用。", "placeholder": "占位符文本", "searchFields": "搜索字段", "displayField": "显示字段", "exactMatch": "完全匹配", "maxSuggestions": "最大建议数", "maxResults": "最大结果数", "setSearchFields": "设置搜索字段", "set": "设置", "fieldSearchable": "可搜索", "fieldName": "名称", "fieldAlias": "别名", "ok": "确定", "cancel": "取消", "invalidUrlTip": "URL ${URL} 无效或不可访问。" }) );
fiskinator/WAB2.0_JBox_MutualAid
widgets/Search/setting/nls/zh-cn/strings.js
JavaScript
apache-2.0
1,903
/* globals describe, it, expect, hot, cold, expectObservable, expectSubscriptions */ var Rx = require('../../dist/cjs/Rx.KitchenSink'); var Observable = Rx.Observable; describe('Observable.prototype.windowCount', function () { it('should emit windows with count 2 and skip 1', function () { var source = hot('^-a--b--c--d--|'); var subs = '^ !'; var expected = 'u-v--x--y--z--|'; var u = cold( '--a--(b|) '); var v = cold( '---b--(c|) '); var x = cold( '---c--(d|)'); var y = cold( '---d--|'); var z = cold( '---|'); var values = { u: u, v: v, x: x, y: y, z: z }; var result = source.windowCount(2, 1); expectObservable(result).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should emit windows with count 2, and skip unspecified', function () { var source = hot('--a--b--c--d--e--f--|'); var subs = '^ !'; var expected = 'x----y-----z-----w--|'; var x = cold( '--a--(b|) '); var y = cold( '---c--(d|) '); var z = cold( '---e--(f|)'); var w = cold( '---|'); var values = { x: x, y: y, z: z, w: w }; var result = source.windowCount(2); expectObservable(result).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should return empty if source is empty', function () { var source = cold('|'); var subs = '(^!)'; var expected = '(w|)'; var w = cold('|'); var values = { w: w }; var result = source.windowCount(2, 1); expectObservable(result).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should return Never if source if Never', function () { var source = cold('-'); var subs = '^'; var expected = 'w'; var w = cold('-'); var expectedValues = { w: w }; var result = source.windowCount(2, 1); expectObservable(result).toBe(expected, expectedValues); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should propagate error from a just-throw source', function () { var source = cold('#'); var subs = '(^!)'; var expected = '(w#)'; var w = cold('#'); var expectedValues = { w: w }; var result = source.windowCount(2, 1); expectObservable(result).toBe(expected, expectedValues); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should raise error if source raises error', function () { var source = hot('--a--b--c--d--e--f--#'); var subs = '^ !'; var expected = 'u-v--w--x--y--z--q--#'; var u = cold( '--a--b--(c|) '); var v = cold( '---b--c--(d|) '); var w = cold( '---c--d--(e|) '); var x = cold( '---d--e--(f|)'); var y = cold( '---e--f--#'); var z = cold( '---f--#'); var q = cold( '---#'); var values = { u: u, v: v, w: w, x: x, y: y, z: z, q: q }; var result = source.windowCount(3, 1); expectObservable(result).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should dispose of inner windows once outer is unsubscribed early', function () { var source = hot('^-a--b--c--d--|'); var subs = '^ ! '; var expected = 'w-x--y--z- '; var w = cold( '--a--(b|) '); var x = cold( '---b--(c|) '); var y = cold( '---c- '); var z = cold( '-- '); var unsub = ' ! '; var values = { w: w, x: x, y: y, z: z }; var result = source.windowCount(2, 1); expectObservable(result, unsub).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); it('should dispose window Subjects if the outer is unsubscribed early', function () { var source = hot('--a--b--c--d--e--f--g--h--|'); var sourceSubs = '^ ! '; var expected = 'x--------- '; var x = cold( '--a--b--c- '); var unsub = ' ! '; var late = time('---------------| '); var values = { x: x }; var window; var result = source.windowCount(10, 10) .do(function (w) { window = w; }); expectObservable(result, unsub).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(sourceSubs); rxTestScheduler.schedule(function () { expect(function () { window.subscribe(); }).toThrowError('Cannot subscribe to a disposed Subject.'); }, late); }); it('should not break unsubscription chains when result is unsubscribed explicitly', function () { var source = hot('^-a--b--c--d--|'); var subs = '^ ! '; var expected = 'w-x--y--z- '; var w = cold( '--a--(b|) '); var x = cold( '---b--(c|) '); var y = cold( '---c- '); var z = cold( '-- '); var unsub = ' ! '; var values = { w: w, x: x, y: y, z: z }; var result = source .mergeMap(function (i) { return Observable.of(i); }) .windowCount(2, 1) .mergeMap(function (i) { return Observable.of(i); }); expectObservable(result, unsub).toBe(expected, values); expectSubscriptions(source.subscriptions).toBe(subs); }); });
justinwoo/RxJS
spec/operators/windowCount-spec.js
JavaScript
apache-2.0
5,581
$(document).ready(function () { google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawBuildSummary); function drawBuildSummary() { var elem = $('#elapsed_time_chart'); var data = [['Elapsed Time', 'Count']]; var categories = []; //Categorize elapsed time based on their range var values = elem.attr('data-values').split(';'); var eTime = ["0", "0", "0", "0", "0", "0"]; var i = 0; values.forEach(function (str, _, _) { eTime[i] = str; i = i + 1; }); var digits = 1; var lowerRange = '0 ~ ' for (var i in eTime) { var upperRange = Math.pow(10, digits); var strRange = lowerRange + upperRange + 's' data.push([strRange, parseInt(eTime[i])]); categories.push(strRange); lowerRange = upperRange + ' ~ '; digits = digits + 1; } var dataTable = google.visualization.arrayToDataTable(data); var options = { title: 'Elapsed Time', curveType: 'function', bar: { groupWidth: '75%' }, isStacked: true }; var chart = new google.visualization.BarChart(elem.get(0)); chart.draw(dataTable, options); google.visualization.events.addListener(chart, 'select', function () { var selectedItem = chart.getSelection()[0]; if (selectedItem) { var category = categories[selectedItem.row]; $('#category_form_kind').attr('value', category); var form = $('#category_form').submit() } }); } });
jaredpar/jenkins
Dashboard/Scripts/elapsed-time.js
JavaScript
apache-2.0
1,729
var s = "Connected";
wojons/scalr
app/www/ui2/js/connection.js
JavaScript
apache-2.0
21
import React from 'react'; import Reflux from 'reflux'; import ChatActions from '../events/chat-actions'; import ChatStore from '../events/chat-store'; import classNames from 'classnames'; import {deepEqual} from '../events/chat-store-utils'; import {Dropdown, MenuItem} from 'react-bootstrap'; var GroupHeaderPane = React.createClass({ mixins: [Reflux.connect(ChatStore, 'store')], shouldComponentUpdate: function(nextProps, nextState) { return !deepEqual(this.state.store, nextState.store, ["selectedGroup.id", "selectedGroup.followed", "selectedIntegration.id", "selectedIntegrationGroupTopic.id", "selectedTopic.id", "selectedIntegrationTopic.id", "topics.id", "integrationTopics.id"]); }, onClick: function () { if (this.state.store.selectedGroup) { ChatActions.selectTopic(); } else if (this.state.store.selectedIntegrationGroup) { ChatActions.selectIntegrationTopic(this.state.store.selectedIntegration, this.state.store.selectedIntegrationGroup); } }, onFollowStateChange: function (newFollowState) { if (this.state.store.selectedGroup) { ChatActions.groupFollowStatusChange(this.state.store.selectedGroup, newFollowState); } }, render: function () { var self = this; var newTopicClass = classNames({ ["selected"]: !(self.state.store.selectedTopic || self.state.store.selectedIntegrationTopic), ["enabled"]: ((self.state.store.selectedGroup || self.state.store.selectedIntegrationGroup)) }); var groupHeader = !self.state.store.selectedIntegration && !self.state.store.selectedGroup ? "" : (!self.state.store.selectedIntegration && self.state.store.selectedGroup ? ("# " + self.state.store.selectedGroup.name) : (self.state.store.selectedGroup ? self.state.store.selectedGroup.name : self.state.store.selectedIntegration.name) ); var followedClass = classNames({ ["followed"]: self.state.store.selectedGroup && self.state.store.selectedGroup.followed }); var followTitle = self.state.store.selectedGroup && self.state.store.selectedGroup.followed ? "Unfollow" : "Follow"; var star = self.state.store.selectedGroup ? ( <span className="glyphicon glyphicon-star-empty star" onClick={self.onFollowStateChange.bind(this, !self.state.store.selectedGroup.followed)}></span> ) : null; var dropDown = self.state.store.selectedGroup ? ( <Dropdown id="group-drop-down" className="pull-right"> <a href="#" bsRole="toggle"> <span className="glyphicon glyphicon-chevron-down"></span> </a> <Dropdown.Menu bsRole="menu"> <MenuItem eventKey="1" onSelect={self.onFollowStateChange.bind(this, !self.state.store.selectedGroup.followed)}>{followTitle}</MenuItem> </Dropdown.Menu> </Dropdown> ) : null; return self.state.store.selectedGroup || self.state.store.selectedIntegration ? (<div id="group-header-pane"> <a id="new-topic" className={newTopicClass} onClick={self.onClick}> New topic </a> <div id="group-header" className={followedClass}>{groupHeader}&nbsp;&nbsp; {star} {dropDown} </div> <div className="clearfix"></div> </div>) : ( <div className="space"></div>); } }); export default GroupHeaderPane;
JetChat/JetChat
public/javascripts/components/group-header-pane.js
JavaScript
apache-2.0
3,767
/** * @license Copyright 2017 The Lighthouse Authors. All Rights Reserved. * 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. */ 'use strict'; /* global DOM, ViewerUIFeatures, ReportRenderer, DragAndDrop, GithubApi, PSIApi, logger, idbKeyval */ /** @typedef {import('./psi-api').PSIParams} PSIParams */ /** * Guaranteed context.querySelector. Always returns an element or throws if * nothing matches query. * @param {string} query * @param {ParentNode} context * @return {HTMLElement} */ function find(query, context) { /** @type {?HTMLElement} */ const result = context.querySelector(query); if (result === null) { throw new Error(`query ${query} not found`); } return result; } /** * Class that manages viewing Lighthouse reports. */ class LighthouseReportViewer { constructor() { this._onPaste = this._onPaste.bind(this); this._onSaveJson = this._onSaveJson.bind(this); this._onFileLoad = this._onFileLoad.bind(this); this._onUrlInputChange = this._onUrlInputChange.bind(this); this._dragAndDropper = new DragAndDrop(this._onFileLoad); this._github = new GithubApi(); this._psi = new PSIApi(); /** * Used for tracking whether to offer to upload as a gist. * @type {boolean} */ this._reportIsFromGist = false; this._reportIsFromPSI = false; this._reportIsFromJSON = false; this._addEventListeners(); this._loadFromDeepLink(); this._listenForMessages(); } static get APP_URL() { return `${location.origin}${location.pathname}`; } /** * Initialize event listeners. * @private */ _addEventListeners() { document.addEventListener('paste', this._onPaste); const gistUrlInput = find('.js-gist-url', document); gistUrlInput.addEventListener('change', this._onUrlInputChange); // Hidden file input to trigger manual file selector. const fileInput = find('#hidden-file-input', document); fileInput.addEventListener('change', e => { if (!e.target) { return; } const inputTarget = /** @type {HTMLInputElement} */ (e.target); if (inputTarget.files) { this._onFileLoad(inputTarget.files[0]); } inputTarget.value = ''; }); // A click on the visual placeholder will trigger the hidden file input. const placeholderTarget = find('.viewer-placeholder-inner', document); placeholderTarget.addEventListener('click', e => { const target = /** @type {?Element} */ (e.target); if (target && target.localName !== 'input' && target.localName !== 'a') { fileInput.click(); } }); } /** * Attempts to pull gist id from URL and render report from it. * @return {Promise<void>} * @private */ _loadFromDeepLink() { const params = new URLSearchParams(location.search); const gistId = params.get('gist'); const psiurl = params.get('psiurl'); const jsonurl = params.get('jsonurl'); if (!gistId && !psiurl && !jsonurl) return Promise.resolve(); this._toggleLoadingBlur(true); let loadPromise = Promise.resolve(); if (psiurl) { loadPromise = this._fetchFromPSI({ url: psiurl, category: params.has('category') ? params.getAll('category') : undefined, strategy: params.get('strategy') || undefined, locale: params.get('locale') || undefined, utm_source: params.get('utm_source') || undefined, }); } else if (gistId) { loadPromise = this._github.getGistFileContentAsJson(gistId).then(reportJson => { this._reportIsFromGist = true; this._replaceReportHtml(reportJson); }).catch(err => logger.error(err.message)); } else if (jsonurl) { const firebaseAuth = this._github.getFirebaseAuth(); loadPromise = firebaseAuth.getAccessTokenIfLoggedIn() .then(token => { return token ? Promise.reject(new Error('Can only use jsonurl when not logged in')) : null; }) .then(() => fetch(jsonurl)) .then(resp => resp.json()) .then(json => { this._reportIsFromJSON = true; this._replaceReportHtml(json); }) .catch(err => logger.error(err.message)); } return loadPromise.finally(() => this._toggleLoadingBlur(false)); } /** * Basic Lighthouse report JSON validation. * @param {LH.Result} reportJson * @private */ _validateReportJson(reportJson) { if (!reportJson.lighthouseVersion) { throw new Error('JSON file was not generated by Lighthouse'); } // Leave off patch version in the comparison. const semverRe = new RegExp(/^(\d+)?\.(\d+)?\.(\d+)$/); const reportVersion = reportJson.lighthouseVersion.replace(semverRe, '$1.$2'); const lhVersion = window.LH_CURRENT_VERSION.replace(semverRe, '$1.$2'); if (reportVersion < lhVersion) { // TODO: figure out how to handler older reports. All permalinks to older // reports will start to throw this warning when the viewer rev's its // minor LH version. // See https://github.com/GoogleChrome/lighthouse/issues/1108 logger.warn('Results may not display properly.\n' + 'Report was created with an earlier version of ' + `Lighthouse (${reportJson.lighthouseVersion}). The latest ` + `version is ${window.LH_CURRENT_VERSION}.`); } } /** * @param {LH.Result} json * @private */ // TODO: Really, `json` should really have type `unknown` and // we can have _validateReportJson verify that it's an LH.Result _replaceReportHtml(json) { // Allow users to view the runnerResult if ('lhr' in json) { json = /** @type {LH.RunnerResult} */ (json).lhr; } // Install as global for easier debugging // @ts-ignore window.__LIGHTHOUSE_JSON__ = json; // eslint-disable-next-line no-console console.log('window.__LIGHTHOUSE_JSON__', json); this._validateReportJson(json); // Redirect to old viewer if a v2 report. v3, v4, v5 handled by v5 viewer. if (json.lighthouseVersion.startsWith('2')) { this._loadInLegacyViewerVersion(json); return; } const dom = new DOM(document); const renderer = new ReportRenderer(dom); const container = find('main', document); try { renderer.renderReport(json, container); // Only give gist-saving callback if current report isn't from a gist. let saveCallback = null; if (!this._reportIsFromGist) { saveCallback = this._onSaveJson; } // Only clear query string if current report isn't from a gist or PSI. if (!this._reportIsFromGist && !this._reportIsFromPSI && !this._reportIsFromJSON) { history.pushState({}, '', LighthouseReportViewer.APP_URL); } const features = new ViewerUIFeatures(dom, saveCallback); features.initFeatures(json); } catch (e) { logger.error(`Error rendering report: ${e.message}`); dom.resetTemplates(); // TODO(bckenny): hack container.textContent = ''; throw e; } finally { this._reportIsFromGist = this._reportIsFromPSI = this._reportIsFromJSON = false; } // Remove the placeholder UI once the user has loaded a report. const placeholder = document.querySelector('.viewer-placeholder'); if (placeholder) { placeholder.remove(); } if (window.ga) { window.ga('send', 'event', 'report', 'view'); } } /** * Updates the page's HTML with contents of the JSON file passed in. * @param {File} file * @return {Promise<void>} * @throws file was not valid JSON generated by Lighthouse or an unknown file * type was used. * @private */ _onFileLoad(file) { return this._readFile(file).then(str => { let json; try { json = JSON.parse(str); } catch (e) { throw new Error('Could not parse JSON file.'); } this._replaceReportHtml(json); }).catch(err => logger.error(err.message)); } /** * Stores v2.x report in IDB, then navigates to legacy viewer in current tab. * @param {LH.Result} reportJson * @private */ _loadInLegacyViewerVersion(reportJson) { const warnMsg = `Version mismatch between viewer and JSON. Opening compatible viewer...`; logger.log(warnMsg, false); // Place report in IDB, then navigate current tab to the legacy viewer const viewerPath = new URL('../viewer2x/', location.href); idbKeyval.set('2xreport', reportJson).then(_ => { window.location.href = viewerPath.href; }); } /** * Reads a file and returns its content as a string. * @param {File} file * @return {Promise<string>} * @private */ _readFile(file) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = function(e) { const readerTarget = /** @type {?FileReader} */ (e.target); const result = /** @type {?string} */ (readerTarget && readerTarget.result); if (!result) { reject('Could not read file'); return; } resolve(result); }; reader.onerror = reject; reader.readAsText(file); }); } /** * Saves the current report by creating a gist on GitHub. * @param {LH.Result} reportJson * @return {Promise<string|void>} id of the created gist. * @private */ _onSaveJson(reportJson) { if (window.ga) { window.ga('send', 'event', 'report', 'share'); } // TODO: find and reuse existing json gist if one exists. return this._github.createGist(reportJson).then(id => { if (window.ga) { window.ga('send', 'event', 'report', 'created'); } history.pushState({}, '', `${LighthouseReportViewer.APP_URL}?gist=${id}`); return id; }).catch(err => logger.log(err.message)); } /** * Enables pasting a JSON report or gist URL on the page. * @param {ClipboardEvent} e * @private */ _onPaste(e) { if (!e.clipboardData) return; e.preventDefault(); // Try paste as gist URL. try { const url = new URL(e.clipboardData.getData('text')); this._loadFromGistURL(url.href); if (window.ga) { window.ga('send', 'event', 'report', 'paste-link'); } } catch (err) { // noop } // Try paste as json content. try { const json = JSON.parse(e.clipboardData.getData('text')); this._replaceReportHtml(json); if (window.ga) { window.ga('send', 'event', 'report', 'paste'); } } catch (err) { } } /** * Handles changes to the gist url input. * @param {Event} e * @private */ _onUrlInputChange(e) { e.stopPropagation(); if (!e.target) { return; } const inputElement = /** @type {HTMLInputElement} */ (e.target); try { this._loadFromGistURL(inputElement.value); } catch (err) { logger.error('Invalid URL'); } } /** * Loads report json from gist URL, if valid. Updates page URL with gist ID * and loads from github. * @param {string} urlStr Gist URL. * @private */ _loadFromGistURL(urlStr) { try { const url = new URL(urlStr); if (url.origin !== 'https://gist.github.com') { logger.error('URL was not a gist'); return; } const match = url.pathname.match(/[a-f0-9]{5,}/); if (match) { history.pushState({}, '', `${LighthouseReportViewer.APP_URL}?gist=${match[0]}`); this._loadFromDeepLink(); } } catch (err) { logger.error('Invalid URL'); } } /** * Initializes of a `message` listener to respond to postMessage events. * @private */ _listenForMessages() { window.addEventListener('message', e => { if (e.source === self.opener && e.data.lhresults) { this._replaceReportHtml(e.data.lhresults); if (self.opener && !self.opener.closed) { self.opener.postMessage({rendered: true}, '*'); } if (window.ga) { window.ga('send', 'event', 'report', 'open in viewer'); } } }); // If the page was opened as a popup, tell the opening window we're ready. if (self.opener && !self.opener.closed) { self.opener.postMessage({opened: true}, '*'); } } /** * @param {PSIParams} params */ _fetchFromPSI(params) { logger.log('Waiting for Lighthouse results ...'); return this._psi.fetchPSI(params).then(response => { logger.hide(); if (!response.lighthouseResult) { if (response.error) { // eslint-disable-next-line no-console console.error(response.error); logger.error(response.error.message); } else { logger.error('PSI did not return a Lighthouse Result'); } return; } this._reportIsFromPSI = true; this._replaceReportHtml(response.lighthouseResult); }); } /** * @param {boolean} force */ _toggleLoadingBlur(force) { const placeholder = document.querySelector('.viewer-placeholder-inner'); if (placeholder) placeholder.classList.toggle('lh-loading', force); } } // node export for testing. if (typeof module !== 'undefined' && module.exports) { module.exports = LighthouseReportViewer; }
umaar/lighthouse
lighthouse-viewer/app/src/lighthouse-report-viewer.js
JavaScript
apache-2.0
13,779
/** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ /** * @fileoverview This file contains additional helper definitions on top of the * Google Closure Library's logging subsystem (see * <http://google.github.io/closure-library/api/namespace_goog_log.html>). * * Aside from providing several helper functions, this file, when executed, sets * up the logging subsystem parameters: * * * The logging level of the root logger is set up according to whether or not * the compilation is performed in a debug mode (see * <http://google.github.io/closure-library/api/namespace_goog.html#DEBUG>). * * Log messages that bubbled till the root logger are emitted to the * JavaScript Console. * * Log messages are set up to be kept (probably, truncated) in a background * page's log buffer, which allows to export them later. */ goog.provide('GoogleSmartCard.Logging'); goog.require('GoogleSmartCard.LogBuffer'); goog.require('GoogleSmartCard.Logging.CrashLoopDetection'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.debug'); goog.require('goog.debug.Console'); goog.require('goog.log'); goog.require('goog.log.Level'); goog.require('goog.log.Logger'); goog.require('goog.object'); goog.scope(function() { const GSC = GoogleSmartCard; /** * @define {boolean} Whether to make every logger created via this library a * child of the |LOGGER_SCOPE|. * Overriding it to false allows to reduce the boilerplate printed in every * logged message; the default true value, on the other hand, allows to avoid * clashes in case the extension creates and manages its own Closure Library * loggers. */ GSC.Logging.USE_SCOPED_LOGGERS = goog.define('GoogleSmartCard.Logging.USE_SCOPED_LOGGERS', true); /** * @define {boolean} Whether to trigger the extension reload in case a fatal * error occurs in Release mode. */ GSC.Logging.SELF_RELOAD_ON_FATAL_ERROR = goog.define('GoogleSmartCard.Logging.SELF_RELOAD_ON_FATAL_ERROR', false); /** * Every logger created via this library is created as a child of this logger, * as long as the |USE_SCOPED_LOGGERS| constant is true. Ignored when that * constant is false. */ const LOGGER_SCOPE = 'GoogleSmartCard'; /** * The logging level that will be applied to the root logger (and therefore * would be effective for all loggers unless the ones that have an explicitly * set level). */ const ROOT_LOGGER_LEVEL = goog.DEBUG ? goog.log.Level.FINE : goog.log.Level.INFO; /** * The capacity of the buffer that stores the emitted log messages. * * When the number of log messages exceeds this capacity, the messages from the * middle will be removed (so only some first and some last messages will be * kept at any given moment of time). */ const LOG_BUFFER_CAPACITY = goog.DEBUG ? 20 * 1000 : 2000; /** * This constant specifies the name of the special window attribute in which our * log buffer is stored. This is used so that popup windows and other pages can * access the background page's log buffer and therefore use a centralized place * for aggregating logs. */ const GLOBAL_LOG_BUFFER_VARIABLE_NAME = 'googleSmartCard_logBuffer'; /** * @type {!goog.log.Logger} */ const rootLogger = goog.asserts.assert(goog.log.getLogger(goog.log.ROOT_LOGGER_NAME)); /** * @type {!goog.log.Logger} */ const logger = GSC.Logging.USE_SCOPED_LOGGERS ? goog.asserts.assert(goog.log.getLogger(LOGGER_SCOPE)) : rootLogger; /** @type {boolean} */ let wasLoggingSetUp = false; /** * The log buffer that aggregates all log messages, to let them be exported if * the user requests so. This variable is initialized to a new `LogBuffer` * instance, but if we're running outside the background page this variable is * later reassigned to the background page's log buffer. * @type {!GSC.LogBuffer} */ let logBuffer = new GSC.LogBuffer(LOG_BUFFER_CAPACITY); /** * Sets up logging parameters and log buffering. * * This function is called automatically when this library file is included. */ GSC.Logging.setupLogging = function() { if (wasLoggingSetUp) return; wasLoggingSetUp = true; setupConsoleLogging(); setupRootLoggerLevel(); goog.log.fine( logger, 'Logging was set up with level=' + ROOT_LOGGER_LEVEL.name + ' and enabled logging to JS console'); setupLogBuffer(); }; /** * Returns a logger. * @param {string} name * @param {!goog.log.Level=} opt_level * @return {!goog.log.Logger} */ GSC.Logging.getLogger = function(name, opt_level) { const logger = goog.log.getLogger(name, opt_level); GSC.Logging.check(logger); goog.asserts.assert(logger); return logger; }; /** * Returns a library-scoped logger. * @param {string} name * @param {!goog.log.Level=} opt_level * @return {!goog.log.Logger} */ GSC.Logging.getScopedLogger = function(name, opt_level) { let fullName; if (GSC.Logging.USE_SCOPED_LOGGERS && name) fullName = `${LOGGER_SCOPE}.${name}`; else if (GSC.Logging.USE_SCOPED_LOGGERS) fullName = LOGGER_SCOPE; else fullName = name; return GSC.Logging.getLogger(fullName, opt_level); }; /** * Returns the logger with the specified name relative to the specified parent * logger. * @param {!goog.log.Logger} parentLogger * @param {string} relativeName * @param {!goog.log.Level=} opt_level * @return {!goog.log.Logger} */ GSC.Logging.getChildLogger = function(parentLogger, relativeName, opt_level) { return GSC.Logging.getLogger(parentLogger.getName() + '.' + relativeName); }; /** * Changes the logger level so that the logger is not more verbose than the * specified level. * @param {!goog.log.Logger} logger * @param {!goog.log.Level} boundaryLevel */ GSC.Logging.setLoggerVerbosityAtMost = function(logger, boundaryLevel) { const effectiveLevel = goog.log.getEffectiveLevel(logger); if (!effectiveLevel || effectiveLevel.value < boundaryLevel.value) goog.log.setLevel(logger, boundaryLevel); }; /** * Checks if the condition evaluates to true. * * In contrast to goog.asserts.assert method, this method works in non-Debug * builds too. * @template T * @param {T} condition The condition to check. * @param {string=} opt_message Error message in case of failure. */ GSC.Logging.check = function(condition, opt_message) { if (!condition) GSC.Logging.fail(opt_message); }; /** * The same as GSC.Logging.check, but the message is prefixed with the logger * title. * @template T * @param {!goog.log.Logger} logger The logger which name is to be prepended * to the error message. * @param {T} condition The condition to check. * @param {string=} opt_message Error message in case of failure. */ GSC.Logging.checkWithLogger = function(logger, condition, opt_message) { if (!condition) GSC.Logging.failWithLogger(logger, opt_message); }; /** * Throws an exception and emits severe log with the specified message. * * In the release mode, this additionally asynchronously initiates the App * reload, unless a crash-and-reload loop is detected. * @param {string=} opt_message Error message in case of failure. */ GSC.Logging.fail = function(opt_message) { const message = opt_message ? opt_message : 'Failure'; goog.log.error(rootLogger, message); scheduleAppReloadIfAllowed(); throw new Error(message); }; /** * Same as GSC.Logging.fail, but the message is prefixed with the logger title. * @param {!goog.log.Logger} logger The logger which name is to be prepended * to the error message. * @param {string=} opt_message Error message in case of failure. */ GSC.Logging.failWithLogger = function(logger, opt_message) { const messagePrefix = 'Failure in ' + logger.getName(); if (opt_message !== undefined) { const transformedMessage = messagePrefix + ': ' + opt_message; GSC.Logging.fail(transformedMessage); } else { GSC.Logging.fail(messagePrefix); } }; /** * Returns the log buffer instance. * * The log buffer instance was either created during this script execution, or * was reused from the background page's global attribute. * @return {!GSC.LogBuffer} */ GSC.Logging.getLogBuffer = function() { return logBuffer; }; function scheduleAppReloadIfAllowed() { if (goog.DEBUG || !GSC.Logging.SELF_RELOAD_ON_FATAL_ERROR) return; GSC.Logging.CrashLoopDetection.handleImminentCrash() .then(function(isInCrashLoop) { if (isInCrashLoop) { goog.log.info( rootLogger, 'Crash loop detected. The application is defunct, but the ' + 'execution state is kept in order to retain the failure logs.'); return; } goog.log.info( rootLogger, 'Reloading the application due to the fatal error...'); reloadApp(); }) .catch(function() { // Don't do anything for repeated crashes within a single run. }); } function reloadApp() { // This method works only in non-kiosk mode. Since this is a much more common // case and as this function doesn't generate errors in any case, this method // is called first. chrome.runtime.reload(); // This method works only in kiosk mode. chrome.runtime.restart(); } function setupConsoleLogging() { const console = new goog.debug.Console; const formatter = console.getFormatter(); formatter.showAbsoluteTime = true; formatter.showRelativeTime = false; console.setCapturing(true); } function setupRootLoggerLevel() { goog.log.setLevel(rootLogger, ROOT_LOGGER_LEVEL); } function setupLogBuffer() { GSC.LogBuffer.attachBufferToLogger( logBuffer, rootLogger, document.location.href); if (!chrome || !chrome.runtime || !chrome.runtime.getBackgroundPage) { // We don't know whether we're running inside the background page and // the API for talking to it is unavailable - therefore no action needed, // i.e., our page will continue using our log buffer. This should only // happen in tests or if this code is running outside an app/extension. return; } // Expose our log buffer in the global window properties. Pages other than the // background will use it to access the background page's log buffer - see the // code directly below. goog.global[GLOBAL_LOG_BUFFER_VARIABLE_NAME] = logBuffer; chrome.runtime.getBackgroundPage(function(backgroundPage) { GSC.Logging.check(backgroundPage); goog.asserts.assert(backgroundPage); if (backgroundPage === window) { // We're running inside the background page - no action needed. return; } // We've discovered we're running outside the background page - so need to // switch to using the background page's log buffer in order to keep all // logs aggregated and available in a single place. // First, obtain a reference to the background page's log buffer. const backgroundLogBuffer = /** @type {GSC.LogBuffer} */ ( backgroundPage[GLOBAL_LOG_BUFFER_VARIABLE_NAME]); GSC.Logging.check(backgroundLogBuffer); goog.asserts.assert(backgroundLogBuffer); // Copy the logs we've accumulated in the current page into the background // page's log buffer. logBuffer.copyToOtherBuffer(backgroundLogBuffer); // From now, start using the background page's buffer for collecting data // from our page's loggers. Dispose of our log buffer to avoid storing new // logs twice. GSC.LogBuffer.attachBufferToLogger( backgroundLogBuffer, rootLogger, document.location.href); logBuffer.dispose(); // Switch our reference to the background page's log buffer. logBuffer = backgroundLogBuffer; // The global reference is not needed if we're not the background page. delete goog.global[GLOBAL_LOG_BUFFER_VARIABLE_NAME]; }); } GSC.Logging.setupLogging(); }); // goog.scope
GoogleChromeLabs/chromeos_smart_card_connector
common/js/src/logging/logging.js
JavaScript
apache-2.0
12,352
/** * SyntaxHighlighter * http://alexgorbatchev.com/SyntaxHighlighter * * SyntaxHighlighter is donationware. If you are using it, please donate. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html * * @version * 3.0.90 (Sat, 18 Jun 2016 21:01:41 GMT) * * @copyright * Copyright (C) 2004-2013 Alex Gorbatchev. * * @license * Dual licensed under the MIT and GPL licenses. */ ;(function() { // CommonJS SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null); function Brush() { // Contributed by Gheorghe Milas and Ahmad Sherif var keywords = 'and assert break class continue def del elif else ' + 'except exec finally for from global if import in is ' + 'lambda not or pass raise return try yield while'; var funcs = '__import__ abs all any apply basestring bin bool buffer callable ' + 'chr classmethod cmp coerce compile complex delattr dict dir ' + 'divmod enumerate eval execfile file filter float format frozenset ' + 'getattr globals hasattr hash help hex id input int intern ' + 'isinstance issubclass iter len list locals long map max min next ' + 'object oct open ord pow print property range raw_input reduce ' + 'reload repr reversed round set setattr slice sorted staticmethod ' + 'str sum super tuple type type unichr unicode vars xrange zip'; var special = 'None True False self cls class_'; this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, { regex: /^\s*@\w+/gm, css: 'decorator' }, { regex: /(['\"]{3})([^\1])*?\1/gm, css: 'comments' }, { regex: /"(?!")(?:\.|\\\"|[^\""\n])*"/gm, css: 'string' }, { regex: /'(?!')(?:\.|(\\\')|[^\''\n])*'/gm, css: 'string' }, { regex: /\+|\-|\*|\/|\%|=|==/gm, css: 'keyword' }, { regex: /\b\d+\.?\w*/g, css: 'value' }, { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, { regex: new RegExp(this.getKeywords(special), 'gm'), css: 'color1' } ]; this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); }; Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['py', 'python']; SyntaxHighlighter.brushes.Python = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
guileschool/guileschool.github.io
assets/js/syntaxhighlighter3/shBrushPython.js
JavaScript
apache-2.0
2,469