repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
DeinDesign/css | node_modules/bower/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/lib/Array/prototype/_compare-by-length.js | <reponame>DeinDesign/css
// Used internally to sort array of lists by length
'use strict';
module.exports = function (a, b) {
return (a.length >>> 0) - (b.length >>> 0);
};
|
TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | platform/lib/all-deps/com/google/gwt/core/ext/linker/impl/installLocationIframe.js | <filename>platform/lib/all-deps/com/google/gwt/core/ext/linker/impl/installLocationIframe.js
// GWT code can be installed anywhere, but an iFrame is the best place if you
// want both variable isolation and runAsync support. Variable isolation is
// useful for avoiding conflicts with JavaScript libraries and critical if
// you want more than one GWT module on your page. The runAsync implementation
// will need to install additional chunks of code into the same iFrame later.
//
// By default, CrossSiteIFrameLinker will use this script to create the iFrame.
// It may be replaced by overriding CrossSiteIframeLinker.getJsInstallLocation()
// to return the name of a different resource file. The replacement script may
// optionally set this variable inside the iframe:
//
// $wnd - the location where the bootstrap module is defined. It should also
// be the location where the __gwtStatsEvent function is defined.
// If not set, the module will set $wnd to window.parent.
var frameDoc;
function getInstallLocationDoc() {
setupInstallLocation();
return frameDoc;
}
// This function is left for compatibility
// and may be used by custom linkers
function getInstallLocation() {
return getInstallLocationDoc().body;
}
function setupInstallLocation() {
if (frameDoc) { return; }
// Create the script frame, making sure it's invisible, but not
// "display:none", which keeps some browsers from running code in it.
var scriptFrame = $doc.createElement('iframe');
scriptFrame.id = '__MODULE_NAME__';
scriptFrame.style.cssText = 'position:absolute; width:0; height:0; border:none; left: -1000px;'
+ ' top: -1000px;';
scriptFrame.tabIndex = -1;
$doc.body.appendChild(scriptFrame);
frameDoc = scriptFrame.contentWindow.document;
// The following code is needed for proper operation in Firefox, Safari, and
// Internet Explorer.
//
// In Firefox, this prevents the frame from re-loading asynchronously and
// throwing away the current document.
//
// In IE, it ensures that the <body> element is immediately available.
frameDoc.open();
var doctype = (document.compatMode == 'CSS1Compat') ? '<!doctype html>' : '';
frameDoc.write(doctype + '<html><head></head><body></body></html>');
frameDoc.close();
}
|
frankquekch/main | src/test/java/seedu/budgeteer/storage/JsonSerializableEntriesBookTest.java | package seedu.budgeteer.storage;
import static org.junit.Assert.assertEquals;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.budgeteer.commons.exceptions.IllegalValueException;
import seedu.budgeteer.commons.util.JsonUtil;
import seedu.budgeteer.model.EntriesBook;
import seedu.budgeteer.testutil.TypicalEntrys;
public class JsonSerializableEntriesBookTest {
private static final Path TEST_DATA_FOLDER = Paths.get("src", "test", "data", "JsonSerializableEntriesBookTest");
private static final Path TYPICAL_ENTRYS_FILE = TEST_DATA_FOLDER.resolve("typicalEntrysAddressBook.json");
private static final Path INVALID_ENTRY_FILE = TEST_DATA_FOLDER.resolve("invalidEntryAddressBook.json");
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void toModelType_typicalPersonsFile_success() throws Exception {
JsonSerializableBudgeteer dataFromFile = JsonUtil.readJsonFile(TYPICAL_ENTRYS_FILE,
JsonSerializableBudgeteer.class).get();
EntriesBook entriesBookFromFile = dataFromFile.toModelType();
EntriesBook typicalPersonsEntriesBook = TypicalEntrys.getTypicalAddressBook();
assertEquals(entriesBookFromFile, typicalPersonsEntriesBook);
}
@Test
public void toModelType_invalidPersonFile_throwsIllegalValueException() throws Exception {
JsonSerializableBudgeteer dataFromFile = JsonUtil.readJsonFile(INVALID_ENTRY_FILE,
JsonSerializableBudgeteer.class).get();
thrown.expect(IllegalValueException.class);
dataFromFile.toModelType();
}
}
|
josemoreno90/kwestion-me | node_modules/firekit-provider/umd/firekit-provider.js | /*!
* firekit-provider v0.2.20 - https://www.react-most-wanted.com/
* MIT Licensed
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["firekit-provider"] = factory(require("react"));
else
root["firekit-provider"] = factory(root["React"]);
})(typeof self !== 'undefined' ? self : this, function(__WEBPACK_EXTERNAL_MODULE_13__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 34);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__store_auth_reducer__ = __webpack_require__(19);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__store_collections_reducer__ = __webpack_require__(21);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__store_connection_reducer__ = __webpack_require__(22);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__store_docs_reducer__ = __webpack_require__(24);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__store_errors_reducer__ = __webpack_require__(25);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__store_initialization_reducer__ = __webpack_require__(26);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__store_lists_reducer__ = __webpack_require__(28);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__store_loadings_reducer__ = __webpack_require__(29);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__store_messaging_reducer__ = __webpack_require__(31);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__store_paths_reducer__ = __webpack_require__(33);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__store_initialization_actions__ = __webpack_require__(40);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_10__store_initialization_actions__["a"]; });
/* unused harmony reexport authReducer */
/* unused harmony reexport collectionsReducer */
/* unused harmony reexport connectionReducer */
/* unused harmony reexport docsReducer */
/* unused harmony reexport errorsReducer */
/* unused harmony reexport initializationReducer */
/* unused harmony reexport listsReducer */
/* unused harmony reexport loadingsReducer */
/* unused harmony reexport messagingReducer */
/* unused harmony reexport pathsReducer */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__store_connection_actions__ = __webpack_require__(41);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return __WEBPACK_IMPORTED_MODULE_11__store_connection_actions__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return __WEBPACK_IMPORTED_MODULE_11__store_connection_actions__["b"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__store_messaging_actions__ = __webpack_require__(42);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return __WEBPACK_IMPORTED_MODULE_12__store_messaging_actions__["b"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return __WEBPACK_IMPORTED_MODULE_12__store_messaging_actions__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__store_errors_actions__ = __webpack_require__(1);
/* unused harmony reexport logError */
/* unused harmony reexport clearError */
/* unused harmony reexport clearAllErrors */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__store_loadings_actions__ = __webpack_require__(6);
/* unused harmony reexport logLoading */
/* unused harmony reexport clearLoading */
/* unused harmony reexport clearAllLoadings */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__store_auth_actions__ = __webpack_require__(43);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return __WEBPACK_IMPORTED_MODULE_15__store_auth_actions__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_15__store_auth_actions__["b"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_15__store_auth_actions__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__store_collections_actions__ = __webpack_require__(44);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return __WEBPACK_IMPORTED_MODULE_16__store_collections_actions__["d"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return __WEBPACK_IMPORTED_MODULE_16__store_collections_actions__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return __WEBPACK_IMPORTED_MODULE_16__store_collections_actions__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return __WEBPACK_IMPORTED_MODULE_16__store_collections_actions__["b"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__store_docs_actions__ = __webpack_require__(45);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return __WEBPACK_IMPORTED_MODULE_17__store_docs_actions__["d"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return __WEBPACK_IMPORTED_MODULE_17__store_docs_actions__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return __WEBPACK_IMPORTED_MODULE_17__store_docs_actions__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return __WEBPACK_IMPORTED_MODULE_17__store_docs_actions__["b"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__store_lists_actions__ = __webpack_require__(46);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return __WEBPACK_IMPORTED_MODULE_18__store_lists_actions__["d"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return __WEBPACK_IMPORTED_MODULE_18__store_lists_actions__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return __WEBPACK_IMPORTED_MODULE_18__store_lists_actions__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return __WEBPACK_IMPORTED_MODULE_18__store_lists_actions__["b"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__store_paths_actions__ = __webpack_require__(47);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return __WEBPACK_IMPORTED_MODULE_19__store_paths_actions__["d"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return __WEBPACK_IMPORTED_MODULE_19__store_paths_actions__["c"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return __WEBPACK_IMPORTED_MODULE_19__store_paths_actions__["a"]; });
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return __WEBPACK_IMPORTED_MODULE_19__store_paths_actions__["b"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__store_lists_selectors__ = __webpack_require__(11);
/* unused harmony reexport listsSelectors */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__store_collections_selectors__ = __webpack_require__(9);
/* unused harmony reexport collectionsSelectors */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_22__store_paths_selectors__ = __webpack_require__(12);
/* unused harmony reexport pathsSelectors */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_23__store_docs_selectors__ = __webpack_require__(10);
/* unused harmony reexport docsSelectors */
/* unused harmony reexport getList */
/* unused harmony reexport getAllLists */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_24__store_loadings_selectors__ = __webpack_require__(48);
/* unused harmony reexport isLoading */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_25__store_errors_selectors__ = __webpack_require__(49);
/* unused harmony reexport hasError */
/* unused harmony reexport getCol */
/* unused harmony reexport getAllCols */
/* unused harmony reexport getAllInitializations */
/* unused harmony reexport getPath */
/* unused harmony reexport getAllPaths */
/* unused harmony reexport getDoc */
/* unused harmony reexport getAllDocs */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_26__store_initialization_selectors__ = __webpack_require__(7);
/* unused harmony reexport isInitialised */
var firekitReducers = {
auth: __WEBPACK_IMPORTED_MODULE_0__store_auth_reducer__["a" /* default */],
collections: __WEBPACK_IMPORTED_MODULE_1__store_collections_reducer__["a" /* default */],
connection: __WEBPACK_IMPORTED_MODULE_2__store_connection_reducer__["a" /* default */],
docs: __WEBPACK_IMPORTED_MODULE_3__store_docs_reducer__["a" /* default */],
errors: __WEBPACK_IMPORTED_MODULE_4__store_errors_reducer__["a" /* default */],
initialization: __WEBPACK_IMPORTED_MODULE_5__store_initialization_reducer__["a" /* default */],
lists: __WEBPACK_IMPORTED_MODULE_6__store_lists_reducer__["a" /* default */],
loadings: __WEBPACK_IMPORTED_MODULE_7__store_loadings_reducer__["a" /* default */],
messaging: __WEBPACK_IMPORTED_MODULE_8__store_messaging_reducer__["a" /* default */],
paths: __WEBPACK_IMPORTED_MODULE_9__store_paths_reducer__["a" /* default */]
};
/* unused harmony default export */ var _unused_webpack_default_export = (firekitReducers);
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = logError;
/* unused harmony export clearError */
/* unused harmony export clearAllErrors */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(8);
function logError(location, err) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* LOG_ERROR */],
location: location,
err: err
};
}
function clearError(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CLEAR_ERROR */],
location: location
};
}
function clearAllErrors() {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CLEAR_ALL_ERRORS */]
};
}
/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export APPEND_INIIALIZE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return INIIALIZE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return DESTROY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return UNWATCH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CHILD_ADDED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CHILD_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CHILD_REMOVED; });
var APPEND_INIIALIZE = "@@firekit/COLLECTIONS@APPEND_INIIALIZE";
var INIIALIZE = "@@firekit/COLLECTIONS@INIIALIZE";
var DESTROY = "@@firekit/COLLECTIONS@DESTROY";
var UNWATCH = "@@firekit/COLLECTIONS@UNWATCH";
var CHILD_ADDED = "@@firekit/COLLECTIONS@CHILD_ADDED";
var CHILD_CHANGED = "@@firekit/COLLECTIONS@CHILD_CHANGED";
var CHILD_REMOVED = "@@firekit/COLLECTIONS@CHILD_REMOVED";
/***/ }),
/* 3 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export INIIALIZE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DESTROY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UNWATCH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return VALUE_CHANGED; });
var INIIALIZE = "@@firekit/DOCS@INIIALIZE";
var DESTROY = "@@firekit/DOCS@DESTROY";
var UNWATCH = "@@firekit/DOCS@UNWATCH";
var VALUE_CHANGED = "@@firekit/DOCS@VALUE_CHANGED";
/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export APPEND_INIIALIZE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return INIIALIZE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return DESTROY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return UNWATCH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CHILD_ADDED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CHILD_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CHILD_REMOVED; });
var APPEND_INIIALIZE = "@@firekit/LISTS@APPEND_INIIALIZE";
var INIIALIZE = "@@firekit/LISTS@INIIALIZE";
var DESTROY = "@@firekit/LISTS@DESTROY";
var UNWATCH = "@@firekit/LISTS@UNWATCH";
var CHILD_ADDED = "@@firekit/LISTS@CHILD_ADDED";
var CHILD_CHANGED = "@@firekit/LISTS@CHILD_CHANGED";
var CHILD_REMOVED = "@@firekit/LISTS@CHILD_REMOVED";
/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export INIIALIZE */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DESTROY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UNWATCH; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return VALUE_CHANGED; });
var INIIALIZE = "@@firekit/PATHS@INIIALIZE";
var DESTROY = "@@firekit/PATHS@DESTROY";
var UNWATCH = "@@firekit/PATHS@UNWATCH";
var VALUE_CHANGED = "@@firekit/PATHS@VALUE_CHANGED";
/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = logLoading;
/* unused harmony export clearLoading */
/* unused harmony export clearAllLoadings */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(30);
function logLoading(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* LOG_LOADING */],
location: location
};
}
function clearLoading(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CLEAR_LOADING */],
location: location
};
}
function clearAllLoadings() {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CLEAR_ALL_LOADINGS */]
};
}
/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = isInitialised;
function isInitialised(state, path, location) {
if (state.initialization !== undefined && state.initialization[path]) {
return state.initialization[path][location];
}
return false;
}
/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return LOG_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CLEAR_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CLEAR_ALL_ERRORS; });
var LOG_ERROR = "@@firekit/ERRORS@LOG_ERROR";
var CLEAR_ERROR = "@@firekit/ERRORS@CLEAR_ERROR";
var CLEAR_ALL_ERRORS = "@@firekit/ERRORS@CLEAR_ALL_ERRORS";
/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getAllCols;
/* harmony export (immutable) */ __webpack_exports__["b"] = getAllInitializations;
/* unused harmony export getCol */
function getAllCols(state) {
return state.collections;
}
function getAllInitializations(state) {
return state.initialization;
}
function getCol(state, location) {
if (state.collections !== undefined && state.collections[location]) {
return state.collections[location];
}
return [];
}
/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getAllDocs;
/* harmony export (immutable) */ __webpack_exports__["b"] = getAllInitializations;
/* unused harmony export getDoc */
function getAllDocs(state) {
return state.docs;
}
function getAllInitializations(state) {
return state.initialization;
}
function getDoc(state, location) {
if (state.docs !== undefined && state.docs[location]) {
return state.docs[location];
}
return null;
}
/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getAllLists;
/* unused harmony export getList */
function getAllLists(state) {
return state.lists;
}
function getList(state, location) {
if (state.lists !== undefined && state.lists[location]) {
return state.lists[location];
}
return [];
}
/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = getAllPaths;
/* unused harmony export getPath */
function getAllPaths(state) {
return state.paths;
}
function getPath(state, location) {
if (state.paths !== undefined && state.paths[location]) {
return state.paths[location];
}
return {};
}
/***/ }),
/* 13 */
/***/ (function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_13__;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (true) {
var REACT_ELEMENT_TYPE = (typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.element')) ||
0xeac7;
var isValidElement = function(object) {
return typeof object === 'object' &&
object !== null &&
object.$$typeof === REACT_ELEMENT_TYPE;
};
// By explicitly using `prop-types` you are opting into new development behavior.
// http://fb.me/prop-types-in-prod
var throwOnDirectAccess = true;
module.exports = __webpack_require__(37)(isValidElement, throwOnDirectAccess);
} else {
// By explicitly using `prop-types` you are opting into new production behavior.
// http://fb.me/prop-types-in-prod
module.exports = require('./factoryWithThrowingShims')();
}
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
function makeEmptyFunction(arg) {
return function () {
return arg;
};
}
/**
* This function accepts and discards inputs; it has no side effects. This is
* primarily useful idiomatically for overridable function endpoints which
* always need to be callable, since JS lacks a null-call idiom ala Cocoa.
*/
var emptyFunction = function emptyFunction() {};
emptyFunction.thatReturns = makeEmptyFunction;
emptyFunction.thatReturnsFalse = makeEmptyFunction(false);
emptyFunction.thatReturnsTrue = makeEmptyFunction(true);
emptyFunction.thatReturnsNull = makeEmptyFunction(null);
emptyFunction.thatReturnsThis = function () {
return this;
};
emptyFunction.thatReturnsArgument = function (arg) {
return arg;
};
module.exports = emptyFunction;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var validateFormat = function validateFormat(format) {};
if (true) {
validateFormat = function validateFormat(format) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
};
}
function invariant(condition, format, a, b, c, d, e, f) {
validateFormat(format);
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2014-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
var emptyFunction = __webpack_require__(15);
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = emptyFunction;
if (true) {
var printWarning = function printWarning(format) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var argIndex = 0;
var message = 'Warning: ' + format.replace(/%s/g, function () {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch (x) {}
};
warning = function warning(condition, format) {
if (format === undefined) {
throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument');
}
if (format.indexOf('Failed Composite propType: ') === 0) {
return; // Ignore CompositeComponent proptype check.
}
if (!condition) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
printWarning.apply(undefined, [format].concat(args));
}
};
}
module.exports = warning;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED';
module.exports = ReactPropTypesSecret;
/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export initialState */
/* harmony export (immutable) */ __webpack_exports__["a"] = auth;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(20);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var initialState = {};
function auth() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var _ref = arguments[1];
var payload = _ref.payload,
type = _ref.type;
switch (type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* AUTH_STATE_CHANGED */]:
return _extends({}, state, payload);
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* AUTH_ERROR */]:
return _extends({}, state, { error: payload });
default:
return state;
}
}
/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AUTH_STATE_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AUTH_ERROR; });
var AUTH_STATE_CHANGED = "@@firekit/AUTH@AUTH_STATE_CHANGED";
var AUTH_ERROR = "@@firekit/AUTH@AUTH_ERROR";
/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = collections;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(2);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function collection() {
var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var action = arguments[1];
var payload = action.payload,
append = action.append;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */]:
return append ? [].concat(list, payload) : payload;
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */]:
return [].concat(list, [payload]);
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */]:
return list.map(function (child) {
return payload.id === child.id ? payload : child;
});
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */]:
return list.filter(function (child) {
return payload.id !== child.id;
});
}
}
function collections() {
var _extends2, _extends3;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = collection(state[action.location], action), _extends2));
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */]:
return _extends({}, state, (_extends3 = {}, _extends3[location] = collection(state[action.location], action), _extends3));
case __WEBPACK_IMPORTED_MODULE_0__types__["d" /* DESTROY */]:
var omitData = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export initialState */
/* harmony export (immutable) */ __webpack_exports__["a"] = connection;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(23);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var initialState = {
isConnected: true
};
function connection() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var _ref = arguments[1];
var payload = _ref.payload,
type = _ref.type;
switch (type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* ON_CONNECTION_STATE_CHANGED */]:
return _extends({}, state, payload);
default:
return state;
}
}
/***/ }),
/* 23 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ON_CONNECTION_STATE_CHANGED; });
var ON_CONNECTION_STATE_CHANGED = "@@firekit/CONNECTION@ON_CONNECTION_STATE_CHANGED";
/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = docs;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(3);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function docs() {
var _extends2;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* VALUE_CHANGED */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = action.payload, _extends2));
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* DESTROY */]:
var omitData = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = errors;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__collections_types__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__docs_types__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__lists_types__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__paths_types__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__types__ = __webpack_require__(8);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function errors() {
var _extends2;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location,
err = action.err;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_4__types__["c" /* LOG_ERROR */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = err, _extends2));
case __WEBPACK_IMPORTED_MODULE_4__types__["a" /* CLEAR_ALL_ERRORS */]:
return {};
case __WEBPACK_IMPORTED_MODULE_4__types__["b" /* CLEAR_ERROR */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["b" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["b" /* UNWATCH */]:
var omit = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = initialization;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__collections_types__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__docs_types__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__lists_types__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__paths_types__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__types__ = __webpack_require__(27);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function locations() {
var _extends2;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var action = arguments[1];
var location = action.location,
locationValue = action.locationValue;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["c" /* VALUE_CHANGED */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = locationValue, _extends2));
}
}
function initialization() {
var _extends3;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var path = action.path;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["c" /* VALUE_CHANGED */]:
return _extends({}, state, (_extends3 = {}, _extends3[path] = locations(state[path], action), _extends3));
case __WEBPACK_IMPORTED_MODULE_4__types__["a" /* CLEAR_INITIALIZATION */]:
return {};
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["b" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["b" /* UNWATCH */]:
var omit = state[path],
rest = _objectWithoutProperties(state, [path]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CLEAR_INITIALIZATION; });
var CLEAR_INITIALIZATION = "@@firekit/INITIALIZATION@CLEAR_INITIALIZATION";
/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = lists;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(4);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function list() {
var list = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var action = arguments[1];
var payload = action.payload,
append = action.append;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */]:
return append ? [].concat(list, payload) : payload;
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */]:
return [].concat(list, [payload]);
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */]:
return list.map(function (child) {
return payload.key === child.key ? payload : child;
});
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */]:
return list.filter(function (child) {
return payload.key !== child.key;
});
}
}
function lists() {
var _extends2, _extends3;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = list(state[action.location], action), _extends2));
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */]:
return _extends({}, state, (_extends3 = {}, _extends3[location] = list(state[action.location], action), _extends3));
case __WEBPACK_IMPORTED_MODULE_0__types__["d" /* DESTROY */]:
var omitData = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = loadings;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__collections_types__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__docs_types__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__lists_types__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__paths_types__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__errors_types__ = __webpack_require__(8);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__types__ = __webpack_require__(30);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function loadings() {
var _extends2;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_5__types__["c" /* LOG_LOADING */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = true, _extends2));
case __WEBPACK_IMPORTED_MODULE_5__types__["a" /* CLEAR_ALL_LOADINGS */]:
return {};
case __WEBPACK_IMPORTED_MODULE_5__types__["b" /* CLEAR_LOADING */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["e" /* INIIALIZE */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["c" /* VALUE_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_2__lists_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["d" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_0__collections_types__["f" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_3__paths_types__["b" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["a" /* DESTROY */]:
case __WEBPACK_IMPORTED_MODULE_1__docs_types__["b" /* UNWATCH */]:
case __WEBPACK_IMPORTED_MODULE_4__errors_types__["c" /* LOG_ERROR */]:
var omit = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return LOG_LOADING; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CLEAR_LOADING; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CLEAR_ALL_LOADINGS; });
var LOG_LOADING = "@@firekit/LOADING@LOG_LOADING";
var CLEAR_LOADING = "@@firekit/LOADING@CLEAR_LOADING";
var CLEAR_ALL_LOADINGS = "@@firekit/LOADING@CLEAR_ALL_LOADINGS";
/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export initialState */
/* harmony export (immutable) */ __webpack_exports__["a"] = messaging;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(32);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
var initialState = {
hasPermission: false,
token: undefined
};
function messaging() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var _ref = arguments[1];
var payload = _ref.payload,
type = _ref.type;
switch (type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["d" /* PERMISSION_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["e" /* TOKEN_CHANGED */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* MESSAGING_ERROR */]:
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* ON_MESSAGE */]:
return _extends({}, state, payload);
case __WEBPACK_IMPORTED_MODULE_0__types__["b" /* ON_CLEAR_MESSAGE */]:
var message = state.message,
rest = _objectWithoutProperties(state, ['message']);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 32 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return TOKEN_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return PERMISSION_CHANGED; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MESSAGING_ERROR; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ON_MESSAGE; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ON_CLEAR_MESSAGE; });
var TOKEN_CHANGED = "@@firekit/MESSAGING@TOKEN_CHANGED";
var PERMISSION_CHANGED = "@@firekit/MESSAGING@PERMISSION_CHANGED";
var MESSAGING_ERROR = "@@firekit/MESSAGING@MESSAGING_ERROR";
var ON_MESSAGE = "@@firekit/MESSAGING@ON_MESSAGE";
var ON_CLEAR_MESSAGE = "@@firekit/MESSAGING@ON_CLEAR_MESSAGE";
/***/ }),
/* 33 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = paths;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(5);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function paths() {
var _extends2;
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var action = arguments[1];
var location = action.location;
switch (action.type) {
case __WEBPACK_IMPORTED_MODULE_0__types__["c" /* VALUE_CHANGED */]:
return _extends({}, state, (_extends2 = {}, _extends2[location] = action.payload, _extends2));
case __WEBPACK_IMPORTED_MODULE_0__types__["a" /* DESTROY */]:
var omitData = state[location],
rest = _objectWithoutProperties(state, [location]);
return _extends({}, rest);
default:
return state;
}
}
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(35);
/***/ }),
/* 35 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__withFirebase__ = __webpack_require__(36);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "withFirebase", function() { return __WEBPACK_IMPORTED_MODULE_0__withFirebase__["a"]; });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__components_FirebaseProvider__ = __webpack_require__(50);
/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return __WEBPACK_IMPORTED_MODULE_1__components_FirebaseProvider__["a"]; });
/***/ }),
/* 36 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_prop_types__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_prop_types__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_firekit__ = __webpack_require__(0);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var withFirebase = function withFirebase(Component) {
var ChildComponent = function ChildComponent(props, context) {
var firebaseApp = context.firebaseApp,
store = context.store;
var dispatch = store.dispatch;
return __WEBPACK_IMPORTED_MODULE_0_react___default.a.createElement(Component, _extends({
dispatch: dispatch,
firebaseApp: firebaseApp,
watchAuth: function watchAuth(onAuthStateChanged, onAuthError) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["t" /* watchAuth */])(firebaseApp, onAuthStateChanged, onAuthError));
},
clearInitialization: function clearInitialization() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["c" /* clearInitialization */])());
},
authStateChanged: function authStateChanged(user) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["b" /* authStateChanged */])(user));
},
authError: function authError(error) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["a" /* authError */])(error));
},
watchConnection: function watchConnection(onChange) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["i" /* initConnection */])(firebaseApp, onChange));
},
unwatchConnection: function unwatchConnection() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["k" /* unsubscribeConnection */])(firebaseApp));
},
watchList: function watchList(path, alias, append) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["w" /* watchList */])(firebaseApp, path, alias, append));
},
unwatchList: function unwatchList(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["r" /* unwatchList */])(firebaseApp, path, alias));
},
destroyList: function destroyList(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["g" /* destroyList */])(firebaseApp, path, alias));
},
unwatchAllLists: function unwatchAllLists() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["n" /* unwatchAllLists */])(firebaseApp));
},
watchCol: function watchCol(path, alias, append) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["u" /* watchCol */])(firebaseApp, path, alias, append));
},
unwatchCol: function unwatchCol(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["p" /* unwatchCol */])(firebaseApp, path, alias));
},
destroyCol: function destroyCol(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["e" /* destroyCol */])(firebaseApp, path, alias));
},
unwatchAllCols: function unwatchAllCols() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["l" /* unwatchAllCols */])(firebaseApp));
},
watchPath: function watchPath(path, alias, logLoading) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["x" /* watchPath */])(firebaseApp, path, alias, logLoading));
},
unwatchPath: function unwatchPath(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["s" /* unwatchPath */])(firebaseApp, path, alias));
},
destroyPath: function destroyPath(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["h" /* destroyPath */])(firebaseApp, path, alias));
},
unwatchAllPaths: function unwatchAllPaths() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["o" /* unwatchAllPaths */])(firebaseApp));
},
watchDoc: function watchDoc(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["v" /* watchDoc */])(firebaseApp, path, alias));
},
unwatchDoc: function unwatchDoc(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["q" /* unwatchDoc */])(firebaseApp, path, alias));
},
destroyDoc: function destroyDoc(path, alias) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["f" /* destroyDoc */])(firebaseApp, path, alias));
},
unwatchAllDocs: function unwatchAllDocs() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["m" /* unwatchAllDocs */])(firebaseApp));
},
clearApp: function clearApp() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["n" /* unwatchAllLists */])(firebaseApp));
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["o" /* unwatchAllPaths */])(firebaseApp));
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["m" /* unwatchAllDocs */])(firebaseApp));
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["l" /* unwatchAllCols */])(firebaseApp));
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["k" /* unsubscribeConnection */])(firebaseApp));
},
initMessaging: function initMessaging(handleTokenChange, onMessageReceieved) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["j" /* initMessaging */])(firebaseApp, handleTokenChange, onMessageReceieved));
},
clearMessage: function clearMessage() {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_2_firekit__["d" /* clearMessage */])());
}
}, props));
};
ChildComponent.contextTypes = {
firebaseApp: __WEBPACK_IMPORTED_MODULE_1_prop_types___default.a.object.isRequired,
store: __WEBPACK_IMPORTED_MODULE_1_prop_types___default.a.object.isRequired
};
return ChildComponent;
};
/* harmony default export */ __webpack_exports__["a"] = (withFirebase);
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var emptyFunction = __webpack_require__(15);
var invariant = __webpack_require__(16);
var warning = __webpack_require__(17);
var assign = __webpack_require__(38);
var ReactPropTypesSecret = __webpack_require__(18);
var checkPropTypes = __webpack_require__(39);
module.exports = function(isValidElement, throwOnDirectAccess) {
/* global Symbol */
var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec.
/**
* Returns the iterator method function contained on the iterable object.
*
* Be sure to invoke the function with the iterable as context:
*
* var iteratorFn = getIteratorFn(myIterable);
* if (iteratorFn) {
* var iterator = iteratorFn.call(myIterable);
* ...
* }
*
* @param {?object} maybeIterable
* @return {?function}
*/
function getIteratorFn(maybeIterable) {
var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]);
if (typeof iteratorFn === 'function') {
return iteratorFn;
}
}
/**
* Collection of methods that allow declaration and validation of props that are
* supplied to React components. Example usage:
*
* var Props = require('ReactPropTypes');
* var MyArticle = React.createClass({
* propTypes: {
* // An optional string prop named "description".
* description: Props.string,
*
* // A required enum prop named "category".
* category: Props.oneOf(['News','Photos']).isRequired,
*
* // A prop named "dialog" that requires an instance of Dialog.
* dialog: Props.instanceOf(Dialog).isRequired
* },
* render: function() { ... }
* });
*
* A more formal specification of how these methods are used:
*
* type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...)
* decl := ReactPropTypes.{type}(.isRequired)?
*
* Each and every declaration produces a function with the same signature. This
* allows the creation of custom validation functions. For example:
*
* var MyLink = React.createClass({
* propTypes: {
* // An optional string or URI prop named "href".
* href: function(props, propName, componentName) {
* var propValue = props[propName];
* if (propValue != null && typeof propValue !== 'string' &&
* !(propValue instanceof URI)) {
* return new Error(
* 'Expected a string or an URI for ' + propName + ' in ' +
* componentName
* );
* }
* }
* },
* render: function() {...}
* });
*
* @internal
*/
var ANONYMOUS = '<<anonymous>>';
// Important!
// Keep this list in sync with production version in `./factoryWithThrowingShims.js`.
var ReactPropTypes = {
array: createPrimitiveTypeChecker('array'),
bool: createPrimitiveTypeChecker('boolean'),
func: createPrimitiveTypeChecker('function'),
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
element: createElementTypeChecker(),
instanceOf: createInstanceTypeChecker,
node: createNodeChecker(),
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
exact: createStrictShapeTypeChecker,
};
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
/*eslint-disable no-self-compare*/
function is(x, y) {
// SameValue algorithm
if (x === y) {
// Steps 1-5, 7-10
// Steps 6.b-6.e: +0 != -0
return x !== 0 || 1 / x === 1 / y;
} else {
// Step 6.a: NaN == NaN
return x !== x && y !== y;
}
}
/*eslint-enable no-self-compare*/
/**
* We use an Error-like object for backward compatibility as people may call
* PropTypes directly and inspect their output. However, we don't use real
* Errors anymore. We don't inspect their stack anyway, and creating them
* is prohibitively expensive if they are created too often, such as what
* happens in oneOfType() for any type before the one that matched.
*/
function PropTypeError(message) {
this.message = message;
this.stack = '';
}
// Make `instanceof Error` still work for returned errors.
PropTypeError.prototype = Error.prototype;
function createChainableTypeChecker(validate) {
if (true) {
var manualPropTypeCallCache = {};
var manualPropTypeWarningCount = 0;
}
function checkType(isRequired, props, propName, componentName, location, propFullName, secret) {
componentName = componentName || ANONYMOUS;
propFullName = propFullName || propName;
if (secret !== ReactPropTypesSecret) {
if (throwOnDirectAccess) {
// New behavior only for users of `prop-types` package
invariant(
false,
'Calling PropTypes validators directly is not supported by the `prop-types` package. ' +
'Use `PropTypes.checkPropTypes()` to call them. ' +
'Read more at http://fb.me/use-check-prop-types'
);
} else if ("development" !== 'production' && typeof console !== 'undefined') {
// Old behavior for people using React.PropTypes
var cacheKey = componentName + ':' + propName;
if (
!manualPropTypeCallCache[cacheKey] &&
// Avoid spamming the console because they are often not actionable except for lib authors
manualPropTypeWarningCount < 3
) {
warning(
false,
'You are manually calling a React.PropTypes validation ' +
'function for the `%s` prop on `%s`. This is deprecated ' +
'and will throw in the standalone `prop-types` package. ' +
'You may be seeing this warning due to a third-party PropTypes ' +
'library. See https://fb.me/react-warning-dont-call-proptypes ' + 'for details.',
propFullName,
componentName
);
manualPropTypeCallCache[cacheKey] = true;
manualPropTypeWarningCount++;
}
}
}
if (props[propName] == null) {
if (isRequired) {
if (props[propName] === null) {
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required ' + ('in `' + componentName + '`, but its value is `null`.'));
}
return new PropTypeError('The ' + location + ' `' + propFullName + '` is marked as required in ' + ('`' + componentName + '`, but its value is `undefined`.'));
}
return null;
} else {
return validate(props, propName, componentName, location, propFullName);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location, propFullName, secret) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== expectedType) {
// `propValue` being instance of, say, date/regexp, pass the 'object'
// check, but we can offer a more precise error message here rather than
// 'of type `object`'.
var preciseType = getPreciseType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturnsNull);
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.');
}
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.'));
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']', ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
if (!isValidElement(propValue)) {
var propType = getPropType(propValue);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected a single ReactElement.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location, propFullName) {
if (!(props[propName] instanceof expectedClass)) {
var expectedClassName = expectedClass.name || ANONYMOUS;
var actualClassName = getClassName(props[propName]);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
if (!Array.isArray(expectedValues)) {
true ? warning(false, 'Invalid argument supplied to oneOf, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (is(propValue, expectedValues[i])) {
return null;
}
}
var valuesString = JSON.stringify(expectedValues);
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.'));
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location, propFullName) {
if (typeof typeChecker !== 'function') {
return new PropTypeError('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.');
}
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.'));
}
for (var key in propValue) {
if (propValue.hasOwnProperty(key)) {
var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error instanceof Error) {
return error;
}
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
if (!Array.isArray(arrayOfTypeCheckers)) {
true ? warning(false, 'Invalid argument supplied to oneOfType, expected an instance of array.') : void 0;
return emptyFunction.thatReturnsNull;
}
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (typeof checker !== 'function') {
warning(
false,
'Invalid argument supplied to oneOfType. Expected an array of check functions, but ' +
'received %s at index %s.',
getPostfixForTypeWarning(checker),
i
);
return emptyFunction.thatReturnsNull;
}
}
function validate(props, propName, componentName, location, propFullName) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location, propFullName, ReactPropTypesSecret) == null) {
return null;
}
}
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.'));
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location, propFullName) {
if (!isNode(props[propName])) {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.'));
}
return null;
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
for (var key in shapeTypes) {
var checker = shapeTypes[key];
if (!checker) {
continue;
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function createStrictShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location, propFullName) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
return new PropTypeError('Invalid ' + location + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.'));
}
// We need to check all keys in case some are required but missing from
// props.
var allKeys = assign({}, props[propName], shapeTypes);
for (var key in allKeys) {
var checker = shapeTypes[key];
if (!checker) {
return new PropTypeError(
'Invalid ' + location + ' `' + propFullName + '` key `' + key + '` supplied to `' + componentName + '`.' +
'\nBad object: ' + JSON.stringify(props[propName], null, ' ') +
'\nValid keys: ' + JSON.stringify(Object.keys(shapeTypes), null, ' ')
);
}
var error = checker(propValue, key, componentName, location, propFullName + '.' + key, ReactPropTypesSecret);
if (error) {
return error;
}
}
return null;
}
return createChainableTypeChecker(validate);
}
function isNode(propValue) {
switch (typeof propValue) {
case 'number':
case 'string':
case 'undefined':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (propValue === null || isValidElement(propValue)) {
return true;
}
var iteratorFn = getIteratorFn(propValue);
if (iteratorFn) {
var iterator = iteratorFn.call(propValue);
var step;
if (iteratorFn !== propValue.entries) {
while (!(step = iterator.next()).done) {
if (!isNode(step.value)) {
return false;
}
}
} else {
// Iterator will provide entry [k,v] tuples rather than values.
while (!(step = iterator.next()).done) {
var entry = step.value;
if (entry) {
if (!isNode(entry[1])) {
return false;
}
}
}
}
} else {
return false;
}
return true;
default:
return false;
}
}
function isSymbol(propType, propValue) {
// Native Symbol.
if (propType === 'symbol') {
return true;
}
// 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
if (propValue['@@toStringTag'] === 'Symbol') {
return true;
}
// Fallback for non-spec compliant Symbols which are polyfilled.
if (typeof Symbol === 'function' && propValue instanceof Symbol) {
return true;
}
return false;
}
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
if (Array.isArray(propValue)) {
return 'array';
}
if (propValue instanceof RegExp) {
// Old webkits (at least until Android 4.0) return 'function' rather than
// 'object' for typeof a RegExp. We'll normalize this here so that /bla/
// passes PropTypes.object.
return 'object';
}
if (isSymbol(propType, propValue)) {
return 'symbol';
}
return propType;
}
// This handles more types than `getPropType`. Only used for error messages.
// See `createPrimitiveTypeChecker`.
function getPreciseType(propValue) {
if (typeof propValue === 'undefined' || propValue === null) {
return '' + propValue;
}
var propType = getPropType(propValue);
if (propType === 'object') {
if (propValue instanceof Date) {
return 'date';
} else if (propValue instanceof RegExp) {
return 'regexp';
}
}
return propType;
}
// Returns a string that is postfixed to a warning about an invalid type.
// For example, "undefined" or "of type array"
function getPostfixForTypeWarning(value) {
var type = getPreciseType(value);
switch (type) {
case 'array':
case 'object':
return 'an ' + type;
case 'boolean':
case 'date':
case 'regexp':
return 'a ' + type;
default:
return type;
}
}
// Returns class name of the object, if any.
function getClassName(propValue) {
if (!propValue.constructor || !propValue.constructor.name) {
return ANONYMOUS;
}
return propValue.constructor.name;
}
ReactPropTypes.checkPropTypes = checkPropTypes;
ReactPropTypes.PropTypes = ReactPropTypes;
return ReactPropTypes;
};
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
object-assign
(c) <NAME>
@license MIT
*/
/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
function toObject(val) {
if (val === null || val === undefined) {
throw new TypeError('Object.assign cannot be called with null or undefined');
}
return Object(val);
}
function shouldUseNative() {
try {
if (!Object.assign) {
return false;
}
// Detect buggy property enumeration order in older V8 versions.
// https://bugs.chromium.org/p/v8/issues/detail?id=4118
var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
test1[5] = 'de';
if (Object.getOwnPropertyNames(test1)[0] === '5') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test2 = {};
for (var i = 0; i < 10; i++) {
test2['_' + String.fromCharCode(i)] = i;
}
var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
return test2[n];
});
if (order2.join('') !== '0123456789') {
return false;
}
// https://bugs.chromium.org/p/v8/issues/detail?id=3056
var test3 = {};
'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
test3[letter] = letter;
});
if (Object.keys(Object.assign({}, test3)).join('') !==
'abcdefghijklmnopqrst') {
return false;
}
return true;
} catch (err) {
// We don't expect any of the above to throw, but better to be safe.
return false;
}
}
module.exports = shouldUseNative() ? Object.assign : function (target, source) {
var from;
var to = toObject(target);
var symbols;
for (var s = 1; s < arguments.length; s++) {
from = Object(arguments[s]);
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
if (getOwnPropertySymbols) {
symbols = getOwnPropertySymbols(from);
for (var i = 0; i < symbols.length; i++) {
if (propIsEnumerable.call(from, symbols[i])) {
to[symbols[i]] = from[symbols[i]];
}
}
}
}
return to;
};
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
if (true) {
var invariant = __webpack_require__(16);
var warning = __webpack_require__(17);
var ReactPropTypesSecret = __webpack_require__(18);
var loggedTypeFailures = {};
}
/**
* Assert that the values match with the type specs.
* Error messages are memorized and will only be shown once.
*
* @param {object} typeSpecs Map of name to a ReactPropType
* @param {object} values Runtime values that need to be type-checked
* @param {string} location e.g. "prop", "context", "child context"
* @param {string} componentName Name of the component for error messages.
* @param {?Function} getStack Returns the component stack.
* @private
*/
function checkPropTypes(typeSpecs, values, location, componentName, getStack) {
if (true) {
for (var typeSpecName in typeSpecs) {
if (typeSpecs.hasOwnProperty(typeSpecName)) {
var error;
// Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
invariant(typeof typeSpecs[typeSpecName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'the `prop-types` package, but received `%s`.', componentName || 'React class', location, typeSpecName, typeof typeSpecs[typeSpecName]);
error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret);
} catch (ex) {
error = ex;
}
warning(!error || error instanceof Error, '%s: type specification of %s `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error);
if (error instanceof Error && !(error.message in loggedTypeFailures)) {
// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error.message] = true;
var stack = getStack ? getStack() : '';
warning(false, 'Failed %s type: %s%s', location, error.message, stack != null ? stack : '');
}
}
}
}
}
module.exports = checkPropTypes;
/***/ }),
/* 40 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["a"] = clearInitialization;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(27);
function clearInitialization() {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CLEAR_INITIALIZATION */]
};
}
/***/ }),
/* 41 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export onConnectionStateChange */
/* harmony export (immutable) */ __webpack_exports__["a"] = initConnection;
/* harmony export (immutable) */ __webpack_exports__["b"] = unsubscribeConnection;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(23);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__errors_actions__ = __webpack_require__(1);
function onConnectionStateChange(isConnected) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* ON_CONNECTION_STATE_CHANGED */],
payload: { isConnected: isConnected }
};
}
function initConnection(firebaseApp, onChange) {
return function (dispatch) {
firebaseApp.database().ref('.info/connected').on('value', function (snapshot) {
dispatch(onConnectionStateChange(snapshot.val()));
if (onChange !== undefined && onChange instanceof Function) {
onChange(snapshot.val());
}
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_1__errors_actions__["a" /* logError */])('.info/connected', err));
});
};
}
function unsubscribeConnection(firebaseApp) {
return function (dispatch) {
firebaseApp.database().ref('.info/connected').off();
dispatch(onConnectionStateChange(false));
};
}
/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export onTokenChanged */
/* unused harmony export onPermissionChanged */
/* unused harmony export onMessage */
/* harmony export (immutable) */ __webpack_exports__["a"] = clearMessage;
/* unused harmony export onMessagingError */
/* harmony export (immutable) */ __webpack_exports__["b"] = initMessaging;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(32);
function onTokenChanged(token) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["e" /* TOKEN_CHANGED */],
payload: { token: token, isInitialized: true }
};
}
function onPermissionChanged(hasPermission, onMessage) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["d" /* PERMISSION_CHANGED */],
payload: { hasPermission: hasPermission, isInitialized: true }
};
}
function onMessage(message) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* ON_MESSAGE */],
payload: { message: message }
};
}
function clearMessage() {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* ON_CLEAR_MESSAGE */]
};
}
function onMessagingError(error) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* MESSAGING_ERROR */],
payload: { error: error }
};
}
function initMessaging(firebaseApp, handleTokenChange, onMessageReceieved, onBackgroundMessageReceived) {
return function (dispatch) {
var messaging = firebaseApp.messaging();
try {
messaging.requestPermission().then(function () {
return messaging.getToken();
}).then(function (token) {
if (handleTokenChange !== undefined && handleTokenChange instanceof Function) {
handleTokenChange(token);
}
dispatch(onPermissionChanged(true));
dispatch(onTokenChanged(token));
}).catch(function (error) {
dispatch(onPermissionChanged(false));
console.warn(error);
});
} catch (e) {
dispatch(onPermissionChanged(false));
console.warn(e);
}
messaging.onMessage(function (payload) {
if (onMessageReceieved !== undefined && onMessageReceieved instanceof Function) {
onMessageReceieved(payload);
}
dispatch(onMessage(payload));
});
};
}
/***/ }),
/* 43 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (immutable) */ __webpack_exports__["b"] = authStateChanged;
/* harmony export (immutable) */ __webpack_exports__["a"] = authError;
/* unused harmony export defaultUserData */
/* harmony export (immutable) */ __webpack_exports__["c"] = watchAuth;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(20);
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function authStateChanged(user) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* AUTH_STATE_CHANGED */],
payload: user
};
}
function authError(error) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* AUTH_ERROR */],
payload: error
};
}
function defaultUserData(user) {
if (user != null) {
return {
displayName: user.displayName,
email: user.email,
photoURL: user.photoURL,
emailVerified: user.emailVerified,
isAnonymous: user.isAnonymous,
uid: user.uid,
providerData: user.providerData,
isAuthorised: true
};
} else {
return {
isAuthorised: false
};
}
}
function watchAuth(firebaseApp, onAuthStateChanged, onAuthError) {
return function (dispatch) {
firebaseApp.auth().onAuthStateChanged(function (user) {
if (onAuthStateChanged && onAuthStateChanged instanceof Function) {
dispatch(authStateChanged(_extends({ isAuthorised: !!user }, onAuthStateChanged(user))));
} else {
dispatch(authStateChanged(_extends({ isAuthorised: !!user }, defaultUserData(user))));
}
}, function (error) {
if (onAuthError && onAuthError instanceof Function) {
dispatch(authError(error));
} else {
dispatch(authError(error));
}
});
};
}
/***/ }),
/* 44 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export initialize */
/* unused harmony export childAdded */
/* unused harmony export childChanged */
/* unused harmony export childRemoved */
/* unused harmony export destroy */
/* unused harmony export unWatch */
/* unused harmony export getRef */
/* unused harmony export getLocation */
/* harmony export (immutable) */ __webpack_exports__["d"] = watchCol;
/* harmony export (immutable) */ __webpack_exports__["c"] = unwatchCol;
/* harmony export (immutable) */ __webpack_exports__["a"] = destroyCol;
/* unused harmony export unwatchAllCol */
/* harmony export (immutable) */ __webpack_exports__["b"] = unwatchAllCols;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(2);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__selectors__ = __webpack_require__(9);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors_actions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loadings_actions__ = __webpack_require__(6);
var initialize = function initialize(list, location, path, locationValue, append) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */],
payload: list,
path: path,
location: location,
append: append,
locationValue: locationValue
};
};
var childAdded = function childAdded(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */],
payload: child,
location: location
};
};
var childChanged = function childChanged(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */],
payload: child,
location: location
};
};
var childRemoved = function childRemoved(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */],
payload: child,
location: location
};
};
var destroy = function destroy(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["d" /* DESTROY */],
location: location
};
};
var unWatch = function unWatch(path) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["f" /* UNWATCH */],
path: path
};
};
var getPath = function getPath(firebaseApp, ref) {
return ref._query.path.segments.join('/');
};
var getRef = function getRef(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return firebaseApp.firestore().collection(path);
} else {
return path;
}
};
var getLocation = function getLocation(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return path;
} else {
return getPath(firebaseApp, path);
}
};
function watchCol(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var append = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var ref = getRef(firebaseApp, firebasePath);
var path = getLocation(firebaseApp, firebasePath);
var location = reduxPath || path;
return function (dispatch, getState) {
var isInitialized = __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__["a" /* isInitialised */](getState(), path, location);
var initialized = false;
if (!isInitialized) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_4__loadings_actions__["a" /* logLoading */])(location));
var unsub = ref.onSnapshot(function (snapshot) {
snapshot.docChanges.forEach(function (change) {
if (change.type === 'added') {
if (initialized) {
dispatch(childAdded({
id: change.doc.id,
data: change.doc.data()
}, location));
} else {
initialized = true;
dispatch(initialize([{
id: change.doc.id,
data: change.doc.data()
}], location, path, unsub, append));
}
}
if (change.type === 'modified') {
dispatch(childChanged({
id: change.doc.id,
data: change.doc.data()
}, location));
}
if (change.type === 'removed') {
dispatch(childRemoved({
id: change.doc.id,
data: change.doc.data()
}, location));
}
});
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
}
};
}
function unwatchCol(firebaseApp, firebasePath) {
return function (dispatch, getState) {
var location = firebasePath;
var allInitializations = __WEBPACK_IMPORTED_MODULE_1__selectors__["b" /* getAllInitializations */](getState());
var unsubs = allInitializations[location];
if (unsubs) {
Object.keys(unsubs).map(function (key) {
var unsub = unsubs[key];
if (typeof unsub === 'function') {
unsub();
}
dispatch(unWatch(location));
});
}
};
}
function destroyCol(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function (dispatch, getState) {
var location = reduxPath || getLocation(firebaseApp, firebasePath);
var locations = getState().initialization[location];
dispatch(unWatch(location));
dispatch(destroy(location));
if (reduxPath) {
dispatch(destroy(reduxPath));
unwatchCol(firebaseApp, reduxPath);
} else if (locations) {
Object.keys(locations).forEach(function (location) {
unwatchCol(firebaseApp, location);
dispatch(destroy(location));
});
}
};
}
function unwatchAllCol(firebaseApp, path) {
return function (dispatch, getState) {
var allLists = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllCols */](getState());
Object.keys(allLists).forEach(function (key, index) {
unwatchCol(firebaseApp, key);
dispatch(unWatch(key));
});
};
}
function unwatchAllCols(firebaseApp, path) {
return function (dispatch, getState) {
var allColls = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllCols */](getState());
Object.keys(allColls).forEach(function (key, index) {
unwatchCol(firebaseApp, key);
dispatch(destroyCol(firebaseApp, allColls[index]));
});
};
}
/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export valueChanged */
/* unused harmony export destroy */
/* unused harmony export unWatch */
/* unused harmony export getRef */
/* unused harmony export getLocation */
/* harmony export (immutable) */ __webpack_exports__["d"] = watchDoc;
/* harmony export (immutable) */ __webpack_exports__["c"] = unwatchDoc;
/* harmony export (immutable) */ __webpack_exports__["a"] = destroyDoc;
/* harmony export (immutable) */ __webpack_exports__["b"] = unwatchAllDocs;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(3);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__selectors__ = __webpack_require__(10);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors_actions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loadings_actions__ = __webpack_require__(6);
var valueChanged = function valueChanged(value, location, path, locationValue) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* VALUE_CHANGED */],
payload: value,
path: path,
location: location,
locationValue: locationValue
};
};
var destroy = function destroy(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* DESTROY */],
location: location
};
};
var unWatch = function unWatch(path) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* UNWATCH */],
path: path
};
};
var getRef = function getRef(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return firebaseApp.firestore().doc(path);
} else {
return path;
}
};
var getLocation = function getLocation(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return path;
} else {
return firebaseApp.firestore().doc(path).path;
}
};
function watchDoc(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var ref = getRef(firebaseApp, firebasePath);
var path = ref.path;
var location = reduxPath || getLocation(firebaseApp, firebasePath);
return function (dispatch, getState) {
var isInitialized = __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__["a" /* isInitialised */](getState(), location);
if (!isInitialized) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_4__loadings_actions__["a" /* logLoading */])(location));
var unsub = ref.onSnapshot(function (doc) {
dispatch(valueChanged(doc.data(), location, path, unsub));
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
}
};
}
function unwatchDoc(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function (dispatch, getState) {
var location = reduxPath || path;
var allInitializations = __WEBPACK_IMPORTED_MODULE_1__selectors__["b" /* getAllInitializations */](getState());
var unsubs = allInitializations[location];
if (unsubs) {
Object.keys(unsubs).map(function (key) {
var unsub = unsubs[key];
if (typeof unsub === 'function') {
unsub();
}
dispatch(unWatch(location));
});
}
};
}
function destroyDoc(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var location = reduxPath || path;
return function (dispatch) {
unwatchDoc(firebaseApp, location);
dispatch(unWatch(location));
dispatch(destroy(location));
};
}
function unwatchAllDocs(firebaseApp) {
return function (dispatch, getState) {
var allPaths = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllDocs */](getState());
Object.keys(allPaths).forEach(function (key, index) {
unwatchDoc(firebaseApp, allPaths[index]);
dispatch(unWatch(key));
});
};
}
/***/ }),
/* 46 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export initialize */
/* unused harmony export childAdded */
/* unused harmony export childChanged */
/* unused harmony export childRemoved */
/* unused harmony export destroy */
/* unused harmony export unWatch */
/* unused harmony export getRef */
/* unused harmony export getLocation */
/* harmony export (immutable) */ __webpack_exports__["d"] = watchList;
/* harmony export (immutable) */ __webpack_exports__["c"] = unwatchList;
/* harmony export (immutable) */ __webpack_exports__["a"] = destroyList;
/* harmony export (immutable) */ __webpack_exports__["b"] = unwatchAllLists;
/* unused harmony export destroyAllLists */
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(4);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__selectors__ = __webpack_require__(11);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors_actions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loadings_actions__ = __webpack_require__(6);
var initialize = function initialize(list, location, path, append) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["e" /* INIIALIZE */],
payload: list,
path: path,
location: location,
append: append,
locationValue: true
};
};
var childAdded = function childAdded(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* CHILD_ADDED */],
payload: child,
location: location
};
};
var childChanged = function childChanged(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* CHILD_CHANGED */],
payload: child,
location: location
};
};
var childRemoved = function childRemoved(child, location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* CHILD_REMOVED */],
payload: child,
location: location
};
};
var destroy = function destroy(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["d" /* DESTROY */],
location: location
};
};
var unWatch = function unWatch(path) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["f" /* UNWATCH */],
path: path
};
};
var getPayload = function getPayload(snapshot) {
return { key: snapshot.key, val: snapshot.val() };
};
var getRef = function getRef(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return firebaseApp.database().ref(path);
} else {
return path;
}
};
var getLocation = function getLocation(firebaseApp, path) {
if (typeof path === 'string' || path instanceof String) {
return path;
} else {
return path.toString().substring(firebaseApp.database().ref().root.toString().length);
}
};
function watchList(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var append = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
var ref = getRef(firebaseApp, firebasePath);
var path = ref.toString();
var location = reduxPath || getLocation(firebaseApp, firebasePath);
return function (dispatch, getState) {
var initialized = false;
var isInitialized = __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__["a" /* isInitialised */](getState(), path, location);
var persistetList = getState().lists ? getState().lists[location] : [];
if (!isInitialized) {
dispatch(initialize(persistetList, location, path, append));
dispatch(Object(__WEBPACK_IMPORTED_MODULE_4__loadings_actions__["a" /* logLoading */])(location));
ref.once('value', function (snapshot) {
initialized = true;
var list = [];
snapshot.forEach(function (childSnapshot) {
var childKey = childSnapshot.key;
var childData = childSnapshot.val();
list.push({ key: childKey, val: childData });
});
dispatch(initialize(list, location, path, append));
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
ref.on('child_added', function (snapshot) {
if (initialized) {
dispatch(childAdded(getPayload(snapshot), location));
}
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
ref.on('child_changed', function (snapshot) {
dispatch(childChanged(getPayload(snapshot), location));
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
ref.on('child_removed', function (snapshot) {
dispatch(childRemoved(getPayload(snapshot), location));
}, function (err) {
console.error(err);
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
}
};
}
function unwatchList(firebaseApp, firebasePath) {
return function (dispatch) {
var ref = getRef(firebaseApp, firebasePath);
ref.off();
dispatch(unWatch(ref.toString()));
};
}
function destroyList(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function (dispatch, getState) {
var ref = getRef(firebaseApp, firebasePath);
var locations = getState().initialization[ref.toString()];
ref.off();
dispatch(unWatch(ref.toString()));
if (reduxPath) {
dispatch(destroy(reduxPath));
} else if (locations) {
Object.keys(locations).forEach(function (location) {
dispatch(destroy(location));
});
}
};
}
function unwatchAllLists(firebaseApp, path) {
return function (dispatch, getState) {
var allLists = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllLists */](getState());
Object.keys(allLists).forEach(function (key, index) {
var ref = firebaseApp.database().ref(key);
ref.off();
dispatch(unWatch(ref.toString()));
});
};
}
function destroyAllLists(firebaseApp, path) {
return function (dispatch, getState) {
var allLists = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllLists */](getState());
Object.keys(allLists).forEach(function (key, index) {
var ref = firebaseApp.database().ref(key);
ref.off();
dispatch(destroyList(firebaseApp, ref.toString()));
});
};
}
/***/ }),
/* 47 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export valueChanged */
/* unused harmony export destroy */
/* unused harmony export unWatch */
/* harmony export (immutable) */ __webpack_exports__["d"] = watchPath;
/* harmony export (immutable) */ __webpack_exports__["c"] = unwatchPath;
/* harmony export (immutable) */ __webpack_exports__["a"] = destroyPath;
/* harmony export (immutable) */ __webpack_exports__["b"] = unwatchAllPaths;
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__types__ = __webpack_require__(5);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__selectors__ = __webpack_require__(12);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__ = __webpack_require__(7);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__errors_actions__ = __webpack_require__(1);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__loadings_actions__ = __webpack_require__(6);
var valueChanged = function valueChanged(value, location, path) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["c" /* VALUE_CHANGED */],
payload: value,
path: path,
location: location,
locationValue: true
};
};
var destroy = function destroy(location) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["a" /* DESTROY */],
location: location
};
};
var unWatch = function unWatch(path) {
return {
type: __WEBPACK_IMPORTED_MODULE_0__types__["b" /* UNWATCH */],
path: path
};
};
function watchPath(firebaseApp, firebasePath) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var location = reduxPath || firebasePath;
return function (dispatch, getState) {
var isInitialized = __WEBPACK_IMPORTED_MODULE_2__initialization_selectors__["a" /* isInitialised */](getState(), location);
if (!isInitialized) {
var ref = firebaseApp.database().ref(firebasePath);
var path = ref.toString();
dispatch(Object(__WEBPACK_IMPORTED_MODULE_4__loadings_actions__["a" /* logLoading */])(location));
ref.on('value', function (snapshot) {
dispatch(valueChanged(snapshot.val(), location, path));
}, function (err) {
dispatch(Object(__WEBPACK_IMPORTED_MODULE_3__errors_actions__["a" /* logError */])(location, err));
});
}
};
}
function unwatchPath(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
return function (dispatch) {
var location = reduxPath || path;
firebaseApp.database().ref(path).off();
dispatch(unWatch(location));
};
}
function destroyPath(firebaseApp, path) {
var reduxPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var location = reduxPath || path;
return function (dispatch) {
firebaseApp.database().ref(path).off();
dispatch(unWatch(location));
dispatch(destroy(location));
};
}
function unwatchAllPaths(firebaseApp) {
return function (dispatch, getState) {
var allPaths = __WEBPACK_IMPORTED_MODULE_1__selectors__["a" /* getAllPaths */](getState());
Object.keys(allPaths).forEach(function (key, index) {
firebaseApp.database().ref(allPaths[index]).off();
dispatch(unWatch(key));
});
};
}
/***/ }),
/* 48 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export isLoading */
function isLoading(state, location) {
if (state.loadings !== undefined && state.loadings[location]) {
return state.loadings[location];
}
return false;
}
/***/ }),
/* 49 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* unused harmony export hasError */
function hasError(state, path) {
if (state.errors !== undefined && state.errors[path]) {
return state.errors[path];
}
return false;
}
/***/ }),
/* 50 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react__ = __webpack_require__(13);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_react___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_react__);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_prop_types__ = __webpack_require__(14);
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_prop_types__);
var _class, _temp;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
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; }
var FirebaseProvider = (_temp = _class = function (_Component) {
_inherits(FirebaseProvider, _Component);
function FirebaseProvider() {
_classCallCheck(this, FirebaseProvider);
return _possibleConstructorReturn(this, _Component.apply(this, arguments));
}
FirebaseProvider.prototype.getChildContext = function getChildContext() {
return {
firebaseApp: this.props.firebaseApp
};
};
FirebaseProvider.prototype.render = function render() {
return this.props.children;
};
return FirebaseProvider;
}(__WEBPACK_IMPORTED_MODULE_0_react__["Component"]), _class.propTypes = {
children: __WEBPACK_IMPORTED_MODULE_1_prop_types___default.a.element
}, _class.childContextTypes = {
firebaseApp: __WEBPACK_IMPORTED_MODULE_1_prop_types___default.a.object.isRequired
}, _temp);
/* harmony default export */ __webpack_exports__["a"] = (FirebaseProvider);
/***/ })
/******/ ])["default"];
}); |
Jakshas/JavaMiniProjects | SimpleCompiler/obliczenia/Deklaracja.java | <reponame>Jakshas/JavaMiniProjects
package obliczenia;
import struktury.*;
public class Deklaracja extends Instrukcja{
String zmienna;
public Deklaracja(String z) throws Exception {
if (z==null) {
throw new Exception("null");
}
this.zmienna=z;
}
@Override
public void wykonaj() throws Exception {
for (Zbior srodowisko : Blok.srodowiska) {
if (srodowisko.szukajtf(zmienna)) {
throw new Exception("taka zmienna juz jest");
}
}
Blok.srodowiska.get(Blok.srodowiska.size()-1).wstaw(new Para(0,zmienna));
}
}
|
Adityajn/College-Codes | TE-1/PL-2/ethereal/libcrafter-master/libcrafter/crafter/Fields/FieldContainer.cpp | /*
Copyright (c) 2012, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "FieldContainer.h"
using namespace std;
using namespace Crafter;
FieldContainer::FieldContainer() {
/* By default, there aren't overlapped fields */
overlaped_flag = 0;
}
FieldContainer::FieldContainer(const FieldContainer& fc) {
const_iterator it;
overlaped_flag = fc.overlaped_flag;
ActiveFields = fc.ActiveFields;
/* Clone each field of the container */
for(it = fc.begin() ; it < fc.end() ; it++)
push_back((*it)->CloneField());
}
void FieldContainer::SetActive(size_t nfield) {
std::set<size_t> OverlappedFields;
/* Get the field pointer */
FieldInfo* ptr = (*this)[nfield];
/* First, check if the field is active */
if(ActiveFields.find(nfield) == ActiveFields.end()) {
/* If the field is not active, it may overlap some other field */
std::set<size_t>::iterator it_active;
for (it_active = ActiveFields.begin() ; it_active != ActiveFields.end() ; ++it_active) {
FieldInfo* FieldPtr = (*this)[(*it_active)];
/* Get information of the active fields */
size_t nword = FieldPtr->GetWord();
/* Check if the fields are in the same word */
if (ptr->GetWord() == nword) {
size_t bitpos = FieldPtr->GetBit();
size_t endpos = FieldPtr->GetEnd();
/* Check intersection */
if ( ( (ptr->GetBit() >= bitpos) && (ptr->GetBit() < endpos) ) ||
( (ptr->GetEnd() > bitpos) && (ptr->GetEnd() <= endpos) ) ) {
OverlappedFields.insert(*it_active);
}
}
}
/* And push it into the active fields set */
ActiveFields.insert(nfield);
}
/* Remove overlapped fields, if any */
std::set<size_t>::iterator it_over;
for (it_over = OverlappedFields.begin() ; it_over != OverlappedFields.end() ; ++it_over)
ActiveFields.erase(*it_over);
}
FieldContainer& FieldContainer::operator=(const FieldContainer& right) {
const_iterator it;
/* Delete each field of the container */
for(it = begin() ; it < end() ; it++)
delete (*it);
clear();
/* Clone each field of the container */
for(it = right.begin() ; it < right.end() ; it++)
push_back((*it)->CloneField());
overlaped_flag = right.overlaped_flag;
ActiveFields = right.ActiveFields;
return *this;
}
FieldContainer::~FieldContainer() {
iterator it;
/* Delete each field of the container */
for(it = begin() ; it < end() ; it++)
delete (*it);
}
void FieldContainer::Print(std::ostream& str) const {
if(!overlaped_flag) {
const_iterator it;
/* Delete each field of the container */
for(it = begin() ; it < end() ; it++)
str << *(*it) << " , ";
} else {
/* Just apply the function to the active fields */
set<size_t>::const_iterator it_active;
for (it_active = ActiveFields.begin() ; it_active != ActiveFields.end(); ++it_active)
str << *(*this)[*it_active] << " , ";
}
}
|
wangrling/media | app/src/main/java/com/android/mm/music/custom/PermissionActivity.java | package com.android.mm.music.custom;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import com.android.mm.R;
import java.util.ArrayList;
import java.util.List;
public class PermissionActivity extends Activity{
private static final String PERVIOUS_INTENT = "pervious_intent";
private static final String REQUEST_PERMISSIONS = "request_permissions";
private static final String KEY_FROM_PREVIEW = "from_preview";
private static final String PACKAGE_URL_SCHEME = "package:";
private static final int REQUEST_CODE = 100;
private String[] mRequestedPermissons;
private Intent mPreviousIntent;
private boolean mIsFromPreview = false;
public static void startFromPreview(Activity activity, String[] permissions, int requestCode) {
Intent intent = new Intent();
intent.setClass(activity, PermissionActivity.class);
intent.putExtra(REQUEST_PERMISSIONS, permissions);
intent.putExtra(PERVIOUS_INTENT, activity.getIntent());
intent.putExtra(KEY_FROM_PREVIEW, true);
activity.startActivityForResult(intent, requestCode);
}
public static boolean checkAndRequestPermission(Activity activity, String[] permissions) {
String[] neededPermissions = checkRequestedPermission(activity, permissions);
if (neededPermissions.length == 0) {
return false;
} else {
Intent intent = new Intent();
intent.setClass(activity, PermissionActivity.class);
intent.putExtra(REQUEST_PERMISSIONS, permissions);
intent.putExtra(PERVIOUS_INTENT, activity.getIntent());
activity.startActivity(intent);
activity.finish();
return true;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreviousIntent = (Intent)getIntent().getExtras().get(PERVIOUS_INTENT);
mIsFromPreview = getIntent().getBooleanExtra(KEY_FROM_PREVIEW, false);
mRequestedPermissons = getIntent().getStringArrayExtra(REQUEST_PERMISSIONS);
if (savedInstanceState == null && mRequestedPermissons != null) {
String[] neededPermissions =
checkRequestedPermission(PermissionActivity.this, mRequestedPermissons);
if (neededPermissions != null && neededPermissions.length != 0) {
requestPermissions(neededPermissions, REQUEST_CODE);
}
}
}
public static String[] checkRequestedPermission(Activity activity, String[] permissionName) {
boolean isPermissionGranted = true;
List<String> needRequestPermission = new ArrayList<String>();
for (String tmp : permissionName) {
isPermissionGranted = (PackageManager.PERMISSION_GRANTED ==
activity.checkSelfPermission(tmp));
if (!isPermissionGranted) {
needRequestPermission.add(tmp);
}
}
String[] needRequestPermissionArray = new String[needRequestPermission.size()];
needRequestPermission.toArray(needRequestPermissionArray);
return needRequestPermissionArray;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
boolean isAllPermissionsGranted = true;
if (requestCode != REQUEST_CODE || permissions == null || grantResults == null ||
permissions.length == 0 || grantResults.length == 0) {
isAllPermissionsGranted = false;
} else {
for (int i : grantResults) {
if (i != PackageManager.PERMISSION_GRANTED)
isAllPermissionsGranted = false;
}
}
if(isAllPermissionsGranted) {
if (mPreviousIntent != null)
if (mIsFromPreview){
startActivity(mPreviousIntent);
setResult(Activity.RESULT_OK);
} else {
if (mPreviousIntent != null)
startActivity(mPreviousIntent);
}
finish();
} else {
showMissingPermissionDialog();
}
}
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.dialog_title_help);
builder.setMessage(R.string.dialog_content);
builder.setNegativeButton(R.string.dialog_button_quit,
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
if (mIsFromPreview){
setResult(Activity.RESULT_CANCELED);
}
finish();
}
});
builder.setPositiveButton(R.string.dialog_button_settings,
new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
startActivity(intent);
finish();
}
});
builder.show();
}
}
|
samuel-gomez/react-starter-toolk | src/shared/components/Cards/Cards.test.js | <reponame>samuel-gomez/react-starter-toolk<gh_stars>1-10
import React from 'react';
import { render, act } from '@testing-library/react';
import Cards from './index';
const defaultProps = { items: [{ id: 'id', title: 'title', picture: { alt: 'alt', name: 'image.jpg' } }] };
describe('<Cards/>', () => {
it('Should render Cards', async () => {
await act(async () => {
const { asFragment } = render(<Cards {...defaultProps} />);
expect(asFragment()).toMatchSnapshot();
});
});
});
|
JCYang/ya_uftp | sender/detail/server.cpp | <reponame>JCYang/ya_uftp<filename>sender/detail/server.cpp<gh_stars>0
#include "sender/server.hpp"
#include "detail/message.hpp"
#include "detail/core.hpp"
#include "detail/progress_notification.hpp"
#include "utilities/network_intf.hpp"
#include "sender/detail/files_delivery_session.hpp"
#include <map>
#include <random>
#include "boost/asio.hpp"
namespace ya_uftp::sender{
class server::impl{
const std::size_t m_max_concurrent_tasks;
core::detail::execution_unit& m_net_exec_unit;
core::detail::execution_unit& m_disk_exec_unit;
static task::token generate_task_token(const task::parameters& params){
if (api::holds_alternative<api::fs::path>(params.files)){
auto& fpath = api::get<api::fs::path>(params.files);
return std::hash<std::string>{}(fpath.string() + '_' +
params.public_multicast_addr.to_string() + ':' + std::to_string(params.destination_port));
}
else{
// ToDo: fix all these
return 0u;
}
}
static std::error_condition validate_target(const api::fs::path& fp){
auto ec = api::error_code{};
auto result = std::error_condition{};
if (not api::fs::exists(fp, ec))
result = std::make_error_condition(std::errc::no_such_file_or_directory);
if (not api::fs::is_regular_file(fp, ec) &&
not api::fs::is_directory(fp, ec) &&
not api::fs::is_symlink(fp, ec))
result = std::make_error_condition(std::errc::not_supported);
return result;
}
std::map<task::token, std::weak_ptr<detail::files_delivery_session>> m_active_sessions;
std::map<task::token, task::parameters> m_waiting_queue;
public:
impl(const std::size_t max_concurrent_tasks)
: m_max_concurrent_tasks(max_concurrent_tasks),
m_net_exec_unit(core::detail::execution_unit::get_for_next_job(core::detail::execution_unit::type::network_io)),
m_disk_exec_unit(core::detail::execution_unit::get_for_next_job(core::detail::execution_unit::type::disk_io)) {}
~impl(){
stop();
}
void run(){
m_net_exec_unit.start();
m_disk_exec_unit.start();
}
void stop(){
std::for_each(m_active_sessions.begin(), m_active_sessions.end(),
[](auto kv){
auto ss = kv.second.lock();
if (ss)
ss->force_end();
});
}
api::variant<task::launch_result, std::error_condition>
sync_files(task::parameters& params){
if (api::holds_alternative<api::fs::path>(params.files)){
auto& file = api::get<api::fs::path>(params.files);
auto ec = validate_target(file);
if (ec)
return ec;
}
else{
// for list of targets, we silently ignore all the invalid/non-exists entries,
// unless there's no valid entries left.
// ToDo: add logs here
auto& files = api::get<std::vector<task::parameters::single_file>>(params.files);
auto cleaned_files = std::vector<task::parameters::single_file>{};
auto include_invalid_entry = false;
for (auto object : files) {
auto ec = validate_target(object.source_path);
if (!ec)
cleaned_files.emplace_back(object);
else
include_invalid_entry = true;
}
if (include_invalid_entry){
if (not cleaned_files.empty())
params.files = std::move(cleaned_files);
else
return std::make_error_condition(std::errc::invalid_argument);
}
}
if (params.public_multicast_addr == params.private_multicast_addr ||
params.public_multicast_addr.is_v4() != params.private_multicast_addr.is_v4())
return std::make_error_condition(std::errc::not_supported);
if (params.allowed_clients)
return std::make_error_condition(std::errc::not_supported);
auto tsk_token = generate_task_token(params);
auto iter = m_active_sessions.find(tsk_token);
if (iter != m_active_sessions.end()){
if (not iter->second.expired())
return task::launch_result{task::initiate_result::already_syncing, tsk_token};
else
m_active_sessions.erase(iter);
}
auto qiter = m_waiting_queue.find(tsk_token);
if (qiter != m_waiting_queue.end())
return task::launch_result{task::initiate_result::already_queueing, tsk_token};
if (m_active_sessions.size() < m_max_concurrent_tasks){
auto& ne = core::detail::execution_unit::get_for_next_job(core::detail::execution_unit::type::network_io);
if (not ne.running())
ne.start();
auto& de = core::detail::execution_unit::get_for_next_job(core::detail::execution_unit::type::disk_io);
if (not de.running())
de.start();
auto new_session = detail::files_delivery_session::create(
ne.context(),
de.context(), params);
m_active_sessions.emplace(tsk_token, new_session);
new_session->start();
return task::launch_result{task::initiate_result::just_started, tsk_token};
}
else{
m_waiting_queue.emplace(tsk_token, params);
return task::launch_result{task::initiate_result::just_queued, tsk_token};
}
}
void cancel_task(task::token tsk_token){
auto iter = m_active_sessions.find(tsk_token);
if (iter != m_active_sessions.end()){
auto ss = iter->second.lock();
if (ss != nullptr)
ss->force_end();
else
m_active_sessions.erase(iter);
}
}
};
server::server(const std::size_t max_concurrent_tasks)
: m_impl(std::make_unique<impl>(max_concurrent_tasks)){}
server::~server() = default;
void server::run(){
m_impl->run();
}
void server::stop(){
m_impl->stop();
}
api::variant<task::launch_result, std::error_condition>
server::sync_files(task::parameters& params){
return m_impl->sync_files(params);
}
api::optional<std::uint32_t> server::install_progress_monitor(task::progress::listener lst)
{
return core::detail::progress_notification::get().add_listener(std::move(lst));
}
void server::cancel_task(task::token tsk_token){
m_impl->cancel_task(tsk_token);
}
} |
dariodsa/JavaCourse | hw05-0036490887/src/main/java/hr/fer/zemris/java/hw05/db/FieldValueGetters.java | package hr.fer.zemris.java.hw05.db;
/**
* Contains static final variable which implements {@link IFieldValueGetter}
* from every returns specific attribute from {@link StudentRecord}
* @author dario
*
*/
public class FieldValueGetters {
/**
* Returns {@link StudentRecord#getFirstName()} of the given {@link StudentRecord}
*/
public static final IFieldValueGetter FIRST_NAME = ((t)->t.getFirstName());
/**
* Returns {@link StudentRecord#getLastName()} of the given {@link StudentRecord}
*/
public static final IFieldValueGetter LAST_NAME = ((t)->t.getLastName());
/**
* Returns {@link StudentRecord#getJmbag()} of the given {@link StudentRecord}
*/
public static final IFieldValueGetter JMBAG = ((t)->t.getJmbag());
/**
* Enum representation of possible variable.
* @author dario
*
*/
public enum Enum {
/**
* firstName variable
*/
FIRST_NAME ("firstName"),
/**
* lastName variable
*/
LAST_NAME ("lastName"),
/**
* jmbag variable
*/
JMBAG ("jmbag"),
/**
* unknown variable
*/
UNKNOWN("");
/**
* string reprsentation of enum
*/
public final String value;
/**
* Enum constructor with string as value.
* @param value
*/
private Enum(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
/**
* Returns {@link Enum} from string value.
* @param value
* @return Enum representation of string
*/
public static Enum fromString(String value) {
for(Enum E : Enum.values()) {
if(E.value.compareTo(value) == 0) {
return E;
}
}
return Enum.UNKNOWN;
}
}
}
|
fabianmeco/english_school | src/student/student.fixture.js | <reponame>fabianmeco/english_school
module.exports = {
post:{
student:{
id: 1,
fullname: "<NAME>",
cid: "1094533533",
birthday: "1990-03-21",
phone_number: "3205654335",
email: "<EMAIL>",
address: "Calle falsa 123"
},
student2:{
id: 2,
fullname: "<NAME>",
cid: "1094533534",
birthday: "1990-03-21",
phone_number: "3205654335",
email: "<EMAIL>",
address: "Calle falsa 123"
},
wrong_student:{
id: 2,
fullname: "<NAME>",
cid: 1094533533,
birthday: "1990-03-21",
phone_number: "320565433",
email: "<EMAIL>",
address: "Calle falsa 123"
},
wrong_student_email:{
id: 3,
fullname: "<NAME>",
cid: "1094533532",
birthday: "1990-03-21",
phone_number: "3205654333",
email: "@domain.comand",
address: "Calle falsa 123"
},
wrngflds_student_email:{
id: 4,
fullname: "<NAME>",
birthday: "1990-03-21",
phone_number: "3205654333",
email: "@domain.comand",
address: "Calle falsa 123"
}
},
put:{
student:{
fullname: "<NAME>",
cid: "1094533533",
birthday: "1990-03-05",
phone_number: "3205654335",
email: "<EMAIL>",
address: "Calle falsa 123"
},
student2:{
fullname: "<NAME>",
cid: "1094533533",
birthday: "1990-03-05",
phone_number: "3205654335",
email: "<EMAIL>",
address: "Calle falsa 123"
}
}
} |
null-kryptonian/ProblemSolving | LeetCode/0067. Add Binary.cpp | <filename>LeetCode/0067. Add Binary.cpp<gh_stars>1-10
class Solution
{
public:
string addBinary(string a, string b) {
int i = a.size() - 1, j = b.size() - 1, carry = 0; // i, j are the index of a, b
string res; // res is the result
while (i >= 0 || j >= 0) { // while there are still digits in a, b
int sum = carry; // sum is the sum of the current digits
if (i >= 0) sum += a[i--] - '0'; // add the digit of a
if (j >= 0) sum += b[j--] - '0'; // add the digit of b
res.push_back(sum % 2 + '0'); // add the digit of sum to the result
carry = sum / 2; // carry is the carry of sum
}
if (carry) res.push_back(carry + '0'); // if there is a carry, add it to the result
reverse(res.begin(), res.end()); // reverse the result
return res; // return the result
}
}; |
marlonruo/PixelWeatherAndroid | www/animaciones/522/522.js | <filename>www/animaciones/522/522.js<gh_stars>0
(function (lib, img, cjs, ss) {
var p; // shortcut to reference prototypes
var rect; // used to reference frame bounds
// library properties:
lib.properties = {
width: 750,
height: 540,
fps: 12,
color: "#02304B",
manifest: [
{src:"images/bat_1.png", id:"bat_1"},
{src:"images/bat_2.png", id:"bat_2"},
{src:"images/lluvia_1.png", id:"lluvia_1"},
{src:"images/lluvia_2.png", id:"lluvia_2"},
{src:"images/lluvia_3.png", id:"lluvia_3"}
]
};
// symbols:
(lib.bat_1 = function() {
this.initialize(img.bat_1);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,108,210);
(lib.bat_2 = function() {
this.initialize(img.bat_2);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,108,210);
(lib.lluvia_1 = function() {
this.initialize(img.lluvia_1);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,750,540);
(lib.lluvia_2 = function() {
this.initialize(img.lluvia_2);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,750,540);
(lib.lluvia_3 = function() {
this.initialize(img.lluvia_3);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,750,540);
(lib.lluvia = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Layer 1
this.instance = new lib.lluvia_1();
this.instance_1 = new lib.lluvia_3();
this.instance_2 = new lib.lluvia_2();
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance}]}).to({state:[{t:this.instance_1}]},1).to({state:[{t:this.instance_2}]},1).wait(1));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = rect = new cjs.Rectangle(0,0,750,540);
p.frameBounds = [rect, rect, rect];
(lib.batman = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// Layer 1
this.instance = new lib.bat_2();
this.instance_1 = new lib.bat_1();
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance}]}).to({state:[{t:this.instance_1}]},2).wait(2));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = rect = new cjs.Rectangle(0,0,108,210);
p.frameBounds = [rect, rect, rect, rect];
// stage content:
(lib._522 = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// lluvia
this.instance = new lib.lluvia("synched",0);
this.instance.setTransform(361.5,268.5,1,1,0,0,0,361.5,268.5);
this.timeline.addTween(cjs.Tween.get(this.instance).wait(30));
// batman
this.instance_1 = new lib.batman("synched",0);
this.instance_1.setTransform(396,435,1,1,0,0,0,54,105);
this.timeline.addTween(cjs.Tween.get(this.instance_1).wait(30));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = rect = new cjs.Rectangle(375,270,750,540);
p.frameBounds = [rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect, rect];
})(lib = lib||{}, images = images||{}, createjs = createjs||{}, ss = ss||{});
var lib, images, createjs, ss; |
mlgjsk/JavaScript | IntermediateAlgorithms/03.seek-and-destroy.js | <reponame>mlgjsk/JavaScript<filename>IntermediateAlgorithms/03.seek-and-destroy.js
/**
* You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments.
* Remove all elements from the initial array that are of the same value as these arguments.
*/
function destroyer(arr) {
var args = Array.from(arguments).slice(1);
return arr.filter(function(val) {
return !args.includes(val);
});
}
destroyer([ 1, 2, 3, 1, 2, 3 ], 2, 3);
|
Jaeguins/Prototype | UEPrototype/Source/UEPrototype/Public/Grid/EditorGrid.h | <gh_stars>0
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Math/Color.h"
#include "EditorGrid.generated.h"
class UMaterialInstanceDynamic;
class UStaticMeshComponent;
class APlayerController;
UCLASS()
class UEPROTOTYPE_API AEditorGrid : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
AEditorGrid();
// 그리드 스냅의 동기화를 설정 on/off 할 수 있는 함수입니다
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetSyncWithGridSnapEnabled(bool bSyncWithGridSnap);
// 그리드 스냅의 동기화여부를 반환하는 함수입니다.
UFUNCTION(BlueprintPure, Category = "Grid")
bool IsSyncWithGridSnap() const;
// 그리드 간격을 설정하는 함수입니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetGridInterval(float GridInterval);
// 그리드 간격을 반환하는 함수입니다.
UFUNCTION(BlueprintPure, Category = "Grid")
float GetGridInterval() const;
// 타이머로 지정한 시간마다 플레이어의 x,y 위치값을 받아서 현재 위치에 추가해주는 함수입니다
UFUNCTION(BluePrintCallable, Category = "Grid")
void UpdateGridPosition();
// 그리드 표시 여부를 토글합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
FORCEINLINE bool ToggleGridView()
{
return (bGridVisualize = !bGridVisualize);
};
// TOGGLE TRACING이 TRUE일 때 UpdateGridPosition를 활성화합니다. 그리드가 사용자를 추적할지 여부를 토글합니다. 주석 수정 필요합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
FORCEINLINE bool ToggleTracing()
{
return (bGridTracing = !bGridTracing);
}
// 지정된 인덱스의 그리드 색상을 변경합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetGridColor(FLinearColor InColor, int InGridIndex);
// 그리드 격자 간격을 조정합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetGridScale(float InGridScale);
// 그리드의 페이드 시작 거리를 조정합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetGridFadeDistance(float InFadeLength);
// 그리드의 오파시티를 조정합니다.
UFUNCTION(BlueprintCallable, Category = "Grid")
void SetGridOpacity(float InGridOpacity);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
private:
//
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Grid", meta = (AllowPrivateAccess = true))
UStaticMeshComponent* EditorGridMesh;
// SM Comp에 입힐 머티리얼
UPROPERTY()
UMaterialInstanceDynamic * MIDTemplate;
// 그리드 간격과 스냅의 동기화를 설정해주는 변수입니다.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Grid", meta = (AllowPrivateAccess = true))
bool bSyncWithGridSnap;
// 그리드의 간격을 설정받는 변수입니다.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Grid", meta = (AllowPrivateAccess = true))
float GridInterval;
// 이전의 그리드 간격 값을 저장해주는 변수입니다.
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Grid", meta = (AllowPrivateAccess = true))
float GridIntervalCache;
// 그리드가 시각화 상태인지 여부
bool bGridVisualize;
// 그리드가 유저를 쫒아다닐 지 여부
bool bGridTracing;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Grid", meta = (AllowPrivateAccess = "true", ClampMin = "1.0", UIMin = "1.0"))
float TraceTimerInterval;
// 로컬 플레이어 캐시
UPROPERTY()
APlayerController const * CachedPlayer;
}; |
jeet/tentacle | vendor/ruby-sequel/spec/adapters/sqlite_spec.rb | <filename>vendor/ruby-sequel/spec/adapters/sqlite_spec.rb
require File.join(File.dirname(__FILE__), '../../lib/sequel/sqlite')
SQLITE_DB = Sequel('sqlite:/')
SQLITE_DB.create_table :items do
integer :id, :primary_key => true, :auto_increment => true
text :name
float :value
end
context "An SQLite database" do
setup do
@db = Sequel('sqlite:/')
end
specify "should provide a list of existing tables" do
@db.tables.should == []
@db.create_table :testing do
text :name
end
@db.tables.should include(:testing)
end
specify "should support getting pragma values" do
@db.pragma_get(:auto_vacuum).should == '0'
end
specify "should support setting pragma values" do
@db.pragma_set(:auto_vacuum, '1')
@db.pragma_get(:auto_vacuum).should == '1'
end
specify "should support getting and setting the auto_vacuum pragma" do
@db.auto_vacuum = :full
@db.auto_vacuum.should == :full
@db.auto_vacuum = :none
@db.auto_vacuum.should == :none
proc {@db.auto_vacuum = :invalid}.should raise_error(SequelError)
end
specify "should support getting and setting the synchronous pragma" do
@db.synchronous = :off
@db.synchronous.should == :off
@db.synchronous = :normal
@db.synchronous.should == :normal
@db.synchronous = :full
@db.synchronous.should == :full
proc {@db.synchronous = :invalid}.should raise_error(SequelError)
end
specify "should support getting and setting the temp_store pragma" do
@db.temp_store = :default
@db.temp_store.should == :default
@db.temp_store = :file
@db.temp_store.should == :file
@db.temp_store = :memory
@db.temp_store.should == :memory
proc {@db.temp_store = :invalid}.should raise_error(SequelError)
end
specify "should be able to execute multiple statements at once" do
@db.create_table :t do
text :name
end
@db << "insert into t (name) values ('abc');insert into t (name) values ('def')"
@db[:t].count.should == 2
@db[:t].order(:name).map(:name).should == ['abc', 'def']
end
specify "should be able to execute transactions" do
@db.transaction do
@db.create_table(:t) {text :name}
end
@db.tables.should == [:t]
proc {@db.transaction do
@db.create_table(:u) {text :name}
raise ArgumentError
end}.should raise_error(ArgumentError)
# no commit
@db.tables.should == [:t]
proc {@db.transaction do
@db.create_table(:v) {text :name}
rollback!
end}.should_not raise_error
# no commit
@db.tables.should == [:t]
end
specify "should support nested transactions" do
@db.transaction do
@db.transaction do
@db.create_table(:t) {text :name}
end
end
@db.tables.should == [:t]
proc {@db.transaction do
@db.create_table(:v) {text :name}
@db.transaction do
rollback! # should roll back the top-level transaction
end
end}.should_not raise_error
# no commit
@db.tables.should == [:t]
end
specify "should provide disconnect functionality" do
@db.tables
@db.pool.size.should == 1
@db.disconnect
@db.pool.size.should == 0
end
end
context "An SQLite dataset" do
setup do
@d = SQLITE_DB[:items]
@d.delete # remove all records
end
specify "should return the correct records" do
@d.to_a.should == []
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'abc', :value => 4.56}
@d << {:name => 'def', :value => 7.89}
@d.select(:name, :value).to_a.sort_by {|h| h[:value]}.should == [
{:name => 'abc', :value => 1.23},
{:name => 'abc', :value => 4.56},
{:name => 'def', :value => 7.89}
]
end
specify "should return the correct record count" do
@d.count.should == 0
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'abc', :value => 4.56}
@d << {:name => 'def', :value => 7.89}
@d.count.should == 3
end
specify "should return the last inserted id when inserting records" do
id = @d << {:name => 'abc', :value => 1.23}
id.should == @d.first[:id]
end
specify "should update records correctly" do
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'abc', :value => 4.56}
@d << {:name => 'def', :value => 7.89}
@d.filter(:name => 'abc').update(:value => 5.3)
# the third record should stay the same
@d[:name => 'def'][:value].should == 7.89
@d.filter(:value => 5.3).count.should == 2
end
specify "should delete records correctly" do
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'abc', :value => 4.56}
@d << {:name => 'def', :value => 7.89}
@d.filter(:name => 'abc').delete
@d.count.should == 1
@d.first[:name].should == 'def'
end
end
context "An SQLite dataset" do
setup do
@d = SQLITE_DB[:items]
@d.delete # remove all records
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'def', :value => 4.56}
@d << {:name => 'ghi', :value => 7.89}
end
specify "should correctly return avg" do
@d.avg(:value).should == ((1.23 + 4.56 + 7.89) / 3).to_s
end
specify "should correctly return sum" do
@d.sum(:value).should == (1.23 + 4.56 + 7.89).to_s
end
specify "should correctly return max" do
@d.max(:value).should == 7.89.to_s
end
specify "should correctly return min" do
@d.min(:value).should == 1.23.to_s
end
end
context "SQLite::Dataset#delete" do
setup do
@d = SQLITE_DB[:items]
@d.delete # remove all records
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'def', :value => 4.56}
@d << {:name => 'ghi', :value => 7.89}
end
specify "should return the number of records affected when filtered" do
@d.count.should == 3
@d.filter {:value < 3}.delete.should == 1
@d.count.should == 2
@d.filter {:value < 3}.delete.should == 0
@d.count.should == 2
end
specify "should return the number of records affected when unfiltered" do
@d.count.should == 3
@d.delete.should == 3
@d.count.should == 0
@d.delete.should == 0
end
end
context "SQLite::Dataset#update" do
setup do
@d = SQLITE_DB[:items]
@d.delete # remove all records
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'def', :value => 4.56}
@d << {:name => 'ghi', :value => 7.89}
end
specify "should return the number of records affected" do
@d.filter(:name => 'abc').update(:value => 2).should == 1
@d.update(:value => 10).should == 3
@d.filter(:name => 'xxx').update(:value => 23).should == 0
end
end
context "An SQLite dataset in array tuples mode" do
setup do
@d = SQLITE_DB[:items]
@d.delete # remove all records
Sequel.use_array_tuples
end
teardown do
Sequel.use_hash_tuples
end
specify "should return the correct records" do
@d.to_a.should == []
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'abc', :value => 4.56}
@d << {:name => 'def', :value => 7.89}
@d.select(:name, :value).to_a.sort_by {|h| h[:value]}.should == [
Array.from_hash({:name => 'abc', :value => 1.23}),
Array.from_hash({:name => 'abc', :value => 4.56}),
Array.from_hash({:name => 'def', :value => 7.89})
]
end
end
context "SQLite dataset" do
setup do
SQLITE_DB.create_table :test do
integer :id, :primary_key => true, :auto_increment => true
text :name
float :value
end
@d = SQLITE_DB[:items]
@d.delete # remove all records
@d << {:name => 'abc', :value => 1.23}
@d << {:name => 'def', :value => 4.56}
@d << {:name => 'ghi', :value => 7.89}
end
teardown do
SQLITE_DB.drop_table :test
end
specify "should be able to insert from a subquery" do
SQLITE_DB[:test] << @d
SQLITE_DB[:test].count.should == 3
SQLITE_DB[:test].select(:name, :value).order(:value).to_a.should == \
@d.select(:name, :value).order(:value).to_a
end
end
|
fabo-corp/phabos | arch/arm/common/lowio.c | /*
* Copyright (C) 2015 <NAME>. All rights reserved.
* Author: <NAME> <<EMAIL>>
*
* Provided under the three clause BSD license found in the LICENSE file.
*/
#include <config.h>
#include <asm/semihosting.h>
#include <stdbool.h>
#include <stdio.h>
void machine_lowputchar(char c);
int machine_lowgetchar(bool wait);
void low_putchar(char c)
{
#ifdef CONFIG_ARM_SEMIHOSTING
semihosting_putc(c);
#else
machine_lowputchar(c);
#endif
}
ssize_t low_write(char *buffer, int count)
{
#ifdef CONFIG_ARM_SEMIHOSTING
return semihosting_write(buffer, count);
#else
for (int i = 0; i < count; i++)
low_putchar(buffer[i]);
return count;
#endif
}
int low_getchar(bool wait)
{
#ifdef CONFIG_ARM_SEMIHOSTING
char c;
if (!wait)
return EOF;
semihosting_read(&c, 1);
return c;
#else
return machine_lowgetchar(wait);
#endif
}
|
protolabz/viewdu | _client_modules/coreapp/translations/config/translationHelper.js | <filename>_client_modules/coreapp/translations/config/translationHelper.js<gh_stars>0
export default class TranslationHelper {
constructor() {
this.translations = {};
}
$get() {
return {
translations: this.translations,
add: function(key, value) {
if(key && value) {
this.translations['en-US'][key] = value;
}
}
}
}
} |
wolfgangwalther/lazygit | pkg/cheatsheet/check.go | package cheatsheet
import (
"fmt"
"io/fs"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"github.com/pmezard/go-difflib/difflib"
)
func Check() {
dir := GetDir()
tmpDir := filepath.Join(os.TempDir(), "lazygit_cheatsheet")
err := os.RemoveAll(tmpDir)
if err != nil {
log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err)
}
err = os.Mkdir(tmpDir, 0o700)
if err != nil {
log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err)
}
generateAtDir(tmpDir)
defer os.RemoveAll(tmpDir)
actualContent := obtainContent(dir)
expectedContent := obtainContent(tmpDir)
if expectedContent == "" {
log.Fatal("empty expected content")
}
if actualContent != expectedContent {
err := difflib.WriteUnifiedDiff(os.Stdout, difflib.UnifiedDiff{
A: difflib.SplitLines(expectedContent),
B: difflib.SplitLines(actualContent),
FromFile: "Expected",
FromDate: "",
ToFile: "Actual",
ToDate: "",
Context: 1,
})
if err != nil {
log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err)
}
fmt.Printf("\nCheatsheets are out of date. Please run `%s` at the project root and commit the changes. If you run the script and no keybindings files are updated as a result, try rebasing onto master and trying again.\n", CommandToRun())
os.Exit(1)
}
fmt.Println("\nCheatsheets are up to date")
}
func obtainContent(dir string) string {
re := regexp.MustCompile(`Keybindings_\w+\.md$`)
content := ""
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if re.MatchString(path) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err)
}
content += fmt.Sprintf("\n%s\n\n", filepath.Base(path))
content += string(bytes)
}
return nil
})
if err != nil {
log.Fatalf("Error occurred while checking if cheatsheets are up to date: %v", err)
}
return content
}
|
krishukr/cpp-code | src/GMOJ/1007/gmoj-1007-b-0.cpp | #include <cstdio>
#include <iomanip>
#include <iostream>
typedef long long ll;
template <typename T>
T read();
int main() {
std::ios::sync_with_stdio(false);
ll x = read<ll>(), y = read<ll>(), ans = 0, l, r;
ll n = std::min(x, y);
for (l = 1; l <= n; l = r + 1) {
r = x / (x / l);
ans += (x % l + x % r) * (r - l + 1) / 2;
}
if (x < y) {
ans += (y - x) * x;
}
std::cout << ans << '\n';
return 0;
}
template <typename T>
T read() {
T x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
return x * f;
} |
kirbo/slacky | src/component/A/A.js | import React from 'react';
import PropTypes from 'prop-types';
import { openExternal } from '../../assets/utils';
/**
* Handle onClick event.
* @param {event} event - Onclick event
*/
const handleClick = event => {
if (event.target.dataset.external === 'true') {
event.preventDefault();
openExternal(event.target.href);
}
};
/**
* Common component for links.
* @param {object} props - Properties for the component.
* @returns {html} <a />
*/
const A = ({ href, name, children, external }) => (
<a
href={href}
onClick={handleClick}
target={external ? '_blank' : '_self'}
rel="noopener noreferrer"
aria-label={name}
data-external={external}
>
{children}
</a>
);
A.propTypes = {
href: PropTypes.string.isRequired,
name: PropTypes.string,
external: PropTypes.bool,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node,
]),
};
A.defaultProps = {
children: null,
};
A.defaultProps = {
external: false,
name: 'link',
};
export default A;
|
anthonybishopric/p2 | Godeps/_workspace/src/github.com/hashicorp/go-reap/reap_stub.go | // +build windows solaris
package reap
// IsSupported returns true if child process reaping is supported on this
// platform. This Windows version always returns false.
func IsSupported() bool {
return false
}
// ReapChildren is not supported on Windows so this always returns right away.
func ReapChildren(pids PidCh, errors ErrorCh, done chan struct{}) {
}
|
cgu101/Voogasalad | src/data/XMLManager.java | package data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import authoring.model.game.Game;
import authoring.model.level.Level;
import engine.State;
import exceptions.data.GameFileException;
/**
* @author Austin, Sung
*/
public class XMLManager {
private static void saveFile (Object obj, String filePath) throws GameFileException {
XStream mySerializer = new XStream(new DomDriver());
FileOutputStream fos = null;
try{
String xml = mySerializer.toXML(obj);
fos = new FileOutputStream(filePath);
fos.write("<?xml version=\"1.0\"?>".getBytes("UTF-8"));
byte[] bytes = xml.getBytes("UTF-8");
fos.write(bytes);
}catch (Exception e){
e.printStackTrace();
System.err.println("Error in XML Write: " + e.getMessage());
}
finally{
if(fos != null){
try{
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static Object loadFile (String filePath) throws GameFileException {
XStream mySerializer = new XStream(new DomDriver());
FileInputStream fis = null;
try {
fis = new FileInputStream (filePath);
return mySerializer.fromXML(fis);
} catch (Exception e) {
e.printStackTrace();
} finally{
if(fis != null){
try{
fis.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
throw new GameFileException();
}
/**
* Saves a game to an absolute file location.
* @param game A {@link Game} containing a bundle of metadata properties and a bundle of levels.
* @param fileLocation
* @throws GameFileException
*/
public static void saveGame(Game game, String fileLocation) throws GameFileException {
// save to game.xml file
// filepath = "src/DESIGN/datafiles/game.xml";
saveFile(game, fileLocation);
}
/**
* Core method to test a game object based on its absolute file location
* TODO: Remove this method for final production
*
* @param game
* @param fileLocation
* @throws GameFileException
*/
public static void testSaveGame (Game obj, File file) throws GameFileException {
String filePath = file.getAbsolutePath();
XStream mySerializer = new XStream(new DomDriver());
FileOutputStream fos = null;
try{
String xml = mySerializer.toXML(obj);
fos = new FileOutputStream(filePath);
fos.write("<?xml version=\"1.0\"?>".getBytes("UTF-8"));
byte[] bytes = xml.getBytes("UTF-8");
fos.write(bytes);
}catch (Exception e){
System.err.println("Error in XML Write: " + e.getMessage());
}
finally{
if(fos != null){
try{
fos.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
throw new GameFileException();
}
/**
* Core method to test loading a game based on a file to return a Game object
* TODO: Eventually remove this method for production
*
* @param file
* @return Game Object
* @throws GameFileException
*/
public static Game testLoadGame (File file) throws GameFileException {
String fileLocation = file.getName();
try {
System.out.println(fileLocation);
return null;
} catch (Exception e) {
throw new GameFileException();
}
}
/**
* Loads a game from an absolute file path.
* @param fileLocation
* @return A {@link Game} to be loaded into the engine.
* @throws GameFileException
*/
public static Game loadGame(String fileLocation) throws GameFileException {
// load from game.xml
try {
return (Game) loadFile(fileLocation);
} catch (Exception e) {
throw new GameFileException();
}
}
/**
* Saves a single level to an absolute file location.
* @param level
* @param fileLocation
* @throws GameFileException
*/
public static void saveLevel(Level level, String fileLocation) throws GameFileException {
// TODO Auto-generated method stub
saveFile(level, fileLocation);
}
/**
* Loads a single level from an absolute file path.
* @param fileLocation
* @return
* @throws GameFileException
*/
public static Level loadLevel(String fileLocation) throws GameFileException {
// TODO Auto-generated method stub
try {
return (Level) loadFile(fileLocation);
} catch (Exception e) {
throw new GameFileException();
}
}
/**
* Saves a save state to an absolute file location.
* @param state
* @param filePath
* @throws GameFileException
*/
public static void saveState(State state, String filePath) throws GameFileException {
// TODO Auto-generated method stub
saveFile(state, filePath);
// saveFile(state, DEFAULT_SAVESTATE_FOLDER + filePath);
}
/**
* Loads a save state from an absolute file path.
* @param filePath
* @return
* @throws GameFileException
*/
public static State loadState(String filePath) throws GameFileException {
try {
return (State) loadFile(filePath);
// return (State) loadFile(DEFAULT_SAVESTATE_FOLDER + filePath);
} catch (Exception e) {
throw new GameFileException();
}
}
/**
* Loads a game from a file.
* @param file
* @return
* @throws GameFileException
*/
public static Game loadGame(File file) throws GameFileException {
return loadGame(file.getName());
}
/**
* Loads a single level from a file.
* @param file
* @return
* @throws GameFileException
*/
public static Level loadLevel(File file) throws GameFileException {
return loadLevel(file.getName());
}
/**
* Loads a savestate from a file.
* @param file
* @return
* @throws GameFileException
*/
public static State loadState(File file) throws GameFileException {
return loadState(file.getName());
}
}
|
HenryLong/Android_busybox | busybox-1.28.0/include/config/uniq.h | #define CONFIG_UNIQ 1
|
Grosskopf/openoffice | main/xmloff/source/text/XMLTextCharStyleNamesElementExport.cxx | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"
#include "XMLTextCharStyleNamesElementExport.hxx"
#include "xmloff/xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmlexp.hxx>
namespace com { namespace sun { namespace star {
namespace beans { class XPropertySet; }
} } }
using namespace ::com::sun::star::uno;
using ::com::sun::star::beans::XPropertySet;
using ::rtl::OUString;
using namespace ::xmloff::token;
XMLTextCharStyleNamesElementExport::XMLTextCharStyleNamesElementExport(
SvXMLExport& rExp,
sal_Bool bDoSth,
sal_Bool bAllStyles,
const Reference < XPropertySet > & rPropSet,
const OUString& rPropName ) :
rExport( rExp ),
nCount( 0 )
{
if( bDoSth )
{
Any aAny = rPropSet->getPropertyValue( rPropName );
Sequence < OUString > aNames;
if( aAny >>= aNames )
{
nCount = aNames.getLength();
OSL_ENSURE( nCount > 0, "no char style found" );
if ( bAllStyles ) ++nCount;
if( nCount > 1 )
{
aName = rExport.GetNamespaceMap().GetQNameByKey(
XML_NAMESPACE_TEXT, GetXMLToken(XML_SPAN) );
sal_Int32 i = nCount;
const OUString *pName = aNames.getConstArray();
while( --i )
{
rExport.AddAttribute( XML_NAMESPACE_TEXT, XML_STYLE_NAME,
rExport.EncodeStyleName( *pName ) );
rExport.StartElement( aName, sal_False );
++pName;
}
}
}
}
}
XMLTextCharStyleNamesElementExport::~XMLTextCharStyleNamesElementExport()
{
if( nCount > 1 )
{
sal_Int32 i = nCount;
while( --i )
rExport.EndElement( aName, sal_False );
}
}
|
remyagrv/ictak-website-mern | backend/src/controller/partnershipController.js | <gh_stars>0
const Partnership = require("../model/PartnershipInfo");
const sendEmail = require("../helpers/sendmail");
const convertJsonToExcel = require("../helpers/convertToExcel");
//Partnership reg. application posting
const postPartnershipAppl = (req, res) => {
try {
var item = {
fullname: req.body.fullname,
email: req.body.email,
phone: req.body.phone,
firm: req.body.firm,
address: req.body.address,
district: req.body.district,
officeSpace: req.body.officeSpace,
noOfEmployees: req.body.noOfEmployees,
briefReport: req.body.briefReport,
expects: req.body.expects,
promoters: req.body.promoters
}
if (item.fullname !== "" && item.email !== "" && item.phone !== "" && item.firm !== "" && item.noOfEmployees > 0) {
const partner = new Partnership(item);
partner.save()
.then(() => {
res.json({ status: "Success" });
sendEmail(item.email,
"ICTAK Partnership Application Confirmation",
"This email message is a computer generated message to confirm the receipt of your partnership application." +
"<br/><br/> Thanks & Regards, <br/> <b>ICT Academy of Kerala</b>"
);
})
.catch((er) => {
console.log(er);
if (!res.headersSent)
res.sendStatus(500).json({ status: "Error" });
});
} else {
res.json({ status: "Error", message: "Invalid inputs" });
}
} catch (error) {
if (!res.headersSent)
res.json({ status: "Error", message: error.message });
}
}
//Partnership reg. application to xlsx
const partnerAppl2Xlsx = async (req, res) => {
try {
let fromDate = new Date(req.query.fromDate);
let toDate = new Date(req.query.toDate);
toDate.setDate(toDate.getDate() + 1);
let filter = {
date: {
$gte: fromDate,
$lt: toDate
}
}
let projection = {
_id: 0,
"Full Name": "$fullname",
"Email ID": "$email",
"Phone": "$phone",
"Est Date": "$firm",
"Address": "$address",
"District": "$district",
"Office Space in Sq m": "$officeSpace",
"No of employees": "$noOfEmployees",
"Brief Report": "$briefReport",
"Expectation from partnership": "$expects",
"Promoter profile": "$promoters"
};
let partnerAppl = await Partnership.find(filter, projection);
if (partnerAppl.length > 0) {
convertJsonToExcel(partnerAppl, "Partnership Applications", res);
} else {
res.json({ status: "Error", message: "No records found" });
}
} catch (err) {
console.log(err);
if (!res.headersSent)
res.json({ status: "Error", message: err.message });
}
}
//View Partnership Applications in a date range
const viewPartnerAppl = async (req, res) => {
try {
let fromDate = new Date(req.query.fromDate);
let toDate = new Date(req.query.toDate);
toDate.setDate(toDate.getDate() + 1);
let filter = {
date: {
$gte: fromDate,
$lt: toDate
}
}
let projection = {
_id: 0,
"Full Name": "$fullname",
"Email ID": "$email",
"Phone": "$phone",
"Est Date": "$firm",
"Address": "$address",
"District": "$district",
"Office Space in Sq m": "$officeSpace",
"No of employees": "$noOfEmployees",
"Brief Report": "$briefReport",
"Expectation from partnership": "$expects",
"Promoter profile": "$promoters"
};
let partnerAppl = await Partnership.find(filter, projection);
if (partnerAppl.length > 0) {
res.json(partnerAppl);
} else {
res.json({ status: "Error", message: "No records found" });
}
} catch (err) {
console.log(err);
if (!res.headersSent)
res.json({ status: "Error", message: err.message });
}
}
module.exports = {
postPartnershipAppl,
partnerAppl2Xlsx,
viewPartnerAppl
} |
semisiu/hermes | hermes-common/src/main/java/pl/allegro/tech/hermes/common/di/factories/CuratorClientFactory.java | <filename>hermes-common/src/main/java/pl/allegro/tech/hermes/common/di/factories/CuratorClientFactory.java<gh_stars>0
package pl.allegro.tech.hermes.common.di.factories;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.allegro.tech.hermes.common.config.ConfigFactory;
import pl.allegro.tech.hermes.common.exception.InternalProcessingException;
import javax.inject.Inject;
import java.util.Optional;
import java.util.concurrent.ThreadFactory;
import static java.time.Duration.ofSeconds;
import static pl.allegro.tech.hermes.common.config.Configs.*;
public class CuratorClientFactory {
public static class ZookeeperAuthorization {
private final String scheme;
private final String user;
private final String password;
public ZookeeperAuthorization(String scheme, String user, String password) {
this.scheme = scheme;
this.user = user;
this.password = password;
}
byte[] getAuth() {
return String.join(":", user, password).getBytes();
}
}
private static final Logger logger = LoggerFactory.getLogger(CuratorClientFactory.class);
private final ConfigFactory configFactory;
@Inject
public CuratorClientFactory(ConfigFactory configFactory) {
this.configFactory = configFactory;
}
public CuratorFramework provide(String connectString) {
return provide(connectString, Optional.empty());
}
public CuratorFramework provide(String connectString, Optional<ZookeeperAuthorization> zookeeperAuthorization) {
int baseSleepTime = configFactory.getIntProperty(ZOOKEEPER_BASE_SLEEP_TIME);
int maxRetries = configFactory.getIntProperty(ZOOKEEPER_MAX_RETRIES);
int maxSleepTime = Ints.saturatedCast(ofSeconds(configFactory.getIntProperty(ZOOKEEPER_MAX_SLEEP_TIME_IN_SECONDS)).toMillis());
ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("hermes-curator-%d")
.setUncaughtExceptionHandler((t, e) ->
logger.error("Exception from curator with name {}", t.getName(), e)).build();
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.threadFactory(threadFactory)
.connectString(connectString)
.sessionTimeoutMs(configFactory.getIntProperty(ZOOKEEPER_SESSION_TIMEOUT))
.connectionTimeoutMs(configFactory.getIntProperty(ZOOKEEPER_CONNECTION_TIMEOUT))
.retryPolicy(new ExponentialBackoffRetry(baseSleepTime, maxRetries, maxSleepTime));
zookeeperAuthorization.ifPresent(it -> builder.authorization(it.scheme, it.getAuth()));
CuratorFramework curatorClient = builder.build();
startAndWaitForConnection(curatorClient);
return curatorClient;
}
private void startAndWaitForConnection(CuratorFramework curator) {
curator.start();
try {
curator.blockUntilConnected();
} catch (InterruptedException interruptedException) {
RuntimeException exception = new InternalProcessingException("Could not start Zookeeper Curator", interruptedException);
logger.error(exception.getMessage(), interruptedException);
throw exception;
}
}
}
|
qwqVictor/netfwd | utils/__init__.py | <reponame>qwqVictor/netfwd<gh_stars>0
from utils.parse_yaml import parse_yaml
from utils.get_free_port import get_free_port
from utils.punycode import punycode_encode |
miniatimat/TEG_JAVA | src/main/test/edu/fiuba/algo3/modelo/TestTurnoRefuerzo.java | package edu.fiuba.algo3.modelo;
import edu.fiuba.algo3.modelo.TurnoRefuerzo.TurnoRefuerzo;
import edu.fiuba.algo3.modelo.excepciones.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
import static edu.fiuba.algo3.modelo.Constantes.colorAmarillo;
import static edu.fiuba.algo3.modelo.Constantes.colorNegro;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestTurnoRefuerzo {
private TurnoRefuerzo turnoRefuerzo;
private Jugador jugador1;
private Jugador jugador2;
private Pais argentina;
private Pais uruguay;
private Pais chile;
private Pais brasil;
private Pais china;
private Pais rusia;
private Juego juego;
private ArrayList<String> tarjetasACanjear;
@BeforeEach
public void setUp() {
this.jugador1 = new Jugador(colorNegro, "Jugador 1");
this.jugador2 = new Jugador(colorAmarillo, "Jugador 2");
argentina = new Pais("Argentina");
argentina.asignarDuenio(jugador1);
uruguay = new Pais("Uruguay");
uruguay.asignarDuenio(jugador2);
chile = new Pais("Chile");
chile.asignarDuenio(jugador1);
brasil = new Pais("Brasil");
brasil.asignarDuenio(jugador1);
china = new Pais("China");
china.asignarDuenio(jugador2);
rusia = new Pais("Rusia");
rusia.asignarDuenio(jugador1);
argentina.hacerLimitrofe(uruguay);
uruguay.hacerLimitrofe(argentina);
argentina.hacerLimitrofe(chile);
chile.hacerLimitrofe(argentina);
argentina.hacerLimitrofe(brasil);
brasil.hacerLimitrofe(argentina);
this.juego = mock(Juego.class);
this.tarjetasACanjear = new ArrayList<>();
tarjetasACanjear.add("Argentina");
tarjetasACanjear.add("Uruguay");
tarjetasACanjear.add("Chile");
when(juego.canjearTarjetas(tarjetasACanjear, jugador1)).thenReturn(4);
turnoRefuerzo = new TurnoRefuerzo(jugador1, 5);
}
@Test
public void test01CreoUnTurnoDeRefuerzoYNoEsNull() {
assertNotNull(turnoRefuerzo);
}
@Test
public void test02CreoUnTurnoDeRefuerzoYNoPuedoReforzar () {
assertFalse(turnoRefuerzo.puedoReforzar());
}
@Test
public void test03CreoUnTurnoDeRefuerzoYIntentoReforzarYLanzaUnaExcepcion() {
assertThrows(PaisNoSeleccionadoException.class, () -> turnoRefuerzo.reforzar(3));
}
@Test
public void test04CreoUnTurnoDeRefuerzoYNoPuedoReagrupar() {
assertFalse(turnoRefuerzo.puedoReagrupar());
}
@Test
public void test05CreoUnTurnoDeRefuerzoYIntentoReagruparYLanzaUnaExcepcion() {
assertThrows(ReagrupeInvalidoException.class, () -> turnoRefuerzo.reagrupar(3));
}
@Test
public void test06CreoUnTurnoDeRefuerzoYNoPuedoAtacarSinSeleccionarAmbosPaises() {
assertFalse(turnoRefuerzo.puedoAtacar());
}
@Test
public void test07CreoUnTurnoDeRefuerzoYIntentoAtacarYLanzaUnaExcepcion() {
assertThrows(AtaqueInvalidoException.class, () -> turnoRefuerzo.atacar(3));
}
@Test
public void test08CreoUnTurnoDeRefuerzoYNoPuedoPasarDeTurno() {
assertFalse(turnoRefuerzo.puedoPasarDeTurno());
}
@Test
public void test09CreoUnTurnoDeRefuerzoYTengoLosEjercitosCorrectosParaReforzar() {
assertEquals(5, turnoRefuerzo.getEjercitosParaReforzar());
}
@Test
public void test09CreoUnTurnoDeRefuerzoYPuedoCanjearTarjetas() {
turnoRefuerzo.canjearTarjetas(tarjetasACanjear, juego);
assertEquals(9, turnoRefuerzo.getEjercitosParaReforzar());
}
@Test
public void test10CreoUnTurnoDeRefuerzoYNoPuedoCancelarAccion() {
assertFalse(turnoRefuerzo.puedoCancelar());
}
@Test
public void test11CreoUnTurnoDeRefuerzoYNoPuedoSeleccionarUnPaisAjeno() {
assertFalse(turnoRefuerzo.puedoSeleccionarPais(uruguay));
}
@Test
public void test12CreoUnTurnoDeRefuerzoYIntentoSeleccionarUnPaisAjenoYLanzaUnaExcepcion() {
assertThrows(SeleccionaPaisAjenoException.class, () -> turnoRefuerzo.seleccionarPais(uruguay));
}
@Test
public void test13CreoUnTurnoDeRefuerzoYPuedoSeleccionarUnPaisPropio() {
turnoRefuerzo.seleccionarPais(argentina);
}
}
|
WWWCourses/PythonCourseNetIT-Slides | pages/themes/DBMS-Lecture2/examples/mongo_CRUD.py | import pymongo
# ------------------------- Connect to MongoDB Server ------------------------ #
# connect to MongoDB server:
client = pymongo.MongoClient("mongodb://localhost:27017")
# ----------------------- Switch context to a database ----------------------- #
# get "python_course" database:
db = client.python_course
# ------------------- Show all Collections in the database: ------------------ #
# get all collections in the database:
collections = db.list_collection_names()
# print(collections)
# ---------------------------------- Create ---------------------------------- #
# insert a new document into "todos" collection:
res = db.todos.insert_one({"title": "Learn MongoDB", "done": False})
# get the id of the inserted document:
# print(res.inserted_id)
# insert multiple documents into "todos" collection:
res = db.todos.insert_many([
{"title": "Learn Python", "done": True},
{"title": "Learn Flask", "done": False},
{"title": "Learn Flask-MongoDB", "done": False}
])
# print(res.inserted_ids)
# insert multiple documents with different shape into "todos" collection:
res = db.todos.insert_many([
{"title": "Learn Python", "done": True},
{"title": "Learn Flask", "description":"Learn Flask to develop quick and easy web applications with the ability to scale up."},
{"title": "Learn MongoDB", "due": "2021-12-31"}
])
# print(list(db.todos.find())[-3:-1])
# ----------------------------------- Read ----------------------------------- #
# find first document in "todos" collection:
print(db.todos.find_one())
# find all documents in "todos" collection:
for todo in db.todos.find():
print(todo) |
ly1012/qa-edu-java-all | unittest-testng/src/test/java/com/liyun/qa/edu/testng/annotations/test/TestGroup.java | <gh_stars>0
package com.liyun.qa.edu.testng.annotations.test;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* @Test 注解 group 属性测试
*/
public class TestGroup {
@Test(groups = { "functest" })
public void testMethod3() {
System.err.println("groups = { functest }");
}
@Test(groups = { "functest", "checkintest" })
public void testMethod1() {
System.err.println("groups = { functest, checkintest }");
}
@Test(groups = { "functest", "checkintest" })
public void testMethod2() {
System.err.println("groups = { functest, checkintest }");
}
@Test(groups = { "checkintest" })
public void testMethod4() {
System.err.println("groups = { checkintest }");
}
}
|
Yurets2000/yurets2000.github.io | Lab7/eshop-app/src/main/java/com/yube/model/dto/Offering.java | package com.yube.model.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import java.util.List;
@Data
@ToString(exclude = {"products"}, callSuper = true)
@EqualsAndHashCode(exclude = {"products"}, callSuper = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class Offering extends ObjectBase {
private List<Product> products;
}
|
billionshang/gem5 | build/x86/python/m5/internal/NetworkLink_vector.py.cc | <filename>build/x86/python/m5/internal/NetworkLink_vector.py.cc
#include "sim/init.hh"
namespace {
const uint8_t data_m5_internal_NetworkLink_vector[] = {
120,156,205,92,125,104,36,103,25,127,102,246,35,183,123,201,
37,185,92,146,187,75,122,183,253,184,118,91,189,75,191,174,
31,182,92,173,215,90,90,245,106,39,149,107,211,234,116,178,
243,102,51,201,238,204,118,102,114,119,91,115,74,205,105,253,
68,197,15,84,68,68,240,15,5,17,4,65,16,4,65,16,
4,161,32,8,130,32,40,130,32,8,130,255,9,234,243,123,
102,102,119,54,217,149,94,247,146,201,37,251,220,155,217,119,
223,121,126,239,243,123,159,247,121,159,121,223,173,81,252,175,
192,175,119,87,136,130,43,26,145,205,191,26,53,136,154,26,
45,105,164,41,141,236,35,180,94,32,255,126,178,11,116,141,
104,73,39,165,211,22,23,114,244,146,78,238,168,124,166,72,
141,156,92,209,168,93,38,149,167,165,2,93,116,39,41,175,
138,180,94,38,255,21,210,52,205,213,232,5,123,132,236,3,
116,141,91,231,66,73,26,60,64,184,88,150,139,37,178,15,
202,197,50,217,163,82,56,72,237,9,82,163,180,52,134,106,
75,135,184,217,187,184,217,113,105,246,77,52,107,243,59,211,
100,31,66,117,214,235,69,212,204,163,166,220,111,92,90,153,
32,91,90,89,97,60,147,157,138,147,164,114,180,118,152,150,
14,147,226,223,73,218,98,200,49,156,41,90,58,146,64,155,
78,149,103,82,229,217,84,249,104,170,124,76,202,135,147,27,
78,117,110,120,92,110,56,71,75,115,164,248,247,120,116,195,
34,45,86,103,216,10,206,127,249,95,149,173,64,225,40,139,
75,202,15,28,207,53,29,119,197,115,116,188,95,132,128,205,
106,16,35,177,241,206,195,120,63,32,177,156,173,199,198,187,
74,220,176,6,133,26,58,93,149,194,85,157,218,85,218,212,
104,45,79,118,142,54,249,54,5,40,80,215,104,75,167,151,
115,168,112,149,101,158,187,248,4,229,195,200,114,107,210,197,
81,75,35,116,181,64,155,5,90,124,97,83,199,133,245,18,
249,223,167,215,230,165,209,3,210,168,78,155,44,243,180,149,
167,171,69,186,200,149,248,210,90,9,240,181,23,54,25,41,
95,89,172,230,89,219,11,41,184,128,98,59,190,107,53,85,
56,197,101,243,130,10,47,123,254,250,251,29,119,221,188,164,
106,161,231,87,203,73,69,47,56,211,178,194,85,67,62,153,
67,151,52,91,161,180,232,185,42,60,200,133,21,199,181,205,
166,103,111,52,84,120,0,205,153,43,78,67,153,166,188,249,
116,179,229,249,225,147,190,239,249,6,122,85,46,54,60,171,
243,9,244,105,173,225,5,170,138,187,201,109,12,52,31,162,
246,74,75,90,132,2,162,45,62,108,171,160,230,59,173,144,
141,21,181,136,218,104,173,10,51,137,8,150,89,44,52,221,
112,97,181,190,18,44,44,174,90,190,90,92,85,238,66,93,
53,207,158,246,124,167,238,184,167,131,208,90,110,168,211,247,
222,125,207,217,211,15,159,190,111,97,121,195,105,216,11,87,
30,122,96,161,213,14,87,61,119,161,121,118,193,113,67,197,
253,212,88,216,217,67,103,184,214,97,220,235,178,83,55,29,
65,105,174,170,70,75,249,99,184,122,28,122,104,19,218,168,
86,212,114,90,85,27,227,82,129,95,57,109,94,63,168,93,
112,128,179,6,236,96,89,62,205,43,24,91,163,117,157,252,
121,176,102,141,127,53,152,153,185,179,136,247,116,121,239,57,
116,80,116,117,45,7,46,68,23,55,133,105,76,57,174,249,
40,140,239,146,208,165,64,107,69,138,104,196,236,139,120,229,
183,33,185,58,154,209,185,241,60,5,95,35,238,112,38,208,
38,197,228,218,202,145,230,78,80,88,198,40,231,171,51,124,
195,79,8,63,23,171,80,255,130,144,36,92,117,2,239,178,
43,166,64,89,70,212,34,247,204,7,219,207,46,175,113,127,
5,39,249,194,139,222,70,165,102,185,174,23,86,44,219,174,
88,97,232,59,203,27,161,10,42,161,87,57,21,84,97,93,
99,50,225,89,167,189,118,43,225,21,56,192,188,138,254,176,
157,90,200,127,8,129,77,177,66,160,66,230,200,170,103,7,
124,29,77,212,85,104,64,201,16,157,236,137,34,66,33,19,
85,113,123,174,119,136,255,126,60,209,68,120,90,45,38,172,
10,84,99,37,44,11,65,173,32,48,69,19,92,23,46,162,
225,75,86,99,67,73,235,204,166,144,21,66,49,210,97,239,
217,120,20,200,146,142,16,116,174,231,218,109,86,214,169,221,
1,61,142,10,39,71,133,149,211,204,200,17,150,69,254,191,
168,205,232,181,124,204,195,98,194,69,248,200,144,132,9,90,
76,6,230,229,22,251,163,170,46,14,69,0,202,120,189,5,
37,124,216,152,135,184,9,226,4,196,201,164,15,246,180,35,
198,182,119,196,131,184,185,46,232,5,39,76,151,75,112,218,
61,99,238,88,119,204,177,19,93,196,216,209,49,194,186,99,
39,15,135,235,159,131,228,170,50,42,115,20,60,15,247,142,
49,38,141,97,56,241,192,64,169,59,92,164,215,140,9,244,
198,129,132,233,6,232,155,230,112,61,197,97,3,6,19,2,
27,199,18,215,105,162,70,68,93,99,14,77,21,250,116,123,
5,226,230,76,250,190,75,194,250,14,18,62,2,61,38,98,
18,142,9,249,202,252,154,208,107,185,216,32,157,9,118,106,
27,249,192,188,124,31,230,221,142,82,110,103,23,100,73,186,
24,248,123,83,164,131,174,122,26,223,5,46,180,103,1,43,
77,183,89,14,29,46,186,179,28,13,232,18,13,220,45,209,
128,68,20,18,93,69,206,61,39,254,61,42,20,208,63,43,
57,154,137,103,249,160,196,178,229,123,87,218,21,111,165,18,
74,7,192,23,63,122,42,56,115,42,120,132,189,108,229,156,
248,183,200,207,70,158,212,87,45,120,66,124,244,201,43,53,
37,83,171,252,101,154,145,227,51,197,9,154,241,148,205,204,
155,70,239,234,73,183,203,20,16,132,62,60,255,222,119,124,
185,211,241,192,241,12,238,92,150,94,207,105,179,204,178,178,
38,234,153,145,251,151,80,78,222,229,215,123,96,9,116,129,
34,132,223,198,98,164,188,224,2,66,227,157,61,76,218,75,
84,198,2,223,230,67,9,131,138,93,6,225,149,75,70,200,
27,36,17,175,70,159,34,112,132,169,16,143,144,206,128,2,
41,166,80,253,35,36,67,169,79,100,33,62,106,17,209,132,
212,96,215,21,60,40,85,163,64,227,25,250,116,106,28,38,
225,64,46,142,105,211,225,64,190,227,223,132,92,111,105,202,
207,247,58,66,88,106,213,10,80,45,242,110,221,161,221,157,
79,58,145,40,123,247,61,101,218,129,232,158,38,212,123,185,
203,51,76,168,115,218,148,158,98,207,61,16,247,118,136,163,
37,215,246,74,211,147,52,56,20,48,163,249,229,37,168,147,
23,0,227,35,18,5,69,241,218,211,220,176,197,205,116,70,
74,33,25,41,127,233,140,20,37,147,225,53,89,3,65,234,
96,195,150,174,241,146,148,163,68,172,0,243,164,10,180,84,
36,53,130,165,10,22,154,133,100,161,89,140,23,154,221,181,
233,168,148,75,82,30,147,181,41,97,65,25,175,77,199,147,
181,41,175,42,199,164,48,25,47,63,121,33,25,47,56,167,
176,224,68,225,72,188,224,92,154,198,138,16,133,153,120,69,
184,52,139,181,53,10,71,177,128,69,225,24,217,51,82,56,
78,246,172,20,230,224,4,48,133,201,120,75,94,226,177,225,
223,123,66,3,177,234,133,200,222,29,6,71,228,132,184,178,
247,158,16,252,124,180,97,53,151,109,235,92,29,247,197,205,
107,137,215,208,19,36,19,105,36,24,241,218,32,48,242,231,
217,4,209,165,189,247,130,15,240,109,58,72,100,204,219,94,
77,92,223,243,171,170,210,84,205,101,94,181,175,58,173,202,
74,195,170,139,205,114,49,210,103,19,164,161,176,116,123,24,
22,220,5,233,85,106,158,203,19,215,6,238,87,177,21,175,
100,149,93,57,93,145,89,175,226,4,21,107,153,223,181,106,
97,52,130,123,61,146,172,4,44,191,30,72,208,191,126,25,
197,108,108,110,154,142,235,240,90,200,161,222,136,163,135,191,
208,214,238,210,86,0,21,58,206,105,158,178,152,228,96,222,
102,135,168,137,186,29,162,142,69,230,91,211,146,64,59,205,
82,89,250,31,217,225,182,76,89,146,101,9,10,190,215,235,
90,34,90,233,119,166,238,244,32,236,96,139,166,221,157,240,
166,118,194,115,220,154,159,138,188,240,9,119,239,89,7,50,
65,19,63,197,184,27,6,209,86,105,136,198,185,44,172,40,
8,161,200,198,208,8,103,251,32,116,88,67,183,166,82,40,
207,102,130,18,222,35,81,230,202,208,72,251,140,70,245,234,
134,213,200,28,38,252,156,104,242,209,62,30,242,58,220,77,
31,178,214,188,86,59,67,111,35,60,133,14,31,187,225,200,
92,117,37,204,26,25,116,120,125,56,100,125,134,159,41,216,
76,51,75,116,113,66,83,244,184,118,195,17,182,124,117,201,
241,54,130,172,17,38,122,188,49,180,111,153,217,9,210,178,
47,109,115,162,217,76,21,88,180,198,186,124,118,104,156,211,
253,232,170,94,101,178,102,237,68,139,194,88,168,242,133,221,
65,233,170,125,131,18,170,124,105,104,148,125,93,143,99,217,
118,15,206,108,72,27,175,27,68,153,175,236,18,210,96,99,
121,255,32,21,101,190,190,27,126,200,52,247,135,73,37,205,
25,233,242,77,162,29,185,103,224,124,170,31,206,207,247,155,
84,250,226,220,110,208,135,51,196,41,186,124,155,118,206,156,
61,43,222,205,238,138,87,244,204,124,198,119,184,142,105,126,
167,171,119,85,122,178,147,110,150,76,92,148,186,107,249,94,
75,249,97,59,74,169,226,225,137,113,6,226,206,30,55,106,
171,134,10,149,217,107,171,112,130,58,79,148,108,21,132,190,
215,54,205,184,227,248,3,166,41,171,84,227,49,136,199,33,
206,67,60,9,241,20,196,211,16,239,131,248,0,196,179,16,
207,65,44,66,32,47,109,92,132,120,17,2,153,68,227,229,
158,62,221,211,5,247,253,124,155,21,220,15,253,87,212,230,
244,146,94,212,74,90,73,47,229,70,249,167,52,232,71,151,
231,247,81,59,233,45,16,59,51,159,182,246,22,50,159,209,
54,156,56,255,89,76,18,158,35,73,194,83,246,221,160,80,
146,180,103,148,11,45,37,185,208,40,231,57,154,228,60,199,
146,156,231,161,36,231,57,158,228,60,39,146,156,231,100,146,
243,60,156,228,60,167,146,156,231,145,36,231,57,157,228,60,
103,146,156,231,108,146,243,60,154,228,60,143,145,125,52,201,
130,30,139,179,160,246,113,41,204,147,61,39,133,155,200,158,
151,194,9,178,111,146,194,73,178,79,72,161,66,246,73,41,
220,76,118,69,10,183,144,125,179,20,110,37,251,22,41,220,
70,246,173,82,56,69,246,109,82,184,157,212,29,180,86,165,
165,59,201,62,37,87,238,66,234,21,143,243,134,74,189,102,
19,53,72,34,235,135,116,35,51,174,198,131,217,3,49,30,
162,248,65,211,160,108,235,117,174,84,230,250,142,55,241,137,
240,90,89,123,231,68,143,31,209,255,153,85,202,29,91,110,
109,203,166,214,40,211,9,70,92,240,143,251,168,126,29,6,
58,209,223,64,38,30,31,189,166,124,47,219,53,115,180,255,
161,163,202,79,134,195,58,128,140,166,185,236,121,141,253,144,
28,136,244,248,233,112,40,143,15,66,217,80,110,182,32,163,
104,68,212,248,89,10,99,250,201,181,96,156,162,222,112,53,
122,10,189,19,233,201,65,72,235,42,12,26,78,13,171,203,
238,195,27,77,198,59,228,218,222,67,31,165,120,35,79,172,
215,207,183,217,248,250,195,245,129,224,131,46,248,172,227,246,
8,117,87,161,95,236,170,213,57,204,221,97,117,99,29,162,
145,33,250,174,86,191,28,218,230,3,157,53,223,132,167,178,
230,62,48,249,193,4,116,164,207,175,118,15,51,15,166,125,
133,185,163,207,175,119,15,115,176,207,48,119,244,249,13,13,
53,103,205,244,7,220,242,90,89,206,87,48,26,171,240,219,
20,182,183,151,66,58,214,31,158,213,106,41,215,222,23,9,
208,72,149,55,135,179,226,209,254,48,85,179,21,102,250,196,
76,30,6,66,137,223,13,135,111,182,63,190,192,121,45,203,
237,7,209,190,117,214,225,247,67,243,116,16,192,203,86,43,
197,210,76,214,169,17,74,86,228,15,187,194,209,101,197,106,
102,205,81,81,226,143,187,226,73,225,103,50,246,164,172,194,
159,134,195,54,192,141,250,153,27,15,30,52,210,226,207,187,
226,97,252,140,205,135,177,7,29,254,186,43,99,175,214,80,
86,166,153,160,232,64,26,43,241,183,225,240,85,250,227,171,
99,3,113,163,225,213,178,206,120,1,65,143,50,127,31,14,
239,128,124,10,135,76,230,178,85,91,207,58,159,146,232,241,
143,109,40,175,63,30,31,20,216,248,86,160,50,143,196,37,
186,129,38,255,220,134,51,57,94,35,56,159,232,226,100,144,
209,97,213,35,146,214,76,14,59,225,168,236,69,247,56,229,
121,184,227,40,202,99,56,138,178,41,135,4,76,61,58,141,
210,77,127,22,40,61,225,184,234,178,185,179,127,162,36,55,
54,96,25,216,123,155,90,148,163,163,228,221,189,79,153,226,
161,218,191,136,146,157,252,227,90,78,59,162,141,189,221,128,
105,126,192,8,216,8,86,163,33,144,117,108,47,135,131,18,
109,254,189,43,238,123,197,247,220,76,183,141,129,139,162,196,
127,134,195,55,96,242,205,218,149,97,242,133,14,154,118,3,
146,103,131,86,162,65,224,212,221,212,8,61,151,29,101,101,
57,42,250,228,181,97,29,247,160,136,81,201,154,45,107,207,
45,97,163,168,50,178,91,72,29,55,80,126,184,47,144,70,
170,148,83,72,223,158,207,29,240,124,131,59,82,249,151,246,
199,222,192,88,151,49,109,55,194,171,154,213,178,106,78,182,
25,21,132,87,137,30,19,125,80,246,236,200,217,143,103,80,
166,180,248,137,119,245,29,148,222,140,99,124,24,66,182,223,
116,119,222,224,49,175,60,107,53,20,4,142,39,25,56,121,
99,224,36,139,129,147,31,198,171,16,104,208,192,241,1,227,
50,68,155,146,240,231,42,196,199,33,94,135,216,130,248,36,
4,118,201,26,159,129,248,28,4,182,89,26,95,132,248,50,
132,108,0,250,42,4,118,177,25,223,128,248,22,4,54,65,
25,216,81,100,124,23,226,123,61,94,32,222,30,212,39,30,
51,81,239,149,158,62,223,211,142,183,248,54,248,190,139,0,
71,118,139,218,156,86,212,177,101,231,186,126,70,182,111,233,
41,105,50,109,109,251,2,151,8,156,60,247,147,115,163,237,
192,192,21,99,188,211,85,209,102,229,120,191,21,172,46,177,
210,5,171,25,125,37,132,124,195,129,113,43,4,182,168,24,
119,116,40,129,62,150,195,186,209,129,105,142,125,229,240,152,
156,21,51,238,131,184,63,25,189,219,182,211,97,115,150,175,
234,78,192,23,66,28,92,111,158,61,147,116,217,153,150,229,
91,205,180,185,228,235,80,154,103,229,121,215,206,138,231,121,
9,183,174,236,232,187,54,6,52,38,117,158,240,154,22,95,
159,235,91,99,209,105,198,45,76,110,123,223,246,241,169,233,
109,87,217,173,57,86,131,39,44,177,229,160,71,113,105,156,
217,80,45,58,24,25,29,94,63,135,71,21,178,254,193,183,
96,148,198,75,76,59,124,43,75,78,43,115,224,159,207,141,
78,148,242,163,7,75,249,210,72,78,190,158,96,76,155,210,
203,249,210,193,153,119,149,180,50,215,236,254,204,172,151,180,
255,1,153,198,47,57,
};
EmbeddedPython embedded_m5_internal_NetworkLink_vector(
"m5/internal/NetworkLink_vector.py",
"/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/build/x86/python/m5/internal/NetworkLink_vector.py",
"m5.internal.NetworkLink_vector",
data_m5_internal_NetworkLink_vector,
3542,
18903);
} // anonymous namespace
|
navikt/fas | src/main/java/no/nav/aura/envconfig/util/Consumer.java | package no.nav.aura.envconfig.util;
@SuppressWarnings("serial")
public abstract class Consumer<T> extends SerializableFunction<T, Void> {
public abstract void perform(T t);
public final Void process(T t) {
perform(t);
return null;
}
}
|
jnthn/intellij-community | python/testData/refactoring/pullup/abstractMethodPy3AddMeta/SuperClass.after.py | from abc import object, ABCMeta, abstractmethod
class Parent(object, metaclass=ABCMeta):
@abstractmethod
def my_method(self, foo):
"""
Eats eggs
:param foo: eggs
"""
pass
@classmethod
@abstractmethod
def my_class_method():
pass |
zealoussnow/chromium | chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/mock_signals_decorator.h | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_SIGNALS_DECORATORS_COMMON_MOCK_SIGNALS_DECORATOR_H_
#define CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_SIGNALS_DECORATORS_COMMON_MOCK_SIGNALS_DECORATOR_H_
#include "chrome/browser/enterprise/connectors/device_trust/signals/decorators/common/signals_decorator.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace enterprise_connectors {
namespace test {
class MockSignalsDecorator : public SignalsDecorator {
public:
MockSignalsDecorator();
~MockSignalsDecorator() override;
MOCK_METHOD(void, Decorate, (SignalsType&, base::OnceClosure), (override));
};
} // namespace test
} // namespace enterprise_connectors
#endif // CHROME_BROWSER_ENTERPRISE_CONNECTORS_DEVICE_TRUST_SIGNALS_DECORATORS_COMMON_MOCK_SIGNALS_DECORATOR_H_
|
sjzeil/AlgAE | algae-client-server/src/main/java/edu/odu/cs/AlgAE/Client/DataViewer/DataCanvas.java | <reponame>sjzeil/AlgAE
package edu.odu.cs.AlgAE.Client.DataViewer;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.LinkedList;
import javax.swing.JPanel;
import edu.odu.cs.AlgAE.Client.DataViewer.Frames.Box;
import edu.odu.cs.AlgAE.Client.DataViewer.Frames.DataShape;
import edu.odu.cs.AlgAE.Client.DataViewer.Frames.Frame;
import edu.odu.cs.AlgAE.Client.SourceViewer.SourceViewer;
public class DataCanvas extends JPanel
{
//private static Logger logger = Logger.getLogger(DataCanvas.class.getName());
private static Font BasicFont = null;
private static float fontScale = 12.0f;
private float zoom;
private static float xyScalingfactor;
private Frame currentPicture;
private Dimension size;
private boolean painted;
private SourceViewer sourceCode;
// Data members for portrayal of dragged boxes
private Box movingBox;
private Rectangle2D lastBoxMove;
private Point2D movingBoxOffset;
private ShapeMover shapeMover;
private boolean movingEnabled;
public DataCanvas(SourceViewer source, ShapeMover mover)
{
sourceCode = source;
zoom = 100.0f;
xyScalingfactor = 1.0f;
currentPicture = null;
size = new Dimension(50,50);
setBackground (Color.white);
setPainted(false);
movingBox = null;
lastBoxMove = null;
movingBoxOffset = null;
shapeMover = mover;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (movingEnabled)
selectBox (e);
}
@Override
public void mouseReleased(MouseEvent e) {
if (movingEnabled)
releaseBox(e);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (movingEnabled)
dragBox(e);
}
});
}
/**
* @param movingEnabled the movingEnabled to set
*/
public void setMovingEnabled(boolean movingEnabled) {
this.movingEnabled = movingEnabled;
}
/**
* @return the movingEnabled
*/
public boolean isMovingEnabled() {
return movingEnabled;
}
public synchronized void setPicture (Frame newPicture)
{
currentPicture = newPicture;
if (newPicture.getLocation() != null)
sourceCode.display(newPicture.getLocation());
setPainted(false);
sizeCheck();
}
@Override
public void paintComponent (Graphics g)
{
super.paintComponent(g);
paintCurrent (g);
}
private void paintCurrent (Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
if (BasicFont == null) {
BasicFont = new Font(Font.MONOSPACED, Font.BOLD, (int)fontScale);
}
g2d.setFont(BasicFont);
g2d.setPaintMode();
FontMetrics metrics = g2d.getFontMetrics(BasicFont);
int hgt = metrics.getHeight();
fontScale = (float)hgt;
int wd = metrics.stringWidth("MWX");
xyScalingfactor = (((float)wd) / 3.0f) /hgt;
g2d.setStroke(new BasicStroke(0.0f));
Frame toBeDrawn = null;
synchronized (this) {
toBeDrawn = currentPicture;
}
if (toBeDrawn != null) {
float scale = fontScale * zoom / 100.0f;
g2d.scale (scale*xyScalingfactor, scale);
ArrayList<LinkedList<DataShape> > byDepth = new ArrayList<LinkedList<DataShape>>();
for (DataShape shape: toBeDrawn) {
int d = shape.getDepth();
while (byDepth.size() <= d) {
byDepth.add(new LinkedList<DataShape>());
}
byDepth.get(d).addLast(shape);
}
for (int d = byDepth.size()-1; d >= 0; --d) {
for (DataShape shape: byDepth.get(d)) {
shape.draw (g2d);
}
}
}
// Draw box being dragged
if (lastBoxMove != null) {
g2d.setColor (new Color(0.5f, 0.5f, 0.5f, 0.5f));
g2d.fill(lastBoxMove);
}
setPainted(true);
}
private synchronized void sizeCheck()
{
Rectangle2D bbox = null;
if (currentPicture != null) {
for (DataShape shape: currentPicture) {
if (bbox == null) {
bbox = shape.getBounds2D();
} else {
Rectangle2D.union(bbox, shape.getBounds2D(), bbox);
}
}
}
if (bbox == null) {
bbox = new Rectangle2D.Double(0.0, 0.0, 50.0, 50.0);
}
int w = (int)(0.99 + fontScale*(bbox.getX() + bbox.getWidth())* zoom/100.0f);
int h = (int)(0.99 + fontScale*(bbox.getY() + bbox.getHeight()) * zoom/100.0f);
if (w != size.width || h != size.height) {
setPreferredSize (new Dimension(w, h));
revalidate();
}
}
private void setPainted(boolean painted) {
this.painted = painted;
}
public boolean isPainted() {
return painted;
}
public static float getYFontScale() {
return fontScale;
}
public static float getXFontScale() {
return fontScale * xyScalingfactor;
}
public void setZoom(float zoomValue) {
zoom = zoomValue;
sizeCheck();
}
private void selectBox(MouseEvent e) {
//System.out.println (e.getX() + " " + e.getY());
Box selected = null;
double x = e.getX() / getXFontScale() / (zoom/100.0);
double y = e.getY() / getYFontScale() / (zoom/100.0);
for (DataShape s: currentPicture) {
if (s instanceof Box){
Box b = (Box)s;
Point2D p = new Point2D.Double(x,y);
if (b.getBounds().contains(p)) {
//System.out.println (b.getID() + " at " + b.getBounds());
if (selected == null ||
b.getBounds().getWidth() * b.getBounds().getHeight()
> selected.getBounds().getWidth() * selected.getBounds().getHeight()) {
selected = b;
}
}
}
}
if (selected != null) {
movingBox = selected;
lastBoxMove = selected.getBounds();
movingBoxOffset = new Point2D.Double(selected.getBounds().getX()-x, selected.getBounds().getY()-y);
}
repaint();
}
public void dragBox(MouseEvent e) {
if (movingBox != null) {
double x = e.getX() / getXFontScale() / (zoom/100.0);
double y = e.getY() / getYFontScale() / (zoom/100.0);
x += movingBoxOffset.getX();
y += movingBoxOffset.getY();
lastBoxMove = new Rectangle2D.Double (x, y, lastBoxMove.getWidth(), lastBoxMove.getHeight());
repaint();
}
}
public void releaseBox(MouseEvent e) {
if (movingBox != null) {
double x = e.getX() / getXFontScale() / (zoom/100.0);
double y = e.getY() / getYFontScale() / (zoom/100.0);
x += movingBoxOffset.getX();
y += movingBoxOffset.getY();
shapeMover.moved (movingBox.getID(), x, y);
currentPicture.add (new Box(movingBox.getID(), (float)x, (float)y,
(float)movingBox.getBounds().getWidth(), (float)movingBox.getBounds().getHeight(),
movingBox.getColor(), movingBox.getDepth()));
movingBox = null;
lastBoxMove = null;
repaint();
}
}
}
|
LewJun/histruts1 | src/test/java/PermissionServiceTest.java | <filename>src/test/java/PermissionServiceTest.java
import com.microandroid.modules.sys.dto.Permission;
import com.microandroid.modules.sys.service.IPermissionService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
public class PermissionServiceTest extends SpringJunitTest {
@Autowired
private IPermissionService permissionService;
@Test
public void testSelectRolesByUsername() {
List<Permission> permissions = permissionService.selectPermissionsByUsername("z3");
LOGGER.info("permissions:{}", permissions);
}
@Test
public void testSelectByIdAndUsername() {
Permission permission = permissionService.selectByIdAndUsername(5, "z3");
LOGGER.info("permission:{}", permission);
}
}
|
ptahchiev/thymeleaf-spring | thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/processor/AbstractSpringFieldTagProcessor.java | <filename>thymeleaf-spring4/src/main/java/org/thymeleaf/spring4/processor/AbstractSpringFieldTagProcessor.java
/*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.
*
* =============================================================================
*/
package org.thymeleaf.spring4.processor;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.BindStatus;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeDefinition;
import org.thymeleaf.engine.AttributeDefinitions;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.engine.IAttributeDefinitionsAware;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.spring4.naming.SpringContextVariableNames;
import org.thymeleaf.spring4.util.FieldUtils;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.util.Validate;
/**
* Binds an input property with the value in the form's backing bean.
* <p>
* Values for <tt>th:field</tt> attributes must be selection expressions
* <tt>(*{...})</tt>, as they will be evaluated on the form backing bean and not
* on the context variables (model attributes in Spring MVC jargon).
*
* @author <NAME>
* @since 3.0.0
*/
public abstract class AbstractSpringFieldTagProcessor
extends AbstractAttributeTagProcessor
implements IAttributeDefinitionsAware {
public static final int ATTR_PRECEDENCE = 1700;
public static final String ATTR_NAME = "field";
private static final TemplateMode TEMPLATE_MODE = TemplateMode.HTML;
protected static final String INPUT_TAG_NAME = "input";
protected static final String SELECT_TAG_NAME = "select";
protected static final String OPTION_TAG_NAME = "option";
protected static final String TEXTAREA_TAG_NAME = "textarea";
protected static final String ID_ATTR_NAME = "id";
protected static final String TYPE_ATTR_NAME = "type";
protected static final String NAME_ATTR_NAME = "name";
protected static final String VALUE_ATTR_NAME = "value";
protected static final String CHECKED_ATTR_NAME = "checked";
protected static final String SELECTED_ATTR_NAME = "selected";
protected static final String DISABLED_ATTR_NAME = "disabled";
protected static final String MULTIPLE_ATTR_NAME = "multiple";
private AttributeDefinition discriminatorAttributeDefinition;
protected AttributeDefinition idAttributeDefinition;
protected AttributeDefinition typeAttributeDefinition;
protected AttributeDefinition nameAttributeDefinition;
protected AttributeDefinition valueAttributeDefinition;
protected AttributeDefinition checkedAttributeDefinition;
protected AttributeDefinition selectedAttributeDefinition;
protected AttributeDefinition disabledAttributeDefinition;
protected AttributeDefinition multipleAttributeDefinition;
private final String discriminatorAttrName;
private final String[] discriminatorAttrValues;
private final boolean removeAttribute;
public AbstractSpringFieldTagProcessor(
final String dialectPrefix, final String elementName,
final String discriminatorAttrName, final String[] discriminatorAttrValues,
final boolean removeAttribute) {
super(TEMPLATE_MODE, dialectPrefix, elementName, false, ATTR_NAME, true, ATTR_PRECEDENCE, false);
this.discriminatorAttrName = discriminatorAttrName;
this.discriminatorAttrValues = discriminatorAttrValues;
this.removeAttribute = removeAttribute;
}
public void setAttributeDefinitions(final AttributeDefinitions attributeDefinitions) {
Validate.notNull(attributeDefinitions, "Attribute Definitions cannot be null");
// We precompute the AttributeDefinitions in order to being able to use much
// faster methods for setting/replacing attributes on the ElementAttributes implementation
this.discriminatorAttributeDefinition =
(this.discriminatorAttrName != null? attributeDefinitions.forName(TEMPLATE_MODE, this.discriminatorAttrName) : null);
this.idAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, ID_ATTR_NAME);
this.typeAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, TYPE_ATTR_NAME);
this.nameAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, NAME_ATTR_NAME);
this.valueAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, VALUE_ATTR_NAME);
this.checkedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, CHECKED_ATTR_NAME);
this.selectedAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, SELECTED_ATTR_NAME);
this.disabledAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, DISABLED_ATTR_NAME);
this.multipleAttributeDefinition = attributeDefinitions.forName(TEMPLATE_MODE, MULTIPLE_ATTR_NAME);
}
private boolean matchesDiscriminator(final IProcessableElementTag tag) {
if (this.discriminatorAttrName == null) {
return true;
}
final boolean hasDiscriminatorAttr = tag.hasAttribute(this.discriminatorAttributeDefinition.getAttributeName());
if (this.discriminatorAttrValues == null || this.discriminatorAttrValues.length == 0) {
return hasDiscriminatorAttr;
}
final String discriminatorTagValue =
(hasDiscriminatorAttr? tag.getAttributeValue(this.discriminatorAttributeDefinition.getAttributeName()) : null);
for (int i = 0; i < this.discriminatorAttrValues.length; i++) {
final String discriminatorAttrValue = this.discriminatorAttrValues[i];
if (discriminatorAttrValue == null) {
if (!hasDiscriminatorAttr || discriminatorTagValue == null) {
return true;
}
} else if (discriminatorAttrValue.equals(discriminatorTagValue)) {
return true;
}
}
return false;
}
@Override
protected void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName, final String attributeValue,
final IElementTagStructureHandler structureHandler) {
/*
* First thing to check is whether this processor really matches, because so far we have asked the engine only
* to match per attribute (th:field) and host tag (input, select, option...) but we still don't know if the
* match is complete because we might still need to assess for example that the 'type' attribute has the
* correct value. For example, the same processor will not be executing on <input type="text" th:field="*{a}"/>
* and on <input type="checkbox" th:field="*{a}"/>
*/
if (!matchesDiscriminator(tag)) {
// Note in this case we do not have to remove the th:field attribute because the correct processor is still
// to be executed!
return;
}
if (this.removeAttribute) {
structureHandler.removeAttribute(attributeName);
}
final BindStatus bindStatus = FieldUtils.getBindStatus(context, attributeValue);
// We set the BindStatus into a local variable just in case we have more BindStatus-related processors to
// be applied for the same tag, like for example a th:errorclass
structureHandler.setLocalVariable(SpringContextVariableNames.SPRING_FIELD_BIND_STATUS, bindStatus);
doProcess(context, tag, attributeName, attributeValue, bindStatus, structureHandler);
}
protected abstract void doProcess(
final ITemplateContext context,
final IProcessableElementTag tag,
final AttributeName attributeName,
final String attributeValue,
final BindStatus bindStatus,
final IElementTagStructureHandler structureHandler);
// This method is designed to be called from the diverse subclasses
protected final String computeId(
final ITemplateContext context,
final IProcessableElementTag tag,
final String name, final boolean sequence) {
String id = tag.getAttributeValue(this.idAttributeDefinition.getAttributeName());
if (!org.thymeleaf.util.StringUtils.isEmptyOrWhitespace(id)) {
return (StringUtils.hasText(id) ? id : null);
}
id = FieldUtils.idFromName(name);
if (sequence) {
final Integer count = context.getIdentifierSequences().getAndIncrementIDSeq(id);
return id + count.toString();
}
return id;
}
}
|
B2M-Software/SMG2.0 | webrest.test/src/test/java/org/fortiss/smg/webrest/test/TestNonce.java | <reponame>B2M-Software/SMG2.0
package org.fortiss.smg.webrest.test;
import java.util.Date;
import org.fortiss.smg.webrest.impl.Constants;
import org.fortiss.smg.webrest.impl.LoginFilter;
import org.junit.Assert;
import org.junit.Test;
public class TestNonce {
@Test
public void checkNonces() {
long current_timestamp = new Date().getTime();
long current_timestamp_fail = new Date().getTime()
+ Constants.MAX_TIMESTAMP_DIFFERENCE + 100;
long before = System.nanoTime();
int tests = 300;
for (int i = 0; i < tests; i++) {
// first request
Assert.assertTrue(LoginFilter.checkNonce("abc" + i, "123",
current_timestamp));
Assert.assertFalse(LoginFilter.checkNonce("abc" + i, "123",
current_timestamp));
// another user
Assert.assertTrue(LoginFilter.checkNonce("abcd" + i, "123",
current_timestamp));
Assert.assertFalse(LoginFilter.checkNonce("abcd" + i, "123",
current_timestamp));
// another request
Assert.assertTrue(LoginFilter.checkNonce("abc" + i, "1234",
current_timestamp));
Assert.assertFalse(LoginFilter.checkNonce("abc" + i, "1234",
current_timestamp));
// Timeout the max
Assert.assertTrue(LoginFilter.checkNonce("abc" + i, "123",
current_timestamp_fail));
Assert.assertTrue(LoginFilter.checkNonce("abc" + i, "1234",
current_timestamp_fail));
Assert.assertTrue(LoginFilter.checkNonce("abcd" + i, "123",
current_timestamp_fail));
}
System.out.println("Took " + (System.nanoTime() - before)
/ (double) tests / 1000 / 100 / 11 + "ms per nonce request");
}
}
|
snowcrystall/gitaly_emg | internal/cache/cache.go | <filename>internal/cache/cache.go
package cache
import (
"context"
"io"
"gitlab.com/gitlab-org/gitaly/v14/proto/go/gitalypb"
"google.golang.org/protobuf/proto"
)
// Cache is a stream-oriented cache which stores RPC responses keyed by protobuf requests.
type Cache interface {
Streamer
Invalidator
}
// Streamer abstracts away the cache concrete type so that it can be override in tests.
type Streamer interface {
GetStream(context.Context, *gitalypb.Repository, proto.Message) (io.ReadCloser, error)
PutStream(context.Context, *gitalypb.Repository, proto.Message, io.Reader) error
}
// Invalidator is able to invalidate parts of the cache pertinent to a
// specific repository. Before a repo mutating operation, StartLease should
// be called. Once the operation is complete, the returned LeaseEnder should
// be invoked to end the lease.
type Invalidator interface {
StartLease(*gitalypb.Repository) (LeaseEnder, error)
}
// LeaseEnder allows the caller to indicate when a lease is no longer needed
type LeaseEnder interface {
EndLease(context.Context) error
}
|
gtechx/cloud | src/chatserver/main.go | <reponame>gtechx/cloud<gh_stars>0
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"gtdb"
"io"
"io/ioutil"
"net"
"os"
"os/signal"
"time"
"github.com/gtechx/base/collections"
. "github.com/gtechx/base/common"
"github.com/gtechx/base/gtnet"
)
var quit chan os.Signal
//var userOLMapAll = map[uint64]map[string]string{} //{uid1:{ios:serveraddr, pc:serveraddr}}
var userOLMapAll = map[uint64]map[string]bool{} //{uid1:{serveraddr1:true, serveraddr2:true}} //所有服登录用户
var sessMap = map[uint64]map[string]ISession{} //{uid:{web:sess, ios:sess, android:sess}} //本地登录用户
var roomMapLocal = map[uint64]map[uint64]bool{} //{rid:{uid1:true, uid2:true}} //本地登录用户所在房间 //need optimize
var uidMapAppZone = map[string]map[string]map[uint64]bool{} //{appname:{zonename:{uid1:true, uid2:true}}}
type ConnData struct {
conn net.Conn
tbl_appdata *gtdb.AppData
platform string
}
var newConnList = collections.NewSafeList() //*collections.SafeList
type ServerEvent struct {
Msgid uint16
Data []byte
}
var serverEventQueue = collections.NewSafeList() //*collections.SafeList
type ServerMsg struct {
Msgid uint16
Data []byte
}
var serverMsgQueue = collections.NewSafeList() //*collections.SafeList
var toDeleteSessList = collections.NewSafeList() //*collections.SafeList
type serverconfig struct {
ServerAddr string `json:"serveraddr"`
ServerNet string `json:"servernet"`
RedisAddr string `json:"redisaddr"`
RedisPassword string `json:"<PASSWORD>"`
RedisDefaultDB uint64 `json:"redisdefaultdb"`
RedisMaxConn int `json:"redismaxconn"`
MysqlAddr string `json:"mysqladdr"`
MysqlUserPassword string `json:"<PASSWORD>"`
MysqlDefaultDB string `json:"mysqldefaultdb"`
MysqlTablePrefix string `json:"mysqltableprefix"`
MysqlLogMode bool `json:"mysqllogmode"`
MysqlMaxConn int `json:"mysqlmaxconn"`
VerifyAddr map[string]string `jsong:"verifyaddr"`
DefaultGroupName string `json:"defaultgroupname"`
}
var srvconfig *serverconfig
var isQuit bool
var dbMgr *gtdb.DBManager
var configpath string = "../res/config/chatserver.config"
func main() {
quit = make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, os.Kill)
pconfig := flag.String("config", "", "-config=")
flag.Parse()
if *pconfig != "" {
configpath = *pconfig
}
defer func() {
if err := recover(); err != nil {
fmt.Println(err)
var tmp string
fmt.Print("press enter to continue...")
fmt.Scanln(&tmp)
}
}()
readConfig()
dbMgr = gtdb.Manager()
err := dbMgr.Initialize(configjson)
if err != nil {
panic("Initialize DB err:" + err.Error())
}
defer dbMgr.UnInitialize()
//clear online user
err = dbMgr.ClearOnlineInfo(srvconfig.ServerAddr)
if err != nil {
panic("clear online info err:" + err.Error())
}
//register server
err = dbMgr.RegisterChatServer(srvconfig.ServerAddr)
if err != nil {
panic("register server to gtdata.Manager err:" + err.Error())
}
defer dbMgr.UnRegisterChatServer(srvconfig.ServerAddr)
//keep live init
keepLiveStart()
//check server
//checkAllServerAlive()
//other server live monitor init
serverMonitorStart()
//read online user
serverlist, err := dbMgr.GetChatServerList()
if err != nil {
panic(err.Error())
}
for _, serveraddr := range serverlist {
users, err := dbMgr.GetAllOnlineUser(serveraddr)
if err != nil {
panic(err.Error())
}
for _, iuid := range users {
uid := Uint64(iuid)
addOLUser(serveraddr, uid)
}
}
server := gtnet.NewServer()
err = server.Start(srvconfig.ServerNet, srvconfig.ServerAddr, onNewConn)
if err != nil {
panic(err.Error())
}
defer server.Stop()
defer dbMgr.ClearOnlineInfo(srvconfig.ServerAddr)
//msg from other server monitor
messagePullStart()
fmt.Println(srvconfig.ServerNet + " server start on addr " + srvconfig.ServerAddr + " ok...")
//frame loop
go loop()
<-quit
//clear
fmt.Println("clear...")
server.Stop()
dbMgr.UnRegisterChatServer(srvconfig.ServerAddr)
dbMgr.ClearOnlineInfo(srvconfig.ServerAddr)
dbMgr.UnInitialize()
// var str string
// fmt.Scanln(&str)
}
func addAppZoneUid(appname, zonename string, uid uint64) {
zonemap, ok := uidMapAppZone[appname]
if !ok {
zonemap = map[string]map[uint64]bool{}
uidMapAppZone[appname] = zonemap
}
sessmap, ok := zonemap[zonename]
if !ok {
sessmap = map[uint64]bool{}
zonemap[zonename] = sessmap
}
sessmap[uid] = true
}
func removeAppZoneUid(appname, zonename string, uid uint64) {
zonemap, ok := uidMapAppZone[appname]
if ok {
sessmap, ok := zonemap[zonename]
if ok {
delete(sessmap, uid)
if len(sessmap) == 0 {
delete(zonemap, zonename)
if len(zonemap) == 0 {
delete(uidMapAppZone, appname)
}
}
}
}
}
func addOLUser(serveraddr string, uid uint64) {
olinfo, ok := userOLMapAll[uid]
if !ok {
olinfo = map[string]bool{}
userOLMapAll[uid] = olinfo
}
olinfo[serveraddr] = true //other server
}
func removeOLUser(serveraddr string, uid uint64) {
olinfo, ok := userOLMapAll[uid]
if ok {
_, ok := olinfo[serveraddr]
if ok {
delete(olinfo, serveraddr)
if len(olinfo) == 0 {
delete(userOLMapAll, uid)
}
}
}
}
func broadcastServerEvent(msgbytes []byte) error {
serverlist, err := dbMgr.GetChatServerList()
if err != nil {
return err
}
for _, serveraddr := range serverlist {
if serveraddr == srvconfig.ServerAddr {
continue
}
err = dbMgr.SendServerEvent(serveraddr, msgbytes)
if err != nil {
return err
}
}
return nil
}
func broadcastServerMsg(msgbytes []byte) error {
serverlist, err := dbMgr.GetChatServerList()
if err != nil {
return err
}
for _, serveraddr := range serverlist {
if serveraddr == srvconfig.ServerAddr {
continue
}
err = dbMgr.SendMsgToServer(serveraddr, msgbytes)
if err != nil {
return err
}
}
return nil
}
func loop() {
for {
//check quit
if isQuit {
break
}
starttime := time.Now().UnixNano()
limitcount := 0
//create sess for new user
for {
item, err := newConnList.Pop()
if err != nil {
break
}
conndata := item.(*ConnData)
sess := CreateSess(conndata.conn, conndata.tbl_appdata, conndata.platform)
sess.Start()
//add user to userOLMapAll
olinfo, ok := userOLMapAll[conndata.tbl_appdata.ID]
if !ok {
olinfo = map[string]bool{}
userOLMapAll[conndata.tbl_appdata.ID] = olinfo
}
_, ok = olinfo[""]
olinfo[""] = true //local server
if !ok {
//if didn't had this id logined on this server
//get room user joined and add room info to roomMapLocal
roomlist, err := dbMgr.GetRoomListByJoined(conndata.tbl_appdata.ID)
if err != nil {
fmt.Println(err.Error())
sess.Stop()
continue
}
for _, room := range roomlist {
userlist, ok := roomMapLocal[room.Rid]
if !ok {
userlist = map[uint64]bool{}
roomMapLocal[room.Rid] = userlist
// users, err := dbMgr.GetRoomUserIds(room.Rid)
// if err != nil {
// continue
// }
// for _, user := range users {
// userlist[user.Dataid] = true
// }
}
userlist[conndata.tbl_appdata.ID] = true
}
//send event to other server
msg := &SMsgUserOnline{Uid: conndata.tbl_appdata.ID, ServerAddr: srvconfig.ServerAddr}
msg.MsgId = SMsgId_UserOnline
msgbytes := Bytes(msg)
if broadcastServerEvent(msgbytes) != nil {
fmt.Println(err.Error())
sess.Stop()
continue
}
err = dbMgr.AddOnlineUser(srvconfig.ServerAddr, conndata.tbl_appdata.ID)
if err != nil {
fmt.Println(err.Error())
sess.Stop()
continue
}
addAppZoneUid(conndata.tbl_appdata.Appname, conndata.tbl_appdata.Zonename, conndata.tbl_appdata.ID)
}
limitcount++
dbMgr.IncrByChatServerClientCount(srvconfig.ServerAddr, 1)
if limitcount >= 10 {
break
}
}
limitcount = 0
//process server event
for {
item, err := serverEventQueue.Pop()
if err != nil {
break
}
event := item.(*ServerEvent)
data := event.Data
fmt.Println("processing server event msgid " + String(event.Msgid))
switch event.Msgid {
case SMsgId_ServerQuit:
isQuit = true
case SMsgId_UserOnline:
uid := Uint64(data)
serveraddr := String(data[8:])
// strarr := strings.Split(platformandserver, "#")
// //platform := strarr[0]
// serveraddr := strarr[1]
addOLUser(serveraddr, uid)
case SMsgId_UserOffline:
uid := Uint64(data)
serveraddr := String(data[8:])
removeOLUser(serveraddr, uid)
case SMsgId_RoomAddUser:
rid := Uint64(data)
uid := Uint64(data[8:])
roomusers, ok := roomMapLocal[rid]
if ok {
roomusers[uid] = true
}
case SMsgId_RoomRemoveUser:
rid := Uint64(data)
uid := Uint64(data[8:])
roomusers, ok := roomMapLocal[rid]
if ok {
_, ok := roomusers[uid]
if ok {
delete(roomusers, uid)
}
}
case SMsgId_RoomDimiss:
rid := Uint64(data)
_, ok := roomMapLocal[rid]
if ok {
delete(roomMapLocal, rid)
}
}
limitcount++
if limitcount >= 10 {
break
}
}
limitcount = 0
//process server msg
for {
item, err := serverMsgQueue.Pop()
if err != nil {
break
}
msg := item.(*ServerMsg)
data := msg.Data
fmt.Println("processing server msg msgid " + String(msg.Msgid))
switch msg.Msgid {
case SMsgId_UserMessage:
uid := Uint64(data)
SendMsgToLocalUid(uid, data[8:])
case SMsgId_RoomMessage:
rid := Uint64(data)
SendMsgToLocalRoom(rid, data[8:])
case SMsgId_ZonePublicMessage:
len := int(data[0])
appname := String(data[1 : 1+len])
data = data[1+len:]
len = int(data[0])
zonename := String(data[1 : 1+len])
data = data[1+len:]
SendZonePublicMsg(appname, zonename, data)
case SMsgId_AppPublicMessage:
len := int(data[0])
appname := String(data[1 : 1+len])
data = data[1+len:]
SendAppPublicMsg(appname, data)
case SMsgId_ServerPublicMessage:
SendServerPublicMsg(data)
}
limitcount++
if limitcount >= 10 {
break
}
}
//traversal all sess, can parallel the update to diff goroutine
for _, sesslist := range sessMap {
for _, sess := range sesslist {
isess := sess.(ISession)
isess.Update()
}
}
//remove sess stoped
for {
item, err := toDeleteSessList.Pop()
if err != nil {
break
}
sess := item.(ISession)
sesslist, ok := sessMap[sess.ID()]
if ok {
delete(sesslist, sess.Platform())
if len(sesslist) == 0 {
delete(sessMap, sess.ID())
//只有当id对应的sesslist为0时才从userOLMapAll中删除,并且向其它服务器广播id从该服务器彻底离线的event
//remove user from userOLMapAll
//delete(userOLMapAll, sess.ID())
// olinfo, ok := userOLMapAll[sess.ID()]
// if ok {
// delete(olinfo, "")
// if len(olinfo) == 0 {
// delete(userOLMapAll, sess.ID())
// }
// }
removeOLUser("", sess.ID())
//get room user joined and add room info to roomMapLocal
roomlist, err := dbMgr.GetRoomListByJoined(sess.ID())
if err != nil {
continue
}
for _, room := range roomlist {
userlist, ok := roomMapLocal[room.Rid]
if ok {
delete(userlist, sess.ID())
// flag := true
// //check if has room use still on this server
// for uid, _ := range userlist {
// //_, ok := userOLMapAll[uid]
// _, ok := sessMap[uid]
// if ok {
// flag = false
// break
// }
// }
if len(userlist) == 0 {
delete(roomMapLocal, room.Rid)
}
}
}
//send event to other server
msg := &SMsgUserOffline{Uid: sess.ID(), ServerAddr: srvconfig.ServerAddr}
msg.MsgId = SMsgId_UserOffline
msgbytes := Bytes(msg)
if broadcastServerEvent(msgbytes) != nil {
fmt.Println(err.Error())
continue
}
dbMgr.RemoveOnlineUser(srvconfig.ServerAddr, sess.ID())
removeAppZoneUid(sess.AppName(), sess.ZoneName(), sess.ID())
}
}
dbMgr.IncrByChatServerClientCount(srvconfig.ServerAddr, -1)
}
endtime := time.Now().UnixNano()
delta := endtime - starttime
sleeptime := 20*1000000 - delta
if sleeptime > 0 {
time.Sleep(time.Duration(sleeptime) * time.Nanosecond)
}
}
}
var configjson string
func readConfig() {
// cf, err := os.Open("../res/config/chatserver.config")
// if err != nil {
// panic("can not open config file chatserver.config")
// }
// fs, err := cf.Stat()
// if err != nil {
// panic("get config file chatserver.config stat error:" + err.Error())
// }
// cbuff := make([]byte, fs.Size())
// _, err = cf.Read(cbuff)
// if err != nil {
// panic("read config file chatserver.config error:" + err.Error())
// }
fmt.Println("reading config:" + configpath)
data, err := ioutil.ReadFile(configpath)
if err != nil {
panic("read config file chatserver.config error:" + err.Error())
}
configjson = string(data)
srvconfig = &serverconfig{}
err = json.Unmarshal(data, srvconfig)
if err != nil {
panic("json.Unmarshal config file chatserver.config error:" + err.Error())
}
}
func onNewConn(conn net.Conn) {
fmt.Println("new conn:", conn.RemoteAddr().String())
isok := false
//defer conn.Close()
time.AfterFunc(5*time.Second, func() {
if !isok {
fmt.Println("time.AfterFunc conn close")
conn.Close()
}
})
msgtype, id, size, msgid, databuff, err := readMsgHeader(conn)
isok = true
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println("new msg msgtype:", msgtype, " id:", id, " size:", size, " msgid:", msgid)
if msgid == MsgId_ReqChatLogin {
//chat login
var errcode uint16
var appdatabytes []byte
tbl_appdata := >db.AppData{}
req := &MsgReqChatLogin{}
if jsonUnMarshal(databuff, req, &errcode) {
userdata, err := dbMgr.GetChatToken(req.Token)
if err != nil {
errcode = ERR_DB
} else {
jsonUnMarshal(userdata, tbl_appdata, &errcode)
fmt.Println("uid:", tbl_appdata.ID, " logined success")
}
}
ret := &MsgRetChatLogin{errcode, appdatabytes}
senddata := packageMsg(RetFrame, id, MsgId_ReqChatLogin, ret)
_, err = conn.Write(senddata)
if err != nil || errcode != ERR_NONE {
fmt.Println(err.Error())
conn.Close()
return
}
fmt.Println(tbl_appdata)
newConnList.Put(&ConnData{conn, tbl_appdata, req.Platform})
}
}
func packageMsg(msgtype uint8, id uint16, msgid uint16, data interface{}) []byte {
ret := []byte{}
databuff := Bytes(data)
datalen := uint16(len(databuff))
ret = append(ret, byte(msgtype))
ret = append(ret, Bytes(id)...)
ret = append(ret, Bytes(datalen)...)
ret = append(ret, Bytes(msgid)...)
if datalen > 0 {
ret = append(ret, databuff...)
}
return ret
}
func readMsgHeader(conn net.Conn) (byte, uint16, uint16, uint16, []byte, error) {
typebuff := make([]byte, 1)
idbuff := make([]byte, 2)
sizebuff := make([]byte, 2)
msgidbuff := make([]byte, 2)
var id uint16
var size uint16
var msgid uint16
var databuff []byte
_, err := io.ReadFull(conn, typebuff)
if err != nil {
goto end
}
//fmt.Println("data type:", typebuff[0])
if typebuff[0] == TickFrame {
goto end
}
_, err = io.ReadFull(conn, idbuff)
if err != nil {
goto end
}
id = Uint16(idbuff)
//fmt.Println("id:", id)
_, err = io.ReadFull(conn, sizebuff)
if err != nil {
goto end
}
size = Uint16(sizebuff)
//fmt.Println("data size:", size)
if size > 65535 {
err = errors.New("too long data size")
goto end
}
_, err = io.ReadFull(conn, msgidbuff)
if err != nil {
goto end
}
msgid = Uint16(msgidbuff)
//fmt.Println("msgid:", msgid)
if size == 0 {
goto end
}
databuff = make([]byte, size)
_, err = io.ReadFull(conn, databuff)
if err != nil {
goto end
}
end:
return typebuff[0], id, size, msgid, databuff, err
}
//first, login with account,appname and zonename
//server will return all appdataid in the zone of app
//client need to use one of the appdataid to enter chat.
//before receive chat server chat msg, client need send ready msg to server.
//账号登录的时候发送账号、密码,返回登录成功的token
//登录聊天有两种情况
//1.聊天APP应用,没有分区
//2.游戏带分区聊天应用
//登录聊天的时候需要发送账号、密码,返回appdataidlist
//进入聊天发送appdataid, 服务器根据appdataid创建session
//客户端发送可以接受消息命令,服务器设置玩家在线
|
kaio7/arquitetura-de-software | FabricaAbstrata/src/br/ifrn/tads/cliente/ClienteFabrica.java | <filename>FabricaAbstrata/src/br/ifrn/tads/cliente/ClienteFabrica.java<gh_stars>0
package br.ifrn.tads.cliente;
import br.ifrn.tads.abstratos.Chassi;
import br.ifrn.tads.abstratos.FabricaAutomoveis;
import br.ifrn.tads.abstratos.Motor;
import br.ifrn.tads.abstratos.Roda;
public class ClienteFabrica {
public static void main(String[] args) {
FabricaAutomoveis fabrica = FabricaAutomoveis.getInstancia();
Motor m = fabrica.criaMotor();
Roda r = fabrica.criaRodas();
Chassi c = fabrica.criaChassi();
System.out.println(m);
System.out.println(r);
System.out.println(c);
}
}
|
windystrife/UnrealEngine_NVIDIAGameWork | Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/test/test_task_steal_limit.cpp | <filename>Engine/Source/ThirdParty/IntelTBB/IntelTBB-4.0/src/test/test_task_steal_limit.cpp
/*
Copyright 2005-2012 Intel Corporation. All Rights Reserved.
The source code contained or described herein and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel
Corporation or its suppliers and licensors. The Material is protected
by worldwide copyright laws and treaty provisions. No part of the
Material may be used, copied, reproduced, modified, published, uploaded,
posted, transmitted, distributed, or disclosed in any way without
Intel's prior express written permission.
No license under any patent, copyright, trade secret or other
intellectual property right is granted to or conferred upon you by
disclosure or delivery of the Materials, either expressly, by
implication, inducement, estoppel or otherwise. Any license under such
intellectual property rights must be express and approved by Intel in
writing.
*/
#include "tbb/task.h"
#include "harness.h"
#include "tbb/task_scheduler_init.h"
using tbb::task;
#if __TBB_ipf
const unsigned StackSize = 1024*1024*6;
#else /* */
const unsigned StackSize = 1024*1024*3;
#endif
// GCC and ICC on Linux store TLS data in the stack space. This test makes sure
// that the stealing limiting heuristic used by the task scheduler does not
// switch off stealing when a large amount of TLS data is reserved.
#if _MSC_VER
__declspec(thread)
#elif __linux__ || ((__MINGW32__ || __MINGW64__) && __TBB_GCC_VERSION >= 40500)
__thread
#endif
char map2[1024*1024*2];
class TestTask : public task {
public:
static volatile int completed;
task* execute() {
completed = 1;
return NULL;
};
};
volatile int TestTask::completed = 0;
void TestStealingIsEnabled () {
tbb::task_scheduler_init init(2, StackSize);
task &r = *new( task::allocate_root() ) tbb::empty_task;
task &t = *new( r.allocate_child() ) TestTask;
r.set_ref_count(2);
r.spawn(t);
int count = 0;
while ( !TestTask::completed && ++count < 6 )
Harness::Sleep(1000);
ASSERT( TestTask::completed, "Stealing is disabled or the machine is heavily oversubscribed" );
r.wait_for_all();
task::destroy(r);
}
int TestMain () {
if ( tbb::task_scheduler_init::default_num_threads() == 1 ) {
REPORT( "Known issue: Test requires at least 2 hardware threads.\n" );
return Harness::Skipped;
}
TestStealingIsEnabled();
return Harness::Done;
}
|
DannyVanHalen/URJC-Academy | urjc-academy/src/main/java/com/dad/urjcacademy/controller/URJCAcademyController.java | <gh_stars>1-10
package com.dad.urjcacademy.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.dad.urjcacademy.entity.Usuario;
import com.dad.urjcacademy.repository.UsuarioRepository;
import com.dad.urjcacademy.services.UsuarioService;
@Controller
public class URJCAcademyController {
@RequestMapping(value= "/", method=RequestMethod.GET)
public String urjc_academy_index(Model model) {
return "index";
}
}
|
ryanloney/openvino-1 | src/core/tests/type_prop/deformable_psroi_pooling.cpp | <reponame>ryanloney/openvino-1
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
#include "util/type_prop.hpp"
using namespace std;
using namespace ngraph;
TEST(type_prop, deformable_psroi_pooling_no_offsets_group_size_3) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 882;
const int64_t group_size = 3;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto def_psroi_pool =
make_shared<op::v1::DeformablePSROIPooling>(input_data, input_coords, output_dim, spatial_scale, group_size);
const PartialShape expected_output{rois_dim, output_dim, group_size, group_size};
ASSERT_EQ(def_psroi_pool->get_output_partial_shape(0), expected_output);
}
TEST(type_prop, deformable_psroi_pooling_group_size_3) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 882;
const int64_t group_size = 3;
const int64_t part_size = 3;
const double spatial_bins = 4;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto input_offsets = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 2, part_size, part_size});
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
input_offsets,
output_dim,
spatial_scale,
group_size,
"bilinear_deformable",
spatial_bins,
spatial_bins,
0.1,
part_size);
const PartialShape expected_output{rois_dim, output_dim, group_size, group_size};
ASSERT_EQ(def_psroi_pool->get_output_partial_shape(0), expected_output);
}
TEST(type_prop, deformable_psroi_pooling_group_size_7) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 162;
const int64_t group_size = 7;
const int64_t part_size = 7;
const double spatial_bins = 4;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto input_offsets = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 2, part_size, part_size});
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
input_offsets,
output_dim,
spatial_scale,
group_size,
"bilinear_deformable",
spatial_bins,
spatial_bins,
0.1,
part_size);
const PartialShape expected_output{rois_dim, output_dim, group_size, group_size};
ASSERT_EQ(def_psroi_pool->get_output_partial_shape(0), expected_output);
}
TEST(type_prop, deformable_psroi_pooling_dynamic_rois) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 882;
const int64_t group_size = 3;
const auto rois_dim = Dimension(100, 200);
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto def_psroi_pool =
make_shared<op::v1::DeformablePSROIPooling>(input_data, input_coords, output_dim, spatial_scale, group_size);
const PartialShape expected_output{rois_dim, output_dim, group_size, group_size};
ASSERT_EQ(def_psroi_pool->get_output_partial_shape(0), expected_output);
}
TEST(type_prop, deformable_psroi_pooling_fully_dynamic) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 882;
const int64_t group_size = 3;
const auto rois_dim = Dimension::dynamic();
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape::dynamic());
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape::dynamic());
auto def_psroi_pool =
make_shared<op::v1::DeformablePSROIPooling>(input_data, input_coords, output_dim, spatial_scale, group_size);
const PartialShape expected_output{rois_dim, output_dim, group_size, group_size};
ASSERT_EQ(def_psroi_pool->get_output_partial_shape(0), expected_output);
}
TEST(type_prop, deformable_psroi_pooling_invalid_group_size) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 882;
const auto rois_dim = 300;
try {
const int64_t group_size = 0;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
output_dim,
spatial_scale,
group_size);
FAIL() << "Invalid group_size not detected";
} catch (const NodeValidationFailure& error) {
EXPECT_HAS_SUBSTRING(error.what(), std::string("Value of `group_size` attribute has to be greater than 0"));
} catch (...) {
FAIL() << "Unknown exception was thrown";
}
}
TEST(type_prop, deformable_psroi_pooling_invalid_output_dim) {
const float spatial_scale = 0.0625;
const auto rois_dim = 300;
const int64_t group_size = 3;
try {
const int64_t output_dim = -882;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
output_dim,
spatial_scale,
group_size);
FAIL() << "Invalid output_dim not detected";
} catch (const NodeValidationFailure& error) {
EXPECT_HAS_SUBSTRING(error.what(), std::string("Value of `output_dim` attribute has to be greater than 0"));
} catch (...) {
FAIL() << "Unknown exception was thrown";
}
}
TEST(type_prop, deformable_psroi_pooling_invalid_data_input_rank) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 162;
const int64_t group_size = 7;
const int64_t part_size = 7;
const double spatial_bins = 4;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto input_offsets = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 2, part_size, part_size});
try {
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
input_offsets,
output_dim,
spatial_scale,
group_size,
"bilinear_deformable",
spatial_bins,
spatial_bins,
0.1,
part_size);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid first input rank not detected";
} catch (const NodeValidationFailure& error) {
EXPECT_HAS_SUBSTRING(error.what(), std::string("First input rank must be compatible with 4 (input rank: 3)"));
} catch (...) {
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, deformable_psroi_pooling_invalid_box_coordinates_rank) {
const int64_t output_dim = 4;
const float spatial_scale = 0.9;
const int64_t group_size = 7;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{2, rois_dim, 5});
try {
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
output_dim,
spatial_scale,
group_size);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid second input rank not detected";
} catch (const NodeValidationFailure& error) {
EXPECT_HAS_SUBSTRING(error.what(), std::string("Second input rank must be compatible with 2 (input rank: 3)"));
} catch (...) {
FAIL() << "Deduced type check failed for unexpected reason";
}
}
TEST(type_prop, deformable_psroi_pooling_invalid_offstes_rank) {
const float spatial_scale = 0.0625;
const int64_t output_dim = 162;
const int64_t group_size = 7;
const int64_t part_size = 7;
const double spatial_bins = 4;
const auto rois_dim = 300;
auto input_data = make_shared<op::Parameter>(element::f32, PartialShape{2, 7938, 63, 38});
auto input_coords = make_shared<op::Parameter>(element::f32, PartialShape{rois_dim, 5});
auto input_offsets = make_shared<op::Parameter>(element::f32, PartialShape{2, rois_dim, 2, part_size, part_size});
try {
auto def_psroi_pool = make_shared<op::v1::DeformablePSROIPooling>(input_data,
input_coords,
input_offsets,
output_dim,
spatial_scale,
group_size,
"bilinear_deformable",
spatial_bins,
spatial_bins,
0.1,
part_size);
// Should have thrown, so fail if it didn't
FAIL() << "Invalid third input rank not detected";
} catch (const NodeValidationFailure& error) {
EXPECT_HAS_SUBSTRING(error.what(), std::string("Third input rank must be compatible with 4 (input rank: 5)"));
} catch (...) {
FAIL() << "Deduced type check failed for unexpected reason";
}
}
|
4rsenaltt/rangingram | java/org/telegram/messenger/VideoEditedInfo.java | <gh_stars>0
/*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright <NAME>, 2013-2015.
*/
package org.telegram.messenger;
import java.util.Locale;
public class VideoEditedInfo {
public long startTime;
public long endTime;
public int rotationValue;
public int originalWidth;
public int originalHeight;
public int resultWidth;
public int resultHeight;
public int bitrate;
public String originalPath;
public String getString() {
return String.format(Locale.US, "-1_%d_%d_%d_%d_%d_%d_%d_%d_%s", startTime, endTime, rotationValue, originalWidth, originalHeight, bitrate, resultWidth, resultHeight, originalPath);
}
public void parseString(String string) {
if (string.length() < 6) {
return;
}
String args[] = string.split("_");
if (args.length >= 10) {
startTime = Long.parseLong(args[1]);
endTime = Long.parseLong(args[2]);
rotationValue = Integer.parseInt(args[3]);
originalWidth = Integer.parseInt(args[4]);
originalHeight = Integer.parseInt(args[5]);
bitrate = Integer.parseInt(args[6]);
resultWidth = Integer.parseInt(args[7]);
resultHeight = Integer.parseInt(args[8]);
for (int a = 9; a < args.length; a++) {
if (originalPath == null) {
originalPath = args[a];
} else {
originalPath += "_" + args[a];
}
}
}
}
}
|
mynaparrot/plugNmeet-server | internal/models/waiting_room.go | <reponame>mynaparrot/plugNmeet-server
package models
import (
"database/sql"
"encoding/json"
"errors"
)
type userWaitingRoomModel struct {
db *sql.DB
roomService *RoomService
}
func NewWaitingRoomModel() *userWaitingRoomModel {
return &userWaitingRoomModel{
roomService: NewRoomService(),
}
}
type ApproveWaitingUsersReq struct {
RoomId string
UserId string `json:"user_id" validate:"required"`
}
func (u *userWaitingRoomModel) ApproveWaitingUsers(r *ApproveWaitingUsersReq) error {
if r.UserId == "all" {
participants, err := u.roomService.LoadParticipantsFromRedis(r.RoomId)
if err != nil {
return err
}
for _, p := range participants {
_ = u.approveUser(r.RoomId, r.UserId, p.Metadata)
}
return nil
}
p, err := u.roomService.LoadParticipantInfoFromRedis(r.RoomId, r.UserId)
if err != nil {
return err
}
return u.approveUser(r.RoomId, r.UserId, p.Metadata)
}
func (u *userWaitingRoomModel) approveUser(roomId, userId, metadata string) error {
meta := make([]byte, len(metadata))
copy(meta, metadata)
m := new(UserMetadata)
_ = json.Unmarshal(meta, m)
m.WaitForApproval = false // this mean doesn't need to wait anymore
newMeta, err := json.Marshal(m)
if err != nil {
return err
}
_, err = u.roomService.UpdateParticipantMetadata(roomId, userId, string(newMeta))
if err != nil {
return errors.New("can't approve user. try again")
}
return nil
}
type UpdateWaitingRoomMessageReq struct {
RoomId string
Msg string `json:"msg" validate:"required"`
}
func (u *userWaitingRoomModel) UpdateWaitingRoomMessage(r *UpdateWaitingRoomMessageReq) error {
room, err := u.roomService.LoadRoomInfoFromRedis(r.RoomId)
if err != nil {
return err
}
m := make([]byte, len(room.Metadata))
copy(m, room.Metadata)
roomMeta := new(RoomMetadata)
_ = json.Unmarshal(m, roomMeta)
roomMeta.Features.WaitingRoomFeatures.WaitingRoomMsg = r.Msg
metadata, err := json.Marshal(roomMeta)
if err != nil {
return err
}
_, err = u.roomService.UpdateRoomMetadata(r.RoomId, string(metadata))
return err
}
|
tvast/smart-diagnostic | dist/conversational-form.js | (function (root) {
// Store setTimeout reference so promise-polyfill will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var setTimeoutFunc = setTimeout;
function noop() {}
// Polyfill for Function.prototype.bind
function bind(fn, thisArg) {
return function () {
fn.apply(thisArg, arguments);
};
}
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
if (typeof fn !== 'function') throw new TypeError('not a function');
this._state = 0;
this._handled = false;
this._value = undefined;
this._deferreds = [];
doResolve(fn, this);
}
function handle(self, deferred) {
while (self._state === 3) {
self = self._value;
}
if (self._state === 0) {
self._deferreds.push(deferred);
return;
}
self._handled = true;
Promise._immediateFn(function () {
var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
if (cb === null) {
(self._state === 1 ? resolve : reject)(deferred.promise, self._value);
return;
}
var ret;
try {
ret = cb(self._value);
} catch (e) {
reject(deferred.promise, e);
return;
}
resolve(deferred.promise, ret);
});
}
function resolve(self, newValue) {
try {
// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (newValue instanceof Promise) {
self._state = 3;
self._value = newValue;
finale(self);
return;
} else if (typeof then === 'function') {
doResolve(bind(then, newValue), self);
return;
}
}
self._state = 1;
self._value = newValue;
finale(self);
} catch (e) {
reject(self, e);
}
}
function reject(self, newValue) {
self._state = 2;
self._value = newValue;
finale(self);
}
function finale(self) {
if (self._state === 2 && self._deferreds.length === 0) {
Promise._immediateFn(function() {
if (!self._handled) {
Promise._unhandledRejectionFn(self._value);
}
});
}
for (var i = 0, len = self._deferreds.length; i < len; i++) {
handle(self, self._deferreds[i]);
}
self._deferreds = null;
}
function Handler(onFulfilled, onRejected, promise) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.promise = promise;
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, self) {
var done = false;
try {
fn(function (value) {
if (done) return;
done = true;
resolve(self, value);
}, function (reason) {
if (done) return;
done = true;
reject(self, reason);
});
} catch (ex) {
if (done) return;
done = true;
reject(self, ex);
}
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.then = function (onFulfilled, onRejected) {
var prom = new (this.constructor)(noop);
handle(this, new Handler(onFulfilled, onRejected, prom));
return prom;
};
Promise.all = function (arr) {
var args = Array.prototype.slice.call(arr);
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([]);
var remaining = args.length;
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then;
if (typeof then === 'function') {
then.call(val, function (val) {
res(i, val);
}, reject);
return;
}
}
args[i] = val;
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex);
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i]);
}
});
};
Promise.resolve = function (value) {
if (value && typeof value === 'object' && value.constructor === Promise) {
return value;
}
return new Promise(function (resolve) {
resolve(value);
});
};
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
};
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
for (var i = 0, len = values.length; i < len; i++) {
values[i].then(resolve, reject);
}
});
};
// Use polyfill for setImmediate for performance gains
Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||
function (fn) {
setTimeoutFunc(fn, 0);
};
Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {
if (typeof console !== 'undefined' && console) {
console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
}
};
/**
* Set the immediate function to execute callbacks
* @param fn {function} Function to execute
* @deprecated
*/
Promise._setImmediateFn = function _setImmediateFn(fn) {
Promise._immediateFn = fn;
};
/**
* Change the function to execute on unhandled rejection
* @param {function} fn Function to execute on unhandled rejection
* @deprecated
*/
Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {
Promise._unhandledRejectionFn = fn;
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = Promise;
} else if (!root.Promise) {
root.Promise = Promise;
}
})(this);
// Polyfill for creating CustomEvents on IE9/10/11
// code pulled from:
// https://github.com/d4tocchini/customevent-polyfill
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
try {
var ce = new window.CustomEvent('test');
ce.preventDefault();
if (ce.defaultPrevented !== true) {
// IE has problems with .preventDefault() on custom events
// http://stackoverflow.com/questions/23349191
throw new Error('Could not prevent default');
}
} catch(e) {
var CustomEvent = function(event, params) {
var evt, origPrevent;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
origPrevent = evt.preventDefault;
evt.preventDefault = function () {
origPrevent.call(this);
try {
Object.defineProperty(this, 'defaultPrevented', {
get: function () {
return true;
}
});
} catch(e) {
this.defaultPrevented = true;
}
};
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent; // expose definition to window
}
// version 0.9.0
/// <reference path="ui/UserInput.ts"/>
/// <reference path="ui/chat/ChatList.ts"/>
/// <reference path="logic/FlowManager.ts"/>
/// <reference path="logic/EventDispatcher.ts"/>
/// <reference path="form-tags/Tag.ts"/>
/// <reference path="form-tags/TagGroup.ts"/>
/// <reference path="form-tags/InputTag.ts"/>
/// <reference path="form-tags/SelectTag.ts"/>
/// <reference path="form-tags/ButtonTag.ts"/>
/// <reference path="data/Dictionary.ts"/>
var cf;
(function (cf) {
var ConversationalForm = (function () {
function ConversationalForm(options) {
this.version = "0.9.2";
this.cdnPath = "//conversational-form-{version}-0iznjsw.stackpathdns.com/";
this.isDevelopment = false;
this.loadExternalStyleSheet = true;
this.preventAutoAppend = false;
this.preventAutoStart = false;
window.ConversationalForm = this;
this.cdnPath = this.cdnPath.split("{version}").join(this.version.split(".").join(""));
console.log('Conversational Form > version:', this.version);
window.ConversationalForm[this.createId] = this;
// possible to create your own event dispatcher, so you can tap into the events of the app
if (options.eventDispatcher)
this._eventTarget = options.eventDispatcher;
// set a general step validation callback
if (options.flowStepCallback)
cf.FlowManager.generalFlowStepCallback = options.flowStepCallback;
this.isDevelopment = ConversationalForm.illustrateAppFlow = !!document.getElementById("conversational-form-development");
if (this.isDevelopment || options.loadExternalStyleSheet == false) {
this.loadExternalStyleSheet = false;
}
if (!isNaN(options.scrollAccerlation))
cf.ScrollController.accerlation = options.scrollAccerlation;
this.preventAutoStart = options.preventAutoStart;
this.preventAutoAppend = options.preventAutoAppend;
if (!options.formEl)
throw new Error("Conversational Form error, the formEl needs to be defined.");
this.formEl = options.formEl;
this.formEl.setAttribute("cf-create-id", this.createId);
this.submitCallback = options.submitCallback;
if (this.formEl.getAttribute("cf-no-animation") == "")
ConversationalForm.animationsEnabled = false;
if (this.formEl.getAttribute("cf-prevent-autofocus") == "")
cf.UserInput.preventAutoFocus = true;
this.dictionary = new cf.Dictionary({
data: options.dictionaryData,
robotData: options.dictionaryRobot,
userImage: options.userImage,
robotImage: options.robotImage,
});
// emoji.. fork and set your own values..
this.context = options.context ? options.context : document.body;
this.tags = options.tags;
this.init();
}
Object.defineProperty(ConversationalForm.prototype, "createId", {
get: function () {
if (!this._createId) {
this._createId = new Date().getTime().toString();
}
return this._createId;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ConversationalForm.prototype, "eventTarget", {
get: function () {
if (!this._eventTarget) {
this._eventTarget = new cf.EventDispatcher(this);
}
return this._eventTarget;
},
enumerable: true,
configurable: true
});
ConversationalForm.prototype.init = function () {
cf.Helpers.setEmojiLib();
if (this.loadExternalStyleSheet) {
// not in development/examples, so inject production css
var head = document.head || document.getElementsByTagName("head")[0];
var style = document.createElement("link");
var githubMasterUrl = this.cdnPath + "conversational-form.min.css";
style.type = "text/css";
style.media = "all";
style.setAttribute("rel", "stylesheet");
style.setAttribute("href", githubMasterUrl);
head.appendChild(style);
}
else {
// expect styles to be in the document
this.isDevelopment = true;
}
// set context position to relative, else we break out of the box
var position = window.getComputedStyle(this.context).getPropertyValue("position").toLowerCase();
if (["fixed", "absolute", "relative"].indexOf(position) == -1) {
this.context.style.position = "relative";
}
// if tags are not defined then we will try and build some tags our selves..
if (!this.tags || this.tags.length == 0) {
this.tags = [];
var fields = [].slice.call(this.formEl.querySelectorAll("input, select, button, textarea"), 0);
for (var i = 0; i < fields.length; i++) {
var element = fields[i];
if (cf.Tag.isTagValid(element)) {
// ignore hidden tags
this.tags.push(cf.Tag.createTag(element));
}
}
}
else {
// tags are manually setup and passed as options.tags.
}
// remove invalid tags if they've sneaked in.. this could happen if tags are setup manually as we don't encurage to use static Tag.isTagValid
var indexesToRemove = [];
for (var i = 0; i < this.tags.length; i++) {
var element = this.tags[i];
if (!element || !cf.Tag.isTagValid(element.domElement)) {
indexesToRemove.push(element);
}
}
for (var i = 0; i < indexesToRemove.length; i++) {
var tag = indexesToRemove[i];
this.tags.splice(this.tags.indexOf(tag), 1);
}
if (!this.tags || this.tags.length == 0) {
console.warn("Conversational Form: No tags found or registered.");
}
//let's start the conversation
this.setupTagGroups();
this.setupUI();
return this;
};
/**
* @name updateDictionaryValue
* set a dictionary value at "runtime"
* id: string, id of the value to update
* type: string, "human" || "robot"
* value: string, value to be inserted
*/
ConversationalForm.prototype.updateDictionaryValue = function (id, type, value) {
cf.Dictionary.set(id, type, value);
if (["robot-image", "user-image"].indexOf(id) != -1) {
this.chatList.updateThumbnail(id == "robot-image", value);
}
};
ConversationalForm.prototype.getFormData = function (serialized) {
if (serialized === void 0) { serialized = false; }
if (serialized) {
var serialized_1 = {};
for (var i = 0; i < this.tags.length; i++) {
var element = this.tags[i];
if (element.name && element.value)
serialized_1[element.name] = element.value;
}
return serialized_1;
}
else {
var formData = new FormData(this.formEl);
return formData;
}
};
ConversationalForm.prototype.addRobotChatResponse = function (response) {
this.chatList.createResponse(true, null, response);
};
ConversationalForm.prototype.addUserChatResponse = function (response) {
// add a "fake" user response..
this.chatList.createResponse(false, null, response);
};
ConversationalForm.prototype.stop = function (optionalStoppingMessage) {
if (optionalStoppingMessage === void 0) { optionalStoppingMessage = ""; }
this.flowManager.stop();
if (optionalStoppingMessage != "")
this.chatList.createResponse(true, null, optionalStoppingMessage);
this.userInput.onFlowStopped();
};
ConversationalForm.prototype.start = function () {
this.userInput.disabled = false;
this.userInput.visible = true;
this.flowManager.start();
};
ConversationalForm.prototype.getTag = function (nameOrIndex) {
if (typeof nameOrIndex == "number") {
return this.tags[nameOrIndex];
}
else {
// TODO: fix so you can get a tag by its name attribute
return null;
}
};
ConversationalForm.prototype.setupTagGroups = function () {
// make groups, from input tag[type=radio | type=checkbox]
// groups are used to bind logic like radio-button or checkbox dependencies
var groups = [];
for (var i = 0; i < this.tags.length; i++) {
var tag = this.tags[i];
if (tag.type == "radio" || tag.type == "checkbox") {
if (!groups[tag.name])
groups[tag.name] = [];
groups[tag.name].push(tag);
}
}
if (Object.keys(groups).length > 0) {
for (var group in groups) {
if (groups[group].length > 0) {
// always build groupd when radio or checkbox
var tagGroup = new cf.TagGroup({
elements: groups[group]
});
// remove the tags as they are now apart of a group
for (var i = 0; i < groups[group].length; i++) {
var tagToBeRemoved = groups[group][i];
if (i == 0)
this.tags.splice(this.tags.indexOf(tagToBeRemoved), 1, tagGroup);
else
this.tags.splice(this.tags.indexOf(tagToBeRemoved), 1);
}
}
}
}
};
ConversationalForm.prototype.setupUI = function () {
// start the flow
this.flowManager = new cf.FlowManager({
cfReference: this,
eventTarget: this.eventTarget,
tags: this.tags
});
this.el = document.createElement("div");
this.el.id = "conversational-form";
this.el.className = "conversational-form";
if (ConversationalForm.animationsEnabled)
this.el.classList.add("conversational-form--enable-animation");
// add conversational form to context
if (!this.preventAutoAppend)
this.context.appendChild(this.el);
//hide until stylesheet is rendered
this.el.style.visibility = "hidden";
var innerWrap = document.createElement("div");
innerWrap.className = "conversational-form-inner";
this.el.appendChild(innerWrap);
// Conversational Form UI
this.chatList = new cf.ChatList({
eventTarget: this.eventTarget
});
innerWrap.appendChild(this.chatList.el);
this.userInput = new cf.UserInput({
eventTarget: this.eventTarget,
cfReference: this
});
innerWrap.appendChild(this.userInput.el);
this.onUserAnswerClickedCallback = this.onUserAnswerClicked.bind(this);
this.eventTarget.addEventListener(cf.ChatResponseEvents.USER_ANSWER_CLICKED, this.onUserAnswerClickedCallback, false);
this.el.classList.add("conversational-form--show");
if (!this.preventAutoStart)
this.flowManager.start();
if (!this.tags || this.tags.length == 0) {
// no tags, so just so the input
this.userInput.visible = true;
}
};
/**
* @name onUserAnswerClicked
* on user ChatReponse clicked
*/
ConversationalForm.prototype.onUserAnswerClicked = function (event) {
var tag = event.detail;
this.flowManager.editTag(tag);
};
/**
* @name remapTagsAndStartFrom
* index: number, what index to start from
* setCurrentTagValue: boolean, usually this method is called when wanting to loop or skip over questions, therefore it might be usefull to set the value of the current tag before changing index.
* ignoreExistingTags: boolean, possible to ignore existing tags, to allow for the flow to just "happen"
*/
ConversationalForm.prototype.remapTagsAndStartFrom = function (index, setCurrentTagValue, ignoreExistingTags) {
if (index === void 0) { index = 0; }
if (setCurrentTagValue === void 0) { setCurrentTagValue = false; }
if (ignoreExistingTags === void 0) { ignoreExistingTags = false; }
if (setCurrentTagValue) {
this.chatList.setCurrentUserResponse(this.userInput.getFlowDTO());
}
// possibility to start the form flow over from {index}
for (var i = 0; i < this.tags.length; i++) {
var tag = this.tags[i];
tag.refresh();
}
this.flowManager.startFrom(index, ignoreExistingTags);
};
/**
* @name focus
* Sets focus on Conversational Form
*/
ConversationalForm.prototype.focus = function () {
if (this.userInput)
this.userInput.setFocusOnInput();
};
ConversationalForm.prototype.doSubmitForm = function () {
this.el.classList.add("done");
this.userInput.reset();
if (this.submitCallback) {
// remove should be called in the submitCallback
this.submitCallback();
}
else {
// this.formEl.submit();
// doing classic .submit wont trigger onsubmit if that is present on form element
// as described here: http://wayback.archive.org/web/20090323062817/http://blogs.vertigosoftware.com/snyholm/archive/2006/09/27/3788.aspx
// so we mimic a click.
var button = this.formEl.ownerDocument.createElement('input');
button.style.display = 'none';
button.type = 'submit';
this.formEl.appendChild(button);
button.click();
this.formEl.removeChild(button);
// remove conversational
this.remove();
}
};
ConversationalForm.prototype.remove = function () {
if (this.onUserAnswerClickedCallback) {
this.eventTarget.removeEventListener(cf.ChatResponseEvents.USER_ANSWER_CLICKED, this.onUserAnswerClickedCallback, false);
this.onUserAnswerClickedCallback = null;
}
if (this.flowManager)
this.flowManager.dealloc();
if (this.userInput)
this.userInput.dealloc();
if (this.chatList)
this.chatList.dealloc();
this.dictionary = null;
this.flowManager = null;
this.userInput = null;
this.chatList = null;
this.context = null;
this.formEl = null;
this.tags = null;
this.submitCallback = null;
this.el.parentNode.removeChild(this.el);
this.el = null;
window.ConversationalForm[this.createId] = null;
};
// to illustrate the event flow of the app
ConversationalForm.illustrateFlow = function (classRef, type, eventType, detail) {
// ConversationalForm.illustrateFlow(this, "dispatch", FlowEvents.USER_INPUT_INVALID, event.detail);
// ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
if (detail === void 0) { detail = null; }
if (ConversationalForm.illustrateAppFlow) {
var highlight = "font-weight: 900; background: " + (type == "receive" ? "#e6f3fe" : "pink") + "; color: black; padding: 0px 5px;";
console.log("%c** event flow: %c" + eventType + "%c flow type: %c" + type + "%c from: %c" + classRef.constructor.name, "font-weight: 900;", highlight, "font-weight: 400;", highlight, "font-weight: 400;", highlight);
if (detail)
console.log("** event flow detail:", detail);
}
};
ConversationalForm.autoStartTheConversation = function () {
if (ConversationalForm.hasAutoInstantiated)
return;
// auto start the conversation
var formElements = document.querySelectorAll("form[cf-form]");
// no form elements found, look for the old init attribute
if (formElements.length === 0) {
formElements = document.querySelectorAll("form[cf-form-element]");
}
var formContexts = document.querySelectorAll("*[cf-context]");
if (formElements && formElements.length > 0) {
for (var i = 0; i < formElements.length; i++) {
var form = formElements[i];
var context = formContexts[i];
new cf.ConversationalForm({
formEl: form,
context: context
});
}
ConversationalForm.hasAutoInstantiated = true;
}
};
return ConversationalForm;
}());
ConversationalForm.animationsEnabled = true;
ConversationalForm.illustrateAppFlow = true;
ConversationalForm.hasAutoInstantiated = false;
cf.ConversationalForm = ConversationalForm;
})(cf || (cf = {}));
if (document.readyState == "complete") {
// if document alread instantiated, usually this happens if Conversational Form is injected through JS
setTimeout(function () { return cf.ConversationalForm.autoStartTheConversation(); }, 0);
}
else {
// await for when document is ready
window.addEventListener("load", function () {
cf.ConversationalForm.autoStartTheConversation();
}, false);
}
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module depending on jQuery.
define(['jquery'], factory);
} else {
// No AMD. Register plugin with global jQuery object.
try{
factory(jQuery);
}catch(e){
// whoops no jquery..
}
}
}(function ($) {
$.fn.conversationalForm = function (options /* ConversationalFormOptions, see README */) {
options = options || {};
if(!options.formEl)
options.formEl = this[0];
return new cf.ConversationalForm(options);
};
}
));
// namespace
var cf;
(function (cf) {
// interface
// class
var Helpers = (function () {
function Helpers() {
}
Helpers.lerp = function (norm, min, max) {
return (max - min) * norm + min;
};
Helpers.norm = function (value, min, max) {
return (value - min) / (max - min);
};
Helpers.getXYFromMouseTouchEvent = function (event) {
var touches = null;
if (event.originalEvent)
touches = event.originalEvent.touches || event.originalEvent.changedTouches;
else if (event.changedTouches)
touches = event.changedTouches;
if (touches) {
return { x: touches[0].pageX, y: touches[0].pageY, touches: touches[0] };
}
else {
return { x: event.pageX, y: event.pageY, touches: null };
}
};
Helpers.getInnerTextOfElement = function (element) {
var tmp = document.createElement("DIV");
tmp.innerHTML = element.innerHTML;
// return
var text = tmp.textContent || tmp.innerText || "";
// text = String(text).replace('\t','');
text = String(text).replace(/^\s+|\s+$/g, '');
return text;
};
Helpers.getMouseEvent = function (eventString) {
var mappings = [];
mappings["click"] = "ontouchstart" in window ? "touchstart" : "click";
mappings["mousedown"] = "ontouchstart" in window ? "touchstart" : "mousedown";
mappings["mouseup"] = "ontouchstart" in window ? "touchend" : "mouseup";
mappings["mousemove"] = "ontouchstart" in window ? "touchmove" : "mousemove";
return mappings[eventString];
};
Helpers.setEmojiLib = function (lib, scriptSrc) {
if (lib === void 0) { lib = "emojify"; }
if (scriptSrc === void 0) { scriptSrc = "//cdnjs.cloudflare.com/ajax/libs/emojify.js/1.1.0/js/emojify.min.js"; }
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.onload = function () {
// we use https://github.com/Ranks/emojify.js as a standard
Helpers.emojilib = window[lib];
if (Helpers.emojilib) {
Helpers.emojilib.setConfig({
img_dir: "https://cdnjs.cloudflare.com/ajax/libs/emojify.js/1.1.0/images/basic/",
});
}
};
script.setAttribute("src", scriptSrc);
head.appendChild(script);
};
Helpers.emojify = function (str) {
if (Helpers.emojilib) {
str = Helpers.emojilib.replace(str);
}
return str;
};
Helpers.setTransform = function (el, transformString) {
el.style["-webkit-transform"] = transformString;
el.style["-moz-transform"] = transformString;
el.style["-ms-transform"] = transformString;
el.style["transform"] = transformString;
};
return Helpers;
}());
Helpers.caniuse = {
fileReader: function () {
if (window.File && window.FileReader && window.FileList && window.Blob)
return true;
return false;
}
};
Helpers.emojilib = null;
cf.Helpers = Helpers;
})(cf || (cf = {}));
/// <reference path="../ConversationalForm.ts"/>
var cf;
(function (cf) {
// interface
var EventDispatcher = (function () {
function EventDispatcher(cfRef) {
this._cf = cfRef;
this.target = document.createDocumentFragment();
}
Object.defineProperty(EventDispatcher.prototype, "cf", {
get: function () {
return this._cf;
},
enumerable: true,
configurable: true
});
EventDispatcher.prototype.addEventListener = function (type, listener, useCapture) {
return this.target.addEventListener(type, listener, useCapture);
};
EventDispatcher.prototype.dispatchEvent = function (event) {
return this.target.dispatchEvent(event);
};
EventDispatcher.prototype.removeEventListener = function (type, listener, useCapture) {
this.target.removeEventListener(type, listener, useCapture);
};
return EventDispatcher;
}());
cf.EventDispatcher = EventDispatcher;
})(cf || (cf = {}));
/// <reference path="../logic/EventDispatcher.ts"/>
// namespace
var cf;
(function (cf) {
// class
var BasicElement = (function () {
function BasicElement(options) {
this.eventTarget = options.eventTarget;
// TODO: remove
if (!this.eventTarget)
throw new Error("this.eventTarget not set!! : " + this.constructor.name);
this.setData(options);
this.createElement();
}
BasicElement.prototype.setData = function (options) {
};
BasicElement.prototype.createElement = function () {
var template = document.createElement('template');
template.innerHTML = this.getTemplate();
this.el = template.firstChild || template.content.firstChild;
return this.el;
};
// template, should be overwritten ...
BasicElement.prototype.getTemplate = function () { return "should be overwritten..."; };
;
BasicElement.prototype.dealloc = function () {
this.el.parentNode.removeChild(this.el);
};
return BasicElement;
}());
cf.BasicElement = BasicElement;
})(cf || (cf = {}));
/// <reference path="../../ConversationalForm.ts"/>
/// <reference path="../BasicElement.ts"/>
/// <reference path="../../form-tags/Tag.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
cf.ControlElementEvents = {
SUBMIT_VALUE: "cf-basic-element-submit",
PROGRESS_CHANGE: "cf-basic-element-progress",
ON_FOCUS: "cf-basic-element-on-focus",
ON_LOADED: "cf-basic-element-on-loaded",
};
cf.ControlElementProgressStates = {
BUSY: "cf-control-element-progress-BUSY",
READY: "cf-control-element-progress-READY",
};
// class
var ControlElement = (function (_super) {
__extends(ControlElement, _super);
function ControlElement(options) {
var _this = _super.call(this, options) || this;
_this.animateInTimer = 0;
_this._partOfSeveralChoices = false;
_this._focus = false;
_this.onFocusCallback = _this.onFocus.bind(_this);
_this.el.addEventListener('focus', _this.onFocusCallback, false);
_this.onBlurCallback = _this.onBlur.bind(_this);
_this.el.addEventListener('blur', _this.onBlurCallback, false);
return _this;
}
Object.defineProperty(ControlElement.prototype, "type", {
get: function () {
return "ControlElement";
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "partOfSeveralChoices", {
get: function () {
return this._partOfSeveralChoices;
},
set: function (value) {
this._partOfSeveralChoices = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "value", {
get: function () {
// value is for the chat response -->
var hasTagImage = this.referenceTag.hasImage;
var str;
if (hasTagImage && !this.partOfSeveralChoices) {
var image = hasTagImage ? "<img src='" + this.referenceTag.domElement.getAttribute("cf-image") + "'/>" : "";
str = "<div class='contains-image'>";
str += image;
str += "<span>" + cf.Helpers.getInnerTextOfElement(this.el) + "</span>";
str += "</div>";
}
else {
str = "<div><span>" + cf.Helpers.getInnerTextOfElement(this.el) + "</span></div>";
}
return str;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "positionVector", {
get: function () {
return this._positionVector;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "tabIndex", {
set: function (value) {
this.el.tabIndex = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "highlight", {
get: function () {
return this.el.classList.contains("highlight");
},
set: function (value) {
this.el.classList.toggle("highlight", value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "focus", {
get: function () {
return this._focus;
},
set: function (value) {
this._focus = value;
if (this._focus)
this.el.focus();
else
this.el.blur();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElement.prototype, "visible", {
get: function () {
return !this.el.classList.contains("hide");
},
set: function (value) {
if (value) {
this.el.classList.remove("hide");
}
else {
this.el.classList.add("hide");
this.tabIndex = -1;
this.highlight = false;
}
},
enumerable: true,
configurable: true
});
ControlElement.prototype.onBlur = function (event) {
this._focus = false;
};
ControlElement.prototype.onFocus = function (event) {
this._focus = true;
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.ControlElementEvents.ON_FOCUS, this.referenceTag);
this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.ON_FOCUS, {
detail: this.positionVector
}));
};
/**
* @name hasImage
* if control element contains an image element
*/
ControlElement.prototype.hasImage = function () {
return false;
};
ControlElement.prototype.calcPosition = function () {
var mr = parseInt(window.getComputedStyle(this.el).getPropertyValue("margin-right"), 10);
// try not to do this to often, re-paint whammy!
this._positionVector = {
height: this.el.offsetHeight,
width: this.el.offsetWidth + mr,
x: this.el.offsetLeft,
y: this.el.offsetTop,
el: this,
};
this._positionVector.centerX = this._positionVector.x + (this._positionVector.width * 0.5);
this._positionVector.centerY = this._positionVector.y + (this._positionVector.height * 0.5);
};
ControlElement.prototype.setData = function (options) {
this.referenceTag = options.referenceTag;
_super.prototype.setData.call(this, options);
};
ControlElement.prototype.animateIn = function () {
clearTimeout(this.animateInTimer);
this.el.classList.add("animate-in");
};
ControlElement.prototype.animateOut = function () {
this.el.classList.add("animate-out");
};
ControlElement.prototype.onChoose = function () {
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.ControlElementEvents.SUBMIT_VALUE, this.referenceTag);
this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.SUBMIT_VALUE, {
detail: this
}));
};
ControlElement.prototype.dealloc = function () {
this.el.removeEventListener('blur', this.onBlurCallback, false);
this.onBlurCallback = null;
this.el.removeEventListener('focus', this.onFocusCallback, false);
this.onFocusCallback = null;
_super.prototype.dealloc.call(this);
};
return ControlElement;
}(cf.BasicElement));
cf.ControlElement = ControlElement;
})(cf || (cf = {}));
/// <reference path="Button.ts"/>
/// <reference path="ControlElement.ts"/>
/// <reference path="RadioButton.ts"/>
/// <reference path="CheckboxButton.ts"/>
/// <reference path="OptionsList.ts"/>
/// <reference path="UploadFileUI.ts"/>
/// <reference path="../../logic/EventDispatcher.ts"/>
/// <reference path="../ScrollController.ts"/>
/// <reference path="../chat/ChatResponse.ts"/>
/// <reference path="../../../typings/globals/es6-promise/index.d.ts"/>
// namespace
var cf;
(function (cf) {
var ControlElements = (function () {
function ControlElements(options) {
this.ignoreKeyboardInput = false;
this.rowIndex = -1;
this.columnIndex = 0;
this.elementWidth = 0;
this.filterListNumberOfVisible = 0;
this.listWidth = 0;
this.el = options.el;
this.eventTarget = options.eventTarget;
this.list = this.el.getElementsByTagName("cf-list")[0];
this.infoElement = options.infoEl;
this.onScrollCallback = this.onScroll.bind(this);
this.el.addEventListener('scroll', this.onScrollCallback, false);
this.onResizeCallback = this.onResize.bind(this);
window.addEventListener('resize', this.onResizeCallback, false);
this.onElementFocusCallback = this.onElementFocus.bind(this);
this.eventTarget.addEventListener(cf.ControlElementEvents.ON_FOCUS, this.onElementFocusCallback, false);
this.onElementLoadedCallback = this.onElementLoaded.bind(this);
this.eventTarget.addEventListener(cf.ControlElementEvents.ON_LOADED, this.onElementLoadedCallback, false);
this.onChatReponsesUpdatedCallback = this.onChatReponsesUpdated.bind(this);
this.eventTarget.addEventListener(cf.ChatListEvents.CHATLIST_UPDATED, this.onChatReponsesUpdatedCallback, false);
this.onUserInputKeyChangeCallback = this.onUserInputKeyChange.bind(this);
this.eventTarget.addEventListener(cf.UserInputEvents.KEY_CHANGE, this.onUserInputKeyChangeCallback, false);
// user input update
this.userInputUpdateCallback = this.onUserInputUpdate.bind(this);
this.eventTarget.addEventListener(cf.FlowEvents.USER_INPUT_UPDATE, this.userInputUpdateCallback, false);
this.listScrollController = new cf.ScrollController({
interactionListener: this.el,
listToScroll: this.list,
eventTarget: this.eventTarget,
listNavButtons: this.el.getElementsByTagName("cf-list-button"),
});
}
Object.defineProperty(ControlElements.prototype, "active", {
get: function () {
return this.elements && this.elements.length > 0;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElements.prototype, "focus", {
get: function () {
if (!this.elements)
return false;
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.focus) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElements.prototype, "highlighted", {
get: function () {
if (!this.elements)
return false;
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.highlight) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElements.prototype, "disabled", {
set: function (value) {
if (value)
this.list.classList.add("disabled");
else
this.list.classList.remove("disabled");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ControlElements.prototype, "length", {
get: function () {
var elements = this.getElements();
return elements.length;
},
enumerable: true,
configurable: true
});
ControlElements.prototype.onScroll = function (event) {
// some times the tabbing will result in el scroll, reset this.
this.el.scrollLeft = 0;
};
/**
* @name onElementLoaded
* when element is loaded, usally image loaded.
*/
ControlElements.prototype.onElementLoaded = function (event) {
this.resize();
};
ControlElements.prototype.onElementFocus = function (event) {
var vector = event.detail;
var x = (vector.x + vector.width < this.elementWidth ? 0 : vector.x - vector.width);
x *= -1;
this.updateRowColIndexFromVector(vector);
this.listScrollController.setScroll(x, 0);
};
ControlElements.prototype.updateRowColIndexFromVector = function (vector) {
for (var i = 0; i < this.tableableRows.length; i++) {
var items = this.tableableRows[i];
for (var j = 0; j < items.length; j++) {
var item = items[j];
if (item == vector.el) {
this.rowIndex = i;
this.columnIndex = j;
break;
}
}
}
};
ControlElements.prototype.onChatReponsesUpdated = function (event) {
this.animateElementsIn();
};
ControlElements.prototype.onUserInputKeyChange = function (event) {
if (this.ignoreKeyboardInput) {
this.ignoreKeyboardInput = false;
return;
}
var dto = event.detail;
var userInput = dto.dto.input;
if (this.active) {
var isNavKey = [cf.Dictionary.keyCodes["left"], cf.Dictionary.keyCodes["right"], cf.Dictionary.keyCodes["down"], cf.Dictionary.keyCodes["up"]].indexOf(dto.keyCode) != -1;
var shouldFilter = dto.inputFieldActive && !isNavKey;
if (shouldFilter) {
// input field is active, so we should filter..
var dto_1 = event.detail.dto;
var inputValue = dto_1.input.getInputValue();
this.filterElementsFrom(inputValue);
}
else {
if (dto.keyCode == cf.Dictionary.keyCodes["left"]) {
this.columnIndex--;
}
else if (dto.keyCode == cf.Dictionary.keyCodes["right"]) {
this.columnIndex++;
}
else if (dto.keyCode == cf.Dictionary.keyCodes["down"]) {
this.updateRowIndex(1);
}
else if (dto.keyCode == cf.Dictionary.keyCodes["up"]) {
this.updateRowIndex(-1);
}
else if (dto.keyCode == cf.Dictionary.keyCodes["enter"] || dto.keyCode == cf.Dictionary.keyCodes["space"]) {
if (this.tableableRows[this.rowIndex] && this.tableableRows[this.rowIndex][this.columnIndex]) {
this.tableableRows[this.rowIndex][this.columnIndex].el.click();
}
else if (this.tableableRows[0] && this.tableableRows[0].length == 1) {
// this is when only one element in a filter, then we click it!
this.tableableRows[0][0].el.click();
}
}
if (!this.validateRowColIndexes()) {
userInput.setFocusOnInput();
}
}
}
if (!userInput.active && this.validateRowColIndexes() && this.tableableRows && (this.rowIndex == 0 || this.rowIndex == 1)) {
this.tableableRows[this.rowIndex][this.columnIndex].focus = true;
}
else if (!userInput.active) {
userInput.setFocusOnInput();
}
};
ControlElements.prototype.validateRowColIndexes = function () {
var maxRowIndex = (this.el.classList.contains("two-row") ? 1 : 0);
if (this.rowIndex != -1 && this.tableableRows[this.rowIndex]) {
// columnIndex is only valid if rowIndex is valid
if (this.columnIndex < 0) {
this.columnIndex = this.tableableRows[this.rowIndex].length - 1;
}
if (this.columnIndex > this.tableableRows[this.rowIndex].length - 1) {
this.columnIndex = 0;
}
return true;
}
else {
this.resetTabList();
return false;
}
};
ControlElements.prototype.updateRowIndex = function (direction) {
var oldRowIndex = this.rowIndex;
this.rowIndex += direction;
if (this.tableableRows[this.rowIndex]) {
// when row index is changed we need to find the closest column element, we cannot expect them to be indexly aligned
var centerX = this.tableableRows[oldRowIndex] ? this.tableableRows[oldRowIndex][this.columnIndex].positionVector.centerX : 0;
var items = this.tableableRows[this.rowIndex];
var currentDistance = 10000000000000;
for (var i = 0; i < items.length; i++) {
var element = items[i];
if (currentDistance > Math.abs(centerX - element.positionVector.centerX)) {
currentDistance = Math.abs(centerX - element.positionVector.centerX);
this.columnIndex = i;
}
}
}
};
ControlElements.prototype.resetTabList = function () {
this.rowIndex = -1;
this.columnIndex = -1;
};
ControlElements.prototype.onUserInputUpdate = function (event) {
this.el.classList.remove("animate-in");
this.infoElement.classList.remove("show");
if (this.elements) {
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.animateOut();
}
}
};
ControlElements.prototype.filterElementsFrom = function (value) {
var inputValuesLowerCase = value.toLowerCase().split(" ");
if (inputValuesLowerCase.indexOf("") != -1)
inputValuesLowerCase.splice(inputValuesLowerCase.indexOf(""), 1);
var elements = this.getElements();
if (elements.length > 1) {
// the type is not strong with this one..
var itemsVisible = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.highlight = false;
var elementVisibility = true;
// check for all words of input
for (var i_1 = 0; i_1 < inputValuesLowerCase.length; i_1++) {
var inputWord = inputValuesLowerCase[i_1];
if (elementVisibility) {
elementVisibility = element.value.toLowerCase().indexOf(inputWord) != -1;
}
}
// set element visibility.
element.visible = elementVisibility;
if (elementVisibility && element.visible)
itemsVisible.push(element);
}
// set feedback text for filter..
this.infoElement.innerHTML = itemsVisible.length == 0 ? cf.Dictionary.get("input-no-filter").split("{input-value}").join(value) : "";
if (itemsVisible.length == 0) {
this.infoElement.classList.add("show");
}
else {
this.infoElement.classList.remove("show");
}
// crude way of checking if list has changed...
var hasListChanged = this.filterListNumberOfVisible != itemsVisible.length;
if (hasListChanged) {
this.resize();
this.animateElementsIn();
}
this.filterListNumberOfVisible = itemsVisible.length;
// highlight first item
if (value != "" && this.filterListNumberOfVisible > 0)
itemsVisible[0].highlight = true;
}
};
ControlElements.prototype.clickOnHighlighted = function () {
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.highlight) {
element.el.click();
break;
}
}
};
ControlElements.prototype.animateElementsIn = function () {
if (this.elements) {
var elements = this.getElements();
if (elements.length > 0) {
if (!this.el.classList.contains("animate-in"))
this.el.classList.add("animate-in");
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.animateIn();
}
}
}
};
ControlElements.prototype.getElements = function () {
if (this.elements.length > 0 && this.elements[0].type == "OptionsList")
return this.elements[0].elements;
return this.elements;
};
/**
* @name buildTabableRows
* build the tabable array index
*/
ControlElements.prototype.buildTabableRows = function () {
this.tableableRows = [];
this.resetTabList();
var elements = this.getElements();
if (this.el.classList.contains("two-row")) {
// two rows
this.tableableRows[0] = [];
this.tableableRows[1] = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.visible) {
// crude way of checking if element is top row or bottom row..
if (element.positionVector.y < 30)
this.tableableRows[0].push(element);
else
this.tableableRows[1].push(element);
}
}
}
else {
// single row
this.tableableRows[0] = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.visible)
this.tableableRows[0].push(element);
}
}
};
ControlElements.prototype.resetAfterErrorMessage = function () {
if (this.currentControlElement) {
//reverse value of currentControlElement.
this.currentControlElement.checked = !this.currentControlElement.checked;
this.currentControlElement = null;
}
this.disabled = false;
};
ControlElements.prototype.focusFrom = function (angle) {
if (!this.tableableRows)
return;
this.columnIndex = 0;
if (angle == "bottom") {
this.rowIndex = this.el.classList.contains("two-row") ? 1 : 0;
}
else if (angle == "top") {
this.rowIndex = 0;
}
if (this.tableableRows[this.rowIndex] && this.tableableRows[this.rowIndex][this.columnIndex]) {
this.ignoreKeyboardInput = true;
this.tableableRows[this.rowIndex][this.columnIndex].focus = true;
}
else {
this.resetTabList();
}
};
ControlElements.prototype.updateStateOnElementsFromTag = function (tag) {
for (var index = 0; index < this.elements.length; index++) {
var element = this.elements[index];
if (element.referenceTag == tag) {
this.updateStateOnElements(element);
break;
}
}
};
ControlElements.prototype.updateStateOnElements = function (controlElement) {
this.currentControlElement = controlElement;
if (this.currentControlElement.type == "RadioButton") {
// uncheck other radio buttons...
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element != controlElement) {
element.checked = false;
}
else {
element.checked = true;
}
}
}
else if (this.currentControlElement.type == "CheckboxButton") {
// change only the changed input
var elements = this.getElements();
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element == controlElement) {
var isChecked = element.referenceTag.domElement.checked;
element.checked = isChecked;
}
}
}
};
ControlElements.prototype.reset = function () {
this.el.classList.remove("one-row");
this.el.classList.remove("two-row");
};
ControlElements.prototype.getElement = function (index) {
return this.elements[index];
};
ControlElements.prototype.getDTO = function () {
var dto = {
text: undefined,
controlElements: [],
};
// generate text value for ChatReponse
if (this.elements && this.elements.length > 0) {
switch (this.elements[0].type) {
case "CheckboxButton":
var numChecked = 0; // check if more than 1 is checked.
var values = [];
for (var i = 0; i < this.elements.length; i++) {
var element_1 = this.elements[i];
if (element_1.checked) {
if (numChecked++ > 1)
break;
}
}
for (var i = 0; i < this.elements.length; i++) {
var element_2 = this.elements[i];
if (element_2.checked) {
if (numChecked > 1)
element_2.partOfSeveralChoices = true;
values.push(element_2.value);
}
dto.controlElements.push(element_2);
}
dto.text = cf.Dictionary.parseAndGetMultiValueString(values);
break;
case "RadioButton":
for (var i = 0; i < this.elements.length; i++) {
var element_3 = this.elements[i];
if (element_3.checked) {
dto.text = element_3.value;
}
dto.controlElements.push(element_3);
}
break;
case "OptionsList":
var element = this.elements[0];
dto.controlElements = element.getValue();
var values = [];
if (dto.controlElements && dto.controlElements[0]) {
for (var i_2 = 0; i_2 < dto.controlElements.length; i_2++) {
var element_4 = dto.controlElements[i_2];
values.push(dto.controlElements[i_2].value);
}
}
// after value is created then set to all elements
dto.controlElements = element.elements;
dto.text = cf.Dictionary.parseAndGetMultiValueString(values);
break;
case "UploadFileUI":
dto.text = this.elements[0].getFilesAsString(); //Dictionary.parseAndGetMultiValueString(values);
dto.controlElements.push(this.elements[0]);
break;
}
}
return dto;
};
ControlElements.prototype.clearTagsAndReset = function () {
this.reset();
if (this.elements) {
while (this.elements.length > 0) {
this.elements.pop().dealloc();
}
}
};
ControlElements.prototype.buildTags = function (tags) {
var _this = this;
this.disabled = false;
var topList = this.el.parentNode.getElementsByTagName("ul")[0];
var bottomList = this.el.parentNode.getElementsByTagName("ul")[1];
// remove old elements
this.clearTagsAndReset();
this.elements = [];
for (var i = 0; i < tags.length; i++) {
var tag = tags[i];
switch (tag.type) {
case "radio":
this.elements.push(new cf.RadioButton({
referenceTag: tag,
eventTarget: this.eventTarget
}));
break;
case "checkbox":
this.elements.push(new cf.CheckboxButton({
referenceTag: tag,
eventTarget: this.eventTarget
}));
break;
case "select":
this.elements.push(new cf.OptionsList({
referenceTag: tag,
context: this.list,
eventTarget: this.eventTarget
}));
break;
case "input":
default:
if (tag.type == "file") {
this.elements.push(new cf.UploadFileUI({
referenceTag: tag,
eventTarget: this.eventTarget
}));
}
// nothing to add.
// console.log("UserInput buildControlElements:", "none Control UI type, only input field is needed.");
break;
}
if (tag.type != "select" && this.elements.length > 0) {
var element = this.elements[this.elements.length - 1];
this.list.appendChild(element.el);
}
}
var isElementsOptionsList = this.elements[0] && this.elements[0].type == "OptionsList";
if (isElementsOptionsList) {
this.filterListNumberOfVisible = this.elements[0].elements.length;
}
else {
this.filterListNumberOfVisible = tags.length;
}
new Promise(function (resolve, reject) { return _this.resize(resolve, reject); }).then(function () {
var h = _this.el.classList.contains("one-row") ? 52 : _this.el.classList.contains("two-row") ? 102 : 0;
var controlElementsAddedDTO = {
height: h,
};
cf.ConversationalForm.illustrateFlow(_this, "dispatch", cf.UserInputEvents.CONTROL_ELEMENTS_ADDED, controlElementsAddedDTO);
_this.eventTarget.dispatchEvent(new CustomEvent(cf.UserInputEvents.CONTROL_ELEMENTS_ADDED, {
detail: controlElementsAddedDTO
}));
});
};
ControlElements.prototype.onResize = function (event) {
this.resize();
};
ControlElements.prototype.resize = function (resolve, reject) {
var _this = this;
// scrollbar things
// Element.offsetWidth - Element.clientWidth
this.list.style.width = "100%";
this.el.classList.remove("resized");
this.el.classList.remove("one-row");
this.el.classList.remove("two-row");
this.elementWidth = 0;
setTimeout(function () {
_this.listWidth = 0;
var elements = _this.getElements();
if (elements.length > 0) {
var listWidthValues = [];
var listWidthValues2 = [];
var containsElementWithImage = false;
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.visible) {
element.calcPosition();
_this.listWidth += element.positionVector.width;
listWidthValues.push(element.positionVector.x + element.positionVector.width);
listWidthValues2.push(element);
}
if (element.hasImage())
containsElementWithImage = true;
}
var elOffsetWidth_1 = _this.el.offsetWidth;
var isListWidthOverElementWidth_1 = _this.listWidth > elOffsetWidth_1;
if (isListWidthOverElementWidth_1 && !containsElementWithImage) {
_this.el.classList.add("two-row");
_this.listWidth = Math.max(elOffsetWidth_1, Math.round((listWidthValues[Math.floor(listWidthValues.length / 2)]) + 50));
_this.list.style.width = _this.listWidth + "px";
}
else {
_this.el.classList.add("one-row");
}
setTimeout(function () {
// recalc after LIST classes has been added
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.visible) {
element.calcPosition();
}
}
// check again after classes are set.
isListWidthOverElementWidth_1 = _this.listWidth > elOffsetWidth_1;
// sort the list so we can set tabIndex properly
var elementsCopyForSorting = elements.slice();
var tabIndexFilteredElements = elementsCopyForSorting.sort(function (a, b) {
var aOverB = a.positionVector.y > b.positionVector.y;
return a.positionVector.x == b.positionVector.x ? (aOverB ? 1 : -1) : a.positionVector.x < b.positionVector.x ? -1 : 1;
});
var tabIndex = 0;
for (var i = 0; i < tabIndexFilteredElements.length; i++) {
var element = tabIndexFilteredElements[i];
if (element.visible) {
//tabindex 1 are the UserInput element
element.tabIndex = 2 + (tabIndex++);
}
else {
element.tabIndex = -1;
}
}
// toggle nav button visiblity
cancelAnimationFrame(_this.rAF);
if (isListWidthOverElementWidth_1) {
_this.el.classList.remove("hide-nav-buttons");
}
else {
_this.el.classList.add("hide-nav-buttons");
}
_this.elementWidth = elOffsetWidth_1;
// resize scroll
_this.listScrollController.resize(_this.listWidth, _this.elementWidth);
_this.buildTabableRows();
_this.el.classList.add("resized");
}, 0);
}
if (resolve)
resolve();
}, 0);
};
ControlElements.prototype.dealloc = function () {
this.currentControlElement = null;
this.tableableRows = null;
cancelAnimationFrame(this.rAF);
this.rAF = null;
window.removeEventListener('resize', this.onResizeCallback, false);
this.onResizeCallback = null;
this.el.removeEventListener('scroll', this.onScrollCallback, false);
this.onScrollCallback = null;
this.eventTarget.removeEventListener(cf.ControlElementEvents.ON_FOCUS, this.onElementFocusCallback, false);
this.onElementFocusCallback = null;
this.eventTarget.removeEventListener(cf.ChatListEvents.CHATLIST_UPDATED, this.onChatReponsesUpdatedCallback, false);
this.onChatReponsesUpdatedCallback = null;
this.eventTarget.removeEventListener(cf.UserInputEvents.KEY_CHANGE, this.onUserInputKeyChangeCallback, false);
this.onUserInputKeyChangeCallback = null;
this.eventTarget.removeEventListener(cf.FlowEvents.USER_INPUT_UPDATE, this.userInputUpdateCallback, false);
this.userInputUpdateCallback = null;
this.eventTarget.removeEventListener(cf.ControlElementEvents.ON_LOADED, this.onElementLoadedCallback, false);
this.onElementLoadedCallback = null;
this.listScrollController.dealloc();
};
return ControlElements;
}());
cf.ControlElements = ControlElements;
})(cf || (cf = {}));
/// <reference path="../logic/Helpers.ts"/>
/// <reference path="../logic/EventDispatcher.ts"/>
// namespace
var cf;
(function (cf) {
var ScrollController = (function () {
function ScrollController(options) {
this.listWidth = 0;
this.visibleAreaWidth = 0;
this.max = 0;
this.interacting = false;
this.x = 0;
this.xTarget = 0;
this.startX = 0;
this.startXTarget = 0;
this.mouseSpeed = 0;
this.mouseSpeedTarget = 0;
this.direction = 0;
this.directionTarget = 0;
this.inputAccerlation = 0;
this.inputAccerlationTarget = 0;
this.interactionListener = options.interactionListener;
this.eventTarget = options.eventTarget;
this.listToScroll = options.listToScroll;
this.prevButton = options.listNavButtons[0];
this.nextButton = options.listNavButtons[1];
this.onListNavButtonsClickCallback = this.onListNavButtonsClick.bind(this);
this.prevButton.addEventListener("click", this.onListNavButtonsClickCallback, false);
this.nextButton.addEventListener("click", this.onListNavButtonsClickCallback, false);
this.documentLeaveCallback = this.documentLeave.bind(this);
this.onInteractStartCallback = this.onInteractStart.bind(this);
this.onInteractEndCallback = this.onInteractEnd.bind(this);
this.onInteractMoveCallback = this.onInteractMove.bind(this);
document.addEventListener("mouseleave", this.documentLeaveCallback, false);
document.addEventListener(cf.Helpers.getMouseEvent("mouseup"), this.documentLeaveCallback, false);
this.interactionListener.addEventListener(cf.Helpers.getMouseEvent("mousedown"), this.onInteractStartCallback, false);
this.interactionListener.addEventListener(cf.Helpers.getMouseEvent("mouseup"), this.onInteractEndCallback, false);
this.interactionListener.addEventListener(cf.Helpers.getMouseEvent("mousemove"), this.onInteractMoveCallback, false);
}
ScrollController.prototype.onListNavButtonsClick = function (event) {
var dirClick = event.currentTarget.getAttribute("direction");
this.pushDirection(dirClick == "next" ? -1 : 1);
};
ScrollController.prototype.documentLeave = function (event) {
this.onInteractEnd(event);
};
ScrollController.prototype.onInteractStart = function (event) {
var vector = cf.Helpers.getXYFromMouseTouchEvent(event);
this.interacting = true;
this.startX = vector.x;
this.startXTarget = this.startX;
this.inputAccerlation = 0;
this.render();
};
ScrollController.prototype.onInteractEnd = function (event) {
this.interacting = false;
};
ScrollController.prototype.onInteractMove = function (event) {
if (this.interacting) {
var vector = cf.Helpers.getXYFromMouseTouchEvent(event);
var newAcc = vector.x - this.startX;
var magnifier = 6.2;
this.inputAccerlationTarget = newAcc * magnifier;
this.directionTarget = this.inputAccerlationTarget < 0 ? -1 : 1;
this.startXTarget = vector.x;
}
};
ScrollController.prototype.render = function () {
var _this = this;
if (this.rAF)
cancelAnimationFrame(this.rAF);
// normalise startX
this.startX += (this.startXTarget - this.startX) * 0.2;
// animate accerlaration
this.inputAccerlation += (this.inputAccerlationTarget - this.inputAccerlation) * (this.interacting ? Math.min(ScrollController.accerlation + 0.1, 1) : ScrollController.accerlation);
var accDamping = 0.25;
this.inputAccerlationTarget *= accDamping;
// animate directions
this.direction += (this.directionTarget - this.direction) * 0.2;
// extra extra
this.mouseSpeed += (this.mouseSpeedTarget - this.mouseSpeed) * 0.2;
this.direction += this.mouseSpeed;
// animate x
this.xTarget += this.inputAccerlation * 0.05;
// bounce back when over
if (this.xTarget > 0)
this.xTarget += (0 - this.xTarget) * cf.Helpers.lerp(ScrollController.accerlation, 0.3, 0.8);
if (this.xTarget < this.max)
this.xTarget += (this.max - this.xTarget) * cf.Helpers.lerp(ScrollController.accerlation, 0.3, 0.8);
this.x += (this.xTarget - this.x) * 0.4;
// toggle visibility on nav arrows
var xRounded = Math.round(this.x);
if (xRounded < 0) {
if (!this.prevButton.classList.contains("active"))
this.prevButton.classList.add("active");
if (!this.prevButton.classList.contains("cf-gradient"))
this.prevButton.classList.add("cf-gradient");
}
if (xRounded == 0) {
if (this.prevButton.classList.contains("active"))
this.prevButton.classList.remove("active");
if (this.prevButton.classList.contains("cf-gradient"))
this.prevButton.classList.remove("cf-gradient");
}
if (xRounded > this.max) {
if (!this.nextButton.classList.contains("active"))
this.nextButton.classList.add("active");
if (!this.nextButton.classList.contains("cf-gradient"))
this.nextButton.classList.add("cf-gradient");
}
if (xRounded <= this.max) {
if (this.nextButton.classList.contains("active"))
this.nextButton.classList.remove("active");
if (this.nextButton.classList.contains("cf-gradient"))
this.nextButton.classList.remove("cf-gradient");
}
// set css transforms
var xx = this.x;
cf.Helpers.setTransform(this.listToScroll, "translateX(" + xx + "px)");
// cycle render
if (this.interacting || (Math.abs(this.x - this.xTarget) > 0.02 && !this.interacting))
this.rAF = window.requestAnimationFrame(function () { return _this.render(); });
};
ScrollController.prototype.setScroll = function (x, y) {
this.xTarget = this.visibleAreaWidth == this.listWidth ? 0 : x;
this.render();
};
ScrollController.prototype.pushDirection = function (dir) {
this.inputAccerlationTarget += (5000) * dir;
this.render();
};
ScrollController.prototype.dealloc = function () {
this.prevButton.removeEventListener("click", this.onListNavButtonsClickCallback, false);
this.nextButton.removeEventListener("click", this.onListNavButtonsClickCallback, false);
this.onListNavButtonsClickCallback = null;
this.prevButton = null;
this.nextButton = null;
document.removeEventListener("mouseleave", this.documentLeaveCallback, false);
document.removeEventListener(cf.Helpers.getMouseEvent("mouseup"), this.documentLeaveCallback, false);
this.interactionListener.removeEventListener(cf.Helpers.getMouseEvent("mousedown"), this.onInteractStartCallback, false);
this.interactionListener.removeEventListener(cf.Helpers.getMouseEvent("mouseup"), this.onInteractEndCallback, false);
this.interactionListener.removeEventListener(cf.Helpers.getMouseEvent("mousemove"), this.onInteractMoveCallback, false);
this.documentLeaveCallback = null;
this.onInteractStartCallback = null;
this.onInteractEndCallback = null;
this.onInteractMoveCallback = null;
};
ScrollController.prototype.reset = function () {
this.interacting = false;
this.startX = 0;
this.startXTarget = this.startX;
this.inputAccerlation = 0;
this.x = 0;
this.xTarget = 0;
cf.Helpers.setTransform(this.listToScroll, "translateX(0px)");
this.render();
this.prevButton.classList.remove("active");
this.nextButton.classList.remove("active");
};
ScrollController.prototype.resize = function (listWidth, visibleAreaWidth) {
this.reset();
this.visibleAreaWidth = visibleAreaWidth;
this.listWidth = Math.max(visibleAreaWidth, listWidth);
this.max = (this.listWidth - this.visibleAreaWidth) * -1;
this.render();
};
return ScrollController;
}());
ScrollController.accerlation = 0.1;
cf.ScrollController = ScrollController;
})(cf || (cf = {}));
// namespace
var cf;
(function (cf) {
// class
var Dictionary = (function () {
function Dictionary(options) {
// can be overwritten
this.data = {
"user-image": "//conversational-form-static-0iznjsw.stackpathdns.com/src/images/human.png",
"entry-not-found": "Dictionary item not found.",
"input-placeholder": "Type your answer here ...",
"group-placeholder": "Type to filter list ...",
"input-placeholder-error": "Your input is not correct ...",
"input-placeholder-required": "Input is required ...",
"input-placeholder-file-error": "File upload failed ...",
"input-placeholder-file-size-error": "File size too big ...",
"input-no-filter": "No results found for <strong>{input-value}</strong>",
"user-reponse-and": " and ",
"user-reponse-missing": "Missing input ...",
"user-reponse-missing-group": "Nothing selected ...",
"general": "General type1|General type2",
"icon-type-file": "<svg class='cf-icon-file' viewBox='0 0 10 14' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><g stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'><g transform='translate(-756.000000, -549.000000)' fill='#0D83FF'><g transform='translate(736.000000, 127.000000)'><g transform='translate(0.000000, 406.000000)'><polygon points='20 16 26.0030799 16 30 19.99994 30 30 20 30'></polygon></g></g></g></g></svg>",
};
// can be overwriten
this.robotData = {
"robot-image": "//conversational-form-static-0iznjsw.stackpathdns.com/src/images/robot.png",
"input": "Please write some text.",
"text": "Please write some text.",
"checkbox": "Select as many as you want.",
"name": "What's your name?",
"email": "Need your e-mail.",
"password": "<PASSWORD>",
"tel": "What's your phone number?",
"radio": "I need you to select one of these.",
"select": "Choose any of these options.",
"general": "General1|General2|General3.."
};
Dictionary.instance = this;
// overwrite data if defined
if (options && options.data)
this.data = this.validateAndSetNewData(options.data, this.data);
// overwrite user image
if (options.userImage)
this.data["user-image"] = options.userImage;
// overwrite robot image
if (options.robotImage)
this.robotData["robot-image"] = options.robotImage;
// overwrite robot questions if defined
if (options && options.robotData)
this.robotData = this.validateAndSetNewData(options.robotData, this.robotData);
}
Dictionary.get = function (id) {
var ins = Dictionary.instance;
var value = ins.data[id];
if (!value) {
value = ins.data["entry-not-found"];
}
else {
var values = value.split("|");
value = values[Math.floor(Math.random() * values.length)];
}
return value;
};
/**
* @name set
* set a dictionary value
* id: string, id of the value to update
* type: string, "human" || "robot"
* value: string, value to be inserted
*/
Dictionary.set = function (id, type, value) {
var ins = Dictionary.instance;
var obj = type == "robot" ? ins.robotData : ins.data;
obj[id] = value;
return obj[id];
};
Dictionary.getRobotResponse = function (tagType) {
var ins = Dictionary.instance;
var value = ins.robotData[tagType];
if (!value) {
// value not found, so pick a general one
var generals = ins.robotData["general"].split("|");
value = generals[Math.floor(Math.random() * generals.length)];
}
else {
var values = value.split("|");
value = values[Math.floor(Math.random() * values.length)];
}
return value;
};
Dictionary.parseAndGetMultiValueString = function (arr) {
// check ControlElement.ts for value(s)
var value = "";
for (var i = 0; i < arr.length; i++) {
var str = arr[i];
var sym = (arr.length > 1 && i == arr.length - 2 ? Dictionary.get("user-reponse-and") : ", ");
value += str + (i < arr.length - 1 ? sym : "");
}
return value;
};
Dictionary.prototype.validateAndSetNewData = function (newData, originalDataObject) {
for (var key in originalDataObject) {
if (!newData[key]) {
console.warn("Conversational Form Dictionary warning, '" + key + "' value is undefined, mapping '" + key + "' to default value. See Dictionary.ts for keys.");
newData[key] = originalDataObject[key];
}
}
return newData;
};
return Dictionary;
}());
Dictionary.keyCodes = {
"left": 37,
"right": 39,
"down": 40,
"up": 38,
"backspace": 8,
"enter": 13,
"space": 32,
"shift": 16,
"tab": 9,
};
cf.Dictionary = Dictionary;
})(cf || (cf = {}));
/// <reference path="../data/Dictionary.ts"/>
/// <reference path="InputTag.ts"/>
/// <reference path="ButtonTag.ts"/>
/// <reference path="SelectTag.ts"/>
/// <reference path="OptionTag.ts"/>
/// <reference path="../ConversationalForm.ts"/>
/// <reference path="../logic/EventDispatcher.ts"/>
// basic tag from form logic
// types:
// radio
// text
// email
// tel
// password
// checkbox
// radio
// select
// button
// namespace
var cf;
(function (cf) {
cf.TagEvents = {
ORIGINAL_ELEMENT_CHANGED: "cf-tag-dom-element-changed"
};
// class
var Tag = (function () {
function Tag(options) {
this.domElement = options.domElement;
this.changeCallback = this.onDomElementChange.bind(this);
this.domElement.addEventListener("change", this.changeCallback, false);
// remove tabIndex from the dom element.. danger zone... should we or should we not...
this.domElement.tabIndex = -1;
// questions array
if (options.questions)
this.questions = options.questions;
// custom tag validation
if (this.domElement.getAttribute("cf-validation")) {
// set it through an attribute, danger land with eval
this.validationCallback = eval(this.domElement.getAttribute("cf-validation"));
}
// reg ex pattern is set on the Tag, so use it in our validation
if (this.domElement.getAttribute("pattern"))
this.pattern = new RegExp(this.domElement.getAttribute("pattern"));
// if(this.type == "email" && !this.pattern){
// // set a standard e-mail pattern for email type input
// this.pattern = new RegExp("^[^@]+@[^@]+\.[^@]+$");
// }
if (this.type != "group" && cf.ConversationalForm.illustrateAppFlow) {
console.log('Conversational Form > Tag registered:', this.type, this);
}
this.refresh();
}
Object.defineProperty(Tag.prototype, "type", {
get: function () {
return this.domElement.getAttribute("type") || this.domElement.tagName.toLowerCase();
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "name", {
get: function () {
return this.domElement.getAttribute("name");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "inputPlaceholder", {
get: function () {
return this._inputPlaceholder;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "label", {
get: function () {
if (!this._label)
this.findAndSetLabel();
if (this._label)
return this._label;
return cf.Dictionary.getRobotResponse(this.type);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "value", {
get: function () {
return this.domElement.value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "hasImage", {
get: function () {
return this.domElement.hasAttribute("cf-image");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "disabled", {
get: function () {
return this.domElement.getAttribute("disabled") != undefined && this.domElement.getAttribute("disabled") != null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "required", {
get: function () {
return !!this.domElement.getAttribute("required") || this.domElement.getAttribute("required") == "";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "question", {
get: function () {
// if questions are empty, then fall back to dictionary, every time
if (!this.questions || this.questions.length == 0)
return cf.Dictionary.getRobotResponse(this.type);
else
return this.questions[Math.floor(Math.random() * this.questions.length)];
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "eventTarget", {
set: function (value) {
this._eventTarget = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Tag.prototype, "errorMessage", {
get: function () {
if (!this.errorMessages) {
// custom tag error messages
if (this.domElement.getAttribute("cf-error")) {
this.errorMessages = this.domElement.getAttribute("cf-error").split("|");
}
else if (this.domElement.parentNode && this.domElement.parentNode.getAttribute("cf-error")) {
this.errorMessages = this.domElement.parentNode.getAttribute("cf-error").split("|");
}
else if (this.required) {
this.errorMessages = [cf.Dictionary.get("input-placeholder-required")];
}
else {
if (this.type == "file")
this.errorMessages = [cf.Dictionary.get("input-placeholder-file-error")];
else {
this.errorMessages = [cf.Dictionary.get("input-placeholder-error")];
}
}
}
return this.errorMessages[Math.floor(Math.random() * this.errorMessages.length)];
},
enumerable: true,
configurable: true
});
Tag.prototype.dealloc = function () {
this.domElement.removeEventListener("change", this.changeCallback, false);
this.changeCallback = null;
this.domElement = null;
this.defaultValue = null;
this.errorMessages = null;
this.pattern = null;
this._label = null;
this.validationCallback = null;
this.questions = null;
};
Tag.isTagValid = function (element) {
if (element.getAttribute("type") === "hidden")
return false;
if (element.getAttribute("type") === "submit")
return false;
// ignore buttons, we submit the form automatially
if (element.getAttribute("type") == "button")
return false;
if (element.style.display === "none")
return false;
if (element.style.visibility === "hidden")
return false;
var innerText = cf.Helpers.getInnerTextOfElement(element);
if (element.tagName.toLowerCase() == "option" && (innerText == "" || innerText == " ")) {
return false;
}
if (element.tagName.toLowerCase() == "select" || element.tagName.toLowerCase() == "option")
return true;
else {
return !!(element.offsetWidth || element.offsetHeight || element.getClientRects().length);
}
};
Tag.createTag = function (element) {
if (Tag.isTagValid(element)) {
// ignore hidden tags
var tag = void 0;
if (element.tagName.toLowerCase() == "input") {
tag = new cf.InputTag({
domElement: element
});
}
else if (element.tagName.toLowerCase() == "textarea") {
tag = new cf.InputTag({
domElement: element
});
}
else if (element.tagName.toLowerCase() == "select") {
tag = new cf.SelectTag({
domElement: element
});
}
else if (element.tagName.toLowerCase() == "button") {
tag = new cf.ButtonTag({
domElement: element
});
}
else if (element.tagName.toLowerCase() == "option") {
tag = new cf.OptionTag({
domElement: element
});
}
return tag;
}
else {
// console.warn("Tag is not valid!: "+ element);
return null;
}
};
Tag.prototype.refresh = function () {
// default value of Tag, check every refresh
this.defaultValue = this.domElement.value;
this.questions = null;
this.findAndSetQuestions();
};
Tag.prototype.setTagValueAndIsValid = function (dto) {
// this sets the value of the tag in the DOM
// validation
var isValid = true;
var valueText = dto.text;
if (this.pattern) {
isValid = this.pattern.test(valueText);
}
if (valueText == "" && this.required) {
isValid = false;
}
var min = parseInt(this.domElement.getAttribute("min"), 10) || -1;
var max = parseInt(this.domElement.getAttribute("max"), 10) || -1;
if (min != -1 && valueText.length < min) {
isValid = false;
}
if (max != -1 && valueText.length > max) {
isValid = false;
}
if (isValid) {
// we cannot set the dom element value when type is file
if (this.type != "file")
this.domElement.value = valueText;
}
else {
// throw new Error("cf-: value:string is not valid. Value: "+value);
}
return isValid;
};
Tag.prototype.findAndSetQuestions = function () {
if (this.questions)
return;
// <label tag with label:for attribute to el:id
// check for label tag, we only go 2 steps backwards..
// from standardize markup: http://www.w3schools.com/tags/tag_label.asp
if (this.domElement.getAttribute("cf-questions")) {
this.questions = this.domElement.getAttribute("cf-questions").split("|");
if (this.domElement.getAttribute("cf-input-placeholder"))
this._inputPlaceholder = this.domElement.getAttribute("cf-input-placeholder");
}
else if (this.domElement.parentNode && this.domElement.parentNode.getAttribute("cf-questions")) {
// for groups the parentNode can have the cf-questions..
var parent_1 = this.domElement.parentNode;
this.questions = parent_1.getAttribute("cf-questions").split("|");
if (parent_1.getAttribute("cf-input-placeholder"))
this._inputPlaceholder = parent_1.getAttribute("cf-input-placeholder");
}
else {
// questions not set, so find it in the DOM
// try a broader search using for and id attributes
var elId = this.domElement.getAttribute("id");
var forLabel = document.querySelector("label[for='" + elId + "']");
if (forLabel) {
this.questions = [cf.Helpers.getInnerTextOfElement(forLabel)];
}
}
if (!this.questions && this.domElement.getAttribute("placeholder")) {
// check for placeholder attr if questions are still undefined
this.questions = [this.domElement.getAttribute("placeholder")];
}
};
Tag.prototype.findAndSetLabel = function () {
// find label..
if (this.domElement.getAttribute("cf-label")) {
this._label = this.domElement.getAttribute("cf-label");
}
else {
var parentDomNode = this.domElement.parentNode;
if (parentDomNode) {
// step backwards and check for label tag.
var labelTags = parentDomNode.getElementsByTagName("label");
if (labelTags.length == 0) {
// check for innerText
var innerText = cf.Helpers.getInnerTextOfElement(parentDomNode);
if (innerText && innerText.length > 0)
labelTags = [parentDomNode];
}
if (labelTags.length > 0 && labelTags[0])
this._label = cf.Helpers.getInnerTextOfElement(labelTags[0]);
}
}
};
/**
* @name onDomElementChange
* on dom element value change event, ex. w. browser autocomplete mode
*/
Tag.prototype.onDomElementChange = function () {
this._eventTarget.dispatchEvent(new CustomEvent(cf.TagEvents.ORIGINAL_ELEMENT_CHANGED, {
detail: {
value: this.value,
tag: this
}
}));
};
return Tag;
}());
cf.Tag = Tag;
})(cf || (cf = {}));
/// <reference path="ButtonTag.ts"/>
/// <reference path="InputTag.ts"/>
/// <reference path="SelectTag.ts"/>
/// <reference path="../ui/UserInput.ts"/>
// group tags together, this is done automatically by looking through InputTags with type radio or checkbox and same name attribute.
// single choice logic for Radio Button, <input type="radio", where name is the same
// multi choice logic for Checkboxes, <input type="checkbox", where name is the same
// namespace
var cf;
(function (cf) {
// class
var TagGroup = (function () {
function TagGroup(options) {
this.elements = options.elements;
if (cf.ConversationalForm.illustrateAppFlow)
console.log('Conversational Form > TagGroup registered:', this.elements[0].type, this);
}
Object.defineProperty(TagGroup.prototype, "required", {
get: function () {
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
if (this.elements[i].required) {
return true;
}
}
return false;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "eventTarget", {
set: function (value) {
this._eventTarget = value;
for (var i = 0; i < this.elements.length; i++) {
var tag = this.elements[i];
tag.eventTarget = value;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "type", {
get: function () {
return "group";
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "name", {
get: function () {
return this.elements[0].name;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "label", {
get: function () {
return this.elements[0].label;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "question", {
get: function () {
// check if elements have the questions, else fallback
var tagQuestion = this.elements[0].question;
if (tagQuestion) {
return tagQuestion;
}
else {
// fallback to robot response from dictionary
var robotReponse = cf.Dictionary.getRobotResponse(this.getGroupTagType());
return robotReponse;
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "activeElements", {
get: function () {
return this._activeElements;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "value", {
get: function () {
// TODO: fix value???
return this._values;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "disabled", {
get: function () {
var disabled = false;
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
if (element.disabled)
disabled = true;
}
return disabled;
},
enumerable: true,
configurable: true
});
Object.defineProperty(TagGroup.prototype, "errorMessage", {
get: function () {
var errorMessage = cf.Dictionary.get("input-placeholder-error");
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
errorMessage = element.errorMessage;
}
return errorMessage;
},
enumerable: true,
configurable: true
});
TagGroup.prototype.dealloc = function () {
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
element.dealloc();
}
this.elements = null;
};
TagGroup.prototype.refresh = function () {
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
element.refresh();
}
};
TagGroup.prototype.getGroupTagType = function () {
return this.elements[0].type;
};
TagGroup.prototype.setTagValueAndIsValid = function (value) {
var isValid = false;
var groupType = this.elements[0].type;
this._values = [];
this._activeElements = [];
switch (groupType) {
case "radio":
var numberRadioButtonsVisible = [];
var wasRadioButtonChecked = false;
for (var i = 0; i < value.controlElements.length; i++) {
var element = value.controlElements[i];
var tag = this.elements[this.elements.indexOf(element.referenceTag)];
if (element.visible) {
numberRadioButtonsVisible.push(element);
if (tag == element.referenceTag) {
tag.domElement.checked = element.checked;
if (element.checked) {
this._values.push(tag.value);
this._activeElements.push(tag);
}
// a radio button was checked
if (!wasRadioButtonChecked && element.checked)
wasRadioButtonChecked = true;
}
}
}
// special case 1, only one radio button visible from a filter
if (!isValid && numberRadioButtonsVisible.length == 1) {
var element = numberRadioButtonsVisible[0];
var tag = this.elements[this.elements.indexOf(element.referenceTag)];
element.checked = true;
tag.domElement.checked = true;
isValid = true;
if (element.checked) {
this._values.push(tag.value);
this._activeElements.push(tag);
}
}
else if (!isValid && wasRadioButtonChecked) {
// a radio button needs to be checked of
isValid = wasRadioButtonChecked;
}
break;
case "checkbox":
// checkbox is always valid
isValid = true;
for (var i = 0; i < value.controlElements.length; i++) {
var element = value.controlElements[i];
var tag = this.elements[this.elements.indexOf(element.referenceTag)];
tag.domElement.checked = element.checked;
if (element.checked) {
this._values.push(tag.value);
this._activeElements.push(tag);
}
}
break;
}
return isValid;
};
return TagGroup;
}());
cf.TagGroup = TagGroup;
})(cf || (cf = {}));
/// <reference path="Tag.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var InputTag = (function (_super) {
__extends(InputTag, _super);
function InputTag(options) {
var _this = _super.call(this, options) || this;
if (_this.type == "text") {
}
else if (_this.type == "email") {
}
else if (_this.type == "tel") {
}
else if (_this.type == "checkbox") {
}
else if (_this.type == "radio") {
}
else if (_this.type == "password") {
}
else if (_this.type == "file") {
// check InputFileTag.ts
}
return _this;
}
InputTag.prototype.findAndSetQuestions = function () {
_super.prototype.findAndSetQuestions.call(this);
// special use cases for <input> tag add here...
};
InputTag.prototype.findAndSetLabel = function () {
_super.prototype.findAndSetLabel.call(this);
if (!this._label) {
// special use cases for <input> tag add here...
}
};
InputTag.prototype.setTagValueAndIsValid = function (value) {
if (this.type == "checkbox") {
// checkbox is always true..
return true;
}
else {
return _super.prototype.setTagValueAndIsValid.call(this, value);
}
};
InputTag.prototype.dealloc = function () {
_super.prototype.dealloc.call(this);
};
return InputTag;
}(cf.Tag));
cf.InputTag = InputTag;
})(cf || (cf = {}));
/// <reference path="Tag.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var SelectTag = (function (_super) {
__extends(SelectTag, _super);
function SelectTag(options) {
var _this = _super.call(this, options) || this;
// build the option tags
_this.optionTags = [];
var domOptionTags = _this.domElement.getElementsByTagName("option");
for (var i = 0; i < domOptionTags.length; i++) {
var element = domOptionTags[i];
var tag = cf.Tag.createTag(element);
if (tag) {
_this.optionTags.push(tag);
}
else {
// console.warn((<any>this.constructor).name, 'option tag invalid:', tag);
}
}
return _this;
}
Object.defineProperty(SelectTag.prototype, "type", {
get: function () {
return "select";
},
enumerable: true,
configurable: true
});
Object.defineProperty(SelectTag.prototype, "value", {
get: function () {
return this._values;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SelectTag.prototype, "multipleChoice", {
get: function () {
return this.domElement.hasAttribute("multiple");
},
enumerable: true,
configurable: true
});
SelectTag.prototype.setTagValueAndIsValid = function (dto) {
var isValid = false;
// select tag values are set via selected attribute on option tag
var numberOptionButtonsVisible = [];
this._values = [];
for (var i = 0; i < this.optionTags.length; i++) {
var tag = this.optionTags[i];
for (var j = 0; j < dto.controlElements.length; j++) {
var controllerElement = dto.controlElements[j];
if (controllerElement.referenceTag == tag) {
// tag match found, so set value
tag.selected = controllerElement.selected;
// check for minimum one selected
if (!isValid && tag.selected)
isValid = true;
if (tag.selected)
this._values.push(tag.value);
if (controllerElement.visible)
numberOptionButtonsVisible.push(controllerElement);
}
}
}
// special case 1, only one optiontag visible from a filter
if (!isValid && numberOptionButtonsVisible.length == 1) {
var element = numberOptionButtonsVisible[0];
var tag = this.optionTags[this.optionTags.indexOf(element.referenceTag)];
element.selected = true;
tag.selected = true;
isValid = true;
if (tag.selected)
this._values.push(tag.value);
}
return isValid;
};
return SelectTag;
}(cf.Tag));
cf.SelectTag = SelectTag;
})(cf || (cf = {}));
/// <reference path="Tag.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var ButtonTag = (function (_super) {
__extends(ButtonTag, _super);
function ButtonTag(options) {
var _this = _super.call(this, options) || this;
if (_this.domElement.getAttribute("type") == "submit") {
}
else if (_this.domElement.getAttribute("type") == "button") {
// this.onClick = eval(this.domElement.onclick);
}
return _this;
}
return ButtonTag;
}(cf.Tag));
cf.ButtonTag = ButtonTag;
})(cf || (cf = {}));
/// <reference path="Tag.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var OptionTag = (function (_super) {
__extends(OptionTag, _super);
function OptionTag() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(OptionTag.prototype, "type", {
get: function () {
return "option";
},
enumerable: true,
configurable: true
});
Object.defineProperty(OptionTag.prototype, "label", {
get: function () {
return cf.Helpers.getInnerTextOfElement(this.domElement);
},
enumerable: true,
configurable: true
});
Object.defineProperty(OptionTag.prototype, "selected", {
get: function () {
return this.domElement.selected;
},
set: function (value) {
if (value)
this.domElement.setAttribute("selected", "selected");
else
this.domElement.removeAttribute("selected");
},
enumerable: true,
configurable: true
});
OptionTag.prototype.setTagValueAndIsValid = function (value) {
var isValid = true;
// OBS: No need to set any validation og value for this tag type ..
// .. it is atm. only used to create pseudo elements in the OptionsList
return isValid;
};
return OptionTag;
}(cf.Tag));
cf.OptionTag = OptionTag;
})(cf || (cf = {}));
/// <reference path="ControlElement.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var Button = (function (_super) {
__extends(Button, _super);
function Button(options) {
var _this = _super.call(this, options) || this;
_this.clickCallback = _this.onClick.bind(_this);
_this.el.addEventListener("click", _this.clickCallback, false);
_this.mouseDownCallback = _this.onMouseDown.bind(_this);
_this.el.addEventListener("mousedown", _this.mouseDownCallback, false);
//image
_this.checkForImage();
return _this;
}
Object.defineProperty(Button.prototype, "type", {
get: function () {
return "Button";
},
enumerable: true,
configurable: true
});
Button.prototype.hasImage = function () {
return this.referenceTag.hasImage;
};
/**
* @name checkForImage
* checks if element has cf-image, if it has then change UI
*/
Button.prototype.checkForImage = function () {
var hasImage = this.hasImage();
if (hasImage) {
this.el.classList.add("has-image");
this.imgEl = document.createElement("img");
this.imageLoadedCallback = this.onImageLoaded.bind(this);
this.imgEl.classList.add("cf-image");
this.imgEl.addEventListener("load", this.imageLoadedCallback, false);
this.imgEl.src = this.referenceTag.domElement.getAttribute("cf-image");
this.el.insertBefore(this.imgEl, this.el.children[0]);
}
};
Button.prototype.onImageLoaded = function () {
this.imgEl.classList.add("loaded");
this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.ON_LOADED, {}));
};
Button.prototype.onMouseDown = function (event) {
event.preventDefault();
};
Button.prototype.onClick = function (event) {
this.onChoose();
};
Button.prototype.dealloc = function () {
this.el.removeEventListener("click", this.clickCallback, false);
this.clickCallback = null;
if (this.imageLoadedCallback) {
this.imgEl.removeEventListener("load", this.imageLoadedCallback, false);
this.imageLoadedCallback = null;
}
this.el.removeEventListener("mousedown", this.mouseDownCallback, false);
this.mouseDownCallback = null;
_super.prototype.dealloc.call(this);
};
// override
Button.prototype.getTemplate = function () {
return "<cf-button class=\"cf-button\">\n\t\t\t\t" + this.referenceTag.label + "\n\t\t\t</cf-button>\n\t\t\t";
};
return Button;
}(cf.ControlElement));
cf.Button = Button;
})(cf || (cf = {}));
/// <reference path="Button.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var RadioButton = (function (_super) {
__extends(RadioButton, _super);
function RadioButton() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(RadioButton.prototype, "type", {
get: function () {
return "RadioButton";
},
enumerable: true,
configurable: true
});
Object.defineProperty(RadioButton.prototype, "checked", {
get: function () {
var _checked = this.el.hasAttribute("checked") && this.el.getAttribute("checked") == "checked";
return _checked;
},
set: function (value) {
if (!value) {
this.el.removeAttribute("checked");
}
else {
this.el.setAttribute("checked", "checked");
}
},
enumerable: true,
configurable: true
});
RadioButton.prototype.onClick = function (event) {
this.checked = !this.checked;
_super.prototype.onClick.call(this, event);
};
// override
RadioButton.prototype.getTemplate = function () {
var isChecked = this.referenceTag.domElement.checked || this.referenceTag.domElement.hasAttribute("checked");
return "<cf-radio-button class=\"cf-button\" checked=" + (isChecked ? "checked" : "") + ">\n\t\t\t\t<div>\n\t\t\t\t\t<cf-radio></cf-radio>\n\t\t\t\t\t" + this.referenceTag.label + "\n\t\t\t\t</div>\n\t\t\t</cf-radio-button>\n\t\t\t";
};
return RadioButton;
}(cf.Button));
cf.RadioButton = RadioButton;
})(cf || (cf = {}));
/// <reference path="Button.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var CheckboxButton = (function (_super) {
__extends(CheckboxButton, _super);
function CheckboxButton() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(CheckboxButton.prototype, "type", {
get: function () {
return "CheckboxButton";
},
enumerable: true,
configurable: true
});
Object.defineProperty(CheckboxButton.prototype, "checked", {
get: function () {
return this.el.getAttribute("checked") == "checked";
},
set: function (value) {
if (!value) {
this.el.removeAttribute("checked");
this.referenceTag.domElement.removeAttribute("checked");
}
else {
this.el.setAttribute("checked", "checked");
this.referenceTag.domElement.setAttribute("checked", "checked");
}
},
enumerable: true,
configurable: true
});
CheckboxButton.prototype.onClick = function (event) {
this.checked = !this.checked;
};
// override
CheckboxButton.prototype.getTemplate = function () {
var isChecked = this.referenceTag.domElement.checked && this.referenceTag.domElement.hasAttribute("checked");
return "<cf-button class=\"cf-button cf-checkbox-button " + (this.referenceTag.label.trim().length == 0 ? "no-text" : "") + "\" checked=" + (isChecked ? "checked" : "") + ">\n\t\t\t\t<div>\n\t\t\t\t\t<cf-checkbox></cf-checkbox>\n\t\t\t\t\t" + this.referenceTag.label + "\n\t\t\t\t</div>\n\t\t\t</cf-button>\n\t\t\t";
};
return CheckboxButton;
}(cf.Button));
cf.CheckboxButton = CheckboxButton;
})(cf || (cf = {}));
/// <reference path="Button.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
cf.OptionButtonEvents = {
CLICK: "cf-option-button-click"
};
// class
var OptionButton = (function (_super) {
__extends(OptionButton, _super);
function OptionButton() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.isMultiChoice = false;
return _this;
}
Object.defineProperty(OptionButton.prototype, "type", {
get: function () {
return "OptionButton";
},
enumerable: true,
configurable: true
});
Object.defineProperty(OptionButton.prototype, "selected", {
get: function () {
return this.el.hasAttribute("selected");
},
set: function (value) {
if (value) {
this.el.setAttribute("selected", "selected");
}
else {
this.el.removeAttribute("selected");
}
},
enumerable: true,
configurable: true
});
OptionButton.prototype.setData = function (options) {
this.isMultiChoice = options.isMultiChoice;
_super.prototype.setData.call(this, options);
};
OptionButton.prototype.onClick = function (event) {
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.OptionButtonEvents.CLICK, this);
this.eventTarget.dispatchEvent(new CustomEvent(cf.OptionButtonEvents.CLICK, {
detail: this
}));
};
// override
OptionButton.prototype.getTemplate = function () {
// be aware that first option element on none multiple select tags will be selected by default
var tmpl = '<cf-button class="cf-button ' + (this.isMultiChoice ? "cf-checkbox-button" : "") + '" ' + (this.referenceTag.domElement.selected ? "selected='selected'" : "") + '>';
tmpl += "<div>";
if (this.isMultiChoice)
tmpl += "<cf-checkbox></cf-checkbox>";
tmpl += this.referenceTag.label;
tmpl += "</div>";
tmpl += "</cf-button>";
return tmpl;
};
return OptionButton;
}(cf.Button));
cf.OptionButton = OptionButton;
})(cf || (cf = {}));
/// <reference path="ControlElement.ts"/>
/// <reference path="OptionButton.ts"/>
// namespace
var cf;
(function (cf) {
// interface
// class
// builds x OptionsButton from the registered SelectTag
var OptionsList = (function () {
function OptionsList(options) {
this.context = options.context;
this.eventTarget = options.eventTarget;
this.referenceTag = options.referenceTag;
// check for multi choice select tag
this.multiChoice = this.referenceTag.domElement.hasAttribute("multiple");
this.onOptionButtonClickCallback = this.onOptionButtonClick.bind(this);
this.eventTarget.addEventListener(cf.OptionButtonEvents.CLICK, this.onOptionButtonClickCallback, false);
this.createElements();
}
Object.defineProperty(OptionsList.prototype, "type", {
get: function () {
return "OptionsList";
},
enumerable: true,
configurable: true
});
OptionsList.prototype.getValue = function () {
var arr = [];
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
if (!this.multiChoice && element.selected) {
arr.push(element);
return arr;
}
else if (this.multiChoice && element.selected) {
arr.push(element);
}
}
return arr;
};
OptionsList.prototype.onOptionButtonClick = function (event) {
// if mutiple... then don remove selection on other buttons
var isMutiple = false;
if (!this.multiChoice) {
// only one is selectable at the time.
for (var i = 0; i < this.elements.length; i++) {
var element = this.elements[i];
if (element != event.detail) {
element.selected = false;
}
else {
element.selected = true;
}
}
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.ControlElementEvents.SUBMIT_VALUE, this.referenceTag);
this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.SUBMIT_VALUE, {
detail: event.detail
}));
}
else {
event.detail.selected = !event.detail.selected;
}
};
OptionsList.prototype.createElements = function () {
this.elements = [];
var optionTags = this.referenceTag.optionTags;
for (var i = 0; i < optionTags.length; i++) {
var tag = optionTags[i];
var btn = new cf.OptionButton({
referenceTag: tag,
isMultiChoice: this.referenceTag.multipleChoice,
eventTarget: this.eventTarget
});
this.elements.push(btn);
this.context.appendChild(btn.el);
}
};
OptionsList.prototype.dealloc = function () {
this.eventTarget.removeEventListener(cf.OptionButtonEvents.CLICK, this.onOptionButtonClickCallback, false);
this.onOptionButtonClickCallback = null;
while (this.elements.length > 0)
this.elements.pop().dealloc();
this.elements = null;
};
return OptionsList;
}());
cf.OptionsList = OptionsList;
})(cf || (cf = {}));
/// <reference path="Button.ts"/>
/// <reference path="../../logic/Helpers.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
// class
var UploadFileUI = (function (_super) {
__extends(UploadFileUI, _super);
function UploadFileUI(options) {
var _this = _super.call(this, options) || this;
_this.maxFileSize = 100000000000;
_this.loading = false;
_this.submitTimer = 0;
_this._fileName = "";
_this._readerResult = "";
if (cf.Helpers.caniuse.fileReader()) {
var maxFileSizeStr = _this.referenceTag.domElement.getAttribute("cf-max-size") || _this.referenceTag.domElement.getAttribute("max-size");
if (maxFileSizeStr) {
var maxFileSize = parseInt(maxFileSizeStr, 10);
_this.maxFileSize = maxFileSize;
}
_this.progressBar = _this.el.getElementsByTagName("cf-upload-file-progress-bar")[0];
_this.onDomElementChangeCallback = _this.onDomElementChange.bind(_this);
_this.referenceTag.domElement.addEventListener("change", _this.onDomElementChangeCallback, false);
}
else {
throw new Error("Conversational Form Error: No FileReader available for client.");
}
return _this;
}
Object.defineProperty(UploadFileUI.prototype, "value", {
get: function () {
return this.referenceTag.domElement.value; //;this.readerResult || this.fileName;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UploadFileUI.prototype, "readerResult", {
get: function () {
return this._readerResult;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UploadFileUI.prototype, "files", {
get: function () {
return this._files;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UploadFileUI.prototype, "fileName", {
get: function () {
return this._fileName;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UploadFileUI.prototype, "type", {
get: function () {
return "UploadFileUI";
},
enumerable: true,
configurable: true
});
UploadFileUI.prototype.getFilesAsString = function () {
// value is for the chat response -->
var icon = document.createElement("span");
icon.innerHTML = cf.Dictionary.get("icon-type-file") + this.fileName;
return icon.outerHTML;
};
UploadFileUI.prototype.onDomElementChange = function (event) {
var _this = this;
console.log("...onDomElementChange");
var reader = new FileReader();
this._files = this.referenceTag.domElement.files;
reader.onerror = function (event) {
console.log("onerror", event);
};
reader.onprogress = function (event) {
console.log("onprogress", event);
_this.progressBar.style.width = ((event.loaded / event.total) * 100) + "%";
};
reader.onabort = function (event) {
console.log("onabort", event);
};
reader.onloadstart = function (event) {
// check for file size
var file = _this.files[0];
var fileSize = file ? file.size : _this.maxFileSize + 1; // if file is undefined then abort ...
if (fileSize > _this.maxFileSize) {
reader.abort();
var dto = {
errorText: cf.Dictionary.get("input-placeholder-file-size-error")
};
cf.ConversationalForm.illustrateFlow(_this, "dispatch", cf.FlowEvents.USER_INPUT_INVALID, dto);
_this.eventTarget.dispatchEvent(new CustomEvent(cf.FlowEvents.USER_INPUT_INVALID, {
detail: dto
}));
}
else {
// good to go
_this._fileName = file.name;
_this.loading = true;
_this.animateIn();
// set text
var sizeConversion = Math.floor(Math.log(fileSize) / Math.log(1024));
var sizeChart = ["b", "kb", "mb", "gb"];
sizeConversion = Math.min(sizeChart.length - 1, sizeConversion);
var humanSizeString = Number((fileSize / Math.pow(1024, sizeConversion)).toFixed(2)) * 1 + " " + sizeChart[sizeConversion];
var text = file.name + " (" + humanSizeString + ")";
_this.el.getElementsByTagName("cf-upload-file-text")[0].innerHTML = text;
_this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.PROGRESS_CHANGE, {
detail: cf.ControlElementProgressStates.BUSY
}));
}
};
reader.onload = function (event) {
_this._readerResult = event.target.result;
_this.progressBar.classList.add("loaded");
_this.submitTimer = setTimeout(function () {
_this.el.classList.remove("animate-in");
_this.onChoose(); // submit the file
_this.eventTarget.dispatchEvent(new CustomEvent(cf.ControlElementEvents.PROGRESS_CHANGE, {
detail: cf.ControlElementProgressStates.READY
}));
}, 0);
};
reader.readAsDataURL(this.files[0]);
};
UploadFileUI.prototype.animateIn = function () {
if (this.loading)
_super.prototype.animateIn.call(this);
};
UploadFileUI.prototype.onClick = function (event) {
// super.onClick(event);
};
UploadFileUI.prototype.triggerFileSelect = function () {
// trigger file prompt
this.referenceTag.domElement.click();
};
// override
UploadFileUI.prototype.dealloc = function () {
clearTimeout(this.submitTimer);
this.progressBar = null;
if (this.onDomElementChangeCallback) {
this.referenceTag.domElement.removeEventListener("change", this.onDomElementChangeCallback, false);
this.onDomElementChangeCallback = null;
}
_super.prototype.dealloc.call(this);
};
UploadFileUI.prototype.getTemplate = function () {
var isChecked = this.referenceTag.value == "1" || this.referenceTag.domElement.hasAttribute("checked");
return "<cf-upload-file-ui>\n\t\t\t\t<cf-upload-file-text></cf-upload-file-text>\n\t\t\t\t<cf-upload-file-progress>\n\t\t\t\t\t<cf-upload-file-progress-bar></cf-upload-file-progress-bar>\n\t\t\t\t</cf-upload-file-progress>\n\t\t\t</cf-upload-file-ui>\n\t\t\t";
};
return UploadFileUI;
}(cf.Button));
cf.UploadFileUI = UploadFileUI;
})(cf || (cf = {}));
/// <reference path="BasicElement.ts"/>
/// <reference path="control-elements/ControlElements.ts"/>
/// <reference path="../logic/FlowManager.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
cf.UserInputEvents = {
SUBMIT: "cf-input-user-input-submit",
KEY_CHANGE: "cf-input-key-change",
CONTROL_ELEMENTS_ADDED: "cf-input-control-elements-added",
HEIGHT_CHANGE: "cf-input-height-change",
};
// class
var UserInput = (function (_super) {
__extends(UserInput, _super);
function UserInput(options) {
var _this = _super.call(this, options) || this;
_this.errorTimer = 0;
_this.initialInputHeight = 0;
_this.shiftIsDown = false;
_this._disabled = false;
//acts as a fallb ack for ex. shadow dom implementation
_this._active = false;
_this.cfReference = options.cfReference;
_this.eventTarget = options.eventTarget;
_this.inputElement = _this.el.getElementsByTagName("textarea")[0];
_this.onInputFocusCallback = _this.onInputFocus.bind(_this);
_this.onInputBlurCallback = _this.onInputBlur.bind(_this);
_this.inputElement.addEventListener('focus', _this.onInputFocusCallback, false);
_this.inputElement.addEventListener('blur', _this.onInputBlurCallback, false);
//<cf-input-control-elements> is defined in the ChatList.ts
_this.controlElements = new cf.ControlElements({
el: _this.el.getElementsByTagName("cf-input-control-elements")[0],
infoEl: _this.el.getElementsByTagName("cf-info")[0],
eventTarget: _this.eventTarget
});
// setup event listeners
_this.windowFocusCallback = _this.windowFocus.bind(_this);
window.addEventListener('focus', _this.windowFocusCallback, false);
_this.keyUpCallback = _this.onKeyUp.bind(_this);
document.addEventListener("keyup", _this.keyUpCallback, false);
_this.keyDownCallback = _this.onKeyDown.bind(_this);
document.addEventListener("keydown", _this.keyDownCallback, false);
_this.flowUpdateCallback = _this.onFlowUpdate.bind(_this);
_this.eventTarget.addEventListener(cf.FlowEvents.FLOW_UPDATE, _this.flowUpdateCallback, false);
_this.onOriginalTagChangedCallback = _this.onOriginalTagChanged.bind(_this);
_this.eventTarget.addEventListener(cf.TagEvents.ORIGINAL_ELEMENT_CHANGED, _this.onOriginalTagChangedCallback, false);
_this.inputInvalidCallback = _this.inputInvalid.bind(_this);
_this.eventTarget.addEventListener(cf.FlowEvents.USER_INPUT_INVALID, _this.inputInvalidCallback, false);
_this.onControlElementSubmitCallback = _this.onControlElementSubmit.bind(_this);
_this.eventTarget.addEventListener(cf.ControlElementEvents.SUBMIT_VALUE, _this.onControlElementSubmitCallback, false);
_this.onControlElementProgressChangeCallback = _this.onControlElementProgressChange.bind(_this);
_this.eventTarget.addEventListener(cf.ControlElementEvents.PROGRESS_CHANGE, _this.onControlElementProgressChangeCallback, false);
_this.submitButton = _this.el.getElementsByTagName("cf-input-button")[0];
_this.onSubmitButtonClickCallback = _this.onSubmitButtonClick.bind(_this);
_this.submitButton.addEventListener("click", _this.onSubmitButtonClickCallback, false);
return _this;
}
Object.defineProperty(UserInput.prototype, "active", {
get: function () {
return this.inputElement === document.activeElement || this._active;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserInput.prototype, "visible", {
set: function (value) {
if (!this.el.classList.contains("animate-in") && value)
this.el.classList.add("animate-in");
else if (this.el.classList.contains("animate-in") && !value)
this.el.classList.remove("animate-in");
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserInput.prototype, "currentTag", {
get: function () {
return this._currentTag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserInput.prototype, "disabled", {
set: function (value) {
var hasChanged = this._disabled != value;
if (hasChanged) {
this._disabled = value;
if (value) {
this.el.setAttribute("disabled", "disabled");
this.inputElement.blur();
}
else {
this.setFocusOnInput();
this.el.removeAttribute("disabled");
}
}
},
enumerable: true,
configurable: true
});
UserInput.prototype.getInputValue = function () {
var str = this.inputElement.value;
// Build-in way to handle XSS issues ->
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
};
UserInput.prototype.getFlowDTO = function () {
var value; // = this.inputElement.value;
// check for values on control elements as they should overwrite the input value.
if (this.controlElements && this.controlElements.active) {
value = this.controlElements.getDTO();
}
else {
value = {
text: this.getInputValue()
};
}
value.input = this;
return value;
};
UserInput.prototype.reset = function () {
if (this.controlElements) {
this.controlElements.clearTagsAndReset();
}
};
UserInput.prototype.onFlowStopped = function () {
if (this.controlElements)
this.controlElements.clearTagsAndReset();
this.disabled = true;
};
/**
* @name onOriginalTagChanged
* on domElement from a Tag value changed..
*/
UserInput.prototype.onOriginalTagChanged = function (event) {
if (this.currentTag == event.detail.tag) {
this.onInputChange();
}
if (this.controlElements && this.controlElements.active) {
this.controlElements.updateStateOnElementsFromTag(event.detail.tag);
}
};
UserInput.prototype.onInputChange = function () {
if (!this.active && !this.controlElements.active)
return;
// safari likes to jump around with the scrollHeight value, let's keep it in check with an initial height.
var oldHeight = Math.max(this.initialInputHeight, parseInt(this.inputElement.style.height, 10));
this.inputElement.style.height = "0px";
this.inputElement.style.height = (this.inputElement.scrollHeight === 0 ? oldHeight : this.inputElement.scrollHeight) + "px";
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.UserInputEvents.HEIGHT_CHANGE);
this.eventTarget.dispatchEvent(new CustomEvent(cf.UserInputEvents.HEIGHT_CHANGE, {
detail: this.inputElement.scrollHeight
}));
};
UserInput.prototype.inputInvalid = function (event) {
var _this = this;
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
var dto = event.detail;
this.inputElement.setAttribute("data-value", this.inputElement.value);
this.inputElement.value = "";
this.el.setAttribute("error", "");
this.disabled = true;
// cf-error
this.inputElement.setAttribute("placeholder", dto.errorText || this._currentTag.errorMessage);
clearTimeout(this.errorTimer);
this.errorTimer = setTimeout(function () {
_this.disabled = false;
_this.el.removeAttribute("error");
_this.inputElement.value = _this.inputElement.getAttribute("data-value");
_this.inputElement.setAttribute("data-value", "");
_this.setPlaceholder();
_this.setFocusOnInput();
if (_this.controlElements)
_this.controlElements.resetAfterErrorMessage();
}, UserInput.ERROR_TIME);
};
UserInput.prototype.setPlaceholder = function () {
if (this._currentTag) {
if (this._currentTag.inputPlaceholder) {
this.inputElement.setAttribute("placeholder", this._currentTag.inputPlaceholder);
}
else {
this.inputElement.setAttribute("placeholder", this._currentTag.type == "group" ? cf.Dictionary.get("group-placeholder") : cf.Dictionary.get("input-placeholder"));
}
}
else {
this.inputElement.setAttribute("placeholder", cf.Dictionary.get("group-placeholder"));
}
};
UserInput.prototype.checkForCorrectInputTag = function () {
// handle password natively
var currentType = this.inputElement.getAttribute("type");
var isCurrentInputTypeTextAreaButNewTagPassword = this._currentTag.type == "password" && currentType != "password";
var isCurrentInputTypeInputButNewTagNotPassword = this._currentTag.type != "password" && currentType == "password";
// remove focus and blur events, because we want to create a new element
if (this.inputElement && (isCurrentInputTypeTextAreaButNewTagPassword || isCurrentInputTypeInputButNewTagNotPassword)) {
this.inputElement.removeEventListener('focus', this.onInputFocusCallback, false);
this.inputElement.removeEventListener('blur', this.onInputBlurCallback, false);
}
if (isCurrentInputTypeTextAreaButNewTagPassword) {
// change to input
var input_1 = document.createElement("input");
Array.prototype.slice.call(this.inputElement.attributes).forEach(function (item) {
input_1.setAttribute(item.name, item.value);
});
input_1.setAttribute("autocomplete", "new-password");
this.inputElement.parentNode.replaceChild(input_1, this.inputElement);
this.inputElement = input_1;
}
else if (isCurrentInputTypeInputButNewTagNotPassword) {
// change to textarea
var textarea_1 = document.createElement("textarea");
Array.prototype.slice.call(this.inputElement.attributes).forEach(function (item) {
textarea_1.setAttribute(item.name, item.value);
});
this.inputElement.parentNode.replaceChild(textarea_1, this.inputElement);
this.inputElement = textarea_1;
}
// add focus and blur events to newly created input element
if (this.inputElement && (isCurrentInputTypeTextAreaButNewTagPassword || isCurrentInputTypeInputButNewTagNotPassword)) {
this.inputElement.addEventListener('focus', this.onInputFocusCallback, false);
this.inputElement.addEventListener('blur', this.onInputBlurCallback, false);
}
if (this.initialInputHeight == 0) {
// initial height not set
this.initialInputHeight = this.inputElement.offsetHeight;
}
};
UserInput.prototype.onFlowUpdate = function (event) {
var _this = this;
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
// animate input field in
this.visible = true;
this._currentTag = event.detail.tag;
this.el.setAttribute("tag-type", this._currentTag.type);
// replace textarea and visa versa
this.checkForCorrectInputTag();
// set input field to type password if the dom input field is that, covering up the input
this.inputElement.setAttribute("type", this._currentTag.type == "password" ? "password" : "input");
clearTimeout(this.errorTimer);
this.el.removeAttribute("error");
this.inputElement.setAttribute("data-value", "");
this.inputElement.value = "";
this.setPlaceholder();
this.resetValue();
if (!UserInput.preventAutoFocus)
this.setFocusOnInput();
this.controlElements.reset();
if (this._currentTag.type == "group") {
this.buildControlElements(this._currentTag.elements);
}
else {
this.buildControlElements([this._currentTag]);
}
if (this._currentTag.type == "text" || this._currentTag.type == "email") {
this.inputElement.value = this._currentTag.defaultValue.toString();
}
setTimeout(function () {
_this.disabled = false;
_this.onInputChange();
}, 150);
};
UserInput.prototype.onControlElementProgressChange = function (event) {
var status = event.detail;
this.disabled = status == cf.ControlElementProgressStates.BUSY;
};
UserInput.prototype.buildControlElements = function (tags) {
this.controlElements.buildTags(tags);
};
UserInput.prototype.onControlElementSubmit = function (event) {
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
// when ex a RadioButton is clicked..
var controlElement = event.detail;
this.controlElements.updateStateOnElements(controlElement);
this.doSubmit();
};
UserInput.prototype.onSubmitButtonClick = function (event) {
this.onEnterOrSubmitButtonSubmit(event);
};
UserInput.prototype.isMetaKeyPressed = function (event) {
// if any meta keys, then ignore, getModifierState, but safari does not support..
if (event.metaKey || [91, 93].indexOf(event.keyCode) !== -1)
return;
};
UserInput.prototype.onKeyDown = function (event) {
if (!this.active && !this.controlElements.focus)
return;
if (this.isMetaKeyPressed(event))
return;
// if any meta keys, then ignore
if (event.keyCode == cf.Dictionary.keyCodes["shift"])
this.shiftIsDown = true;
// prevent textarea line breaks
if (event.keyCode == cf.Dictionary.keyCodes["enter"] && !event.shiftKey) {
event.preventDefault();
}
};
UserInput.prototype.onKeyUp = function (event) {
if (!this.active && !this.controlElements.focus)
return;
if (this.isMetaKeyPressed(event))
return;
if (event.keyCode == cf.Dictionary.keyCodes["shift"]) {
this.shiftIsDown = false;
}
else if (event.keyCode == cf.Dictionary.keyCodes["up"]) {
event.preventDefault();
if (this.active && !this.controlElements.focus)
this.controlElements.focusFrom("bottom");
}
else if (event.keyCode == cf.Dictionary.keyCodes["down"]) {
event.preventDefault();
if (this.active && !this.controlElements.focus)
this.controlElements.focusFrom("top");
}
else if (event.keyCode == cf.Dictionary.keyCodes["tab"]) {
// tab key pressed, check if node is child of CF, if then then reset focus to input element
var doesKeyTargetExistInCF = false;
var node = event.target.parentNode;
while (node != null) {
if (node === this.cfReference.el) {
doesKeyTargetExistInCF = true;
break;
}
node = node.parentNode;
}
// prevent normal behaviour, we are not here to take part, we are here to take over!
if (!doesKeyTargetExistInCF) {
event.preventDefault();
if (!this.controlElements.active)
this.setFocusOnInput();
}
}
if (this.el.hasAttribute("disabled"))
return;
var value = this.getFlowDTO();
if ((event.keyCode == cf.Dictionary.keyCodes["enter"] && !event.shiftKey) || event.keyCode == cf.Dictionary.keyCodes["space"]) {
if (event.keyCode == cf.Dictionary.keyCodes["enter"] && this.active) {
event.preventDefault();
this.onEnterOrSubmitButtonSubmit();
}
else {
// either click on submit button or do something with control elements
if (event.keyCode == cf.Dictionary.keyCodes["enter"] || event.keyCode == cf.Dictionary.keyCodes["space"]) {
event.preventDefault();
var tagType = this._currentTag.type == "group" ? this._currentTag.getGroupTagType() : this._currentTag.type;
if (tagType == "select" || tagType == "checkbox") {
var mutiTag = this._currentTag;
// if select or checkbox then check for multi select item
if (tagType == "checkbox" || mutiTag.multipleChoice) {
if (this.active && event.keyCode == cf.Dictionary.keyCodes["enter"]) {
// click on UserInput submit button, only ENTER allowed
this.submitButton.click();
}
else {
// let UI know that we changed the key
this.dispatchKeyChange(value, event.keyCode);
if (!this.active) {
// after ui has been selected we RESET the input/filter
this.resetValue();
this.setFocusOnInput();
this.dispatchKeyChange(value, event.keyCode);
}
}
}
else {
this.dispatchKeyChange(value, event.keyCode);
}
}
else {
if (this._currentTag.type == "group") {
// let the controlements handle action
this.dispatchKeyChange(value, event.keyCode);
}
}
}
else if (event.keyCode == cf.Dictionary.keyCodes["space"] && document.activeElement) {
this.dispatchKeyChange(value, event.keyCode);
}
}
}
else if (event.keyCode != cf.Dictionary.keyCodes["shift"] && event.keyCode != cf.Dictionary.keyCodes["tab"]) {
this.dispatchKeyChange(value, event.keyCode);
}
this.onInputChange();
};
UserInput.prototype.dispatchKeyChange = function (dto, keyCode) {
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.UserInputEvents.KEY_CHANGE, dto);
this.eventTarget.dispatchEvent(new CustomEvent(cf.UserInputEvents.KEY_CHANGE, {
detail: {
dto: dto,
keyCode: keyCode,
inputFieldActive: this.active
}
}));
};
UserInput.prototype.windowFocus = function (event) {
if (!UserInput.preventAutoFocus)
this.setFocusOnInput();
};
UserInput.prototype.onInputBlur = function (event) {
this._active = false;
};
UserInput.prototype.onInputFocus = function (event) {
this._active = true;
this.onInputChange();
};
UserInput.prototype.setFocusOnInput = function () {
this.inputElement.focus();
};
UserInput.prototype.onEnterOrSubmitButtonSubmit = function (event) {
if (event === void 0) { event = null; }
if (this.active && this.controlElements.highlighted) {
// active input field and focus on control elements happens when a control element is highlighted
this.controlElements.clickOnHighlighted();
}
else {
if (!this._currentTag) {
// happens when a form is empty, so just play along and submit response to chatlist..
this.eventTarget.cf.addUserChatResponse(this.inputElement.value);
}
else {
// we need to check if current tag is file
if (this._currentTag.type == "file" && event) {
// trigger <input type="file" but only when it's from clicking button
this.controlElements.getElement(0).triggerFileSelect();
}
else {
// for groups, we expect that there is always a default value set
this.doSubmit();
}
}
}
};
UserInput.prototype.doSubmit = function () {
var dto = this.getFlowDTO();
this.disabled = true;
this.el.removeAttribute("error");
this.inputElement.setAttribute("data-value", "");
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.UserInputEvents.SUBMIT, dto);
this.eventTarget.dispatchEvent(new CustomEvent(cf.UserInputEvents.SUBMIT, {
detail: dto
}));
};
UserInput.prototype.resetValue = function () {
this.inputElement.value = "";
this.onInputChange();
};
UserInput.prototype.dealloc = function () {
this.inputElement.removeEventListener('blur', this.onInputBlurCallback, false);
this.onInputBlurCallback = null;
this.inputElement.removeEventListener('focus', this.onInputFocusCallback, false);
this.onInputFocusCallback = null;
window.removeEventListener('focus', this.windowFocusCallback, false);
this.windowFocusCallback = null;
document.removeEventListener("keydown", this.keyDownCallback, false);
this.keyDownCallback = null;
document.removeEventListener("keyup", this.keyUpCallback, false);
this.keyUpCallback = null;
this.eventTarget.removeEventListener(cf.FlowEvents.FLOW_UPDATE, this.flowUpdateCallback, false);
this.flowUpdateCallback = null;
this.eventTarget.removeEventListener(cf.FlowEvents.USER_INPUT_INVALID, this.inputInvalidCallback, false);
this.inputInvalidCallback = null;
this.eventTarget.removeEventListener(cf.ControlElementEvents.SUBMIT_VALUE, this.onControlElementSubmitCallback, false);
this.onControlElementSubmitCallback = null;
this.submitButton = this.el.getElementsByClassName("cf-input-button")[0];
this.submitButton.removeEventListener("click", this.onSubmitButtonClickCallback, false);
this.onSubmitButtonClickCallback = null;
_super.prototype.dealloc.call(this);
};
// override
UserInput.prototype.getTemplate = function () {
return "<cf-input>\n\t\t\t\t<cf-info></cf-info>\n\t\t\t\t<cf-input-control-elements>\n\t\t\t\t\t<cf-list-button direction=\"prev\">\n\t\t\t\t\t</cf-list-button>\n\t\t\t\t\t<cf-list-button direction=\"next\">\n\t\t\t\t\t</cf-list-button>\n\t\t\t\t\t<cf-list>\n\t\t\t\t\t</cf-list>\n\t\t\t\t</cf-input-control-elements>\n\n\t\t\t\t<cf-input-button class=\"cf-input-button\">\n\t\t\t\t\t<div class=\"cf-icon-progress\"></div>\n\t\t\t\t\t<div class=\"cf-icon-attachment\"></div>\n\t\t\t\t</cf-input-button>\n\t\t\t\t\n\t\t\t\t<textarea type='input' tabindex=\"1\" rows=\"1\"></textarea>\n\n\t\t\t</cf-input>\n\t\t\t";
};
return UserInput;
}(cf.BasicElement));
UserInput.preventAutoFocus = false;
UserInput.ERROR_TIME = 2000;
cf.UserInput = UserInput;
})(cf || (cf = {}));
/// <reference path="../BasicElement.ts"/>
/// <reference path="../../logic/Helpers.ts"/>
/// <reference path="../../ConversationalForm.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
cf.ChatResponseEvents = {
USER_ANSWER_CLICKED: "cf-on-user-answer-clicked",
};
// class
var ChatResponse = (function (_super) {
__extends(ChatResponse, _super);
function ChatResponse(options) {
var _this = _super.call(this, options) || this;
_this._tag = options.tag;
_this.textEl = _this.el.getElementsByTagName("text")[0];
return _this;
}
Object.defineProperty(ChatResponse.prototype, "tag", {
get: function () {
return this._tag;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ChatResponse.prototype, "disabled", {
get: function () {
return this.el.classList.contains("disabled");
},
set: function (value) {
this.el.classList.toggle("disabled", value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ChatResponse.prototype, "visible", {
set: function (value) {
if (value) {
this.el.classList.add("show");
}
else {
this.el.classList.remove("show");
}
},
enumerable: true,
configurable: true
});
ChatResponse.prototype.setValue = function (dto) {
if (dto === void 0) { dto = null; }
if (!this.visible) {
this.visible = true;
}
var isThinking = this.textEl.hasAttribute("thinking");
if (!dto) {
this.setToThinking();
}
else {
this.response = dto.text;
var processedResponse = this.processResponseAndSetText();
if (this.responseLink && !this.isRobotReponse) {
// call robot and update for binding values ->
this.responseLink.processResponseAndSetText();
}
// check for if response type is file upload...
if (dto && dto.controlElements && dto.controlElements[0]) {
switch (dto.controlElements[0].type) {
case "UploadFileUI":
this.textEl.classList.add("file-icon");
break;
}
}
if (!this.isRobotReponse && !this.onClickCallback) {
this.onClickCallback = this.onClick.bind(this);
this.el.addEventListener(cf.Helpers.getMouseEvent("click"), this.onClickCallback, false);
}
}
};
ChatResponse.prototype.hide = function () {
this.el.classList.remove("show");
this.disabled = true;
};
ChatResponse.prototype.show = function () {
this.el.classList.add("show");
this.disabled = false;
if (!this.response) {
this.setToThinking();
}
else {
this.checkForEditMode();
}
};
ChatResponse.prototype.updateThumbnail = function (src) {
this.image = src;
var thumbEl = this.el.getElementsByTagName("thumb")[0];
thumbEl.style.backgroundImage = "url(" + this.image + ")";
};
ChatResponse.prototype.setLinkToOtherReponse = function (response) {
// link reponse to another one, keeping the update circle complete.
this.responseLink = response;
};
ChatResponse.prototype.processResponseAndSetText = function () {
var _this = this;
var innerResponse = this.response;
if (this._tag && this._tag.type == "password" && !this.isRobotReponse) {
var newStr = "";
for (var i = 0; i < innerResponse.length; i++) {
newStr += "*";
}
innerResponse = newStr;
}
else {
innerResponse = cf.Helpers.emojify(innerResponse);
}
if (this.responseLink && this.isRobotReponse) {
// if robot, then check linked response for binding values
// one way data binding values:
innerResponse = innerResponse.split("{previous-answer}").join(this.responseLink.parsedResponse);
// add more..
// innerResponse = innerResponse.split("{...}").join(this.responseLink.parsedResponse);
}
// check if response contains an image as answer
var responseContains = innerResponse.indexOf("contains-image") != -1;
if (responseContains)
this.textEl.classList.add("contains-image");
// now set it
this.textEl.innerHTML = innerResponse;
this.parsedResponse = innerResponse;
// bounce
this.textEl.removeAttribute("thinking");
this.textEl.removeAttribute("value-added");
setTimeout(function () {
_this.textEl.setAttribute("value-added", "");
}, 0);
this.checkForEditMode();
return innerResponse;
};
ChatResponse.prototype.checkForEditMode = function () {
if (!this.isRobotReponse && !this.textEl.hasAttribute("thinking")) {
this.el.classList.add("can-edit");
this.disabled = false;
}
};
ChatResponse.prototype.setToThinking = function () {
this.textEl.innerHTML = ChatResponse.THINKING_MARKUP;
this.el.classList.remove("can-edit");
this.textEl.setAttribute("thinking", "");
};
/**
* @name onClickCallback
* click handler for el
*/
ChatResponse.prototype.onClick = function (event) {
this.setToThinking();
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.ChatResponseEvents.USER_ANSWER_CLICKED, event);
this.eventTarget.dispatchEvent(new CustomEvent(cf.ChatResponseEvents.USER_ANSWER_CLICKED, {
detail: this._tag
}));
};
ChatResponse.prototype.setData = function (options) {
var _this = this;
this.image = options.image;
this.response = "";
this.isRobotReponse = options.isRobotReponse;
_super.prototype.setData.call(this, options);
setTimeout(function () {
_this.setValue();
if (_this.isRobotReponse || options.response != null) {
// Robot is pseudo thinking, can also be user -->
// , but if addUserChatResponse is called from ConversationalForm, then the value is there, therefore skip ...
setTimeout(function () { return _this.setValue({ text: options.response }); }, 0); //ConversationalForm.animationsEnabled ? Helpers.lerp(Math.random(), 500, 900) : 0);
}
else {
// shows the 3 dots automatically, we expect the reponse to be empty upon creation
// TODO: Auto completion insertion point
setTimeout(function () { return _this.el.classList.add("peak-thumb"); }, cf.ConversationalForm.animationsEnabled ? 1400 : 0);
}
}, 0);
};
ChatResponse.prototype.dealloc = function () {
if (this.onClickCallback) {
this.el.removeEventListener(cf.Helpers.getMouseEvent("click"), this.onClickCallback, false);
this.onClickCallback = null;
}
_super.prototype.dealloc.call(this);
};
// template, can be overwritten ...
ChatResponse.prototype.getTemplate = function () {
return "<cf-chat-response class=\"" + (this.isRobotReponse ? "robot" : "user") + "\">\n\t\t\t\t<thumb style=\"background-image: url(" + this.image + ")\"></thumb>\n\t\t\t\t<text>" + (!this.response ? ChatResponse.THINKING_MARKUP : this.response) + "</text>\n\t\t\t</cf-chat-response>";
};
return ChatResponse;
}(cf.BasicElement));
ChatResponse.THINKING_MARKUP = "<thinking><span>.</span><span>.</span><span>.</span></thinking>";
cf.ChatResponse = ChatResponse;
})(cf || (cf = {}));
/// <reference path="ChatResponse.ts"/>
/// <reference path="../BasicElement.ts"/>
/// <reference path="../../logic/FlowManager.ts"/>
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// namespace
var cf;
(function (cf) {
// interface
cf.ChatListEvents = {
CHATLIST_UPDATED: "cf-chatlist-updated"
};
// class
var ChatList = (function (_super) {
__extends(ChatList, _super);
function ChatList(options) {
var _this = _super.call(this, options) || this;
_this.responses = [];
// flow update
_this.flowUpdateCallback = _this.onFlowUpdate.bind(_this);
_this.eventTarget.addEventListener(cf.FlowEvents.FLOW_UPDATE, _this.flowUpdateCallback, false);
// user input update
_this.userInputUpdateCallback = _this.onUserInputUpdate.bind(_this);
_this.eventTarget.addEventListener(cf.FlowEvents.USER_INPUT_UPDATE, _this.userInputUpdateCallback, false);
// user input key change
_this.onInputKeyChangeCallback = _this.onInputKeyChange.bind(_this);
_this.eventTarget.addEventListener(cf.UserInputEvents.KEY_CHANGE, _this.onInputKeyChangeCallback, false);
// user input height change
_this.onInputHeightChangeCallback = _this.onInputHeightChange.bind(_this);
_this.eventTarget.addEventListener(cf.UserInputEvents.HEIGHT_CHANGE, _this.onInputHeightChangeCallback, false);
return _this;
}
ChatList.prototype.onInputHeightChange = function (event) {
var dto = event.detail.dto;
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, dto);
this.scrollListTo();
};
ChatList.prototype.onInputKeyChange = function (event) {
var dto = event.detail.dto;
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, dto);
};
ChatList.prototype.onUserInputUpdate = function (event) {
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
if (this.currentUserResponse) {
var response = event.detail;
this.setCurrentUserResponse(response);
}
else {
// this should never happen..
throw new Error("No current response ..?");
}
};
ChatList.prototype.onFlowUpdate = function (event) {
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
var currentTag = event.detail.tag;
if (this.currentResponse)
this.currentResponse.disabled = false;
if (this.containsTagResponse(currentTag) && !event.detail.ignoreExistingTag) {
// because user maybe have scrolled up and wants to edit
// tag is already in list, so re-activate it
this.onUserWantsToEditTag(currentTag);
}
else {
// robot response
var robot = this.createResponse(true, currentTag, currentTag.question);
if (this.currentUserResponse) {
// linked, but only if we should not ignore existing tag
this.currentUserResponse.setLinkToOtherReponse(robot);
robot.setLinkToOtherReponse(this.currentUserResponse);
}
// user response, create the waiting response
this.currentUserResponse = this.createResponse(false, currentTag);
}
};
/**
* @name containsTagResponse
* @return boolean
* check if tag has already been responded to
*/
ChatList.prototype.containsTagResponse = function (tagToChange) {
for (var i = 0; i < this.responses.length; i++) {
var element = this.responses[i];
if (!element.isRobotReponse && element.tag == tagToChange) {
return true;
}
}
return false;
};
/**
* @name onUserAnswerClicked
* on user ChatReponse clicked
*/
ChatList.prototype.onUserWantsToEditTag = function (tagToChange) {
var oldReponse;
for (var i = 0; i < this.responses.length; i++) {
var element = this.responses[i];
if (!element.isRobotReponse && element.tag == tagToChange) {
// update element thhat user wants to edit
oldReponse = element;
break;
}
}
// reset the current user response
this.currentUserResponse.processResponseAndSetText();
if (oldReponse) {
// only disable latest tag when we jump back
if (this.currentUserResponse == this.responses[this.responses.length - 1]) {
this.currentUserResponse.hide();
}
this.currentUserResponse = oldReponse;
this.onListUpdate(this.currentUserResponse);
}
};
ChatList.prototype.onListUpdate = function (chatResponse) {
var _this = this;
setTimeout(function () {
_this.eventTarget.dispatchEvent(new CustomEvent(cf.ChatListEvents.CHATLIST_UPDATED, {
detail: _this
}));
chatResponse.show();
_this.scrollListTo(chatResponse);
}, 0);
};
/**
* @name setCurrentUserResponse
* Update current reponse, is being called automatically from onFlowUpdate, but can also in rare cases be called automatically when flow is controlled manually.
* reponse: FlowDTO
*/
ChatList.prototype.setCurrentUserResponse = function (dto) {
this.flowDTOFromUserInputUpdate = dto;
if (!this.flowDTOFromUserInputUpdate.text) {
if (dto.input.currentTag.type == "group") {
this.flowDTOFromUserInputUpdate.text = cf.Dictionary.get("user-reponse-missing-group");
}
else if (dto.input.currentTag.type != "password")
this.flowDTOFromUserInputUpdate.text = cf.Dictionary.get("user-reponse-missing");
}
this.currentUserResponse.setValue(this.flowDTOFromUserInputUpdate);
this.scrollListTo();
};
ChatList.prototype.updateThumbnail = function (robot, img) {
cf.Dictionary.set(robot ? "robot-image" : "user-image", robot ? "robot" : "human", img);
var newImage = robot ? cf.Dictionary.getRobotResponse("robot-image") : cf.Dictionary.get("user-image");
for (var i = 0; i < this.responses.length; i++) {
var element = this.responses[i];
if (robot && element.isRobotReponse) {
element.updateThumbnail(newImage);
}
else if (!robot && !element.isRobotReponse) {
element.updateThumbnail(newImage);
}
}
};
ChatList.prototype.createResponse = function (isRobotReponse, currentTag, value) {
if (value === void 0) { value = null; }
var response = new cf.ChatResponse({
// image: null,
tag: currentTag,
eventTarget: this.eventTarget,
isRobotReponse: isRobotReponse,
response: value,
image: isRobotReponse ? cf.Dictionary.getRobotResponse("robot-image") : cf.Dictionary.get("user-image"),
});
this.responses.push(response);
this.currentResponse = response;
var scrollable = this.el.querySelector("scrollable");
scrollable.appendChild(this.currentResponse.el);
this.onListUpdate(response);
return response;
};
ChatList.prototype.scrollListTo = function (response) {
if (response === void 0) { response = null; }
try {
var scrollable_1 = this.el.querySelector("scrollable");
var y_1 = response ? response.el.offsetTop - 50 : 1000000000;
scrollable_1.scrollTop = y_1;
setTimeout(function () { return scrollable_1.scrollTop = y_1; }, 100);
}
catch (e) {
// catch errors where CF have been removed
}
};
ChatList.prototype.getTemplate = function () {
return "<cf-chat type='pluto'>\n\t\t\t\t\t\t<scrollable></scrollable>\n\t\t\t\t\t</cf-chat>";
};
ChatList.prototype.dealloc = function () {
this.eventTarget.removeEventListener(cf.FlowEvents.FLOW_UPDATE, this.flowUpdateCallback, false);
this.flowUpdateCallback = null;
this.eventTarget.removeEventListener(cf.FlowEvents.USER_INPUT_UPDATE, this.userInputUpdateCallback, false);
this.userInputUpdateCallback = null;
this.eventTarget.removeEventListener(cf.UserInputEvents.KEY_CHANGE, this.onInputKeyChangeCallback, false);
this.onInputKeyChangeCallback = null;
_super.prototype.dealloc.call(this);
};
return ChatList;
}(cf.BasicElement));
cf.ChatList = ChatList;
})(cf || (cf = {}));
/// <reference path="../form-tags/Tag.ts"/>
/// <reference path="../ConversationalForm.ts"/>
var cf;
(function (cf) {
// interface
cf.FlowEvents = {
USER_INPUT_UPDATE: "cf-flow-user-input-update",
USER_INPUT_INVALID: "cf-flow-user-input-invalid",
// detail: string
FLOW_UPDATE: "cf-flow-update",
};
// class
var FlowManager = (function () {
function FlowManager(options) {
this.stopped = false;
this.maxSteps = 0;
this.step = 0;
this.savedStep = -1;
this.stepTimer = 0;
/**
* ignoreExistingTags
* @type boolean
* ignore existing tags, usually this is set to true when using startFrom, where you don't want it to check for exisintg tags in the list
*/
this.ignoreExistingTags = false;
this.cfReference = options.cfReference;
this.eventTarget = options.eventTarget;
this.setTags(options.tags);
this.maxSteps = this.tags.length;
this.userInputSubmitCallback = this.userInputSubmit.bind(this);
this.eventTarget.addEventListener(cf.UserInputEvents.SUBMIT, this.userInputSubmitCallback, false);
}
Object.defineProperty(FlowManager.prototype, "currentTag", {
get: function () {
return this.tags[this.step];
},
enumerable: true,
configurable: true
});
FlowManager.prototype.userInputSubmit = function (event) {
var _this = this;
cf.ConversationalForm.illustrateFlow(this, "receive", event.type, event.detail);
var appDTO = event.detail;
var isTagValid = this.currentTag.setTagValueAndIsValid(appDTO);
var hasCheckedForTagSpecificValidation = false;
var hasCheckedForGlobalFlowValidation = false;
var onValidationCallback = function () {
// check 1
if (_this.currentTag.validationCallback && typeof _this.currentTag.validationCallback == "function") {
if (!hasCheckedForTagSpecificValidation && isTagValid) {
hasCheckedForTagSpecificValidation = true;
_this.currentTag.validationCallback(appDTO, function () {
isTagValid = true;
onValidationCallback();
}, function (optionalErrorMessage) {
isTagValid = false;
if (optionalErrorMessage)
appDTO.errorText = optionalErrorMessage;
onValidationCallback();
});
return;
}
}
// check 2, this.currentTag.required <- required should be handled in the callback.
if (FlowManager.generalFlowStepCallback && typeof FlowManager.generalFlowStepCallback == "function") {
if (!hasCheckedForGlobalFlowValidation && isTagValid) {
hasCheckedForGlobalFlowValidation = true;
// use global validationCallback method
FlowManager.generalFlowStepCallback(appDTO, function () {
isTagValid = true;
onValidationCallback();
}, function (optionalErrorMessage) {
isTagValid = false;
if (optionalErrorMessage)
appDTO.errorText = optionalErrorMessage;
onValidationCallback();
});
return;
}
}
// go on with the flow
if (isTagValid) {
// do the normal flow..
cf.ConversationalForm.illustrateFlow(_this, "dispatch", cf.FlowEvents.USER_INPUT_UPDATE, appDTO);
// update to latest DTO because values can be changed in validation flow...
appDTO = appDTO.input.getFlowDTO();
_this.eventTarget.dispatchEvent(new CustomEvent(cf.FlowEvents.USER_INPUT_UPDATE, {
detail: appDTO //UserInput value
}));
// goto next step when user has answered
setTimeout(function () { return _this.nextStep(); }, cf.ConversationalForm.animationsEnabled ? 250 : 0);
}
else {
cf.ConversationalForm.illustrateFlow(_this, "dispatch", cf.FlowEvents.USER_INPUT_INVALID, appDTO);
// Value not valid
_this.eventTarget.dispatchEvent(new CustomEvent(cf.FlowEvents.USER_INPUT_INVALID, {
detail: appDTO //UserInput value
}));
}
};
// TODO, make into promises when IE is rolling with it..
onValidationCallback();
};
FlowManager.prototype.startFrom = function (indexOrTag, ignoreExistingTags) {
if (ignoreExistingTags === void 0) { ignoreExistingTags = false; }
if (typeof indexOrTag == "number")
this.step = indexOrTag;
else {
// find the index..
this.step = this.tags.indexOf(indexOrTag);
}
this.ignoreExistingTags = ignoreExistingTags;
if (!this.ignoreExistingTags) {
this.editTag(this.tags[this.step]);
}
else {
//validate step, and ask for skipping of current step
this.showStep();
}
};
FlowManager.prototype.start = function () {
this.stopped = false;
this.validateStepAndUpdate();
};
FlowManager.prototype.stop = function () {
this.stopped = true;
};
FlowManager.prototype.nextStep = function () {
if (this.stopped)
return;
if (this.savedStep != -1)
this.step = this.savedStep;
this.savedStep = -1; //reset saved step
this.step++;
this.validateStepAndUpdate();
};
FlowManager.prototype.previousStep = function () {
this.step--;
this.validateStepAndUpdate();
};
FlowManager.prototype.addStep = function () {
// this can be used for when a Tags value is updated and new tags are presented
// like dynamic tag insertion depending on an answer.. V2..
};
FlowManager.prototype.dealloc = function () {
this.eventTarget.removeEventListener(cf.UserInputEvents.SUBMIT, this.userInputSubmitCallback, false);
this.userInputSubmitCallback = null;
};
/**
* @name editTag
* go back in time and edit a tag.
*/
FlowManager.prototype.editTag = function (tag) {
this.ignoreExistingTags = false;
this.savedStep = this.step - 1;
this.step = this.tags.indexOf(tag); // === this.currentTag
this.validateStepAndUpdate();
};
FlowManager.prototype.setTags = function (tags) {
this.tags = tags;
for (var i = 0; i < this.tags.length; i++) {
var tag = this.tags[i];
tag.eventTarget = this.eventTarget;
}
};
FlowManager.prototype.skipStep = function () {
this.nextStep();
};
FlowManager.prototype.validateStepAndUpdate = function () {
if (this.maxSteps > 0) {
if (this.step == this.maxSteps) {
// console.warn("We are at the end..., submit click")
this.cfReference.doSubmitForm();
}
else {
this.step %= this.maxSteps;
if (this.currentTag.disabled) {
// check if current tag has become or is disabled, if it is, then skip step.
this.skipStep();
}
else {
this.showStep();
}
}
}
};
FlowManager.prototype.showStep = function () {
if (this.stopped)
return;
cf.ConversationalForm.illustrateFlow(this, "dispatch", cf.FlowEvents.FLOW_UPDATE, this.currentTag);
this.currentTag.refresh();
this.eventTarget.dispatchEvent(new CustomEvent(cf.FlowEvents.FLOW_UPDATE, {
detail: {
tag: this.currentTag,
ignoreExistingTag: this.ignoreExistingTags
}
}));
};
return FlowManager;
}());
FlowManager.STEP_TIME = 1000;
cf.FlowManager = FlowManager;
})(cf || (cf = {}));
|
SepioSystems/demisto-sdk | demisto_sdk/commands/init/templates/HelloWorld/HelloWorld_test.py | from .HelloWorld import Client, say_hello_command, say_hello_over_http_command
def test_say_hello():
client = Client(base_url='https://test.com', verify=False, auth=('test', 'test'))
args = {
'name': 'Dbot'
}
_, outputs, _ = say_hello_command(client, args)
assert outputs['hello'] == 'Hello Dbot'
def test_say_hello_over_http(requests_mock):
mock_response = {'result': 'Hello Dbot'}
requests_mock.get('https://test.com/hello/Dbot', json=mock_response)
client = Client(base_url='https://test.com', verify=False, auth=('test', 'test'))
args = {
'name': 'Dbot'
}
_, outputs, _ = say_hello_over_http_command(client, args)
assert outputs['hello'] == 'Hello Dbot'
|
krevelen/coala | coala-core/src/test/java/io/coala/experimental/embody/RepresentingCapability.java | /* $Id$
* $URL: https://dev.almende.com/svn/abms/coala-common/src/main/java/com/almende/coala/service/embodier/EntityEmbodierService.java $
*
* Part of the EU project Adapt4EE, see http://www.adapt4ee.eu/
*
* @license
* 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.
*
* Copyright (c) 2010-2013 Almende B.V.
*/
package io.coala.experimental.embody;
import io.coala.agent.Agent;
import io.coala.capability.CapabilityFactory;
import io.coala.capability.embody.PerceivingCapability;
/**
* {@link RepresentingCapability} embodies an {@link Agent}s within some environment in
* order to connect sensors (via publish-subscribe pattern) and effectors
*
* @date $Date: 2014-06-11 13:21:10 +0200 (Wed, 11 Jun 2014) $
* @version $Revision: 299 $
* @author <a href="mailto:<EMAIL>">Rick</a>
*
* @param <THIS> the (sub)type of {@link RepresentingCapability} to build
*/
public interface RepresentingCapability
extends PerceivingCapability
{
/**
* {@link Factory}
*
* @version $Revision: 299 $
* @author <a href="mailto:<EMAIL>">Rick</a>
*/
interface Factory extends CapabilityFactory<RepresentingCapability>
{
}
/**
* @return
*/
Object getEntity();
}
|
dweng0/game | node_modules/@babylonjs/core/Meshes/Compression/dracoCompression.js | <reponame>dweng0/game
import { Tools } from "../../Misc/tools";
import { WorkerPool } from '../../Misc/workerPool';
import { VertexData } from "../../Meshes/mesh.vertexData";
function createDecoderAsync(wasmBinary) {
return new Promise(function (resolve) {
DracoDecoderModule({ wasmBinary: wasmBinary }).then(function (module) {
resolve({ module: module });
});
});
}
function decodeMesh(decoderModule, dataView, attributes, onIndicesData, onAttributeData) {
var buffer = new decoderModule.DecoderBuffer();
buffer.Init(dataView, dataView.byteLength);
var decoder = new decoderModule.Decoder();
var geometry;
var status;
try {
var type = decoder.GetEncodedGeometryType(buffer);
switch (type) {
case decoderModule.TRIANGULAR_MESH:
geometry = new decoderModule.Mesh();
status = decoder.DecodeBufferToMesh(buffer, geometry);
break;
case decoderModule.POINT_CLOUD:
geometry = new decoderModule.PointCloud();
status = decoder.DecodeBufferToPointCloud(buffer, geometry);
break;
default:
throw new Error("Invalid geometry type " + type);
}
if (!status.ok() || !geometry.ptr) {
throw new Error(status.error_msg());
}
if (type === decoderModule.TRIANGULAR_MESH) {
var numFaces = geometry.num_faces();
var numIndices = numFaces * 3;
var byteLength = numIndices * 4;
var ptr = decoderModule._malloc(byteLength);
try {
decoder.GetTrianglesUInt32Array(geometry, byteLength, ptr);
var indices = new Uint32Array(numIndices);
indices.set(new Uint32Array(decoderModule.HEAPF32.buffer, ptr, numIndices));
onIndicesData(indices);
}
finally {
decoderModule._free(ptr);
}
}
var processAttribute = function (kind, attribute) {
var numComponents = attribute.num_components();
var numPoints = geometry.num_points();
var numValues = numPoints * numComponents;
var byteLength = numValues * Float32Array.BYTES_PER_ELEMENT;
var ptr = decoderModule._malloc(byteLength);
try {
decoder.GetAttributeDataArrayForAllPoints(geometry, attribute, decoderModule.DT_FLOAT32, byteLength, ptr);
var values = new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues);
if (kind === "color" && numComponents === 3) {
var babylonData = new Float32Array(numPoints * 4);
for (var i = 0, j = 0; i < babylonData.length; i += 4, j += numComponents) {
babylonData[i + 0] = values[j + 0];
babylonData[i + 1] = values[j + 1];
babylonData[i + 2] = values[j + 2];
babylonData[i + 3] = 1;
}
onAttributeData(kind, babylonData);
}
else {
var babylonData = new Float32Array(numValues);
babylonData.set(new Float32Array(decoderModule.HEAPF32.buffer, ptr, numValues));
onAttributeData(kind, babylonData);
}
}
finally {
decoderModule._free(ptr);
}
};
if (attributes) {
for (var kind in attributes) {
var id = attributes[kind];
var attribute = decoder.GetAttributeByUniqueId(geometry, id);
processAttribute(kind, attribute);
}
}
else {
var nativeAttributeTypes = {
"position": "POSITION",
"normal": "NORMAL",
"color": "COLOR",
"uv": "TEX_COORD"
};
for (var kind in nativeAttributeTypes) {
var id = decoder.GetAttributeId(geometry, decoderModule[nativeAttributeTypes[kind]]);
if (id !== -1) {
var attribute = decoder.GetAttribute(geometry, id);
processAttribute(kind, attribute);
}
}
}
}
finally {
if (geometry) {
decoderModule.destroy(geometry);
}
decoderModule.destroy(decoder);
decoderModule.destroy(buffer);
}
}
/**
* The worker function that gets converted to a blob url to pass into a worker.
*/
function worker() {
var decoderPromise;
onmessage = function (event) {
var data = event.data;
switch (data.id) {
case "init": {
var decoder = data.decoder;
if (decoder.url) {
importScripts(decoder.url);
decoderPromise = DracoDecoderModule({ wasmBinary: decoder.wasmBinary });
}
postMessage("done");
break;
}
case "decodeMesh": {
if (!decoderPromise) {
throw new Error("Draco decoder module is not available");
}
decoderPromise.then(function (decoder) {
decodeMesh(decoder, data.dataView, data.attributes, function (indices) {
postMessage({ id: "indices", value: indices }, [indices.buffer]);
}, function (kind, data) {
postMessage({ id: kind, value: data }, [data.buffer]);
});
postMessage("done");
});
break;
}
}
};
}
function getAbsoluteUrl(url) {
if (typeof document !== "object" || typeof url !== "string") {
return url;
}
return Tools.GetAbsoluteUrl(url);
}
/**
* Draco compression (https://google.github.io/draco/)
*
* This class wraps the Draco module.
*
* **Encoder**
*
* The encoder is not currently implemented.
*
* **Decoder**
*
* By default, the configuration points to a copy of the Draco decoder files for glTF from the babylon.js preview cdn https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js.
*
* To update the configuration, use the following code:
* ```javascript
* DracoCompression.Configuration = {
* decoder: {
* wasmUrl: "<url to the WebAssembly library>",
* wasmBinaryUrl: "<url to the WebAssembly binary>",
* fallbackUrl: "<url to the fallback JavaScript library>",
* }
* };
* ```
*
* Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
* Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
* Use `DracoCompression.DecoderAvailable` to determine if the decoder configuration is available for the current context.
*
* To decode Draco compressed data, get the default DracoCompression object and call decodeMeshAsync:
* ```javascript
* var vertexData = await DracoCompression.Default.decodeMeshAsync(data);
* ```
*
* @see https://www.babylonjs-playground.com/#N3EK4B#0
*/
var DracoCompression = /** @class */ (function () {
/**
* Constructor
* @param numWorkers The number of workers for async operations. Specify `0` to disable web workers and run synchronously in the current context.
*/
function DracoCompression(numWorkers) {
if (numWorkers === void 0) { numWorkers = DracoCompression.DefaultNumWorkers; }
var decoder = DracoCompression.Configuration.decoder;
var decoderInfo = (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") ? {
url: decoder.wasmUrl,
wasmBinaryPromise: Tools.LoadFileAsync(getAbsoluteUrl(decoder.wasmBinaryUrl))
} : {
url: decoder.fallbackUrl,
wasmBinaryPromise: Promise.resolve(undefined)
};
if (numWorkers && typeof Worker === "function") {
this._workerPoolPromise = decoderInfo.wasmBinaryPromise.then(function (decoderWasmBinary) {
var workerContent = decodeMesh + "(" + worker + ")()";
var workerBlobUrl = URL.createObjectURL(new Blob([workerContent], { type: "application/javascript" }));
var workerPromises = new Array(numWorkers);
for (var i = 0; i < workerPromises.length; i++) {
workerPromises[i] = new Promise(function (resolve, reject) {
var worker = new Worker(workerBlobUrl);
var onError = function (error) {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
reject(error);
};
var onMessage = function (message) {
if (message.data === "done") {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
resolve(worker);
}
};
worker.addEventListener("error", onError);
worker.addEventListener("message", onMessage);
worker.postMessage({
id: "init",
decoder: {
url: getAbsoluteUrl(decoderInfo.url),
wasmBinary: decoderWasmBinary,
}
});
});
}
return Promise.all(workerPromises).then(function (workers) {
return new WorkerPool(workers);
});
});
}
else {
this._decoderModulePromise = decoderInfo.wasmBinaryPromise.then(function (decoderWasmBinary) {
if (!decoderInfo.url) {
throw new Error("Draco decoder module is not available");
}
return Tools.LoadScriptAsync(decoderInfo.url).then(function () {
return createDecoderAsync(decoderWasmBinary);
});
});
}
}
Object.defineProperty(DracoCompression, "DecoderAvailable", {
/**
* Returns true if the decoder configuration is available.
*/
get: function () {
var decoder = DracoCompression.Configuration.decoder;
return !!((decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") || decoder.fallbackUrl);
},
enumerable: false,
configurable: true
});
DracoCompression.GetDefaultNumWorkers = function () {
if (typeof navigator !== "object" || !navigator.hardwareConcurrency) {
return 1;
}
// Use 50% of the available logical processors but capped at 4.
return Math.min(Math.floor(navigator.hardwareConcurrency * 0.5), 4);
};
Object.defineProperty(DracoCompression, "Default", {
/**
* Default instance for the draco compression object.
*/
get: function () {
if (!DracoCompression._Default) {
DracoCompression._Default = new DracoCompression();
}
return DracoCompression._Default;
},
enumerable: false,
configurable: true
});
/**
* Stop all async operations and release resources.
*/
DracoCompression.prototype.dispose = function () {
if (this._workerPoolPromise) {
this._workerPoolPromise.then(function (workerPool) {
workerPool.dispose();
});
}
delete this._workerPoolPromise;
delete this._decoderModulePromise;
};
/**
* Returns a promise that resolves when ready. Call this manually to ensure draco compression is ready before use.
* @returns a promise that resolves when ready
*/
DracoCompression.prototype.whenReadyAsync = function () {
if (this._workerPoolPromise) {
return this._workerPoolPromise.then(function () { });
}
if (this._decoderModulePromise) {
return this._decoderModulePromise.then(function () { });
}
return Promise.resolve();
};
/**
* Decode Draco compressed mesh data to vertex data.
* @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
* @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
* @returns A promise that resolves with the decoded vertex data
*/
DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
if (this._workerPoolPromise) {
return this._workerPoolPromise.then(function (workerPool) {
return new Promise(function (resolve, reject) {
workerPool.push(function (worker, onComplete) {
var vertexData = new VertexData();
var onError = function (error) {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
reject(error);
onComplete();
};
var onMessage = function (message) {
if (message.data === "done") {
worker.removeEventListener("error", onError);
worker.removeEventListener("message", onMessage);
resolve(vertexData);
onComplete();
}
else if (message.data.id === "indices") {
vertexData.indices = message.data.value;
}
else {
vertexData.set(message.data.value, message.data.id);
}
};
worker.addEventListener("error", onError);
worker.addEventListener("message", onMessage);
var dataViewCopy = new Uint8Array(dataView.byteLength);
dataViewCopy.set(new Uint8Array(dataView.buffer, dataView.byteOffset, dataView.byteLength));
worker.postMessage({ id: "decodeMesh", dataView: dataViewCopy, attributes: attributes }, [dataViewCopy.buffer]);
});
});
});
}
if (this._decoderModulePromise) {
return this._decoderModulePromise.then(function (decoder) {
var vertexData = new VertexData();
decodeMesh(decoder.module, dataView, attributes, function (indices) {
vertexData.indices = indices;
}, function (kind, data) {
vertexData.set(data, kind);
});
return vertexData;
});
}
throw new Error("Draco decoder module is not available");
};
/**
* The configuration. Defaults to the following urls:
* - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
* - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
* - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
*/
DracoCompression.Configuration = {
decoder: {
wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
}
};
/**
* Default number of workers to create when creating the draco compression object.
*/
DracoCompression.DefaultNumWorkers = DracoCompression.GetDefaultNumWorkers();
DracoCompression._Default = null;
return DracoCompression;
}());
export { DracoCompression };
//# sourceMappingURL=dracoCompression.js.map |
tottijbzy/urly | prettier.config.js | module.exports = {
// https://prettier.io/docs/en/options.html#print-width
printWidth: 80,
// https://prettier.io/docs/en/options.html#tabs
useTabs: true,
// https://prettier.io/docs/en/options.html#semicolons
semi: true,
// https://prettier.io/docs/en/options.html#quotes
singleQuote: false,
// https://prettier.io/docs/en/options.html#trailing-commas
trailingComma: "es5",
// https://prettier.io/docs/en/options.html#bracket-spacing
bracketSpacing: true,
// https://prettier.io/docs/en/options.html#arrow-function-parentheses
arrowParens: "always",
// https://prettier.io/docs/en/options.html#require-pragma
requirePragma: false,
// https://prettier.io/docs/en/options.html#insert-pragma
insertPragma: false,
overrides: [
{
files: ["defaults.js", "presets.js"],
options: {
printWidth: 1000000,
},
},
],
};
|
hoolatech/datarouter-1 | datarouter-task-tracker/src/main/java/io/datarouter/tasktracker/scheduler/LongRunningTaskStatus.java | <reponame>hoolatech/datarouter-1
/*
* Copyright © 2009 HotPads (<EMAIL>)
*
* 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.
*/
package io.datarouter.tasktracker.scheduler;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import io.datarouter.instrumentation.task.TaskStatus;
import io.datarouter.util.enums.DatarouterEnumTool;
import io.datarouter.util.enums.StringEnum;
public enum LongRunningTaskStatus implements StringEnum<LongRunningTaskStatus>{
RUNNING(TaskStatus.RUNNING, "running", true, false),
SUCCESS(TaskStatus.SUCCESS, "success", false, false),
ERRORED(TaskStatus.ERRORED, "errored", false, true),
STOP_REQUESTED(TaskStatus.STOP_REQUESTED, "stopRequested", false, false),
MAX_DURATION_REACHED(TaskStatus.MAX_DURATION_REACHED, "maxDurationReached", false, false),
TIMED_OUT(TaskStatus.TIMED_OUT, "timedOut", false, true),
INTERRUPTED(TaskStatus.INTERRUPTED, "interrupted", false, true),
;
private static final Map<TaskStatus,LongRunningTaskStatus> BY_TASK_STATUS = Arrays.stream(values())
.collect(Collectors.toMap(LongRunningTaskStatus::getStatus, Function.identity()));
private final TaskStatus status;
private final String persistentString;
private final boolean isRunning;
public final boolean isBadState;
LongRunningTaskStatus(TaskStatus status, String persistentString, boolean isRunning, boolean isBadState){
this.status = status;
this.persistentString = persistentString;
this.isRunning = isRunning;
this.isBadState = isBadState;
}
public static LongRunningTaskStatus fromTaskStatus(TaskStatus status){
return BY_TASK_STATUS.get(status);
}
public static LongRunningTaskStatus fromPersistentStringStatic(String str){
return DatarouterEnumTool.getEnumFromString(values(), str, null);
}
@Override
public LongRunningTaskStatus fromPersistentString(String str){
return fromPersistentStringStatic(str);
}
public TaskStatus getStatus(){
return status;
}
@Override
public String getPersistentString(){
return persistentString;
}
public boolean isRunning(){
return isRunning;
}
}
|
zkaif/yunpian-stargate | yunpian-stargate-core/src/main/java/com/yunpian/stargate/core/process/IStargateClientEncod.java | <filename>yunpian-stargate-core/src/main/java/com/yunpian/stargate/core/process/IStargateClientEncod.java<gh_stars>0
package com.yunpian.stargate.core.process;
import com.yunpian.stargate.core.context.ProducerContext;
import com.yunpian.stargate.core.vo.StargateMessage;
/**
* Created with IntelliJ IDEA. User: ZhouKaifan Date:2018/8/15 Time:下午9:35
*/
public interface IStargateClientEncod {
byte[] encod(StargateMessage stargateMessage, ProducerContext producerContext);
}
|
zhuangsc/Plasma-ompss1 | core_blas-qwrapper/qwrapper_cgetrip.c | <gh_stars>0
/**
*
* @file qwrapper_cgetrip.c
*
* PLASMA InPlaceTransformation module
* PLASMA is a software package provided by Univ. of Tennessee,
* Univ. of California Berkeley and Univ. of Colorado Denver
*
* This work is the implementation of an inplace transformation
* based on the GKK algorithm by <NAME>
* and its fortran implementation.
*
* @version 2.6.0
* @author <NAME>
* @date 2010-11-15
*
* @generated c Tue Jan 7 11:44:57 2014
*
**/
#include "common.h"
/***************************************************************************//**
*
**/
void QUARK_CORE_cgetrip(Quark *quark, Quark_Task_Flags *task_flags,
int m, int n, PLASMA_Complex32_t *A, int szeA)
{
DAG_CORE_GETRIP;
QUARK_Insert_Task(quark, CORE_cgetrip_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
0);
}
/***************************************************************************//**
*
**/
void QUARK_CORE_cgetrip_f1(Quark *quark, Quark_Task_Flags *task_flags,
int m, int n,
PLASMA_Complex32_t *A, int szeA,
PLASMA_Complex32_t *fake, int szeF, int paramF)
{
DAG_CORE_GETRIP;
if ( (fake == A) && (paramF & GATHERV) ) {
QUARK_Insert_Task(
quark, CORE_cgetrip_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT | paramF,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
0);
} else {
QUARK_Insert_Task(
quark, CORE_cgetrip_f1_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
sizeof(PLASMA_Complex32_t)*szeF, fake, paramF,
0);
}
}
/***************************************************************************//**
*
**/
void QUARK_CORE_cgetrip_f2(Quark *quark, Quark_Task_Flags *task_flags,
int m, int n,
PLASMA_Complex32_t *A, int szeA,
PLASMA_Complex32_t *fake1, int szeF1, int paramF1,
PLASMA_Complex32_t *fake2, int szeF2, int paramF2)
{
DAG_CORE_GETRIP;
if ( (fake2 == A) && (paramF2 & GATHERV) ) {
QUARK_Insert_Task(
quark, CORE_cgetrip_f1_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT | paramF2,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
sizeof(PLASMA_Complex32_t)*szeF1, fake1, paramF1,
0);
} else if ( (fake1 == A) && (paramF1 & GATHERV) ) {
QUARK_Insert_Task(
quark, CORE_cgetrip_f1_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT | paramF1,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
sizeof(PLASMA_Complex32_t)*szeF2, fake2, paramF2,
0);
} else {
QUARK_Insert_Task(
quark, CORE_cgetrip_f2_quark, task_flags,
sizeof(int), &m, VALUE,
sizeof(int), &n, VALUE,
sizeof(PLASMA_Complex32_t)*szeA, A, INOUT,
sizeof(PLASMA_Complex32_t)*szeA, NULL, SCRATCH,
sizeof(PLASMA_Complex32_t)*szeF1, fake1, paramF1,
sizeof(PLASMA_Complex32_t)*szeF2, fake2, paramF2,
0);
}
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgetrip_quark = PCORE_cgetrip_quark
#define CORE_cgetrip_quark PCORE_cgetrip_quark
#endif
void CORE_cgetrip_quark(Quark *quark)
{
int m;
int n;
PLASMA_Complex32_t *A;
PLASMA_Complex32_t *W;
quark_unpack_args_4(quark, m, n, A, W);
CORE_cgetrip(m, n, A, W);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgetrip_f1_quark = PCORE_cgetrip_f1_quark
#define CORE_cgetrip_f1_quark PCORE_cgetrip_f1_quark
#endif
void CORE_cgetrip_f1_quark(Quark *quark)
{
int m;
int n;
PLASMA_Complex32_t *A;
PLASMA_Complex32_t *W;
PLASMA_Complex32_t *fake;
quark_unpack_args_5(quark, m, n, A, W, fake);
CORE_cgetrip(m, n, A, W);
}
/***************************************************************************//**
*
**/
#if defined(PLASMA_HAVE_WEAK)
#pragma weak CORE_cgetrip_f2_quark = PCORE_cgetrip_f2_quark
#define CORE_cgetrip_f2_quark PCORE_cgetrip_f2_quark
#endif
void CORE_cgetrip_f2_quark(Quark *quark)
{
int m;
int n;
PLASMA_Complex32_t *A;
PLASMA_Complex32_t *W;
PLASMA_Complex32_t *fake1;
PLASMA_Complex32_t *fake2;
quark_unpack_args_6(quark, m, n, A, W, fake1, fake2);
CORE_cgetrip(m, n, A, W);
}
|
kekshd/keks | app/controllers/text_storage_controller.rb | <gh_stars>1-10
# encoding: utf-8
class TextStorageController < ApplicationController
before_filter :require_admin
def update
@message = (TextStorage.find(params[:id])) rescue nil
if @message && @message.update_attributes(params[:text_storage])
flash[:success] = "Mitteilung aktualisiert"
redirect_to :back
else
redirect_to :back
end
end
end
|
othuntgithub/AdditionalEnderItems | src/main/java/com/hidoni/additionalenderitems/setup/ModItemGroup.java | <filename>src/main/java/com/hidoni/additionalenderitems/setup/ModItemGroup.java<gh_stars>0
package com.hidoni.additionalenderitems.setup;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import java.util.function.Supplier;
public class ModItemGroup extends ItemGroup
{
private final Supplier<ItemStack> displayStack;
public static final ModItemGroup ADDITIONAL_ENDER_ITEMS_GROUP = new ModItemGroup("additionalenderitemsitemgroup", () -> new ItemStack(ModItems.ENDER_TORCH.get()));
public ModItemGroup(String label, Supplier<ItemStack> displayStack)
{
super(label);
this.displayStack = displayStack;
}
@Override
public ItemStack createIcon()
{
return displayStack.get();
}
}
|
LETG/geoauth | app/decorators/user_decorator.rb | class UserDecorator < Draper::Decorator
include Draper::LazyHelpers
delegate_all
#def name
# [ first_name, last_name ].compact.join(' ')
#end
def created_date
created_at.strftime('%d/%m/%Y')
end
def roles_count
roles.count
end
# Define presentation-specific methods here. Helpers are accessed through
# `helpers` (aka `h`). You can override attributes, for example:
#
# def created_at
# helpers.content_tag :span, class: 'time' do
# object.created_at.strftime("%a %m/%d/%y")
# end
# end
end
|
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism | Variant Programs/3-1/9/Islander.java | public class Islander {
private String atollNominate;
private int enumerateCultivators;
public Islander(String peiConstitute, int numerousGardeners) {
this.atollNominate = peiConstitute;
this.enumerateCultivators = numerousGardeners;
}
public void early() {
for (int i = 0; i < enumerateCultivators; i++) {
new Thread(new Breeder(atollNominate + "_Farmer" + (i + 1))).start();
}
}
}
|
comicgenie/rdf | src/main/java/org/comicwiki/gcd/tables/PublisherTable.java | /*******************************************************************************
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. ComicGenie 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.
*******************************************************************************/
package org.comicwiki.gcd.tables;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import org.apache.spark.sql.Column;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SQLContext;
import org.comicwiki.BaseTable;
import org.comicwiki.Join;
import org.comicwiki.TableRow;
import org.comicwiki.ThingFactory;
import org.comicwiki.joinrules.IdToInstanceJoinRule;
import org.comicwiki.model.Instant;
import org.comicwiki.model.schema.Country;
import org.comicwiki.model.schema.Organization;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Join(value = CountryTable.class, leftKey = "fkCountryId", leftField = "country", withRule=IdToInstanceJoinRule.class)
@Singleton
public class PublisherTable extends BaseTable<PublisherTable.PublisherRow> {
private static final class Columns {
public static final Column[] ALL_COLUMNS = new Column[] {
new Column("id"), new Column("name"), new Column("country_id"),
new Column("year_began"), new Column("year_ended"),
new Column("notes"), new Column("url"), new Column("modified") };
public static final int COUNTRY_ID = 2;
public static final int ID = 0;
public static final int MODIFIED = 7;
public static final int NAME = 1;
public static final int NOTES = 5;
public static final int URL = 6;
public static final int YEAR_BEGAN = 3;
public static final int YEAR_ENDED = 4;
}
public static class PublisherRow extends TableRow<Organization> {
public Organization instance = create(thingFactory);
/**
* gcd_country.id
*/
public int fkCountryId;
public Country country;
public Date modified;
public String name;
public String notes;
public String url;
public Integer yearBegan;
public Integer yearEnded;
}
private static final String sInputTable = "gcd_publisher";
private static final String sParquetName = sInputTable + ".parquet";
private static ThingFactory thingFactory;
@Inject
public PublisherTable(SQLContext sqlContext, ThingFactory thingFactory) {
super(sqlContext, sParquetName);
PublisherTable.thingFactory = thingFactory;
}
@Override
public PublisherRow process(Row row) throws IOException {
PublisherRow publisherRow = new PublisherRow();
if (!row.isNullAt(Columns.COUNTRY_ID)) {
publisherRow.fkCountryId = row.getInt(Columns.COUNTRY_ID);
}
publisherRow.modified = row.getTimestamp(Columns.MODIFIED);
publisherRow.name = row.getString(Columns.NAME);
publisherRow.instance.name = publisherRow.name;
publisherRow.notes = row.getString(Columns.NOTES);
publisherRow.url = row.getString(Columns.URL);
if (!row.isNullAt(Columns.YEAR_BEGAN)) {
publisherRow.yearBegan = row.getInt(Columns.YEAR_BEGAN);
}
if (!row.isNullAt(Columns.YEAR_ENDED)) {
publisherRow.yearEnded = row.getInt(Columns.YEAR_ENDED);
}
if (!row.isNullAt(Columns.ID)) {
publisherRow.id = row.getInt(Columns.ID);
add(publisherRow);
}
return publisherRow;
}
@Override
public void saveToParquetFormat(String jdbcUrl) {
super.saveToParquetFormat(sInputTable, Columns.ALL_COLUMNS, jdbcUrl);
}
@Override
protected void transform(PublisherRow row) {
super.transform(row);
Organization publisher = row.instance;
try {
publisher.addUrl(new URL("http://www.comics.org/publisher/"
+ row.id));
} catch (MalformedURLException e1) {
}
//TODO: has brand? indicia_publishers?
//publisher.urls.add(URI.create("http://www.comics.org/publisher/"
// + row.id +"/brands"));
publisher.name = row.name;
if (row.country != null) {
publisher.location = row.country.instanceId;
}
if (row.yearBegan != null) {
Instant began = thingFactory.create(Instant.class);
began.year = row.yearBegan;
publisher.foundingDate = began.instanceId;
}
if (row.yearEnded != null) {
Instant ended = thingFactory.create(Instant.class);
ended.year = row.yearEnded;
publisher.dissolutionDate = ended.instanceId;
}
if (!Strings.isNullOrEmpty(row.notes)) {
publisher.addDescription(row.notes);
}
if (!Strings.isNullOrEmpty(row.url)) {
try {
publisher.addUrl(new URL(row.url));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
HunYahiko/smart-parking-system | sps-backend/src/main/java/com/utm/stanislav/parkingapp/configuration/deserializer/ParkingStatusJsonDeserializer.java | package com.utm.stanislav.parkingapp.configuration.deserializer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.utm.stanislav.parkingapp.model.enums.ParkingStatus;
import java.io.IOException;
import java.util.Optional;
public class ParkingStatusJsonDeserializer extends JsonDeserializer<ParkingStatus> {
@Override
public ParkingStatus deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode jsonNode = p.getCodec().readTree(p);
String status = jsonNode.textValue();
Optional<ParkingStatus> parkingStatus = ParkingStatus.fromString(status);
if (parkingStatus.isPresent()) {
return parkingStatus.get();
} else {
throw new IOException("Exception parsing MessageType");
}
}
}
|
nml5566/DuneBoardGame | node_modules/Dune/Map/ShieldWall.js | <reponame>nml5566/DuneBoardGame
module.exports = ShieldWall;
var BaseTerritory = require("./Base.js");
ShieldWall.prototype = new BaseTerritory();
ShieldWall.prototype.constructor = ShieldWall;
function ShieldWall() {
this.name = "Shield Wall";
var neighbors = new Array(
"HoleInTheRock", "SihayaRidge", "GaraKulon", "PastyMesa", "TheMinorErg",
"FalseWallEast", "ImperialBasin"
);
this.setNeighbors(neighbors);
}
|
antaljanosbenjamin/miscellaneous | tests/codility/MolybdenumTests.cpp | <reponame>antaljanosbenjamin/miscellaneous
#include <catch2/catch.hpp>
#include "Molybdenum.hpp"
struct TestInfo {
std::vector<int> A;
int K;
std::vector<int> expectedLeaders;
};
TEST_CASE("General") {
auto testInfo =
// NOLINTNEXTLINE(readability-magic-numbers,google-build-using-namespace)
GENERATE(TestInfo{{2, 1, 3, 1, 2, 2, 3}, 3, {2, 3}}, TestInfo{{1, 2, 2, 1, 2}, 4, {2, 3}}, TestInfo{{1}, 1, {2}});
const auto calculatedLeaders = Molybdenum::solution(testInfo.A, testInfo.K);
CHECK(calculatedLeaders == testInfo.expectedLeaders);
}
|
comprakt/comprakt-fuzz-tests | output/bbfa2733d9eb4195bb64ede3106a9d7c.java | <filename>output/bbfa2733d9eb4195bb64ede3106a9d7c.java
class KVf {
}
class xjVK4x9Ny8Ah {
public void[][][] PjbCRVgT;
public static void ERTEhEbJYxGK (String[] PYfpR82g) {
if ( -true.WS4gL7oCXiXoZ) ;
;
}
public fnUGlB7 Z_rpT;
public static void xeA9bhFnYVD (String[] dJUi_KjeKS) {
!!-false.LPsftp1SJmp();
boolean oF7Gr4V5McDN;
pWUHzMMNWtM.QSsJ6yuSs6a6;
while ( --!066790[ -true.B]) {
void[][] ELzRJhlg;
}
tYH sj9WV_tf90Vb0 = -null.yuZx_e() = true[ -!C5irVOkcr.Gtk6q];
void YgXT92m;
if ( !---!false[ !!-!this[ new boolean[ -!8.Vnbhvc()].wkij77k]]) {
return;
}else if ( 163768.lWBLPGc4_ybONs) if ( !false.i()) return;
!false[ !-new Bo2kTLDS9qj()[ !this._EMl]];
while ( --RlXpi6m().V2j43q9_4eJn4w) -----true[ --87776564.X8];
while ( i3pJF2().FUFrRszxQug()) return;
}
}
class LNLFufoZ {
}
class aQt2JBw {
public int[] sLDeRf (Yqb91i5W5fP_6W[][][][] JWs7x11pPK, void[][][][] J4J, upGn6Z K, void eunoBgPru5qt, void[] Odm4) throws LhawvCUPtET3t {
boolean[][] jjArL = !new boolean[ --!-false[ null[ -M9s()[ 85367.g()]]]].oEqotbHJvO7;
;
int VpPQ4y5Be7n = !-null[ !!!!!this.tBYE()] = 53200630.a1Yh;
boolean[][][] SYAD;
void Z = ( !-ylKraX6O().tl()).p1tk72srG7() = true.m6Ifi();
void FmLc7 = -!new boolean[ false.XGT].zZfrrHe() = false[ true[ cq8().d4lSsoas2iIS]];
;
boolean AIPObaH6t = !this[ !-false.Sc806bQracGF];
t4SsiC Rdo282E_0D1Au;
taO4PD R4_eOCfArxDaef = !!!null.LvkS7();
MpOSu[] t4ZGgrseoR;
HB9EP17JT_sSe min3Er9AEEde = aQ9sNBkMXvkYQG[ -new L0WtXe().zaMEPuX6VI5a] = !!this.dOXe;
kL8efQ7ze1j Bw = RsKkHoMS22iug()[ --083571178[ true[ new rb_slSHaV4Z[ -new K().WSqT2IgSde8L41].aSqhZu()]]] = nowiC2lLU[ py0mKJU6U().xIS_pxeLtnvV];
boolean[][] ISL5;
}
public boolean lbn9UA (int CNwyHL, boolean[][][][] ZIb, boolean q) throws A8YhBiBc0nB {
boolean JPmD55;
int tgK31VoCjFVw = -new i().rW() = !!false.X1Rbas72r();
;
while ( -!new void[ !null.KP406Z].JYukyC) {
int[][] iuSrevf1mPV;
}
;
Z3 mGx5 = -( this.mmH8567IKct7z())[ --new GIFNg().u9] = 0.CHCqDpHcD5tA;
{
if ( ( !new void[ null.Fp()].Azw)[ !false.kdilI34eCj6x]) ;
;
{
boolean Ux4rrqAhL;
}
}
return;
if ( xEE1evznML.F4Z5uFnKSC55N()) ;else if ( q7VyhWdqcDmUd().LlF5ndc) if ( Z1C31Al[ !new gc9ApDKT2()[ -!!-LyFd12U4SurK.t]]) return;
{
xoqywiKmHoY.hy3X24Dt6M;
void GejEBgf1oFbTG;
return;
while ( -!this[ -!null.wPb()]) while ( cDjAH4.nVGzm4ftbgyMZ) {
boolean[] Z6Y;
}
;
if ( new q8rzDWC7i4LK48()[ !null[ new o()[ !--null[ !!( new void[ 9[ --!true.pqGD()]].anmtp5iMiwBNi()).QrT]]]]) ;
-this.rj;
Gc57dPt47RUwmv Gt5XD_xTlTudf;
return;
void[] rFVu9;
8294.LN;
{
int[][][] U;
}
-zlm_pbB().FnAFthuF;
}
void[] gB15 = true.dT;
void _r6s5p_sn;
}
public boolean[] MspHoVEU () throws QllbFmeamzf {
!jO[ !--41528[ true.MhoKlOx]];
t XHrJpTtj = __KWBkJL.NDL9qgY9If0eot() = --c().Bu0W();
return;
;
int YI7nwbGg66s;
boolean ApJTSfc0x;
int XPvA;
void[][][][][] mTEi = !-this.GJjpdfZ2ZRF4YO() = false[ true.ukw()];
boolean[] Daza3wL;
}
public static void gbo7f5ykS (String[] n2u7kQb) {
int hl8F94O3PWRi;
int[][] mZ7neRG;
;
;
Erut Fh8MaTzrlCT = -!true.GeG2c1JHF;
;
aUuDJK[][] dfFaSOR00YZnI = -null[ false.qz()];
boolean[] h;
if ( -this.Jy265oAExeQ()) {
-new int[ --!-!new aSuG()[ 115.bMoKMkQpt2q]].IAi7NBr5349VT;
}
{
int ACMkIyzs;
if ( !gyHMEg.ZKPmZ()) if ( -84589671.o()) {
void[][] M7kJ;
}
boolean[] Y;
boolean[][] VjF;
if ( -!656.Xs7Za()) if ( !-null[ 704144.WWS]) while ( aAKPNjFlMaNMaL().Qmp) return;
deQYy_GelQL[][] w0wZ4QIRChzz;
;
}
--278353194[ -null.w];
!false.OEs27SbjF2Dg;
if ( 504.eRZ8BvJEi6Vjm()) !new uXRiznIezh7eh3().GGX;else while ( -!-mdwS_rvLx.eVf8sz8Z4bIJI0()) ;
void y;
int[] lqaIkLWdsK1 = -qz.GLjzB9BWW() = this.uKYL();
void[][] S = !ZzgYO.vHm3kOFERGC = -false[ !!!new vmKfYUS().N9YBQF6()];
}
public void[] t7jm1vp_c4Ln () {
;
boolean[] r6kX7zY;
void[] Ctdeb = -null.GI();
boolean I = !!false.a_qnM = new boolean[ oVX3().GZmcdS4InH].f04tFWpoh41XhK();
void[] VkLBf;
int aJtDBUVwGGq_Wc;
void[][][][] vjha;
;
}
public static void C2JeGT (String[] TV596) throws A {
return !--!!-true.A();
NI lOhl5;
pFZ_[] s = !-( this.Ntqv()).CfG92o9eHZg() = ( new int[ z._4jI5rGVvMkeR()].UaKcYGw).mrK3dYsog3;
;
void odLt9 = -!-Do3vq()[ 9867474.PgP] = !-this.VWpdEidjHNH;
while ( -ZWyl2cN()[ !84997020.MbYtw1NHLez]) while ( this.UGg) return;
;
int[][] jsAt5uDTm = yZSV.UFe;
void[] X6T9wEWlkuYYW = !--true.dXVaR();
!219.iwDZH();
}
public s74nM kdE;
public void[] yBJ () throws ML {
;
ZRSgBim8[] ZAA8Tq0 = !!new MqB6M8Z[ false[ new A3tuaHw6OLrkOj().Gfq()]].BPThdb1 = !true.tSilEsVmW;
return -YO6qGgSn().wYG8tItkBJM();
return;
boolean NifjHa = !!-new int[ gqzeKxWyg6fxM.QGQvDks].Y17XcMqZ = true[ EQFpkAHDXTi.AhmN0Tk3sYaO];
int[][] tt5PSbDPww_Uy;
int L;
MEl_[] l = !!new HUaFRaCSSLA1L()[ -this.A];
if ( -( --true.xlIjmTk3h2).UhdsIEYncXm) {
void[] qV;
}
!gfpa5jW().FSt6pIDhau2();
if ( ( !null.nmFc4m5)[ !false[ !qV0hhe.ofCo4CGD]]) if ( -!---90513890.C_hnbYP157uUo()) return;
;
int Pq7tqvEg8rw;
int r943c_e6q2ENbX = !( --( m40VkQ0d.z1)._2R()).khf9f;
while ( this.LTR3()) while ( -new ADzIQpul8kG3Cl().g5DCh) {
void[] g9MWXpiP;
}
int LF;
KuopcYBGjB9r P = !false[ ( !-null.GfZDT4moF6()).KivM4hl()] = --this.LumRYc;
int oSOobZPeV = hfzzSDmu31ot().eCqlbEjc3();
bM1T[][][] u = ---e[ -false.Bt3TYjEecbwtz];
}
public static void x (String[] K7Dmc) throws Qs {
int SMORWsISKe = !-this.Fr;
boolean hbSiMr;
int gZJDCkJ9 = -null.dJ5F1rcl;
if ( -true.ptSzmWMZshVUF) if ( !null[ this[ -!!oFYvnj[ false.wl0xz7aK08Z()]]]) {
ZoRF20rAaxaeeN[][][][][] gQP0uI;
}else ;
int OvxhX9dkV8E = new int[ !yZsY1k()._6Z3418SkdYp0S][ -new xJ5R2UFi().c9_gFrWhTM_D] = null.TJ2Oxbzq5;
int M8 = 183887913.FCFtIuIs6h;
return;
}
public static void Jwpo_EdxS (String[] I) throws c_ {
;
while ( -this[ !---!new int[ 195[ null.CnkSQw_vl1MI]][ !!true.L6Cx9A9BAKIglx]]) if ( -!-this.IVYLCoggW1) if ( true.Di59Th1JiL()) !-Ad2GRmLQJo().CTlxLATBh();
void[] M_IV = -37180.plPwq_jjNF5Vl;
if ( IVjHmXxgB.TCAPKmQRBSv) if ( -false.Nuc) false.bDvH42mEmL();else ;
l[] u9;
return -PDD2FxH1RjZCa.reQJKX_30V72;
;
{
boolean UBjbfXUyRFXJr;
while ( !new YR2Nqw_d().BVjDUtsv1A7()) if ( !72425.Z9i()) if ( !false[ wV90BTP318VjNV.vND64JW8z()]) return;
if ( Bov7Z().yM8ik07Hf_) if ( true.afviHyQW()) return;
int[] P;
return;
if ( ( null.wKDQwra0RERy).bvvQvy()) return;
return;
;
if ( -false.OwuLP8rSO()) {
int[][][][][] twjY1u9;
}
return;
return;
}
int V;
ghPFq[] Wa5ZB5hEKE = !!true[ -!!-aNZ[ -new void[ !!-!this.zC][ hwk_15RGoZkS4o().plo]]];
int EvYRhHLR3mQOtn = -!!!new int[ true.VGTv()].t_wqFoSWr_;
void C;
int GD7jvH9Z_dO;
int[][][][][] w27B0FqnQd;
}
public int _mLHjsM3;
}
class CV4R1g {
public void aHY (int[][][] RtXzpKqKI, Zu qw, void SLG8, void[][][][][][] AwzrblQl, boolean _uOY, int[][] oau) {
boolean AkT7qkh_fA9;
void PFxSeTFnBnAw;
{
boolean Lbi5g;
return;
int AkQmrdo6B9Hww;
int[] UMTg4Ju8nOD2;
return;
boolean Ios8iu2R;
int oR3YHGxC;
;
int[] ur;
boolean snQBP9ww;
_lb mx4LQ7u_quU;
while ( -!new dJFMWrR()[ false.a0fEXifkzR]) !--jokPxVNOkkhwQ.eR;
this.PBBuHLUGqp1Ol();
Paa uvx;
void CcEo;
int[] S4;
}
int MeCKgjaiBM = -true.VG();
if ( !null.teR4OGlSc897m9) return;
}
public boolean Q7iFX8Xs2uqcH () throws RgDIWRTpX_ {
void[] fmSgok_SC_I = --!BJnD7t8xyYJ.IAkuprj() = ----90[ ( !-950.pjI).B];
new BABXRj().B;
!!81.DkzWLh7R5RSuk7();
int rp8tTVxGvZs;
return;
;
boolean LH;
--!--nCyHGKsahkhU9[ V2n8w.tkcYZUq3()];
return -!!350287293.jtH;
int ZbNYNg = false[ -!-5875[ new int[ -this.mpxkDy2oAx()][ !false[ !!null.BKFsws1C()]]]] = 3650[ !new S7xU2jr9C().ln];
void kOb6FszwZFdhJP = new LMJ5nzlS2().e = W.Gnq3uFY4ik;
if ( !!511[ -new void[ -( -null.rQJ5x_rR6QsLok()).V2hTrD8fpEYCN].AGSWVX4XinlX()]) 1691740.Y();else if ( new CKLTlhAhatKYf[ this[ new wpH6NbA8ijiba[ ---!null[ new int[ !new m().Fy85Lq][ new OAfQOvyJa4Dg().NiAnK]]][ WoCu.UV4iUlsXb]]].Pg_Uv_Rm()) while ( true.YtnRKkXk()) ;
return !4.OA7JZem16mmz3;
boolean[] lJPAiaRbZoyA;
if ( tOgvQ1Q4QNz.mgNDwGO5ShZB()) return;
boolean nJOLYpFi4J5QE;
FAXh2x0lGbJ[][][][][] RRj9 = new boolean[ null.q].ketSlr9DnXl;
int VQ7IaOPSzLnpf;
}
public boolean[][] tqaDw1 (boolean Ia476owU, boolean[][][] mAkUcxWdhUd2dg, void GSPK, boolean Zpq7CTKi, boolean[][][][] ATWbEXx9eddC, YqrhXGcsr8TZ T7CbKXg0dPeP, GEf8cpqU hUorEajy4gGorp) throws vSifw {
void[] ohBf = !P3KGXT()[ this.W];
;
int PgKA1KogGT;
boolean[] pK = !!new CMpa[ 76102396[ ( true[ new Ppz26o()[ false.x9lnwzpfKYNf()]])[ new void[ -null.GLPTiH8zusey()][ -025.VzYlc4]]]][ !!!!new omqgUYSH8sCg().B] = !( !-this.gVr8x()).IFk63RromLyez;
boolean BjotD9p61fSD = !false[ this.oOSMyz8GM7()] = null.UosOnTBl();
void[] BzOrMInVg;
;
c_JKZ2qbLAF4q5[] o;
{
while ( SbPahj().uJuywusyVtA()) ;
;
D01_()[ !!false[ -new VWrQAKo()[ XHjA2()[ !true.Rygwz]]]];
void[] t5NwCiAm;
boolean gBoxf_krH;
boolean uW7Ei;
x00 UIJ95;
void ovStL;
while ( !-( ( null.qKdw6ZkGb).f1()).BjayapjOt()) if ( jgxszdTB.HZ1IYROsUl) return;
{
;
}
return;
{
boolean[][] dr;
}
int[][] eJLsxqyRMtW8;
}
boolean[] oAimz9C6UBsVbu = !this.MjTg() = -( false[ -Bc60TLMB9zb2[ false.ZzBA]])[ this[ -Pm3e2GnLpvF5N().nmKlXLkXKswe]];
void[] ECELnwwJX;
boolean yBgcikATY8F;
;
NaZ[][] xhwWQL4nLTRstI;
boolean[][] Va;
while ( !false[ !new int[ !( M8BaY_yds().U9bg4F()).Ik1Iby()][ !new sXTT9HF0fbAnO().UvnT7eqZP()]]) ;
return;
boolean Ejo_xDVnjWcdom = 0[ false[ PC().OemXWb7]];
}
}
class Hn3htla8a6SZBd {
}
class ZW7N {
}
|
lukmccall/SudokuSolver | Web/RecognizerLib/src/main/java/pl/sudokusolver/recognizerlib/extractors/digits/DigitsExtractStrategy.java | package pl.sudokusolver.recognizerlib.extractors.digits;
import org.opencv.core.Mat;
import java.util.Optional;
/**
* Abstract interpretation of digit extraction algorithm.
*/
public interface DigitsExtractStrategy {
/**
* Looking for digit in given image.
* @param cell matrix with sudoku's cell. This matrix be type of <code>CV_8U</code>.
* @return matrix with digit when algorithm correctly extracted digit, if not it return <code>Optional.Empty()</code>.
*/
Optional<Mat> extract(Mat cell);
}
|
theumitoner/dx2 | app/components/Tables/tableParts/EditableCell.js | <reponame>theumitoner/dx2<gh_stars>1-10
import React from 'react';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import TableCell from '@material-ui/core/TableCell';
import TextField from '@material-ui/core/TextField';
import css from 'dan-styles/Table.scss';
const styles = {};
class EditableCell extends React.Component {
handleUpdate(event) {
const { updateRow, branch } = this.props;
event.persist();
updateRow(event, branch);
}
render() {
const {
cellData,
edited,
inputType,
theme,
} = this.props;
switch (inputType) {
case 'text':
return (
<TableCell padding="default">
<TextField
placeholder={cellData.type}
name={cellData.type}
className={classNames(css.crudInput, theme.palette.type === 'dark' ? css.lightTxt : css.darkTxt)}
id={cellData.id.toString()}
value={cellData.value}
onChange={(event) => this.handleUpdate(event)}
disabled={!edited}
margin="none"
inputProps={{
'aria-label': 'Description',
}}
/>
</TableCell>
);
case 'number':
return (
<TableCell padding="none">
<TextField
id={cellData.id.toString()}
name={cellData.type}
className={classNames(css.crudInput, theme.palette.type === 'dark' ? css.lightTxt : css.darkTxt)}
value={cellData.value}
onChange={(event) => this.handleUpdate(event)}
type="number"
InputLabelProps={{
shrink: true,
}}
margin="none"
disabled={!edited}
/>
</TableCell>
);
default:
return (
<TableCell padding="default">
<TextField
placeholder={cellData.type}
name={cellData.type}
className={classNames(css.crudInput, theme.palette.type === 'dark' ? css.lightTxt : css.darkTxt)}
id={cellData.id.toString()}
value={cellData.value}
onChange={(event) => this.handleUpdate(event)}
disabled={!edited}
margin="none"
inputProps={{
'aria-label': 'Description',
}}
/>
</TableCell>
);
}
}
}
EditableCell.propTypes = {
inputType: PropTypes.string.isRequired,
cellData: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
updateRow: PropTypes.func.isRequired,
edited: PropTypes.bool.isRequired,
branch: PropTypes.string.isRequired,
};
export default withStyles(styles, { withTheme: true })(EditableCell);
|
MirrorTown/wayne | src/backend/models/tekton.go | <filename>src/backend/models/tekton.go
package models
import (
"time"
)
const (
TektonStatusFail = -1
TektonStatusSuc = 1
TektonStatusCheck = 0
TableNameTekton = "tekton"
)
type tektonModel struct{}
type Tekton struct {
Id int64 `orm:"auto" json:"id,omitempty"`
Name string `orm:"unique;index;size(128)" json:"name,omitempty"`
Group string `orm:"index;size(128)" json:"group,omitempty"`
Version string `orm:"index;size(128)" json:"version,omitempty"`
Kind string `orm:"index;size(128)" json:"kind,omitempty"`
Cluster string `orm:"index;size(128)" json:"cluster,omitempty"`
Namespace string `orm:"index;size(128)" json:"namespace,omitempty"`
MetaData string `orm:"type(text)" json:"metaData,omitempty"`
Status int32 `orm:"index;default(0)" json:"status"`
Git string `orm:"index;size(128)" json:"git,omitempty"`
CreateTime *time.Time `orm:"auto_now_add;type(datetime)" json:"createTime,omitempty"`
UpdateTime *time.Time `orm:"auto_now;type(datetime)" json:"updateTime,omitempty"`
}
func (*Tekton) TableName() string {
return TableNameTekton
}
func (*tektonModel) GetNames() ([]Tekton, error) {
tekton := []Tekton{}
_, err := Ormer().
QueryTable(new(Tekton)).
All(&tekton, "Id", "Name")
if err != nil {
return nil, err
}
return tekton, nil
}
func (*tektonModel) GetAllNeedCheck() ([]Tekton, error) {
tekton := []Tekton{}
_, err := Ormer().
QueryTable(new(Tekton)).
Filter("Kind", "pipelineruns").
Filter("Status", TektonStatusCheck).
All(&tekton)
if err != nil {
return nil, err
}
return tekton, nil
}
func (*tektonModel) GetTektonByArgs(name string) ([]Tekton, error) {
tekton := []Tekton{}
_, err := Ormer().
QueryTable(new(Tekton)).
Filter("Name", name).
All(&tekton)
if err != nil {
return nil, err
}
return tekton, nil
}
// Add insert a new Tekton into database and returns
// last inserted Id on success.
func (*tektonModel) AddOrUpdate(m *Tekton) (err error) {
v := &Tekton{Name: m.Name}
//查询是否存在该记录
if err = Ormer().Read(v, "Name"); err == nil {
m.UpdateTime = nil
m.Id = v.Id
_, err = Ormer().Update(m, "MetaData", "Status", "Git")
return
}
m.CreateTime = nil
_, err = Ormer().Insert(m)
return
}
// GetByName retrieves Tekton by Name. Returns error if
// Id doesn't exist
func (*tektonModel) GetByName(name string) (v *Tekton, err error) {
v = &Tekton{Name: name}
if err = Ormer().Read(v, "Name"); err == nil {
return v, nil
}
return nil, err
}
// GetById retrieves Tekton by Id. Returns error if
// Id doesn't exist
func (*tektonModel) GetById(id int64) (v *Tekton, err error) {
v = &Tekton{Id: id}
if err = Ormer().Read(v); err == nil {
return v, nil
}
return nil, err
}
// UpdateTekton updates Tekton by Name and returns error if
// the record to be updated doesn't exist
func (*tektonModel) UpdateByName(m *Tekton) (err error) {
v := Tekton{Name: m.Name}
// ascertain id exists in the database
if err = Ormer().Read(&v, "Name"); err == nil {
m.UpdateTime = nil
_, err = Ormer().Update(m)
return err
}
return
}
// Delete deletes Tekton by Id and returns error if
// the record to be deleted doesn't exist
func (*tektonModel) DeleteByName(name string, logical bool) (err error) {
v := Tekton{Name: name}
// ascertain id exists in the database
if err = Ormer().Read(&v, "Name"); err == nil {
_, err = Ormer().Delete(&v)
return err
}
return
}
|
Infiniverse/v-ol3 | gwt-ol3/src/main/java/org/vaadin/gwtol3/client/tilegrid/XYZTileGridOptions.java | package org.vaadin.gwtol3.client.tilegrid;
import org.vaadin.gwtol3.client.Extent;
/**
* Created by mjhosio on 23/02/15.
*/
public class XYZTileGridOptions extends TileGridOptions {
protected XYZTileGridOptions(){
}
public static final native XYZTileGridOptions create()/*-{
return {};
}-*/;
public final native void setExtent(Extent extent)/*-{
this.extent = extent;
}-*/;
}
|
sara-nl/data-exchange | tasker/tasker/watcher/src/watcher/Watcher.scala | package watcher
import cats.data.Kleisli
import cats.effect.{IO, Resource}
import doobie.util.transactor.Transactor
import io.chrisdavenport.log4cats.slf4j.Slf4jLogger
import nl.surf.dex.database.{Permissions, Tasks}
import nl.surf.dex.messaging.Messages
import nl.surf.dex.messaging.Messages.StartContainer
import nl.surf.dex.storage.{CloudStorage, FilesetOps}
import cats.implicits._
object Watcher {
private val logger = Slf4jLogger.getLogger[IO]
case class Deps(
tickStream: fs2.Stream[IO, _],
storageFactory: CloudStorage => Resource[IO, FilesetOps],
publisher: StartContainer => IO[Unit],
xa: Transactor[IO]
)
def scheduled: Kleisli[IO, Deps, Unit] =
Kleisli {
case Deps(tickStream, storageFactory, publisher, xa) =>
tickStream
.evalTap(_ => logger.debug(s"Fetching eligible permissions from DB"))
.through(_.flatMap { _ =>
fs2.Stream
.evalSeq(Permissions.activeStreamingWithRuns.run(xa))
.evalTap(p =>
logger.debug(
s"Reacting on permission $p \n (already applied for ${p._2.size} datasets"
)
)
.through(DataSet.newDatasetsPipe(storageFactory))
.evalTap {
case (newDatasetPath, permission) =>
for {
_ <-
logger
.info(s"Processing new data set ${newDatasetPath}")
taskId <-
Tasks
.insert(xa)(permission, newDatasetPath)
_ <- logger.info(s"Created a new task in the DB $taskId")
_ <- publisher(
Messages.StartContainer(
s"$taskId",
permission.dataSet.copy(path = newDatasetPath),
permission.algorithm,
permission.algorithmETag.some
)
)
} yield ()
}
.evalTap(ds => logger.info(s"Processing a new data set $ds"))
})
.compile
.drain
}
}
|
sly1061101/ECE391_OS | student-distrib/pit.h | #ifndef _PIT_H
#define _PIT_H
#include "lib.h"
#ifndef ASM
/* Programmable Interval Timer Initialization */
extern void pit_init (int32_t freq);
/* Pit interrupt handler*/
extern void pit_handler(void);
#endif
#endif
|
zipated/src | third_party/mesa/src/src/mesa/drivers/dri/i965/brw_vs.h | <gh_stars>1000+
/*
Copyright (C) Intel Corp. 2006. All Rights Reserved.
Intel funded Tungsten Graphics (http://www.tungstengraphics.com) to
develop this 3D driver.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice (including the
next paragraph) shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************/
/*
* Authors:
* <NAME> <<EMAIL>>
*/
#ifndef BRW_VS_H
#define BRW_VS_H
#include "brw_context.h"
#include "brw_eu.h"
#include "brw_program.h"
#include "program/program.h"
struct brw_vs_prog_key {
GLuint program_string_id;
/**
* Number of channels of the vertex attribute that need GL_FIXED rescaling
*/
uint8_t gl_fixed_input_size[VERT_ATTRIB_MAX];
/**
* True if at least one clip flag is enabled, regardless of whether the
* shader uses clip planes or gl_ClipDistance.
*/
GLuint userclip_active:1;
/**
* How many user clipping planes are being uploaded to the vertex shader as
* push constants.
*/
GLuint nr_userclip_plane_consts:4;
/**
* True if the shader uses gl_ClipDistance, regardless of whether any clip
* flags are enabled.
*/
GLuint uses_clip_distance:1;
/**
* For pre-Gen6 hardware, a bitfield indicating which clipping planes are
* enabled. This is used to compact clip planes.
*
* For Gen6 and later hardware, clip planes are not compacted, so this
* value is zero to avoid provoking unnecessary shader recompiles.
*/
GLuint userclip_planes_enabled_gen_4_5:MAX_CLIP_PLANES;
GLuint copy_edgeflag:1;
GLuint point_coord_replace:8;
GLuint clamp_vertex_color:1;
struct brw_sampler_prog_key_data tex;
};
struct brw_vs_compile {
struct brw_compile func;
struct brw_vs_prog_key key;
struct brw_vs_prog_data prog_data;
int8_t constant_map[1024];
struct brw_vertex_program *vp;
GLuint nr_inputs;
GLuint first_output;
GLuint last_scratch; /**< measured in 32-byte (register size) units */
GLuint first_tmp;
GLuint last_tmp;
struct brw_reg r0;
struct brw_reg r1;
struct brw_reg regs[PROGRAM_ADDRESS+1][128];
struct brw_reg tmp;
struct {
bool used_in_src;
struct brw_reg reg;
} output_regs[128];
struct brw_reg userplane[MAX_CLIP_PLANES];
/** we may need up to 3 constants per instruction (if use_const_buffer) */
struct {
GLint index;
struct brw_reg reg;
} current_const[3];
};
bool brw_vs_emit(struct gl_shader_program *prog, struct brw_vs_compile *c);
void brw_old_vs_emit(struct brw_vs_compile *c);
bool brw_vs_precompile(struct gl_context *ctx, struct gl_shader_program *prog);
void brw_vs_debug_recompile(struct brw_context *brw,
struct gl_shader_program *prog,
const struct brw_vs_prog_key *key);
#endif
|
markusschuettler/middy | packages/error-logger/__tests__/index.js | const test = require('ava')
const sinon = require('sinon')
const middy = require('../../core/index.js')
const errorLogger = require('../index.js')
test('It should log errors and propagate the error', async (t) => {
const error = new Error('something bad happened')
const logger = sinon.spy()
const handler = middy((event, context) => {
throw error
})
handler.use(errorLogger({ logger }))
let response
try {
response = await handler()
} catch (err) {
t.true(logger.calledWith(error))
t.is(response, undefined)
t.deepEqual(err, error)
}
})
test('It should throw error when invalid logger', async (t) => {
const error = new Error('something bad happened')
const logger = false
const handler = middy((event, context) => {
throw error
})
let response
try {
handler.use(errorLogger({ logger }))
response = await handler()
} catch (err) {
t.is(response, undefined)
t.is(
err.message,
'Middleware must be an object containing at least one key among "before", "after", "onError"'
)
}
})
|
EUye9IM/Block_cipher | include/X917.h | <gh_stars>0
#pragma once
#include<NTL/ZZ.h>
#include<bitset>
// 随机 返回 m*64 位 / 8 字节 二进制
NTL::ZZ X917rand(std::bitset<64> const&seed,int m); |
cragkhit/elasticsearch | references/bcb_chosen_clones/selected#583523#26#34.java | void shuffle() {
Random random = new Random();
for (int i = cards.size() - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
Card c = cards.get(j);
cards.set(j, cards.get(i));
cards.set(i, c);
}
}
|
bkvalexey/aiogram_dialog | aiogram_dialog/widgets/media/base.py | from typing import Optional, Any
from aiogram_dialog.manager.manager import DialogManager
from aiogram_dialog.utils import MediaAttachment
from aiogram_dialog.widgets.when import Whenable
class Media(Whenable):
async def render_media(
self,
data: Any,
manager: DialogManager
) -> Optional[MediaAttachment]:
if not self.is_(data, manager):
return None
return await self._render_media(data, manager)
async def _render_media(
self,
data: Any,
manager: DialogManager
) -> Optional[MediaAttachment]:
return None
|
data-provider/core | test-e2e/nodejs/cjs/data/books/providers.js | <reponame>data-provider/core
const MockProvider = require("../mock-provider");
const BOOKS = [
{
id: 1,
author: 1,
title: "1984",
},
{
id: 2,
author: 1,
title: "Animal Farm",
},
{
id: 3,
author: 2,
title: "Farenheit 451",
},
{
id: 4,
author: 3,
title: "Brave new world",
},
{
id: 5,
author: 4,
title: "The Old Man and the Sea",
},
];
const booksProvider = new MockProvider({
id: "books",
data: BOOKS,
});
module.exports = {
booksProvider,
};
|
bingtw/real.taiwanstat.com | vegetable-price/workspace/mobileproj/js/MobilePage.js | <filename>vegetable-price/workspace/mobileproj/js/MobilePage.js
MobilePage = {
list: {},
appendCvItem:
function(){
for(var i = 0; i < DataProcessM.vagNum; i++){
var name = DataProcessM.vagNameMap[DataProcessM.vagIdList[i]];
var id = DataProcessM.vagIdList[i];
$("#chooseVagetable").append("<div class='cvItem cvItemVag' data-vagid='" + id + "'>" + name + "</div>");
}
$(".cvItemVag").click(MobilePage.cvItemVagEvent);
},
menuItemEvent:
function(){
if($(this).data("index") == "0"){
if(list.sortOption == "price"){
$(this).html("改為以價格排序");
list.sortByOptionAndAnimate(list.sortOptionBool, increaseTag);
}else{
$(this).html("改為以漲幅排序");
list.sortByOptionAndAnimate(list.sortOptionBool, "price");
}
} else if($(this).data("index") == "1"){
list.sortOptionBool = !list.sortOptionBool;
list.sortByDefaultAndAnimate();
} else if($(this).data("index") == "2"){
if(isInSettingMode == true){
$(".slider").css("left", "0%");
isInSettingMode = false;
} else {
$(".slider").css("left", "-100%");
isInSettingMode = true;
}
}
},
sitItemEvent:
function(){
increaseTag = $(this).data("mode");
list.show(increaseTag);
if(list.sortOption == "price"){
list.sortByDefaultAndAnimate();
}else{
list.sortByOptionAndAnimate(list.sortOptionBool, increaseTag);
}
},
vagDeselectAllEvent:
function(){
$(".cvItemVag").css("color", "#bbbbbb");
for(var i = 0; i < DataProcessM.vagNum; i++){
list.removeItem(DataProcessM.vagIdList[i]);
}
},
vagSelectAllEvent:
function(){
MobilePage.vagDeselectAllEvent();
$(".cvItemVag").css("color", "#000000");
for(var i = 0; i < DataProcessM.vagNum; i++){
list.addItem(i);
}
},
cvItemVagEvent:
function(){
if( list.idInList($(this).data("vagid")) ){
$(this).css("color", "#bbbbbb");
list.removeItem($(this).data("vagid"));
} else {
$(this).css("color", "#000000");
list.addItem(DataProcessM.getIndexFromId($(this).data("vagid")));
}
}
} |
saga810203/jfw | jfw-util/src/main/java/org/jfw/util/bean/define/FixedValueDefine.java | <gh_stars>0
package org.jfw.util.bean.define;
import org.jfw.util.bean.BeanFactory;
public class FixedValueDefine extends ValueDefine{
private Object value;
@Override
public void init(BeanFactory bf, String name, Class<?> clazz, boolean isRef, String val) throws ConfigException {
this.name = name;
this.clazz = clazz==null?String.class:clazz;
if(this.clazz.equals(Integer.class) ){
this.value = Integer.valueOf(val);
} else if(this.clazz.equals(Byte.class) ){
this.value = Byte.valueOf(val);
} else if(this.clazz.equals(Short.class) ){
this.value = Short.valueOf(val);
} else if(this.clazz.equals(Long.class)){
this.value = Long.valueOf(val);
} else if(this.clazz.equals(Float.class)){
this.value = Float.valueOf(val);
} else if(this.clazz.equals(Double.class)){
this.value = Double.class;
} else if(this.clazz.equals(Boolean.class)){
this.value = Boolean.valueOf(val);
} else if(this.clazz.equals(Character.class)){
this.value = Character.valueOf(val.charAt(0));
} else if(this.clazz.equals(String.class)){
this.value = val;
} else if(this.clazz.equals(java.math.BigInteger.class)){
this.value = new java.math.BigInteger(val);
} else if(this.clazz.equals(java.math.BigDecimal.class)){
this.value = new java.math.BigDecimal(val);
} else if(this.clazz.equals(Class.class)){
try {
this.value = Class.forName(val);
} catch (ClassNotFoundException e) {
throw new ConfigException("invalid class name["+val+"]",e);
}
}
}
public void setValue(Object value){
this.value = value;
}
@Override
public Object getValue(BeanFactory bf) {
return this.value;
}
}
|
metehkaya/Algo-Archive | Problems/AtCoder/Contests/Beginner_Contests/Contest_188/D.Snuke_Prime.cpp | <filename>Problems/AtCoder/Contests/Beginner_Contests/Contest_188/D.Snuke_Prime.cpp
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
using namespace std;
typedef long long LL;
LL ans;
int n,c;
map<int,LL> mp;
int main() {
scanf("%d%d",&n,&c);
for( int i = 0 , x,y,z ; i < n ; i++ ) {
scanf("%d%d%d",&x,&y,&z);
mp[x] += z;
mp[y+1] -= z;
}
LL curr = 0;
map<int,LL>::iterator it1,it2;
it1 = mp.begin();
it2 = it1;
it2++;
while(it2 != mp.end()) {
curr += it1->se;
LL add = min(curr,(LL)c);
int len = it2->fi - it1->fi;
ans += add*len;
it1++,it2++;
}
printf("%lld\n",ans);
return 0;
}
|
nandvar/Sattva-Care | public_html/cloud/data/updater-ocbuvdlb4ccs/backups/nextcloud-11.0.0.10/apps/files_texteditor/l10n/hu_HU.js | OC.L10N.register(
"files_texteditor",
{
"This file is too big to be opened. Please download the file instead." : "Ez a fájl túl nagy a megnyitáshoz. Kérjük, helyette töltsd le a fájlt.",
"Cannot read the file." : "Nem olvasható a fájl!",
"Invalid file path supplied." : "Helytelen elérési utat adott meg.",
"The file is locked." : "A fájl zárolva van.",
"An internal server error occurred." : "Belső szerverhiba történt.",
"Cannot save file as it has been modified since opening" : "Nem tudom a fáljt menteni, mert időközben a tartalma megváltozott.",
"Insufficient permissions" : "Nincs jogosultsága hozzá",
"File path not supplied" : "Fálj elérést nem adta meg",
"File mtime not supplied" : "File módosítási idő nincs megadva",
"saving..." : "mentés...",
"saved!" : "mentve!",
"failed!" : "sikertelen!",
"Saved" : "Elmentve",
"There was a problem saving your changes. Click to resume editing." : "Hiba történt a módosítások mentésekor. Szerkesztés folytatásához kattints ide.",
"An error occurred!" : "Hiba történt!",
"Text file" : "Szövegfájl",
"New text file.txt" : "Új szöveges fájl.txt"
},
"nplurals=2; plural=(n != 1);");
|
rocky341/Gaffer | rest-api/core-rest/src/test/java/uk/gov/gchq/gaffer/rest/ExampleGeneratorTest.java | <gh_stars>1-10
/*
* Copyright 2017-2020 Crown Copyright
*
* 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.
*/
package uk.gov.gchq.gaffer.rest;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.reflections.Reflections;
import uk.gov.gchq.gaffer.commonutil.StreamUtil;
import uk.gov.gchq.gaffer.operation.Operation;
import uk.gov.gchq.gaffer.rest.factory.DefaultGraphFactory;
import uk.gov.gchq.gaffer.rest.factory.GraphFactory;
import uk.gov.gchq.gaffer.rest.service.v2.example.DefaultExamplesFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
public class ExampleGeneratorTest {
private final DefaultExamplesFactory generator = new DefaultExamplesFactory();
private final GraphFactory graphFactory = new DefaultGraphFactory();
public static Collection<Object[]> instancesToTest() {
final Reflections reflections = new Reflections("uk.gov.gchq");
final Set<Class<? extends Operation>> clazzes = reflections.getSubTypesOf(Operation.class);
return clazzes.stream()
.filter(clazz -> !clazz.isInterface() && !Modifier.isAbstract(clazz.getModifiers()))
.map(clazz -> new Object[]{clazz})
.collect(Collectors.toList());
}
@BeforeEach
public void before(@TempDir Path tempDir) throws IllegalAccessException, NoSuchFieldException, IOException {
final File storePropertiesFile = Files.createFile(tempDir.resolve("store.properties")).toFile();
FileUtils.writeLines(storePropertiesFile, IOUtils.readLines(StreamUtil.openStream(ExampleGeneratorTest.class, "store.properties")));
System.setProperty(SystemProperty.STORE_PROPERTIES_PATH, storePropertiesFile.getAbsolutePath());
final File schemaFile = Files.createFile(tempDir.resolve("schema.json")).toFile();
FileUtils.writeLines(schemaFile, IOUtils.readLines(StreamUtil.openStream(ExampleGeneratorTest.class, "/schema/schema.json")));
System.setProperty(SystemProperty.SCHEMA_PATHS, schemaFile.getAbsolutePath());
System.setProperty(SystemProperty.GRAPH_ID, "graphId");
// Manually inject GraphFactory
final Field field = generator.getClass().getDeclaredField("graphFactory");
field.setAccessible(true);
field.set(generator, graphFactory);
}
@ParameterizedTest
@MethodSource("instancesToTest")
public void shouldBuildOperation(final Class<? extends Operation> opClass) throws InstantiationException, IllegalAccessException, JsonProcessingException {
// Given
final Operation operation = generator.generateExample(opClass);
// Then
assertThat(operation, notNullValue());
}
@ParameterizedTest
@MethodSource("instancesToTest")
public void shouldHandleCharField(final Class<? extends Operation> opClass) throws InstantiationException, IllegalAccessException {
// Given
final Operation operation = generator.generateExample(ExampleCharOperation.class);
//Then
assertThat(operation, notNullValue());
}
}
|
RubyAfterAll/material | lib/material/rspec/custom_matchers/have_material_component.rb | # frozen_string_literal: true
# RSpec matcher that tests usages of `.register_component`
#
# class ExampleMaterial < ApplicationMaterial
# register_component :foo
# register_component :bar, max_length: 10
# end
#
# RSpec.describe ExampleMaterial do
# it { is_expected.to have_material_component :foo }
# it { is_expected.to have_material_component(:bar).with_options(max_length: 10) }
# end
RSpec::Matchers.define :have_material_component do |component_name|
match do
@component = test_subject._components[component_name]
@component.present? && @component.instance_of?(Material::Components::Component) && options_matching?
end
def options_matching?
if @options.present?
@options.keys.all? { |option| @component.options[option] == @options[option] }
else
true
end
end
chain :with_options do |options|
@options = options
end
description do
"have material component #{component_name}#{" with options #{@options}" if @options.present?}"
end
failure_message do
"expected to have material component #{component_name}#{" with options #{@options}" if @options.present?}"
end
failure_message_when_negated do
"not expected to have material component #{component_name}#{" with options #{@options}" if @options.present?}"
end
def test_subject
subject.is_a?(Class) ? subject : subject.class
end
end
|
ypsvlq/dale | gale/glob.c | #include <string.h>
#include <stdlib.h>
#include "common.h"
#include "host.h"
#include "object.h"
static int qsortobj(const void *a, const void *b) {
return strcmp((*(struct obj **)a)->str, (*(struct obj **)b)->str);
}
static bool match(char *pattern, const char *str) {
char *p, *p2, *p3;
size_t sz;
bool greedy;
while (1) {
if (!*pattern && !*str) {
return true;
} else if (!*pattern || !*str) {
return false;
} else if (*pattern == '?') {
pattern++;
str++;
} else if (*pattern != '*') {
if (*pattern != *str)
return false;
pattern++;
str++;
} else {
pattern++;
if (!*pattern)
return true;
greedy = true;
if ((p = strchr(pattern, '*'))) {
*p = 0;
p2 = p + 1;
while ((p3 = strchr(p2, '*'))) {
*p3 = 0;
if (!strcmp(pattern, p2)) {
greedy = false;
break;
}
*p3 = '*';
p2 = p3 + 1;
}
if (!strcmp(pattern, p2))
greedy = false;
}
str = strstr(str, pattern);
if (!str) {
if (p)
*p = '*';
return false;
}
if (greedy) {
sz = strlen(pattern);
while (sz && strlen(str) > sz) {
p2 = strstr(str + sz, pattern);
if (p2)
str = p2;
else
break;
}
}
if (p)
*p = '*';
}
}
}
void glob(char *pattern, vec(struct obj *) *out) {
char *mpattern, *dir, *dirend, *nextdir, *file, *path, *path2;
void *d;
vec(struct obj *) vec;
size_t origlen;
mpattern = strchr(pattern, '*');
if (!mpattern) {
if (hostfexists(pattern))
vec_push(*out, objinit(xstrdup(pattern)));
return;
}
dirend = strchr(pattern, '/');
if (dirend && dirend < mpattern) {
while ((nextdir = strchr(dirend+1, '/')) < mpattern && nextdir > dirend)
dirend = nextdir;
mpattern = dirend + 1;
*dirend = 0;
} else if (mpattern > pattern) {
mpattern = pattern;
}
dir = (dirend && !strchr(pattern, '*')) ? pattern : ".";
d = hostdopen(dir);
if (!d)
goto ret_dirend;
if ((nextdir = strchr(mpattern, '/')))
*nextdir = 0;
vec = *out;
origlen = vec_len(vec);
while ((file = hostdread(d))) {
if (match(mpattern, file)) {
path = joinstr(dir, "/", file, NULL);
if (!nextdir) {
vec_push(vec, objinit(path));
} else {
if (hostisdir(path)) {
path2 = joinstr(path, "/", nextdir+1, NULL);
glob(path2, &vec);
free(path2);
}
free(path);
}
}
free(file);
}
hostdclose(d);
qsort(vec+origlen, vec_len(vec)-origlen, sizeof(*vec), qsortobj);
*out = vec;
if (nextdir)
*nextdir = '/';
ret_dirend:
if (dirend)
*dirend = '/';
}
|
truthiswill/lombok-intellij-plugin | src/main/java/de/plushnikov/intellij/plugin/processor/handler/singular/SingularCollectionHandler.java | package de.plushnikov.intellij.plugin.processor.handler.singular;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiVariable;
import de.plushnikov.intellij.plugin.psi.LombokLightMethodBuilder;
import de.plushnikov.intellij.plugin.util.PsiTypeUtil;
import org.jetbrains.annotations.NotNull;
import java.text.MessageFormat;
class SingularCollectionHandler extends AbstractSingularHandler {
SingularCollectionHandler(String qualifiedName, boolean shouldGenerateFullBodyBlock) {
super(qualifiedName, shouldGenerateFullBodyBlock);
}
protected void addOneMethodParameter(@NotNull LombokLightMethodBuilder methodBuilder, @NotNull PsiType psiFieldType, @NotNull String singularName) {
final PsiType oneElementType = PsiTypeUtil.extractOneElementType(psiFieldType, methodBuilder.getManager());
methodBuilder.withParameter(singularName, oneElementType);
}
protected void addAllMethodParameter(@NotNull LombokLightMethodBuilder methodBuilder, @NotNull PsiType psiFieldType, @NotNull String singularName) {
final PsiManager psiManager = methodBuilder.getManager();
final PsiType elementType = PsiTypeUtil.extractAllElementType(psiFieldType, psiManager);
final PsiType collectionType = PsiTypeUtil.createCollectionType(psiManager, CommonClassNames.JAVA_UTIL_COLLECTION, elementType);
methodBuilder.withParameter(singularName, collectionType);
}
protected String getClearMethodBody(String psiFieldName, boolean fluentBuilder) {
final String codeBlockTemplate = "if (this.{0} != null) \n this.{0}.clear();\n {1}";
return MessageFormat.format(codeBlockTemplate, psiFieldName, fluentBuilder ? "\nreturn this;" : "");
}
protected String getOneMethodBody(@NotNull String singularName, @NotNull String psiFieldName, @NotNull PsiType psiFieldType, @NotNull PsiManager psiManager, boolean fluentBuilder) {
final String codeBlockTemplate = "if (this.{0} == null) this.{0} = new java.util.ArrayList<{3}>(); \n" +
"this.{0}.add({1});{2}";
final PsiType oneElementType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager);
return MessageFormat.format(codeBlockTemplate, psiFieldName, singularName, fluentBuilder ? "\nreturn this;" : "",
oneElementType.getCanonicalText(false));
}
protected String getAllMethodBody(@NotNull String singularName, @NotNull PsiType psiFieldType, @NotNull PsiManager psiManager, boolean fluentBuilder) {
final String codeBlockTemplate = "if (this.{0} == null) this.{0} = new java.util.ArrayList<{2}>(); \n"
+ "this.{0}.addAll({0});{1}";
final PsiType oneElementType = PsiTypeUtil.extractOneElementType(psiFieldType, psiManager);
return MessageFormat.format(codeBlockTemplate, singularName, fluentBuilder ? "\nreturn this;" : "",
oneElementType.getCanonicalText(false));
}
@Override
public void appendBuildPrepare(@NotNull StringBuilder buildMethodCode, @NotNull PsiVariable psiVariable, @NotNull String fieldName) {
final PsiManager psiManager = psiVariable.getManager();
final PsiType elementType = PsiTypeUtil.extractOneElementType(psiVariable.getType(), psiManager);
final String selectedFormat;
if (SingularCollectionClassNames.JAVA_UTIL_NAVIGABLE_SET.equals(collectionQualifiedName)) {
selectedFormat = "{2}<{1}> {0} = new java.util.TreeSet<{1}>();\n" +
"if (this.{0} != null) {0}.addAll(this.{0});\n" +
"{0} = java.util.Collections.unmodifiableNavigableSet({0});\n";
} else if (SingularCollectionClassNames.JAVA_UTIL_SORTED_SET.equals(collectionQualifiedName)) {
selectedFormat = "{2}<{1}> {0} = new java.util.TreeSet<{1}>();\n" +
"if (this.{0} != null) {0}.addAll(this.{0});\n" +
"{0} = java.util.Collections.unmodifiableSortedSet({0});\n";
} else if (SingularCollectionClassNames.JAVA_UTIL_SET.equals(collectionQualifiedName)) {
selectedFormat = "{2}<{1}> {0};\n" +
"switch (this.{0} == null ? 0 : this.{0}.size()) '{'\n" +
" case 0: \n" +
" {0} = java.util.Collections.emptySet();\n" +
" break;\n" +
" case 1: \n" +
" {0} = java.util.Collections.singleton(this.{0}.get(0));\n" +
" break;\n" +
" default: \n" +
" {0} = new java.util.LinkedHashSet<{1}>(this.{0}.size() < 1073741824 ? 1 + this.{0}.size() + (this.{0}.size() - 3) / 3 : java.lang.Integer.MAX_VALUE);\n" +
" {0}.addAll(this.{0});\n" +
" {0} = java.util.Collections.unmodifiableSet({0});\n" +
"'}'\n";
} else {
selectedFormat = "{2}<{1}> {0};\n" +
"switch (this.{0} == null ? 0 : this.{0}.size()) '{'\n" +
"case 0: \n" +
" {0} = java.util.Collections.emptyList();\n" +
" break;\n" +
"case 1: \n" +
" {0} = java.util.Collections.singletonList(this.{0}.get(0));\n" +
" break;\n" +
"default: \n" +
" {0} = java.util.Collections.unmodifiableList(new java.util.ArrayList<{1}>(this.{0}));\n" +
"'}'\n";
}
buildMethodCode.append(MessageFormat.format(selectedFormat,
fieldName, elementType.getCanonicalText(false), collectionQualifiedName));
}
}
|
franz1981/infinispan | query/src/main/java/org/infinispan/query/impl/massindex/MassIndexerProgressNotifier.java | <gh_stars>0
package org.infinispan.query.impl.massindex;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.LongAdder;
import org.hibernate.search.engine.reporting.EntityIndexingFailureContext;
import org.hibernate.search.engine.reporting.FailureHandler;
import org.hibernate.search.util.common.SearchException;
import org.infinispan.commons.time.TimeService;
import org.infinispan.query.logging.Log;
import org.infinispan.search.mapper.common.EntityReference;
import org.infinispan.search.mapper.mapping.SearchMapping;
import org.infinispan.util.logging.LogFactory;
class MassIndexerProgressNotifier {
private static final Log log = LogFactory.getLog(MassIndexerProgressNotifier.class, Log.class);
private final MassIndexerProgressMonitor monitor;
private final SearchMapping searchMapping;
private final AtomicReference<RecordedEntityIndexingFailure> entityIndexingFirstFailure = new AtomicReference<>(null);
private final LongAdder entityIndexingFailureCount = new LongAdder();
private FailureHandler failureHandler;
MassIndexerProgressNotifier(SearchMapping searchMapping, TimeService timeService) {
this.monitor = new MassIndexerProgressMonitor(timeService);
this.searchMapping = searchMapping;
}
void notifyDocumentsAdded(int size) {
monitor.documentsAdded(size);
}
void notifyIndexingCompletedSuccessfully() {
monitor.indexingCompleted();
SearchException entityIndexingException = createEntityIndexingExceptionOrNull();
if (entityIndexingException != null) {
throw entityIndexingException;
}
}
<T> void notifyEntityIndexingFailure(Class<T> type, Object id, Throwable throwable) {
RecordedEntityIndexingFailure recordedFailure = new RecordedEntityIndexingFailure(throwable);
entityIndexingFirstFailure.compareAndSet(null, recordedFailure);
entityIndexingFailureCount.increment();
EntityIndexingFailureContext.Builder contextBuilder = EntityIndexingFailureContext.builder();
contextBuilder.throwable(throwable);
// Add minimal information here, but information we're sure we can get
contextBuilder.failingOperation(log.massIndexerIndexingInstance(type.getSimpleName()));
// Add more information here, but information that may not be available if the session completely broke down
// (we're being extra careful here because we don't want to throw an exception while handling and exception)
EntityReference entityReference = EntityReference.withDefaultName(type, id);
if (entityReference != null) {
contextBuilder.entityReference(entityReference);
recordedFailure.entityReference = entityReference;
}
if (failureHandler == null) {
failureHandler = searchMapping.getFailureHandler();
}
failureHandler.handle(contextBuilder.build());
}
private SearchException createEntityIndexingExceptionOrNull() {
RecordedEntityIndexingFailure firstFailure = entityIndexingFirstFailure.get();
if (firstFailure == null) {
return null;
}
return log.massIndexingEntityFailures(entityIndexingFailureCount.longValue(), firstFailure.entityReference, firstFailure.throwable.getMessage(), firstFailure.throwable);
}
private static class RecordedEntityIndexingFailure {
private Throwable throwable;
private EntityReference entityReference;
RecordedEntityIndexingFailure(Throwable throwable) {
this.throwable = throwable;
}
}
}
|
MacSourcePorts/OpenJKDF2 | src/Engine/sithSprite.h | <gh_stars>0
#ifndef _SITHSPRITE_H
#define _SITHSPRITE_H
#include "types.h"
#include "globals.h"
#define sithSprite_Startup_ADDR (0x004F2130)
#define sithSprite_Shutdown_ADDR (0x004F2170)
#define sithSprite_Load_ADDR (0x004F2190)
#define sithSprite_FreeEntry_ADDR (0x004F2330)
#define sithSprite_LoadEntry_ADDR (0x004F23B0)
#define sithSprite_New_ADDR (0x004F25F0)
int sithSprite_Startup();
void sithSprite_Shutdown();
int sithSprite_Load(sithWorld *world, int a2);
void sithSprite_FreeEntry(sithWorld *world);
rdSprite* sithSprite_LoadEntry(char *fpath);
int sithSprite_New(sithWorld *world, int num);
#endif // _SITHSPRITE_H
|
SAFE-anwang/safe | src/app/app.cpp | <gh_stars>10-100
#include "app.h"
#include "app.pb.h"
#include "main.h"
#include "validation.h"
#include "utilstrencodings.h"
#include <algorithm>
using namespace std;
uint16_t g_nAppHeaderVersion = 1;
uint16_t g_nAppDataVersion = 1;
string g_strSafeAssetId = "cfe2450bf016e2ad8130e4996960a32e0686c1704b62a6ad02e49ee805a9b288";
string g_strSafePayId = "a4bea6705cd38d535e873da1c9ad897048b6bbc8e286ca9b28bd18bb22eedcc9";
CAmount APP_OUT_VALUE = 0.0001 * COIN;
static string szKeyWords[] = {
"安资", "安聊", "安投", "安付", "安資",
"SafeAsset", "SafeChat", "SafeVote", "SafePay", "AnWang", "BankLedger", "ElectionChain", "SafeNetSpace", "DarkNetSpace",
"SAFE", "ELT", "DNC", "DNC2",
"BTC", "ETH", "EOS", "LTC", "DASH", "ETC",
"Bitcoin", "Ethereum", "LiteCoin", "Ethereum Classic",
"人民币", "港元", "港币", "澳门元", "澳门币", "新台币", "RMB", "CNY", "HKD", "MOP", "TWD", "人民幣", "港幣", "澳門元", "澳門幣", "新台幣", "澳门幣",
"mSAFE", "μSAFE", "duffs", "tSAFE", "mtSAFE", "μtSAFE", "tduffs", "AnYou", "SafeGame"
};
static string szSimilarKeyWords[] = {
"安网", "银链", "安網", "銀鏈", "銀链", "银鏈", "安游", "安遊"
};
string TrimString(const string& strValue)
{
string strTemp = strValue;
strTemp.erase(0, strTemp.find_first_not_of(" "));
strTemp.erase(strTemp.find_last_not_of(" ") + 1);
return strTemp;
}
string ToLower(const string& strValue)
{
string strTemp = strValue;
transform(strTemp.begin(), strTemp.end(), strTemp.begin(), (int (*)(int))tolower);
return strTemp;
}
bool IsKeyWord(const string& strValue)
{
string strTempValue = ToLower(strValue);
// compare with fixed keywords
for(unsigned int i = 0; i < sizeof(szKeyWords) / sizeof(string); i++)
{
string strTemp = ToLower(szKeyWords[i]);
if(strTempValue == strTemp)
return true;
}
// compare with similar keyword
for(unsigned int i = 0; i < sizeof(szSimilarKeyWords) / sizeof(string); i++)
{
string strTemp = ToLower(szSimilarKeyWords[i]);
if(strTempValue.find(strTemp) != string::npos)
return true;
}
return false;
}
bool IsContainSpace(const string& strValue)
{
return strValue.find(' ') != string::npos || strValue.find('\t') != string::npos;
}
bool IsValidUrl(const string& strUrl)
{
if(strUrl == "http://" || strUrl == "https://")
return false;
return ((strUrl.find("http://") == 0) || (strUrl.find("https://") == 0));
}
static void FillHeader(const CAppHeader& header, vector<unsigned char>& vHeader)
{
// 1. flag: safe
vHeader.push_back('s');
vHeader.push_back('a');
vHeader.push_back('f');
vHeader.push_back('e');
// 2. version (2 bytes)
const unsigned char* pVersion = (const unsigned char*)&header.nVersion;
vHeader.push_back(pVersion[0]);
vHeader.push_back(pVersion[1]);
// 3. app id (32 bytes)
const unsigned char* pAppId = header.appId.begin();
for(unsigned int i = 0; i < header.appId.size(); i++)
vHeader.push_back(pAppId[i]);
// 4. app command (4 bytes)
const unsigned char* pAppCmd = (const unsigned char*)&header.nAppCmd;
vHeader.push_back(pAppCmd[0]);
vHeader.push_back(pAppCmd[1]);
vHeader.push_back(pAppCmd[2]);
vHeader.push_back(pAppCmd[3]);
}
vector<unsigned char> FillRegisterData(const string& strAdminAddress, const CAppHeader& header, const CAppData& appData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::RegisterData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_adminaddress(strAdminAddress);
data.set_appname(appData.strAppName);
data.set_appdesc(appData.strAppDesc);
data.set_devtype((const unsigned char*)&appData.nDevType, sizeof(appData.nDevType));
data.set_devname(appData.strDevName);
data.set_weburl(appData.strWebUrl);
data.set_logourl(appData.strLogoUrl);
data.set_coverurl(appData.strCoverUrl);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillAuthData(const string& strAdminAddress, const CAppHeader& header, const CAuthData& authData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::AuthData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_settype((const unsigned char*)&authData.nSetType, sizeof(authData.nSetType));
data.set_adminaddress(strAdminAddress);
data.set_useraddress(authData.strUserAddress);
data.set_auth(authData.nAuth);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillExtendData(const CAppHeader& header, const CExtendData& extendData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::ExtendData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_auth(extendData.nAuth);
data.set_extenddata(extendData.strExtendData);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillIssueData(const CAppHeader& header, const CAssetData& assetData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::IssueData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_shortname(assetData.strShortName);
data.set_assetname(assetData.strAssetName);
data.set_assetdesc(assetData.strAssetDesc);
data.set_assetunit(assetData.strAssetUnit);
data.set_totalamount(assetData.nTotalAmount);
data.set_firstissueamount(assetData.nFirstIssueAmount);
data.set_firstactualamount(assetData.nFirstActualAmount);
data.set_decimals((const unsigned char*)&assetData.nDecimals, sizeof(assetData.nDecimals));
data.set_destory(assetData.bDestory);
data.set_paycandy(assetData.bPayCandy);
data.set_candyamount(assetData.nCandyAmount);
data.set_candyexpired((const unsigned char*)&assetData.nCandyExpired, sizeof(assetData.nCandyExpired));
data.set_remarks(assetData.strRemarks);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillCommonData(const CAppHeader& header, const CCommonData& commonData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::CommonData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_assetid(commonData.assetId.begin(), commonData.assetId.size());
data.set_amount(commonData.nAmount);
data.set_remarks(commonData.strRemarks);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillPutCandyData(const CAppHeader& header, const CPutCandyData& candyData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::PutCandyData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_assetid(candyData.assetId.begin(), candyData.assetId.size());
data.set_amount(candyData.nAmount);
data.set_expired((const unsigned char*)&candyData.nExpired, sizeof(candyData.nExpired));
data.set_remarks(candyData.strRemarks);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillGetCandyData(const CAppHeader& header, const CGetCandyData& candyData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::GetCandyData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_assetid(candyData.assetId.begin(), candyData.assetId.size());
data.set_amount(candyData.nAmount);
data.set_remarks(candyData.strRemarks);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
vector<unsigned char> FillTransferSafeData(const CAppHeader& header, const CTransferSafeData& safeData)
{
vector<unsigned char> vData;
FillHeader(header, vData);
App::TransferSafeData data;
uint16_t nVersion = g_nAppDataVersion;
data.set_version((const unsigned char*)&nVersion, sizeof(nVersion));
data.set_remarks(safeData.strRemarks);
string strData;
data.SerializeToString(&strData);
unsigned int nSize = data.ByteSize();
const unsigned char* pData = (const unsigned char*)strData.data();
for(unsigned int i = 0; i < nSize; i++)
vData.push_back(pData[i]);
return vData;
}
static void ParseHeader(const vector<unsigned char>& vData, CAppHeader& header, unsigned int& nOffset)
{
nOffset = TXOUT_RESERVE_MIN_SIZE;
// 1. version (2 bytes)
header.nVersion = *(uint16_t*)&vData[nOffset];
nOffset += sizeof(header.nVersion);
// 2. app id (32 bytes)
vector<unsigned char> vAppId;
for(unsigned int i = 0; i < header.appId.size(); i++)
vAppId.push_back(vData[nOffset++]);
header.appId = uint256(vAppId);
// 3. app command (4 bytes)
header.nAppCmd = *(uint32_t*)&vData[nOffset];
nOffset += sizeof(header.nAppCmd);
}
bool ParseReserve(const vector<unsigned char>& vReserve, CAppHeader& header, vector<unsigned char>& vData)
{
if(vReserve.size() <= TXOUT_RESERVE_MIN_SIZE + sizeof(uint16_t) + 32 + sizeof(uint32_t))
return false;
//SPOS no need to parse
unsigned int nStartSPOSOffset = TXOUT_RESERVE_MIN_SIZE;
std::vector<unsigned char> vchConAlg;
for(unsigned int k = 0; k < 4; k++)
vchConAlg.push_back(vReserve[nStartSPOSOffset++]);
if (vchConAlg[0] == 's' && vchConAlg[1] == 'p' && vchConAlg[2] == 'o' && vchConAlg[3] == 's')
return false;
unsigned int nOffset = 0;
ParseHeader(vReserve, header, nOffset);
for(unsigned int i = nOffset; i < vReserve.size(); i++)
vData.push_back(vReserve[i]);
return true;
}
bool ParseRegisterData(const vector<unsigned char>& vAppData, CAppData& appData, string* pAdminAddress)
{
App::RegisterData data;
if(!data.ParseFromArray(&vAppData[0], vAppData.size()))
return false;
if(pAdminAddress) *pAdminAddress = data.adminaddress();
appData.strAppName = data.appname();
appData.strAppDesc = data.appdesc();
appData.nDevType = *(uint8_t*)data.devtype().data();
appData.strDevName = data.devname();
appData.strWebUrl = data.weburl();
appData.strLogoUrl = data.logourl();
appData.strCoverUrl = data.coverurl();
return true;
}
bool ParseAuthData(const vector<unsigned char>& vAuthData, CAuthData& authData, string* pAdminAddress)
{
App::AuthData data;
if(!data.ParseFromArray(&vAuthData[0], vAuthData.size()))
return false;
if(pAdminAddress) *pAdminAddress = data.adminaddress();
authData.nSetType = *(uint8_t*)data.settype().data();
authData.strUserAddress = data.useraddress();
authData.nAuth = data.auth();
return true;
}
bool ParseExtendData(const vector<unsigned char>& vExtendData, CExtendData& extendData)
{
App::ExtendData data;
if(!data.ParseFromArray(&vExtendData[0], vExtendData.size()))
return false;
extendData.nAuth = data.auth();
extendData.strExtendData = data.extenddata();
return true;
}
bool ParseIssueData(const std::vector<unsigned char>& vAssetData, CAssetData& assetData)
{
App::IssueData data;
if(!data.ParseFromArray(&vAssetData[0], vAssetData.size()))
return false;
assetData.strShortName = data.shortname();
assetData.strAssetName = data.assetname();
assetData.strAssetDesc = data.assetdesc();
assetData.strAssetUnit = data.assetunit();
assetData.nTotalAmount = data.totalamount();
assetData.nFirstIssueAmount = data.firstissueamount();
assetData.nFirstActualAmount = data.firstactualamount();
assetData.nDecimals = *(uint8_t*)data.decimals().data();
assetData.bDestory = data.destory();
assetData.bPayCandy = data.paycandy();
assetData.nCandyAmount = data.candyamount();
assetData.nCandyExpired = *(uint16_t*)data.candyexpired().data();
assetData.strRemarks = data.remarks();
return true;
}
bool ParseCommonData(const std::vector<unsigned char>& vCommonData, CCommonData& commonData)
{
App::CommonData data;
if(!data.ParseFromArray(&vCommonData[0], vCommonData.size()))
return false;
std::vector<unsigned char> vAssetId;
unsigned int nSize = data.assetid().size();
unsigned char* pAssetId = (unsigned char*)data.assetid().data();
for(unsigned int i = 0; i < nSize; i++)
vAssetId.push_back(pAssetId[i]);
commonData.assetId = uint256(vAssetId);
commonData.nAmount = data.amount();
commonData.strRemarks = data.remarks();
return true;
}
bool ParsePutCandyData(const std::vector<unsigned char>& vCandyData, CPutCandyData& candyData)
{
App::PutCandyData data;
if(!data.ParseFromArray(&vCandyData[0], vCandyData.size()))
return false;
std::vector<unsigned char> vAssetId;
unsigned int nSize = data.assetid().size();
unsigned char* pAssetId = (unsigned char*)data.assetid().data();
for(unsigned int i = 0; i < nSize; i++)
vAssetId.push_back(pAssetId[i]);
candyData.assetId = uint256(vAssetId);
candyData.nAmount = data.amount();
candyData.nExpired = *(uint16_t*)data.expired().data();
candyData.strRemarks = data.remarks();
return true;
}
bool ParseGetCandyData(const std::vector<unsigned char>& vCandyData, CGetCandyData& candyData)
{
App::GetCandyData data;
if(!data.ParseFromArray(&vCandyData[0], vCandyData.size()))
return false;
std::vector<unsigned char> vAssetId;
unsigned int nSize = data.assetid().size();
unsigned char* pAssetId = (unsigned char*)data.assetid().data();
for(unsigned int i = 0; i < nSize; i++)
vAssetId.push_back(pAssetId[i]);
candyData.assetId = uint256(vAssetId);
candyData.nAmount = data.amount();
candyData.strRemarks = data.remarks();
return true;
}
bool ParseTransferSafeData(const vector<unsigned char>& vSafeData, CTransferSafeData& safeData)
{
App::TransferSafeData data;
if(!data.ParseFromArray(&vSafeData[0], vSafeData.size()))
return false;
safeData.strRemarks = data.remarks();
return true;
}
bool ExistAppName(const string& strAppName, const bool fWithMempool)
{
uint256 appId;
return GetAppIdByAppName(strAppName, appId, fWithMempool);
}
bool ExistAppId(const uint256& appId, const bool fWithMempool)
{
CAppId_AppInfo_IndexValue appInfo;
return GetAppInfoByAppId(appId, appInfo, fWithMempool);
}
bool ExistShortName(const std::string& strShortName, const bool fWithMempool)
{
uint256 assetId;
return GetAssetIdByShortName(strShortName, assetId, fWithMempool);
}
bool ExistAssetName(const std::string& strAssetName, const bool fWithMempool)
{
uint256 assetId;
return GetAssetIdByAssetName(strAssetName, assetId, fWithMempool);
}
bool ExistAssetId(const uint256& assetId, const bool fWithMempool)
{
CAssetId_AssetInfo_IndexValue assetInfo;
return GetAssetInfoByAssetId(assetId, assetInfo, fWithMempool);
}
|
subelsky/sproutcore-abbot | lib/sproutcore/builders/base.rb | module SC
# Builder classes implement the more complex algorithms for building
# resources in SproutCore such as building HTML, JavaScript or CSS.
# Builders are usually invoked from within build tasks which are, in-turn,
# selected by the manifest.
#
module Builder
# The base class extended by most builder classes. This contains some
# default functionality for handling loading and writing files. Usually
# you will want to consult the specific classes instead for more info.
#
class Base
# entry the current builder is working on
attr_accessor :entry
def initialize(entry=nil)
@entry =entry
end
# override this method in subclasses to actually do build
def build(dst_path)
end
# main entry called by build tasls
def self.build(entry, dst_path)
new(entry).build(dst_path)
end
# Reads the lines from the source file. If the source file does not
# exist, returns empty array.
def readlines(src_path)
if File.exist?(src_path) && !File.directory?(src_path)
File.readlines(src_path)
else
[]
end
end
# joins the array of lines. this is where you can also do any final
# post-processing on the build
def joinlines(lines)
lines * ""
end
# writes the passed lines to the named file
def writelines(dst_path, lines)
FileUtils.mkdir_p(File.dirname(dst_path))
f = File.open(dst_path, 'w')
f.write joinlines(lines)
f.close
end
# Handles occurances of sc_static() or static_url()
def replace_static_url(line)
line.gsub(/(sc_static|static_url)\(\s*['"](.+)['"]\s*\)/) do | rsrc |
static_entry = entry.manifest.find_entry($2)
static_url(static_entry.nil? ? '' : static_entry.cacheable_url)
end
end
# Generates the proper output for a given static url and a given target
# this is often overridden by subclasses. the default just wraps in
# quotes.
def static_url(url='')
["'", url.gsub('"','\"'),"'"].join('')
end
end # class
end # module Builder
end # module SC |
pcsx-redux/nugget | openbios/cdrom/statemachine.h | /*
MIT License
Copyright (c) 2020 PCSX-Redux authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include "common/compiler/stdint.h"
int cdromSeekL(uint8_t *msf);
int cdromGetStatus(uint8_t *responsePtr);
int cdromRead(int count, void *buffer, uint32_t mode);
int cdromSetMode(uint32_t mode);
int cdromIOVerifier();
int cdromDMAVerifier();
void cdromIOHandler();
void cdromDMAHandler();
void getLastCDRomError(uint8_t *err1, uint8_t *err2);
int cdromInnerInit();
enum AutoAckType {
AUTOACK_IO = 0,
AUTOACK_DMA = 1,
};
int setCDRomIRQAutoAck(enum AutoAckType type, int value);
void enqueueCDRomHandlers();
void dequeueCDRomHandlers();
|
Pandrex247/patched-src-eclipselink | sdo/eclipselink.sdo.test/src/org/eclipse/persistence/testing/sdo/helper/xmlhelper/loadandsave/substitutiongroups/SingleValueNonBaseTypeTestCases.java | /*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.xmlhelper.loadandsave.substitutiongroups;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Type;
import commonj.sdo.helper.XMLDocument;
import java.io.FileReader;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import junit.textui.TestRunner;
import org.eclipse.persistence.sdo.SDOConstants;
import org.eclipse.persistence.sdo.helper.DefaultSchemaResolver;
import org.eclipse.persistence.sdo.helper.SDOClassGenerator;
import org.eclipse.persistence.sdo.helper.SDOXSDHelper;
import org.w3c.dom.Document;
import org.eclipse.persistence.testing.sdo.helper.xmlhelper.loadandsave.LoadAndSaveTestCases;
public class SingleValueNonBaseTypeTestCases extends LoadAndSaveTestCases {
public SingleValueNonBaseTypeTestCases(String name) {
super(name);
}
public static void main(String[] args) {
String[] arguments = { "-c", "org.eclipse.persistence.testing.sdo.helper.xmlhelper.loadandsave.substitutiongroups.SingleValueNonBaseTypeTestCases" };
TestRunner.main(arguments);
}
protected String getSchemaName() {
return getSchemaLocation() + "SubstitutionGroup.xsd";
}
protected String getControlFileName() {
return ("./org/eclipse/persistence/testing/sdo/helper/xmlhelper/loadandsave/substitutiongroups/single_value_non_base.xml");
}
protected String getControlWriteFileName() {
return ("./org/eclipse/persistence/testing/sdo/helper/xmlhelper/loadandsave/substitutiongroups/single_value_non_base.xml");
}
protected String getNoSchemaControlFileName() {
return "";
}
protected String getControlRootURI() {
return "TEST/NS";
}
protected String getControlRootName() {
return "employee-data";
}
protected String getRootInterfaceName() {
return "EmployeeType";
}
public void testNoSchemaLoadFromInputStreamSaveDataObjectToString() throws Exception {
}
protected String getSchemaLocation() {
return "./org/eclipse/persistence/testing/sdo/helper/xmlhelper/loadandsave/substitutiongroups/";
}
public void registerTypes() {
}
protected List<String> getPackages() {
List<String> packages = new ArrayList<String>();
packages.add("test/ns");
return packages;
}
}
|
augsun/JXEfficient | JXEfficient/Classes/JXEfficient/UIView/JXTagLayout/JXTagFlowLayout.h | <reponame>augsun/JXEfficient
//
// JXTagFlowLayout.h
// JXEfficient
//
// Created by augsun on 2/16/18.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
UICollectionView 的 itemCell 不等宽 flowLayout.
*/
@interface JXTagFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, assign) CGFloat itemHeight; ///< 固定行高
@property (nonatomic, copy) CGFloat (^widthForItem)(NSIndexPath *indexPath); ///< 请求宽度
@end
NS_ASSUME_NONNULL_END
|
zyk6271/SYR_NEW | applications/rtc.c | #include <rtthread.h>
#include <rtdevice.h>
#include <stm32l4xx.h>
#include "pin_config.h"
#include "Flashwork.h"
#include "lcd_display.h"
#include "adcwork.h"
#define DBG_TAG "RTC"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
rt_timer_t RTC_Timer=RT_NULL;
rt_thread_t RTC_Task=RT_NULL;
rt_thread_t RTC_Check_Thread=RT_NULL;
rt_sem_t RTC_Sem = RT_NULL;
rt_sem_t RTC_Check_Sem = RT_NULL;
RTC_HandleTypeDef RtcHandle;
extern uint8_t Reminder_Week;
extern uint8_t Reminder_Day;
extern uint8_t Reminder_Enable;
extern uint8_t Automatic_Week;
extern uint8_t Automatic_Day;
extern uint8_t Automatic_Enable;
extern uint8_t LCD_Flag;
extern uint8_t RTC_Wakeup_Flag;
extern uint8_t Low_Power_Flag;
uint32_t RTC_Reminder_Time = 0;
uint32_t RTC_Automatic_Time = 0;
uint32_t Reminder_Time = 0;
uint32_t Automatic_Time = 0;
void RTC_Timer_Entry(void)
{
if(Reminder_Enable)
{
RTC_Reminder_Time++;
LOG_D("RTC_Reminder_Time is %d\r\n",RTC_Reminder_Time);
}
if(Automatic_Enable)
{
RTC_Automatic_Time++;
LOG_D("RTC_Automatic_Time is %d\r\n",RTC_Automatic_Time);
}
}
void RTC_Check(void)
{
rt_sem_release(RTC_Check_Sem);
}
void RTC_Clear(void)
{
RTC_Reminder_Time = 0;
RTC_Automatic_Time = 0;
}
void RTC_Reset(void)
{
RTC_Reminder_Time = 0;
RTC_Automatic_Time = 0;
Flash_Set(16,0);
Flash_Set(17,0);
}
uint8_t RTC_Event_Flag = 0;
extern uint8_t screen_reload;
void RTC_Check_Callback(void *parameter)
{
while(1)
{
if(rt_sem_take(RTC_Check_Sem, 0) == RT_EOK)
{
LOG_D("RTC Check For Two Timers\r\n");
RTC_Event_Flag = 0;
if(Reminder_Enable)
{
if(RTC_Reminder_Time >= Reminder_Week*7*24+Reminder_Day*24)
{
RTC_Reminder_Time = 0;
RTC_Event_Flag = 1;
Flash_Set(16,0);
LOG_D("Reminder_Enable\r\n");
screen_reload = 0;
if(Low_Power_Flag)
{
LcdInit();
LCD_Refresh();
}
ScreenTimerRefresh();
JumptoReminder();
}
else
{
Flash_Set(16,RTC_Reminder_Time);
}
}
if(Automatic_Enable)
{
if(RTC_Automatic_Time >= Automatic_Week*7*24+Automatic_Day*24 )
{
RTC_Automatic_Time = 0;
RTC_Event_Flag = 1;
Flash_Set(17,0);
screen_reload = 0;
LOG_D("Automatic_Enable\r\n");
if(Low_Power_Flag)
{
LcdInit();
LCD_Refresh();
ScreenTimerRefresh();
}
JumptoAutomatic();
}
else
{
Flash_Set(17,RTC_Automatic_Time);
}
}
if(RTC_Event_Flag == 0 && Low_Power_Flag==1)
{
LOG_D("EnterLowPower\r\n");
EnterLowPower();
}
}
rt_thread_mdelay(10);
}
}
void RTC_Check_Init(void)
{
RTC_Check_Sem = rt_sem_create("RTC_Check_Sem", 0, RT_IPC_FLAG_FIFO);
RTC_Check_Thread = rt_thread_create("RTC_Check", RTC_Check_Callback, RT_NULL, 2048, 10, 10);
if(RTC_Check_Thread!=RT_NULL)rt_thread_startup(RTC_Check_Thread);
}
void RTC_AlarmConfig(void)
{
RTC_DateTypeDef sdatestructure;
RTC_TimeTypeDef stimestructure;
RTC_AlarmTypeDef salarmstructure;
sdatestructure.Year = 0x14;
sdatestructure.Month = RTC_MONTH_FEBRUARY;
sdatestructure.Date = 0x18;
sdatestructure.WeekDay = RTC_WEEKDAY_TUESDAY;
if(HAL_RTC_SetDate(&RtcHandle,&sdatestructure,RTC_FORMAT_BIN) != HAL_OK)
{
/* Initialization Error */
}
stimestructure.Hours = 0;
stimestructure.Minutes = 0;
stimestructure.Seconds = 0;
stimestructure.TimeFormat = RTC_HOURFORMAT12_AM;
stimestructure.DayLightSaving = RTC_DAYLIGHTSAVING_NONE ;
stimestructure.StoreOperation = RTC_STOREOPERATION_RESET;
if(HAL_RTC_SetTime(&RtcHandle,&stimestructure,RTC_FORMAT_BIN) != HAL_OK)
{
/* Initialization Error */
}
salarmstructure.Alarm = RTC_ALARM_A;
salarmstructure.AlarmDateWeekDay = RTC_WEEKDAY_MONDAY;
salarmstructure.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY;
salarmstructure.AlarmMask = RTC_ALARMMASK_DATEWEEKDAY;
salarmstructure.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
salarmstructure.AlarmTime.TimeFormat = RTC_HOURFORMAT12_AM;
salarmstructure.AlarmTime.Hours = 1;
salarmstructure.AlarmTime.Minutes = 0;
salarmstructure.AlarmTime.Seconds = 0;
salarmstructure.AlarmTime.SubSeconds = 0;
if(HAL_RTC_SetAlarm_IT(&RtcHandle,&salarmstructure,RTC_FORMAT_BIN) == HAL_OK)
{
LOG_D("RTC Alarm Set Ok\r\n");
}
}
void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *RtcHandle)
{
RTC_TimeTypeDef sTime = {0};
sTime.Hours = 0;
sTime.Minutes = 0;
sTime.Seconds = 0;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
HAL_RTC_SetTime(RtcHandle, &sTime, RTC_FORMAT_BIN);
RTC_Timer_Entry();
RTC_Check();
}
void RTC_Init(void)
{
RTC_Reminder_Time = Flash_Get(16);
RTC_Automatic_Time = Flash_Get(17);
Reminder_Time = Reminder_Week*7*24+Reminder_Day*24;
Automatic_Time = Automatic_Week*7*24+Automatic_Day*24;
__HAL_RCC_RTC_ENABLE();
HAL_NVIC_SetPriority(RTC_Alarm_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
RtcHandle.Instance = RTC;
RtcHandle.Init.HourFormat = RTC_HOURFORMAT_24;
RtcHandle.Init.AsynchPrediv = 127;
RtcHandle.Init.SynchPrediv = 255;
RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE;
RtcHandle.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
if (HAL_RTC_Init(&RtcHandle) != HAL_OK)
{
}
RTC_AlarmConfig();
RTC_Check_Init();
LOG_D("RTC Init is Success\r\n");
}
MSH_CMD_EXPORT(RTC_Init,RTC_Init);
void RTC_Alarm_IRQHandler(void)
{
if(Low_Power_Flag)
{
SystemClock_Config();
AfterWake();
LOG_I("RTC Wake Up\r\n");
}
HAL_RTC_AlarmIRQHandler(&RtcHandle);
}
|
egraba/vbox_openbsd | VirtualBox-5.0.0/src/VBox/Frontends/VirtualBox/src/settings/global/UIGlobalSettingsNetworkDetailsNAT.h | /* $Id: $ */
/** @file
* VBox Qt GUI - UIGlobalSettingsNetworkDetailsNAT class declaration.
*/
/*
* Copyright (C) 2009-2013 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#ifndef __UIGlobalSettingsNetworkDetailsNAT_h__
#define __UIGlobalSettingsNetworkDetailsNAT_h__
/* Local includes */
#include "QIDialog.h"
#include "QIWithRetranslateUI.h"
#include "UIGlobalSettingsNetworkDetailsNAT.gen.h"
/* Forward decalrations: */
struct UIDataNetworkNAT;
/* Global settings / Network page / Details sub-dialog: */
class UIGlobalSettingsNetworkDetailsNAT : public QIWithRetranslateUI2<QIDialog>, public Ui::UIGlobalSettingsNetworkDetailsNAT
{
Q_OBJECT;
public:
/* Constructor: */
UIGlobalSettingsNetworkDetailsNAT(QWidget *pParent, UIDataNetworkNAT &data);
protected:
/* Handler: Translation stuff: */
void retranslateUi();
/* Handler: Polish event: */
void polishEvent(QShowEvent *pEvent);
private slots:
/* Handler: Port-forwarding stuff: */
void sltEditPortForwarding();
/* Handler: Dialog stuff: */
void accept();
private:
/* Helpers: Load/Save stuff: */
void load();
void save();
/* Variable: External data reference: */
UIDataNetworkNAT &m_data;
};
#endif /* __UIGlobalSettingsNetworkDetailsNAT_h__ */
|
gitoscc/simples | simple/src/com/google/devtools/simple/runtime/components/TextBox.java | /*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.simple.runtime.components;
import com.google.devtools.simple.runtime.annotations.SimpleComponent;
import com.google.devtools.simple.runtime.annotations.SimpleEvent;
import com.google.devtools.simple.runtime.annotations.SimpleObject;
import com.google.devtools.simple.runtime.annotations.SimpleProperty;
import com.google.devtools.simple.runtime.parameters.BooleanReferenceParameter;
/**
* Simple text box component.
*
* @author <NAME>
*/
@SimpleComponent
@SimpleObject
public interface TextBox extends TextComponent {
/**
* Default GotFocus event handler.
*/
@SimpleEvent
void GotFocus();
/**
* Default LostFocus event handler.
*/
@SimpleEvent
void LostFocus();
/**
* Default Validate event handler.
*
* @param text text to validate
* @param accept must be set to {@code false} to reject the text input, the
* default value is {@code true}
*/
@SimpleEvent
void Validate(String text, BooleanReferenceParameter accept);
/**
* Enabled property getter.
*
* @return {@code true} indicates enabled, {@code false} disabled
*/
@SimpleProperty
boolean Enabled();
/**
* Enabled property setter.
*
* @param enabled {@code true} for enabled, {@code false} disabled
*/
@SimpleProperty(type = SimpleProperty.PROPERTY_TYPE_BOOLEAN,
initializer = "True")
void Enabled(boolean enabled);
/**
* Hint property getter method.
*
* @return hint text
*/
@SimpleProperty
String Hint();
/**
* Hint property setter method.
*
* @param hint hint text
*/
@SimpleProperty(type = SimpleProperty.PROPERTY_TYPE_STRING,
initializer = "\"\"")
void Hint(String hint);
}
|
cquiroz/ocs | bundle/edu.gemini.sp.vcs/src/main/scala/edu/gemini/sp/vcs2/MergeContext.scala | package edu.gemini.sp.vcs2
import edu.gemini.pot.sp.version._
import edu.gemini.pot.sp.{ISPNode, ISPProgram, SPNodeKey}
import edu.gemini.spModel.rich.pot.sp._
import scalaz._
import Scalaz._
/** Provides a common interface to queries we must make during the merge process
* about the local and remote versions of a program. The local context is
* based upon the local `ISPProgram` which the remote context is extracted from
* the `Diff`s we collect from the remote program. */
sealed trait ProgContext {
def parent(k: SPNodeKey): Option[SPNodeKey]
def vm: VersionMap
def version(k: SPNodeKey): NodeVersions = vm.getOrElse(k, EmptyNodeVersions)
/** Determines whether the given node has been seen before in this program,
* regardless of whether it is currently present. */
def isKnown(k: SPNodeKey): Boolean = vm.contains(k)
/** Determines whether the given node is still present in this program.
* Note that `isPresent` implies `isKnown` but not vice versa. */
def isPresent(k: SPNodeKey): Boolean
/** Determines whether the given node was previously known in this program
* but has been deleted. This is as opposed to a node that is missing but
* has never been seen before. Here `isDeleted` does not imply `!isKnown`. */
def isDeleted(k: SPNodeKey): Boolean = isKnown(k) && !isPresent(k)
}
object ProgContext {
final case class Local(prog: ISPProgram) extends ProgContext {
val nodeMap = prog.nodeMap
val vm = prog.getVersions
def get(k: SPNodeKey): Option[ISPNode] =
nodeMap.get(k)
def parent(k: SPNodeKey): Option[SPNodeKey] =
for {
n <- nodeMap.get(k)
p <- Option(n.getParent)
} yield p.key
def isPresent(k: SPNodeKey): Boolean = nodeMap.contains(k)
}
final case class Remote(diff: ProgramDiff, remoteVm: VersionMap) extends ProgContext {
val plan = diff.plan
val diffMap: Map[SPNodeKey, Tree[MergeNode]] =
plan.update.foldTree(Map.empty[SPNodeKey, Tree[MergeNode]]) { (t,m) =>
m + (t.rootLabel.key -> t)
}
def vm: VersionMap = remoteVm
def get(k: SPNodeKey): Option[Tree[MergeNode]] =
diffMap.get(k)
def parent(k: SPNodeKey): Option[SPNodeKey] = remoteParents.get(k)
private val remoteParents: Map[SPNodeKey, SPNodeKey] =
plan.update.foldTree(Map.empty[SPNodeKey, SPNodeKey]) { (t, m) =>
val parentKey = t.rootLabel.key
(m/:t.subForest) { (m2, c) => m2 + (c.rootLabel.key -> parentKey) }
}
def isPresent(k: SPNodeKey): Boolean = diffMap.contains(k)
}
}
/** Holds the local and remote context for convenience. */
final case class MergeContext(local: ProgContext.Local, remote: ProgContext.Remote) {
def syncVersion(k: SPNodeKey): NodeVersions = local.version(k).sync(remote.version(k))
}
object MergeContext {
def apply(prog: ISPProgram, diff: ProgramDiff): MergeContext = {
val localVm = prog.getVersions
// Start with the local version map and apply the differences.
val remoteVm0 = diff.plan.update.sFoldRight(localVm) { (mn,vm) =>
mn match {
case m: Modified => vm.updated(mn.key, m.nv)
case _ => vm
}
}
val remoteVm = (remoteVm0/:diff.plan.delete) { (vm, miss) =>
if (miss.nv === EmptyNodeVersions) vm - miss.key
else vm.updated(miss.key, miss.nv)
}
MergeContext(ProgContext.Local(prog), ProgContext.Remote(diff, remoteVm))
}
} |
plimkilde/DHMQC | qc/roof_ridge_alignment.py | <reponame>plimkilde/DHMQC
# Copyright (c) 2015-2016, Danish Geodata Agency <<EMAIL>>
# Copyright (c) 2016, Danish Agency for Data Supply and Efficiency <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
'''
Find planes - works for 'simple houses' etc...
Useful for finding house edges (where points fall of a plane) and roof 'ridges', where planes intersect...
Houses with parallel roof patches at different heights are problematic - would be better split out into more input polygons...
# work in progress...
'''
from __future__ import print_function
from builtins import str
from builtins import range
import sys
import os
import time
from math import degrees, acos
import numpy as np
from qc.thatsDEM import pointcloud, vector_io, array_geometry
from qc.db import report
from . import dhmqc_constants as constants
from qc.utils.osutils import ArgumentParser
from qc.find_planes import plot3d, plot_intersections, find_planar_pairs, cluster
DEBUG = "-debug" in sys.argv
# z-interval to restrict the pointcloud to.
Z_MIN = constants.z_min_terrain
Z_MAX = constants.z_max_terrain + 30
# hmm try to only use building classifications here - should be less noisy!
cut_to = [constants.building, constants.surface]
progname = os.path.basename(__file__).replace(".pyc", ".py")
parser = ArgumentParser(
description="Check displacement of roofridges relative to input polygons",
prog=progname,
)
parser.add_argument(
"-use_all",
action="store_true",
help="Check all buildings. Else only check those with 4 corners.",
)
db_group = parser.add_mutually_exclusive_group()
db_group.add_argument(
"-use_local",
action="store_true",
help="Force use of local database for reporting.",
)
db_group.add_argument(
"-schema",
help="Specify schema for PostGis db.",
)
parser.add_argument(
"-class",
dest="cut_class",
type=int,
default=cut_to,
help="Inspect points of this class - defaults to 'surface' and 'building'",
)
parser.add_argument(
"-sloppy",
action="store_true",
help="Use all buildings - no geometry restrictions (at all).",
)
parser.add_argument(
"-search_factor",
type=float,
default=1,
help="Increase/decrease search factor - may result in larger computational time.",
)
parser.add_argument(
"-debug",
action="store_true",
help="Increase verbosity...",
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-layername",
help="Specify layername (e.g. for reference data in a database)",
)
group.add_argument(
"-layersql",
help="Specify sql-statement for layer selection (e.g. for reference data in a database)",
type=str,
)
parser.add_argument(
"las_file",
help="input 1km las tile.",
)
parser.add_argument(
"build_polys",
help="input reference building polygons (path or connection string).",
)
def usage():
parser.print_help()
# TODO: modularise common code in roof_ridge scripts...
def get_intersections(poly, line):
# hmmm - not many vertices, probably fast enough to run a python loop
# TODO: test that all vertices are corners...
intersections = []
distances = []
rotations = []
a_line = np.array(line[:2])
n_line = np.sqrt((a_line**2).sum())
for i in range(poly.shape[0] - 1): # polygon is closed...
v = poly[i + 1] - poly[i] # that gives us a,b for that line
n_v = np.sqrt((v**2).sum())
cosv = np.dot(v, a_line) / (n_v * n_line)
try:
a = degrees(acos(cosv))
except Exception as e:
print("Math exception: %s" % str(e))
continue
#print("Angle between normal and input line is: %.4f" %a)
if abs(a) > 20 and abs(a - 180) > 20:
continue
else:
n2 = np.array((-v[1], v[0])) # normal to 'vertex' line
c = np.dot(poly[i], n2)
A = np.vstack((n2, a_line))
try:
xy = np.linalg.solve(A, (c, line[2]))
except Exception as e:
print("Exception in linalg solver: %s" % (str(e)))
continue
xy_v = xy - poly[i]
# check that we actually get something on the line...
n_xy_v = np.sqrt((xy_v**2).sum())
cosv = np.dot(v, xy_v) / (n_v * n_xy_v)
if abs(cosv - 1) < 0.01 and n_xy_v / n_v < 1.0:
center = poly[i] + v * 0.5
d = np.sqrt(((center - xy)**2).sum())
cosv = np.dot(n2, a_line) / (n_v * n_line)
try:
rot = degrees(acos(cosv)) - 90.0
except Exception as e:
print("Exception finding rotation: %s, numeric instabilty..." % (str(e)))
continue
print("Distance from intersection to line center: %.4f m" % d)
print("Rotation: %.4f dg" % rot)
intersections.append(xy.tolist())
distances.append(d)
rotations.append(rot)
return np.asarray(intersections), distances, rotations
# Now works for 'simple' houses...
def main(args):
pargs = parser.parse_args(args[1:])
lasname = pargs.las_file
polyname = pargs.build_polys
kmname = constants.get_tilename(lasname)
print("Running %s on block: %s, %s" % (os.path.basename(args[0]), kmname, time.asctime()))
use_local = pargs.use_local
if pargs.schema is not None:
report.set_schema(pargs.schema)
reporter = report.ReportRoofridgeCheck(use_local)
cut_class = pargs.cut_class
print("Using class(es): %s" % (cut_class))
# default step values for search...
steps1 = 32
steps2 = 14
search_factor = pargs.search_factor
if search_factor != 1:
# can turn search steps up or down
steps1 = int(search_factor * steps1)
steps2 = int(search_factor * steps2)
print("Incresing search factor by: %.2f" % search_factor)
print("Running time will increase exponentionally with search factor...")
pc = pointcloud.fromAny(lasname).cut_to_class(cut_class).cut_to_z_interval(Z_MIN, Z_MAX)
try:
extent = np.asarray(constants.tilename_to_extent(kmname))
except Exception:
print("Could not get extent from tilename.")
extent = None
polys = vector_io.get_geometries(polyname, pargs.layername, pargs.layersql, extent)
fn = 0
sl = "+" * 60
is_sloppy = pargs.sloppy
use_all = pargs.use_all
for poly in polys:
print(sl)
fn += 1
print("Checking feature number %d" % fn)
a_poly = array_geometry.ogrgeom2array(poly)
# secret argument to use all buildings...
if (len(a_poly) > 1 or a_poly[0].shape[0] != 5) and (not use_all) and (not is_sloppy):
print("Only houses with 4 corners accepted... continuing...")
continue
pcp = pc.cut_to_polygon(a_poly)
# hmmm, these consts should perhaps be made more visible...
if (pcp.get_size() < 500 and (not is_sloppy)) or (pcp.get_size() < 10):
print("Few points in polygon...")
continue
# Go to a more numerically stable coord system - from now on only consider outer ring...
a_poly = a_poly[0]
xy_t = a_poly.mean(axis=0)
a_poly -= xy_t
pcp.xy -= xy_t
pcp.triangulate()
geom = pcp.get_triangle_geometry()
m = geom[:, 1].mean()
sd = geom[:, 1].std()
if (m > 1.5 or 0.5 * sd > m) and (not is_sloppy):
print("Feature %d, bad geometry...." % fn)
print(m, sd)
continue
planes = cluster(pcp, steps1, steps2)
if len(planes) < 2:
print("Feature %d, didn't find enough planes..." % fn)
pair, equation = find_planar_pairs(planes)
if pair is not None:
p1 = planes[pair[0]]
p2 = planes[pair[1]]
z1 = p1[0] * pcp.xy[:, 0] + p1[1] * pcp.xy[:, 1] + p1[2]
z2 = p2[0] * pcp.xy[:, 0] + p2[1] * pcp.xy[:, 1] + p2[2]
print("%s" % ("*" * 60))
print("Statistics for feature %d" % fn)
if DEBUG:
plot3d(pcp.xy, pcp.z, z1, z2)
intersections, distances, rotations = get_intersections(a_poly, equation)
if intersections.shape[0] == 2:
line_x = intersections[:, 0]
line_y = intersections[:, 1]
z_vals = p1[0] * intersections[:, 0] + p1[1] * intersections[:, 1] + p1[2]
if abs(z_vals[0] - z_vals[1]) > 0.01:
print("Numeric instabilty for z-calculation...")
z_val = float(np.mean(z_vals))
print("Z for intersection is %.2f m" % z_val)
if abs(equation[1]) > 1e-3:
a = -equation[0] / equation[1]
b = equation[2] / equation[1]
line_y = a * line_x + b
elif abs(equation[0]) > 1e-3:
a = -equation[1] / equation[0]
b = equation[2] / equation[0]
line_x = a * line_y + b
if DEBUG:
plot_intersections(a_poly, intersections, line_x, line_y)
# transform back to real coords
line_x += xy_t[0]
line_y += xy_t[1]
wkt = "LINESTRING(%.3f %.3f %.3f, %.3f %.3f %.3f)" % (
line_x[0], line_y[0], z_val, line_x[1], line_y[1], z_val)
print("WKT: %s" % wkt)
reporter.report(kmname, rotations[0], distances[0], distances[1], wkt_geom=wkt)
else:
print("Hmmm - something wrong, didn't get exactly two intersections...")
if __name__ == "__main__":
main(sys.argv)
|
barsnes-group/csf-pr | src/main/java/no/uib/probe/csf/pr/touch/view/core/TrendSymbol.java | <reponame>barsnes-group/csf-pr
package no.uib.probe.csf.pr.touch.view.core;
import com.vaadin.ui.VerticalLayout;
import java.util.HashMap;
/**
* This class represents trend symbol layouts (arrow-up,diamond and arrow-down)
* used in protein trend line chart and spark line in quant protein table.
*
* @author <NAME>
*/
public class TrendSymbol extends VerticalLayout implements Comparable<TrendSymbol> {
/**
* Parameters map.
*/
private final HashMap<String, Object> parameterMap;
/**
* The trend value(0:100% Increased,1:less than 100% Increased
* ,2:Equal,3:less than 100% Decreased,4:100% Increased,5:Quantified on
* peptide level, or 6:Quant information not available).
*/
private Integer trend;
/**
* Constructor to initialize the main attributes and layout.
*
* @param trend the trend value(0:100% Increased,1:less than 100% Increased
* ,2:Equal,3:less than 100% Decreased,4:100% Increased,5:Quantified on
* peptide level, or 6:Quant information not available).
*/
public TrendSymbol(int trend) {
parameterMap = new HashMap<>();
this.trend = trend;
this.addStyleName("slowtransition");
switch (trend) {
case 0:
this.setStyleName("arrow-up100");
break;
case 1:
this.setStyleName("arrow-upless100");
break;
case 2:
this.setStyleName("diamond");
break;
case 3:
this.setStyleName("arrow-downless100");
break;
case 4:
this.setStyleName("arrow-down100");
break;
case 5:
this.setStyleName("darkgraydiamond");
break;
case 6:
this.setStyleName("graydiamond");
break;
}
}
/**
* Set trend symbol.
*
* @param trend the trend value(0:100% Increased,1:less than 100% Increased
* ,2:Equal,3:less than 100% Decreased,4:100% Increased,5:Quantified on
* peptide level, or 6:Quant information not available).
*/
public void setTrend(int trend) {
this.trend = trend;
}
/**
* Add parameter
*
* @param name parameter name
* @param value parameter value
*/
public void addParam(String name, Object value) {
parameterMap.put(name, value);
}
/**
* Get parameter value
*
* @param paramName parameter key
* @return parameter value.
*/
public Object getParam(String paramName) {
return parameterMap.get(paramName);
}
/**
* Override compare to method (comparing based on trend
*
* @param o object to compare with
* @return comparison results
*/
@Override
public int compareTo(TrendSymbol o) {
int i = this.trend.compareTo(o.trend);
return i;
}
}
|
rohansachdeva1990/java-programming | concurrency/executor-framework/src/main/java/com/rohan/java/concurrency/terminating/executors/TerminatingExecutorTasksFirstWay.java | package com.rohan.java.concurrency.terminating.executors;
import com.rohan.java.concurrency.common.factory.NamedThreadFactory;
import com.rohan.java.concurrency.common.tasks.FactorialTaskA;
import com.rohan.java.concurrency.common.tasks.LoopTaskE;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TerminatingExecutorTasksFirstWay {
public static void main(String[] args) throws InterruptedException {
String currentThreadName = Thread.currentThread().getName();
System.out.println("[" + currentThreadName + "] Main thread starts here...");
ExecutorService executorService = Executors.newCachedThreadPool(new NamedThreadFactory());
LoopTaskE task1 = new LoopTaskE();
FactorialTaskA task2 = new FactorialTaskA(30, 1000);
executorService.execute(task1);
executorService.submit(task2);
executorService.shutdown();
TimeUnit.MILLISECONDS.sleep(3000);
task1.cancel();
task2.cancel();
System.out.println("[" + currentThreadName + "] Main thread ends here...");
}
}
|
uploadexpress/app | helpers/request.go | package helpers
import (
"encoding/json"
"io"
"io/ioutil"
)
func GetRequestParams(body io.ReadCloser) (map[string]interface{}, error) {
byteBody, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
var params map[string]interface{}
err = json.Unmarshal(byteBody, ¶ms)
if err != nil {
return nil, err
}
return params, nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.