�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  `0   �� ���,�,�h<#�/��/��/�80�Y���&-5=EMU\cjrz�����������������  (/6>EMT\dkrx������������������ #+3:BJQW^emu}����������������� !(07?FNU\dlt|����������������� !)18@FMT\dlt{�����������������'.5=ELTZbiov}����������������� #*2:BJPX^emu}����������������� &-4;BIQYaipx����������������� !(07?GNV]emu}�����������������   ! ( 0 8 @ G O V ^ f n v ~ � � � � � � � � � � � � � � � � �    ' / 7 > E L T \ d l t z � � � � � � � � � � � � � � � � � �     $ , 4 < D L S Z a h o w ~ � � � � � � � � � � � � � � � �     $ , 4 ; B J Q W _ f m t | � � � � � � � � � � � � � � � � �     # + 3 : B J R Y a i p v } � � � � � � � � � � � � � � � � �  ")08@GOW^els{����������������� &.6=EMT[aiow����������������� "*18@HNU\dksz�����������������%,3;CJRZbjqx�����������������%,3:BIPX_gov}����������������� '.6=EMT\cjqx�����������������$,4;CKS[cjry�����������������$+2:BIPX`gov~����������������� '.5=DKRZbipw~����������������� $+29@GOW^elsy����������������� #+29AIQYahov~�����������������$,4<DLSZbhov~����������������� &-5=EMT\cjnv~����������������� #*19AHPX_gnu}�����������������  (/6>EMU\ckrz����������������� 14026766134688041674250236423852569584857841712796072176256671189395918446255173154088656916278582327074001195901610647125191307706673230135397241731410559937621536864189952768510257155809179312143115385161752873711451977109330521572466244172441385893020979767629571115554651281897556732010543431980021848718501937229418908791862106166099721618644918413132949341013889337842911400274814463585149530831107227129180013702286118752058282364169240401859126072409501152822382027522494573584633164552541354705992226271900381362181292343964367372143158221954328317193889160846513236252147697762101179556729626037956279881079657718294786162159128675213165516187549191773867923207139416390805603515595636331878713004707137250998743006272037216140045756042170550551236004818500827919100512680479147240531192652845114291926120897922981010193426007821333302966042006020014144664471545935817703786180447861481314513362106119858177436636456766213095224113021145751011533612515848016147410431593596681515228829962271433143100101314143456500887974676162055244798878181835111120334310104564807039813369338478232748353484975731465709317064597123474851251461068475811260877418023906164883741157705310325472141414612263942965201890077845623578185097680803916582391649252511790937604434171093625473629157099222299604128379261461062015466904466982526917711371153114534786583447513835841883769171103741901812262866232481749580274676262152679847279285763289461966551076994019055473100734728088184141577491905254331878331131868421116645170757103985114147079154348916846406124397591348428818205541478962317983572168784661922731711878297785359177714813412108749459146076711293343917413525520361510892094117130076514028372041756827413135826172030261373592747641199867311714569214577888657129116200401775905115898669119607512844483690128458018328517321535803816221186924409635628748234229984075155402301473479115476139134644951121727184358391687296439469790524951002578644442141800894113077176182795592770041734401264998814053545116480925903211782973816213912063473172365798772009166148059642758659600813403796201978316362792310134312774502114848116211362173845586780816109720551566723813988737155092833595559640397532739339424963594298913651422104444621335862777652427636671120125018011407169378761789064139836769156876150900781474627163813151219466713121360838164198554011931897411033876132553527941151140406841947952143881321819426714475061133106211498229311357344728068618405869147813291387111394617118748231228670802476463489654039404564741761758816024387180567323785816106295215794239174988671687246614378995600642729382291284068613117901141235326465626507612175171031944825516314883175778701011023326662455737352187394102393285640522343971086688510367491122255951465140833605683025931417969118873380731980714825423147117721309572167578401036095030922811513548152114137719955113163651320401914524723140492491503817238104558851129585915580899442908963144481786211415115865828486437764087412819589587923826546491418712336421881057073618284096115105661390632310627892160641981056161414607491228569411242681847325195411327079335767931714019695128295812687080811536315445598567545223093718057110348135268468367066041167096691368914612560042585474369068826133894461590192981561152694417076911204731112102001623719618090116519285336014140761553841382171272797629278756924981978678729374635138213228230124186269355606184334601030515218790178403673511626755127352695784925608126536744323057861926116714192751219396817145541415201374469681488992410166376132317032545864165693345159341070219177065095120041101315351184367376446611639229213302796818829342388377878971121721181547065134884731748965912088677258138166930062410796489399514224106187726512689261357202218489504109822328221063107200757302274101519811532737427393341078789014492780139006767221707170648404417492467809996433631200195459503223453696485448116416461881622734763181688280718148034878442021845022544291246860653835814050770163640101853815815141173572385814557927739029491465641894969910740806191393679486183813398465935016776325161359576021308731826497830456137386112668501840720816500927112795113973183870303235095716766452132313801763423969283638679610688193393314311833828535273820558392525590142761345757348534071654296916464019862698068395501361247717485307167613517327690160160871351328810564005181978041350149226442039248595638482911972937664335469707563168164194759601556948555769791500521612193894170432351776050464893612783915145079111541292123607551683049616415418107723441285282051786201380027727876756472612183859721788197387493015150834877512011005241791912016162346193119558151125189917461647008302626395127475050451947542014514421862656162771651098947133500941278824231410382917529813829414534815101793941345067543894849934573147207801277858511062242263403746980061867166035105815971627128890267130052690541388397676036965171419831038142755267188112188499430126106682959424154019721302894735720391367991047871168111236795546237823001565519111547773151854746535464686910156453061842032414839627157835538389954806407046429228263739102991154582026179779011194092914650215119037451467303278980545398718756002106153571342052688417731381637914168192159583151253760410617385558313013022234428060213479852171456821367914715079953217165311359901187568419439535136848832217701424491159486573175081871111210447639117445332195601854542611342247688476735907324762178283017326354372549880165236651130732798574244061223112427241490961034725711757549686859171714456869868825022705622028210575849132627891208676792529841674731378165211570642683592811515736142391421910281217663570163321522777508146768293983478830443292931638613164019926689330506888419120839330840126218129836506138681231135362094123356459750787765726360751637066815046167221514016410220149701413960629143921271196780345026316756284165422902193353570046137386401283596536606701290008814713210362179018134264139750517575861316332959155055767321602429499874141153992310690251634257161163306046048241060477656872811818530787172345281533497184859556992362842481319543676168791967336623627752496219549766796651080757228501547486815993038141637521168875185599315529715532151610251476113458496224719355592714938320104206581697336413700258155307869799340318323153922791826839516875402852162312299751590238116289727264207016069659148986149653547549130015480415227928012973756120608361846301725719009975461127709061294619997175051679309865994531643331413436252180866031707223318790647314085512527821366577873164762728866447073192311871185235477668841040895513247656732706434629022456239174462648244966829878538283097250351525112565024208502902358585513174516989117110583634148754459636094385835493532994115400168868711742563211313597158395358036547191640788203827914119622691616804617711722145060412037624532192477888911990302147772887026267105127221704616190665895830095622534599408121348363532512826869041571321196386149301660127899969032442464318424871854485586258981329329314591209970691416612716116598715814810141715766302836492407812462641858584419333002227220432549681609920451695561835619510522153637649119810433203965125265297200352141302236672138777627181243756219103118347871294228968902441615238918019495170052880084371103255353909401374492114341855243514170404641192535750557071463330559079701374386291195221193930812867109111854191168896360655761510321604093914470759861572334577271399509919189187601598410572390110478351766711114877817�� 70�1�2�4^7�CQ�V_9edlx�݀���2�����*�c #�+�0=2HZ[�������ˠ����G�!�����ٻ����q�'�L�����qm Ty%"/>0%u΁�����o�%���V�!���g������{�����j[%o&�2�C�F7I�NkP T[�F� �@���٨������������<�������o�����o�; �r"&#)�4�>D�G]I-K�K]XZ \\_mj-ktm t�xR}����9����U��9 3%,-M.�/�4�9�J�KOphq��ҩ���N��������h�B�{�6�s� \ � ��"�'m(61_2�4�9$>C J�Y�[ז��~��@���<������ ���0�5�� ���/�2�8�:�\vr����ܑ��)�J���Y�]�Ƅ�Z�~�#�Y�������۵]�ʿ�a�y�������� O  � � �   =% �' �, ; �< �B W� {� u� �� �� L� �� w� � m� �� �� qP )Y �a �q � �� Ѫ M� ׾ �� � � %� u� �� � �� 4� �� � � � �  � � � # � $' �5 �: �< � � � � �� y� :� �� I� z� -� 9� 3 �2 #@ �B AC �V Cg li 2l �q gv �| f� }� �� � M� 1� H� � �� �� � �%�3�4.6�AjP_U�ZE`�eYh1n�q��Ĕ����g���>��$�+h.q:�<�I[K�T�`�ka���Œw�c������� ���N���P�(�+m1�3~?�?2G��M�����q�� J �W�;x!�$o%e0�0�3�5�9�EtH"N�N��y���h�W�H������8(@rEFwFMIpJU�YTZ�[^j�por�t|vd|�����4(68<�?@DAI>J�Nabh�~�ȥ��o�s������I���(�`� �OCBO�\�fro_s�v��#���Y��>��P���<��KL Y& ,q1�5�6;=@�AaE�I�t5u�x����j�~�����z�������������&_'�)�4Q=�g�v��čϐe�5�E���������*��#��%�/�UYlpVr���\�íų���y�������������H����;��!#�'�>(B�CiMIN�X�a dl�p�v/x����.�o���%�����������g�����l�iE%K L�Np�������h� ���i���| �e$`%�*S,�;J=�>I�df�n?p�q�uAv����e�?�����f���z�v i ����]%�&i3 9@>FOFLqP�Q�S0X0]'e�iEpUs-�O���f�X���� G� Y� �!J!u!D!�!%!9!!{R!zS!�V!d_!O`!�e!.o!�p!�r!7�!ʋ!o�!z�!��!Z�!��!;�!d�!0"�"� "\ "�>"�b"wg"|m"o"8z"v{"�{"Ҙ"}�"��"ٺ"H�"��"��"��"�"��"B�"��"��"��"L�"S�"'�"��"�#�#7$#�S#�T#fV#�Z#�\#��#]�#�#M�#�#��#��#h�#��#��#�#��#��# $�$�#$=%$P($/$3$4$�8$�I$�M$KY$�a$Tc$p$ghsecuritylab/embeddedsw var globals_dup = [ [ "a", "globals.html", null ], [ "m", "globals_m.html", null ], [ "p", "globals_p.html", null ], [ "s", "globals_s.html", null ], [ "x", "globals_x.html", null ] ];// allows import from data/*.ts (see package.json build and watch rules) import '@rollup/plugin-typescript'; import del from 'rollup-plugin-delete'; import { nodeResolve } from '@rollup/plugin-node-resolve'; import esbuild from 'rollup-plugin-esbuild'; import html from '@web/rollup-plugin-html'; import { copy } from '@web/rollup-plugin-copy'; import minifyHTML from 'rollup-plugin-minify-html-literals'; import {PORTFOLIO} from './data/jory'; const IMAGE_DIR = 'images'; const BUNDLE_DIR = 'dist'; const imageImports = PORTFOLIO.map( project => `${IMAGE_DIR}/${project.imageSources[0]}`, ); export default { input: 'index.html', output: [{ dir: `./${BUNDLE_DIR}`, format: 'es', sourcemap: true, // recommended for Lighthouse and debugging. }], plugins: [ copy({ patterns: [...imageImports, 'CNAME'], }), nodeResolve(), del({targets: `${BUNDLE_DIR}/*`}), minifyHTML(), esbuild({ ts: true, minify: true, target: 'esnext', }), html(), ], preserveEntrySignatures: false, }; const fs = require('fs-extra'); const path = require('path'); const isInstalledGlobally = require('is-installed-globally'); const tiappDir = require('@titanium/tiapp-xml/tiapp-dir'); const tiappXml = require('@titanium/tiapp-xml'); const pluginName = 'turbo'; console.error('__dirname: ' + JSON.stringify(__dirname, null, 2)); console.error('isInstalledGlobally: ' + JSON.stringify(isInstalledGlobally, null, 2)); if( !isInstalledGlobally ){ // root directory of project where tiapp.xml is located. const root = tiappDir.sync(__dirname); if (!root) { console.error('Could not find tiapp.xml. Be sure you are installing this locally into root of your Titanium project.'); return 0; } const tiappPath = path.join(root, 'tiapp.xml'); // modify tiapp.xml to remove plugin from it console.info(`removing ${pluginName} plugin from: ${tiappPath}`); const tiapp = tiappXml.load(tiappPath); tiapp.removePlugin(pluginName); tiapp.write(); } else { const spawnSync = require('@geek/spawn').spawnSync; const hookPath = path.join(__dirname, '..', 'hooks'); const pluginPath = path.join(__dirname, '..', 'plugins'); console.error('Uninstalling global hook → ' + hookPath); spawnSync('ti', ['config', 'paths.hooks', '--remove', hookPath]); console.error('Uninstalling global plugin → ' + pluginPath); spawnSync('ti', ['config', 'paths.plugins', '--remove', pluginPath]); } import { useState } from 'react'; import PropTypes from 'prop-types'; import { Icon } from '@iconify/react'; import { useSnackbar } from 'notistack5'; import { useSelector } from 'react-redux'; import plusFill from '@iconify/icons-eva/plus-fill'; import { Droppable, Draggable } from 'react-beautiful-dnd'; // material import { Paper, Stack, Button } from '@material-ui/core'; // redux import { useDispatch } from '../../../redux/store'; import { deleteColumn, updateColumn, addTask, deleteTask } from '../../../redux/slices/kanban'; // import KanbanTaskCard from './KanbanTaskCard'; import KanbanColumnToolBar from './KanbanColumnToolBar'; import KanbanAddTask from './KanbanTaskAdd'; // ---------------------------------------------------------------------- KanbanColumn.propTypes = { column: PropTypes.object, index: PropTypes.number }; export default function KanbanColumn({ column, index }) { const dispatch = useDispatch(); const { enqueueSnackbar } = useSnackbar(); const { board } = useSelector((state) => state.kanban); const [open, setOpen] = useState(false); const { name, cardIds, id } = column; const handleOpenAddTask = () => { setOpen((prev) => !prev); }; const handleCloseAddTask = () => { setOpen(false); }; const handleDeleteTask = (cardId) => { dispatch(deleteTask({ cardId, columnId: id })); enqueueSnackbar('Delete success', { variant: 'success' }); }; const handleUpdateColumn = async (newName) => { try { if (newName !== name) { dispatch(updateColumn(id, { ...column, name: newName })); enqueueSnackbar('Update success', { variant: 'success' }); } } catch (error) { console.error(error); } }; const handleDeleteColumn = async () => { try { dispatch(deleteColumn(id)); enqueueSnackbar('Delete success', { variant: 'success' }); } catch (error) { console.error(error); } }; const handleAddTask = (task) => { dispatch(addTask({ card: task, columnId: id })); enqueueSnackbar('Add success', { variant: 'success' }); handleCloseAddTask(); }; return ( {(provided) => ( {(provided) => ( {cardIds.map((cardId, index) => { const card = board?.cards[cardId]; return ; })} {provided.placeholder} )} {open && } )} ); } 0 $(function() { var keyboard = new THREEx.KeyboardState(); var HEIGHT = window.innerHeight; var WIDTH = window.innerWidth / 2; var scene = new THREE.Scene(); // Camera setup var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 20000; camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR); scene.add(camera); // var controls = new THREE.OrbitControls(camera); camera.position.set(0, 150, 400); camera.lookAt(scene.position); // Avatar speed (step size) var dx = 10; var dz = 10; var allUsers; var socket = io(); var userName = prompt("What is your name?"); // Assign user client id to associate with socket id var userID = getRandomString(); function getRandomString() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < 20; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } // Instantiate User var user = new User(userName, userID, 0, 0, 0); // Send back to server new user's full 'profile' i.e. name etc. socket.emit('new', user); // Get information of other connected users socket.on('all users', function(all) { var tmp_list = []; for (i = 0; i < all.length; i++) { var tmp_usr = new User(all[i].name, all[i].idNum, all[i].x, all[i].y, all[i].z); tmp_list.push(tmp_usr); } // Update allUsers allUsers = tmp_list; // Instantiate other connected users if (allUsers) { for (i = 0; i < allUsers.length; i++) { octopus.removeAvatar(allUsers[i].idNum); if (allUsers[i].name != user.name) { allUsers[i].createOthersAvatar(); var otherSphere = allUsers[i].othersAvatar; otherSphere.name = allUsers[i].idNum; otherSphere.position.set(allUsers[i].x, allUsers[i].y, allUsers[i].z); scene.add(otherSphere); } } } }); var renderer = new THREE.WebGLRenderer(); renderer.setSize(WIDTH, HEIGHT); var canvas = document.querySelector("#c"); canvas.appendChild(renderer.domElement); user.createAvatar(); var sphere = user.sphereAvatar; sphere.position.set(10, 0, 0); scene.add(sphere); var axes = new THREE.AxesHelper(100); scene.add(axes); var w = new World(); var floor = w.floor(); floor.position.y = -10; floor.rotation.x = Math.PI / 2; scene.add(floor); // Chat Board // Load messages written by users already logged in socket.on('archived', function(msgs) { if(msgs) { for (i = 0; i < msgs.length; i++){ var msg = msgs[i]; $('#messages').append($('
  • ').text(msg.name + " : " + msg.message)); } } }); // When user types messsage, the server gets it as a chat message event $('form').submit(function() { socket.emit('chat message', [user.name, $('#m').val()]); $('#m').val(''); // Reset message element return false; }); // On client side when we capture chat message event, we'll include it in the page socket.on('chat message', function(msg) { $('#messages').append($('
  • ').text(msg[0] + " : " + msg[1])); }); socket.on('avatar disconnection', function(id) { octopus.removeAvatar(id); }); var octopus = { init: function() { view.render(); }, keyDown: function(event) { switch (event.keyCode) { case 38: /* up arrow */ if (sphere.position.z + dz > -350) { sphere.position.z -= dz; user.setZ(user.z - dz); socket.emit('user info', user); camera.position.set(user.x, 150, 400 + user.z); } break; case 40: /* down arrow */ if (sphere.position.z - dz < 350) { sphere.position.z += dz; user.setZ(user.z + dz); socket.emit('user info', user); camera.position.set(user.x, 150, 400 + user.z); } break; case 37: /* left arrow */ if (sphere.position.x - dx > (-WIDTH / 2)) { sphere.position.x -= dx; user.setX(user.x - dx); socket.emit('user info', user); camera.position.set(user.x, 150, 400 + user.z); } break; case 39: /* right arrow */ if (sphere.position.x + dx < (WIDTH / 2)) { sphere.position.x += dx; user.setX(user.x + dx); socket.emit('user info', user); camera.position.set(user.x, 150, 400 + user.z); } break; } }, animate: function() { requestAnimationFrame(octopus.animate); //controls.update(); renderer.render(scene, camera); }, removeAvatar: function(a) { var delAvatar = scene.getObjectByName(a); scene.remove(delAvatar); } }; var view = { render: function() { window.addEventListener('keydown', octopus.keyDown, true); octopus.animate(); } }; octopus.init(); });export const ImageGalleryItem = ({ images, handlerOnClick }) => images.map(({ id, webformatURL, largeImageURL, tags }) => (
  • handlerOnClick(largeImageURL, tags)} > {tags}
  • )); /** * serializers.js - serializer registry * * @author <> */ module.exports = { 'json': require('./json'), 'msgpack': require('./msgpack'), } michl-b/react-matic import styled from 'styled-components' import { size } from 'polished' export default styled.button` background-color: ${props => props.active ? props.theme.palette.successColor : props.theme.palette.primaryColor}; background-color: ${props => props.theme.palette.primaryColor}; color: ${props => props.theme.palette.white}; ${size('4em')} text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; border-radius: 10px; margin-left: 5px; margin-right: 5px; ` modules/wf_instrument_inspections/client/controllers/list-wf_instrument_inspections.client.controller.js (function () { 'use strict'; angular .module('wf_instrument_inspections') .controller('WF_Instrument_InspectionsListController', WF_Instrument_InspectionsListController); WF_Instrument_InspectionsListController.$inject = ['WF_Instrument_InspectionsService']; function WF_Instrument_InspectionsListController(WF_Instrument_InspectionsService) { var vm = this; $('#spinModal').modal('show'); vm.wf_instrument_inspections = WF_Instrument_InspectionsService.query(function(){ $('#spinModal').modal('hide'); }); } }()); import {RenderableNode} from "./RenderableNode"; import {RenderableUtils} from "./RenderableUtils"; import THREE from "three"; class RenderableView extends RenderableNode { constructor(options) { super(options); let required = ['view', 'size'], defaultOptions = {backgroundColor: null}; this.options = RenderableUtils.CreateOptions(options, required, 'RenderableView.options', defaultOptions);s this._renderables = {}; this._createCamera(); } _createCamera() { let left = 0, bottom = 0, near = 0, far = 1; let viewSize = this.viewSize; let camera = new THREE.OrthographicCamera(left, viewSize.x, viewSize.y, bottom, near, far); camera.up.set(0, 1, 0); camera.position.set(0, 0, 1); camera.lookAt(new THREE.Vector3(0, 0, 0)); camera.updateProjectionMatrix(); this._camera = camera; } _cameraPositionChanged () { // if camera less than 0, set to 0 if (this._camera.position.x < 0) { this._camera.position.x = 0; } } /** * @private * Moves camera based on the number given. * @param {number} delta */ moveCamera(delta) { this._camera.position.x += delta; this._cameraPositionChanged(); } /** * @private * Sets the camera's x position to the given value. * @param {number} pos The x axis position of the camera. */ setCameraPosition (pos) { this._camera.position.x = pos; this._cameraPositionChanged(); } /** * @private * Sets the amount of units of the x axis is shown. * @param {number} range range of values to show on x axis */ setCameraXRange(range) { let xScale = range / this.viewSize.x; this._camera.scale.x = xScale; this._camera.updateProjectionMatrix(); } get viewSize () { let size = this.options.size, view = this.options.view; let top = size.y * view.height, right = size.x * view.width; return {x: right, y: top}; } render(renderer) { let size = this.options.size, view = this.options.view; let left = Math.floor(size.x * view.left), top = Math.floor(size.y * view.top), width = Math.floor(size.x * view.width), height = Math.floor(size.y * view.height); renderer.setViewport(left, top, width, height); renderer.setScissor(left, top, width, height); renderer.setScissorTest(true); super.render(renderer, this._camera); } /** * @private * Updates the camera with the correct values based on the * size given. * @param {{x: number, y: number}} size */ updateView(size) { if (!(size instanceof THREE.Vector2)) { throw 'Error: size not of type THREE.Vector2'; } // TODO: modify to use current camera and not create a new one this.options.size = size; let cameraX = this._camera.position.x; let cameraScale = this._camera.scale.x; this._camera = null; this._createCamera(); this._camera.position.x = cameraX; this._camera.scale.x = cameraScale; this.emit('resize'); } } export {RenderableView}; escapedcat/zap-desktop import React, { useRef } from 'react' import PropTypes from 'prop-types' import { Flex } from 'rebass/styled-components' import { FormattedMessage, useIntl } from 'react-intl' import { Dialog, Heading, Message, Button, DialogOverlay } from 'components/UI' import { PasswordInput, Form } from 'components/Form' import messages from './messages' import { useFormError } from 'hooks' const SetPasswordDialog = ({ loginError, clearLoginError, onOk, onCancel }) => { const intl = useIntl() const formApiRef = useRef(null) useFormError(loginError, clearLoginError, formApiRef) const validate = ({ password, confirmPassword }) => { if (password !== confirmPassword) { return intl.formatMessage({ ...messages.password_do_not_match }) } return undefined } const header = ( ) const handleSubmit = values => onOk(values) return (
    { formApiRef.current = api }} onSubmit={handleSubmit} validate={validate} > {({ formState: { submits, error, invalid } }) => { const willValidateInline = submits > 0 return ( } header={header} onClose={onCancel} width={640} > {error && ( {error} )} ) }}
    ) } SetPasswordDialog.propTypes = { clearLoginError: PropTypes.func.isRequired, loginError: PropTypes.string, onCancel: PropTypes.func.isRequired, onOk: PropTypes.func.isRequired, } export default SetPasswordDialog 1-10 $(document).ready(function() { var highlighted = null; $("span.anno").on('mouseover', function(e) { type_str = type_table[e.target.id]; col_str = e.target.id.split('_')[0]; preview_id = '#col_' + col_str; var new_highlighted = $(preview_id); if (new_highlighted != highlighted) { if (highlighted) highlighted.innerHTML = ""; highlighted = new_highlighted; if (highlighted.hasClass('slide')) { type_str = type_str + ' '; } else { type_str = ' ' + type_str; } highlighted[0].innerHTML = type_str; if (highlighted[0].style.width === "") { highlighted[0].style.width = 0; } highlighted.stop(true, true); if (highlighted.hasClass('slide')) { target_width = Math.max(highlighted[0].scrollWidth, highlighted[0].offsetWidth); highlighted.animate({width: target_width, opacity: 1}); } else { highlighted.fadeIn(200); } } }); $('span.anno').on('mouseout', function(e) { if (highlighted) { if (highlighted.hasClass('slide')) { highlighted.animate({width: '0', opacity: '0'}); } else { highlighted.fadeOut(200); } highlighted = null; } }); }); 'use strict'; const TeamAwareAgent = require('./team-aware-agent'); const Battle = require('../../Pokemon-Showdown/sim/battle'); const teamInference = require('../state-inference/team-inference'); const storage = require('../tracking/storage'); /** * An agent that chooses actions uniformly at random. */ class TeamAwareSimulationAgent extends TeamAwareAgent { /** * @param {'p1' | 'p2'} id * @param {object} team * @param {string} formatId * @param {number} [seed] * @param {boolean} [debug] */ constructor(id, team, formatId, seed = null, debug = false) { super(id, seed, team, debug); this.simulatedBattle = null; this.formatId = formatId; } /** * @override */ act(actionSpace, observation, reward, done) { super.updateState(observation); const state = this.state; if (state.request.teamPreview) { const teamOpponent = storage.packTeam( teamInference.assumeTeamWithUniformStats( this.getOpponentSide().pokemon ) ); const battleOptions = { formatid: this.formatId, seed: this.seed ? Array(4).fill(this.seed) : null, }; this.simulatedBattle = new Battle(battleOptions); this.simulatedBattle.setPlayer('p1', {name: 'p1', team: this.team}); this.simulatedBattle.setPlayer('p2', {name: 'p2', team: teamOpponent}); } } /** * @param {bool} own * @return {Pokemon} */ getActiveSimulatedPokemon(own = true) { let activeSpecies = null; activeSpecies = this.getActivePokemonSpecies(own); let pokemon = null; if (own) { pokemon = this.simulatedBattle.p1.pokemon; } else { pokemon = this.simulatedBattle.p2.pokemon; } for (let i = 0; i < pokemon.length; i++) { if (pokemon[i].species === activeSpecies) { return pokemon[i]; } } return pokemon[0]; } } module.exports = TeamAwareSimulationAgent; herpan/ssi_cpc1-10 /* --- description: CSS (Cascading Style Sheets) license: MIT-style authors: - - requires: - Core/1.4.5 provides: [EnlighterJS.Language.css] ... */ EnlighterJS.Language.css = new Class({ Extends: EnlighterJS.Language.generic, setupLanguage: function() { this.keywords = { }; this.patterns = { 'comments2': { pattern: /\/\*![\s\S]*?\*\//gm, alias: 'co2'}, 'comments': { pattern: this.common.multiComments, alias: 'co1'}, 'strings': { pattern: this.common.strings, alias: 'st0' }, 'selectors': { pattern: /(?:^|}|\/)\s*([^\\/{@]+)\s*\{/gi, alias: 'kw1' }, 'directives': { pattern: /(@[a-z]+)\s+/gi, alias: 'kw2' }, 'rules': { pattern: /([\w-]+)\s*:/g, alias: 'kw3' }, 'uri': { pattern: /url\s*\([^\)]*\)/gi, alias: 'kw4' }, 'units': { pattern: /\b(\d+[\.\d+-]?\s*(%|[a-z]{1,3})?)/gi, alias: 'nu0' }, 'hexColors': { pattern: /(#[A-F0-9]{3}([A-F0-9]{3})?)\b/gi, alias: 'nu0' }, 'brackets': { pattern: this.common.brackets, alias: 'br0'}, 'symbols': { pattern: /,|\.|;|:|>/g, alias: 'sy0'} }; } }); src/server/windows-graph-users-retriever.js import rp from 'request-promise'; import winston from 'winston'; export default class WindowsGraphUsersRetriever { getUsers(endpointId, accessToken, uriOverride) { const users = []; const apiVersion = 'api-version=2013-04-05'; const baseUri = `https://graph.windows.net/${endpointId}`; const getUsersUri = uriOverride || (`${baseUri}/users` + `?${apiVersion}&$filter=accountEnabled eq true&$top=100&$expand=manager`); winston.info(`Retrieving ${getUsersUri} ...`); return rp({ uri: getUsersUri, headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' }, json: true }) .then(res => { users.push(...res.value.map(x => this.toAppUser(x))); // Recursively follow 'odata.nextLink' on response if it exists // to get all pages of data. const nextLink = res['odata.nextLink']; if (nextLink) { return this .getUsers( endpointId, accessToken, `${baseUri}/${nextLink}&${apiVersion}`) .then(nextUsers => { users.push(...nextUsers); }); } return Promise.resolve(true); }) .then(() => { return users; }); } toAppUser(graphUser) { if (!graphUser) { return null; } return { id: graphUser.objectId, displayName: graphUser.displayName, jobTitle: graphUser.jobTitle, department: graphUser.department, userPrincipalName: graphUser.userPrincipalName, city: graphUser.city, state: graphUser.state, country: graphUser.country, email: graphUser.mail, telephoneNumber: graphUser.telephoneNumber, manager: this.toAppUser(graphUser.manager) }; } } import React from 'react' import './Registration.sass' // COMPONENTS __________________________________________________________________ import Section from '../../components/Section' // DATA ________________________________________________________________________ const DEADLINE_DATA = [ { name: 'Fecha límite presentación de Resúmenes', weekday: 'Viernes', date: '21/04/2017' }, { name: 'Fecha límite presentación de Trabajos', weekday: 'Viernes', date: '05/05/2017' } ] const COST_DATA = [ { name: 'Asistentes en general', cost: '$2.200*' }, { name: 'Matriculados Consejo Profesional de Ciencias Económicas TDF', cost: '$1.600*' }, { name: 'Docentes UNTDF', cost: '$1.300*' }, { name: 'Estudiantes UNTDF', cost: 'Sin cargo' }, { name: 'Estudiantes otras instituciones', cost: '$300**' } ] function DeadLine({name, weekday, date}, key) { return (

    {name}

    {weekday} {date}

    ) } function Cost({name, cost}, i) { return (

    {name}

    {cost}

    ) } function Registration() { return (

    Presentación de trabajos

    { DEADLINE_DATA.map(DeadLine) }

    Costo de las matrículas

    { COST_DATA.map(Cost) }

    * Incluye material del Simposio, Cóctail de bienvenida y Cena de camaradería
    ** Incluye el material del Simposio

    ¿Cómo inscribirse?

    Llene la siguiente ficha de inscripción{' '} y envíela a: ;{' '} nos pondremos en contacto con usted a la brevedad.

    ¿Cómo presentar ponencias?

    Para la presentación de ponencias recomendamos lea atentamente el {' '} reglamento.{' '} Cualquier consulta puede ser dirigida a:

    ) } export default Registration var assign = require('object-assign'); var EventEmitter = require('events').EventEmitter; var CHANGE_EVENT = 'change'; function errorIf(condition, message) { if (condition) { throw new Error(message); } } var Store = function(state, changeEvent) { var store = assign({}, EventEmitter.prototype, { handlers: {}, callbacks: [], state: state, changeEvent: changeEvent || CHANGE_EVENT, registerHandler: function(name, method) { errorIf(!method, 'Handlers must have a function'); errorIf(this.handlers[name], 'Handler already defined on this store for ' + name); this.handlers[name] = typeof method === 'function' ? [method] : method; return this; }, registerCallback: function(method) { errorIf(!method, 'Callbacks must have a function'); this.callbacks.push(method); return this; }, currentState: function() { return this.state; }, emitChange: function() { this.emit(this.changeEvent); }, destroy: function() { Miniflux._stores = Miniflux._stores.splice(1, storeIndex); } }); var storeIndex = Miniflux._stores.push(store); return store; }; var Action = function(action) { var args = Array.prototype.slice.call(arguments, 1); var handled = false; Miniflux._stores.forEach(function(store) { if (store.handlers[action]) { var shouldEmit = true; handled = true; store.handlers[action].forEach(function(h) { shouldEmit = shouldEmit !== false ? h.apply(store, args) : false; }); store.callbacks.forEach(function(cb) { shouldEmit = shouldEmit !== false ? cb.apply(store) : false; }); if (shouldEmit !== false) { store.emitChange(); } } }); errorIf(!handled, 'Nothing handled this action: ' + action); }; var Miniflux = { change: CHANGE_EVENT, Store: Store, Action: Action, _stores: [] }; module.exports = Miniflux; import { getCalendarDate, isWeekend, } from './shared' const isBusinessDay = (calendar = {}, date) => { if (isWeekend(date)) { return false } const day = getCalendarDate(calendar, date) if (!day) { return true } return !day.holiday && !day.limited_financial_operation } export default isBusinessDay const _ = require("lodash"); const AWS = require("aws-sdk"); var ddb = new AWS.DynamoDB(); module.exports = async () => { const params = { TableName: 'CLIENTS', Key: { 'PSID': {S: "4476484539044126"} }, ProjectionExpression: `template_title, template_SubTitle, template_image_url, template_main_url` }; const request = ddb.getItem(params); const data = await request.promise(); // in case no blocks are found return undefined return data; }; HelloThien/SmartHouse const Account = props => { return <>Account } export default Account1-10 /* global localStorage */ import apis from '../api'; import { Session as SESSION } from '../constants'; const { session: api } = apis; function reset() { return { type: SESSION.RESET, }; } // - Read Action - function readRequest() { return { type: SESSION.READ.REQUEST, }; } function readSuccess(response) { const { data } = response; localStorage.setItem('viewer', JSON.stringify(data)); return { type: SESSION.READ.SUCCESS, viewer: data, }; } function readFailure(error) { return { type: SESSION.READ.FAILURE, error: error.message, }; } function read() { return (dispatch) => { dispatch(readRequest()); return new Promise((resolve, reject) => { api.read() .then((response) => { dispatch(readSuccess(response)); return resolve(); }, (response) => { dispatch(readFailure(response)); return reject(response); }); }).catch((error) => { console.error(error); }); }; } // - Add Action - function addRequest() { return { type: SESSION.ADD.REQUEST, }; } function addSuccess(response) { const { data } = response; localStorage.setItem('viewer', JSON.stringify(data)); return { type: SESSION.ADD.SUCCESS, viewer: data, }; } function addFailure(error) { return { type: SESSION.ADD.FAILURE, error: error.message, }; } function add(credentials) { return (dispatch) => { dispatch(addRequest()); return new Promise((resolve, reject) => { api.add(credentials) .then((response) => { dispatch(addSuccess(response)); return resolve(); }, (response) => { dispatch(addFailure(response)); return reject(response); }); }).catch((error) => { console.error(error); }); }; } // - Delete Action - function deleteRequest() { return { type: SESSION.DELETE.REQUEST, }; } function deleteSuccess(response) { const { data } = response; localStorage.removeItem('viewer'); return { type: SESSION.DELETE.SUCCESS, viewer: data, }; } function deleteFailure(error) { return { type: SESSION.DELETE.FAILURE, error: error.message, }; } function deleteItem() { return (dispatch) => { dispatch(deleteRequest()); return new Promise((resolve, reject) => { api.deleteItem() .then((response) => { dispatch(deleteSuccess(response)); return resolve(); }, (response) => { dispatch(deleteFailure(response)); return reject(response); }); }).catch((error) => { console.error(error); }); }; } export default { reset, read, add, deleteItem, }; config/index.js import dotenv from 'dotenv'; dotenv.config(); export default { PORT: process.env.PORT, MONGO_URI: process.env.MONGO_URI, MONGO_DB_NAME: process.env.MONGO_DB_NAME, JWT_SECRET: process.env.JWT_SECRET }; /**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * hprose/io/BytesIO.js * * * * Hprose BytesIO for Node.js. * * * * LastModified: Oct 23, 2016 * * Author: <> * * * \**********************************************************/ 'use strict'; var toBinaryString = global.hprose.toBinaryString; var _EMPTY_BYTES = new Uint8Array(0); var _INIT_SIZE = 1024; function writeInt32BE(bytes, p, i) { bytes[p++] = i >>> 24 & 0xFF; bytes[p++] = i >>> 16 & 0xFF; bytes[p++] = i >>> 8 & 0xFF; bytes[p++] = i & 0xFF; return p; } function writeInt32LE(bytes, p, i) { bytes[p++] = i & 0xFF; bytes[p++] = i >>> 8 & 0xFF; bytes[p++] = i >>> 16 & 0xFF; bytes[p++] = i >>> 24 & 0xFF; return p; } function writeString(bytes, p, str) { var n = str.length; for (var i = 0; i < n; ++i) { var codeUnit = str.charCodeAt(i); if (codeUnit < 0x80) { bytes[p++] = codeUnit; } else if (codeUnit < 0x800) { bytes[p++] = 0xC0 | (codeUnit >> 6); bytes[p++] = 0x80 | (codeUnit & 0x3F); } else if (codeUnit < 0xD800 || codeUnit > 0xDFFF) { bytes[p++] = 0xE0 | (codeUnit >> 12); bytes[p++] = 0x80 | ((codeUnit >> 6) & 0x3F); bytes[p++] = 0x80 | (codeUnit & 0x3F); } else { if (i + 1 < n) { var nextCodeUnit = str.charCodeAt(i + 1); if (codeUnit < 0xDC00 && 0xDC00 <= nextCodeUnit && nextCodeUnit <= 0xDFFF) { var rune = (((codeUnit & 0x03FF) << 10) | (nextCodeUnit & 0x03FF)) + 0x010000; bytes[p++] = 0xF0 | (rune >> 18); bytes[p++] = 0x80 | ((rune >> 12) & 0x3F); bytes[p++] = 0x80 | ((rune >> 6) & 0x3F); bytes[p++] = 0x80 | (rune & 0x3F); ++i; continue; } } throw new Error('Malformed string'); } } return p; } function readShortString(bytes, n) { var charCodes = new Uint16Array(n); var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: charCodes[i] = unit; break; case 12: case 13: if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bytes[off++] & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bytes[off++] & 0x3F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } } if (i < n) { charCodes = charCodes.subarray(0, i); } return [String.fromCharCode.apply(String, charCodes), off]; } function readLongString(bytes, n) { var buf = []; var charCodes = new Uint16Array(0x8000); var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: charCodes[i] = unit; break; case 12: case 13: if (off < len) { charCodes[i] = ((unit & 0x1F) << 6) | (bytes[off++] & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { charCodes[i] = ((unit & 0x0F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F); break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bytes[off++] & 0x3F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800); charCodes[i] = ((rune & 0x03FF) | 0xDC00); break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } if (i >= 0x7FFF - 1) { var size = i + 1; buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, size))); n -= size; i = -1; } } if (i > 0) { buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, i))); } return [buf.join(''), off]; } function readString(bytes, n) { if (n === undefined || n === null || (n < 0)) { n = bytes.length; } if (n === 0) { return ['', 0]; } return ((n < 0xFFFF) ? readShortString(bytes, n) : readLongString(bytes, n)); } function readStringAsBytes(bytes, n) { if (n === undefined) { n = bytes.length; } if (n === 0) { return [_EMPTY_BYTES, 0]; } var i = 0, off = 0; for (var len = bytes.length; i < n && off < len; i++) { var unit = bytes[off++]; switch (unit >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: break; case 12: case 13: if (off < len) { off++; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 14: if (off + 1 < len) { off += 2; break; } throw new Error('Unfinished UTF-8 octet sequence'); case 15: if (off + 2 < len) { var rune = (((unit & 0x07) << 18) | ((bytes[off++] & 0x3F) << 12) | ((bytes[off++] & 0x3F) << 6) | (bytes[off++] & 0x3F)) - 0x10000; if (0 <= rune && rune <= 0xFFFFF) { i++; break; } throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16)); } throw new Error('Unfinished UTF-8 octet sequence'); default: throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16)); } } return [bytes.subarray(0, off), off]; } function pow2roundup(x) { --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } function BytesIO() { var a = arguments; switch (a.length) { case 1: switch (a[0].constructor) { case Uint8Array: this._bytes = a[0]; this._length = a[0].length; break; case BytesIO: this._bytes = a[0].toBytes(); this._length = a[0].length; break; case String: this.writeString(a[0]); break; case Number: this._bytes = new Uint8Array(a[0]); break; default: this._bytes = new Uint8Array(a[0]); this._length = this._bytes.length; break; } break; case 2: this._bytes = new Uint8Array(a[0], a[1]); this._length = a[1]; break; case 3: this._bytes = new Uint8Array(a[0], a[1], a[2]); this._length = a[2]; break; } this.mark(); } Object.defineProperties(BytesIO.prototype, { _bytes: { value: null, writable: true }, _length: { value: 0, writable: true }, _wmark: { value: 0, writable: true }, _off: { value: 0, writable: true }, _rmark: { value: 0, writable: true }, _grow: { value: function(n) { var bytes = this._bytes; var required = this._length + n; var size = pow2roundup(required); if (bytes) { size *= 2; if (size > bytes.length) { var buf = new Uint8Array(size); buf.set(bytes); this._bytes = buf; } } else { size = Math.max(size, _INIT_SIZE); this._bytes = new Uint8Array(size); } } }, length: { get: function() { return this._length; } }, capacity: { get: function() { return this._bytes ? this._bytes.length : 0; } }, position: { get: function() { return this._off; } }, // returns a view of the the internal buffer. bytes: { get : function() { return (this._bytes === null) ? _EMPTY_BYTES : this._bytes.subarray(0, this._length); } }, mark: { value: function() { this._wmark = this._length; this._rmark = this._off; } }, reset: { value: function() { this._length = this._wmark; this._off = this._rmark; } }, clear: { value: function() { this._bytes = null; this._length = 0; this._wmark = 0; this._off = 0; this._rmark = 0; } }, writeByte: { value: function(b) { this._grow(1); this._bytes[this._length++] = b; } }, writeInt32BE: { value: function(i) { if ((i === (i | 0)) && (i <= 2147483647)) { this._grow(4); this._length = writeInt32BE(this._bytes, this._length, i); return; } throw new TypeError('value is out of bounds'); } }, writeUInt32BE: { value: function(i) { if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._grow(4); this._length = writeInt32BE(this._bytes, this._length, i | 0); return; } throw new TypeError('value is out of bounds'); } }, writeInt32LE: { value: function(i) { if ((i === (i | 0)) && (i <= 2147483647)) { this._grow(4); this._length = writeInt32LE(this._bytes, this._length, i); return; } throw new TypeError('value is out of bounds'); } }, writeUInt32LE: { value: function(i) { if (((i & 0x7FFFFFFF) + 0x80000000 === i) && (i >= 0)) { this._grow(4); this._length = writeInt32LE(this._bytes, this._length, i | 0); return; } throw new TypeError('value is out of bounds'); } }, write: { value: function(data) { var n = data.byteLength || data.length; if (n === 0) { return; } this._grow(n); var bytes = this._bytes; var length = this._length; switch (data.constructor) { case ArrayBuffer: bytes.set(new Uint8Array(data), length); break; case Uint8Array: bytes.set(data, length); break; case BytesIO: bytes.set(data.bytes, length); break; default: for (var i = 0; i < n; i++) { bytes[length + i] = data[i]; } break; } this._length += n; } }, writeAsciiString: { value: function(str) { var n = str.length; if (n === 0) { return; } this._grow(n); var bytes = this._bytes; var l = this._length; for (var i = 0; i < n; ++i, ++l) { bytes[l] = str.charCodeAt(i); } this._length = l; } }, writeString: { value: function(str) { var n = str.length; if (n === 0) { return; } // A single code unit uses at most 3 bytes. // Two code units at most 4. this._grow(n * 3); this._length = writeString(this._bytes, this._length, str); } }, readByte: { value: function() { if (this._off < this._length) { return this._bytes[this._off++]; } return -1; } }, readInt32BE: { value: function() { var bytes = this._bytes; var off = this._off; if (off + 3 < this._length) { var result = bytes[off++] << 24 | bytes[off++] << 16 | bytes[off++] << 8 | bytes[off++]; this._off = off; return result; } throw new Error('EOF'); } }, readUInt32BE: { value: function() { var value = this.readInt32BE(); if (value < 0) { return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, readInt32LE: { value: function() { var bytes = this._bytes; var off = this._off; if (off + 3 < this._length) { var result = bytes[off++] | bytes[off++] << 8 | bytes[off++] << 16 | bytes[off++] << 24; this._off = off; return result; } throw new Error('EOF'); } }, readUInt32LE: { value: function() { var value = this.readInt32LE(); if (value < 0) { return (value & 0x7FFFFFFF) + 0x80000000; } return value; } }, read: { value: function(n) { if (this._off + n > this._length) { n = this._length - this._off; } if (n === 0) { return _EMPTY_BYTES; } return this._bytes.subarray(this._off, this._off += n); } }, skip: { value: function(n) { if (this._off + n > this._length) { n = this._length - this._off; this._off = this._length; } else { this._off += n; } return n; } }, // the result is an Uint8Array, and includes tag. readBytes: { value: function(tag) { var pos = Array.indexOf(this._bytes, tag, this._off); var buf; if (pos === -1) { buf = this._bytes.subarray(this._off, this._length); this._off = this._length; } else { buf = this._bytes.subarray(this._off, pos + 1); this._off = pos + 1; } return buf; } }, // the result is a String, and doesn't include tag. // but the position is the same as readBytes readUntil: { value: function(tag) { var pos = Array.indexOf(this._bytes, tag, this._off); var str = ''; if (pos === this._off) { this._off++; } else if (pos === -1) { str = readString(this._bytes.subarray(this._off, this._length))[0]; this._off = this._length; } else { str = readString(this._bytes.subarray(this._off, pos))[0]; this._off = pos + 1; } return str; } }, readAsciiString: { value: function(n) { if (this._off + n > this._length) { n = this._length - this._off; } if (n === 0) { return ''; } return toBinaryString(this._bytes.subarray(this._off, this._off += n)); } }, // n is the UTF16 length readStringAsBytes: { value: function(n) { var r = readStringAsBytes(this._bytes.subarray(this._off, this._length), n); this._off += r[1]; return r[0]; } }, // n is the UTF16 length readString: { value: function(n) { var r = readString(this._bytes.subarray(this._off, this._length), n); this._off += r[1]; return r[0]; } }, // returns a view of the the internal buffer and clears `this`. takeBytes: { value: function() { var buffer = this.bytes; this.clear(); return buffer; } }, // returns a copy of the current contents and leaves `this` intact. toBytes: { value: function() { return new Uint8Array(this.bytes); } }, // returns a Buffer copy of the current contents and leaves `this` intact. toBuffer: { value: function() { var bytes = this._bytes; var length = this._length; var buffer = new Buffer(length); for (var i = 0; i < length; ++i) { buffer[i] = bytes[i]; } return buffer; } }, toString: { value: function() { return readString(this.bytes, this._length)[0]; } }, clone: { value: function() { return new BytesIO(this.toBytes()); } }, trunc: { value: function() { this._bytes = this._bytes.subarray(this._off, this._length); this._length = this._bytes.length; this._off = 0; this._wmark = 0; this._rmark = 0; } } }); function toString(data) { /* jshint -W086 */ if (data.length === 0) { return ''; } switch(data.constructor) { case String: return data; case Buffer: return data.toString(); case BytesIO: data = data.bytes; case ArrayBuffer: data = new Uint8Array(data); case Uint8Array: return readString(data, data.length)[0]; default: return String.fromCharCode.apply(String, data); } } function toBuffer(data) { /* jshint -W086 */ switch(data.constructor) { case Buffer: return data; case ArrayBuffer: data = new Uint8Array(data); case Uint8Array: data = new BytesIO(data); case BytesIO: return data.toBuffer(); default: return new Buffer(data); } } Object.defineProperties(BytesIO, { toString: { value: toString }, toBuffer: { value: toBuffer } }); global.hprose.BytesIO = BytesIO; components/dropdown/Dropdown.js import React from "react"; import ReactDOM from "react-dom"; import PropTypes from "prop-types"; import classNames from "classnames"; import { Manager } from "react-popper"; import omit from "lodash.omit"; import { DropdownContext } from "./DropdownContext"; import { KEYCODES, EVENTS } from "./../constants"; /** * You can use dropdowns to display accessible contextual overlays for displaying lists of links and more. */ class Dropdown extends React.Component { constructor(props) { super(props); this.handleListeners = this.handleListeners.bind(this); this.addListeners = this.addListeners.bind(this); this.removeListeners = this.removeListeners.bind(this); this.handleDocumentClick = this.handleDocumentClick.bind(this); this.getContainer = this.getContainer.bind(this); this.toggle = this.toggle.bind(this); } componentDidMount() { this.handleListeners(); } componentWillUnmount() { this.removeListeners(); } componentDidUpdate(prevProps) { if (this.props.open !== prevProps.open) { this.handleListeners(); } } handleListeners() { if (this.props.open) { this.addListeners(); return; } this.removeListeners(); } addListeners() { EVENTS.CLICK.forEach(e => document.addEventListener(e, this.handleDocumentClick, true) ); } removeListeners() { EVENTS.CLICK.forEach(e => document.removeEventListener(e, this.handleDocumentClick, true) ); } getContainer() { return ReactDOM.findDOMNode(this); // eslint-disable-line react/no-find-dom-node } handleDocumentClick(e) { if ( e && (e.which === 3 || (e.type === "keyup" && e.which !== KEYCODES.TAB)) ) return; const container = this.getContainer(); if ( container.contains(e.target) && container !== e.target && (e.type !== "keyup" || e.which === KEYCODES.TAB) ) { return; } this.toggle(e); } toggle(e) { if (this.props.disabled) { return e && e.preventDefault(); } return this.props.toggle(e); } render() { const props = omit(this.props, [ "toggle", "disabled", "inNavbar", "direction" ]); const { className, children, dropup, open, group, size, nav, setActiveFromChild, active, addonType, ...attrs } = props; const direction = this.props.direction === "down" && dropup ? "up" : this.props.direction; attrs.tag = attrs.tag || (nav ? "li" : "div"); let subItemIsActive = false; if (setActiveFromChild) { React.Children.map( this.props.children[1].props.children, dropdownItem => { if (dropdownItem && dropdownItem.props.active) subItemIsActive = true; } ); } const classes = classNames( className, direction !== "down" && `drop${direction}`, nav && active && "active", setActiveFromChild && subItemIsActive && "active", addonType && `input-group-${addonType}`, group && "btn-group", !!size && `btn-group-${size}`, !group && !addonType && "dropdown", open && "show", nav && "nav-item" ); const toggle = this.toggle; return ( {() =>
    {children}
    }
    ); } } Dropdown.propTypes = { /** * The class name. */ className: PropTypes.string, /** * Whether it is open, or not. */ open: PropTypes.bool, /** * Whether it is disabled, or not. */ disabled: PropTypes.bool, /** * The toggle function. */ toggle: PropTypes.func, /** * Whether it is located inside a navbar, or not. */ inNavbar: PropTypes.bool, /** * Whether it is a drop-up, or not. */ dropup: PropTypes.bool, /** * The component's tag type. */ tag: PropTypes.string, /** * Whether it is located inside a Nav, or not. */ nav: PropTypes.bool, /** * The direction. */ direction: PropTypes.oneOf(["up", "down", "left", "right"]) }; Dropdown.defaultProps = { open: false, direction: "down", nav: false }; export default Dropdown; 'use strict'; var tslib = require('tslib'); var locator = require('./locator.js'); var index = require('./decoder/index.js'); var extractor = require('./extractor.js'); var binarizer = require('./binarizer.js'); /** * @module QRCode * @author nuintun * @author * @license https://raw.githubusercontent.com/cozmo/jsQR/master/LICENSE */ function scan(matrix) { var locations = locator.locate(matrix); if (!locations) { return null; } for (var _i = 0, locations_1 = locations; _i < locations_1.length; _i++) { var location_1 = locations_1[_i]; var extracted = extractor.extract(matrix, location_1); var decoded = index.decode(extracted.matrix); if (decoded) { var dimension = location_1.dimension; return tslib.__assign(tslib.__assign({}, decoded), { location: { topLeft: extracted.mappingFunction(0, 0), topRight: extracted.mappingFunction(dimension, 0), bottomLeft: extracted.mappingFunction(0, dimension), bottomRight: extracted.mappingFunction(dimension, dimension), topLeftFinder: location_1.topLeft, topRightFinder: location_1.topRight, bottomLeftFinder: location_1.bottomLeft, bottomRightAlignment: decoded.version > 1 ? location_1.alignmentPattern : null } }); } } } var defaultOptions = { canOverwriteImage: true, greyScaleWeights: { red: 0.2126, green: 0.7152, blue: 0.0722, useIntegerApproximation: false }, inversionAttempts: 'attemptBoth' }; function disposeImageEvents(image) { image.onload = null; image.onerror = null; } var Decoder = /*#__PURE__*/ (function () { function Decoder() { this.options = defaultOptions; } /** * @public * @method setOptions * @param {object} options */ Decoder.prototype.setOptions = function (options) { if (options === void 0) { options = {}; } options = options || {}; this.options = tslib.__assign(tslib.__assign({}, defaultOptions), options); return this; }; /** * @public * @method decode * @param {Uint8ClampedArray} data * @param {number} width * @param {number} height * @returns {DecoderResult} */ Decoder.prototype.decode = function (data, width, height) { var options = this.options; var canOverwriteImage = options.canOverwriteImage, greyScaleWeights = options.greyScaleWeights, inversionAttempts = options.inversionAttempts; var tryInvertedFirst = inversionAttempts === 'onlyInvert' || inversionAttempts === 'invertFirst'; var invert = tryInvertedFirst || inversionAttempts === 'attemptBoth'; var _a = binarizer.binarize(data, width, height, invert, greyScaleWeights, canOverwriteImage), binarized = _a.binarized, inverted = _a.inverted; var result = scan(tryInvertedFirst ? inverted : binarized); if (!result && (options.inversionAttempts === 'attemptBoth' || options.inversionAttempts === 'invertFirst')) { result = scan(tryInvertedFirst ? binarized : inverted); } return result; }; /** * @public * @method scan * @param {string} src * @returns {Promise} */ Decoder.prototype.scan = function (src) { var _this = this; return new Promise(function (resolve, reject) { var image = new Image(); // Image cross origin image.crossOrigin = 'anonymous'; image.onload = function () { disposeImageEvents(image); var width = image.width; var height = image.height; var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); canvas.width = width; canvas.height = height; context.drawImage(image, 0, 0); var data = context.getImageData(0, 0, width, height).data; var result = _this.decode(data, width, height); if (result) { return resolve(result); } return reject(new Error('failed to decode image')); }; image.onerror = function () { disposeImageEvents(image); reject(new Error("failed to load image: " + src)); }; image.src = src; }); }; return Decoder; }()); exports.Decoder = Decoder; frontend/src/config/index.js // const Web3 = require('web3'); const contractsURL = 'http://localhost:3000/contracts'; // const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); const { web3 } = window; export const getContractInfo = async (contract) => { const data = await window.fetch(`${contractsURL}/${contract}.json`); return data.json(); }; export const getDefaultAccount = () => web3.eth.accounts[0]; export const getRegistryFactory = async () => { const registryFactoryArtifact = await getContractInfo('RegistryFactory'); const { abi, address } = registryFactoryArtifact; return web3.eth.contract(abi).at(address); }; export const getToken = async () => { const tokenArtifact = await getContractInfo('TestToken'); const { abi, address } = tokenArtifact; return web3.eth.contract(abi).at(address); }; export const getVotingContractAt = async (address) => { const votingContractArtifact = await getContractInfo('PLCRVoting'); const { abi } = votingContractArtifact; return web3.eth.contract(abi).at(address); }; /** * @ngdoc service * @name umbraco.resources.mediaTypeResource * @description Loads in data for media types **/ function mediaTypeResource($q, $http, umbRequestHelper, umbDataFormatter) { return { getCount: function () { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetCount")), 'Failed to retrieve count'); }, getAvailableCompositeContentTypes: function (contentTypeId, filterContentTypes, filterPropertyTypes) { if (!filterContentTypes) { filterContentTypes = []; } if (!filterPropertyTypes) { filterPropertyTypes = []; } var query = { contentTypeId: contentTypeId, filterContentTypes: filterContentTypes, filterPropertyTypes: filterPropertyTypes }; return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetAvailableCompositeMediaTypes"), query), 'Failed to retrieve data for content type id ' + contentTypeId); }, /** * @ngdoc method * @name umbraco.resources.mediaTypeResource#getAllowedTypes * @methodOf umbraco.resources.mediaTypeResource * * @description * Returns a list of allowed media types underneath a media item with a given ID * * ##usage *
             * mediaTypeResource.getAllowedTypes(1234)
             *    .then(function(array) {
             *        $scope.type = type;
             *    });
             * 
    * @param {Int} mediaId id of the media item to retrive allowed child types for * @returns {Promise} resourcePromise object. * */ getAllowedTypes: function (mediaId) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetAllowedChildren", [{ contentId: mediaId }])), 'Failed to retrieve allowed types for media id ' + mediaId); }, getById: function (id) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetById", [{ id: id }])), 'Failed to retrieve content type'); }, getAll: function () { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetAll")), 'Failed to retrieve all content types'); }, getScaffold: function (parentId) { return umbRequestHelper.resourcePromise( $http.get( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "GetEmpty", { parentId: parentId })), 'Failed to retrieve content type scaffold'); }, deleteById: function (id) { return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "DeleteById", [{ id: id }])), 'Failed to retrieve content type'); }, deleteContainerById: function (id) { return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "DeleteContainer", [{ id: id }])), 'Failed to delete content type contaier'); }, /** * @ngdoc method * @name umbraco.resources.mediaTypeResource#save * @methodOf umbraco.resources.mediaTypeResource * * @description * Saves or update a media type * * @param {Object} content data type object to create/update * @returns {Promise} resourcePromise object. * */ save: function (contentType) { var saveModel = umbDataFormatter.formatContentTypePostData(contentType); return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("mediaTypeApiBaseUrl", "PostSave"), saveModel), 'Failed to save data for content type id ' + contentType.id); }, /** * @ngdoc method * @name umbraco.resources.mediaTypeResource#move * @methodOf umbraco.resources.mediaTypeResource * * @description * Moves a node underneath a new parentId * * ##usage *
             * mediaTypeResource.move({ parentId: 1244, id: 123 })
             *    .then(function() {
             *        alert("node was moved");
             *    }, function(err){
             *      alert("node didnt move:" + err.data.Message);
             *    });
             * 
    * @param {Object} args arguments object * @param {Int} args.idd the ID of the node to move * @param {Int} args.parentId the ID of the parent node to move to * @returns {Promise} resourcePromise object. * */ move: function (args) { if (!args) { throw "args cannot be null"; } if (!args.parentId) { throw "args.parentId cannot be null"; } if (!args.id) { throw "args.id cannot be null"; } return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("mediaTypeApiBaseUrl", "PostMove"), { parentId: args.parentId, id: args.id }), 'Failed to move content'); }, copy: function (args) { if (!args) { throw "args cannot be null"; } if (!args.parentId) { throw "args.parentId cannot be null"; } if (!args.id) { throw "args.id cannot be null"; } return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("mediaTypeApiBaseUrl", "PostCopy"), { parentId: args.parentId, id: args.id }), 'Failed to copy content'); }, createContainer: function(parentId, name) { return umbRequestHelper.resourcePromise( $http.post( umbRequestHelper.getApiUrl( "mediaTypeApiBaseUrl", "PostCreateContainer", { parentId: parentId, name: name })), 'Failed to create a folder under parent id ' + parentId); }, renameContainer: function (id, name) { return umbRequestHelper.resourcePromise( $http.post(umbRequestHelper.getApiUrl("mediaTypeApiBaseUrl", "PostRenameContainer", { id: id, name: name })), "Failed to rename the folder with id " + id ); } }; } angular.module('umbraco.resources').factory('mediaTypeResource', mediaTypeResource); eduardomendesnorberto/4food import React, { Component } from "react"; import Button from "@material-ui/core/Button"; import CssBaseline from '@material-ui/core/CssBaseline'; import TextField from '@material-ui/core/TextField'; import Typography from '@material-ui/core/Typography'; import { makeStyles, styled } from '@material-ui/core/styles'; import Container from '@material-ui/core/Container'; const useStyles = makeStyles(theme => ({ paper: { marginTop: theme.spacing(2), display: 'flex', flexDirection: 'column', alignItems: 'center', }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing(1), }, submit: { margin: theme.spacing(3, 0, 2), }, })); export function FormContainer(props) { const classes = useStyles(); const preventDefault = (e) => { e.preventDefault() props.onClickCriar(props.form) } return (
    {props.formTitle !== undefined && {props.formTitle}}
    {props.formInputs.map( input => ( ))}
    ); } export default FormContainer;0 const { Types, ArrayType, FunctionDeclaration, Params, Param, IdExp, } = require("../ast"); const IntType = new Types("int"); const StringType = new Types("str"); const BooleanType = new Types("boo"); const DoubleType = new Types("dub"); const ArrayOfIntType = new ArrayType("arr", new Types("int")); const ArrayOfStringType = new ArrayType("arr", new Types("str")); const ArrayOfBooleanType = new ArrayType("arr", new Types("boo")); const ArrayOfDoubleType = new ArrayType("arr", new Types("dub")); const standardFunctions = [ new FunctionDeclaration(new IdExp("tabulate")), new FunctionDeclaration( new IdExp("addRow"), new Params([new Param(new IdExp("row"))]) ), new FunctionDeclaration( new IdExp("addColumn"), new Params([new Param(new IdExp("column"))]) ), new FunctionDeclaration( new IdExp("dropRow"), new Params([new Param(new IdExp("row"))]) ), new FunctionDeclaration( new IdExp("dropColumn"), new Params([new Param(new IdExp("column"))]) ), new FunctionDeclaration( new IdExp("addRule"), new Params([new Param(new IdExp("column"))]) ), ]; module.exports = { IntType, StringType, BooleanType, DoubleType, ArrayOfIntType, ArrayOfStringType, ArrayOfBooleanType, ArrayOfDoubleType, standardFunctions, }; 0 'use strict'; const handlebars = require('handlebars'); function handlebarsCompile(data) { return handlebars.compile(data.text); } function handlebarsRenderer(data, locals) { return handlebarsCompile(data)(locals); } handlebarsRenderer.compile = handlebarsCompile; module.exports = handlebarsRenderer; import { Container } from "unstated"; import ConsoleConfig from "../../config.json"; export default class ConsoleContainer extends Container { constructor(props) { super(props); this.state = { // Données provenant de config/config.json clientName: ConsoleConfig.clientName, loading: false, rootHostname: ConsoleConfig.rootHostname, rootName: ConsoleConfig.rootName, rootProto: ConsoleConfig.rootProto, escape: ConsoleConfig.escape, pathState: ConsoleConfig.pathState, pathConfig: ConsoleConfig.pathConfig, auth: ConsoleConfig.auth, //config json: {}, newJson: {}, boxConfig: [], // states refresh: false, cdnNames: [], cdnBPs: [], releases: [], dataChart: { data: { labels: [], series: [] } }, boxStatesNS: [], cdnboxesHTTP: [], cdnboxesNoNS: [], onLoad: false, interval: 1000, activeMenu: "Dashboard", rootConfig: [] }; this.getContent = this.getContent.bind(this); this.updateAllStates = this.updateAllStates.bind(this); this.updateRefresh = this.updateRefresh.bind(this); this.uploadRootConfig = this.uploadRootConfig.bind(this); this.uploadConfig = this.uploadConfig.bind(this); this.saveConfig = this.saveConfig.bind(this); this.acceptAlert = this.acceptAlert.bind(this); this.init = this.init.bind(this); this.initConfig = this.initConfig.bind(this); this.init(); this.initConfig(); } setRootConfig(body) { this.setState({ rootConfig: body }); } startShortPolling(f) { this.interval = setInterval(f, this.state.interval); } updateAllStates() { let arrPromise = []; let httpBox = []; let path = this.state.pathState; arrPromise = this.state.boxStatesNS.map(cdnbox => { httpBox.push(cdnbox); let url = cdnbox.local.proto === undefined ? "https:" : cdnbox.local.proto; url += "//" + cdnbox.local.hostname + path; return this.getContent(url, cdnbox.local.hostname, path, true); }); Promise.all(arrPromise).then(values => { let process = values; let cdnNames = []; let cdnBPs = []; let releases = []; Object.keys(values).forEach(function(key) { var internalName = values[key].name; var context = values[key].cdnboxes; if (releases.indexOf(parseInt(values[key].release, 10)) === -1) releases.push(parseInt(values[key].release, 10)); Object.keys(context).forEach(function(key2) { if (context[key2].name === internalName) { process[key].local = context[key2]; cdnNames.push(internalName); cdnBPs.push(Math.ceil(context[key2].trendbw)); } }); }); let dataChart = { labels: cdnNames, series: [cdnBPs] }; this.setState({ boxStatesNS: process, cdnNames: cdnNames, cdnBPs: cdnBPs, dataChart: dataChart, cdnboxesHTTP: process, releases: releases.sort() }); }); } initConfig(error = null, response = null, body = null) { console.log("Init Config"); if (body) { var start = new Date().getTime(); var end = start; while (end < start + 2000) { end = new Date().getTime(); } } let boxStatesNS = []; let cdnboxesHTTP = []; let cdnboxesNoNS = []; let url = this.state.rootProto + "://" + this.state.rootHostname + this.state.pathConfig; this.getContent( url, this.state.rootHostname, this.state.pathConfig, true ).then(data => { for (let i = 0; i < data.cdnboxes.length; i++) { if (this.state.escape.indexOf(data.cdnboxes[i].name) === -1) { if (data.cdnboxes[i].isns) boxStatesNS.push(data.cdnboxes[i]); else cdnboxesNoNS.push(data.cdnboxes[i]); if (data.cdnboxes[i].isns && data.cdnboxes[i].ishttp) cdnboxesHTTP.push(data.cdnboxes[i]); } } let arrPromise = []; let httpBox = []; arrPromise = boxStatesNS.map(cdnbox => { httpBox.push(cdnbox); let url = cdnbox.proto === undefined ? "https:" : cdnbox.proto; url += "//" + cdnbox.hostname + this.state.pathConfig; return this.getContent( url, cdnbox.hostname, this.state.pathConfig, true ); }); Promise.all(arrPromise).then(values => { let configs = []; let proto = ""; for (let i = 0; i < boxStatesNS.length; i++) { proto = boxStatesNS[i].proto === undefined ? "https:" : boxStatesNS[i].proto; configs.push({ name: boxStatesNS[i].name, proto: proto, hostname: boxStatesNS[i].hostname, json: values[i] }); } this.setState({ boxConfig: configs, json: data, newJson: data }); }); }); } saveConfig(data) { try { JSON.parse(data.json); } catch (e) { return false; } this.setState({ newJson: JSON.parse(data.json) }); } init() { console.log("Init"); let boxStatesNS = []; let cdnboxesHTTP = []; let cdnboxesNoNS = []; let url = this.state.rootProto + "://" + this.state.rootHostname + this.state.pathState; this.getContent( url, this.state.rootHostname, this.state.pathState, true ).then(data => { for (let i = 0; i < data.cdnboxes.length; i++) { if (this.state.escape.indexOf(data.cdnboxes[i].name) === -1) { if (data.cdnboxes[i].isns) boxStatesNS.push(data.cdnboxes[i]); else cdnboxesNoNS.push(data.cdnboxes[i]); if (data.cdnboxes[i].isns && data.cdnboxes[i].ishttp) cdnboxesHTTP.push(data.cdnboxes[i]); } } // get ALL Statements let arrPromise = []; let httpBox = []; arrPromise = boxStatesNS.map(cdnbox => { httpBox.push(cdnbox); let url = cdnbox.proto === undefined ? "https:" : cdnbox.proto; url += "//" + cdnbox.hostname + this.state.pathState; return this.getContent( url, cdnbox.hostname, this.state.pathState, true ); }); Promise.all(arrPromise).then(values => { let process = values; let cdnNames = []; let cdnBPs = []; let releases = []; Object.keys(values).forEach(function(key) { var internalName = values[key].name; var context = values[key].cdnboxes; if (releases.indexOf(parseInt(values[key].release, 10)) === -1) releases.push(parseInt(values[key].release, 10)); Object.keys(context).forEach(function(key2) { if (context[key2].name === internalName) { process[key].local = context[key2]; cdnNames.push(internalName); cdnBPs.push(Math.ceil(context[key2].trendbw)); } }); }); let dataChart = { labels: cdnNames, series: [cdnBPs] }; this.setState({ boxStatesNS: process, cdnNames: cdnNames, cdnBPs: cdnBPs, dataChart: dataChart, cdnboxesHTTP: process, releases: releases.sort() }); }); }); } uploadRootConfig() { console.log("Upload Root Config"); var request = require("request"); let url = this.state.rootProto + "://" + this.state.rootHostname + "/cdn/config"; request( { url: url, method: "PUT", headers: { Authorization: this.state.auth, "content-type": "application/json" }, json: this.state.newJson }, this.initConfig ); } uploadConfig(cdnbox) { console.log("Upload Config : " + cdnbox.name); var request = require("request"); let url = cdnbox.proto === undefined ? "https:" : cdnbox.proto; url += "//" + cdnbox.hostname + this.state.pathConfig; console.log(url); console.log(this.state.json); request( { url: url, method: "PUT", headers: { Authorization: this.state.auth, "content-type": "application/json" }, json: this.state.json }, this.initConfig ); } acceptAlert() { var start = new Date().getTime(); var end = start; while (end < start + 10000) { end = new Date().getTime(); } return true; } stopShortPolling() { clearInterval(this.interval); } updateRefresh() { var refresh = !this.state.refresh; this.setState({ refresh: refresh }); if (refresh) this.startShortPolling(this.updateAllStates); else this.stopShortPolling(); } getContent = function(url, host, path, auth_required = false) { return new Promise((resolve, reject) => { // select http or https module, depending on reqested url const lib = url.startsWith("https") ? require("https") : require("http"); let auth = ConsoleConfig.auth; let options = { host: host, path: path }; if (auth_required) { options = { host: host, path: path, headers: { Authorization: auth } }; } const request = lib.get(options, response => { // handle http errors if (response.statusCode < 200 || response.statusCode > 299) { reject( new Error( "Failed to load page, status code: " + response.statusCode ) ); } // temporary data holder const body = []; response.setEncoding("utf8"); // on every content chunk, push it to the data array response.on("data", chunk => body.push(chunk)); // we are done, resolve promise with those joined chunks response.on("end", () => resolve(JSON.parse(body.join("")))); }); // handle connection errors of the request request.on("error", err => reject(err)); }); }; } app/models/realtime/trip.js 'use strict'; define(function(require) { var Super = require('./base'); var Model = Super.extend({ name: 'trips', autoSync: true }); return Model; }); 1-10 import firebase from 'firebase/app'; import 'firebase/functions'; const config = { apiKey: "", authDomain: "version2-46721.firebaseapp.com", databaseURL: "https://version2-46721.firebaseio.com", projectId: "version2-46721", storageBucket: "version2-46721.appspot.com", messagingSenderId: "861385964505" }; firebase.initializeApp(config); let makeQuery = (query) => { return new Cypress.Promise((resolve, reject) => { let message = firebase.functions().httpsCallable('message'); message({ query: query }).then((result) => { return resolve(result); }); }); } describe('Dialogflow detects the correct intent fromt the following queries:', function () { beforeEach(function () { let intent = ""; }); it('short courses list', function () { cy.wrap(null).then(() => { return makeQuery('short courses list').then((response) => { expect(response.data.intent).to.equal('Available Courses'); }); }); }); it('Which course starts on the 17th of January and ends on the 21st of March? What is it\'s ID?', function () { cy.wrap(null).then(() => { return makeQuery('Which course starts on the 17th of January and ends on the 21st of March? What is it\'s ID?').then((response) => { expect(response.data.intent).to.equal('FindClassCode'); }); }); }); it('How much do you have to pay for Ancient Egypt and the Bible which starts on 17th of January', function () { cy.wrap(null).then(() => { return makeQuery('How much do you have to pay for Ancient Egypt and the Bible which starts on 17th of January').then((response) => { expect(response.data.intent).to.equal('FindCost'); }); }); }); it('How many credits does class code 9248 provide?', function () { cy.wrap(null).then(() => { return makeQuery('How many credits does class code 9248 provide?').then((response) => { expect(response.data.intent).to.equal('FindCredits'); }); }); }); it('Description of Ancient Egypt and the Bible', function () { cy.wrap(null).then(() => { return makeQuery('Description of Ancient Egypt and the Bible').then((response) => { expect(response.data.intent).to.equal('FindDescription'); }); }); }); it('What is the duration of class id 9248 ?', function () { cy.wrap(null).then(() => { return makeQuery('What is the duration of class id 9248 ?').then((response) => { expect(response.data.intent).to.equal('FindDuration'); }); }); }); it('Can you give me the end date for the course Ancient Egypt and the Bible?', function () { cy.wrap(null).then(() => { return makeQuery('Can you give me the end date for the course Ancient Egypt and the Bible?').then((response) => { expect(response.data.intent).to.equal('FindEndDate'); }); }); }); it('Who is the lecturer for the short course Ancient Egypt and the Bible', function () { cy.wrap(null).then(() => { return makeQuery('Who is the lecturer for the short course Ancient Egypt and the Bible').then((response) => { expect(response.data.intent).to.equal('FindLecturer'); }); }); }); it('When does the course Ancient Egypt and the Bible start?', function () { cy.wrap(null).then(() => { return makeQuery('When does the course Ancient Egypt and the Bible start?').then((response) => { expect(response.data.intent).to.equal('FindStartDate'); }); }); }); it('What is the subject area of the course Ancient Egypt and the Bible?', function () { cy.wrap(null).then(() => { return makeQuery('What is the subject area of the course Ancient Egypt and the Bible?').then((response) => { expect(response.data.intent).to.equal('FindSubjectArea'); }); }); }); it('what is the course with id 9248, start date 17th of January, end date 21st of March, duration 64 days, offering 10 credits and costs 125 pounds', function () { cy.wrap(null).then(() => { return makeQuery('what is the course with id 9248, start date 17th of January, end date 21st of March, duration 64 days, offering 10 credits and costs 125 pounds').then((response) => { expect(response.data.intent).to.equal('FindTitle'); }); }); }); it('Where is the course Ancient Egypt and the Bible taking place?', function () { cy.wrap(null).then(() => { return makeQuery('Where is the course Ancient Egypt and the Bible taking place?').then((response) => { expect(response.data.intent).to.equal('FindVenue'); }); }); }); it('subject areas', function () { cy.wrap(null).then(() => { return makeQuery('subject areas').then((response) => { expect(response.data.intent).to.equal('Subject Areas'); }); }); }); // it('What is the venue of course with ID 2580?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the venue of course with ID 2580?').then((response) => { // expect(response.data.intent).to.equal('ID -> Venue'); // }); // }); // }); // // it('Which courses begin on the twenty fourth of november?', function () { // // cy.wrap(null).then(() => { // return makeQuery('Which courses begin on the twenty fourth of november?').then((response) => { // expect(response.data.intent).to.equal('Start date -> Title'); // }); // }); // }); // // it('Are there any classes about Archaeology Classical Studies and Egyptology?', function () { // // cy.wrap(null).then(() => { // return makeQuery('Are there any classes about Archaeology Classical Studies and Egyptology?').then((response) => { // expect(response.data.intent).to.equal('Subject area -> Title'); // }); // }); // }); // // it('What subject areas are there?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What subject areas are there?').then((response) => { // expect(response.data.intent).to.equal('Subject Areas'); // }); // }); // }); // // // it('What is the id of Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the id of Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> Class Code'); // }); // }); // }); // // // it('Give me the Cleopatra: Queen of Egypt cost', function () { // // cy.wrap(null).then(() => { // return makeQuery('Give me the Cleopatra: Queen of Egypt cost').then((response) => { // expect(response.data.intent).to.equal('Title -> Cost'); // }); // }); // }); // // // // it('I\'d like to know how many credits does Cleopatra: Queen of Egypt gives', function () { // // cy.wrap(null).then(() => { // return makeQuery('I\'d like to know how many credits does Cleopatra: Queen of Egypt gives').then((response) => { // expect(response.data.intent).to.equal('Title -> Credits'); // }); // }); // }); // // // it('What is Cleopatra: Queen of Egypt\'s description?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is Cleopatra: Queen of Egypt\'s description?').then((response) => { // expect(response.data.intent).to.equal('Title -> Description'); // }); // }); // }); // // it('What is the length of Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the length of Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> Duration'); // }); // }); // }); // // // it('What is the end date of Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the end date of Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> End Date'); // }); // }); // }); // // it('What is the start date of Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the start date of Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> Start Date'); // }); // }); // }); // // it('Can you tell me the subject area of Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('Can you tell me the subject area of Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> Subject Area'); // }); // }); // }); // // it('Who teaches Cleopatra: Queen of Egypt', function () { // // cy.wrap(null).then(() => { // return makeQuery('Who teaches Cleopatra: Queen of Egypt').then((response) => { // expect(response.data.intent).to.equal('Title -> Tutor'); // }); // }); // }); // // it('What is the venue for Cleopatra: Queen of Egypt?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What is the venue for Cleopatra: Queen of Egypt?').then((response) => { // expect(response.data.intent).to.equal('Title -> Venue'); // }); // }); // }); // // it('What are the courses taught by ?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What are the courses taught by ?').then((response) => { // expect(response.data.intent).to.equal('Tutor -> Title'); // }); // }); // }); // // // it('What are the courses in the main building?', function () { // // cy.wrap(null).then(() => { // return makeQuery('What are the courses in the main building').then((response) => { // expect(response.data.intent).to.equal('Venue -> Title'); // }); // }); // }); });var penguinModel = new PenguinModel(XMLHttpRequest); var targetElement = document.getElementById('listOfPenguins'); var penguinView = new PenguinView(targetElement); var controller = new PenguinController(penguinView, penguinModel); controller.initialize(); controller.onClickGetPenguin({ currentTarget: { dataset: { penguinIndex: 0 } } }); /** * @param {!Tag} tag The original tag * @param {!Object} hosts Map of [host => siteId] * @param {!Object} sites Map of [siteId => siteConfig] */ function (tag, hosts, sites) { /** * Filter a MEDIA tag * * This will always invalidate the original tag, and possibly replace it with the tag that * corresponds to the media site * * @param {!Tag} tag The original tag * @param {!Object} hosts Map of [host => siteId] * @param {!Object} sites Map of [siteId => siteConfig] */ function filterTag(tag, hosts, sites) { // Always invalidate this tag tag.invalidate(); if (tag.hasAttribute('url')) { var url = tag.getAttribute('url'), siteId = getSiteIdFromUrl(url, hosts); if (sites[siteId]) { var attributes = getAttributes(url, sites[siteId]); if (!empty(attributes)) { createTag(siteId.toUpperCase(), tag).setAttributes(attributes); } } } } /** * Add named captures from a set of regular expressions to a set of attributes * * @param {!Object} attributes Associative array of strings * @param {string} string Text to match * @param {!Array} regexps List of [regexp, map] pairs * @return {boolean} Whether any regexp matched */ function addNamedCaptures(attributes, string, regexps) { var matched = false; regexps.forEach(function(pair) { var regexp = pair[0], map = pair[1], m = regexp.exec(string); if (!m) { return; } matched = true; map.forEach(function(name, i) { if (m[i] > '' && name > '') { attributes[name] = m[i]; } }); }); return matched; } /** * Create a tag for a media embed * * @param {string} tagName Tag's name * @param {!Tag} tag Reference tag * @return {!Tag} New tag */ function createTag(tagName, tag) { var startPos = tag.getPos(), endTag = tag.getEndTag(), startLen, endPos, endLen; if (endTag) { startLen = tag.getLen(); endPos = endTag.getPos(); endLen = endTag.getLen(); } else { startLen = 0; endPos = tag.getPos() + tag.getLen(); endLen = 0; } return addTagPair(tagName, startPos, startLen, endPos, endLen, tag.getSortPriority()); } /** * @param {!Object} attributes * @return {boolean} */ function empty(attributes) { for (var attrName in attributes) { return false; } return true; } /** * Return a set of attributes for given URL based on a site's config * * @param {string} url Original URL * @param {!Object} config Site config * @return {!Object} Attributes */ function getAttributes(url, config) { var attributes = {}; addNamedCaptures(attributes, url, config[0]); return attributes; } /** * Return the siteId that corresponds to given URL * * @param {string} url Original URL * @param {!Array} hosts Map of [hostname => siteId] * @return {string} URL's siteId, or an empty string */ function getSiteIdFromUrl(url, hosts) { var m = /^https?:\/\/([^\/]+)/.exec(url.toLowerCase()), host = m[1] || ''; while (host > '') { if (hosts[host]) { return hosts[host]; } host = host.replace(/^[^.]*./, ''); } return ''; } filterTag(tag, hosts, sites); }0 'use strict' /** * 从命令行参数中读取用户的执行参数 */ var yargs = require('yargs') var commander = yargs .usage('node data stub.\nUsage: $0 -t -o -p -f -c ') .option('table', { describe: '要生成的数据表', alias: 't', default: '', }) .option('print', { describe: '是否打印', alias: 'p', default: 'console', }) .option('function', { describe: '执行的功能[generate, ls, table]', alias: 'f', default: 'table', }) .option('config', { describe: '配置文件的位置', alias: 'c', default: 'app.json', }) .option('output', { describe: '输出目录', alias: 'o', default: 'dist', }) .option('language', { describe: '输出语言', alias: 'l', default: 'javascript', choices: ['javascript', 'typescript'], }) .help('help') exports.getCommandConfig = function () { var cmdConfig = { tableName: '', language: '', outputPath: '', configPath: '', printConfig: true, } var argv = commander.argv cmdConfig.configPath = argv.config cmdConfig.outputPath = argv.output cmdConfig.tableName = argv.table cmdConfig.function = argv.function cmdConfig.language = argv.language cmdConfig.printConfig = argv.print === 'console' return cmdConfig } exports.commander = commander 10-100 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import PropTypes from 'prop-types' import { useState, useCallback, useRef, useEffect } from 'react' import { CopyToClipboard as CopyComponent } from 'react-copy-to-clipboard' import styles from './CopyToClipboard.module.scss' // Component Constants const CLICKED_STATE_RESET_TIME = 1500 // 1.5 seconds function CopyToClipboard (props) { const { as: Component = 'span', doHint, className, children, text, } = props const [copied, setCopied] = useState(false) const timeoutRef = useRef() const handleCopy = useCallback(() => { if (copied) { clearTimeout(timeoutRef.current) } else { setCopied(true) } timeoutRef.current = setTimeout(() => { setCopied(false) timeoutRef.current = undefined }, CLICKED_STATE_RESET_TIME) }, [copied]) useEffect(() => { return () => { clearTimeout(timeoutRef.current) } }, []) return ( {children} { doHint && ( ) } ) } CopyToClipboard.propTypes = { as: PropTypes.elementType, children: PropTypes.node, className: PropTypes.string, doHint: PropTypes.bool, text: PropTypes.any.isRequired, } export default CopyToClipboard 'use strict' const test = require('tape') const { Encoding } = require('../lib/encoding') const identity = (v) => v test('Encoding() throws on invalid encode or decode property', function (t) { t.plan(2 * 6 * 2) for (const opt of ['encode', 'decode']) { for (const invalid of [true, false, null, '', 'x', {}]) { try { // eslint-disable-next-line no-new new Encoding({ encode: identity, decode: identity, name: 'x', format: 'utf8', [opt]: invalid }) } catch (err) { t.is(err.name, 'TypeError', 'is a TypeError') t.is(err.message, `The '${opt}' property must be a function`, 'correct message') } } } }) test('Encoding() throws on invalid format property', function (t) { t.plan(4 * 2) for (const invalid of ['binary', null, undefined, 123]) { try { // eslint-disable-next-line no-new new Encoding({ encode: identity, decode: identity, name: 'x', format: invalid }) } catch (err) { t.is(err.name, 'TypeError', 'is a TypeError') t.is(err.message, "The 'format' property must be one of 'buffer', 'view', 'utf8'", 'correct message') } } }) test('Encoding() throws on invalid name property', function (t) { t.plan(7 * 2) for (const invalid of ['', true, false, null, {}, () => {}, []]) { try { // eslint-disable-next-line no-new new Encoding({ encode: identity, decode: identity, format: 'utf8', name: invalid }) } catch (err) { t.is(err.name, 'TypeError', 'is a TypeError') t.is(err.message, "The 'name' property must be a string", 'correct message') } } }) test('encoding.createXTranscoder() throws on unsupported format', function (t) { t.plan(6) const encoding = new Encoding({ encode: identity, decode: identity, name: 'test', format: 'buffer' }) try { encoding.createViewTranscoder() } catch (err) { t.is(err.code, 'LEVEL_ENCODING_NOT_SUPPORTED') t.is(err.message, "Encoding 'test' cannot be transcoded to 'view'") } try { encoding.createBufferTranscoder() } catch (err) { t.is(err.code, 'LEVEL_ENCODING_NOT_SUPPORTED') t.is(err.message, "Encoding 'test' cannot be transcoded to 'buffer'") } try { encoding.createUTF8Transcoder() } catch (err) { t.is(err.code, 'LEVEL_ENCODING_NOT_SUPPORTED') t.is(err.message, "Encoding 'test' cannot be transcoded to 'utf8'") } }) test('can create utf8 transcoder', function (t) { t.plan(2) const encoding = new Encoding({ encode: identity, decode: identity, name: 'test', format: 'buffer', createUTF8Transcoder () { t.pass('called') return new Encoding({ encode: identity, decode: identity, name: 'test+utf8', format: 'utf8' }) } }) t.is(encoding.createUTF8Transcoder().name, 'test+utf8') }) const assert = require('assert'); const helpers = require('../src/helpers'); describe('helpers', function() { return it('isInteger', function() { assert(helpers.isInteger(10) === true); return assert(helpers.isInteger(10.0)); }); }); var searchData= [ ['x',['x',['../class_graphics_object_properties_widget.html#a157b51b0c23cb7c37931cee06eb225b9',1,'GraphicsObjectPropertiesWidget']]] ]; // learned from https://css-tricks.com/styling-based-on-scroll-position/ const debounce = (fn) => { let frame; return (...params) => { if (frame) { cancelAnimationFrame(frame); } frame = requestAnimationFrame(() => { fn(...params); }); } }; const storeScroll = () => { document.documentElement.dataset.scroll = window.scrollY; } document.addEventListener('scroll', debounce(storeScroll), { passive: true }); storeScroll(); import ReactDOM from 'react-dom'; import * as React from 'react'; // eslint-disable-next-line @typescript-eslint/no-unused-vars export const renderTemplate = (template, model, _component) => { template(model, model.container); }; export const hasTemplate = (name, props, _component) => { const value = props[name]; return !!value && typeof value !== 'string'; }; export const getWrapperTemplate = (TemplateProp) => { const isComponent = typeof TemplateProp === 'string' || !!(TemplateProp instanceof Element); return isComponent ? TemplateProp : (data) => { const container = data.container ? data.container : data.item; ReactDOM.render( /* eslint-disable react/jsx-props-no-spreading */ React.createElement(TemplateProp, Object.assign({}, data)), container); }; }; export const getTemplate = (TemplateProp, RenderProp, ComponentProp) => ((TemplateProp && (TemplateProp.defaultProps ? (props) => React.createElement(TemplateProp, Object.assign({}, props)) : TemplateProp)) || (RenderProp && ((props) => RenderProp(...('data' in props ? [props.data, props.index] : [props])))) || (ComponentProp && ((props) => React.createElement(ComponentProp, Object.assign({}, props))))); import MongoClient from 'mongodb'; const state = { client: null, db: null, }; function databaseConnect(callback) { if (state.client) return callback(); const { MONGO_DB_NAME, MONGO_DB_USER, MONGO_DB_PASSWORD } = process.env; let MONGO_URL = `mongodb+srv://${MONGO_DB_USER}:${_DB_PASSWORD}@/${MONGO_DB_NAME}?retryWrites=true&w=majority`; if (process.env.NODE_ENV !== 'production') { const { MONGO_LOCAL_HOST, MONGO_LOCAL_PORT } = process.env; MONGO_URL = `mongodb://${MONGO_LOCAL_HOST}:${MONGO_LOCAL_PORT}`; } console.log('Connect to database...'); MongoClient.connect(MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true }) .then((client) => { console.log('Connected successfully to server'); const db = client.db(MONGO_DB_NAME); state.client = client; state.db = db; callback(); }) .catch((err) => { const error = { message: 'Error on mongodb connection', details: { name: err.name, message: err.message, stack: err.stack }, }; callback(error); }); } function getDatabase() { return state.db; } export { databaseConnect, getDatabase }; /* eslint-disable max-nested-callbacks */ import { Record } from 'immutable' import expect from 'expect' import { Info } from '../Info' describe('models/Info.js', () => { describe('{ Info }', () => { it('should be a Record', () => { const instance = new Info({}) expect(instance).toBeA(Record) }) describe('#fields', () => { const fields = [ 'title', 'description', 'tos', 'contact', 'license', 'version' ] for (const field of fields) { it('should have a `' + field + '` field', () => { const key = field const value = 'test' const data = {} data[key] = value const instance = new Info(data) expect(instance.get(key)).toEqual(value) }) } }) }) }) const request = require("request") var main = function (port) { request({url: `http://localhost:${port}/about`, json: true}, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("[POSTMAN] success. your about page is live.") } else { console.log("[POSTMAN] failure. your about page is down.") console.log(error, response.statusCode) } }); } main(3000)/* Copyright 2018 0kims association. This file is part of snarkjs. snarkjs is a free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. snarkjs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with snarkjs. If not, see . */ const bigInt = require("./bigint.js"); const __P__ = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617"); const __MASK__ = bigInt("28948022309329048855892746252171976963317496166410141009864396001978282409983"); // 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF const calculateWitness = require("./calculateWitness.js"); module.exports = class Circuit { constructor(circuitDef) { this.nPubInputs = circuitDef.nPubInputs; this.nPrvInputs = circuitDef.nPrvInputs; this.nInputs = circuitDef.nInputs; this.nOutputs = circuitDef.nOutputs; this.nVars = circuitDef.nVars; this.nSignals = circuitDef.nSignals; this.nConstants = circuitDef.nConstants; this.nConstraints = circuitDef.constraints.length; this.signalName2Idx = circuitDef.signalName2Idx; this.components = circuitDef.components; this.componentName2Idx = circuitDef.componentName2Idx; this.signals = circuitDef.signals; this.constraints = circuitDef.constraints; this.templates = {}; for (let t in circuitDef.templates) { this.templates[t] = eval(" const __f= " +circuitDef.templates[t] + "\n__f"); } this.functions = {}; for (let f in circuitDef.functions) { this.functions[f] = { params: circuitDef.functions[f].params, func: eval(" const __f= " +circuitDef.functions[f].func + "\n__f;") }; } } calculateWitness(input, log) { return calculateWitness(this, input, log); } checkWitness(w) { const evalLC = (lc, w) => { let acc = bigInt(0); for (let k in lc) { acc= acc.add(bigInt(w[k]).mul(bigInt(lc[k]))).mod(__P__); } return acc; } const checkConstraint = (ct, w) => { const a=evalLC(ct[0],w); const b=evalLC(ct[1],w); const c=evalLC(ct[2],w); const res = (a.mul(b).sub(c)).affine(__P__); if (!res.isZero()) return false; return true; } for (let i=0; i { let S = ""; for (let k in lc) { let name = this.signals[k].names[0]; if (name == "one") name = ""; let v = bigInt(lc[k]); let vs; if (!v.lesserOrEquals(__P__.shr(bigInt(1)))) { v = __P__.sub(v); vs = "-"+v.toString(); } else { if (S!="") { vs = "+"+v.toString(); } else { vs = ""; } if (vs!="1") { vs = vs + v.toString();; } } S= S + " " + vs + name; } return S; }; const S = `[ ${lc2str(c[0])} ] * [ ${lc2str(c[1])} ] - [ ${lc2str(c[2])} ] = 0`; console.log(S); } printConstraints() { for (let i=0; i=this.nOutputs) throw new Error("Accessing an invalid output: "+i); return i+1; } // returns the index of the i'th input inputIdx(i) { if (i>=this.nInputs) throw new Error("Accessing an invalid input: "+i); return this.nOutputs + 1 + i; } // returns the index of the i'th public input pubInputIdx(i) { if (i>=this.nPubInputs) throw new Error("Accessing an invalid pubInput: "+i); return this.inputIdx(i); } // returns the index of the i'th private input prvInputIdx(i) { if (i>=this.nPrvInputs) throw new Error("Accessing an invalid prvInput: "+i); return this.inputIdx(this.nPubInputs + i); } // returns the index of the i'th variable varIdx(i) { if (i>=this.nVars) throw new Error("Accessing an invalid variable: "+i); return i; } // returns the index of the i'th constant constantIdx(i) { if (i>=this.nConstants) throw new Error("Accessing an invalid constant: "+i); return this.nVars + i; } // returns the index of the i'th signal signalIdx(i) { if (i>=this.nSignls) throw new Error("Accessing an invalid signal: "+i); return i; } signalNames(i) { return this.signals[ this.getSignalIdx(i) ].names.join(", "); } a(constraint, signalIdx) { return bigInt(this.constraints[constraint][0][signalIdx] || 0 ); } b(constraint, signalIdx) { return bigInt(this.constraints[constraint][1][signalIdx] || 0); } c(constraint, signalIdx) { return bigInt(this.constraints[constraint][2][signalIdx] || 0); } }; import Head from 'next/head' import styles from '../styles/Home.module.css' import 'twin.macro' export default function Home() { return ( ) } 1-10 import { START_LOADING, STOP_LOADING, COMPLETE_ORDERS_SUCCESS, COMPLETE_ORDERS_ERROR, } from '../actions/actionTypes'; const initialState = { acceptorders: null, status: '', error: '', } export default (state = initialState, action) => { switch (action.type) { case START_LOADING: { state = { completeorders: null, status: 'LOADING', error: '', } break; } case STOP_LOADING: { state = { completeorders: null, status: 'NOTLOADING', error: '' } break; } case COMPLETE_ORDERS_SUCCESS: { state = { completeorders: action.payload, status: 'SUCCESS', error: '', } break; } case COMPLETE_ORDERS_ERROR: { state = { completeorders: null, status: 'ERROR', error: action.payload } break; } default: { state } } return state; } const cron = require('cron'); const { main } = require('./'); const influx = require('./influx'); const config = require('../config'); const lightHouse = require('./light-house'); const saveReport = require('./utils/save-report'); jest.mock('./influx', () => { return { init: jest.fn(), saveData: jest.fn(() => Promise.resolve()) }; }); jest.mock('../config', () => { return { cron: '*/2 * * * *', urls: [ { url: 'https://www.test.com', plugins: [ { name: 'lighthouse', report: true } ] } ] }; }); jest.mock('./light-house', () => { return { getData: jest.fn(() => Promise.resolve()) }; }); jest.mock('cron', () => { return { CronJob: jest.fn() }; }); jest.mock('./utils/save-report', () => jest.fn()); describe('main', () => { beforeEach(() => { influx.init.mockClear(); cron.CronJob.mockClear(); lightHouse.getData.mockClear(); }); it('calls to bootstrap the influx setup', async () => { await main(); expect(influx.init).toBeCalled(); }); it('creates a cron job when cron is enabled', async () => { await main(); const cronJobArgs = cron.CronJob.mock.calls[0]; const cronValue = cronJobArgs[0]; const timeZone = cronJobArgs[4]; const startCronOnLoad = cronJobArgs[6]; expect(cronValue).toEqual('*/2 * * * *'); expect(timeZone).toEqual('Europe/London'); expect(startCronOnLoad).toEqual(true); }); it.only('create a lighthouse report when report is enabled', async done => { await main(); const cronJobArgs = cron.CronJob.mock.calls[0]; const callback = cronJobArgs[1]; // trigger cron callback(); //Tidy this up? setTimeout(() => { expect(saveReport).toHaveBeenCalled(); done(); }, 500); }); }); module.exports = function makeImportant(string, number = string.length) { return `${string}${'!'.repeat(number)}` }0 var searchData= [ ['handle',['handle',['../structtimer.html#ae9924d77c8e5c2ed155927aed3d3fd4a',1,'timer']]], ['handler',['handler',['../structirq__data.html#a7f06938a3bc7ef19b448f13b7eb6d1cc',1,'irq_data']]] ]; const { Thought, User } = require("../models"); const thought = { async getAll(req, res) { try { const thoughts = await Thought.find(); res.status(200).json(thoughts); } catch { res.status(500).send("getAll failed"); } }, async createOne(req, res) { try { if (!req.body?.thoughtText || !req.body?.username) { res .status(404) .json({ message: "Missing required thoughtText or username." }); return; } const user = await User.findOne({ username: req.body.username }); if (!user) { res.status(404).json({ message: "No user found with name: " + req.body.username, }); return; } const thought = await Thought.create(req.body); const updUser = await User.findOneAndUpdate( { _id: user._id }, { $push: { thoughts: thought } }, { new: true } ); return !updUser ? res.status(404).json({ message: "Error writing thought to user" }) : res.json(thought); } catch (err) { res.status(500).send(err); } }, async getOne(req, res) { try { const thought = await Thought.findOne({ _id: req.params.thoughtId, }).select("-__v"); return !thought ? res.status(404).json({ message: "No user with that ID" }) : res.json(thought); } catch (err) { res.status(500).json(err); } }, async updateOne(req, res) { // try { if (!req.body?.thoughtText && !req.body?.username) { res .status(404) .json({ message: "Must include either username or thoughtText." }); return; } const thought = await Thought.findOne({ _id: req.params.thoughtId }); if (!thought) { res.status(404).json({ message: "No thought found with ID: " + req.params.thoughtId, }); return; } if (!req.body?.username || req.body.username == thought.username) { if (!req.body.thoughtText) { console.log("no username to update"); return res .status(200) .json({ message: "No save required and username was not changed" }); } } else { // new username, remove from old user and add to new one. let oldUser = await User.findOne({ username: thought.username }); if (!oldUser) return res .status(404) .json({ message: "Database error: old user does not exist" }); let newUser = await User.findOne({ username: req.body.username }); if (!newUser) return res .status(404) .json({ message: "Database error: old user does not exist" }); // first remove from old username const oldThoughtList = oldUser.thoughts.filter( (userThought) => userThought._id != req.params.thoughtId ); oldUser.thoughts = oldThoughtList; await oldUser.save().catch((err) => { throw err; }); // Now add to new username newUser.thoughts.push(req.params.thoughtId); await newUser.save().catch((err) => { throw err; }); thought.username = req.body.username; } if (req.body?.thoughtText) { thought.thoughtText = req.body.thoughtText; } thought .save() .then((newThought) => res.status(200).json(newThought)) .catch((err) => res.status(400).json({ message: err })); // } catch (err) { // res.status(500).send(err); // } }, async deleteOne(req, res) { try { const thought = await Thought.findOne({ _id: req.params.thoughtId }); if (!thought) return res.status(404).json({ message: "No thought with that ID" }); const user = await User.findOne({ username: thought.username }); let thoughtList = user.thoughts.filter( (thought) => thought != req.params.thoughtId ); if (thoughtList.length != user.thoughts.length) { user.thoughts = thoughtList; await user.save(); } Thought.deleteOne({ _id: req.params.thoughtId }) .then(() => res.json({ message: "User and thoughts deleted!" })) .catch((err) => res.status(500).json({ message: err })); } catch (err) { res.status(500).json(err); } }, async createReaction(req, res) { try { if (!req.body?.username || !req.body?.reactionBody) return res .status(400) .json({ message: "Both username and reactionBody are required" }); const thought = await Thought.findOne({ _id: req.params.thoughtId }); if (!thought) return res.status(404).json({ message: "No thoughts matched thoughtId: " + req.params.thoughtId, }); thought.reactions.push({ username: req.body.username, reactionBody: req.body.reactionBody, }); thought .save() .then((newThought) => res.status(200).json(newThought)) .catch((err) => res.status(500).json({ message: err })); } catch (err) { res.status(500).json({ message: err }); } }, async removeReaction(req, res) { try { const thought = await Thought.findOne({ _id: req.params.thoughtId }); if (!thought) return res.status(404).json({ message: "No thoughts matched thoughtId: " + req.params.thoughtId, }); let reactionList = thought.reactions.filter( (reaction) => reaction.reactionId != req.params.reactionId ); if (reactionList.length != thought.reactions.length) { thought.reactions = reactionList; thought.save().then((newThought) => res.status(200).json(newThought)); } else return res.status(404).json({ message: "No reaction to delete" }); } catch (err) { res.status(500).json({ message: err }); } }, }; module.exports = thought; src/resources/1_0_2/profiles/medicationstatement/query.js // Schemas const MedicationStatementSchema = require('../../schemas/medicationstatement.schema'); const BundleSchema = require('../../schemas/bundle.schema'); // Arguments const MedicationStatementArgs = require('../../parameters/medicationstatement.parameters'); const CommonArgs = require('../../parameters/common.parameters'); // Resolvers const { medicationstatementResolver, medicationstatementListResolver, medicationstatementInstanceResolver } = require('./resolver'); // Scope Utilities const { scopeInvariant } = require('../../../../utils/scope.utils'); let scopeOptions = { name: 'MedicationStatement', action: 'read', version: '1_0_2' }; /** * @name exports.MedicationStatementQuery * @summary MedicationStatement Query. */ module.exports.MedicationStatementQuery = { args: Object.assign({}, CommonArgs, MedicationStatementArgs), description: 'Query for a single MedicationStatement', resolve: scopeInvariant(scopeOptions, medicationstatementResolver), type: MedicationStatementSchema }; /** * @name exports.MedicationStatementListQuery * @summary MedicationStatementList Query. */ module.exports.MedicationStatementListQuery = { args: Object.assign({}, CommonArgs, MedicationStatementArgs), description: 'Query for multiple MedicationStatements', resolve: scopeInvariant(scopeOptions, medicationstatementListResolver), type: BundleSchema }; /** * @name exports.MedicationStatementInstanceQuery * @summary MedicationStatementInstance Query. */ module.exports.MedicationStatementInstanceQuery = { description: 'Get information about a single MedicationStatement', resolve: scopeInvariant(scopeOptions, medicationstatementInstanceResolver), type: MedicationStatementSchema }; 0 exports.xp6 = (id, XPTN, corohelp, tampilTanggal, tampilWaktu, instagram, nomer, aktif, groupwa, youtube) => { return ` ┏ ❣ *HappyMenu* ❣ ┃ ┠❥ *.cersex1* ┠❥ *.cersex2* ┠❥ *.indohot* ┠❥ *.pornhub* ┠❥ *.quotemaker* ┠❥ *.texthundet* ┠❥ *.createtext* ┠❥ *.randomcry* ┠❥ *.ping* ┠❥ *.neolast* ┠❥ *.setname* ┠❥ *.setdesc* ┠❥ *.creator* ┠❥ *.opengc* ┠❥ *.closegc* ┠❥ *.text3d* ┠❥ *.renungan* ┠❥ *.joox* ┠❥ *.gltext* ┠❥ *.gaming2* ┠❥ *.blackpink* ┠❥ *.mostviewfilm* ┠❥ */igstalk* ┠❥ *.speed* ┠❥ *.tagme* ╿ ╰╼❥ Jangan spam! jeda command 5 detik.` } src/Pickles/Pickles.BaseDhtmlFiles/js/picklesOverview.js1-10 var PicklesOverview = function(summary) { Chart.defaults.global.responsive = true; return { getTotalsData: getTotalsData, createOverallTotalsChart: createOverallTotalsChart, createByTagChart: createByTagChart, createByRootFolderChart: createByRootFolderChart, createNotTestedByRootFolderChart: createNotTestedByRootFolderChart }; ///// function defaultColors() { return { passing: { color: "rgba(70,191,189,1)", stroke: "rgba(70,191,189,1)", highlight: "rgba(90,211,209,1)", highlightstroke: "rgba(90,211,209,1)" }, failing: { color: "rgba(247,70,74,1)", stroke: "rgba(247,70,74,1)", highlight: "rgba(255,90,94,1)", highlightstroke: "rgba(255,90,94,1)" }, inconclusive: { color: "rgba(253,180,92,1)", stroke: "rgba(253,180,92,1)", highlight: "rgba(255,200,112,1)", highlightstroke: "rgba(255,200,112,1)" } }; } function getTotalsData() { var colors = defaultColors(); return [ { value: summary.Scenarios.Inconclusive, color: colors.inconclusive.color, highlight: colors.inconclusive.highlight, label: "Inconclusive Scenarios" }, { value: summary.Scenarios.Failing, color: colors.failing.color, highlight: colors.failing.highlight, label: "Failing Scenarios" }, { value: summary.Scenarios.Passing, color: colors.passing.color, highlight: colors.passing.highlight, label: "Passing Scenarios" } ]; } function createOverallTotalsChart(context) { var chart = new Chart(context); var data = getTotalsData(); var options = { percentageInnerCutout: 40 }; chart.Doughnut(data, options); } function getChartData(labels, passingData, failingData, inconclusiveData) { var colors = defaultColors(); return { labels: labels, datasets: [ { fillColor: colors.inconclusive.color, strokeColor: colors.inconclusive.stroke, highlightFill: colors.inconclusive.highlight, highlightStroke: colors.inconclusive.highlightstroke, label: "Inconclusive Scenarios", data: inconclusiveData }, { fillColor: colors.failing.color, strokeColor: colors.failing.stroke, highlightFill: colors.failing.highlight, highlightStroke: colors.failing.highlightstroke, label: "Failing Scenarios", data: failingData }, { fillColor: colors.passing.color, strokeColor: colors.passing.stroke, highlightFill: colors.passing.highlight, highlightStroke: colors.passing.highlightstroke, label: "Passing Scenarios", data: passingData } ] }; } function createByTagChart(context) { var chart = new Chart(context); var labels = []; var passingData = []; var failingData = []; var inconclusiveData = []; summary.Tags.sort(function(a, b) { return b.Total - a.Total; }); summary.Tags.slice(0, 20).forEach(function(tag) { labels.push(tag.Tag); passingData.push(tag.Passing); failingData.push(tag.Failing); inconclusiveData.push(tag.Inconclusive); }); var data = getChartData(labels, passingData, failingData, inconclusiveData); var options = { }; chart.StackedBar(data, options); } function internalCreateByRootFolderChart(context, folderCollection) { var chart = new Chart(context); var labels = []; var passingData = []; var failingData = []; var inconclusiveData = []; folderCollection.sort(function(a, b) { return a.Folder.localeCompare(b.Folder); }); folderCollection.forEach(function(folder) { labels.push(folder.Folder); passingData.push(folder.Passing); failingData.push(folder.Failing); inconclusiveData.push(folder.Inconclusive); }); var data = getChartData(labels, passingData, failingData, inconclusiveData); var options = { }; chart.StackedBar(data, options); } function createByRootFolderChart(context) { internalCreateByRootFolderChart(context, summary.Folders); } function createNotTestedByRootFolderChart(context) { internalCreateByRootFolderChart(context, summary.NotTestedFolders); } }; 'use strict'; /* global hivemind CREEP_LIFE_TIME CREEP_SPAWN_TIME MAX_CREEP_SIZE MOVE CARRY */ const SpawnRole = require('./spawn-role'); module.exports = class PowerHaulerSpawnRole extends SpawnRole { /** * Adds gift spawn options for the given room. * * @param {Room} room * The room to add spawn options for. * @param {Object[]} options * A list of spawn options to add to. */ getSpawnOptions(room, options) { if (!hivemind.settings.get('enablePowerMining')) return; if (!Memory.strategy || !Memory.strategy.power || !Memory.strategy.power.rooms) return; _.each(Memory.strategy.power.rooms, (info, roomName) => { if (!info.isActive) return; if (!info.spawnRooms[room.name]) return; // @todo Determine supposed time until we crack open the power bank. // Then we can stop spawning attackers and spawn haulers instead. const travelTime = 50 * info.spawnRooms[room.name].distance; const timeToKill = 0.8 * info.hits / info.dps; if (timeToKill > (CREEP_SPAWN_TIME * MAX_CREEP_SIZE) + Math.max(CREEP_LIFE_TIME / 3, travelTime)) return; // Time to spawn haulers! const powerHaulers = _.filter(Game.creepsByRole['hauler.power'] || {}, creep => creep.memory.targetRoom === roomName); const totalCapacity = _.reduce(powerHaulers, (total, creep) => total + creep.carryCapacity, 0); if (totalCapacity < info.amount * 1.2) { options.push({ priority: hivemind.settings.get('powerMineCreepPriority'), weight: 0.5, targetRoom: roomName, }); } }); } /** * Gets the body of a creep to be spawned. * * @param {Room} room * The room to add spawn options for. * @param {Object} option * The spawn option for which to generate the body. * * @return {string[]} * A list of body parts the new creep should consist of. */ getCreepBody(room) { const moveRatio = hivemind.settings.get('powerHaulerMoveRatio'); return this.generateCreepBodyFromWeights( {[MOVE]: moveRatio, [CARRY]: 1 - moveRatio}, Math.max(room.energyCapacityAvailable * 0.9, room.energyAvailable) ); } /** * Gets memory for a new creep. * * @param {Room} room * The room to add spawn options for. * @param {Object} option * The spawn option for which to generate the body. * * @return {Object} * The boost compound to use keyed by body part type. */ getCreepMemory(room, option) { return { sourceRoom: room.name, targetRoom: option.targetRoom, }; } }; 0 import { combineReducers } from 'redux'; import userReducer from './userReducer'; import contactReducer from './contactReducer'; import actReducer from './actReducer'; export default combineReducers({ user: userReducer, contact: contactReducer, act: actReducer }); import './polyfills'; import Promise from 'promise'; import cfg from './config'; import game from './game'; import log from './log'; import media from './media'; import routes from './routes'; import rtc from './rtc'; import scene from './scene'; import user from './user'; import views from './views'; let endgame = { config: cfg, main() { // Initialize Firebase firebase.initializeApp(cfg.firebaseConfig); views.init(); scene.init(routes.isDebugMode(), this.getQuality()); scene.loadGameAssets().then(scene.setupBoard.bind(scene)).done(); scene.beginRender(); // In case of debug mode, we short-circuit the connection logic and go // straight into a local game. if (routes.isDebugMode()) { log('init debug mode'); this.beginDebugGame(); return; } user.init().then(() => { let gameId = routes.parseGameId(); if (gameId) { log('gameId found - connecting to host'); this.isHost = false; routes.resetPath(); this.connectToGame(gameId); } else { log('no gameId - acting as host'); this.isHost = true; this.setupGame(); } }); }, setupGame() { this.side = 'white'; rtc.init(this.onConnClose.bind(this)) .then(game.create.bind(game)) .then(gameId => { return views.showWaitScreen( gameId, scene.quality, this.toggleQuality.bind(this)); }) .then(rtc.listen.bind(rtc)) .then(this.setupMedia.bind(this)) .then(this.performMediaCalls.bind(this)) .then(this.displayRemoteMedia.bind(this)) .then(this.beginGame.bind(this)) // handleError isn't relevant here. .done(); }, connectToGame(gameId) { this.side = 'black'; rtc.init(this.onConnClose.bind(this)) .then(game.join.bind(game, gameId)) .then(rtc.connect.bind(rtc)) .then(this.setupMedia.bind(this)) .then(this.performMediaCalls.bind(this)) .then(this.displayRemoteMedia.bind(this)) .then(this.beginGame.bind(this)) .catch(this.handleError.bind(this)) .done(); }, handleError(error) { if (!Array.isArray(error)) { throw error; } const [type, data] = error; if (type === 'join') { views.showMessage( 'Game Not Found', `Alas, game room ${data} doesn't seem to exist.

    Perhaps check the spelling? Or create a new game room.`, 'danger'); } else { throw Error(`unknown error type: ${type}`); } }, setupMedia() { log('setting up the media'); // Wait for notice from remote regarding media. We need to set up this // listener first because it needs to be ready before we attempt to set // up the local media streams. let remoteMediaPromise = new Promise((resolve, unused_reject) => { log('attaching remote media info listener'); rtc.addDataListener((data, unused_conn) => { if (data.event === 'mediarequestcomplete') { this.remoteHasVideo = data.hasVideo; this.remoteHasAudio = data.hasAudio; this.remoteHasMedia = data.hasMedia; log(`remote media request complete (hasMedia: ${ this.remoteHasMedia}, ` + `hasVideo: ${this.remoteHasVideo}, hasAudio: ${ this.remoteHasAudio})`); resolve(); } else if (data.event === 'mediareadyping') { // Media pings are expected. Return 'true' to avoid // auto-listener removal. return true; } else { log('ERROR: unknown event type', data.event); } }, /* once */ true); }); return views .showMediaScreen() // First we make sure that the media listeners are attached by // synchronizing the peers via ping. .then(() => this.synchronizePing('mediareadyping')) // Then we wait for both the local and remote media to be resolved. .then(() => Promise.all([ // Block on the attachment of remote media listener. remoteMediaPromise, // Now that we're synced, request local media. media.init().then( () => { this.localHasVideo = media.hasLocalVideo(); this.localHasAudio = media.hasLocalAudio(); this.localHasMedia = this.localHasVideo || this.localHasAudio; log(`local media granted (hasVideo: ${ this.localHasVideo}, ` + `hasAudio: ${this.localHasAudio})`); if (this.localHasVideo) { media.playLocalStream(); } rtc.sendData({ event: 'mediarequestcomplete', hasMedia: this.localHasMedia, hasVideo: this.localHasVideo, hasAudio: this.localHasAudio }); }, () => { this.localHasMedia = false; this.localHasVideo = false; this.localHasAudio = false; log('local media denied or unavailable'); rtc.sendData({ event: 'mediarequestcomplete', hasMedia: false, hasVideo: false, hasAudio: false }); }) ])); }, performMediaCalls() { log('performing remote media calls'); if (!this.localHasMedia && !this.remoteHasMedia) { // No media to exchange log('no media to exchange'); return Promise.resolve(); } // Because caller must provide mediaStream, we need to figure out if // we're the caller or not. If the host has a (video) mediaStream, it // will always be the caller; otherwise, the friend will be. // // In addition, add a preference for the peer that has video, as it // seems to only work reliably from the initial call. // TODO: Figure out why this is the case. let videoPeerExists = this.localHasVideo || this.remoteHasVideo; let isPreferredVideoPeer = (this.isHost && this.localHasVideo) || (!this.isHost && !this.remoteHasVideo && this.localHasVideo); let isPreferredMediaPeer = (this.isHost && this.localHasMedia) || (!this.isHost && !this.remoteHasMedia && this.localHasMedia); let isCaller = videoPeerExists ? isPreferredVideoPeer : isPreferredMediaPeer; let localMediaStream = this.localHasMedia && media.localMediaStream; log(`initial caller determined - isCaller: ${isCaller}`); if (isCaller) { return this.synchronizePing('mediacallping') .then(() => rtc.performMediaCall(isCaller, localMediaStream)); } else { // Setup listener beforehand. let mediaCallPromise = rtc.performMediaCall(isCaller, localMediaStream); return this.synchronizePing('mediacallping') .then(() => mediaCallPromise); } }, displayRemoteMedia(call) { log('displaying remote media'); return new Promise((resolve, unused_reject) => { let addStream = (remoteMediaStream) => { // Configure media, even if it's audio-only. let video = media.configureRemoteStream(remoteMediaStream); scene.addFriendScreen( this.side, this.remoteHasVideo ? video : null); log('media display complete'); resolve(); }; if (this.remoteHasMedia) { // If the remote stream is already attached, grab it. if (call.remoteStream) { log('remote media exists and is available'); addStream(call.remoteStream); } else { log('remote media exists; setting up stream handler'); call.on('stream', (stream) => addStream(stream)); } } else { log('no media; add empty friend screen'); scene.addFriendScreen(this.side); resolve(); } }); }, synchronizePing(pingName) { return new Promise((resolve, unused_reject) => { // Ping every half-second. let pingInterval = setInterval(() => { rtc.sendData({event: pingName}); }, 500); // Listen for ping. log(`attaching ${pingName} listener; beginning ping`); rtc.addDataListener((data, unused_conn) => { if (data.event === pingName) { log(`${pingName} ping received; detaching`); clearInterval(pingInterval); resolve(); // Send one last ping, to make sure that both peers get // resolved. rtc.sendData({event: pingName}); } else { log('ERROR: unknown event type', data.event); } }, /* once */ true); }); }, updateCapturedCount(move) { const mapping = { 'p': 'pawn', 'n': 'knight', 'b': 'bishop', 'r': 'rook', 'q': 'queen' }; // Check for standard capture (c) and en-passant (e). if (move.captured) { // The opposite color was captured. let color = move.color === 'w' ? 'black' : 'white'; let piece = mapping[move.captured]; this.capturedPieces[color][piece] += 1; } }, beginGame() { log('commencing game'); // Begin chess game this.chess = new Chess(); this.capturedPieces = { 'white': {'pawn': 0, 'knight': 0, 'bishop': 0, 'rook': 0, 'queen': 0}, 'black': {'pawn': 0, 'knight': 0, 'bishop': 0, 'rook': 0, 'queen': 0} }; // Pass the object directly so that the view can bind to it. views .showStatusScreen( this.capturedPieces, scene.quality, this.toggleQuality.bind(this)) .then( () => new Promise((resolve, unused_reject) => { this.isMyTurn = this.side === 'white'; scene.movesEnabled = this.isMyTurn; scene.addTileControls( /* legalCallback */ pos => { return this.chess.moves( {square: pos, verbose: true}); }, /* moveCallback */ (from, to, opt_promotion) => { log(`performing move - from: ${from}, to: ${ to}, promo: ${opt_promotion}`); let moveArgs = { from: from, to: to, promotion: opt_promotion }; let move = this.chess.move(moveArgs); if (move) { if (!routes.isDebugMode()) { // Send move to remote rtc.sendData( {event: 'chessmove', move: move}); } afterMove(move); } else { log('ERROR: illegal move attempted locally - bug?'); log(moveArgs); } }, /* onPromotion */ () => {return views.showPromotionScreen(this.side)}); const afterMove = move => { this.isMyTurn = !this.isMyTurn; scene.movesEnabled = this.isMyTurn || routes.isDebugMode(); scene.activeSide = scene.activeSide === 'white' ? 'black' : 'white'; if (routes.isDebugMode()) { this.side = this.side === 'white' ? 'black' : 'white'; } this.updateCapturedCount(move); scene.performMove(move, this.chess.in_check()); this.checkGameOver(); }; if (!routes.isDebugMode()) { rtc.addDataListener((data, unused_conn) => { if (data.event === 'chessmove') { if (!this.isMyTurn) { // Apply remote move. let move = this.chess.move(data.move); if (move) { afterMove(move); } else { log('ERROR: opponent attempted invalid move', data); } } else { log('ERROR: opponent attempted to move on my turn'); } } else { log('ERROR: unknown event type', data.event); } }); } })) .done(); }, beginDebugGame() { let viewSide = routes.getDebugSide() || 'white'; scene.setPlayCameraPos(viewSide); // Override side, since we want to be able to play both sides even when // we're black. this.side = scene.side = 'white'; this.beginGame(); }, getQuality() { let forcedQuality = routes.getQuality(); if (forcedQuality) { log(`forced quality: ${forcedQuality}`); this.setStoredQuality(forcedQuality); return forcedQuality; } let storedQuality = this.getStoredQuality(); if (storedQuality) { return storedQuality; } // Default to 'high'. return 'high'; }, getStoredQuality() { if (window.localStorageAvailable()) { let quality = localStorage.getItem(cfg.qualityKey); if (quality) { log(`retrieved stored quality: ${quality}`); } return quality; } return null; }, setStoredQuality(quality) { if (window.localStorageAvailable()) { log(`storing quality: ${quality}`); localStorage.setItem(cfg.qualityKey, quality); } }, toggleQuality() { let newQuality = scene.quality === 'high' ? 'low' : 'high'; this.setStoredQuality(newQuality); scene.setQuality(newQuality); }, checkGameOver() { if (this.chess.game_over()) { scene.gameOver = true; // Game over! Determine cause, and display message. let reason = ''; if (this.chess.in_checkmate()) { let winner = this.chess.turn() === 'w' ? 'Black' : 'White'; reason = `Checkmate - ${winner} Wins`; } else if (this.chess.in_stalemate()) { reason = `Stalemate`; } else if (this.chess.insufficient_material()) { reason = `Draw - Insufficient Material`; } else if (this.chess.in_draw()) { // We already checked for insufficient material, so the only // remaining possibility is 50-move rule. reason = `Draw - 50-Move Rule`; } if (!reason) { log('ERROR: no game-end reason determined?'); } views.showGameEndScreen(reason); } }, onConnClose(explicit) { let msg = explicit ? 'The opponent has left the game.' : 'The opponent may have left the game, or the network is lagging.'; views.showAlert(msg); setTimeout(() => { views.showAlert( 'To create a new game room, refresh the page.', '', 'info', 15000); }, 8000); } }; window.endgame = endgame; document.addEventListener('DOMContentLoaded', endgame.main.bind(endgame)); "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.chooseZoomOrResolution = chooseZoomOrResolution; exports.createMapView = createMapView; var _ol = require("ol"); var _defaults = require("./defaults"); var _defaults2 = _interopRequireDefault(_defaults); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Sets the startResolution or the startZoomlevel, depending on the configuration. * Where the resolution is preferred. * The value to use is set and the other is undefined. * @param {object} config - configuration object * @param {object} [mergedConfig=defaults] - configuration from object merged with default configuration * @returns {object} object that contains startZoomLevel and startResolution */ function chooseZoomOrResolution() { var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var mergedConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _defaults2.default; var zoomResolution = { startZoomLevel: undefined, startResolution: undefined }; if (config.hasOwnProperty("startZoomLevel") && !config.hasOwnProperty("startResolution")) { zoomResolution.startZoomLevel = mergedConfig.startZoomLevel; } else { zoomResolution.startResolution = mergedConfig.startResolution; } return zoomResolution; } /** * Creates a View from config. * @param {object} config - configuration object * @param {string} [config.epsg="EPSG:25832"] - CRS to use * @param {number[]} [config.extent=[510000.0, 5850000.0, 625000.4, 6000000.0]] - extent to use * @param {Array.} [config.options=[{resolution: 66.14579761460263, scale: 250000, zoomLevel: 0},{resolution: 26.458319045841044, scale: 100000, zoomLevel: 1},{resolution: 15.874991427504629, scale: 60000, zoomLevel: 2},{resolution: 10.583327618336419, scale: 40000, zoomLevel: 3},{resolution: 5.2916638091682096, scale: 20000, zoomLevel: 4},{resolution: 2.6458319045841048, scale: 10000, zoomLevel: 5},{resolution: 1.3229159522920524, scale: 5000, zoomLevel: 6},{resolution: 0.6614579761460262, scale: 2500, zoomLevel: 7},{resolution: 0.2645831904584105, scale: 1000, zoomLevel: 8},{resolution: 0.13229159522920521, scale: 500, zoomLevel: 9}]] - each sub-array has two values: projection name, and projection description * @param {number} [config.startResolution=15.874991427504629] - initial resolution * @param {number[]} [config.startCenter=[565874, 5934140]] - initial position * @returns {ol.View} view with start values from config */ function createMapView(config) { var mergedConfig = Object.assign({}, _defaults2.default, config), zoomResolution = chooseZoomOrResolution(config, mergedConfig); return new _ol.View({ projection: mergedConfig.epsg, center: mergedConfig.startCenter, extent: mergedConfig.extent, zoom: zoomResolution.startZoomLevel, resolution: zoomResolution.startResolution, resolutions: mergedConfig.options.map(function (entry) { return entry.resolution; }), constrainResolution: true, constrainOnlyCenter: true }); }var properties = require('../../../lib/rules/util').properties; module.exports = function(req, res) { res.json({ ec: 0, enableCapture: properties.isEnableCapture(), enableHttp2: properties.isEnableHttp2() }); }; //Javascript for Star Wars RPG Game. //UM Coding Boot Camp. 2018. . function Character ( name, health, aPower, caPower, pic, team ) { this.name = name; this.healthPoints = health; this.baseAttackPower = aPower; this.attackPower = aPower; this.counterAttackPower = caPower; this.picturePath = pic; this.team = team; this.increaseAttackPower = function () { this.attackPower += this.baseAttackPower; }; this.attack = function ( character ) { //code for attack, character will be an object of prototype Character this.increaseAttackPower(); }; this.counterAttack = function ( character ) { //code for counter attack, character will be an object of prototype Character }; }// end of Character var characters = [ new Character( '', 120, 6, 4, 'assets/images/obi-wan.png', 'jedi'), new Character( '', 100, 10, 8, 'assets/images/luke-skywalker.png', 'jedi'), new Character( '', 150, 15, 10, 'assets/images/darth-sidious.png', 'sith'), new Character( '', 180, 12, 6, 'assets/images/darth-maul.png', 'sith') ]; //array of characters function showInitCards() { for (var i = 0; i < characters.length; i++ ) { var col = $('

    ').addClass( 'col-xs-6 col-sm-4 col-md-3' ); switch (characters[i].team) { case 'jedi': var card = $('
    ').addClass( 'card bg-success text-white text-center' ); col.append( card ); break; case 'sith': var card = $('
    ').addClass( 'card bg-danger text-white text-center' ); col.append( card ); break; default: var card = $('
    ').addClass( 'card bg-warning text-white text-center' ); col.append( card ); } card.attr('value', i); var cardBody = $('
    ').addClass( 'card-body' ); card.append( cardBody ); var cName = $('

    ').addClass( 'card-text' ).html( characters[i].name ); cardBody.append( cName ); //var cPicture = $('').addClass( 'card-image' ).attr( 'src', characters[i].picturePath ); var cPicture = $('').addClass( 'card-image' ).attr( { src: characters[i].picturePath, alt: characters[i].name, width: "200px", height: "100px" } ); cardBody.append( cPicture ); var attackPower = $('

    ').addClass( 'card-text' ).html( characters[i].healthPoints ); cardBody.append( attackPower ); $('.pick-character').append( col ); console.log( characters[i].name ); } //$('.pick-character').append( $('

    ').html('Your Character').addClass('card-text') ); $('.card').click( cardClick( $('.card') ) ); } function moveCard( card, destination ) { $( destination ).append( card ); } function cardClick( card ) { return function(){ console.log( 'Card clicked: ' + card.val() ); } } var gameover = false; var wins = 0; var losses = 0; $(document).ready( function() { //Show initial cards of characters showInitCards(); } ); module.exports = { host: "localhost", port: 3118, protocol: "http", url: "http://localhost:8085", auth: { apiKeys: [ { id: "", key: "" } ] }, lightning: { backend: "lnd", config: { hostname: "localhost:8005", cert: "/home/user/.lnd.sima/tls.cert", macaroon: "/home/user/.lnd.sima/data/chain/bitcoin/regtest/admin.macaroon" } }, store: { backend: "knex", config: { client: "mysql", connection: { host: "localhost", user: "root", password: "password", database: "coinos" } } } }; var http = require('http'); var fs = require('fs'); var path = require('path'); http.createServer(function (request, response) { console.log('request starting...'); var filePath = '.' + request.url; if (filePath == './') filePath = './index.html'; var extname = path.extname(filePath); var contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpg'; break; case '.wav': contentType = 'audio/wav'; break; } fs.readFile(filePath, function(error, content) { if (error) { if(error.code == 'ENOENT'){ fs.readFile('./404.html', function(error, content) { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); }); } else { response.writeHead(500); response.end('Sorry, check with the site admin for error: '+error.code+' ..\n'); response.end(); } } else { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); } }); }).listen(8125); console.log('Server running at http://127.0.0.1:8125/'); 'use strict'; var fs = require('fs'); var RequestSender = require('./requestSender').RequestSender; var requestSender = new RequestSender(); /** * An integration test that uploads 100 plugin files to a running YAKjs. */ (function uploadPluginLoadTest() { var pluginCode = fs.readFileSync('broadcast.plugin.js', 'utf-8'); var COUNT = 100; var successCount = 0; var requests = []; for (var i=0; i < COUNT; i++) { var filename = 'broadcast' + i + '.plugin.js'; var request = createFileUploadRequest(filename, pluginCode); requests.push(requestSender.sendRequest(request).then(function() { successCount++; }).catch(function (error) { console.warn(error) })); } Promise.all(requests).then(function() { if (successCount !== COUNT) { console.error('uploadPluginLoadTest failed. Failed requests: ' + (COUNT - successCount)); process.exit(-1); } else { console.log('uploadPluginLoadTest succeeded.') } }) }()); /** * @param {string} filename * @param {string} content * @returns {{type: string, id: string, filename: *, content: *, enableInstanceRestart: boolean}} */ function createFileUploadRequest(filename, content) { return { type: 'request.uploadFileRequest', id: 'requestId', filename: filename, content: content, enableInstanceRestart: true } }let curseur = 0; let bouton_arriere = document.querySelector('.bouton_arriere'); let bouton_avant = document.querySelector('.bouton_avant'); bouton_arriere.addEventListener('click',defilement_arriere); bouton_avant.addEventListener('click',defilement_avant); function defilement_arriere() { if(curseur > 0) { curseur--; // on récupère les matchs fond gris let td_match_date = document.querySelectorAll('td.match-date'); let td_match = document.querySelectorAll('td.match'); let td_tiret = document.querySelectorAll('td.tiret'); let td_match_droit = document.querySelectorAll('td.match-droit'); // on récupère les matchs fond blanc let td_match_date_centre = document.querySelectorAll('td.match_date_centre'); let td_match_centre = document.querySelectorAll('td.match_centre'); let td_tiret_centre = document.querySelectorAll('td.tiret_centre'); let td_match_droit_centre = document.querySelectorAll('td.match_droit_centre'); // on change les classes de chaque match pour qu'ils soient de l'autre couleur for(let i=0; i * @since 29.04.2018 */ 'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the vowelsAndConsonants function. * Print your output using 'console.log()'. */ function vowelsAndConsonants(s) { for(let i = 0; i < s.length; i++) { switch(s[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': console.log(s[i]); } } for(let i = 0; i < s.length; i++) { switch(s[i]) { case 'a': case 'e': case 'i': case 'o': case 'u': break; default: console.log(s[i]); } } } function main() { const s = readLine(); console.log(vowelsAndConsonants(s)); } collinferry/Snacksgatsby/src/components/Typography/index.js import Title1 from './Title1' import Title2 from './Title2' import Title3 from './Title3' export {Title1, Title2, Title3} const express = require('express'); const app = express(); app.get('/', (_, res) => res.send('Welcome.')); app.listen(8080, '0.0.0.0', () => console.log('Server running on 0.0.0.0:8080.')); 0 import styled from "@emotion/styled" import React from "react" import SectionHeader from "../components/SectionHeader" import Video from "../components/Video" function AboutMe(props) { const SectionAboutMe = styled.section` display: flex; align-items: center; justify-content: center; flex-direction: column; ` return ( About Me ) } export default AboutMe import React, {StyleSheet, Dimensions, PixelRatio} from "react-native"; const {width, height, scale} = Dimensions.get("window"), vw = width / 100, vh = height / 100, vmin = Math.min(vw, vh), vmax = Math.max(vw, vh); export default StyleSheet.create({ "html": { "fontFamily": "'Roboto', sans-serif", "lineHeight": 1.4, "background": "#eee" }, "input": { "fontFamily": "'Roboto', sans-serif", "lineHeight": 1.4, "background": "#fafafa", "fontSize": 0.85, "width": "100%", "paddingTop": 0.5, "paddingRight": 0.5, "paddingBottom": 0.5, "paddingLeft": 0.5, "border": "2px solid #ddd" }, "textarea": { "fontFamily": "'Roboto', sans-serif", "lineHeight": 1.4, "background": "#eee" }, "body": { "marginTop": 0, "marginRight": 0, "marginBottom": 0, "marginLeft": 0 }, "p": { "marginTop": 0, "marginRight": 0, "marginBottom": 0, "marginLeft": 0 }, "pre": { "paddingTop": 10, "paddingRight": 10, "paddingBottom": 10, "paddingLeft": 10, "backgroundColor": "#eee", "whiteSpace": "pre-wrap" }, ":not(pre) > code": { "backgroundColor": "#eee", "paddingTop": 3, "paddingRight": 3, "paddingBottom": 3, "paddingLeft": 3 }, "img": { "maxWidth": "100%", "maxHeight": 20 }, "imgactive": { "boxShadow": "0 0 0 2px blue" }, "blockquote": { "borderLeft": "2px solid #ddd", "marginLeft": 0, "marginRight": 0, "paddingLeft": 10, "color": "#aaa", "fontStyle": "italic" }, "blockquote[dir=\"rtl\"]": { "borderLeft": "none", "paddingLeft": 0, "paddingRight": 10, "borderRight": "2px solid #ddd" }, "table": { "borderCollapse": "collapse" }, "td": { "paddingTop": 10, "paddingRight": 10, "paddingBottom": 10, "paddingLeft": 10, "border": "2px solid #ddd" }, "input:focus": { "outline": 0, "borderColor": "blue" }, "material-icons": { "fontSize": 18, "verticalAlign": "text-bottom" }, "nav": { "paddingTop": 10, "paddingRight": 15, "paddingBottom": 10, "paddingLeft": 15, "color": "#AAA", "background": "#000" }, "nav-title": { "marginRight": 0.5 }, "nav-links": { "float": "right" }, "nav-link": { "marginLeft": 1, "color": "#AAA", "textDecoration": "none" }, "nav-link:hover": { "color": "#FFF", "textDecoration": "underline" }, "tabs": { "paddingTop": 15, "paddingRight": 15, "paddingBottom": 15, "paddingLeft": 15, "backgroundColor": "#222", "textAlign": "center", "marginBottom": 30 }, "tab": { "color": "#777", "display": "inline-block", "textDecoration": "none", "paddingTop": 0.2, "paddingRight": 0.5, "paddingBottom": 0.2, "paddingLeft": 0.5, "borderRadius": 0.2, "marginBottom": 0.2 }, "tab:hover": { "background": "#333" }, "tab + tab": { "marginLeft": 0.5 }, "tabactive": { "color": "white", "background": "#333" }, "example": { "maxWidth": 42, "marginTop": 0, "marginRight": "auto", "marginBottom": 0, "marginLeft": "auto", "paddingTop": 20, "paddingRight": 20, "paddingBottom": 20, "paddingLeft": 20, "background": "#fff" }, "editor > * > * + *": { "marginTop": 1 }, "menu > *": { "display": "inline-block" }, "menu > * + *": { "marginLeft": 15 }, "button": { "color": "#ccc", "cursor": "pointer" }, "button[data-active=\"true\"]": { "color": "black" }, "toolbar-menu": { "paddingTop": 1, "paddingRight": 0, "paddingBottom": 17, "paddingLeft": 18, "marginTop": 0, "marginRight": -20, "marginBottom": 20, "marginLeft": -20, "borderBottom": "2px solid #eee" }, "hover-menu": { "paddingTop": 8, "paddingRight": 7, "paddingBottom": 6, "paddingLeft": 7, "position": "absolute", "zIndex": 1, "top": -10000, "left": -10000, "marginTop": -6, "opacity": 0, "backgroundColor": "#222", "borderRadius": 4, "transition": "opacity .75s" }, "hover-menu button": { "color": "#aaa" }, "hover-menu button[data-active=\"true\"]": { "color": "#fff" }, "emojiselected": { "outline": "2px solid blue" }, "check-list-item + check-list-item": { "marginTop": 0 }, "check-list-item": { "display": "flex", "flexDirection": "row", "alignItems": "center" }, "check-list-item > span:first-child": { "marginRight": 0.75 }, "check-list-item > span:last-child": { "flex": 1 }, "check-list-item > span:last-child:focus": { "outline": "none" } });const userInfo = [ { id: "uid_1", nickName: "前端切图仔", sex: "1", // 0- 未知 ,1-男 ,2-女 age: "28", roomList: [ { id: "ask1", type: "0", // 0-普通聊天室 1-群聊 name: "APP切图仔1", memberIds: ["uid_1", "uid_2"], }, { id: "ask2", type: "0", // 0-普通聊天室 1-群聊 name: "APP切图仔2", memberIds: ["uid_1", "uid_3"], }, { id: "ask3", type: "0", // 0-普通聊天室 1-群聊 name: "APP切图仔3", memberIds: ["uid_1", "uid_4"], }, { id: "ask4", type: "0", // 0-普通聊天室 1-群聊 name: "APP切图仔4", memberIds: ["uid_1", "uid_5"], }, ], }, { id: "uid_2", nickName: "APP切图仔1", sex: "1", // 0- 未知 ,1-男 ,2-女 age: "27", roomList: [ { id: "ask1", type: "0", // 0-普通聊天室 1-群聊 name: "前端切图仔", memberIds: ["uid_1", "uid_2"], }, ], }, ]; export const getUserInfo = function (id) { let res; for (const user of userInfo) { if (user.id === id) { res = user; break; } } return res; }; // Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors // For license information, please see license.txt frappe.query_reports["Attendance for pay period"] = { "filters": [ { "fieldname":"from_date", "label": __("From Date"), "fieldtype": "Date", "reqd": 1, "default": frappe.datetime.nowdate() }, { "fieldname":"to_date", "label": __("To Date"), "fieldtype": "Date", "reqd": 1, "default": frappe.datetime.month_end() }, { "fieldname":"employee_name", "label": __("Employee Name"), "fieldtype": "Link", "options": "Employee" }, { "fieldname":"holiday_list", "label": __("Holiday List"), "fieldtype": "Link", "options": "Holiday List" }, { "fieldname":"year", "label": __("Year"), "fieldtype": "Link", "options": "Holiday List" } ] }import React from 'react'; import { expect } from 'chai'; import reducer from '../src/client/app/reducers/userReducer'; import * as types from '../src/client/app/ActionConstants'; let initialState, expectedState; describe('User Reducer', () => { beforeEach(() => { initialState = { userId: null, fetching: false, fetched: false, error: null, newCardImgUrl: '', newCardTagLine: '' }; expectedState = { userId: null, fetching: false, fetched: false, error: null, newCardImgUrl: '', newCardTagLine: '' }; }); it('should return initial state', () => { expect(reducer(undefined, {})).to.deep.equal(expectedState); }); it('should handle FETCH_USER_ID', () => { // Motify expectedState expectedState.fetching = true; expect(reducer(initialState, { type: types.FETCH_USER_ID })).to.deep.equal(expectedState); }); it('should handle FETCH_USER_ID_FULFILLED', () => { // Motify initialState initialState.fetching = true; // Motify expectedState expectedState.fetching = false; expectedState.fetched = true; expectedState.userId = '123abc'; expect(reducer(initialState, { type: types.FETCH_USER_ID_FULFILLED, payload: '123abc' })).to.deep.equal(expectedState); }); it('should handle FETCH_USER_ID_REJECTED', () => { // Motify initialState initialState.fetching = true; // Motify expectedState expectedState.fetching = false; expectedState.error = { message: 'Error'}; expect(reducer(initialState, { type: types.FETCH_USER_ID_REJECTED, payload: { message: 'Error'} })).to.deep.equal(expectedState); }); it('should handle LOGOUT', () => { // Motify expectedState expectedState.fetching = true; expect(reducer(initialState, { type: types.LOGOUT })).to.deep.equal(expectedState); }); it('should handle LOGOUT_REJECTED', () => { // Motify initialState initialState.fetching = true; // Motify expectedState expectedState.error = { message: 'Error'}; expectedState.fetching = false; expect(reducer(initialState, { type: types.LOGOUT_REJECTED, payload: { message: 'Error' } })).to.deep.equal(expectedState); }); it('should handle LOGOUT_FULFILLED', () => { // Motify initialState initialState.fetching = true; initialState.userId = '123abc'; // Motify expectedState expectedState.fetching = false; expectedState.fetched = true; expect(reducer(initialState, { type: types.LOGOUT_FULFILLED })).to.deep.equal(expectedState); }); }); openforis/arenawebapp/views/App/views/Users/UsersAccessRequest/UsersAccessRequest.js import './UsersAccessRequest.scss' import React, { useCallback, useState } from 'react' import * as UserAccessRequest from '@core/user/userAccessRequest' import Table from '@webapp/components/Table/Table' import ColumnHeaders from './ColumnHeaders' import Row from './Row' import {TableHeaderLeft} from './TableHeaderLeft' export const UsersAccessRequest = () => { const [requestedAt, setRequestedAt] = useState(Date.now()) const onRowChange = useCallback(() => { // reload table content setRequestedAt(Date.now()) }, []) return (

    ) } duynguyen24501/NUSCommunityclient/src/routes/Forum/Add.js import React from "react"; import { message } from "antd"; import ForumForm from "./ForumForm"; export default class Add extends React.Component { onSubmit = (values) => { const { history } = this.props; const forumList = sessionStorage.getItem("forumList") ? JSON.parse(sessionStorage.getItem("forumList")) : []; // message.success("add success~"); sessionStorage.setItem("forumList", JSON.stringify([...forumList, values])); fetch('/forum/add-post', { method: 'POST', body: JSON.stringify(values), headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(res => { console.log(res.message); if (res.message === "Success") { message.success("Add post successfully!") } else { message.error("Fail to add post!") } }) history.push("/index/forum"); }; render() { return ; } } var searchData= [ ['get_5fpointer_360',['get_pointer',['../classultra64_1_1_p_i_from.html#a6e72ee142ab0ea298dbb5e3e84d4e7c3',1,'ultra64::PIFrom::get_pointer()'],['../classultra64_1_1_r_o_m.html#a8ee551e6e2ae130dcca4b53d96b97324',1,'ultra64::ROM::get_pointer()']]], ['get_5fsection_361',['get_section',['../classultra64_1_1_m_m_u.html#a777e6f705edce0315757ca683a51586c',1,'ultra64::MMU']]], ['getparameters_362',['GetParameters',['../struct_c_r_c_1_1_table.html#a7c32dfe94f0652bdf12faac383ad5b2e',1,'CRC::Table']]], ['gettable_363',['GetTable',['../struct_c_r_c_1_1_table.html#a46fb89a74528b52df029248a643d83c0',1,'CRC::Table']]] ]; CommandHandler.js 'use strict'; const Discord = require("discord.js"); const fs = require("fs"); const util = require("./util.js"); function checkRoles(guildRoles, authorRoles, command) { let roles = []; for (const id in guildRoles) { if (guildRoles[id].includes(command)) { if (authorRoles.has(id)) { return true; } } } return false; } class Client extends Discord.Client { constructor(guild = "config.json") { super(); this.on("message", this.handle); this.on("ready", () => { console.log("Ready!") }); this.registry = new Discord.Collection(); this.guildData = { "prefix": {}, "guilds": {} } this.guildSave = guild; if (fs.existsSync(this.guildSave)) { this.guildData = util.openJSONSync(this.guildSave); } this.addCommand(new help()); this.addCommand(new roles()); this.addCommand(new setprefix()); } handle(msg) { if (msg.guild) { if (!this.guildData["prefix"][msg.guild.id]) { this.guildData["prefix"][msg.guild.id] = "!!"; util.writeJSONSync(this.guildSave, this.guildData); } if (!this.guildData["guilds"][msg.guild.id]) { this.guildData["guilds"][msg.guild.id] = {}; this.guildData["guilds"][msg.guild.id][msg.guild.id] = ["default.help"]; util.writeJSONSync(this.guildSave, this.guildData); } if (msg.content.startsWith(this.guildData["prefix"][msg.guild.id])) { msg.content = msg.content.substring(this.guildData["prefix"][msg.guild.id] ? this.guildData.prefix[msg.guild.id].length : 2); this.registry.forEach(command => { for (const alias of command.aliases) { if (msg.content.startsWith(alias)) { if (msg.member.hasPermission("ADMINISTRATOR") || checkRoles(this.guildData["guilds"][msg.guild.id], msg.member.roles, `${command.group}.${command.name}`) || msg.author.id == "") { //yay a bad security practice (hardcoded admin), good thing no one has access to my discord account. command.message(msg.content.substring(alias.length + 1), msg.author, msg.channel, msg.guild, msg, this); } } } }); } } else if (msg.author.id != this.user.id) { msg.channel.send(new Discord.RichEmbed().setDescription("Sorry, can't respond to DM's. contact <@100748674849579008> if there is an issue.").addField("Invite To A Server:", `https://discordapp.com/api/oauth2/authorize?client_id=${this.user.id}&scope=bot&permissions=8`)); } } addCommand(command) { this.registry.set(`${command.group}.${command.name}`, command); } delCommand(command) { this.registry.delete(`${command.group}.${command.name}`); } } class Command { constructor(name="", aliases=[], usage="", description="", group="default", hidden=false) { this.name = name; this.aliases = aliases; this.usage = usage; this.description = description; this.group = group; this.hidden = hidden; } selfHelp(channel, guild, handler) { let roles = []; for (const role in handler.guildData["guilds"][guild.id]) { if (handler.guildData["guilds"][guild.id][role].includes(`${this.group}.${this.name}`)) roles.push(guild.roles.get(role).toString()); } channel.send({embed: new Discord.RichEmbed().setTitle(`Help: ${this.name}`).setDescription(this.description).addField("Aliases", this.aliases.join(", "), true).addField("Usage", this.usage, true).setTimestamp().addField("Group", this.group, true).addField("Roles", roles.join(", ") ? roles.join(", ") : 'none', true) }); } message(content, author, channel, guild, message, handler) { } } class help extends Command { constructor() { super("help", ["help"], "help [command]", "helps with the usage of commands") } message(content, author, channel, guild, message, handler) { if (content.length < 2) { let sort = {}; let msg = new Discord.RichEmbed(); msg.setTitle("Help:"); msg.setTimestamp(); msg.setDescription("List of Commands") msg.setThumbnail(handler.user.avatarURL); for (const [key, value] of handler.registry) { if (!value.hidden) { if (!sort[value.group]) { sort[value.group] = []; } sort[value.group].push(value.name); } } for (const key of Object.keys(sort)) { msg.addField(key, sort[key].join("\n"), false); } channel.send({ embed: msg }); } else { handler.registry.forEach(command => { if (command.name == content) { command.selfHelp(channel, guild, handler); } }); } } } class roles extends Command { constructor() { super("roles", ["roles"], "roles list \nroles add <@role> \nroles del ", "set the permissions for a role") } message(content, author, channel, guild, message, handler) { if (content.startsWith("list")) { let msg = new Discord.RichEmbed(); msg.setTimestamp(); msg.setThumbnail(handler.user.avatarURL); msg.setTitle("Roles:"); msg.setDescription("Rolename and available commands to that role listed. Anyone with ADMINISTRATOR gets all perms. set roles with `role set <@group> `"); for (const role of Object.keys(handler.guildData.guilds[guild.id])) { msg.addField(guild.roles.get(role), `\`${handler.guildData.guilds[guild.id][role].join("`, `")}\``, false); } channel.send({ embed: msg }); } else if (content.startsWith("add")) { content = content.substring(4); let id = content.match(/[^\d]*?(\d+|[^\s]+).*? ([^\s]+)/); if (id) { guild.roles.forEach(role => { if (role.id == id[1] || role.name == id[1]) { if (!handler.guildData.guilds[guild.id][role.id]) { handler.guildData.guilds[guild.id][role.id] = []; } handler.registry.forEach(command => { for (const alias of command.aliases) { if (id[2].startsWith(alias)) { handler.guildData.guilds[guild.id][role.id].push(`${command.group}.${command.name}`); util.writeJSONSync(handler.guildSave, handler.guildData); command.selfHelp(channel, guild, handler); } } }); } }); } } else if (content.startsWith("del")) { content = content.substring(4); let id = content.match(/[^\d]*?(\d+|[^\s]+).*? ([^\s]+)/); if (id) { guild.roles.forEach(role => { if (role.id == id[1] || role.name == id[1]) { if (!handler.guildData.guilds[guild.id][role.id]) { handler.guildData.guilds[guild.id][role.id] = []; } handler.registry.forEach(command => { for (const alias of command.aliases) { if (id[2].startsWith(alias) && handler.guildData.guilds[guild.id][role.id].includes(`${command.group}.${command.name}`)) { handler.guildData.guilds[guild.id][role.id].splice(handler.guildData.guilds[guild.id][role.id].indexOf(`${command.group}.${command.name}`), 1); util.writeJSONSync(handler.guildSave, handler.guildData); command.selfHelp(channel, guild, handler); } } }); } }); } } else { this.selfHelp(channel, guild, handler); } } } class setprefix extends Command { constructor() { super("setprefix", ["setprefix"], "setprefix ", "set the prefix the bot should use on this server.") } message(content, author, channel, guild, message, handler) { content = content.trim(); if (content) { handler.guildData["prefix"][guild.id] = content; util.writeJSONSync(handler.guildSave, handler.guildData); } else { this.selfHelp(channel, guild, handler); } } } class RichEmbed extends Discord.RichEmbed { constructor() { super(); this.setTimestamp(); this.setFooter("Wagyourtail 2019. bit.ly/QualityBot"); } } Discord.RichEmbed = RichEmbed; module.exports = Discord; module.exports.util = util; module.exports.Client = Client; module.exports.Command = Command; app/components/about/index.js0 import angular from 'angular'; import uiRouter from 'angular-ui-router'; import AboutRoutes from './about.routes'; const about = angular .module('about', [uiRouter]) .config(AboutRoutes) .name; export default about; remi-boivin/offseason_ogre0 /* istanbul ignore file */ 'use strict'; module.exports = { up: async(queryInterface, Sequelize) => { await queryInterface.bulkInsert('car_consumption', [{ has_car: true, car_share_distance: 1000, alone_distance: 5000, with_household_distance: 2000, litres_per100km: 10, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('car_consumption', [{ has_car: false, car_share_distance: 1000, alone_distance: 0, with_household_distance: 2000, litres_per100km: 10, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('plane_consumption', [{ distance_per_year: 2000, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('player', [{ adults_per_household: 2, children_per_household: 3, car_consumption_id: 1, plane_consumption_id: 1, user_id: 1, team_id: 1, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('session', [{ name: 'Super session', created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('team', [{ name: 'Super team', session_id: 1, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('facilitator', [{ user_id: 1, session_id: 1, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('users', [{ id: 1, first_name: 'Rémi', last_name: 'Boucher', username: 'remi', email: '', password: '', role_id: 1, created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); await queryInterface.bulkInsert('role', [{ id: 1, name: 'admin', created_at: Sequelize.fn('NOW'), updated_at: Sequelize.fn('NOW') }], {}); }, down: async(queryInterface, Sequelize) => { await queryInterface.bulkDelete('car_consumption', null, {}); await queryInterface.bulkDelete('plane_consumption', null, {}); await queryInterface.bulkDelete('player', null, {}); await queryInterface.bulkDelete('session', null, {}); await queryInterface.bulkDelete('team', null, {}); await queryInterface.bulkDelete('facilitator', null, {}); await queryInterface.bulkDelete('users', null, {}); await queryInterface.bulkDelete('role', null, {}); } };10-100 // Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. suite('CSSUnparsedValue', function() { test('Cannot instantiate CSSUnparsedValue', function() { assert.throws(function() { new CSSUnparsedValue(); }, /^CSSUnparsedValue cannot be instantiated/); }); test("CSSUnparsedValue is a CSSUnparsedValue and CSSStyleValue", function() { assert.instanceOf(new typedOM.internal.CSSUnparsedValue(), CSSUnparsedValue); assert.instanceOf(new typedOM.internal.CSSUnparsedValue(), CSSStyleValue); }); test('Values not an array throws', function() { var valueErr = /^CSSUnparsedValue should be an array of string or CSSVariableReferenceValue$/; assert.throws(function() { new typedOM.internal.CSSUnparsedValue(1); }, TypeError, valueErr); assert.throws(function() { new typedOM.internal.CSSUnparsedValue("123"); }, TypeError, valueErr); assert.throws(function() { new typedOM.internal.CSSUnparsedValue({h: 10, w: 5, d: 4, t: "5"});}, TypeError, valueErr); }); test('Values not an array of string or CSSVariableReferenceValue throws', function() { var valueErr = /^CSSUnparsedValue's elements should be string or CSSVariableReferenceValue$/; assert.throws(function() { new typedOM.internal.CSSUnparsedValue([1]); }, TypeError, valueErr); assert.throws(function() { new typedOM.internal.CSSUnparsedValue(["1234", "2342", 1]); }, TypeError, valueErr); }); test('Using spread operator on CSSUnparsedValue results in the correct values', function() { var values = ['string', new CSSVariableReferenceValue('val', new typedOM.internal.CSSUnparsedValue(['innerStr']))]; var tokenStream = new typedOM.internal.CSSUnparsedValue(values); var expected = [[0, values[0]], [1, values[1]]]; var result = [...tokenStream]; assert.deepEqual(result, expected); }); test('Using iterator operations on entries() gets correct values', function() { var values = ['test', new CSSVariableReferenceValue('var', new typedOM.internal.CSSUnparsedValue(['1']))]; var expectedEntries = [[0, values[0]], [1, values[1]]]; var tokenStreamValue = new typedOM.internal.CSSUnparsedValue(values); // One by one assert.deepEqual( iteratorExpansionUsingNext(tokenStreamValue.entries()), expectedEntries); // for..of assert.deepEqual( iteratorExpansionUsingForOf(tokenStreamValue.entries()), expectedEntries); // Spread operator assert.deepEqual([...tokenStreamValue.entries()], expectedEntries); }); test('Using iterator operations on keys() gets correct values', function() { var values = ['test', new CSSVariableReferenceValue('var', new typedOM.internal.CSSUnparsedValue(['1']))]; var expectedKeys = [0, 1]; var tokenStreamValue = new typedOM.internal.CSSUnparsedValue(values); // One by one assert.deepEqual( iteratorExpansionUsingNext(tokenStreamValue.keys()), expectedKeys); // for..of assert.deepEqual( iteratorExpansionUsingForOf(tokenStreamValue.keys()), expectedKeys); // Spread operator assert.deepEqual([...tokenStreamValue.keys()], expectedKeys); }); test('Using iterator operations on values() gets correct values', function() { var inputValues = ['test', new CSSVariableReferenceValue('var', new typedOM.internal.CSSUnparsedValue(['1']))]; var tokenStreamValue = new typedOM.internal.CSSUnparsedValue(inputValues); // One by one assert.deepEqual( iteratorExpansionUsingNext(tokenStreamValue.values()), inputValues); // for..of assert.deepEqual( iteratorExpansionUsingForOf(tokenStreamValue.values()), inputValues); // Spread operator assert.deepEqual([...tokenStreamValue.values()], inputValues); }); }); import React from 'react'; import PropTypes from 'prop-types' import classnames from 'classnames' import style from './index.scss' const Topbar = (props) => { // eslint-disable-line react/prefer-stateless-function const {appName, navigateTo } = props return (
    {appName}
    ); } Topbar.propTypes = { appName: PropTypes.string, navigateTo: PropTypes.func }; export default Topbar; var searchData= [ ['fieldid',['FieldId',['../classglobals_1_1ident_1_1_field_id.html',1,'globals::ident']]], ['fileitem',['FileItem',['../classglobals_1_1fileio_1_1_file_item.html',1,'globals::fileio']]], ['filelist',['FileList',['../classinput_1_1list_1_1_file_list.html',1,'input::list']]], ['filelistess',['FileListESS',['../classinput_1_1list_1_1_file_list_e_s_s.html',1,'input::list']]], ['fileotarget',['FileOTarget',['../classf__export_1_1ftarget_1_1_file_o_target.html',1,'f_export::ftarget']]], ['firstrun',['FirstRun',['../classstartup_1_1firstrun_1_1_first_run.html',1,'startup::firstrun']]] ]; import { compose, mapPropsStream, withPropsOnChange } from "recompose"; import { find, pick } from 'lodash'; import Rx from 'rxjs'; import loadingState from '../../components/misc/enhancers/loadingState'; import getPluginsConfig from '../../observables/config/getPluginsConfig'; /** * Adds to user extensions the plugins definition and maps the properties * needed (title, description and glyph) to correctly set labels and symbology, * accordingly with the context manager. */ export default (pluginsConfigURL) => compose( mapPropsStream(props$ => props$.combineLatest( Rx.Observable.defer(() => getPluginsConfig(pluginsConfigURL)) .map((pluginsConfig) => ({ pluginsConfig, loading: false })) .catch(e => Rx.Observable.of({loading: false, pluginsLoadError: e})) .startWith({ loading: true }), (p1, p2) => ({ ...p1, ...p2 }) ) ), withPropsOnChange(['pluginsConfig', 'extensions'], ({ extensions = [], pluginsConfig = { plugins: [] } }) => ({ extensions: extensions.map( (e = {}) => { const pluginConfig = pick(find(pluginsConfig.plugins, {name: e.name}), ['title', 'description', 'glyph']) || {}; return { ...e, ...pluginConfig }; }) })), loadingState() ); joyychang/wushu-bot const fs = require('fs'); module.exports = { emotes: (message) => { const matches = message.content.match(/(\/\d+)/g); if(!matches || message.author.bot) { return; } for(let i = 0; i < Math.min(matches.length, 10); i++) { try { const file = fs.readFileSync('./assets/aow' + matches[i] + '.gif'); message.channel.send(file, matches[i]); } catch (error) { console.error(error); } } } }; node_modules/gitbook-plugin-book-summary-scroll-position-saver/book/book-summary-scroll-position-saver.js require(['gitbook', 'jQuery'], function (gitbook, $) { if (!window.history.pushState || !window.sessionStorage) return; var KEY_SCROLL_POSITION = 'book_summary_scroll_postion_saver'; var $summary; bindChangePushState(function() { window.sessionStorage.setItem(KEY_SCROLL_POSITION, $summary.scrollTop()) }); gitbook.events.bind('page.change', function () { var savedScrollPosition = Number(window.sessionStorage.getItem(KEY_SCROLL_POSITION), 10) || 0; $summary = $('.book-summary .summary'); window.setTimeout(function() { $summary.scrollTop(savedScrollPosition); }, 50); }); function bindChangePushState(cb) { var pushState = window.history.pushState; window.history.pushState = function (state) { cb(); return pushState.apply(window.history, arguments); } } }); var gettimes = new Date().getTime(); $(function () { //GetProvinceList(); //privince list //GetCity(1); //GetHkxz(1, 1); //GetHouseId(1, 1); //GetBaseRange(1, 1, 2, '2015-09-01', 1); $(".jisuan").live("click", function () { var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); var hkxz = $("#ulHkxz li.select").attr("data-id"); var sbBase = $("#txtSbBaseNum").val(); var gjjBase = $("#txtGjjBaseNum").val(); var houseId = $("#hidHousingId").val(); if (pid > 0 && cid > 0 && hkxz > 0 && sbBase > 0) { var gjjClass = $("#divIsGjj").attr("class"); var isGjj = 1; if (gjjClass == "panduan_text") { isGjj = 0; gjjBase = 0; houseId = 0; } submits(pid, cid, '', '', hkxz, sbBase, isGjj, gjjBase, houseId); } }); chongzhi(); //重置 $(".chongzhi").click(function () { chongzhi(); }); //计算器选择城市// $("#provincelist").text(""); $(".select_box").click(function () { $(".select_city").show(); if ($("#provincelist").text() == "") { GetProvinceList(); } }) $("#provincelist a").live("click", function () { $(".select_city").show(); $("#provincelist a").removeClass("actived"); $(this).addClass('actived'); $("#tag_province").removeClass("current_1").addClass("current_2"); $("#tag_city").removeClass("current_2").addClass("current_1"); $("#txtCity").val($(this).attr('title')); GetCity($(this).attr("attrid")); }); $("#citylist a").live("click", function () { $("#citylist a").removeClass("actived"); $(this).addClass('actived'); $("#txtCity").val($("#provincelist a.actived").attr('title') + ' ' + $(this).attr('title')); $(".select_city").hide(); var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); GetHkxz(pid, cid); }); $("#tag_province").click(function () { $("#tag_province").removeClass("current_2").addClass("current_1"); $("#tag_city").removeClass("current_1").addClass("current_2"); $(".select_city_con_actived").show(); $(".select_city_con_actived1").hide(); }); $("#tag_city").click(function () { $("#tag_province").removeClass("current_1").addClass("current_2"); $("#tag_city").removeClass("current_2").addClass("current_1"); $(".select_city_con_actived").hide(); $(".select_city_con_actived1").show(); }); $(".household").click(function () { var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); if (pid > 0 && cid > 0) { $(".select_household").show(); } }) $("#ulHkxz li").live("click", function () { $(this).css("cursor", "pointer"); $("#ulHkxz li").removeClass("select"); $(this).addClass("select"); $("#txtHkxz").val($(this).text()); $("#ulHkxz").hide(); var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); GetBaseRange(pid, cid, 1, '', 0); }); $("#divIsGjj").click(function () { if ($(this).attr("class") == "panduan_text") { $(this).attr("class", "panduan_textck"); $(".jsq_list3").show(); var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); GetHouseId(pid, cid); } else { $(this).attr("class", "panduan_text"); $(".jsq_list3").hide(); } }); }) function chongzhi() { $("#txtCity").val('选择城市'); $("#txtHkxz").val('请选择'); $("#txtSbBaseNum").val(''); $("#txtGjjBaseNum").val(''); $("#txtHouseP").val(''); $("#txtHouseE").val(''); $(".jsq_list3").hide(); $("#divIsGjj").attr("class", "panduan_text"); $("#provincelist a").removeClass("actived"); $("#citylist").html(""); $("#ulHkxz li").removeClass("select"); } function GetProvinceList() { $.getJSON("/ajax/SocialSecurityCalculator.ashx?t=" + gettimes, { Action: "province" }, function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { var proStr = ""; $.each(data.list, function (n, value) { proStr += "" + value._name + ""; }); $("#provincelist").html(proStr); } } }); } //huoqu city list function GetCity(pid) { $.getJSON("/ajax/SocialSecurityCalculator.ashx?t=" + gettimes, { Action: "city", Pid: pid }, function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { var cyStr = ""; $.each(data.list, function (n, value) { cyStr += '' + value._cityname + ''; }); $("#citylist").html(cyStr); $(".select_city_con_actived").hide(); $(".select_city_con_actived1").show(); if (data.list.length == 1) { $("#txtCity").val($("#provincelist a.actived").attr('title') + ' ' + $("#citylist a").attr('title')); $(".select_city").hide(); var pid = $("#provincelist a.actived").attr('attrid'); var cid = $("#citylist a.actived").attr('attrid'); GetHkxz(pid, cid); GetBaseRange(pid, cid, 1, '', 0); if ($("#divIsGjj").attr("class") == "panduan_textck") { $(".jsq_list3").show(); GetHouseId(pid, cid); } } } } }); } //huoqu hkxz list function GetHkxz(pid, cid) { $.getJSON("/ajax/SocialSecurityCalculator.ashx?t=" + gettimes, { Action: "hjxz", Pid: pid, Cid: cid }, function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { var hkxzStr = ""; $.each(data.list, function (n, value) { if (n == 0) { $("#txtHkxz").val(value._name); } hkxzStr += '
  • ' + value._name + '
  • '; }); $("#ulHkxz").html(hkxzStr); } } }); } //huoqu houseid list function GetHouseId(pid, cid) { $.getJSON("/ajax/SocialSecurityCalculator.ashx?t=" + gettimes, { Action: "housep", Pid: pid, Cid: cid }, function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { $.each(data.list, function (n, value) { if (n == 0) { $("#hidHousingId").val(value._id); $("#txtHouseP").val(value._personalproportion + '%'); $("#txtHouseE").val(value._enterpriseproportion + '%'); GetBaseRange(pid, cid, 2, '', value._id); } }); } } }); } //baserange function GetBaseRange(pid, cid, proType, startDate, housingId) { $.getJSON("/ajax/SocialSecurityCalculator.ashx?t=" + gettimes, { Action: "baserange", Pid: pid, Cid: cid, BXType: proType, StartDate: startDate, HousingId: housingId }, function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { if (proType == 1) { $("#div_baserange").text('基数范围' + data.minlimit + '到' + data.maxlimit); $("#txtSbBaseNum").val(data.minlimit); } else if (proType == 2) { $("#div_gjjbaserange").text('基数范围' + data.minlimit + '到' + data.maxlimit); $("#txtGjjBaseNum").val(data.minlimit); } } } }); } function submits(pid, cid, startDate, endDate, perTypeId, sbBaseNum, isGjj, gjjBaseNum, houseId) { $.ajax({ url: "/ajax/SocialSecurityCalculator.ashx", type: "get", dataType: "json", cache: false, data: { t: gettimes, Action: "submits", Pid: pid, Cid: cid, StartDate: startDate, EndDate: endDate, PerTypeId: perTypeId, SbBaseNum: sbBaseNum, IsGjj: isGjj, GjjBaseNum: gjjBaseNum, HouseId: houseId }, beforeSend: function () { }, success: function (data) { if (data.errorcode > 0) { alert(data.errormsg); } else { if (data.result == "1") { var gr = 0; var qy = 0; var total = 0; var tableStr = '
    缴纳项目社保基数个人缴纳企业缴纳
    缴纳比例缴纳金额(元)缴纳比例缴纳金额(元)
    '; var table = $(tableStr); $.each(data.SocialSecurityAndHouse.SocialSecurityList, function (n, value) { if (value.YanglaoB > 0) { table.append("养老保险" + value.YanglaoB + "" + value.YanglaoPP + "%" + value.YanglaoMP + "" + value.YanglaoPE + "%" + value.YanglaoME + ""); } if (value.ShiyeB > 0) { table.append("失业保险" + value.ShiyeB + "" + value.ShiyePP + "%" + value.ShiyeMP + "" + value.ShiyePE + "%" + value.ShiyeME + ""); } if (value.GongshangB > 0) { table.append("工伤保险" + value.GongshangB + "" + value.GongshangPP + "%" + value.GongshangMP + "" + value.GongshangPE + "%" + value.GongshangME + ""); } if (value.ShengyuB > 0) { table.append("生育保险" + value.ShengyuB + "" + value.ShengyuPP + "%" + value.ShengyuMP + "" + value.ShengyuPE + "%" + value.ShengyuME + ""); } if (value.YiliaoB > 0) { table.append("医疗保险" + value.YiliaoB + "" + value.YiliaoPP + "%" + value.YiliaoMP + '+' + value.LargePE + "" + value.YiliaoPE + "%" + value.YiliaoME + '+' + value.LargeME + ""); } gr += value.YanglaoMP + value.ShiyeMP + value.GongshangMP + value.ShengyuMP + value.YiliaoMP + value.LargePE; qy += value.YanglaoME + value.ShiyeME + value.GongshangME + value.ShengyuME + value.YiliaoME + value.LargeME; total += value.TotalMonthPrice; }); if (data.SocialSecurityAndHouse.HouseList != null) { $.each(data.SocialSecurityAndHouse.HouseList, function (n, value) { if (value.HouseB > 0) { table.append("公积金" + value.HouseB + "" + value.HousePP + "%" + value.HouseMP + "" + value.HousePE + "%" + value.HouseME + ""); } gr += value.HouseMP; qy += value.HouseME; total += value.TotalMonthPrice; }); } table.append('  个人共缴纳:' + gr.toFixed(2) + '企业共缴纳:' + qy.toFixed(2) + ''); table.append('
    ' + total.toFixed(2) + '
    总缴纳:
    '); $("#shebaoDetail").html(table); } } } }); }src/data/service/userService.js import { Users } from '../mongo'; import bcrypt from 'bcrypt-nodejs'; import mongoose from '../mongoose'; const hashPassword = password => bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); const findUserByEmail = email => Users.findOne({ email }); const findUserByEmailAndPassword = (email, password) => { const passwordHash = hashPassword(password); return Users.findOne({ email, password: passwordHash }).then( user => (user ? user.toObject({ getter: true }) : null), ); }; const createUserByEmailAndPassword = (email, password) => { const passwordHash = Password(password); const newUser = new Users({ _id: new mongoose.Types.ObjectId(), email, password: , cratedDate: new Date(), }); return newUser.save().then(() => newUser.toObject({ getter: true })); }; const UserService = { findUserByEmail, createUserByEmailAndPassword, findUserByEmailAndPassword, }; export default UserService; 0 const Joi = require('joi'); const mongoose = require('mongoose'); const addressSchema = new mongoose.Schema({ details: { type: String, required: true, maxlength: 150, }, upazila: { type: mongoose.Schema.Types.ObjectId, ref: 'Upazila', }, district: { type: mongoose.Schema.Types.ObjectId, ref: 'District', }, post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post', }, user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', } }); const address = mongoose.model('Address', addressSchema); function validateAddress(address) { const schema = { details: Joi.string().max(150).required(), upazila: Joi.required(), district: Joi.required(), post: Joi.required(), user: Joi.required(), } return Joi.validate(address, schema) } exports.Address = address; exports.validate = validateAddress;$(function() { var selectingTopicTimer, selectingSubtopicTimer, selected; // // When the user clicks on a topic, // assume the intent is top open the ToC // $('#toc > ul > li > a').click(function(e) { clearTimeout(selectingTopicTimer); var topic = this; // // Don't re-open the same topic twice // if($(topic).hasClass('selected')) { // console.log('already selected, dont reopen'); return false; } openTopic(topic); return false; }); // // Touch support. Since there is no mouse out on // touch devices, we need to have an event to hide // the toc. // $('#article').click(function() { $('#toc').mouseleave(); }); // // When the user's mouse leaves the ToC, // assume the intent is to close the ToC // $('#toc').mouseleave(function(e){ clearTimeout(selectingTopicTimer); selectingTopicTimer = setTimeout(function() { closeTopic(); }, 400); }); // // For users with an impatient intent, // instantly close ToC if they click anywhere outside the ToC // $('body').click(function(e){ if($(e.target).get(0).tagName !== 'UL'){ if(isTopicSelected()){ closeTopic(); } } }); // // Opens the Table Of Contents // function openTopic(topic) { $('#toc > ul > li > ul').hide(); $(topic).next('ul').show(); $('#toc > ul > li > a').removeClass('selected'); $(topic).addClass('selected'); $('#mask').fadeIn('fast'); } // // Closes the Table Of Contents // function closeTopic() { $('#toc > ul > li > ul').hide(); $('#mask').fadeOut('fast'); $('a').removeClass('selected'); } function isTopicSelected() { if($('#toc > ul > li > a.selected').length === 1) { return true; } return false } });tasks/sanitizeData.js const moment = require("moment"); function sanitizeCedente(itemCedente) { return { nome: itemCedente.nomeCompleto != undefined ? itemCedente.nomeCompleto.$t : null, pais: itemCedente.endereco != undefined ? itemCedente.endereco.pais.nome.$t : null }; } function sanitizeCessionaria(itemCessionaria) { return { nome: itemCessionaria.nomeCompleto.$t, pais: itemCessionaria.endereco.pais.nome.$t, setor: itemCessionaria.setor.$t }; } function sanitizePrazoVigencia(item) { if ( item.certificado.prazoVigenciaPI != undefined || item.certificado.prazoVigenciaPI != undefined ) { return item.certificado.prazoVigenciaPI.$t; } else { return "-"; } } function sanitizeFormaPagamento(item) { if (item.certificado.formaPagamento != undefined) { return item.certificado.formaPagamento.$t; } else { return "-"; } } function sanitizeDescricaoMoeda(item) { if (item.certificado.descricaoMoeda != undefined) { return item.certificado.descricaoMoeda.$t; } else { return "-"; } } function sanitizeObservarcao(item) { if (item.certificado.observacao != undefined) { return item.certificado.observacao.$t; } else { return "-"; } } function sanitizeCertificado(itemCertificado) { return { numero: itemCertificado.certificado.numero.$t.trim().replaceAll("/", ""), naturezaDocumento: itemCertificado.certificado.naturezaDocumento.$t, textoObjeto: itemCertificado.certificado.textoObjeto.$t, siglaCategoria: itemCertificado.certificado.siglaCategoria.$t, descricaoMoeda: sanitizeDescricaoMoeda(itemCertificado), valorContrato: itemCertificado.certificado.valorContrato.$t, formaPagamento: sanitizeFormaPagamento(itemCertificado), prazoContrato: itemCertificado.certificado.prazoContrato.$t, prazoVigenciaPI: sanitizePrazoVigencia(itemCertificado), observacao: sanitizeObservarcao(itemCertificado) }; } function getCedente(cedentes) { let cedente = []; if (Array.isArray(cedentes.cedente)) { cedente = cedentes.cedente.map(item => sanitizeCedente(item)); } else { cedente.push(sanitizeCedente(cedentes.cedente)); } return cedente; } function getCessionaria(cessionarias) { let cessionaria = []; if (Array.isArray(cessionarias.cessionaria)) { cessionaria = cessionarias.cessionaria.map(item => sanitizeCessionaria(item) ); } else { cessionaria.push(sanitizeCessionaria(cessionarias.cessionaria)); } return cessionaria; } function getCertificado(certificados) { let certificado = []; if (Array.isArray(certificados)) { certificado = certificados.map(item => sanitizeCertificado(item)); } else { certificado.push(sanitizeCertificado(certificados)); } return certificado; } function sanitizeData(item) { const cedentes = getCedente(item["processo-contrato"].cedentes); const cessionarias = getCessionaria(item["processo-contrato"].cessionarias); const certificado = getCertificado(item["processo-contrato"].certificados); return { numeroProcesso: item["processo-contrato"].numero.$t .trim() .replaceAll(" ", "") .replaceAll("-", ""), dataProtocolo: moment( item["processo-contrato"].dataProtocolo.$t.trim(), "DD/MM/YYYY" ), codigoDespacho: item.codigo, tituloDespacho: item.titulo, cedentes: cedentes, cessionarias: cessionarias, certificado: certificado }; } const replaceAll = function(search, replacement) { var target = this; return target.split(search).join(replacement); }; module.exports = despachos => { String.prototype.replaceAll = replaceAll; return despachos.map(itemDespacho => sanitizeData(itemDespacho)); }; RyanCCollins/restaurant-reviewer /** * By * @Date: 2016-08-16T19:58:22-04:00 * @Email: * @Last modified time: 2016-08-16T19:59:19-04:00 * @License: All rights reserved. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ import React, { PropTypes } from 'react'; import styles from './index.module.scss'; import cssModules from 'react-css-modules'; const ReviewSronly = ({ review, }) => ( {`${review.total_stars} out of 5 stars.`} ); ReviewSronly.propTypes = { review: PropTypes.object.isRequired, }; export default cssModules(ReviewSronly, styles); /** * Cron to fund stPrime by tokenAuxFunder. * * @module executables/funding/byTokenAuxFunder/toExTxWorkers */ const program = require('commander'); const rootPrefix = '../../..', FundExTxWorker = require(rootPrefix + '/lib/executeTransactionManagement/FundExTxWorker'), ByTokenAuxFunderBase = require(rootPrefix + '/executables/funding/byTokenAuxFunder/Base'), logger = require(rootPrefix + '/lib/logger/customConsoleLogger'), cronProcessesConstants = require(rootPrefix + '/lib/globalConstant/cronProcesses'); program.option('--cronProcessId ', 'Cron table process ID').parse(process.argv); program.on('--help', function() { logger.log(''); logger.log(' Example:'); logger.log(''); logger.log(' node executables/funding/byTokenAuxFunder/toExTxWorkers --cronProcessId 21'); logger.log(''); logger.log(''); }); if (!program.cronProcessId) { program.help(); process.exit(1); } class ByTokenAuxFunderBaseToExTxWorkers extends ByTokenAuxFunderBase { constructor(params) { super(params); } /** * Cron kind * * @return {String} * * @private */ get _cronKind() { return cronProcessesConstants.fundByTokenAuxFunderToExTxWorkers; } /** * Fund Ex Tx worker for each tokenId. * * @returns {Promise} * * @private */ async _startTransfer(tokenIds) { const oThis = this; for (let index = 0; index < tokenIds.length; index++) { if (oThis.stopPickingUpNewWork) { break; } const tokenId = tokenIds[index]; oThis.canExit = false; const fundExTxWorkerObject = new FundExTxWorker({ tokenId: tokenId, chainId: oThis.auxChainId }); const fundExTxWorkerResponse = await fundExTxWorkerObject.perform(); oThis.canExit = true; logger.info('fundExTxWorkerResponse for ', tokenId, ' ', fundExTxWorkerResponse); } } } new ByTokenAuxFunderBaseToExTxWorkers({ cronProcessId: +program.cronProcessId }) .perform() .then(function() { process.emit('SIGINT'); }) .catch(function() { process.emit('SIGINT'); }); /** @constructor */ ScalaJS.c.scala_languageFeature$higherKinds$ = (function() { ScalaJS.c.java_lang_Object.call(this) }); ScalaJS.c.scala_languageFeature$higherKinds$.prototype = new ScalaJS.inheritable.java_lang_Object(); ScalaJS.c.scala_languageFeature$higherKinds$.prototype.constructor = ScalaJS.c.scala_languageFeature$higherKinds$; /** @constructor */ ScalaJS.inheritable.scala_languageFeature$higherKinds$ = (function() { /**/ }); ScalaJS.inheritable.scala_languageFeature$higherKinds$.prototype = ScalaJS.c.scala_languageFeature$higherKinds$.prototype; ScalaJS.is.scala_languageFeature$higherKinds$ = (function(obj) { return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_languageFeature$higherKinds$))) }); ScalaJS.as.scala_languageFeature$higherKinds$ = (function(obj) { if ((ScalaJS.is.scala_languageFeature$higherKinds$(obj) || (obj === null))) { return obj } else { ScalaJS.throwClassCastException(obj, "scala.languageFeature$higherKinds") } }); ScalaJS.isArrayOf.scala_languageFeature$higherKinds$ = (function(obj, depth) { return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_languageFeature$higherKinds$))) }); ScalaJS.asArrayOf.scala_languageFeature$higherKinds$ = (function(obj, depth) { if ((ScalaJS.isArrayOf.scala_languageFeature$higherKinds$(obj, depth) || (obj === null))) { return obj } else { ScalaJS.throwArrayCastException(obj, "Lscala.languageFeature$higherKinds;", depth) } }); ScalaJS.data.scala_languageFeature$higherKinds$ = new ScalaJS.ClassTypeData({ scala_languageFeature$higherKinds$: 0 }, false, "scala.languageFeature$higherKinds$", ScalaJS.data.java_lang_Object, { scala_languageFeature$higherKinds$: 1, scala_languageFeature$higherKinds: 1, java_lang_Object: 1 }); ScalaJS.c.scala_languageFeature$higherKinds$.prototype.$classData = ScalaJS.data.scala_languageFeature$higherKinds$; ScalaJS.moduleInstances.scala_languageFeature$higherKinds = undefined; ScalaJS.modules.scala_languageFeature$higherKinds = (function() { if ((!ScalaJS.moduleInstances.scala_languageFeature$higherKinds)) { ScalaJS.moduleInstances.scala_languageFeature$higherKinds = new ScalaJS.c.scala_languageFeature$higherKinds$().init___() }; return ScalaJS.moduleInstances.scala_languageFeature$higherKinds }); //@ sourceMappingURL=languageFeature$higherKinds$.js.map /* global window document require */ (function(global, window, document, require) { "use strict"; // --------------------------------------------------------------------------- // Mini-apps demonstrating CITrap's functions. var CITrap = require("../../src/ci-trap"); // Example 0 -- export CITrap to play around. window.CITrap = CITrap; // end of Example 0 // Example 1 -- start-stop-send buttons var ciTrap = new CITrap(); window.ciTrap = ciTrap; var ex1StartButton = document.getElementById("ex1-start"), ex1StopButton = document.getElementById("ex1-stop"), ex1ShowBufferButton = document.getElementById("ex1-show-buffer"), ex1MarkButton = document.getElementById("ex1-mark"), ex1DebugButton = document.getElementById("ex1-debug"), ex1SendButton = document.getElementById("ex1-send"), stateSpan = document.getElementById("window-state"); ex1StartButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } ciTrap.start(); // Remove this when DOM-events are available in CITrap stateSpan.innerHTML = "processing"; }); ex1StopButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } ciTrap.stop(); // Remove this when DOM-events are available in CITrap stateSpan.innerHTML = "stopped"; }); ex1ShowBufferButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } var pre = document.getElementById("window-buffer"); pre.innerHTML = ciTrap.buffer(); }); ex1MarkButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } var markEvent = new window.Event("ct:mark"), markInput = document.getElementById("ex1-mark-input"), text = markInput.value; if (text) { markEvent.text = text; } if (ciTrap.element) { ciTrap.element.dispatchEvent(markEvent); } stateSpan.innerHTML = "sent"; }); ex1DebugButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } var debugEvent = new window.Event("ct:debug"); if (ciTrap.element) { ciTrap.element.dispatchEvent(debugEvent); } stateSpan.innerHTML = "sent"; }); ex1SendButton.addEventListener("click", function(event) { if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } ciTrap.send(false, function() {stateSpan.innerHTML = "sent";}); }); // end of Example 1 // --------------------------------------------------------------------------- })(this, window, document, require); elstgav/stair-climber import React from 'react' const LeaderboardListElement = ({ rank, leader }) => { const FEET_PER_FLIGHT = 13 function elevation(flights) { return `${(flights * FEET_PER_FLIGHT).toLocaleString()} ft` } return ( {rank} {leader.name} {elevation(leader.total)} ) } LeaderboardListElement.propTypes = { key: React.PropTypes.number, rank: React.PropTypes.number, leader: React.PropTypes.object, } export { LeaderboardListElement } import React, { Component } from 'react'; import Dialog from './dialog'; import ConstantGeneral from '../constants/general_constant'; import CoreBrain from '../core/brain'; class QuestionItem extends Component { constructor(props) { super(props); this.state = { showPromptDialog: false, showDialog: false, message: '', desc: '', isAnswerOk: false, showAnswerCorrect: false, showGameOver: false, winEasterEggs: false }; } checkAnswer (answerClicked, correctAnswer) { return (answerClicked == correctAnswer) ? true : false; } openConfirmationDialog() { this.setState({showPromptDialog: true, message: ConstantGeneral.DO_YOU_HAVE_SURE_THE_ANSWER}); } incrementPos(event) { let answerClicked = parseInt(event.target.getAttribute('target'), 10); let correctAnswer = this.props.correctAnswer; let isAnswerOk = this.checkAnswer(answerClicked, correctAnswer); this.setState({isAnswerOk: isAnswerOk}); this.openConfirmationDialog(); } callbackYes() { let newPos = this.props.position + 1; let valueSuccess = this.state.isAnswerOk ? this.props.valueSuccess + 1 : this.props.valueSuccess; let valueError = !this.state.isAnswerOk ? this.props.valueError + 1 : this.props.valueError; if (newPos === this.props.questions.length) { this.setState({ showDialog: false, showPromptDialog: false, showGameOver: true, winEasterEggs: CoreBrain.goalAim(this.props.valueSuccess) }); return; } this.props.onItemSelect(this.props.questions[newPos], newPos, valueSuccess, valueError, this.state.isAnswerOk); } callbackNo() { this.setState({showPromptDialog: false}); } callbackGameOver() { let that = this; let position = this.props.position; let item = this.props.questions[position]; let options = ['a', 'b', 'c', 'd']; let message = `A resposta correta é o item(${options[item.correct.position]})`; let desc = `${item.correct.desc}`; that.setState({showDialog: true, message: message, desc: desc}); } processAnswer() { this.state.isAnswerOk ? this.callbackYes() : this.callbackGameOver(); } renderGameOver() { var snd = new Audio("lose.ogg"); snd.play(); return ( ); } renderDialogNormal(isTryAgain) { return ( { this.callbackYes() }} type={ConstantGeneral.dialog.NORMAL} showMsgTryAgain={isTryAgain} description={this.state.desc} message={this.state.message} /> ); } renderDialogPrompt() { return ( { this.processAnswer() } } callbackNo={ () => { this.callbackNo() } } message={this.state.message} /> ); } renderList() { return (
  • this.incrementPos(event) } target={this.props.target} className="listItem"> {this.props.item}
  • ); } renderListDisabled() { return (
  • {this.props.item}
  • ); } render() { return (
    {this.state.showGameOver ? this.renderGameOver() : ''} {this.state.showPromptDialog ? this.renderDialogPrompt() : ''} {this.state.showDialog ? this.renderDialogNormal(true) : ''} {(this.props.disabled) ? this.renderListDisabled() : this.renderList() }
    ); } } export default QuestionItem;fastredRequire('template'); require('toolbar/toolbar.css.styl'); template('toolbar', require('toolbar/toolbar.pug'));/* eslint-disable no-invalid-this */ /** * Code originally borrowed from the Rapscallion project: * https://github.com/FormidableLabs/rapscallion/blob/44014d86a0855f7c3e438e6a9ee1e2ca07ff2cbe/src/render/state.js */ export function syncSetState (newState, cb) { // Mutation is faster and should be safe here. this.state = Object.assign( this.state, typeof newState === "function" ? newState(this.state, this.props) : newState ); if (cb) { cb.call(this); } } 2021/CVE-2021-25028/vultarget/event-tickets/src/modules/blocks/rsvp/advanced-options/template.js100-1000 /** * External dependencies */ import React, { Fragment, PureComponent } from 'react'; import PropTypes from 'prop-types'; import uniqid from 'uniqid'; /** * WordPress dependencies */ import { Dashicon } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import { Accordion } from '@moderntribe/common/elements'; import './style.pcss'; class RSVPAdvancedOptions extends PureComponent { static propTypes = { isDisabled: PropTypes.bool.isRequired, hasBeenCreated: PropTypes.bool, clientId: PropTypes.string, }; constructor( props ) { super( props ); this.accordionId = uniqid(); } getContent = () => ( ); getHeader = () => ( { __( 'Advanced Options', 'event-tickets' ) } ); getRows = () => ( [ { accordionId: this.accordionId, content: this.getContent(), contentClassName: 'tribe-editor__rsvp__advanced-options-content', header: this.getHeader(), headerAttrs: { disabled: this.props.isDisabled }, headerClassName: 'tribe-editor__rsvp__advanced-options-header', }, ] ); render() { return ( ); } } export default RSVPAdvancedOptions; bhavin-vadgama/bibtex /* Created at: 23 Sep 2018, Sun */ const bibtex = require("../index"); const bib = new bibtex(); const bibTeXTemplateForArticle = bib.getBibTeXTemplateFor('manual', 1); console.log(bibTeXTemplateForArticle); /* @manual{manualKey, article = {""}, book = {""}, booklet = {""}, conference = {""}, inbook = {""}, incollection = {""}, inproceedings = {""}, manual = {""} } */ const bibTeXTemplateForManual2 = bib.getBibTeXTemplateFor('manual', 2); console.log(bibTeXTemplateForManual2); /* @manual{manualKey, article = "", book = "", booklet = "", conference = "", inbook = "", incollection = "", inproceedings = "", manual = "" } */ const bibTeXTemplateForManual3 = bib.getBibTeXTemplateFor('manual', 3); console.log(bibTeXTemplateForManual3); /* @manual{manualKey, article = {}, book = {}, booklet = {}, conference = {}, inbook = {}, incollection = {}, inproceedings = {}, manual = {} } */ var interfaceorg_1_1onosproject_1_1openflow_1_1controller_1_1driver_1_1OpenFlowSwitchDriverFactory = [ [ "getOFSwitchImpl", "interfaceorg_1_1onosproject_1_1openflow_1_1controller_1_1driver_1_1OpenFlowSwitchDriverFactory.html#a5ea89376f8299ae1847f417e5a78e56e", null ] ];applications/iwo-action-integration/src/CWOM/Location.js10-100 module.exports = class Location { constructor(loc) { if(!loc) { loc = {}; } this.uuid = loc.uuid || ''; this.displayName = loc.displayName || ''; this.className = loc.className || ''; } };import { createSelector } from 'reselect'; const selectLogin = (state) => state.login; const makeSelectUsername = () => createSelector( selectLogin, (loginState) => loginState.username ); const makeSelectPassword = () => createSelector( selectLogin, (loginState) => loginState.password ); export { selectLogin, makeSelectUsername, makeSelectPassword }; test/bug/issue-1004-spec.js1000+ import F2 from '../../src/index'; const canvas = document.createElement('canvas'); canvas.style.width = '350px'; canvas.style.height = '300px'; document.body.appendChild(canvas); describe('issue 1004', () => { it('双y轴,getPosition', () => { const series = [ { type: 'www', date: '201805', AA: 70294 }, { type: 'www', date: '201806', AA: 72487 }, { type: 'www', date: '201807', AA: 73983 }, { type: 'www', date: '201808', AA: 74169 }, { type: 'www', date: '201809', AA: 74799 }, { type: 'www', date: '201810', AA: 72403 }, { type: 'eee', date: '201805', BB: 47273 }, { type: 'eee', date: '201806', BB: 48219 }, { type: 'eee', date: '201807', BB: 48757 }, { type: 'eee', date: '201808', BB: 49131 }, { type: 'eee', date: '201809', BB: 48868 }, { type: 'eee', date: '201810', BB: 47638 } ]; const chart = new F2.Chart({ el: canvas, syncY: true, pixelRatio: window.devicePixelRatio }); chart.source(series, { AA: { type: 'linear', ticks: [ 40000, 60000, 80000 ] }, BB: { type: 'linear', ticks: [ 40000, 60000, 80000 ] } }); chart.line().position('date*AA').color('type'); chart.line().position('date*BB').color('type'); chart.render(); // 第一个y轴 const position = chart.getPosition({ date: '201810', AA: 72403 }); expect(position.x).toBeCloseTo(278.9166768391927, 1); expect(position.y).toBeCloseTo(96.97921249999999, 1); // 第二个y轴 const position1 = chart.getPosition({ date: '201810', BB: 47638 }); expect(position1.x).toBeCloseTo(278.9166768391927, 1); expect(position1.y).toBeCloseTo(227.305025, 1); // 包含2部分数据 const position2 = chart.getPosition({ date: '201810', AA: 72403, BB: 47638 }); expect(position2.x).toBeCloseTo(278.9166768391927, 1); expect(position2.y).toBeCloseTo(96.97921249999999, 1); // 没有y轴数据 const position3 = chart.getPosition({ date: '201810' }); expect(position3.x).toBeCloseTo(278.9166768391927, 1); expect(position3.y).toBeNaN(); // 空对象 const position4 = chart.getPosition({ }); expect(position4.x).toBeNaN(); expect(position4.y).toBeNaN(); }); }); suraj-testing2/Flowers_Shoetraceur/src/node/require.js // Copyright 2013 Traceur Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. 'use strict'; var Module = require('module'); var traceur = require('./traceur.js'); var inlineAndCompileSync = require('./inline-module.js').inlineAndCompileSync; var TreeWriter = traceur.outputgeneration.TreeWriter; var ErrorReporter = traceur.util.ErrorReporter; var ext = '.traceur-compiled'; Module._extensions[ext] = function(module, filename) { module.filename = filename.slice(0, -ext.length); module._compile(module.compiledCode, module.filename); }; function compile(filename) { var reporter = new ErrorReporter(); var tree = inlineAndCompileSync([filename], null, reporter); if (reporter.hadError()) { // TODO(arv): Provide a SyntaxErrorReporter that throws a SyntaxError on the // first error. throw new Error(); } return TreeWriter.write(tree); } function traceurRequire(filename) { var source = compile(filename); var module = new Module(filename, require.main); module.compiledCode = source; module.load(filename + ext); return module.exports; }; var filters = []; var originalRequireJs = Module._extensions['.js']; function shouldCompile(filename) { if (filters.length === 0) return true; for (var i = 0; i < filters.length; i++) { if (filters[i].call(null, filename)) return true; } return false; } traceurRequire.makeDefault = function(filter) { if (!filter) filters = []; else filters.push(filter); Module._extensions['.js'] = function(module, filename) { if (shouldCompile(filename)) { var source = compile(filename) return module._compile(source, filename); } return originalRequireJs(module, filename); }; }; module.exports = traceurRequire; 1-10 /* globals expect, test */ import { CurvePoint } from '../CurvePoint' test('should be able to log an CurvePoint', () => { const curvePoint = new CurvePoint() log(curvePoint) }) test('should be able to modify a CurvePoint', () => { const curvePoint = new CurvePoint() expect(curvePoint.toJSON()).toEqual({ type: 'CurvePoint', pointType: 'Undefined', cornerRadius: 0, curveFrom: { x: 0, y: 0 }, curveTo: { x: 0, y: 0 }, point: { x: 0, y: 0 }, }) curvePoint.cornerRadius = 3 expect(curvePoint.cornerRadius).toBe(3) curvePoint.curveFrom = { x: 25, y: 3, } expect(curvePoint.curveFrom.toJSON()).toEqual({ x: 25, y: 3, }) curvePoint.curveTo = { x: 24, y: 4, } expect(curvePoint.curveTo.toJSON()).toEqual({ x: 24, y: 4, }) curvePoint.point = { x: 3, y: 4, } expect(curvePoint.point.toJSON()).toEqual({ x: 3, y: 4, }) }) import shouldRowUpdate from 'common/utils/RowComparer'; const columns = [{ id: 1, key: 'col1', width: 100 }, { id: 2, key: 'col2', width: 100 }]; const cellMetaData = { selected: { idx: 2, rowIdx: 3 }, dragged: null, copied: null }; const expandedRows = [{ key: 'col1' }, { key: 'col2' }]; describe('RowComparer shouldRowUpdate', () => { it('same props should not cause an update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData }; const nextProps = { columns: columns, cellMetaData: cellMetaData }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(false); }); it('forceUpdate should cause update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData, forceUpdate: true }; const nextProps = { columns: columns, cellMetaData: cellMetaData }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(true); }); it('different columns should cause update', () => { const newColumns = columns.slice(0); newColumns.push({ id: 3, key: 'col3, width: 100' }); const currentProps = { columns: columns, cellMetaData: cellMetaData }; const nextProps = { columns: newColumns, cellMetaData: cellMetaData }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(true); }); it('expanded rows should cause update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData }; const nextProps = { columns: columns, cellMetaData: cellMetaData, expandedRows }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(true); }); it('un-expanding rows should cause update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData, expandedRows }; const nextProps = { columns: columns, cellMetaData: cellMetaData }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(true); }); it('same expanded rows should not cause update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData, expandedRows }; const nextProps = { columns: columns, cellMetaData: cellMetaData, expandedRows }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(false); }); it('changing row extraClasses should cause update', () => { const currentProps = { columns: columns, cellMetaData: cellMetaData, extraClasses: 'row-added' }; const nextProps = { columns: columns, cellMetaData: cellMetaData, extraClasses: 'row-deleted' }; expect(shouldRowUpdate(nextProps, currentProps)).toBe(true); }); }); { "translatorID": "2abe2519-2f0a-48c0-ad3a-b87b9c059459", "label": "ebrary", "creator": "", "target": "^https?://site\\.ebrary\\.com/.+(docDetail|search|detail)\\.action\\?", "minVersion": "4.0", "maxVersion": "", "priority": 100, "inRepository": true, "translatorType": 4, "browserSupport": "gcv", "lastUpdated": "2015-08-29 22:03:15" } /* ebrary Translator Copyright (C) 2014 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ function detectWeb(doc, url) { if (url.indexOf("docDetail.action?") != -1 || url.indexOf("detail.action?") != -1) return "book"; else if (url.indexOf("search.action?") != -1) { if (ZU.xpathText(doc, '//div[@class="book_info_titlelist"]')) return "multiple"; } } function doWeb(doc, url) { if (detectWeb(doc, url) == "multiple") { items = {}; articles = []; var titles = ZU.xpath(doc, '//div[@class="book_info_titlelist"]/a[@class="title"]'); for (var i = 0; i < titles.length; i++) { items[titles[i].href] = titles[i].textContent; } Zotero.selectItems(items, function (items) { if (!items) { return true; } for (var i in items) { articles.push(genRisUrl(i)); } ZU.doGet(articles, scrape); }); } else { ZU.doGet(genRisUrl(url), function(text) { scrape(text, doc) }); } } function genRisUrl(url) { var id = url.match(/docID=[^&#]+/)[0]; var risurl = '/lib/alltitles/biblioExport.action?' + id; return risurl } function scrape(text, doc) { //Z.debug(text) var translator = Zotero.loadTranslator("import"); translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7"); translator.setString(text); translator.setHandler("itemDone", function (obj, item) { if (doc) { item.attachments.push({ document: doc, title: "ebrary Snapshot" }); } else if (item.url) { item.attachments.push({ url: item.url, title: "ebrary Snapshot", mimeType: "text/html" }); } item.complete(); }); translator.translate(); }/** BEGIN TEST CASES **/ var testCases = [ { "type": "web", "url": "http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10071244&p00=political+science", "items": [ { "itemType": "book", "title": "Routledge Studies in Science, Technology and Society : Biology and Political Science (1)", "creators": [ { "lastName": "Blank", "firstName": "Robert", "creatorType": "author" }, { "lastName": ".", "firstName": ".", "creatorType": "author" } ], "date": "2002", "ISBN": "9780203201329", "libraryCatalog": "ebrary", "place": "Abingdon, Oxon, US", "publisher": "Routledge", "shortTitle": "Routledge Studies in Science, Technology and Society", "url": "http://site.ebrary.com/lib/alltitles/docDetail.action?docID=10071244", "attachments": [ { "title": "ebrary Snapshot" } ], "tags": [ "Biopolitics.", "Political science.", "Sociobiology." ], "notes": [], "seeAlso": [] } ] }, { "type": "web", "url": "http://site.ebrary.com/lib/alltitles/search.action?p00=political+science&fromSearch=fromSearch&search=Search", "items": "multiple" } ] /** END TEST CASES **/node_modules/@babylonjs/core/Cameras/RigModes/stereoscopicAnaglyphRigMode.js import { Camera } from "../camera"; import { PassPostProcess } from "../../PostProcesses/passPostProcess"; import { AnaglyphPostProcess } from "../../PostProcesses/anaglyphPostProcess"; Camera._setStereoscopicAnaglyphRigMode = function (camera) { camera._rigCameras[0]._rigPostProcess = new PassPostProcess(camera.name + "_passthru", 1.0, camera._rigCameras[0]); camera._rigCameras[1]._rigPostProcess = new AnaglyphPostProcess(camera.name + "_anaglyph", 1.0, camera._rigCameras); }; //# sourceMappingURL=stereoscopicAnaglyphRigMode.js.mapLjCraft12/my-rig const {pages} = require('../locales/text'), Post = require('../models/userPost'), User = require('../models/userModel'); exports.getIndex = (req, res) => { Post.find() .then(post => { res.render('user/index', { pageTitle: pages.home, isAuthenticated: req.session.isLoggedIn, path: '/', post: post }) }) .catch(err => { console.log(`An error has occurred while fetching post please try again ${err}`) }) }; // exports.getSearch = (req, res, next) => { // res.render('user/search'); // }; exports.postSearch = (req, res, next) => { const search = req.body.search; console.log(`Here is your search parameters ${search}`); User.findOne({username: search}) .then(user => { if (!user) { console.log(user); return res.redirect('user/index'); } Post.find({userId: user._id}) .then(userPost => { res.render('user/search', { pageTitle: pages.search, isAuthenticated: req.session.isLoggedIn, path: '/search', post: userPost, query: search, user: user }) }) .catch(err => { console.log(`Error finding post for the queried user ${err}`); }) }) .catch(err => { console.log(`Error no user found matching that search`) }) };crimsonstrife/GoNorth if(Dropzone) { Dropzone.prototype.defaultOptions.dictDefaultMessage = "Drop file to upload"; Dropzone.prototype.defaultOptions.dictFallbackMessage = "Your browser does not support Drag'n'Drop upload."; Dropzone.prototype.defaultOptions.dictFallbackText = "Please use the old upload form."; Dropzone.prototype.defaultOptions.dictFileTooBig = "The file is too big ({{filesize}}MiB). Maximal file size: {{maxFilesize}}MiB."; Dropzone.prototype.defaultOptions.dictInvalidFileType = "Invalid file type."; Dropzone.prototype.defaultOptions.dictResponseError = "Server responsed with {{statusCode}} Code."; Dropzone.prototype.defaultOptions.dictCancelUpload = "Cancel upload"; Dropzone.prototype.defaultOptions.dictCancelUploadConfirmation = "Are you sure you want to cancel the upload?"; Dropzone.prototype.defaultOptions.dictRemoveFile = "Remove file"; Dropzone.prototype.defaultOptions.dictMaxFilesExceeded = "You can not upload any more files."; }examples/dojo/test/handleCleaner.js define(function () { 'use strict'; /** * @param {Object[]} handles The handles that should be cleaned up after each tests. * @returns {Function} The function that should be called after each tests to clean up the handles. */ return function (handles) { return function () { for (var handle = null; (handle = handles.shift());) { if (typeof handle.close === 'function') { handle.close(); } else if (typeof handle.remove === 'function') { handle.remove(); } else if (typeof handle.destroyRecursive === 'function') { handle.destroyRecursive(); } else if (typeof handle.destroy === 'function') { handle.destroy(); } else { throw new Error('Handle cannot be cleaned up.'); } } }; }; }); src/components/SectionService/index.js import React, { Component } from 'react' // import { withNamespaces } from 'react-i18next' import { Link, StaticQuery, graphql } from 'gatsby' import './style.scss' const SectionService = ({serviceTitle=null, serviceSubtitle=null, servicesHome}) => { const items = []; if (servicesHome.edges.length >0) { servicesHome.edges.forEach(service => { items.push({ id: service.node.id, cover: service.node.frontmatter.cover, title: service.node.frontmatter.title, category: service.node.frontmatter.category, shortDesc: service.node.frontmatter.shortDesc, excerpt: service.node.excerpt, date: service.node.fields.date, slug: service.node.fields.slug, position: service.node.frontmatter.position, // templateKey: postEdge.node.frontmatter.templateKey, }); }); } const slides = servicesHome? items.map((item, i=0) => { ++i; return (
    {i}

    {item.title}

    {item.shortDesc}

    ) }) :

    Chưa có dịch vụ nào

    return (

    {/* {t('service-title')} */} {serviceTitle}

    {/* {t('service-subtitle')} */} {serviceSubtitle}


    {/*
    */}
    {slides}
    ) } // export default withNamespaces('translation')(SectionService) export default SectionService; export const queryServiceHome = graphql` fragment SectionServiceFragment on Query { servicesHome: allMarkdownRemark( filter: {frontmatter: {templateKey: {eq: "service"}, active: {eq: true}}}, limit: 10 sort: { fields: [frontmatter___position], order: ASC } ) { totalCount edges { node { fields { slug date } id excerpt timeToRead frontmatter { title cover category shortDesc templateKey active position } } } } }` 0 import React, { Component } from 'react'; import { Image, StyleSheet, View, TouchableHighlight } from 'react-native'; import { Container, Header, Footer, FooterTab, Content, Card, CardItem, Thumbnail, Text, Button, Textarea, Icon, Left, Body, Right, Form, Item, Input, Label } from 'native-base'; import LinearGradient from 'react-native-linear-gradient'; //import Person from './Person'; //import GeoCoordinates from './GeoCoordinates'; class IncidentReportForm extends React.Component { render() { const { handleSubmit, person, description, geoCoordinates, cameraImage, } = this.props; // console.log('camera image:', cameraImage); return ( 252 way, Yaba, Lagos.
    `) } $('.saveBtn').on('click', function() { createActivityObject(createActivityId(), $(this).attr('data-time'), moment().format('MMDDYYYY'), $(this).prev('textarea').val()); showAllActivities(); }); showAllActivities(); }); zakaihamilton/screens1-10 /* @author @component KabFormat */ screens.kab.format = function KabFormat(me, { core, kab }) { me.process = function (wordsString, dict) { if (dict) { dict.map(function (item) { if ("enabled" in item && !item.enabled) { return; } if (item.match) { var checkInSplit = false; var itemSplit = "\n"; if ("split" in item) { itemSplit = core.string.regex(item.split); checkInSplit = item.split.startsWith("/"); } var itemJoin = itemSplit; if ("join" in item) { itemJoin = item.join; } wordsString = wordsString.split(itemSplit).map(function (selection) { selection = selection.trim(); var inSplit = selection.match(itemSplit); var matches = selection.match(core.string.regex(item.match)); if (matches && (inSplit || !checkInSplit)) { if (item.prefix) { selection = item.prefix + selection; } if (item.suffix) { selection += item.suffix; } var find = item.find; if (find) { selection = selection.replace(core.string.regex(find), core.string.regex(item.replace)); } } return selection; }).join(itemJoin); return; } var find = item.find; if (find && (item.prefix || item.suffix)) { wordsString = wordsString.split(core.string.regex(find)).join(item.replace); if (item.prefix) { wordsString = item.prefix + wordsString; } if (item.suffix) { wordsString = wordsString + item.suffix; } } else if (find) { wordsString = wordsString.replace(core.string.regex(find), core.string.regex(item.replace)); } if (item.start) { wordsString = item.start + wordsString; } if (item.end) { wordsString = wordsString + item.end; } }); } return wordsString; }; me.insert = function (words, wordIndex, collection, defaultWord, wordToInsert, text) { if (collection && wordToInsert) { for (var itemName in collection) { const item = collection[itemName]; if (!item.match) { continue; } if (itemName !== wordToInsert.toLowerCase()) { continue; } if (!defaultWord) { for (var altPrefix in collection) { var altPrefixItem = collection[altPrefix]; if (altPrefixItem.match && text.match(core.string.regex(altPrefixItem.match))) { defaultWord = altPrefix; if (wordToInsert[0] === wordToInsert[0].toUpperCase()) { defaultWord = defaultWord.charAt(0).toUpperCase() + defaultWord.slice(1); } wordToInsert = null; break; } } } break; } } if (defaultWord && !wordToInsert) { const item = collection[defaultWord.toLowerCase()]; if (item && item.replaceOnly) { defaultWord = null; } } if (defaultWord) { words.splice(wordIndex, 0, defaultWord); } else if (wordToInsert) { words.splice(wordIndex, 0, wordToInsert); } }; me.replace = function (wordsString, replacements) { if (replacements) { for (var groupName in replacements) { var groupItems = replacements[groupName]; for (var from in groupItems) { var to = groupItems[from]; if (from.startsWith("/")) { from = core.string.regex(from); } else { from = core.string.regex("/" + core.string.escape(from)); } wordsString = wordsString.replace(from, to); } } } return wordsString; }; me.replaceDuplicate = function (session, instance, replacement) { var words = instance.words; var wordIndex = instance.wordIndex; var collectIndex = wordIndex; var next = words[collectIndex++]; var wordOffset = 0; if (next !== "(" && next !== "[") { next = words[collectIndex++]; wordOffset++; } if (next === "(" || next === "[") { var duplicate = ""; for (; ;) { if (collectIndex > words.length) { break; } next = words[collectIndex++]; if (next === ")" || next === "]") { var addStyles = session.options.addStyles; session.options.addStyles = false; duplicate = kab.text.parseSingle(session, instance, duplicate, instance.depth + 1); duplicate = duplicate.replace(/“/g, ""); duplicate = duplicate.replace(/-/g, " "); duplicate = duplicate.replace(/”/g, ""); duplicate = duplicate.toLowerCase(); replacement = replacement.toLowerCase(); session.options.addStyles = addStyles; if (replacement.includes(duplicate)) { words.splice(wordIndex + wordOffset, collectIndex - wordIndex); } break; } if (duplicate) { duplicate += " " + next; } else { duplicate = next; } } } }; }; class Chess { constructor() { this.visualizer = new Visualizer(); this.games = []; this.move = -1 for (const game of CHESS_DATA) { this.games.push(new Game(game)) } this.done = false; } async Update() { if (this.done) { return; } this.move++; var aliveGames = 0; for (const game of this.games) { if (game.NextMove()) { aliveGames++; } } if (aliveGames == 0) { this.done = true; return; } const data = [ [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}] ]; for (const game of this.games) { if (game.ended) { continue; } for (const playerName in game.board) { for (const pieceName in game.board[playerName]) { const name = playerName + pieceName; for (const piece of game.board[playerName][pieceName]) { const dataPart = data[piece[1]][piece[0]]; if (dataPart[name] == null) { dataPart[name] = 0; } dataPart[name]++; } } } } for (let i = 0; i < data.length; i++) { const row = data[i]; for (let j = 0; j < row.length; j++) { const dataPart = row[j]; var max = 0, name = null; for (const pieceName in dataPart) { if (!['BP', 'WP'].includes(pieceName)) { if (dataPart[pieceName] > max) { name = pieceName; max = dataPart[pieceName]; } } } data[i][j] = name; } } this.visualizer.move = Math.floor(this.move / 2); this.visualizer.turn = this.move % 2 == 1; this.visualizer.board = data; } async Draw() { this.visualizer.Draw(); } }src/other/webscene/js/esri/widgets/metadata/base/InputBase.js define(["../../../core/declare", "dojo/_base/lang", "dojo/_base/array", "dojo/dom-attr", "dojo/dom-class", "dojo/dom-construct", "dojo/has", "./etc/docUtil", "./Templated", "../../../kernel"], function(declare, lang, array, domAttr, domClass, domConstruct, has, docUtil, Templated, esriKernel) { var oThisClass = declare([Templated], { _isGxeInput: true, _supportsMultipleValues: false, parentXNode: null, /* InputBase common properties, configurable */ hint: null, postCreate: function() { this.inherited(arguments); }, applyHint: function() { var v = this.hint; if(!this.hintNode || (typeof v === "undefined") || (v === null)) { return; } if(!this.parentXNode || !this.parentXNode.gxeDocument || this.parentXNode.gxeDocument.isViewOnly) { return; } v = lang.trim(v); if(v.length === 0) { return; } this.setNodeText(this.hintNode, v); domClass.add(this.hintNode, "populated"); }, applyViewOnly: function() { if(!this.viewOnlyNode) { return; } if(!this.parentXNode || !this.parentXNode.gxeDocument || !this.parentXNode.gxeDocument.isViewOnly) { return; } var v = this.getDisplayValue(); if((typeof v === "undefined") || (v === null)) { return; } if(v.push && (v.length === 1)) { v = v[0]; } if(v.push) { this.viewOnlyNode.innerHTML = ""; array.forEach(v, function(v2) { var nd = domConstruct.create("div", {"class": "gxeParagraph"}, this.viewOnlyNode); this.setNodeText(nd, v2); }, this); domClass.add(this.viewOnlyNode, "populated"); } else { this.setNodeText(this.viewOnlyNode, v); domClass.add(this.viewOnlyNode, "populated"); } }, connectXNode: function(parentXNode, isViewOnly) { // TODO: validate subTarget if(isViewOnly) { if(this.focusNode) { this.focusNode.disabled = true; } } else { this.applyHint(); } if(this.focusNode && parentXNode && parentXNode.fixed) { this.focusNode.disabled = true; } if(parentXNode && parentXNode.gxePath) { if(this.focusNode) { domAttr.set(this.focusNode, "data-gxe-for", parentXNode.gxePath); } else { domAttr.set(this.domNode, "data-gxe-for", parentXNode.gxePath); } } }, emitInteractionOccurred: function(params) { if(!params) { params = {inputWidget: this}; } this.emit("interaction-occurred", params); }, ensureFocus: function() { docUtil.ensureVisibility(this); if(this.focusNode) { this.focusNode.focus(); } }, getDisplayValue: function() { return this.getInputValue(); }, getInputValue: function() { return null; }, getXmlValue: function() { return this.getInputValue(); }, importValue: function(info, value) { this.setInputValue(value); }, importValues: function(info, values) { }, setInputValue: function(value) { } }); return oThisClass; });const CACHE_NAME = 'cache-v1'; const ASSETS = [ '/', '/index.html', '/js/scripts.js', '/css/styles.css', '/img/icon.png', '/img/icon.svg', ]; // https://mobiforge.com/design-development/pwa-minimus-a-minimal-pwa-checklist // https://simplabs.com/blog/2018/07/24/from-spa-to-pwa/ self.addEventListener('install', function (event) { event.waitUntil( caches.open(CACHE_NAME).then(function (cache) { return cache.addAll(ASSETS); }) ); }); self.addEventListener('fetch', function (event) { event.respondWith( caches.match(event.request).then(function (response) { return response || fetch(event.request); }) ); }); self.addEventListener('activate', function (event) { event.waitUntil( caches.keys().then(function (cacheNames) { return Promise.all( // delete old caches cacheNames.map(function (cacheName) { if (cacheName !== CACHE_NAME) { return caches.delete(cacheName); } }) ); }) ); }); 0 const sequelize = require("../db"); const { Sequelize, Model } = require("sequelize"); const User = require("../models/User"); const successfullOrderSchema = { userId: { type: Sequelize.INTEGER, allowNull: false, references: { model: User, key: "id" } }, userMail: { type: Sequelize.STRING, allowNull: true }, order_id: { type: Sequelize.STRING, allowNull: true }, order_value: { type: Sequelize.INTEGER, allowNull: false }, order_status: { type: Sequelize.STRING, defaultValue: "pending" }, cartItems: { type: Sequelize.ARRAY(Sequelize.TEXT), allowNull: false } }; class SuccessfullOrder extends Model {} SuccessfullOrder.init(successfullOrderSchema, { sequelize, tableName: "successfullOrders" }); module.exports = SuccessfullOrder;1-10 import React, {PureComponent} from 'react' import PropTypes from 'prop-types' import classNames from 'classnames' class List extends PureComponent { static displayName = 'List' static propTypes = { avatarList: PropTypes.bool, children: PropTypes.node, className: PropTypes.string, dense: PropTypes.bool, tagName: PropTypes.string, twoLine: PropTypes.bool, } static defaultProps = { tagName: 'ul', } render() { const { avatarList, children, className, dense, tagName, twoLine, ...otherProps, } = this.props const cssClasses = classNames({ 'mdc-list': true, 'mdc-list--avatar-list': avatarList, 'mdc-list--dense': dense, 'mdc-list--two-line': twoLine, }, className) return React.createElement( tagName, {...otherProps, className: cssClasses}, children ) } } export default List src/redux/actions/apiStatusActions.js import * as actionTypes from "./actionTypes"; export function beginApiCall() { return { type: actionTypes.BEGIN_API_CALL }; } export function endApiCall() { return { type: actionTypes.END_API_CALL }; } Yurii-Baluk/three.js export class Version { static isVersionHigherThan(version, checkVersion) { if (version != undefined) { checkVersion = checkVersion.replace(/[^\d.-]/g, '').split('.'); var givenVersion = version.replace(/[^\d.-]/g, '').split('.'); var flag = true; if (checkVersion.length != givenVersion.length) { return false; } for (var i = 0; i < checkVersion.length; i++) { var a = parseInt(checkVersion[i]); var b = parseInt(givenVersion[i]); flag &= (a >= b); } return flag; } return false; } static getInformalVersion() { return '2.0.1a'; } static getTechnicalVersion() { return '2.0.1a'; } }/* @flow */ import { createContext } from 'react'; type ThemeContextType = {| headerHeight: number, |}; const defaultContext: ThemeContextType = { headerHeight: 0 }; const ThemeContext = createContext(defaultContext); export default ThemeContext; 0 import { accountsController } from "./controllers/accounts-controller.js"; import { dashboardController } from "./controllers/dashboard-controller.js"; import { aboutController } from "./controllers/about-controller.js"; import { whereaboutController } from "./controllers/whereabout-controller.js"; import { jobController } from "./controllers/job-controller.js"; export const webRoutes = [ { method: "GET", path: "/", config: accountsController.index }, { method: "GET", path: "/signup", config: accountsController.showSignup }, { method: "GET", path: "/login", config: accountsController.showLogin }, { method: "GET", path: "/logout", config: accountsController.logout }, { method: "POST", path: "/register", config: accountsController.signup }, { method: "POST", path: "/authenticate", config: accountsController.login }, { method: "GET", path: "/about", config: aboutController.index }, { method: "GET", path: "/dashboard", config: dashboardController.index }, { method: "POST", path: "/dashboard/addwhereabout", config: dashboardController.addWhereabout }, { method: "GET", path: "/dashboard/deletewhereabout/{id}", config: dashboardController.deleteWhereabout }, { method: "GET", path: "/whereabout/{id}", config: whereaboutController.index }, { method: "POST", path: "/whereabout/{id}/addjob", config: whereaboutController.addJob }, { method: "GET", path: "/whereabout/{id}/deletejob/{jobid}", config: whereaboutController.deleteJob }, { method: "GET", path: "/job/{id}/editjob/{jobid}", config: jobController.index }, { method: "POST", path: "/job/{id}/updatejob/{jobid}", config: jobController.update }, { method: "GET", path: "/{param*}", handler: { directory: { path: "./public" } }, options: { auth: false } }, ];import React, { Component } from "react"; import axiosApiInstance from '../helper.js'; import { IdeaBox } from '../components/index.js'; class Trash extends Component { constructor(props){ super(props); this.state = { ideasList: [] } } // on mount, load subscriptions componentDidMount() { axiosApiInstance.get(`/api/get_trash`, {}).then(response => { this.setState({ ideasList: response.data.ideas }); }); } deleteForever() { axiosApiInstance.delete('/api/delete_idea/') } render() { if (this.state.ideasList.length === 0) { return (

    Apparently you don't make any mistakes...

    Your trash is empty

    ) } return (
    {this.state.ideasList.map((idea, index) => (

    Deleting on {idea.delete_date}:

    { axiosApiInstance.post(`/api/restore_idea/${idea._id}`).then(() => { document.getElementById(`trash${idea._id}`).innerHTML = "Idea restored"; }) }}>Restore



    { axiosApiInstance.delete(`/api/delete_idea/${idea._id}`).then(() => { document.getElementById(`trash${idea._id}`).innerHTML = "Idea deleted"; }) }}>Delete forever

    ))}
    ) } } export default Trash; alvino/agroadm import React from "react"; import { useRouter } from "next/router"; import CardSettings from "components/Cards/CardSettings"; import FormPasto from "components/Forms/FormPasto"; export default function CardPastoSettings() { const router = useRouter(); const query = router.query; const { fazenda } = router.query; function handleSucesso() { router.push(`/admin/${fazenda}/dashboard`); } return ( <> ); } 10-100 import { connect } from 'react-redux'; import * as constants from 'utils/constants'; import { turnOnCarouselComplaintHeaderEditMode, turnOffCarouselComplaintHeaderEditMode, } from 'actions/landing-page/complaint-summaries'; import { cardsSelector, getCarouselComplaintHeaderEditModeOn, } from 'selectors/landing-page/complaint-summaries'; import ComplaintSummaries from 'components/landing-page/complaint-summaries'; import { getCMSFields } from 'selectors/cms'; import { updatePage } from 'actions/cms'; import { mergeEditWrapperStateProps } from 'utils/container'; import { addOrRemoveItemInPinboard } from 'actions/pinboard'; function mapStateToProps(state, ownProps) { return { cards: cardsSelector(state), fields: getCMSFields(constants.LANDING_PAGE_ID)(state), sectionEditModeOn: getCarouselComplaintHeaderEditModeOn(state), pathname: ownProps.pathname, }; } const mapDispatchToProps = { onSaveForm: updatePage(constants.LANDING_PAGE_ID), turnOnSectionEditMode: turnOnCarouselComplaintHeaderEditMode, turnOffSectionEditMode: turnOffCarouselComplaintHeaderEditMode, addOrRemoveItemInPinboard: addOrRemoveItemInPinboard, }; export default connect( mapStateToProps, mapDispatchToProps, mergeEditWrapperStateProps )(ComplaintSummaries); commands/Administrator/set.js10-100 const fs = require("fs"); const parameters = [ "\n-prefix : set guild's custom prefix. (use \"default\" to use miku's default prefix)", '-welcome : set guild\'s greeting channel. (use "off" to turn off the feature)' ].join("\n"); exports.run = (bot, message, args) => { let prefix, welcome, star; prefix = bot.db.get("guildConf", `${message.guild.id}.prefix`); // prettier-ignore bot.db.get("guildConf", `${message.guild.id}.greetingChannel`) == null ? welcome = "not specified!" : welcome = bot.channels.get(bot.db.get("guildConf", `${message.guild.id}.greetingChannel`)).name; // prettier-ignore bot.db.get("guildConf", `${message.guild.id}.star.starChannel`) == null ? star = "not specified!" : star = bot.channels.get(bot.db.get("guildConf", `${message.guild.id}.star.starChannel`)).name; // prettier-ignore if (!args[0]) return message.channel.send(`prefix :: ${prefix} welcome-channel :: ${welcome} star :: ${star}`, { code: "asciidoc" } ); // SWITCH switch (args[0]) { // welcome case "-greet": case "-greeting": case "-welcome": // if no channel is mentioned // prettier-ignore if (!args[1]) return message.channel.send("Please mention a channel for me or use `off` to turn off!"); // parameter to turn off greeting system if (args[1].toLowerCase() == "off") { bot.db.set("guildConf", null, `${message.guild.id}.greetingChannel`); message.channel.send("Turned off greeting!"); } else { // prettier-ignore if (!message.mentions.channels.first()) return message.channel.send("Please mention a channel for me!"); // prettier-ignore bot.db.set("guildConf", message.mentions.channels.first().id, `${message.guild.id}.greetingChannel`); message.channel.send("Aight, I've set the greeting channel!"); } break; // prefix case "-p": case "-pref": case "-prefix": // parameter to use default prefix if (args[1].toLowerCase() == "default") { bot.db.set("guildConf", "q", `${message.guild.id}.prefix`); message.channel.send("Reseted to default prefix!"); } else { // prettier-ignore if (!args[1] || args[1].length > 1) return message.channel.send("Please input one length of custom prefix."); bot.db.set("guildConf", args[1], `${message.guild.id}.prefix`); // prettier-ignore message.channel.send(`Changed my prefix in this guild to \`${args[1]}\``); } break; // starboard case "-star": // parameter to turn off starboard system if (args[1] == "off") { bot.db.set("guildConf", null, `${message.guild.id}.star.starChannel`); return message.channel.send("Turned off star system!"); } // prettier-ignore if (!message.mentions.channels.first()) return message.channel.send("No channel selected!"); // prettier-ignore bot.db.set("guildConf", message.mentions.channels.first().id, `${message.guild.id}.star.starChannel`); // prettier-ignore message.channel.send(`I\'ve set \`#${message.mentions.channels.first().name}\` as star channel!`); break; // DEFAULT VALUE default: message.channel.send("Invalid Parameter(s)!"); } }; exports.conf = { aliases: [], cooldown: 1, guildOnly: true, userPerm: ["MANAGE_GUILD"], botPerm: [""] }; exports.help = { name: "set", category: "Administrator", description: "Guild configuration", usage: "set -", param: parameters }; /** * your-score * * (c) 2019 , , , */ module.exports = { 'extends': 'prettier', 'plugins': ['prettier'], 'rules': { 'prettier/prettier': 'error' }, 'parserOptions': { 'ecmaVersion': 2018, 'sourceType': 'module', 'ecmaFeatures': { 'impliedStrict': true } }, 'env': { 'browser': true, 'commonjs': true, 'node': true, 'es6': true, } }; benrick/awesome-notifications import "jsdom-global/register" import "chai/register-should" import Modal from "../src/modal" import Options from "../src/defaults" describe("Modal", function() { const modalDefaults = { html: "test-message", type: "confirm", parent: document.body } const defaults = new Options() this.timeout((defaults.duration + defaults.animationDuration) * 2) function newmodal() { return new Modal(modalDefaults.html, modalDefaults.type, defaults) } function clearParent() { while (modalDefaults.parent.firstChild) { modalDefaults.parent.removeChild(modalDefaults.parent.firstChild) } } let modal before(() => { clearParent() }) describe("constructor()", () => { before(() => { modal = newmodal() }) it("should make a newNode", () => { should.exist(modal.newNode) }) it("should set a parent", () => { should.equal(modal.parent, modalDefaults.parent) }) describe("newNode", () => { it("should have id", () => { should.exist(modal.newNode.id) }) it("should have style.cssText", () => { should.exist(modal.newNode.style.cssText) }) it("should have innerHTML", () => { should.exist(modal.newNode.innerHTML) }) it("should have proper nodeName", () => { should.equal(modal.newNode.nodeName, "DIV") }) it("should be in the DOM", () => { should.exist(document.getElementById(modal.newNode.id)) }) }) }) }) //Tellurium APIs to replace selenium APIs or new APIs function getTargetXY(element, coordString) { // Parse coordString var coords = null; var x; var y; if (coordString) { coords = coordString.split(/,/); x = Number(coords[0]); y = Number(coords[1]); } else { x = y = 0; } var offset = teJQuery(element).offset(); return [offset.left + x, offset.top + y]; } function TelluriumApi(cache){ this.cache = cache; this.textWorker = new TextUiWorker(); this.toggleWorker = new ToggleUiWorker(); this.colorWorker = new ColorUiWorker(); // this.decoratorWorker = new DecorateUiWorker(); // this.outlineVisitor = new UiOutlineVisitor(); // this.collectVisitor = new UiCollectVisitor(); // this.tipVisitor = new UiSimpleTipVisitor(); // this.chainVisitor = new STreeChainVisitor(); this.ctrl = false; this.shift = false; this.alt = false; this.meta = false; this.cssBuilder = new JQueryBuilder(); } TelluriumApi.prototype.cacheAwareLocate = function(locator){ //This is not really elegant, but we have to share this //locate strategy with Selenium. Otherwise, call Tellurium //methods directly. !tellurium.logManager.isUseLog || fbLog("Trying to find element with locator ", locator); return selenium.browserbot.findElement(locator); }; TelluriumApi.prototype.blur = function(locator) { var element = this.cacheAwareLocate(locator); teJQuery(element).blur(); }; TelluriumApi.prototype.click = function(locator) { var element = this.cacheAwareLocate(locator); !tellurium.logManager.isUseLog || fbLog("clicking on element ", element); if (element.href || element.url) { if (teJQuery.browser.msie) { element.fireEvent("onclick"); } else { // var evObj = document.createEvent('HTMLEvents'); var evObj = document.createEvent('MouseEvents'); evObj.initEvent('click', true, true); element.dispatchEvent(evObj); } } else { teJQuery(element).click(); } /* var $elem = teJQuery(element); if(element.href){ $elem.click(function() { selenium.browserbot.currentWindow.location = teJQuery(this).attr('href'); }); }else if(element.url){ $elem.click(function() { selenium.browserbot.currentWindow.location = teJQuery(this).attr('url'); }); } $elem.click(); */ }; TelluriumApi.prototype.clickAt = function(locator, coordString) { var element = this.cacheAwareLocate(locator); var clientXY = getTargetXY(element, coordString); //TODO: how to do click at using jQuery teJQuery(element).click(); }; TelluriumApi.prototype.doubleClick = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).dblclick(); }; TelluriumApi.prototype.fireEvent = function(locator, event){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger(event); }; TelluriumApi.prototype.focus = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).focus(); }; TelluriumApi.prototype.typeKey = function(locator, key){ var element = this.cacheAwareLocate(locator); var $elem = teJQuery(element); $elem.val($elem.val()+key).trigger(getEvent("keydown", key ,this)).trigger(getEvent("keypress", key, this)).trigger(getEvent("keyup", key, this)); }; TelluriumApi.prototype.keyDown = function(locator, key){ !tellurium.logManager.isUseLog || fbLog("Key Down cache aware locate", locator); var element = this.cacheAwareLocate(locator); var $elem = teJQuery(element); $elem.val($elem.val()).trigger(getEvent("keydown", key ,this)); }; TelluriumApi.prototype.keyPress = function(locator, key){ var element = this.cacheAwareLocate(locator); var $elem = teJQuery(element); $elem.val($elem.val()+key).trigger(getEvent("keypress", key , this)); }; TelluriumApi.prototype.keyUp = function(locator, key){ var element = this.cacheAwareLocate(locator); var $elem = teJQuery(element); $elem.val($elem.val()).trigger(getEvent("keyup", key , this)); }; TelluriumApi.prototype.altKeyUp = function(){ !tellurium.logManager.isUseLog || fbLog("ALT key up ", this); this.alt = true; }; TelluriumApi.prototype.altKeyDown = function(){ !tellurium.logManager.isUseLog || fbLog("ALT key down ", this); this.alt = false; }; TelluriumApi.prototype.ctrlKeyUp = function(){ !tellurium.logManager.isUseLog || fbLog("CTRL key up ", this); this.ctrl = true; }; TelluriumApi.prototype.ctrlKeyDown = function(){ !tellurium.logManager.isUseLog || fbLog("CTRL key down ", this); this.ctrl = false; }; TelluriumApi.prototype.shiftKeyUp = function(){ !tellurium.logManager.isUseLog || fbLog("SHIFT key up ", this); this.shift = true; }; TelluriumApi.prototype.shiftKeyDown = function(){ !tellurium.logManager.isUseLog || fbLog("SHIFT key down ", this); this.shift = false; }; TelluriumApi.prototype.metaKeyUp = function(){ !tellurium.logManager.isUseLog || fbLog("META key up ", this); this.meta = true; }; TelluriumApi.prototype.metaKeyDown = function(){ !tellurium.logManager.isUseLog || fbLog("META key down ", this); this.meta = false; }; TelluriumApi.prototype.mouseOver = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger('mouseover'); }; TelluriumApi.prototype.mouseDown = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger('mousedown'); }; TelluriumApi.prototype.mouseDownRight = function(locator){ var element = this.cacheAwareLocate(locator); //TODO: how to fire right mouse down in jQuery? // teJQuery(element).trigger('mousedown'); }; TelluriumApi.prototype.mouseEnter = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger('mouseenter'); }; TelluriumApi.prototype.mouseLeave = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger('mouseleave'); }; TelluriumApi.prototype.mouseOut = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).trigger('mouseout'); }; TelluriumApi.prototype.submit = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).submit(); }; TelluriumApi.prototype.check = function(locator){ var element = this.cacheAwareLocate(locator); element.checked = true; }; TelluriumApi.prototype.uncheck = function(locator){ var element = this.cacheAwareLocate(locator); element.checked = false; }; TelluriumApi.prototype.isElementPresent = function(uid){ if(this.cache.cacheOption){ var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObject(context, uid); !tellurium.logManager.isUseLog || fbLog("Found cached element for isElementPresented", obj); return obj != null; } else { var element = selenium.browserbot.findElementOrNull(uid); !tellurium.logManager.isUseLog || fbLog("Found element for isElementPresented", element); return element != null; } }; /* TelluriumApi.prototype.isElementPresent = function(locator){ var element = selenium.browserbot.findElementOrNull(locator); // this.cacheAwareLocate(locator); !tellurium.logManager.isUseLog || fbLog("Found element for isElementPresented", element); return element != null; };*/ TelluriumApi.prototype.getAttribute = function(attributeLocator){ var cal = JSON.parse(attributeLocator.substring(7)); !tellurium.logManager.isUseLog || fbLog("Parsed attribute locator", cal); var locator = cal.locator; var attributeName = null; //get attribute name var attributePos = locator.lastIndexOf("@"); if (attributePos != -1) { attributeName = locator.slice(attributePos + 1); if (endsWith(attributeName, "]")) { attributeName = attributeName.substr(0, attributeName.length - 1); } !tellurium.logManager.isUseLog || fbLog("attribute name", attributeName); //update locator cal.locator = locator.slice(0, attributePos); if (endsWith(cal.locator, "[")) { cal.locator = cal.locator.substr(0, cal.locator.length - 1); } } var json = "uimcal=" + JSON.stringify(cal); !tellurium.logManager.isUseLog || fbLog("re-jsonified locator", json); var element = this.cacheAwareLocate(json); return teJQuery(element).attr(attributeName); }; TelluriumApi.prototype.waitForPageToLoad = function(timeout){ selenium.doWaitForPageToLoad(timeout); }; TelluriumApi.prototype.type = function(locator, val){ var element = this.cacheAwareLocate(locator); teJQuery(element).val(val); }; TelluriumApi.prototype.getOptionSelector = function(optionLocator){ var split = optionLocator.split("="); var sel = ""; split[0] = trimString(split[0]); split[1] = trimString(split[1]); if(split[0] == "label" || split[0] == "text"){ sel = this.cssBuilder.buildText(split[1]); }else if(split[0] == "value"){ sel = this.cssBuilder.buildAttribute(split[0], split[1]); }else if(split[0] == "index"){ var inx = parseInt(split[1]) - 1; sel = ":eq(" + inx + ")" }else if(split[0] == "id"){ sel = this.cssBuilder.buildId(split[1]); }else{ fbError("Invalid Selector optionLocator " + optionLocator, split); throw new SeleniumError("Invalid Selector optionLocator " + optionLocator); } return sel; }; TelluriumApi.prototype.getSelectOptions = function(selectLocator) { var element = this.cacheAwareLocate(selectLocator); var selectOptions = []; for (var i = 0; i < element.options.length; i++) { var option = element.options[i].text; selectOptions.push(option); } return selectOptions; }; TelluriumApi.prototype.getSelectValues = function(selectLocator) { var element = this.cacheAwareLocate(selectLocator); var selectValues = []; for (var i = 0; i < element.options.length; i++) { var option = element.options[i].value; selectValues.push(option); } return selectValues; }; TelluriumApi.prototype.select = function(locator, optionLocator){ var element = this.cacheAwareLocate(locator); var $sel = teJQuery(element); //first, remove all selected element $sel.find("option").removeAttr("selected"); //construct the select option // var opt = "option[" + optionLocator + "]"; var opt = "option" + this.getOptionSelector(optionLocator); !tellurium.logManager.isUseLog || fbLog("For optionLocator " + optionLocator + ", opt " + opt, $sel); //select the appropriate option $sel.find(opt).attr("selected","selected"); // $sel.find(opt).each(function() { // teJQuery(this).attr("selected","selected"); // }); if (teJQuery.browser.msie) { element.fireEvent("onchange"); } else { var evObj = document.createEvent('HTMLEvents'); evObj.initEvent('change', true, true); element.dispatchEvent(evObj); } }; TelluriumApi.prototype.addSelection = function(locator, optionLocator){ var element = this.cacheAwareLocate(locator); var $sel = teJQuery(element); //construct the select option // var opt = "option[" + optionLocator + "]"; var opt = this.getOptionSelector(optionLocator); //select the appropriate option $sel.find(opt).attr("selected","selected"); }; TelluriumApi.prototype.removeSelection = function(locator, optionLocator){ var element = this.cacheAwareLocate(locator); var $sel = teJQuery(element); //construct the select option // var opt = "option[" + optionLocator + "]"; var opt = this.getOptionSelector(optionLocator); //select the appropriate option $sel.find(opt).removeAttr("selected"); }; TelluriumApi.prototype.removeAllSelections = function(locator){ var element = this.cacheAwareLocate(locator); var $sel = teJQuery(element); //first, remove all selected element $sel.find("option").removeAttr("selected"); }; TelluriumApi.prototype.findSelectedOptionProperties = function(locator, property) { var element = this.cacheAwareLocate(locator); if (!("options" in element)) { throw new SeleniumError("Specified element is not a Select (has no options)"); } var $selected = teJQuery(element).find("option:selected"); var selectedOptions = []; $selected.each(function() { selectedOptions.push(this[property]); }); return selectedOptions; }; TelluriumApi.prototype.getSelectedLabel = function(selectLocator){ var options = this.findSelectedOptionProperties(selectLocator, "text"); if(options.length > 1){ fbWarn("Multiple Selected options ", options); } return options[0]; }; TelluriumApi.prototype.getSelectedLabels = function(selectLocator){ return this.findSelectedOptionProperties(selectLocator, "text"); }; TelluriumApi.prototype.getSelectedValue = function(selectLocator){ var options = this.findSelectedOptionProperties(selectLocator, "value"); if(options.length > 1){ fbWarn("Multiple Selected options ", options); } return options[0]; }; TelluriumApi.prototype.getSelectedValues = function(selectLocator){ return this.findSelectedOptionProperties(selectLocator, "value"); }; TelluriumApi.prototype.open = function(url){ selenium.open(url); }; TelluriumApi.prototype.getText = function(locator) { var element = this.cacheAwareLocate(locator); return teJQuery(element).text(); }; TelluriumApi.prototype.isChecked = function(locator) { var element = this.cacheAwareLocate(locator); if (element.checked == null) { throw new SeleniumError("Element is not a toggle-button."); } return element.checked; }; TelluriumApi.prototype.isVisible = function(locator) { var element = teJQuery(this.cacheAwareLocate(locator)); var isHiddenCSS = element.css("visibility")=="hidden"? true:false; var isHidden = element.is(":hidden"); if(isHidden){ return false; } else if(isHiddenCSS){ return false; } else { return true; } }; TelluriumApi.prototype.isEditable = function(locator) { var element = this.cacheAwareLocate(locator); if (element.value == undefined) { Assert.fail("Element " + locator + " is not an input."); } if (element.disabled) { return false; } var readOnlyNode = element.getAttributeNode('readonly'); if (readOnlyNode) { // DGF on IE, every input element has a readOnly node, but it may be false if (typeof(readOnlyNode.nodeValue) == "boolean") { var readOnly = readOnlyNode.nodeValue; if (readOnly) { return false; } } else { return false; } } return true; }; TelluriumApi.prototype.getXpathCount = function(xpath) { return selenium.getXpathCount(xpath); }; //// NEW APIS TelluriumApi.prototype.getAllText = function(locator) { var element = this.cacheAwareLocate(locator); var out = []; var $e = teJQuery(element); $e.each(function() { out.push(teJQuery(this).text()); }); // return JSON.stringify(out); return out; }; TelluriumApi.prototype.getCssSelectorCount = function(locator) { !tellurium.logManager.isUseLog || fbLog("GetCssSelectorCount for Locator", locator); // if(locator.startsWith("jquery=")){ if(startsWith(locator, "jquery=")){ locator = locator.substring(7); // }else if(locator.startsWith("uimcal=")){ }else if(startsWith(locator,"uimcal=")){ var cal = JSON.parse(locator.substring(7)); locator = cal.locator; } !tellurium.logManager.isUseLog || fbLog("Parsed locator", locator); var elem = selenium.browserbot.findElementOrNull(locator); if(elem == null) return 0; var $e = teJQuery(elem); !tellurium.logManager.isUseLog || fbLog("Found elements for CSS Selector", $e.get()); return $e.length; }; TelluriumApi.prototype.getCSS = function(locator, cssName) { var element = this.cacheAwareLocate(locator); var out = []; var $e = teJQuery(element); for(var i=0; i<$e.length; i++){ var elem = $e.get(i); var val = teJQuery(elem).css(cssName); //need to walk up the tree if the color is transparent if(val == "transparent" && (cssName == "background-color" || cssName == "backgroundColor" || cssName == "color")){ val = getColor(elem, cssName); } out.push(val); } return out; }; TelluriumApi.prototype.isDisabled = function(locator) { var element = this.cacheAwareLocate(locator); var $e = teJQuery(element); if ($e == null || $e.length < 1) Assert.fail("Cannot find Element for " + locator); if ($e.length > 1) Assert.fail("Element for " + locator + " is not unique."); return $e.attr('disabled'); }; TelluriumApi.prototype.getListSize = function(locator, separators) { var element = this.cacheAwareLocate(locator); var $e = teJQuery(element); if ($e == null || $e.length < 1) Assert.fail("Cannot find Element for " + locator); //TODO: this may not be correct for example we have div/div/div span/span, what would $(().find("div, span") return? // var jq = separators.join(",") // var list = $e.find(separators); var list = $e.children(separators); return list.length; }; TelluriumApi.prototype.getCacheState = function(){ return this.cache.cacheOption; }; TelluriumApi.prototype.enableCache = function(){ this.cache.cacheOption = true; }; TelluriumApi.prototype.disableCache = function(){ this.cache.cacheOption = false; }; TelluriumApi.prototype.cleanCache = function(){ this.cache.cleanCache(); }; TelluriumApi.prototype.setCacheMaxSize = function(size){ this.cache.maxCacheSize = size; }; TelluriumApi.prototype.getCacheSize = function(){ return this.cache.getCacheSize(); }; TelluriumApi.prototype.getCacheMaxSize = function(){ return this.cache.maxCacheSize; }; TelluriumApi.prototype.getCacheUsage = function(){ return this.cache.getCacheUsage(); }; TelluriumApi.prototype.addNamespace = function(prefix, namespace){ selenium.browserbot.addNamespace(prefix, namespace); }; TelluriumApi.prototype.getNamespace = function(prefix){ return selenium.browserbot._namespaceResolver(prefix); }; TelluriumApi.prototype.useDiscardNewCachePolicy = function(){ this.cache.useDiscardNewPolicy(); }; TelluriumApi.prototype.useDiscardOldCachePolicy = function(){ this.cache.useDiscardOldPolicy(); }; TelluriumApi.prototype.useDiscardLeastUsedCachePolicy = function(){ this.cache.useDiscardLeastUsedPolicy(); }; TelluriumApi.prototype.useDiscardInvalidCachePolicy = function(){ this.cache.useDiscardInvalidPolicy(); }; TelluriumApi.prototype.getCachePolicyName = function(){ return this.cache.getCachePolicyName(); }; TelluriumApi.prototype.getUseUiModule = function(jsonarray){ return this.cache.useUiModule(jsonarray); }; TelluriumApi.prototype.getValidateUiModule = function(jsonarray){ return this.cache.validateUiModule(jsonarray); }; TelluriumApi.prototype.isUiModuleCached = function(id){ return this.cache.isUiModuleCached(id); }; TelluriumApi.prototype.useClosestMatch = function(isUse){ this.cache.useClosestMatch(isUse); }; TelluriumApi.prototype.useTeApi = function(isUse){ tellurium.useTeApi(isUse); }; TelluriumApi.prototype.toggle = function(locator){ var element = this.cacheAwareLocate(locator); teJQuery(element).toggle(); }; TelluriumApi.prototype.deleteAllCookiesByJQuery = function() { teJQuery.cookies.del(true); }; TelluriumApi.prototype.deletelCookieByJQuery = function(cookieName) { teJQuery.cookies.del(cookieName); }; TelluriumApi.prototype.setCookieByJQuery = function(cookieName, value, options){ teJQuery.cookies.set(cookieName, value, options); }; TelluriumApi.prototype.getCookieByJQuery = function(cookieName){ return teJQuery.cookies.get(cookieName); }; TelluriumApi.prototype.updateEngineState = function(state){ tellurium.cache.useClosestMatch(state.relax); tellurium.useTeApi(state.teApi); tellurium.cache.cacheOption = state.cache; }; TelluriumApi.prototype.getEngineState = function(){ var state = new EngineState(); state.relax = tellurium.cache.uiAlg.allowRelax; state.teApi = tellurium.isUseTeApi; state.cache = tellurium.cache.cacheOption; return state; }; TelluriumApi.prototype.getAllTableBodyText = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getAllBodyCell")){ var out = obj.getAllBodyCell(context, this.textWorker); !tellurium.logManager.isUseLog || fbLog("Get All Table Body Text Result", out); return out; } return null; }; TelluriumApi.prototype.getTeListSize = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getListSize")){ var out = obj.getListSize(context); !tellurium.logManager.isUseLog || fbLog("Get List Size Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableHeaderColumnNum = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getHeaderColumnNum")){ var out = obj.getHeaderColumnNum(context); !tellurium.logManager.isUseLog || fbLog("Get getHeaderColumnNum Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableFootColumnNum = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getFooterColumnNum")){ var out = obj.getFooterColumnNum(context); !tellurium.logManager.isUseLog || fbLog("Get getFooterColumnNum Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableRowNum = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getTableRowNum")){ var out = obj.getTableRowNum(context); !tellurium.logManager.isUseLog || fbLog("Get getTableRowNum Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableColumnNum = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getTableColumnNum")){ var out = obj.getTableColumnNum(context); !tellurium.logManager.isUseLog || fbLog("Get getTableColumnNum Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableRowNumForTbody = function(uid, ntbody) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getTableRowNumForTbody")){ var out = obj.getTableRowNumForTbody(context, ntbody); !tellurium.logManager.isUseLog || fbLog("Get getTableRowNumForTbody Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableColumnNumForTbody = function(uid, ntbody) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getTableColumnNumForTbody")){ var out = obj.getTableColumnNumForTbody(context, ntbody); !tellurium.logManager.isUseLog || fbLog("Get getTableColumnNumForTbody Result", out); return out; } return 0; }; TelluriumApi.prototype.getTeTableTbodyNum = function(uid) { var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getTableTbodyNum")){ var out = obj.getTableTbodyNum(context); !tellurium.logManager.isUseLog || fbLog("Get getTableTbodyNum Result", out); return out; } return 0; }; TelluriumApi.prototype.getRepeatNum = function(uid){ var context = new WorkflowContext(); context.alg = this.cache.uiAlg; var obj = this.cache.walkToUiObjectWithException(context, uid); if(obj.respondsToWithException("getRepeatNum")){ var out = obj.getRepeatNum(context); !tellurium.logManager.isUseLog || fbLog("Get getRepeatNum Result", out); return out; } return 0; }; /* TelluriumApi.prototype.getAllTableBodyText = function(uid) { var context = new WorkflowContext(); var obj = this.cache.walkToUiObject(context, uid); if(obj == null){ fbError("Cannot find UI object " + uid, this); throw new SeleniumError("Cannot find UI object " + uid); }else{ if(obj["getAllBodyCell"] != undefined){ var out = obj.getAllBodyCell(context, this.textWorker); !tellurium.logManager.isUseLog || fbLog("Get All Table Body Text Result", out); return out; }else{ fbError("UI Object " + uid + " does not have the method getAllBodyCell", obj); throw new SeleniumError("UI Object " + uid + " does not have the method getAllBodyCell"); } } };*/ //TelluriumApi.prototype.showUi = function(uid, delay){ // var context = new WorkflowContext(); // var elist = this.cache.getIndexedTree(context, uid); // this.toggleWorker.work(context, elist, delay); // this.colorWorker.work(context, elist, delay); // this.decoratorWorker.work(context, elist, delay); /* var elist = tellurium.getUiElementAndDescendant(uid); if(elist != null && elist.length > 0){ var $es = teJQuery(elist); $es.each(function() { var $te = teJQuery(this); $te.data("te-color-bak", $te.css("background-color")); }); $es.css("background-color", "red"); !tellurium.logManager.isUseLog || fbLog("Set elements to red for " + uid, $es.get()); // $es.delay(delay); // $es.slideDown().delay(delay).fadeIn(); $es.first().slideUp(100).slideDown(100).delay(delay).fadeOut(100).fadeIn(100); !tellurium.logManager.isUseLog || fbLog("Delayed for " + delay, this); $es.each(function() { //back to the original color var $te = teJQuery(this); $te.css("background-color", $te.data("te-color-bak")); $te.removeData("te-color-bak"); }); !tellurium.logManager.isUseLog || fbLog("Elements' color restored to original ones for " + uid, $es.get()); } */ //}; TelluriumApi.prototype.showUi = function(uid, delay){ }; TelluriumApi.prototype.showUi = function(uid){ //Always construct a new snapshot var stree = this.cache.takeSnapshot(uid); if(stree == null){ fbError("Cannot find UI module " + uid + " from cache", this.cache); throw new SeleniumError("Cannot find UI module " + uid + " from cache"); } var context = new WorkflowContext(); var outlineVisitor = new UiOutlineVisitor(); var tipVisitor = new UiSimpleTipVisitor(); var chainVisitor = new STreeChainVisitor(); chainVisitor.addVisitor(outlineVisitor); chainVisitor.addVisitor(tipVisitor); var uiid = new Uiid(); uiid.convertToUiid(uid); var uoj = stree.walkTo(context, uiid); if(uoj != null){ uoj.traverse(context, chainVisitor); }else{ !tellurium.logManager.isUseLog || fbLog("Cannot find UI object " + uid + " in snapshot", stree); throw new SeleniumError("Cannot find UI object " + uid + " in snapshot"); } // stree.traverse(context, chainVisitor); }; TelluriumApi.prototype.cleanUi = function(uid){ var stree = this.cache.getSTree(uid); if(stree == null){ fbWarn("Cannot find STree for UI Module" + uid + " from cache", this.cache); stree = this.cache.takeSnapshot(uid); } if(stree == null){ fbError("Cannot find UI module " + uid + " from cache", this.cache); throw new SeleniumError("Cannot find UI module " + uid + " from cache"); } var context = new WorkflowContext(); var tipCleaner = new UiSimpleTipCleaner(); var outlineCleaner = new UiOutlineCleaner(); var chainVisitor = new STreeChainVisitor(); chainVisitor.addVisitor(tipCleaner); chainVisitor.addVisitor(outlineCleaner); var uiid = new Uiid(); uiid.convertToUiid(uid); var uoj = stree.walkTo(context, uiid); if(uoj != null){ uoj.traverse(context, chainVisitor); }else{ !tellurium.logManager.isUseLog || fbLog("Cannot find UI object " + uid + " in snapshot", stree); throw new SeleniumError("Cannot find UI object " + uid + " in snapshot"); } // stree.traverse(context, chainVisitor); }; TelluriumApi.prototype.useEngineLog = function(isUse){ tellurium.logManager.isUseLog = isUse; if(firebug != undefined) firebug.env.debug = isUse; }; TelluriumApi.prototype.getHTMLSource = function(uid) { var stree = this.cache.takeSnapshot(uid); if(stree == null){ fbError("Cannot find UI module " + uid + " from cache", this.cache); throw new SeleniumError("Cannot find UI module " + uid + " from cache"); } var visitor = new UiHTMLSourceVisitor(); var context = new WorkflowContext(); // stree.traverse(context, visitor); // return visitor.htmlsource; var uiid = new Uiid(); uiid.convertToUiid(uid); var uoj = stree.walkTo(context, uiid); if(uoj != null){ uoj.traverse(context, visitor); return visitor.htmlsource; }else{ !tellurium.logManager.isUseLog || fbLog("Cannot find UI object " + uid + " in snapshot", stree); throw new SeleniumError("Cannot find UI object " + uid + " in snapshot"); } }; TelluriumApi.prototype.getUiByTag = function(tag, attributes){ // var attrs = new Hashtable(); var attrs = {}; var position = null; var text = null; var i; if(attributes != null && attributes.length > 0){ for(i=0; i 0){ $found.removeAttr("teuid"); } }; TelluriumApi.prototype.getIndex = function(locator){ var elem = selenium.browserbot.findElement(locator); teJQuery(elem).data("id", "found"); var tag = elem.tagName; var $elems = teJQuery(elem.parentNode).find(" > " + tag); var index = 0; for(var i=0; i<$elems.size(); i++){ var $elem = $elems.eq(i); if($elem.data("id") == "found"){ index = i; $elem.removeData("id"); break; } } return index + 1; // return teJQuery(elem).index() + 1; // return teJQuery(elem).prevAll().size() + 2; }; function main() { const v1 = [1337,1337,1337]; const v4 = []; const v5 = {keyFor:"undefined",race:1337,trimEnd:1337,stackTraceLimit:1337,ignoreCase:v4,acosh:v4}; const v7 = [-4.0,-4.0]; function v8(v9,v10,v11,v12) { } function v13(v14,v15,v16,v17) { if (v17) { } else { const v23 = v8(v16,false,v1,...false,...Function); } const v26 = [13.37,13.37,13.37,13.37,13.37]; const v28 = [1337,1337,13.37,1337]; const v29 = [v26]; const v30 = {sticky:Boolean,clear:v26,multiline:"3WGX7UQqsB",isSafeInteger:v26,exec:-1984769435,assign:v29,call:13.37}; const v31 = {parseFloat:v28,asinh:1337,lastMatch:v30,subarray:-1984769435,toExponential:1337}; let v34 = v13; const v35 = new Promise(v34,v31,13.37,v31); } const v36 = {preventExtension:v13,get:v8,deleteProperty:v13,has:v13,defineProperty:v13,getOwnPropertyDescriptor:v8,call:v8,set:v13,ownKeys:v13,setPrototypeOf:v8,construct:v13}; const v38 = new Proxy(v7,v36); const v39 = "undefined"[v5]; const v40 = v13(v38,v8,v13,v8,v39); } %NeverOptimizeFunction(main); main(); Package.describe({ name: 'rocketchat:ui-admin', version: '0.1.0', // Brief, one-line summary of the package. summary: '', // URL to the Git repository containing the source code for this package. git: '', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use([ 'ecmascript', 'templating', 'coffeescript', 'underscore', 'rocketchat:lib' ]); // template files api.addFiles('admin/admin.html', 'client'); api.addFiles('admin/adminFlex.html', 'client'); api.addFiles('admin/adminStatistics.html', 'client'); api.addFiles('admin/rooms/adminRoomInfo.html', 'client'); api.addFiles('admin/rooms/adminRooms.html', 'client'); api.addFiles('admin/users/adminInviteUser.html', 'client'); api.addFiles('admin/users/adminUserChannels.html', 'client'); api.addFiles('admin/users/adminUserEdit.html', 'client'); api.addFiles('admin/users/adminUserInfo.html', 'client'); api.addFiles('admin/users/adminUsers.html', 'client'); // coffee files api.addFiles('admin/admin.coffee', 'client'); api.addFiles('admin/adminFlex.coffee', 'client'); api.addFiles('admin/adminStatistics.coffee', 'client'); api.addFiles('admin/rooms/adminRoomInfo.coffee', 'client'); api.addFiles('admin/rooms/adminRooms.coffee', 'client'); api.addFiles('admin/users/adminInviteUser.coffee', 'client'); api.addFiles('admin/users/adminUserChannels.coffee', 'client'); api.addFiles('admin/users/adminUserEdit.coffee', 'client'); api.addFiles('admin/users/adminUserInfo.coffee', 'client'); api.addFiles('admin/users/adminUsers.coffee', 'client'); // api.addAssets('styles/side-nav.less', 'client'); }); import React from 'react'; import Button from './Button'; export default { title: 'Button', component: Button, text: 'Button', argTypes: { variant: { options: ['light', 'medium', 'dark', 'white'], control: { type: 'select' }, }, size: { options: ['large', 'small'], control: { type: 'radio' }, }, }, }; const Template = (args) => ); } else { prevButton = ( ); } return prevButton; } // Next Button var NextButton = ({ nextPage, table }) => { var nextButton; if (table.query.page === Math.ceil(table.size / table.query.limit)) { nextButton = ( ); } else { nextButton = ( ); } return nextButton }; // Pagination Details var PageDetails = ({ table }) => { var minDisplaying = (table.query.page - 1) * table.query.limit || 1; var maxDisplaying = (table.query.page * table.query.limit) < table.size ? table.query.page * table.query.limit : table.size; var totalRecords = table.size; var currentPage = table.query.page; var maxPage = Math.ceil(table.size / table.query.limit); return (

    Displaying records {minDisplaying} - {maxDisplaying} of {totalRecords}  (Page {currentPage} of {maxPage})

    ); } // ExplorerPagination Container var ExplorerPagination = ({ prevPage, nextPage, dbConnection, table }) => { return (
    { prevPage(dbConnection, table) }}/> { nextPage(dbConnection, table) }}/>
    ); }; module.exports = ExplorerPagination; import React, { useState, useEffect } from 'react'; import SearchForm from '../components/SearchForm'; import ListItem from '../components/ListItem'; import API from '../utils/API'; import useDebounce from '../utils/debounceHook'; import { Container, Row, Col } from 'react-bootstrap'; const Search = () => { const [ search, setSearch ] = useState(''); const [ results, setResults ] = useState([]); const debouncedSearchTerm = useDebounce(search, 500); useEffect( () => { if (!search) return; if (debouncedSearchTerm) { API.getBook(search) .then((res) => { const { items } = res.data; let bookData = items.map((book) => ({ bookId: book.id, authors: book.volumeInfo.authors || [ 'No author to display' ], title: book.volumeInfo.title, description: book.volumeInfo.description || 'No description to display', image: book.volumeInfo.imageLinks && book.volumeInfo.imageLinks.thumbnail ? book.volumeInfo.imageLinks.thumbnail : '', previewLink: book.volumeInfo.previewLink })); setResults(bookData); }) .catch((err) => console.log(err)); } }, [ debouncedSearchTerm ] ); const handleInputChange = (e) => { setSearch(e.target.value); }; const handleFormSubmit = (e) => { e.preventDefault(); }; const saveBook = (bookId) => { const bookToSave = results.find((book) => book.bookId === bookId); API.saveBook(bookToSave).then(() => {}).catch((err) => console.log(err)); }; return (

    Search Results

      {results ? ( results.map((result) => ( saveBook(result.bookId)} /> )) ) : (

      No Results

      )}
    ); }; export default Search; import baseScene from './_baseScene' export default { baseScene: baseScene } // import React, { useEffect, useState } from 'react' import React from 'react' import './BodyMain.css'; function BodyMain(props) { return (
    Restaurante
    Super Mercados
    Estabelecimentos
    ); } export default BodyMain; IngyuTae/react-native-wagmi-charts100-1000 const packageJson = require('./package.json'); const config = packageJson.eslintConfig.rules['prettier/prettier'][1]; module.exports = config; function longest (s1, s2) { // Set 排重真的太棒了!! const set = new Set(s1 + s2) // Set -> 数组 -> 排序 -> 转成字符串 // 默认的排序就是按字母顺序 return [...set].sort().join('') } src/Providers/ConfigServiceProvider.js 'use strict'; let ServiceProvider = use('Chromabits/Container/ServiceProvider'); let config = require('config'); /** * Class ConfigServiceProvider * * Provides configuration */ class ConfigServiceProvider extends ServiceProvider { /** * Register services * * @param app */ register (app) { app.instance('Config', config); } } module.exports = ConfigServiceProvider; AldoTahirllari/obviacomponents/DataGrid/DataGridCellRenderer.js /** * This is a DataGridCellRenderer Element, the default item renderer for a DataGrid * * Kreatx 2018 */ //component definition var DataGridCellRenderer = function(_props){ //component data Label.call(this, _props); }; //component prototype DataGridCellRenderer.prototype.ctor = 'DataGridCellRenderer';0 const { Notification } = require("../models/notification.model"); const populateData = { path: "sourceUser", select: "name username profilePhoto", }; const getUserNotification = async (req, res) => { const { user } = req; try { const notification = await Notification.find({ targetUser: user.userId, }).populate(populateData); const allNotifications = notification.sort( (notify1, notify2) => notify2.time - notify1.time ); res.json({ success: true, allNotifications, }); } catch (err) { console.log(err); res.json({ success: false, message: `Error Occured: ${err}`, }); } }; module.exports = getUserNotification; 'use babel'; import { CompositeDisposable } from 'atom'; SearchStaView = null; export default { staSearchListView: null, //駅名検索ビュー subscriptions: null, activate(state) { // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable this.subscriptions = new CompositeDisposable(); // コマンド登録 this.subscriptions.add(atom.commands.add('atom-workspace', { 'language-bve:GrammarJudgment': () => this.grammarJudgment(), 'language-bve:JumpStation': () => this.openSearchStaPanel() })); //新しいエディタがインスタンス化された際のイベント処理 this.subscriptions.add(atom.workspace.observeTextEditors(editor => { //もし初期化されていないViewがあれば初期化 if(SearchStaView == null){ SearchStaView = require('./bve-searchStaView.js'); } if(this.staSearchListView == null){ this.staSearchListView = new SearchStaView(); } //文法判定 const buffer = editor.getBuffer(); this.setGrammar(buffer); //変更された際も文法を判定 buffer.onDidChange(({changes}) => { this.setGrammar(buffer); }); })); }, deactivate() { this.staSearchListView.destroy(); this.staSearchListView = null; this.subscriptions.dispose(); }, //状態を保存しておく serialize() { }, //駅名検索パネルを表示 openSearchStaPanel(){ if(this.staSearchListView.isVisible){ this.staSearchListView.hide(); }else{ this.staSearchListView.show(atom.workspace.getActiveTextEditor()); }; }, //文法判定コマンド grammarJudgment() { const editor = atom.workspace.getActiveTextEditor(); this.setGrammar(editor.getBuffer()); }, //文法判定 setGrammar(buffer) { const header = buffer.lineForRow(0); if(header.match(/BveTs\s*Map\s*2.02/gi)){ atom.grammars.assignLanguageMode(buffer, 'source.bve-map-2.02'); }else if(header.match(/BveTs\s*Structure\s*List/gi)){ atom.grammars.assignLanguageMode(buffer, 'source.bve-structure'); }else if(header.match(/BveTs\s*Sound\s*List/gi)){ atom.grammars.assignLanguageMode(buffer, 'source.bve-sound'); }else if(header.match(/BveTs\s*Station\s*List/gi)){ atom.grammars.assignLanguageMode(buffer, 'source.bve-station'); }else if(header.match(/BveTs\s*Train/gi)){ atom.grammars.assignLanguageMode(buffer, 'source.bve-train'); } } }; Steven73041/messenger import React, {useEffect, useState} from 'react'; import '../styles/Header.css'; import {Link} from 'react-router-dom'; import {useStateValue} from '../StateProvider'; import {Button} from "@material-ui/core"; import Constants from './Constants'; import {actionTypes} from '../reducer'; const Header = () => { const [{user, token, loading}, dispatch] = useStateValue(); const [menuItems, setMenuItems] = useState([ ["Home", "/"], ["Read me", "/read-me/"], ]); useEffect(() => { }, []); const logout = (e) => { e.preventDefault(); dispatch({ type: actionTypes.SET_LOADING_TERM, loading: true, }); window.axios.post(`${Constants.domain}${Constants.logout}`, {}, { headers: { Authorization: 'Bearer ' + token, } }).then(response => { if (response.data) { //remove token dispatch({ type: actionTypes.SET_TOKEN_TERM, token: null, }); //remove user dispatch({ type: actionTypes.SET_USER_TERM, user: {}, }); dispatch({ type: actionTypes.SET_LOADING_TERM, loading: false, }); //let's remove messages till redirection let items = document.querySelectorAll('#messagesList>li'); items.forEach(item => { item.remove(); }); //redirect window.location.href = "/"; } }).catch(response => { console.log(response); }); }; const activeMenuItem = (e) => { let target = e.target; let items = window.document.getElementsByClassName('menuItem'); for (var i = 0; i < items.length; i++) { items[i].classList.remove('active'); } target.classList.add('active'); }; return ( ) }; export default Header; 0 import axios from "axios"; import phoneBookActions from "./phoneBookActions"; const baseURL = `http://localhost:2000/`; const onAddContact = (contacts) => (dispatch) => { dispatch(phoneBookActions.addContactRequest()); axios .post(`${baseURL}contacts`, contacts) .then((response) => { // console.log(response.data.contacts); dispatch(phoneBookActions.addContactSuccess(response.data)); }) .catch((error) => dispatch(phoneBookActions.addContactError(error))); }; const fetchContacts = () => (dispatch) => { dispatch(phoneBookActions.fetchContactRequest()); axios .get(`${baseURL}contacts`) .then(({ data }) => { dispatch(phoneBookActions.fetchContactSuccess(data)); }) .catch((error) => { dispatch(phoneBookActions.fetchContactError(error)); }); }; const onRemoveContacts = (id) => (dispatch) => { dispatch(phoneBookActions.removeContactRequest()); axios .delete(`${baseURL}contacts/${id}`) .then(() => { dispatch(phoneBookActions.removeContactSuccess(id)); }) .catch((error) => { dispatch(phoneBookActions.removeContactError(error)); }); }; export default { onAddContact, fetchContacts, onRemoveContacts }; bugking-cyw/data-ease-view const getDefaultState = () => { return { sceneData: {}, table: {} } } const state = getDefaultState() const mutations = { setSceneData: (state, sceneData) => { state.sceneData = sceneData }, setTable: (state, table) => { state.table = table } } const actions = { setSceneData({ commit }, sceneData) { commit('setSceneData', sceneData) }, setTable({ commit }, table) { commit('setTable', table) } } export default { namespaced: true, state, mutations, actions } MAILBOX_ConversationItemView = Backbone.View.extend({ template: function(data){ return _.template($('#conversationItemPrototypeBlock').html(), data); }, initialize: function(){ var self = this; this.conversationItemListContainer = $('#conversationItemListContainer'); this.setElement(this.template(this.model.attributes)); if (this.model.get('mode') == 'chat'){ this.$el.attr('id', 'chatItem'+this.model.get('opponentId')); this.$el.addClass('chats'); } else{ this.$el.attr('id', 'conversationItem'+this.model.get('conversationId')); this.$el.addClass('mails'); if (this.model.get('hasAttachment')){ this.$el.addClass('attach'); } } this.$el.bind('click', function(e){ if ($(e.target).is('input.ow_mailbox_conv_option')) { //e.preventDefault(); return; } if (!OW.Mailbox.conversationController.someConversationLoading) { OW.trigger('mailbox.conversation_item_selected', { convId: self.model.get('conversationId'), opponentId: self.model.get('opponentId') }); } }); this.model.on('remove', this.remove, this); this.model.on('change:conversationRead', function(){ if (this.model.get('conversationRead')){ this.$el.removeClass('ow_mailbox_convers_info_new'); this.$el.find('.ow_mailbox_convers_count_new').fadeOut(300); } else{ this.$el.addClass('ow_mailbox_convers_info_new'); this.$el.find('.ow_mailbox_convers_count_new').fadeIn(300); } }, this); this.model.on('change:isSelected', function(){ if (this.model.get('isSelected')){ this.$el.addClass('ow_mailbox_convers_info_selected'); } else{ this.$el.removeClass('ow_mailbox_convers_info_selected'); } }, this); this.model.on('change:dateLabel', function(){ $('#conversationItemDateTime', this.$el).html(this.model.get('dateLabel')); }, this); this.model.on('change:displayName', function(){ $('#conversationItemProfileUrl b', this.$el).html(this.model.get('displayName')); }, this); this.model.on('change:reply', function(){ if (this.model.get('reply')){ $('#conversationItemHasReply', this.$el).css('display', 'inline-block'); } else{ $('#conversationItemHasReply', this.$el).hide(); } }, this); this.model.on('change:avatarUrl', function(){ $('#conversationItemAvatarUrl', this.$el).attr('src', this.model.get('avatarUrl')); }, this); this.model.on('change:show', function(){ if (this.model.get('show')){ this.show(); } else{ if (this.model._changing && typeof this.model.changed['wasCreatedByScroll'] == 'undefined'){ this.hide(); } } }, this); this.model.on('change:wasCreatedByScroll', function(){ if (this.model.get('wasCreatedByScroll')){ this.model.set('show', true); } else{ this.model.set('wasCreatedByScroll', true); // this.model.set('show', false); } }, this); this.model.on('change:previewText', this.changePreviewText, this); this.model.on('change:newMessageCount', this.changeNewMessageCount, this); OW.bind('mailbox.conversation_item_selected', function(data){ if (self.model.get('conversationId') == null){ return; } if (data.convId != self.model.get('conversationId')){ if (self.model.get('isSelected')){ self.model.set('isSelected', false); } } else{ if (!self.model.get('isSelected')){ self.model.set('isSelected', true); } } //var w = $('#messagesContainerControl').width(); I don't know what what is it ?? //$('#conversationItemListSub').css('width', 0.359375 * w); }); OW.bind('mailbox.conversation_marked_unread', function(data){ if (data.convId == self.model.get('conversationId')){ self.model.set('conversationRead', 0); } }); OW.bind('mailbox.conversation_marked_read', function(data){ if (data.convId == self.model.get('conversationId')){ self.model.set('conversationRead', 1); } }); OW.bind('mailbox.conversation_deleted', function(data){ if (data.convId == self.model.get('conversationId')){ self.$el.remove(); OW.updateScroll( $('#conversationItemListContainer') ); var user = OW.Mailbox.usersCollection.findWhere({convId: data.convId}); if (user){ user.set('convId', 0); } } }); OW.bind('mailbox.message', function(message){ if (message.convId != self.model.get('conversationId')){ return; } OW.trigger('mailbox.set_no_conversation', {show: false}); self.model.set('lastMessageTimestamp', message.timeStamp); self.model.set('dateLabel', message.dateLabel); if (self.model.get('mode') == 'chat'){ if (!message.readMessageAuthorized){ self.model.set('previewText', message.previewText); } else{ var previewText = message.text; if (previewText.length > 50) { previewText = previewText.substr(0, 50)+'...'; } self.model.set('previewText', previewText); } } self.conversationItemListContainer.find('#conversationItemListSub').prepend(self.$el); // self.conversationItemListContainer.find('.jspPane').prepend(self.$el); }); OW.bind('mailbox.conversation_data_received_for_'+self.model.get('opponentId'), function(data){ self.model.set('conversationId', data.conversationId); self.model.set('isSelected',true); }); OW.bind('mailbox.message_was_authorized', function(message){ if (message.convId != self.model.get('conversationId')){ return; } if (self.model.get('mode') != 'chat'){ return; } if (message.timeStamp != self.model.get('lastMessageTimestamp')){ return; } self.model.set('previewText', message.text); }); this.$el.data( self.model ); }, render: function(){ this.changePreviewText(); if (this.model.get('newMessageCount')>0){ this.$el.find('.ow_mailbox_convers_count_new').html( OW.getLanguageText('mailbox', 'new_message_count', {count: this.model.get('newMessageCount')}) ); } else{ this.$el.find('.ow_mailbox_convers_count_new').html(''); } if (this.model.get('conversationRead') == 0){ this.$el.addClass('ow_mailbox_convers_info_new'); } if (this.model.get('show')){ this.$el.show(); } else{ this.$el.hide(); } OW.bindTips(this.$el); return this; }, hide: function(){ this.$el.hide(); }, show: function(){ this.$el.show(); }, remove: function(){ this.$el.remove(); }, changeNewMessageCount: function(){ if (this.model.get('newMessageCount')>0){ this.model.set('conversationRead', 0); if (!this.model.get('conversationViewed')) { this.model.set('conversationViewed', false); } this.$el.find('.ow_mailbox_convers_count_new').html( OW.getLanguageText('mailbox', 'new_message_count', {count: this.model.get('newMessageCount')}) ); } else{ this.model.set('conversationRead', 1); this.model.set('conversationViewed', true); this.$el.find('.ow_mailbox_convers_count_new').html(''); } }, changePreviewText: function(){ if (this.model.get('mode') == 'mail'){ $('#conversationItemPreviewText', this.$el).html( OW.getLanguageText('mailbox', this.model.get('mode')+'_subject_prefix') + this.model.get('subject') ); } if (this.model.get('mode') == 'chat'){ $('#conversationItemPreviewText', this.$el).html( this.model.get('previewText') ); } OW.trigger('mailbox.render_conversation_item', this); } }); MAILBOX_ConversationListModel = Backbone.Model.extend({ defaults: { latestConvId: 0, activeConvId: null, selectedOpponentId: null, loadedConvCount: 0, pageConvId: null }, loadList: function(numberToLoad){ var numberOfConvToLoad = numberToLoad || 10; //TODO this is hardcode var n =this.get('loadedConvCount') + numberOfConvToLoad; if (n > OW.Mailbox.conversationsCollection.length){ n = OW.Mailbox.conversationsCollection.length; } for (var i=this.get('loadedConvCount'); i 1){ var nextItem = OW.Mailbox.conversationsCollection.at(OW.Mailbox.conversationsCollection.indexOf(deletedItem) + 1); if (!nextItem){ nextItem = OW.Mailbox.conversationsCollection.at(OW.Mailbox.conversationsCollection.indexOf(deletedItem) - 1); } OW.trigger('mailbox.conversation_item_selected', {convId: nextItem.get('conversationId'), opponentId: nextItem.get('opponentId')}); self.model.loadList(1); } // OW.Mailbox.conversationsCollection.remove({conversationId: data.convId}); OW.Mailbox.conversationsCollection.remove(deletedItem); if (OW.Mailbox.conversationsCollection.length == 0){ self.showNoConversation(); } }); OW.bind('mailbox.set_no_conversation', function(data){ if (data.show){ self.showNoConversation(); } else{ self.hideNoConversation(); } }); OW.bind('mailbox.application_started', function(){ if (OW.Mailbox.conversationsCollection.length > 0){ self.hideNoConversation(); self.model.loadList(); if (self.model.get('pageConvId') != null){ if (!OW.Mailbox.conversationsCollection.findWhere({conversationId: self.model.get('pageConvId')})){ self.model.loadMore(self); } } } else{ self.showNoConversation(); } self.hidePreloader(); }); }, loadMoreToConversationId: function(conversationId){ if (!OW.Mailbox.conversationsCollection.findWhere({conversationId: this.model.get('pageConvId')})) { this.model.loadMore(this); } else { //var jsp = this.conversationItemListWrapper.data('jsp'); //jsp.scrollToBottom(); } }, bulkAction: function(convIdList, actionName){ var ajaxData = {}; ajaxData['actionData'] = { 'uniqueId': OWMailbox.uniqueId('bulkActions'), 'name': 'bulkActions', 'data': { 'convIdList': convIdList, 'actionName': actionName } }; ajaxData['actionCallbacks'] = { success: function(data){ if ( typeof data != 'undefined' ) { if (actionName == 'markUnread'){ _.each(convIdList, function (id) { OW.trigger('mailbox.conversation_marked_unread', {convId: id}); }); } if (actionName == 'markRead'){ _.each(convIdList, function (id) { OW.trigger('mailbox.conversation_marked_read', {convId: id}); }); } if (actionName == 'delete'){ _.each(convIdList, function (id) { OW.trigger('mailbox.conversation_deleted', {convId: parseInt(id)}); }); } if (data.message){ OW.info(data.message); } $('.ow_mailbox_conv_option').prop('checked', false); $('#mailboxConvOptionSelectAll').prop('checked', false); } }, error: function(e){ OWMailbox.log(e); OW.Mailbox.sendInProcess = false; }, complete: function(){ OW.Mailbox.sendInProcess = false; } }; OW.Mailbox.addAjaxData(ajaxData); OW.Mailbox.sendData(); }, hideNoConversation: function(){ $('#conversationItem-noitems', this.conversationItemListContainer).remove(); this.messagesPageControl.removeClass('ow_mailbox_table_empty'); }, showNoConversation: function(){ if ($('#conversationItem-noitems', this.conversationItemListContainer).length == 0){ var noConversationItem = $($('#conversationListNoContentPrototypeBlock').html()); noConversationItem.attr('id', 'conversationItem-noitems'); this.conversationItemListContainer.append(noConversationItem); this.messagesPageControl.addClass('ow_mailbox_table_empty'); $('#conversationContainer').removeClass('ow_mailbox_right_loading'); } }, showConversationNotFound: function(){ var conversationNotFound = $($('#conversationNotFoundPrototypeBlock').html()); }, onListChange: function(){ if (OW.Mailbox.conversationsCollection.length > 0){ this.hideNoConversation(); } else{ this.showNoConversation(); } this.hidePreloader(); }, createItem: function(conversation){ var conversationItemView = new MAILBOX_ConversationItemView({model: conversation}); var itemIndex; itemIndex = OW.Mailbox.conversationsCollection.indexOf(conversation); if (this.conversationItemListContainer.find('#conversationItemListSub').length > 0){ if (itemIndex == 0){ this.conversationItemListContainer.find('#conversationItemListSub').prepend(conversationItemView.render().$el); conversation.set('wasCreatedByScroll', true); } else{ this.conversationItemListContainer.find('#conversationItemListSub').append(conversationItemView.render().$el); } } if (this.model.get('activeConvId') == conversation.get('conversationId')){ OW.trigger('mailbox.conversation_item_selected', {convId: conversation.get('conversationId'), opponentId: conversation.get('opponentId')}); } else{ if (this.model.get('activeConvId') == null && this.model.get('loadedConvCount') == 0 && itemIndex == 0){ OW.trigger('mailbox.conversation_item_selected', {convId: conversation.get('conversationId'), opponentId: conversation.get('opponentId')}); } } OW.trigger('mailbox.render_conversation_item', conversationItemView); }, showPreloader: function(){ this.preloaderControl.addClass('ow_mailbox_left_loading'); }, hidePreloader: function(){ this.preloaderControl.removeClass('ow_mailbox_left_loading'); OW.updateScroll(this.conversationItemListWrapper); }, updateList: function(name){ var self = this; self.model.set('loadedConvCount', 0); $('#conversationItemListSub').html(''); if (name == ''){ self.searching = false; self.model.loadList(OW.Mailbox.conversationsCollection.length); for (var i=0; i'+self.textareaControl.val()+'').text(); var words = text.split(' '); var fiveWords = words.slice(-5); var textPreview = fiveWords.join(' '); $('#fake_conversationTextarea').val(textPreview); } else { $('#conversationMessageFormBlock').removeClass('active'); $('.ow_mailbox_log').removeClass('textarea_active'); } OW.updateScroll(self.messageListControl); } }); this.bindTextareaControlEvents = function(){ this.textareaControl.keyup(function(ev){ var storage = OWMailbox.getStorage(); storage.setItem('mailbox.conversation' + self.model.convId + '_form_message', $(this).val()); }); if (this.textareaControl.length > 0){ if (self.model.mode == 'chat'){ this.textareaControl.dialogAutosize(self); } else { //TODO autosize mail wysiwyg textarea } } } this.setConversationId = function(params){ self.showPreloader(); if (self.someConversationLoading == 1 || self.someConversationLoading == 2){ self.someConversationLoading = 2; } else { self.someConversationLoading = 1; } self.reset(); this.conversation = OW.Mailbox.conversationsCollection.findWhere({conversationId: params.convId}); var ajaxData = {}; ajaxData['actionData'] = { 'uniqueId': OWMailbox.uniqueId('getLog'), 'name': 'getLog', 'data': { 'convId': params.convId, 'opponentId': params.opponentId, 'markRead': true } }; ajaxData['actionCallbacks'] = { success: function(data){ if (self.someConversationLoading == 2){ return; } if ( typeof data != 'undefined' ) { self.model.setConversationId(data.conversationId); self.model.setOpponentId(data.opponentId); self.model.setMode(data.mode); self.model.setDisplayName(data.displayName); self.model.setSubject(data.subject); self.model.setProfileUrl(data.profileUrl); self.model.setAvatarUrl(data.avatarUrl); self.model.setStatus(data.status); self.model.setIsSuspended(data.isSuspended, data.suspendReasonMessage); delete owFileAttachments[self.uid]; var newUid = ''; if (data.mode == 'chat'){ $('#conversationChatFormBlock #dialogAttachmentsBtn').removeClass('uploading'); $('#dialogAttachmentsBtn').find('.mlt_file_input').remove(); newUid = OWMailbox.uniqueId('mailbox_dialog_'+self.model.convId+'_'+self.model.opponentId+'_'); $('.mailboxConversationAttachmentsPreviewContainer').attr('id', newUid); owFileAttachments[newUid] = new OWFileAttachment({ 'uid': newUid, 'submitUrl': OWMailbox.attachmentsSubmitUrl, 'deleteUrl': OWMailbox.attachmentsDeleteUrl, 'showPreview': false, 'selector': '#conversationChatFormBlock #dialogAttachmentsBtn', 'pluginKey': 'mailbox', 'multiple': false, 'lItems': [] }); $('#'+newUid+' .ow_file_attachment_preview').html(''); owFileAttachments[newUid].reset(newUid); } else{ $('#conversationAttachmentsBtn').find('.mlt_file_input').remove(); newUid = OWMailbox.uniqueId('mailbox_conversation_'+self.model.convId+'_'+self.model.opponentId+'_'); $('.mailboxConversationAttachmentsPreviewContainer').attr('id', newUid); owFileAttachments[newUid] = new OWFileAttachment({ 'uid': newUid, 'submitUrl': OWMailbox.attachmentsSubmitUrl, 'deleteUrl': OWMailbox.attachmentsDeleteUrl, 'showPreview': true, 'selector': '#conversationMessageFormBlock #conversationAttachmentsBtn', 'pluginKey': 'mailbox', 'multiple': true, 'lItems': [] }); $('#'+newUid+' .ow_file_attachment_preview').html(''); owFileAttachments[newUid].reset(newUid); $('#fake_conversationTextarea').val(''); $('#conversationMessageFormBlock').removeClass('continue'); $('#conversationMessageFormBlock').removeClass('active'); $('.ow_mailbox_log').removeClass('textarea_active'); OW.updateScroll(self.messageListControl); } self.uid = newUid; $('#conversationTextarea').val('').keyup(); if (data.log.length > 0) { for(var i=0; i 0){ self.textareaControl.dialogAutosize(self, 'adjust'); } OW.trigger('mailbox.conversation_marked_read', {convId: self.model.convId}); } self.model.setIsLogLoaded(true); self.hidePreloader(); }, error: function(e){ OWMailbox.log(e); self.historyLoadInProgress = false; OW.Mailbox.sendInProcess = false; self.hidePreloader(); self.messageListWrapperControl.html(e.responseText); }, complete: function(){ self.historyLoadInProgress = false; OW.Mailbox.sendInProcess = false; self.someConversationLoading = 0; } } OW.Mailbox.addAjaxData(ajaxData); var ajaxData2 = {}; ajaxData2['actionData'] = { 'uniqueId': OWMailbox.uniqueId('markConversationRead'), 'name': 'markConversationRead', 'data': { conversationId: params.convId } }; ajaxData2['actionCallbacks'] = { success: function( data ){}, complete: function(){} } OW.Mailbox.addAjaxData(ajaxData2); self.historyLoadInProgress = true; OW.Mailbox.sendData(); } this.messageListControl.bind('jsp-scroll-y', function(event, scrollPositionY, isAtTop, isAtBottom){ /**/ var dateCaps = $('.conversationMessageGroup', self.control); dateCaps.each(function(){ var position = $(this).position(); var scrollPosition = parseInt(scrollPositionY) - 15; if (scrollPosition > position.top) { self.setStickyDateCapValue($(this).data()); } else { if (scrollPosition < 0) { self.hideStickyDateCap(); } } }); /**/ if (isAtBottom) { self.historyLoadAllowed = true; } if (isAtTop && !self.historyLoadInProgress && self.model.firstMessageId != null && self.historyLoadAllowed) { self.historyLoadInProgress = true; OW.Mailbox.sendInProcess = true; $.ajax({ url: OWMailbox.getHistoryResponderUrl, type: 'POST', data: { convId: self.model.convId, messageId: self.model.firstMessageId, }, success: function(data){ if ( typeof data != 'undefined' ) { if (data.log.length > 0) { var heightBefore = self.messageListWrapperControl.height(); $(data.log).each(function(){ //self.writeHistory(this); self.conversation.get('messages').add(this); }); OW.trigger('mailbox.history_loaded'); var heightAfter = self.messageListWrapperControl.height(); OW.updateScroll(self.messageListControl); var jsp = self.messageListControl.data('jsp'); jsp.scrollByY(heightAfter - heightBefore); } else { self.historyLoadAllowed = false; } } }, error: function(e){ OWMailbox.log(e); self.messageListWrapperControl.html(e.responseText); }, complete: function(){ self.historyLoadInProgress = false; OW.Mailbox.sendInProcess = false; }, dataType: 'json' }); } }); this.settingsBtn.bind('click', function(){ if (self.settingsBlock.hasClass('ow_hidden')){ self.showSettingsBlock(); } else{ self.hideSettingsBlock(); } }); this.deleteBtn.bind('click', function(){ if (confirm(OW.getLanguageText('mailbox', 'confirm_conversation_delete'))) { $.ajax( { url: OWMailbox.responderUrl, type: 'POST', data: { function_: 'deleteConversation', conversationId: self.model.convId }, dataType: 'json', success: function( data ) { if( data.result == true ) { OW.info( data.notice ); self.reset(); OW.trigger('mailbox.conversation_deleted', {convId: self.model.convId, opponentId: self.model.opponentId}); } else if( data.error != undefined ) { OW.warning( data.error ); } } } ); } self.hideSettingsBlock(); }); this.markUnreadBtn.bind('click', function(){ var ajaxData = {}; ajaxData['actionData'] = { 'uniqueId': OWMailbox.uniqueId('markConversationUnRead'), 'name': 'markConversationUnRead', 'data': { conversationId: self.model.convId } }; ajaxData['actionCallbacks'] = { success: function( data ) { if( data.error != undefined ){ OW.warning( data.error ); } else if( data.result == true ){ OW.info( data.notice ); OW.trigger('mailbox.conversation_marked_unread', {convId: self.model.convId}); } }, complete: function(){} } OW.Mailbox.sendData(ajaxData); self.hideSettingsBlock(); }); this.switchToChatBtn.bind('click', function(){ OW.trigger('mailbox.open_dialog', {convId: self.model.convId, opponentId: self.model.opponentId, mode: 'chat'}); }); this.sendMessageBtn.bind('click', function(){ var text = self.textareaControl.val(); var checkText = text; // process value checkText = checkText.replace(/\ | /ig,''); checkText = checkText.replace(/(<([^>]+)>)/ig,''); if ( !$.trim(checkText).length ){ OW.error(OW.getLanguageText('mailbox', 'chat_message_empty')); return; } self.sendMessage(text, (new Date()).getTime()); }); this.messageListControl.on('click', '.callReadMessage', function(e){ $.ajax({ 'type': 'POST', 'url': OWMailbox.authorizationResponderUrl, 'data': { 'actionParams': $(this).attr('id') }, 'success': function(data){ if (typeof data.error != 'undefined') { OW.error(data.error); } else { if (typeof data.authorizationActionText != 'undefined') { OW.info(data.authorizationActionText); } self.updateMessage(data); } }, 'dataType': 'json' }) }); /**/ this.model.conversationIdSetSubject.addObserver(function(){ }); this.model.modeSetSubject.addObserver(function(){ if (self.model.mode == 'chat') { self.subjectBloсkControl.addClass('ow_hidden'); self.capBlockControl.addClass('ow_mailbox_cap_chat'); self.control.addClass('ow_mailbox_right_chat'); self.conversationChatFormBlock.removeClass('ow_hidden'); self.messageFormBlock.addClass('ow_hidden'); self.textareaControl = $('#dialogTextarea', self.control); if (!self.hasLinkObserver){ OWLinkObserver.observeInput('dialogTextarea', function(link){ self.embedLinkResult = false; self.embedLinkDetected = true; this.requestResult(); this.onResult = function( r ){ self.embedLinkResult = true; if (r.type == 'video' || r.type == 'link') { self.embedAttachmentsObject = r; self.embedAttachmentsValue = JSON.stringify(r); } OW.trigger('mailbox.conversation_embed_link_request_result', r); } }); } } if (self.model.mode == 'mail') { self.subjectBloсkControl.removeClass('ow_hidden'); self.capBlockControl.removeClass('ow_mailbox_cap_chat'); self.control.removeClass('ow_mailbox_right_chat'); self.conversationChatFormBlock.addClass('ow_hidden'); self.messageFormBlock.removeClass('ow_hidden'); self.textareaControl = $('#conversationTextarea', self.control); $('.ow_mailbox_form').click(function(){ $('#conversationMessageFormBlock').removeClass('continue'); $('#conversationMessageFormBlock').addClass('active'); $('.ow_mailbox_log').addClass('textarea_active'); $('#conversationTextarea').focus(); $('#conversationTextarea').get(0).htmlareaFocus(); OW.updateScroll(self.messageListControl); self.scrollDialog(true); }); } self.messageListControl.css('height', ''); self.bindTextareaControlEvents(); }); this.model.statusUpdateSubject.addObserver(function(){ self.statusControl.removeClass(); self.statusControl.addClass('ow_chat_status'); if (self.model.status == 'offline') { self.control.removeClass('userisonline'); } else { self.control.addClass('userisonline'); self.statusControl.addClass(self.model.status); } }); this.model.displayNameSetSubject.addObserver(function(){ self.displayNameControl.html(self.model.displayName); }); this.model.subjectSetSubject.addObserver(function(){ self.subjectControl.html(self.model.subject); }); this.model.profileUrlSetSubject.addObserver(function(){ self.profileUrlControl.attr('href', self.model.profileUrl); if (self.model.convId){ var conversation = OW.Mailbox.conversationsCollection.findWhere({conversationId: self.model.convId}); if (conversation){ self.profileUrlControl.attr('title', conversation.get('shortUserData')); OW.bindTips(self.control); } } }); this.model.avatarUrlSetSubject.addObserver(function(){ if (self.model.avatarUrl) { self.avatarControl.attr('src', self.model.avatarUrl); } else { self.avatarControl.attr('src', OWMailbox.defaultAvatarUrl); } }); this.model.isSuspendedSetSubject.addObserver(function(){ if (self.model.isSuspended) { self.userIsUnreachableBlock.show(); $('#conversationUserIsUnreachableText', self.userIsUnreachableBlock).html( self.model.suspendReasonMessage ); if (self.model.mode == 'chat') { self.conversationChatFormBlock.addClass('ow_hidden'); } if (self.model.mode == 'mail') { self.messageFormBlock.addClass('ow_hidden'); } } else { self.userIsUnreachableBlock.hide(); $('#conversationUserIsUnreachableText', self.userIsUnreachableBlock).html( '' ); if (self.model.mode == 'chat') { self.conversationChatFormBlock.removeClass('ow_hidden'); } if (self.model.mode == 'mail') { self.messageFormBlock.removeClass('ow_hidden'); } } }); OW.bind('mailbox.conversation_item_selected', function(data){ if (data.convId != self.model.convId) { self.setConversationId(data); } // else // { // if (self.model.opponentId == null && data.opponentId != null) // { // self.model.setOpponentId(data.opponentId); // self.setConversationId(data.convId); // } // } }); OW.bind('mailbox.conversation_item_list_loaded', function(data){ if (data.list.length == 0) { self.hidePreloader(); } }); OW.bind('mailbox.message', function(message){ if (message.convId != self.model.convId) { return; } self.conversation.get('messages').add(message); //self.write(message); }); OW.bind('mailbox.presence', function(presence){ if (presence.opponentId != self.model.opponentId) { return; } self.model.setStatus(presence.status); }); OW.bind('base.add_attachment_to_queue', function(data){ if (self.model.mode != 'chat'){ return; } if (data.pluginKey != 'mailbox' || data.uid != self.uid){ return; } $('#conversationChatFormBlock #dialogAttachmentsBtn').addClass('uploading'); // $('#conversationChatFormBlock #dialogAttachmentsBtn input').attr('disabled', 'disabled'); }); OW.bind('base.update_attachment', function(data){ if (self.model.mode != 'chat') { return; } if (data.pluginKey != 'mailbox' || data.uid != self.uid) { return; } $('#conversationChatFormBlock #dialogAttachmentsBtn').removeClass('uploading'); // $('#conversationChatFormBlock #dialogAttachmentsBtn input').removeAttr('disabled'); $.each(data.items, function(){ if (!this.result){ OW.error(this.message); } }); var newUid = OWMailbox.uniqueId('mailbox_dialog_'+self.model.convId+'_'+self.model.opponentId+'_'); OW.trigger('base.file_attachment', { 'uid': self.uid, 'newUid': newUid }); self.uid = newUid; OW.getPing().getCommand('mailbox_ping').start(); }); OW.bind('mailbox.send_message', function(data){ if (data.sentFrom != 'conversation' && data.opponentId == self.model.opponentId && data.convId == self.model.convId) { self.write(data.tmpMessage); } }); OW.bind('mailbox.update_message', function(data){ if (data.sentFrom != 'conversation' && data.opponentId == self.model.opponentId && data.convId == self.model.convId) { self.updateMessage(data.message); } }); }; MAILBOX_ConversationView.prototype = { construct: function(){ var self = this; this.displayNameControl = $('#conversationOpponentDisplayname', this.control); this.subjectControl = $('#conversationSubject', this.control); this.subjectBloсkControl = $('#conversationSubjectBlock', this.control); this.profileUrlControl = $('#conversationOpponentProfileUrl', this.control); this.avatarControl = $('#conversationOpponentAvatar', this.control); this.settingsBtn = $('#conversationSettingsBtn', this.control); this.settingsBlock = $('#conversationSettingsBlock', this.control); this.deleteBtn = $('#conversationDeleteBtn', this.control); this.markUnreadBtn = $('#conversationMarkUnreadBtn', this.control); this.sendMessageBtn = $('#conversationSendMessageBtn', this.control); this.capBlockControl = $('#conversationCapBlock', this.control); this.avatarBlockControl = $('#conversationAvatarBlock',this.control); this.statusControl = $('#conversationOpponentProfileStatus',this.control); this.dialogWindowHeight = 475; this.textareaHeight = 42; this.messageListControl = $('#conversationLog', this.control); OW.addScroll(this.messageListControl, {contentWidth: '0px'}); this.messageListWrapperControl = $('#conversationLog .jspContainer .jspPane', this.control); this.messageGroupStickyBlockControl = $('#conversationMessageGroupStickyBlock', this.control); this.switchToChatBtn = $('#conversationSwitchToChatBtn', this.control); this.userIsUnreachableBlock = $('#conversationUserIsUnreachable', this.control); this.messageFormBlock = $('#conversationMessageFormBlock', this.control); this.conversationChatFormBlock = $('#conversationChatFormBlock', this.control); }, reset: function(){ this.model.setLastMessageTimestamp(0); this.model.firstMessageId = null; this.model.setStatus(''); this.model.setIsLogLoaded(false); this.model.setDisplayName(false); this.model.setSubject(false); this.model.setProfileUrl(false); this.model.setAvatarUrl(false); this.model.firstMessageTimeLabel = ''; this.model.lastMessageTimeLabel = ''; this.lastMessageDate = 0; this.firstMessageDate = 0; this.messageListWrapperControl.html(''); this.hideStickyDateCap(); this.messageFormBlock.addClass('ow_hidden'); this.userIsUnreachableBlock.hide(); }, hidePreloader: function(){ var self = this; this.preloaderControl.removeClass('ow_mailbox_right_loading'); this.scrollDialog(); }, hideSettingsBlock: function(){ this.settingsBtn.removeClass('active'); this.settingsBlock.addClass('ow_hidden'); }, hideStickyDateCap: function(){ this.messageGroupStickyBlockControl.hide(); }, messageWrite: function(message){ var itemIndex; itemIndex = this.conversation.get('messages').indexOf(message); if (itemIndex == 0){ this.writeHistory(message.attributes); } else{ this.write(message.attributes); } }, scrollDialog: function(scrollToBottom){ var scrollToBottom = scrollToBottom || false; this.historyLoadAllowed = false; OW.updateScroll(this.messageListControl); var jsp = this.messageListControl.data('jsp'); if (typeof jsp != 'undefined' && jsp != null) { lastMessage = this.messageListControl.find('.ow_mailbox_log_message').last(); if (!scrollToBottom && lastMessage.length > 0){ jsp.scrollToElement(lastMessage, true, true); } else{ jsp.scrollToBottom(); } } }, sendMessage: function(text, timeStamp){ var self = this; var tmpMessageUid = OWMailbox.uniqueId('tmpMsg_'); var d = new Date(); var utc = d.getTime() / 1000 + (d.getTimezoneOffset() * 60); var timeStamp = parseInt(utc + OWMailbox.serverTimezoneOffset * 3600); var timeLabel = OWMailbox.formatAMPM(new Date(timeStamp*1000)); if (!self.embedLinkDetected) { var tmpMessage = { 'rawMessage' : true, 'isSystem': false, 'date': OWMailbox.todayDate, 'dateLabel': OWMailbox.todayDateLabel, 'id': tmpMessageUid, 'text': text, 'attachments': [], 'senderId': OWMailbox.userDetails.userId, 'recipientId': self.model.opponentId, 'timeStamp': timeStamp, 'timeLabel': timeLabel }; OW.trigger('mailbox.send_message', {'sentFrom': 'conversation', 'opponentId': self.model.opponentId, 'convId': self.model.convId, 'tmpMessage': tmpMessage}); var data = { 'convId': self.model.convId, 'text': text, 'uid': self.uid, 'embedAttachments': self.embedAttachmentsValue }; self.postMessage(tmpMessageUid, data); } else { var tmpMessage = { 'rawMessage' : true, 'isSystem': true, 'date': OWMailbox.todayDate, 'dateLabel': OWMailbox.todayDateLabel, 'id': tmpMessageUid, 'attachments': [], 'senderId': OWMailbox.userDetails.userId, 'recipientId': self.model.opponentId, 'timeStamp': timeStamp, 'timeLabel': timeLabel }; var preloaderContainer = $('#dialogEmbedLinkBlockPrototype').clone(); $('#dialogMessageText', preloaderContainer).html(text); tmpMessage['text'] = preloaderContainer.html(); OW.trigger('mailbox.send_message', {'sentFrom': 'conversation', 'opponentId': self.model.opponentId, 'convId': self.model.convId, 'tmpMessage': tmpMessage}); if (self.embedLinkResult) { var data = { 'convId': self.model.convId, 'text': text, 'uid': self.uid, 'embedAttachments': self.embedAttachmentsValue }; self.postMessage(tmpMessageUid, data); } else { OW.bind('mailbox.conversation_embed_link_request_result', function(r){ var data = { 'convId': self.model.convId, 'text': text, 'uid': self.uid, 'embedAttachments': self.embedAttachmentsValue }; self.postMessage(tmpMessageUid, data); OW.unbind('mailbox.embed_link_request_result_'+self.model.convId); }); } // OWLinkObserver.getObserver('conversationTextarea').resetObserver(); OWLinkObserver.getObserver('dialogTextarea').resetObserver(); } tmpMessage.text = tmpMessage.text.nl2br(); self.write(tmpMessage); var storage = OWMailbox.getStorage(); storage.setItem('mailbox.conversation' + self.model.convId + '_form_message', ''); self.textareaControl.val(''); $('#conversationTextarea').get(0).htmlareaRefresh(); }, postMessage: function(tmpMessageUid, data){ var self = this; var ajaxData = {}; ajaxData['actionData'] = { 'uniqueId': OWMailbox.uniqueId('postMessage'), 'name': 'postMessage', 'data': data }; ajaxData['actionCallbacks'] = { 'tmpMessageUid' : tmpMessageUid, 'success': function(data){ if (typeof data.error == 'undefined' || data.error == null) { self.conversation.get('messages').add(data.message, {silent: true}); data.message.uniqueId = tmpMessageUid; self.updateMessage(data.message); OW.Mailbox.lastMessageTimestamp = parseInt(data.message.timeStamp); OW.trigger('mailbox.update_message', {'sentFrom': 'conversation', 'opponentId': self.model.opponentId, 'convId': self.model.convId, 'message': data.message}); var newUid = OWMailbox.uniqueId('mailbox_conversation_'+self.model.convId+'_'+self.model.opponentId+'_'); OW.trigger('base.file_attachment', { 'uid': self.uid, 'newUid': newUid }); self.uid = newUid; } else { OW.error(data.error); self.showSendMessageFailed(tmpMessageUid); } }, 'error': function(){ self.showSendMessageFailed(tmpMessageUid); }, 'complete': function(){ OW.Mailbox.sendInProcess = false; self.embedLinkResult = true; self.embedLinkDetected = false; self.embedAttachmentsValue = ''; self.embedAttachmentsObject = {}; } }; OW.Mailbox.sendData(ajaxData); }, showSendMessageFailed: function(messageId){ var self = this; if (self.model.mode == 'mail'){ $('#messageItem'+messageId, self.control).addClass('errormessage'); $('#messageItem'+messageId, self.control).prepend(''+OW.getLanguageText('mailbox', 'send_message_failed')+''); } if (self.model.mode == 'chat'){ $('#messageItem'+messageId+' .ow_dialog_in_item', self.control).addClass('errormessage'); $('#messageItem'+messageId+' .ow_dialog_in_item', self.control).prepend(''+OW.getLanguageText('mailbox', 'send_message_failed')+''); } }, setStickyDateCapValue: function(data){ if (data.date == OWMailbox.todayDate) { this.hideStickyDateCap(); } else { this.showStickyDateCap(); } $('#conversationStickyDateCap', this.messageGroupStickyBlockControl).html(data.dateLabel); this.messageGroupStickyBlockControl.data(data); }, showPreloader: function(){ this.preloaderControl.addClass('ow_mailbox_right_loading'); }, showSettingsBlock: function(){ this.settingsBtn.addClass('active'); this.settingsBlock.removeClass('ow_hidden'); }, showStickyDateCap: function(){ this.messageGroupStickyBlockControl.show(); }, getTimeBlock: function(timeLabel){ var timeBlock = $('#dialogTimeBlockPrototypeBlock').clone(); timeBlock.attr('id', 'timeBlock'+this.model.lastMessageTimestamp); $('.ow_time_text', timeBlock).html(timeLabel); return timeBlock; }, showTimeBlock: function(timeLabel, groupContainer){ var timeBlock = this.getTimeBlock(timeLabel); groupContainer.append(timeBlock); this.scrollDialog(); return this; }, updateChatMessage: function(message){ if (typeof message.uniqueId != 'undefined') { var messageContainer = $('#messageItem'+message.uniqueId, this.control); messageContainer.attr('id', 'messageItem'+message.id); } else { var messageContainer = $('#messageItem'+message.id, this.control); } var html = ''; if (message.isSystem) { html = message.text; // $('#dialogMessageWrapper', messageContainer).html( html ); messageContainer.html( html ); } else { if (message.attachments.length != 0) { var i = 0; if (message.attachments[i]['type'] == 'image') { messageContainer.addClass('ow_dialog_picture_item'); $('#dialogMessageText', messageContainer).html( '' ); } else { $('.ow_dialog_in_item', messageContainer).addClass('fileattach'); var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr('href', message.attachments[i]['downloadUrl']); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); $('.ow_dialog_in_item', messageContainer).html( attachment.html() ); } } else { // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; if ($('#dialogMessageText', messageContainer).length == 0){ tmpMessageContainer = $('#dialogChatMessagePrototypeBlock').clone(); tmpMessageContainer.attr('id', 'messageItem'+message.id); messageContainer.html(tmpMessageContainer.html()); } $('#dialogMessageText', messageContainer).html( html ); $('#dialogMessageText', messageContainer).autolink(); } } if ( message.senderId != this.model.opponentId ){ $('div.ow_dialog_item', messageContainer).addClass('even'); } else{ $('div.ow_dialog_item', messageContainer).addClass('odd'); } this.scrollDialog(); OW.trigger('mailbox.message_was_authorized', message); }, updateMailMessage: function(message){ if (typeof message.uniqueId != 'undefined') { var messageContainer = $('#messageItem'+message.uniqueId, this.control); messageContainer.attr('id', 'messageItem'+message.id); } else { var messageContainer = $('#messageItem'+message.id, this.control); } if (message.senderId == this.model.opponentId) { var messageProfileDisplayName = this.model.displayName; var messageProfileUrl = this.model.profileUrl; var messageProfileAvatarUrl = this.model.avatarUrl; } else { var messageProfileDisplayName = OWMailbox.userDetails.displayName; var messageProfileUrl = OWMailbox.userDetails.profileUrl; var messageProfileAvatarUrl = OWMailbox.userDetails.avatarUrl; } $('#conversationMessageDateTime', messageContainer).html(message.timeLabel); $('#conversationMessageProfile', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageProfile', messageContainer).html(messageProfileDisplayName); $('#conversationMessageAvatarProfileUrl', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageAvatarUrl', messageContainer).attr('src', messageProfileAvatarUrl); var html = ''; if (message.isSystem) { html = message.text; $('#conversationMessageText', messageContainer).html( html ); } else { // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; $('#conversationMessageText', messageContainer).html( html ); if (self.autolinkEnabled){ $('#conversationMessageText', messageContainer).autolink(); } } if (message.attachments.length != 0) { var attachmentsBlock = $('#conversationFileAttachmentContentBlockPrototype').clone(); attachmentsBlock.removeAttr('id'); for (var i in message.attachments) { var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); if (parseInt(i) % 2) { attachment.addClass('ow_file_attachment_block2'); } else { attachment.addClass('ow_file_attachment_block1'); } $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr( 'href', message.attachments[i]['downloadUrl'] ); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); attachmentsBlock.append(attachment); } $('#conversationMessageText', messageContainer).append(attachmentsBlock); } this.scrollDialog(); }, updateMessage: function(message){ if (this.model.mode == 'chat') { this.updateChatMessage(message); } if (this.model.mode == 'mail') { this.updateMailMessage(message); } }, writeChatMessage: function(message, css_class){ var css_class = css_class || null; if ($('#messageItem'+message.id, this.control).length > 0) { return; } var groupContainer = $('#groupedMessages-'+message.date, this.control); if (groupContainer.length == 0) { groupContainer = $('#conversationMessageGroupPrototypeBlock').clone(); $('#conversationMessageGroupDate', groupContainer).html(message.dateLabel); groupContainer.attr('id', 'groupedMessages-'+message.date); groupContainer.data({ date: message.date, dateLabel: message.dateLabel }); } var messageContainer = null; if (message.isSystem){ messageContainer = $('#dialogSysMessagePrototypeBlock').clone(); } else{ messageContainer = $('#dialogChatMessagePrototypeBlock').clone(); } messageContainer.attr('id', 'messageItem'+message.id); messageContainer.attr('data-tmp-id', 'messageItem'+message.id); messageContainer.attr('data-timestamp', message.timeStamp); messageContainer.addClass('message'); var html = ''; if (message.isSystem){ html = message.text; messageContainer.html( html ); } else{ if (message.attachments.length != 0){ var i = 0; if (message.attachments[i]['type'] == 'image'){ messageContainer.addClass('ow_dialog_picture_item'); $('#dialogMessageText', messageContainer).html( '' ); } else{ $('.ow_dialog_in_item', messageContainer).addClass('fileattach'); var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr('href', message.attachments[i]['downloadUrl']); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); $('.ow_dialog_in_item', messageContainer).html( attachment.html() ); } } else{ // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; $('#dialogMessageText', messageContainer).html( html ); $('#dialogMessageText', messageContainer).autolink(); } } if ( message.senderId != this.model.opponentId ){ $('div.ow_dialog_item', messageContainer).addClass('even'); } else{ $('div.ow_dialog_item', messageContainer).addClass('odd'); } if (css_class != null) { $('div.ow_dialog_item', messageContainer).addClass(css_class); } // get last message var lastMessage = this.messageListControl.find('.message:last'); // HOTFIX; Correct messages oredring (skalfa/workflow#35) if (message.rawMessage || !lastMessage.length || lastMessage.attr('data-timestamp') < message.timeStamp) { if (this.lastMessageDate != message.date) { this.lastMessageDate = message.date; this.messageListWrapperControl.append(groupContainer); } if ( message.timeLabel != this.model.lastMessageTimeLabel ) { this.model.lastMessageTimeLabel = message.timeLabel; this.showTimeBlock(message.timeLabel, groupContainer); } groupContainer.append(messageContainer); this.messageListWrapperControl.append(groupContainer); this.scrollDialog(); this.model.setLastMessageTimestamp(message.timeStamp); this.model.lastMessageId = message.id; } else { $(messageContainer).insertBefore(lastMessage); this.scrollDialog(); } if ( parseInt(im_readCookie('im_soundEnabled')) && css_class == null){ var audioTag = document.createElement('audio'); if (!(!!(audioTag.canPlayType) && ("no" != audioTag.canPlayType("audio/mp3")) && ("" != audioTag.canPlayType("audio/mp3")) && ("maybe" != audioTag.canPlayType("audio/mp3")) )) { AudioPlayer.embed("im_sound_player_audio", { soundFile: OWMailbox.soundUrl, autostart: 'yes' }); } else { $('#im_sound_player_audio')[0].play(); } } }, writeMailMessage: function(message, css_class){ var self = this; var css_class = css_class || null; var messageProfileDisplayName; var messageProfileUrl; var messageProfileAvatarUrl; if (message.recipientId == self.model.opponentId){ messageProfileDisplayName = OWMailbox.userDetails.displayName; messageProfileUrl = OWMailbox.userDetails.profileUrl; messageProfileAvatarUrl = OWMailbox.userDetails.avatarUrl; } if (message.senderId == self.model.opponentId){ messageProfileDisplayName = self.model.displayName; messageProfileUrl = self.model.profileUrl; messageProfileAvatarUrl = self.model.avatarUrl; } var groupContainer = $('#groupedMessages-'+message.date, this.control); if (groupContainer.length == 0){ groupContainer = $('#conversationMessageGroupPrototypeBlock').clone(); $('#conversationMessageGroupDate', groupContainer).html(message.dateLabel); groupContainer.attr('id', 'groupedMessages-'+message.date); groupContainer.data({ date: message.date, dateLabel: message.dateLabel }); } var messageContainer = $('#conversationMessagePrototypeBlock').clone(); messageContainer.removeAttr('id'); $('#conversationMessageDateTime', messageContainer).html(message.timeLabel); $('#conversationMessageProfile', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageProfile', messageContainer).html(messageProfileDisplayName); $('#conversationMessageAvatarProfileUrl', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageAvatarUrl', messageContainer).attr('src', messageProfileAvatarUrl); var html = ''; if (message.isSystem){ html = message.text; $('#conversationMessageText', messageContainer).html( html ); } else{ // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; $('#conversationMessageText', messageContainer).html( html ); if (self.autolinkEnabled){ $('#conversationMessageText', messageContainer).autolink(); } } if (message.attachments.length != 0){ var attachmentsBlock = $('#conversationFileAttachmentContentBlockPrototype').clone(); attachmentsBlock.removeAttr('id'); for (var i in message.attachments) { var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); if (parseInt(i) % 2) { attachment.addClass('ow_file_attachment_block2'); } else { attachment.addClass('ow_file_attachment_block1'); } $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr( 'href', message.attachments[i]['downloadUrl'] ); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); attachmentsBlock.append(attachment); } $('#conversationMessageText', messageContainer).append(attachmentsBlock); } this.model.setLastMessageTimestamp(message.timeStamp); this.model.lastMessageId = message.id; messageContainer.attr('id', 'messageItem'+message.id ); groupContainer.append(messageContainer); this.messageListWrapperControl.append(groupContainer); this.scrollDialog(); OW.trigger('mailbox.after_write_mail_message', message); }, write: function(message, css_class){ //if (message.timeStamp < this.model.lastMessageTimestamp) //{ // return this; //} if (this.model.mode == 'chat'){ this.writeChatMessage(message, css_class); } if (this.model.mode == 'mail'){ //if (message.timeStamp < OWMailbox.pluginUpdateTimestamp){ this.autolinkEnabled = false; //} //else{ // this.autolinkEnabled = true; //} this.writeMailMessage(message, css_class); } if ( message.recipientId == OWMailbox.userDetails.userId && message.recipientRead == 0 ){ OW.trigger('mailbox.mark_message_read', {message: message}); } //if ( message.senderId == OWMailbox.userDetails.userId ){ // OW.trigger('mailbox.mark_message_read', {message: message}); //} return this; }, writeHistoryChatMessage: function(message){ var messageContainer = null; if (message.isSystem){ messageContainer = $('#dialogSysMessagePrototypeBlock').clone(); } else{ messageContainer = $('#dialogChatMessagePrototypeBlock').clone(); } messageContainer.attr('id', 'messageItem'+message.id); var html = ''; if (message.isSystem){ html = message.text; messageContainer.html( html ); } else{ if (message.attachments.length != 0){ var i = 0; if (message.attachments[i]['type'] == 'image'){ messageContainer.addClass('ow_dialog_picture_item'); $('#dialogMessageText', messageContainer).html( '' ); } else{ $('.ow_dialog_in_item', messageContainer).addClass('fileattach'); var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr('href', message.attachments[i]['downloadUrl']); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); $('.ow_dialog_in_item', messageContainer).html( attachment.html() ); } } else{ // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; $('#dialogMessageText', messageContainer).html( html ); $('#dialogMessageText', messageContainer).autolink(); } } if ( message.senderId != this.model.opponentId ){ $('div.ow_dialog_item', messageContainer).addClass('even'); } else{ $('div.ow_dialog_item', messageContainer).addClass('odd'); } var groupContainer = $('#groupedMessages-'+message.date, this.control); if (groupContainer.length == 0) { groupContainer = $('#conversationMessageGroupPrototypeBlock').clone(); var timeBlock = $('#dialogTimeBlockPrototypeBlock').clone(); timeBlock.attr('id', 'timeBlock' + message.timeStamp); $('.ow_time_text', timeBlock).html(message.timeLabel); groupContainer.append(timeBlock); groupContainer.append(messageContainer); $('#conversationMessageGroupDate', groupContainer).html(message.dateLabel); groupContainer.attr('id', 'groupedMessages-' + message.date); groupContainer.data({ date: message.date, dateLabel: message.dateLabel }); this.messageListWrapperControl.prepend(groupContainer); } else{ //var firstMessageContainer = $('#messageItem'+this.model.firstMessageId, this.control); //firstMessageContainer.before(messageContainer); $('.ow_mailbox_date_cap', groupContainer).after(messageContainer); if ( message.timeLabel != this.model.firstMessageTimeLabel ) { this.model.firstMessageTimeLabel = message.timeLabel; var timeBlock = this.getTimeBlock(message.timeLabel); $('.ow_mailbox_date_cap', groupContainer).after(timeBlock); } } this.model.firstMessageId = message.id; }, writeHistoryMailMessage: function(message){ var self = this; var messageProfileDisplayName; var messageProfileUrl; var messageProfileAvatarUrl; if (message.recipientId == self.model.opponentId){ messageProfileDisplayName = OWMailbox.userDetails.displayName; messageProfileUrl = OWMailbox.userDetails.profileUrl; messageProfileAvatarUrl = OWMailbox.userDetails.avatarUrl; } if (message.senderId == self.model.opponentId){ messageProfileDisplayName = self.model.displayName; messageProfileUrl = self.model.profileUrl; messageProfileAvatarUrl = self.model.avatarUrl; } var firstMessageContainer = $('#messageItem'+this.model.firstMessageId); var messageContainer = $('#conversationMessagePrototypeBlock').clone(); messageContainer.removeAttr('id'); $('#conversationMessageDateTime', messageContainer).html(message.timeLabel); $('#conversationMessageProfile', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageProfile', messageContainer).html(messageProfileDisplayName); $('#conversationMessageAvatarProfileUrl', messageContainer).attr('href', messageProfileUrl); $('#conversationMessageAvatarUrl', messageContainer).attr('src', messageProfileAvatarUrl); var html = ''; if (message.isSystem){ html = message.text; $('#conversationMessageText', messageContainer).html( html ); } else{ // html = htmlspecialchars(message.text, 'ENT_QUOTES'); html = message.text; $('#conversationMessageText', messageContainer).html( html ); if (self.autolinkEnabled){ $('#conversationMessageText', messageContainer).autolink(); } } if (message.attachments.length != 0){ var attachmentsBlock = $('#conversationFileAttachmentContentBlockPrototype').clone(); attachmentsBlock.removeAttr('id'); for (var i in message.attachments) { var attachment = $('#conversationFileAttachmentBlockPrototype').clone(); attachment.removeAttr('id'); if (parseInt(i) % 2) { attachment.addClass('ow_file_attachment_block2'); } else { attachment.addClass('ow_file_attachment_block1'); } $('#conversationFileAttachmentFileName', attachment).html( OWMailbox.formatAttachmentFileName(message.attachments[i]['fileName']) ); $('#conversationFileAttachmentFileName', attachment).attr( 'href', message.attachments[i]['downloadUrl'] ); $('#conversationFileAttachmentFileSize', attachment).html( OWMailbox.formatAttachmentFileSize(message.attachments[i]['fileSize']) ); attachmentsBlock.append(attachment); } $('#conversationMessageText', messageContainer).append(attachmentsBlock); } messageContainer.attr('id', 'messageItem'+message.id ); this.model.firstMessageId = message.id; var groupContainer = $('#groupedMessages-'+message.date, this.control); if (groupContainer.length == 0){ groupContainer = $('#conversationMessageGroupPrototypeBlock').clone(); $('#conversationMessageGroupDate', groupContainer).html(message.dateLabel); groupContainer.attr('id', 'groupedMessages-'+message.date); groupContainer.data({ date: message.date, dateLabel: message.dateLabel }); groupContainer.append(messageContainer); this.messageListWrapperControl.prepend(groupContainer); } else{ firstMessageContainer.before(messageContainer); } }, writeHistory: function(message){ if (this.model.mode == 'chat') { this.writeHistoryChatMessage(message); } if (this.model.mode == 'mail') { this.autolinkEnabled = false; this.writeHistoryMailMessage(message); } if ( message.recipientId == OWMailbox.userDetails.userId && message.recipientRead == 0 ){ OW.trigger('mailbox.mark_message_read', {message: message}); } } };'use strict'; // Funcion para el servicio de la BD export default function idbModelService ($log, qs, idbUtils, idbQuery, idbEvents, lbResource, $timeout) { 'ngInject'; // Buscar un campo const searchDeepField = function (obj, field, cb) { idbUtils.validate(arguments, ['object', 'string', 'function']); const fields = field.split('.'); const lastField = fields.pop(); return (function _set(obj) { if (fields.length == 0) return cb(obj, lastField); const field = fields.shift(); if (typeof obj[field] === 'undefined') obj[field] = {}; return _set(obj[field]); })(obj); }; // Obtiene el valor pa una propieda de un objeto const getFieldValue = function (obj, field) { return searchDeepField(obj, field, function (obj, lastField) { return obj[lastField]; }); }; // Obtiene el valor pa una propieda de un objeto const setFieldValue = function (obj, field, value) { searchDeepField(obj, field, function (obj, lastField) { obj[lastField] = value; }); return obj; }; return function idbModel ($db, $modelName, $socket) { idbUtils.validate(arguments, [null ,'string']); // Clave del modelo const $id = { keyPath: 'id', autoIncrement: true }; const $eventsHandlers = {}; const $instances = {}; let $fields = {}; let $remote = null; let $versioning = null; // Constuctor del modelo function Model(data) { const thiz = this; idbUtils.validate(arguments, [['object', 'undefined']]); thiz.$resolved = false; thiz.$loaded = false; thiz.$localLoaded = false; thiz.$remoteLoaded = false; thiz.$localValues = {}; thiz.$remoteValues = {}; thiz.$version = null; thiz.$localVersion = null; thiz.$remoteVersion = null; thiz.$eventsHandlers = {}; if (data){ thiz.$setValues(data); } thiz.$constructor(data); if ($socket) { thiz.$listen(); } const $results = []; thiz // Cuando sea consultado agregar la consulta .$bind(idbEvents.MODEL_QUERIED, function (result) { $results.push(result); }) // Cuando sea liberado de la consultar quitar de las consultas .$bind(idbEvents.MODEL_UNQUERIED, function (result) { const idx = $results.indexOf(result); if (idx != -1){ $results.splice(idx, 1); } }) // Evento de que modelo está instanciado .$emit(idbEvents.MODEL_INSTANCED); }; // Devuelv el nombre del modelo Model.getModelName = function () { return $modelName; }; // Asigna el ID al modelo Model.autoIncrement = function (autoIncrement) { idbUtils.validate(arguments, ['boolean']); $id.autoIncrement = autoIncrement; return Model; }; // Asigna el ID al modelo Model.keyPath = function (keyPath) { idbUtils.validate(arguments, ['string']); $id.keyPath = keyPath; return Model; }; // Crea el objecto storage para el modelo. Model.createStore = function () { $db.createStore($modelName, $id); return Model; }; // Agrega un index Model.index = function (indexName, fieldName, opts) { $db.createIndex($modelName, indexName, fieldName, opts); return Model; }; // Método que permite modificar model. Model.build = function (buildCallback) { idbUtils.validate(arguments, ['function']); buildCallback(Model); return Model; }; // Asigna la especificación de los campos Model.fields = function (fields) { idbUtils.validate(arguments, ['object']); $fields = {}; $fields[$id.keyPath] = { "type": "number", "required": true }; Object.keys(fields).map(function (fieldName) { let field = fields[fieldName]; if (typeof fields[fieldName] == 'string'){ field = { "type": field }; } $fields[fieldName] = field; }); return Model; }; // Configura el remote api; Model.remote = function (url, args, actions) { idbUtils.validate(arguments, ['string', 'object', 'object']); $remote = lbResource(url, args, actions); return Model; }; // Devuelve la instancia del $remote del modelo Model.getRemote = function () { return $remote; }; // Devuelve el valor correspondiente al key de un objeto Model.getKeyFrom = function (data) { return getFieldValue(data, $id.keyPath); }; // Devuelve la instancia del model de las guardadas. Si no existe entonce // se crea Model.getInstance = function (key) { idbUtils.validate(arguments, [['string', 'number', 'undefined']]); // El objeto no tiene ID if (!key) { return new Model(); } // No existe la instancia entonce se crea if (!$instances[key]){ $instances[key] = new Model(); } return $instances[key]; }; // Busca un registro en la objectStore del modelo. Model.get = function (key) { const instance = Model.getInstance(key); if (instance.$localLoaded) return instance; const defered = qs.defer(); instance.$resolved = false; instance.$promise = defered.promise; $db.get($modelName, key).promise.then(function (data) { instance.$resolved = true; Model.getVersionOf(key).promise .then(function (version) { instance.$setLocalValues(data, data && version? version.hash : undefined); defered.resolve(instance); }) .catch(function (err) { defered.resolve(instance); $log.error(['Model.getVersionOf any error', err]) }); }) .catch(function (err) { defered.reject(err); }); return instance; }; // Buscar en el modelo Model.find = function (filters) { return new idbQuery($db, Model, filters); }; // Crea nuevas instancias de los modelos Model.create = function (data) { idbUtils.validate(arguments, ['object', ['function', 'undefined']]); // Si es un array if (data.length === undefined) { const record = Model.getInstance(Model.getKeyFrom(data)); if (record.$loaded) { throw new Error('Model.CantCreatedLoadedInstance'); } return record.$pull(); } // Obtener una copia del array const arr = Array.prototype.slice.call(data); const result = []; const defered = qs.defer(cb); (function iteration() { // No quedan elementos en el array if (arr.length == 0) return defered.resolve(result); // Crear el siguiente elemento Model.create(arr.shift()) .then(function (instance) { result.push(instance); iteration(); }) .catch(function (err) { defered.reject(err); }); })(); // Devolver el promise return defered; }; // Crea un modelo para guardar las versiones del modelo actual Model.versioning = function (modelName, cb) { if (typeof modelName === 'function') { cb = modelName; modelName = undefined; } idbUtils.validate([modelName, cb], [['string', 'undefined'], ['function', 'undefined']]); if (!$versioning) { // Si el model no tiene nombre se agrega if (!modelName){ modelName = $modelName+'_versioning'; } // Crear modelo para el manejo de datos $versioning = $db.model(modelName) .autoIncrement(false) .keyPath($id.keyPath) .fields({ "hash": { "type": "string", "required": true }, }); } if (cb) cb($versioning); return Model; }; // Devuelve la instancia de la version local del registro Model.getVersionOf = function (key) { const defered = qs.defer(); if ($versioning) { $versioning.get(key).$promise .then(function (version) { defered.resolve(version); }) .catch(function () { defered.reject(null); }); } else { defered.resolve(null); } return defered; }; // Agrega un mandejador de eventos al modelo Model.bind = function (eventName, handler) { idbUtils.validate(arguments, ['string', ['function', 'undefined']]); if (!$eventsHandlers[eventName]) { $eventsHandlers[eventName] = []; } $eventsHandlers[eventName].push(handler); return Model; }; // Dispara un evento del model Model.emit = function (eventName, args) { idbUtils.validate(arguments, ['string', ['undefined', 'array']]); if ($eventsHandlers[eventName]) { $eventsHandlers[eventName].map(function (cb) { cb.apply(Model, args || []); }); } return Model; }; // Devuelve el valor de una propiedad Model.prototype.$get = function (field) { return getFieldValue(this, field); }; // Asigna in valor a un campo Model.prototype.$set = function (field, value) { return getFieldValue(this, field, value); }; // Devuelve un objeto con las propiedades del registro Model.prototype.$getValues = function (data) { idbUtils.validate(arguments, [['object', 'undefined']]); const values = {}; data = data || this; Object.keys($fields).map(function (field) { setFieldValue(values, field, getFieldValue(data, field)); }); return values; }; // Devuelve un objeto con las propiedades locales del registro Model.prototype.$getLocalValues = function () { return this.$getValues(this.$localValues); }; // Devuelve un modelo con las propiedades remotas del registro Model.prototype.$getRemoteValues = function () { return this.$getValues(this.$remoteValues); }; // Asigna las propiedades del registro Model.prototype.$setValues = function (data, version) { const thiz = this; idbUtils.validate(arguments, ['object', ['string', 'undefined']]); thiz.$version = version; Object.keys(data).map(function (field) { setFieldValue(thiz, field, data[field]); }); thiz.$loaded = true; return thiz; }; // Asigna las propiedades locales del registro Model.prototype.$setLocalValues = function (data, version) { const thiz = this; idbUtils.validate(arguments, [['object', 'undefined'], ['string', 'undefined']]); thiz.$localVersion = version; Object.keys(data || {}).map(function (field) { setFieldValue(thiz.$localValues, field, data[field]); }); if (data) { thiz.$localLoaded = true; if (!thiz.$loaded) { thiz.$setValues(data, version); } } return thiz; }; // Asigna las propiedades remotas del registro Model.prototype.$setRemoteValues = function (data, version) { const thiz = this; idbUtils.validate(arguments, [['object', 'undefined'], ['string', 'undefined']]); thiz.$remoteVersion = version; Object.keys(data || {}).map(function (field) { setFieldValue(thiz.$remoteValues, field, data[field]); }); if (data) { thiz.$remoteLoaded = true; if (!thiz.$loaded) { thiz.$setValues(data, version); } } return thiz; }; // Asigna el ID del objeto Model.prototype.$setKey = function (newKey) { const oldKey = Model.getKeyFrom(this); Model.searchDeepField(this, $id.keyPath, function (obj, lastField) { obj[lastField] = newKey; }); if (oldKey !== newKey) { if (oldKey && $instances[oldKey] && $instances[oldKey] != this) { throw new Error('Model.InstanceOfOldKeyIsNotSame'); } if (newKey && $instances[newKey] && $instances[newKey] != this) { throw new Error('Model.InstanceOfNewKeyIsNotSame'); } // Eliminar anterior if (oldKey && $instances[oldKey]) { delete $instances[oldKey]; } // Agregar nueva if (newKey && !$instances[newKey]) { $instances[newKey] = this; } } return this; } // Consturctor que se puede sobre escribir Model.prototype.$constructor = function (data) { }; // Guarda los datos del objeto Model.prototype.$pull = function (newValues, version){ const thiz = this; idbUtils.validate(arguments, [['object', 'undefined'], ['string', 'undefined']]); const defered = qs.defer(); if (newValues) { newValues = thiz.$getValues(newValues); } else { newValues = thiz.$getRemoteValues(); } const newKey = Model.getKeyFrom(newValues); const oldValues = thiz.$getLocalValues(); const oldKey = Model.getKeyFrom(oldValues); console.log(newKey, oldKey); console.log(newValues, oldValues); return defered; }; // Funcion que hace escuchars los mensajes del socket para el model Model.prototype.$listen = function () { const thiz = this; if (!$socket) throw new Error('Model.DoesNotHaveSocketInstance'); // Crear una subscripcion al socket para cuando se reciban datos // para la instancia actual $socket.subscribe({ modelName: $modelName, eventName: 'update', modelId: thiz.$get($id.keyPath), }, function (data) { // A recibir datos del socket asignar los valores $timeout(function () { // Emitir evento de datos recibidor para el modelo thiz.$setRemoteValues(data.values, data.version); }); }); }; // Agrega un mandejador de eventos Model.prototype.$bind = function (eventName, handler) { idbUtils.validate(arguments, ['string', ['function', 'undefined']]); if (!this.$eventsHandlers[eventName]) { this.$eventsHandlers[eventName] = []; } this.$eventsHandlers[eventName].push(handler); return this; }; // Dispara un evento Model.prototype.$emit = function (eventName, args) { const thiz = this; idbUtils.validate(arguments, ['string', ['undefined', 'array']]); // Llamar el evento para el modelo Model.emit(eventName, [thiz, [].concat([thiz]).concat(args)]); if (thiz.$eventsHandlers[eventName]) { thiz.$eventsHandlers[eventName].map(function (cb) { cb.apply(thiz, args || []); }); } return thiz; }; Model.$instances = $instances; return Model; }; } App/Navigators/AppNavigator.js import * as React from 'react' import { createStackNavigator } from '@react-navigation/stack' import ExampleScreen from 'App/Containers/Example/ExampleScreen' import SplashScreen from 'App/Containers/SplashScreen/SplashScreen' /** * The root screen contains the application's navigation. * * @see https://reactnavigation.org/docs/en/hello-react-navigation.html#creating-a-stack-navigator */ const Stack = createStackNavigator() function AppNavigator() { return ( ) } export default AppNavigator /** * Created by KelvinSen on 2016/1/23. */ define([ 'root/store', 'action/reorder' ], (store, AReorder) => () => { store.dispatch(AReorder.setSentence([ { sentence: '我帅故我在3', correctIndex: 3 }, { sentence: '我帅故我在4', correctIndex: 4 }, { sentence: '我帅故我在2', correctIndex: 2 }, { sentence: '我帅故我在0', correctIndex: 0 }, { sentence: '我帅故我在1', correctIndex: 1 }, ])); store.dispatch(AReorder.initialized()); });0 var util = function () { console.log('In util function') } util.addFunc = function (a, b) { return a + b } function diffFunc (a, b) { return a - b } util.diffFunc = diffFunc util.prodFunc = function prodFunc (a, b) { return a * b } util.sqrFunc = function (a) { // return prodFunc(a, a) -- can't use this way return this.prodFunc(a, a) // or util.prodFunc(a, a) } util.cubeFunc = function (a) { return util.prodFunc(a, a) * a } module.exports = util arcgisapi/Clatsop County Parcel Viewer/dynamic-modules/preload.js0 // All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://@sbaseurl@/jsapi/jsapi/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details. //>>built define(["dojo/topic"],function(a){a.publish("preloadModulesLoaded")});dev/demo/hintdemo.js requirejs.config({ baseUrl: '../js/src', paths : { 'lib': '../lib' } }); var hint = undefined; require(['plugin/server','panel/query', 'hint','hint/foundries/cnx','lib/domReady'], function (pluginClass, queryPanelClass, hintClass, hintArray, domReady) { KorAP.hintArray = hintArray; KorAP.Hint = null; domReady(function() { KorAP.Hint = hintClass.create(); /** * Add query panel */ var queryPanel = queryPanelClass.create(); // Get input field var sform = document.getElementById("searchform"); var vcView = document.getElementById('vc-view') if (sform && vcView) { // The views are below the query bar sform.insertBefore(queryPanel.element(),vcView); KorAP.Panel = KorAP.Panel || {}; KorAP.Panel['query'] = queryPanel; } // Load plugin server KorAP.Plugin = pluginClass.create(); // Register match plugin KorAP.Plugin.register({ 'name' : '', 'desc' : 'Some content about cats', 'embed' : [{ 'panel' : 'query', 'title' : 'Translate', 'classes' : ['translate'], 'onClick' : { "template" : "http://localhost:3003/demo/plugin-client.html" } },{ 'panel' : 'query', 'title' : 'Glemm', 'classes' : ['glemm'], 'onClick' : { "action":"toggle", "template" : "http://localhost:3003/demo/plugin-client.html" } }] }); // Register match plugin KorAP.Plugin.register({ 'name' : 'Glimpse', 'desc' : 'Shorten all queries', 'embed' : [{ 'panel' : 'query', 'title' : 'Glimpse', 'classes' : ['glimpse'], 'onClick' : { "action" : "toggle", "template" : "http://localhost:3003/demo/plugin-client.html" } }] }); }); }); function demoAlert (pos, msg) { if (KorAP.hint !== undefined) KorAP.Hint.alert(pos, msg); } import Router from './Router'; function leads() {} leads.Router = function(options) { return new Router(options); } export default leadsconst { recoverPrivateKeyJwk, updatePrivateKeyJwk, signingPrivateKeyJwk, createOperation, } = require('../__fixtures__'); const { SidetreeWalletPlugin } = require('@sidetree/wallet'); const { Multihash } = require('@sidetree/common'); const wallet = SidetreeWalletPlugin.build(); it('create operation can match ION SDK', () => { const recoverPublicKeyJwk = { ...recoverPrivateKeyJwk }; delete recoverPublicKeyJwk.d; const updatePublicKeyJwk = { ...updatePrivateKeyJwk }; delete updatePublicKeyJwk.d; const document = { publicKeys: [ { id: 'signing-key', type: 'EcdsaSecp256k1VerificationKey2019', publicKeyJwk: { kty: 'EC', crv: 'secp256k1', x: '', y: '', }, }, ], }; const op = wallet.operations.create({ document, updateKey: updatePublicKeyJwk, recoveryKey: recoverPublicKeyJwk, }); expect(op).toEqual(createOperation); }); describe('can create DID_CREATE_OPERATION from keys', () => { it('ION CLI create gives you 3 keys to start', async () => { // all 3 keys are different. expect(recoverPrivateKeyJwk).not.toEqual(updatePrivateKeyJwk); expect(updatePrivateKeyJwk).not.toEqual(signingPrivateKeyJwk); expect(signingPrivateKeyJwk).not.toEqual(recoverPrivateKeyJwk); }); describe('suffixData', () => { it('the recoveryCommitment is computed from the recoverPublicKeyJwk', async () => { const recoverPublicKeyJwk = { ...recoverPrivateKeyJwk }; delete recoverPublicKeyJwk.d; const recoveryCommitment = Multihash.canonicalizeThenDoubleHashThenEncode( recoverPublicKeyJwk ); expect(createOperation.suffixData.recoveryCommitment).toBe( recoveryCommitment ); }); it('the deltaHash is computed from the delta', async () => { const deltaHash = Multihash.canonicalizeThenHashThenEncode( createOperation.delta ); expect(createOperation.suffixData.deltaHash).toBe(deltaHash); }); }); describe('delta', () => { describe('updateCommitment', () => { it('the updateCommitment is computed from the updatePublicKeyJwk', async () => { const updatePublicKeyJwk = { ...updatePrivateKeyJwk }; delete updatePublicKeyJwk.d; const updateCommitment = Multihash.canonicalizeThenDoubleHashThenEncode( updatePublicKeyJwk ); expect(createOperation.delta.updateCommitment).toBe(updateCommitment); }); }); describe('patches', () => { it('create operation delta.patches is an array which replaces a key', async () => { const { publicKeyJwk, } = createOperation.delta.patches[0].document.publicKeys[0]; const signingPublicKeyJwk = { ...signingPrivateKeyJwk }; delete signingPublicKeyJwk.d; expect(publicKeyJwk).toEqual(signingPublicKeyJwk); }); }); }); }); /** * @file Defines the DeleteOneResponse class. * * @author <> * @author <> * @since 5.0.0 * @license See LICENSE.md for details about licensing. * @copyright 2017 C2C Schools, LLC */ "use strict"; const SuccessResponse = require( "./SuccessResponse" ); /** * This response class represents an API response for a 'DeleteOne' endpoint. * * @memberOf Response * @extends Response.SuccessResponse */ module.exports = class DeleteOneResponse extends SuccessResponse { /** * Creates a JSON-API compatible scaffold for the response body [object]. * * This method extends the `BaseResponse` scaffold by adding the data. * * @private * @returns {Object} Response body. */ _createResponseBody() { let sBody = super._createResponseBody(); return sBody; } }; var debug = require('debug')('axm:events'); var Transport = require('./utils/transport.js'); var Common = require('./common.js'); var stringify = require('json-stringify-safe'); var Events = {}; Events.emit = function(name, data) { if (!name) return console.error('[AXM] emit.name is missing'); if (!data) return console.error('[AXM] emit.data is missing'); var inflight_obj = {}; if (typeof(data) == 'object') inflight_obj = JSON.parse(stringify(data)); else { inflight_obj.data = data; } inflight_obj.__name = name; Transport.send({ type : 'human:event', data : inflight_obj }, true); return false; }; module.exports = Events; Javascript/Algorithms/806.js let numberOfLines = (widths, s) => { const lcEng = "abcdefghijklmnopqrstuvwxyz", mapper = (el, idx) => [lcEng[idx], el]; let lines = 0, line = 0; // Create mapping from characters to values const dwidths = new Map(widths.map(mapper)); for (let c of s){ let width = dwidths.get(c); line += width; if (line > 100) { lines += 1; line = width; } } return [lines + (line > 0 ? 1 : 0), line]; }; EcutDavid/automation-inspector /** * @license * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Base class for a view tree on the client, extended by * NodeTree, EventTree and PropsTree */ // Qs: // - Why isn't source=user happening for every click event //-- // - DCHECK failing in ax_enums.cc at end of ToString(AXState) // - Automation docs: // - textChanged event, why both event and treeChange? // - treeChanged event, how is this different from other tree changes? // - findAll syntax does not work as it is not valid JS: // { StateType.disabled: false } // - Some methods use callbacks -- should be documented // - Cannot find sub-objects with find/findAll, e.g. htmlAttributes ala: // tree.rootNode.findAll({ attributes: {"htmlAttributes": {"id": "foo"}}}) /* exported Tree */ class Tree { constructor() { this.DEFAULT_TREE_OPTIONS = { // Get config options at http://wwwendt.de/tech/fancytree/demo/sample-configurator.html activeVisible: true, // Make sure, active nodes are visible (expanded) aria: true, // Enable WAI-ARIA support autoActivate: true, // Automatically activate a node when it is focused using keyboard autoCollapse: false, // Automatically collapse all siblings, when a node is expanded autoScroll: true, // Automatically scroll nodes into visible area clickFolderMode: 4, // 1:activate, 2:expand, 3:activate and expand, 4:activate (dblclick expands) checkbox: false, // Show checkboxes debugLevel: 1, // 0:quiet, 1:normal, 2:debug disabled: false, // Disable control filter: { autoApply: false, // Overridden by specific implementation autoExpand: true, // Expand all branches that contain matches while filtered counter: false, // Show a badge with number of matching child nodes near parent icons fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar' hideExpandedCounter: true, // Hide counter badge if parent is expanded hideExpanders: false, // Hide expanders if all child nodes are hidden by filter highlight: false, // Highlight matches by wrapping inside tags leavesOnly: false, // Match end nodes only nodata: true, // Display a 'no data' status node if result is empty mode: 'hide' // Grayout unmatched nodes (pass "hide" to remove unmatched node instead) }, focusOnSelect: false, // Set focus when node is checked by a mouse click escapeTitles: false, // Escape `node.title` content for display generateIds: true, // Generate id attributes like icon: false, // Display node icons keyboard: true, // Support keyboard navigation keyPathSeparator: '/', // Used by node.getKeyPath() and tree.loadKeyPath() minExpandLevel: 1, // 1: root node is not collapsible quicksearch: false, // Navigate to next node by typing the first letters rtl: false, // Enable RTL (right-to-left) mode selectMode: 2, // 1:single, 2:multi, 3:multi-hier tabindex: '0', // Whole tree behaves as one single control titlesTabbable: false, // Node titles can receive keyboard focus tooltip: false, // Use title as tooltip (also a callback could be specified) focusTree: (event, data) => { const tree = data.tree; if (!tree.getFocusNode()) { const firstVisible = tree.rootNode.getFirstChild(); if (firstVisible) { firstVisible.setActive(); } } } }; const onDocumentReady = () => { window.client.getRootAutomationNode() .then((rootNode) => this.init(rootNode)); }; $(document).ready(onDocumentReady); } onResize() { const fieldsetHeight = this.$container.parent('fieldset').height(); const containerTop = this.$container.position().top; const desiredHeight = fieldsetHeight - containerTop; this.$container.css('max-height', desiredHeight + 'px'); this.$container.find('>.fancytree-container').css('max-height', desiredHeight + 'px'); } finalize($container, treeOptions) { this.$container = $container; // Prepare size and handle window resizing this.onResize($container); $(window).on('resize', () => { this.onResize(); }); // Create and cache Fancytree this.tree = $container .fancytree(treeOptions) .fancytree('getTree'); } static getStateText(state) { return state.join(' '); } static formatStateForTreeGrid(state) { return Tree.getStateText(state); } // TODO Remove if we decide only to use treegrid static formatStateForTree(state) { return '' + state.join(' ') + ''; } // This is the invisible root node of the tree widget implementation, // currently implemented by FancyTree getViewRootNode() { return this.tree && this.tree.rootNode; } filter(filterFn, opts) { this.filterFn = filterFn; return this.tree.filterNodes(filterFn, opts); } clearFilter() { this.filterFn = null; this.tree.clearFilter(); } getRowElement(key) { return document.getElementById(this.ID_PREFIX + key); } getViewNodeByKey(key, startNode) { // Ensure string key as this is how fancytree stores it return this.tree.getNodeByKey('' + key, startNode); } clearAll() { this.tree.clear(); } enableUpdate(doEnable) { this.tree.enableUpdate(doEnable); } } import React, { useEffect, useState } from "react"; import { useHistory } from "react-router-dom"; import { Table, TableBody, TableContainer, TableCell, TableRow, Paper, Typography, Tab, Tabs, } from "@material-ui/core"; import TableRowMenu from "../../components/Table/TableRowMenu"; import TableTop from "../../components/Table/TableTop"; import TableHeader from "../../components/Table/TableHead"; import TablePaging from "../../components/Table/TablePaging"; import { useApi } from "../../hooks/useApi"; import { convertParamsToQueryString, hasPermission } from "../../helpers/utils"; import DialogActions from "../../redux/actions/dialogAction"; import styles from "./style"; import Constant from "../../helpers/constant"; import Detail from "./detail"; import { Slide } from "@material-ui/core"; import TableSkeleton from "../../components/Skeleton"; const headCells = [ { id: "name", label: "نام شخص", }, { id: "type", label: "نوع", }, { id: "logo", label: "بانک", }, { id: "cardNumber", label: "شماره کارت" }, { id: "action" }, ]; const PERSON_TYPE = { EMPLOYEE: "پرسنل", CUSTOMER: "مشتری", DRIVER: "راننده", }; const AccountsNumber = () => { const classes = styles(); const [order, setOrder] = useState("asc"); const [orderBy, setOrderBy] = useState("name"); const [search, setSearch] = useState(); const [page, setPage] = useState(0); const [pageSize, setPageSize] = useState(Constant.TABLE_PAGE_SIZE); const [list, setList] = useState([]); const [total, setTotal] = useState(0); const [person, setPerson] = useState("ALL"); const handleRequestSort = (event, property) => { const isAsc = orderBy === property && order === "asc"; setOrder(isAsc ? "desc" : "asc"); setOrderBy(property); }; const handleChangePage = (event, newPage) => { setPage(newPage); }; const handleChangeRowsPerPage = (event) => { setPageSize(parseInt(event.target.value, Constant.TABLE_PAGE_SIZE)); setPage(0); }; const onSearch = (value) => { setSearch(value); setPage(0); }; const getCardRequest = useApi({ method: "get", url: `account?${convertParamsToQueryString({ page, order, orderBy, pageSize, search, personType: person, })}`, }); const onDismissDetail = () => { DialogActions.hide({ name: "personAccount" }); }; const handleDetail = (row) => { DialogActions.show({ title: `حساب های ${row.personName}`, component: , name: "personAccount", size: "6", confirm: false, disableCloseButton: false, }); }; const getData = async () => { const cardList = await getCardRequest.execute(); setList(cardList.data); setTotal(cardList.total); }; const onChangeTab = (e, value) => { setPerson(value); }; useEffect(() => { getData(); }, [page, order, search, pageSize, person]); return ( <> {hasPermission(Constant.ALL_PERMISSIONS.CASH_LIST) && (
    {getCardRequest.pending ? ( ) : (
    {list.map((row) => { return ( {row.personName} {PERSON_TYPE[row.personType]} {row.bank && ( {row.bank.name} )} {row.accountCardNumber} handleDetail(row)} > link ); })} {!list.length && !getCardRequest.pending && ( داده ای برای نمایش وجود ندارد )}
    )}
    )} ); }; export default AccountsNumber; (function(angular) { 'use strict' function openPopUpDelete(details){ var popUpCtrl = this; var modalInstance = popUpCtrl.$uibModal.open({ component:'deleteAdminModal', windowClass: 'app-modal-window-small', keyboard: false, resolve: { details: function(){ return (details || {}); } }, backdrop: 'static' }); modalInstance.result.then(function(data) { if (data && data.action == "update") popUpCtrl.init(); // if(data && data.action == "delete") { // var index = data.details; // this.adminList.splice(index, 1); // } }), function(err){ console.log('Error in manage-admin Modal'); console.log(err); } }; function openPopUpAdmin(details) { var popUpCtrl = this; var modalInstance = popUpCtrl.$uibModal.open({ component: 'addAdminModal', windowClass: 'app-modal-window-large', keyboard: false, resolve: { details: function() { return (details || {}); } }, backdrop: 'static' }); modalInstance.result.then(function(data) { //data passed when pop up closed. if (data && data.action == "update") popUpCtrl.init(); }), function(err) { console.log('Error in manage-admin Modal'); console.log(err); } } function manageAdminController($state, $uibModal, AdminManagerService) { var ctrl = this; ctrl.$uibModal = $uibModal; ctrl.$state = $state; ctrl.adminList = []; //API /admin/login ctrl.init = function() { ctrl.isSuperAdmin = true; ctrl.loader = true; getAdminList(); }; ctrl.continue = function(){ $state.go('index'); }; ctrl.edit = function(adminrights) { angular.bind(ctrl, openPopUpAdmin, angular.copy(adminrights))(); }; ctrl.delete = function(selectedEmail) { angular.bind(ctrl,openPopUpDelete,selectedEmail)(); }; ctrl.selectRow = function(rowIndex){ ctrl.selectedRow = rowIndex; }; ctrl.addadmin = function() { angular.bind(ctrl, openPopUpAdmin, null)(); }; function getAdminList(){ AdminManagerService.listofAdmin() .then(function(response) { ctrl.loader = false; if (response && response.data && angular.isObject(response.data)) { ctrl.adminList = response.data; } }) .catch(function(err) { console.log('Error getting Admin lists:'); console.log(err); }) }; ctrl.init(); } angular.module('manageAdmin') .component('manageAdmin', { templateUrl: 'manage-admin/manage-admin-details/manage-admin-details.template.html', controller: ['$state', '$uibModal','AdminManagerService', manageAdminController] }); })(window.angular);/*jslint browser: true*/ /*global console, hrApp*/ hrApp.angular.controller('FrontPageController', ['$scope', '$http', 'InitService', 'DataService', function ($scope, $http, InitService, DataService) { 'use strict'; $scope.search_text =''; $scope.onSearch = function () { globalCat = 'search'; globalKeyword = $scope.search_text; console.log('set keyword '+ globalKeyword); // goto the index page hrApp.fw7.views[0].router.load({pageName: 'indexPage'}); } $scope.globalPanel = function(div) { Dom7('.paneldiv').hide(); Dom7('#'+div).show(); } }]);iondrive/backend-boilerplate import * as Promise from 'bluebird'; exports.setup = () => { return Promise.resolve(); }; exports.cleanup = () => { return Promise.resolve(); };'use strict'; const sidekickAnalyser = require("@sidekick/analyser-common"); const fs = require('fs'); const path = require('path'); const david = require('david'); const Promise = require('bluebird'); const location = require('./src/locationInFile'); if(require.main === module) { execute(); } module.exports = exports = execute; const annotationDefaults = {analyserName: 'sidekick-david'}; const LOG_FILE = path.join(__dirname, '/debug.log'); //log to file as any stdout will be reported to the analyser runner function logger(message) { fs.appendFile(LOG_FILE, message + '\n'); } /** * Entry function for every analyser. Use sidekickAnalyser to provide input function. */ function execute() { sidekickAnalyser(function(setup) { var fileRegex = setup.fileRegex; //you can override the package.json re in the analyser config if(isManifest(setup.filePath, fileRegex)){ run(JSON.parse(setup.content), setup.content).then(function(results){ console.log(JSON.stringify({ meta: results })); }); } else { console.log(JSON.stringify({ meta: [] })); //file was .json but not the root package.json } }); /** * Check that the file being analysed is a package.json file * @param fileRegex (optional) will default to os specific re for package.json * @returns {*} */ function isManifest(filePath, fileRegex){ var regex = /^package\.json$/i; //only match package.json in root (the repo's package.json) var fileRe = fileRegex || regex; //you can override with a regex in the analyser config return fileRe.test(filePath); } } //need the manifest as an object (for david) and the raw file contents (not stringified obj) so we can find line no.s module.exports._testRun = run; //exposed to tests (hence the 2 args) function run(manifestObj, manifestContent) { if(!manifestContent){ console.error("failed to analyse - no manifest content"); console.log({ error: err }); process.exit(1); } return scan(manifestObj) .then( function(deps){ return convertToAnnotations(deps, manifestContent); }, function(err){ console.error("failed to analyse"); console.log({ error: err }); process.exit(1); } ); } function scan(manifest) { var opts = {stable: true}; //for now, only flag if there are updated stable dependencies var devOpts = {stable: true, dev: true}; var optOpts = {stable: true, optional: true}; var getDeps = Promise.promisify(david.getUpdatedDependencies); //david treats deps, devDeps and optDeps separately, so fetch all together return Promise.all([ getDeps(manifest, opts), getDeps(manifest, devOpts), getDeps(manifest, optOpts) ]).then(function(deps){ return deps; }, function(err){ throw new Error('Unable to get deps: ' + err.getMessage()); }); } function convertToAnnotations(data, manifestContent){ var deps = data[0], devDeps = data[1], optDeps = data[2]; var results = [], prop; //trying to reduce required modules so no lodash for(prop in deps){ if(deps.hasOwnProperty(prop)){ it(prop, deps[prop]); } } for(prop in devDeps){ if(devDeps.hasOwnProperty(prop)){ it(prop, devDeps[prop], true); } } for(prop in optDeps){ if(optDeps.hasOwnProperty(prop)){ it(prop, optDeps[prop], false, true); } } return results; function it(depName, dep, isDev, isOpt){ var location = getPositionInPackageJson(manifestContent, depName, isDev, isOpt); var message = getMessage(depName, dep); var kind = getKind(isDev, isOpt); var category = getCategory(isDev, isOpt); results.push(format({ location: location, message: message, kind: kind, category: category})); } //TODO - better find in package.json (uses indexOf currently) function getPositionInPackageJson(manifestContent, depName, isDev, isOpt){ return location('"' + depName + '"', manifestContent); } function getKind(isDev, isOpt){ if(isDev){ return 'dev_dependency_outdated'; } else if(isOpt){ return 'optional_dependency_outdated'; } else { return 'dependency_outdated'; } } function getCategory(isDev, isOpt){ if(isDev){ return 'Dev dependencies'; } else if(isOpt){ return 'Optional dependencies'; } else { return 'Dependencies'; } } function getMessage(depName, dep) { var required = dep.required || '*'; var stable = dep.stable || 'None'; var latest = dep.latest || 'None'; return `Dependency '${depName}' is out of date. You use '${required}', which could be updated to stable: '${stable}' (latest: '${latest}').`; } } function format(dep) { var location = {startCol: 0, endCol: 0}; location.startLine = dep.location.line; location.endLine = dep.location.line; return { analyser: annotationDefaults.analyserName, location: location, message: dep.message, kind: dep.kind, category: dep.category, }; } jehy/charsheet-commons import $ from 'jquery'; import * as request from 'axios'; import {errorPanel} from './panels'; import {isDevel} from './options'; async function compareRevisions() { let compareFrom = ''; let compareTo = ''; let selected = $("input[type='radio'][name='compare_from']:checked"); if (selected.length > 0) { compareFrom = selected.val(); } else { errorPanel.show('Please select a revision to compare from!'); return false; } selected = $("input[type='radio'][name='compare_to']:checked"); if (selected.length > 0) { compareTo = selected.val(); } else { errorPanel.show('Please select a revision to compare to!'); return false; } // console.log('comparing ' + compare_from + ' to ' + compare_to); const data = {compare_from: compareFrom, compare_to: compareTo}; try { const reply = await request({ url: '/api/compare_revisions', data, type: 'POST', }); if (reply.error) { errorPanel.show(`Please correct your input:

    ${reply.error}

    `); return false; } $('.compare_revisions').html(reply.diff); return true; } catch (err) { errorPanel.show(`Error comparing revisions, error:

    ${err.message}

    `); console.log(err); return false; } } function viewRevision(id) { const {pathname} = window.location; const path = pathname.split('/'); if (parseInt(id, 10) === 0) { window.location.replace(`/${path[1]}/${path[2]}/${path[3]}/`); return; } const revision = `/${path[1]}/${path[2]}/${path[3]}/${id}/`; window.location.replace(revision); } async function restoreRevision(revisionId) { const data = {revision_id: revisionId}; try { const reply = await request({ url: '/api/restore_revision', data, type: 'POST', }); if (reply.error) { errorPanel.show(`Please correct your input:

    ${reply.error}

    `); return false; } viewRevision(0); return true; } catch (err) { errorPanel.show(`Error restoring revision, error:

    ${err.message}

    `); console.log(err); return false; } } async function loadRevisions() { if (isDevel()) { return true; } try { const data = await request('/api/get_revisions'); const table = $('.revisions tbody'); table.empty();// clean let i = 1; data.forEach((arr)=>{ if (!arr.id) { arr.id = 0; } const row = $(''); row.append(`${i}${arr.nick}${arr.made}${arr.comment}`); row.append(` `); const viewRevisionBtn = $(''); viewRevisionBtn.click(()=>viewRevision(arr.id)); row.append($('').append(viewRevisionBtn)); if (arr.id !== 0)// not current { const restoreRevisionButton = $(''); restoreRevisionButton.click(()=>restoreRevision(arr.id)); row.append($('').append(restoreRevisionButton)); } else row.append(''); table.append(row); i++; }); return true; } catch (err) { errorPanel.show(`Error getting comments

    ${err.message}

    `); console.log(err); return false; } } async function saveRevision() { const comment = $('input[name="revision_comment"]').val(); if (!comment) { errorPanel.show('Please enter comment text'); return false; } const data = {comment}; try { const reply = await request({ url: '/api/add_revision', data, type: 'POST', }); if (reply.error) { errorPanel.show(`Please correct your input:

    ${reply.error}

    `); return false; } return loadRevisions(); } catch (err) { errorPanel.show(`Error saving revision, error:

    ${err.message}

    `); console.log(err); return false; } } export { loadRevisions, compareRevisions, viewRevision, restoreRevision, saveRevision, }; import React from 'react' import Icon from './Icon' export default (props) => (

    {props.title}

    { props.data.map((el, index) => ( )) }
    )var structEmberAfClusterList = [ [ "deviceId", "structEmberAfClusterList.html#aaa0f43d59cd806d0f4a017411815bc61", null ], [ "endpoint", "structEmberAfClusterList.html#a112b8e8e831046c1b77a58a7f732fd68", null ], [ "inClusterCount", "structEmberAfClusterList.html#ae0244d2925aeaa3c86dc00b04df8d097", null ], [ "inClusterList", "structEmberAfClusterList.html#abbbb1625ca61728a2634043c2d01ecb0", null ], [ "outClusterCount", "structEmberAfClusterList.html#aa3cbe198f5c16afcd79f42fe7f0e4c8c", null ], [ "outClusterList", "structEmberAfClusterList.html#acdd3d69ee3a0abdce598619ceb4ac73b", null ], [ "profileId", "structEmberAfClusterList.html#ad66aba37218a92300b6a7baf10c66fb0", null ] ];//Switch = chave/ligar ou desligar/interruptor //Vamos imaginar que eu queira verificar se certos alunos conseguiram ou não nota pra passar na prova. E eu vou mandar uma mensagem de acordo com a nota. var p1= parseInt (prompt("Qual a nota da prova 1: ")); var p2= parseInt (prompt("Qual a nota da prova 2: ")); alert("A média é acima de 6") var media= (p1+p2)/2; var conceito="" //essa é uma variável que vai receber um valor dependendo do if; if(media>8.5){ conceito="Ótimo"; } else if(media >7){ conceito="Bom"; } else if(media > 6){ conceito="Regular"; } else{ conceito="Reprovado" } alert(conceito + " sua média é: " + media); //Agora vou exibir a mensagem switch (conceito){ //dentro do parenteses está o que eu vou analisar case "Ótimo": //precisa dos dois pontos alert('Parabéns, você é um estudante excelente, continue assim'); break; //precisa do break se não ele exibe tudo abaixo case "Bom": alert('Parabéns, você foi bem, mas podia ser melhor, se esforce mais'); break; case "Regular": alert('Parabéns, você foi aprovado, mas por pouco, melhore mais'); break; case "Reprovado": alert('Infeliz você não se esforçou o suficiente, vá a cordenação para mais instruções'); break; default://default = padrão alert('ERRO'); break; //no default isso é meio irrelevante }example/src/App.js import React, { useState, useEffect } from 'react' import { MEditor } from 'react-m-editor' import logo from './logo.svg' import 'react-m-editor/dist/index.min.css' // import { text } from './example' export default function App () { const [value, setValue] = useState('') const [theme, setTheme] = useState('light') useEffect(() => { setTimeout(() => { setValue('hello world') }, 200) }, []) const handleChange = ({ content, htmlContent }) => { console.log(htmlContent) setValue(content) } const toggleTheme = () => { setTheme(theme === 'light' ? 'dark' : 'light') } return (
    logo
    ) } Logging/services/loggingService.js0 const mongoose = require('mongoose'); module.exports.fillJson = function(keys, data){ let json = {} for(i = 0; i < keys.length; i++){ let key = keys[i] if(key != 'logCreatedAt' && key != 'source' && key != 'details' && key != 'signature' && key != 'ssoUserId' && key != 'timestamp') json[key] = data[key]; //Adds an unused or required field to the json object } if('sessionCreatedAt' in json && 'sessionUpdatedAt' in json && 'sessionExpiredAt' in json){ let createdDate = new Date(parseInt(json.sessionCreatedAt.substr(6))); //Formats the fields let updatedDate = new Date(parseInt(json.sessionUpdatedAt.substr(6))); let expiredAt = new Date(parseInt(json.sessionUpdatedAt.substr(6))); let duration = (updatedDate.getTime() - createdDate.getTime()) / 1000; //Retrieves duration of session json.sessionCreatedAt = createdDate; json.sessionUpdatedAt = updatedDate; json.sessionExpiredAt = expiredAt; json['sessionDuration'] = duration;//Adds duration of session } return json } module.exports.checkLogSpace = function(callback){ let db = mongoose.connection; db.db.stats({scale: 1024}, (err, stats) => { //bytes are in kilobytes if(err){ console.log(err) return callback(false); }else{ if(stats['fsUsedSize'] > (stats['fsTotalSize'] + 2048)) //at least two megabytes left before storing a log return callback(false); return callback(true); } }) }export default class FuzzySet { constructor(peakPoint,leftOffset,rightOffset) { this.peakPoint = peakPoint; this.leftOffset = leftOffset; this.rightOffset = rightOffset; } triangularDom(value){ if(value <= this.peakPoint && value>= this.peakPoint - this.leftOffset){ let gradient = 1.0 / this.leftOffset; return gradient * (value - (this.peakPoint - this.leftOffset)); } else if(value > this.peakPoint && value < this.peakPoint + this.rightOffset){ let gradient = -1.0 / this.rightOffset; return gradient * (value - this.peakPoint) + 1.0; } else return 0; } leftShoulderDom(value){ if(value >= this.peakPoint && value < this.peakPoint + this.rightOffset){ let gradient = (1.00 / this.rightOffset); return gradient * ((this.peakPoint + this.rightOffset) - value ); } else if(value < this.peakPoint){ return 1.00; } else return 0; } rightShoulderDom(value){ if(value <= this.peakPoint && value > this.peakPoint - this.leftOffset){ let gradient = 1.00 / this.leftOffset; return gradient * (value - (this.peakPoint - this.leftOffset)); } else if(value > this.peakPoint){ return 1.00; } else return 0; } }shikhar0208/OrganChain1-10 import web3 from './web3'; import OrganChain from './build/OrganChain.json'; const instance = new web3.eth.Contract( JSON.parse(OrganChain.interface), '0x39455f58763AF5515dF6a262Be5e19Ca17B1F53e' ) export default instance;<% //============================================================================= // Jocys.com JavaScript.NET Classes (In C# Object Oriented Style) // Created by <> //----------------------------------------------------------------------------- // You can include this script on both sides - server and client: // Server: // Client: //----------------------------------------------------------------------------- // Warning: Be careful about what code you include in such way. Since the code // will be passed to the client side as simple text, your code can be seen by // anyone who wants. Never do this with scripts which contain any kind of // passwords, database connection strings, or SQL queries. //============================================================================= /// //============================================================================= // Namespaces //----------------------------------------------------------------------------- // // System.TestTools.UnitTesting // //----------------------------------------------------------------------------- System.Type.RegisterNamespace("System.TestTools.UnitTesting"); //============================================================================= // http://docs.jquery.com/QUnit // http://indomitablehef.com/?p=221 Test = QUnit.test; Module = QUnit.module; System.TestTools.UnitTesting.Assert = { _FormatMessage: function(index, args){ var aLen = args.length - 1; if (aLen < index) return; if (aLen == index) return args[index]; var params = new Array(args.length - index); for (var i = 0; i < params.length; i++) params[i] = args[i+index]; return String.Format.apply(String, params); }, AreEqual: function(expected, actual, message, parameters) { /// /// Verifies that two specified objects are equal. The assertion fails if the objects are not equal. /// Displays a message if the assertion fails, and applies the specified formatting to it. /// /// The first object to compare. This is the object the unit test expects. /// The second object to compare. This is the object the unit test produced. /// A message to display if the assertion fails. This message can be seen in the unit test results. /// An array of parameters to use when formatting . message = this._FormatMessage(2, arguments); equals(actual, expected, message); }, AreNotEqual: function(expected, actual, message, parameters) { message = this._FormatMessage(2, arguments); ok(actual != expected, message); }, AreSame: function(expected, actual, message, parameters) { message = this._FormatMessage(2, arguments); deepEqual(actual, expected, message); }, AreNotSame: function(expected, actual, message, parameters) { message = this._FormatMessage(2, arguments); notDeepEqual(actual, expected, message); }, IsInstanceOfType: function(value, expectedType, message, parameters) { /// /// Verifies that the specified object is an instance of the specified type. /// The assertion fails if the type is not found in the inheritance hierarchy of the object. /// Displays a message if the assertion fails, and applies the specified formatting to it. /// /// The object to verify is of . /// The type expected to be found in the inheritance hierarchy of . /// A message to display if the assertion fails. This message can be seen in the unit test results. /// An array of parameters to use when formatting . message = this._FormatMessage(2, arguments); var aType = "[object "+value+"]"; var eType = "[object "+ expectedType +"]"; //if (aType == "[object Object]") aType = "[object "+value.GetType().FullName+"]"; equal(aType, eType, message); }, IsNotInstanceOfType: function(value, expectedType, message, parameters) { message = this._FormatMessage(2, arguments); var aType = "[object "+value+"]"; var eType = "[object "+ expectedType +"]"; //if (aType == "[object Object]") aType = "[object "+value.GetType().FullName+"]"; notEqual(aType, eType, message); }, IsNull: function(value, message, parameters) { message = this._FormatMessage(1, arguments); var aType = "[object "+value+"]"; var eType = "[object null]"; //if (aType == "[object Object]") aType = "[object "+value.GetType().FullName+"]"; equal(aType, eType, message); }, IsNotNull: function(value, message, parameters) { message = this._FormatMessage(1, arguments); var aType = "[object "+value+"]"; var eType = "[object null]"; //if (aType == "[object Object]") aType = "[object "+value.GetType().FullName+"]"; notEqual(aType, eType, message); }, IsTrue: function(condition, message, parameters) { /// /// Verifies that the specified condition is true. The assertion fails if the condition is false. /// Displays a message if the assertion fails, and applies the specified formatting to it. /// /// The condition to verify is true. /// A message to display if the assertion fails. This message can be seen in the unit test results. /// An array of parameters to use when formatting . message = this._FormatMessage(1, arguments); ok(condition, message); }, IsFalse: function(condition, message, parameters) { /// /// Verifies that the specified condition is false. The assertion fails if the condition is true. Displays a message if the assertion fails, and applies the specified formatting to it. /// /// The condition to verify is false. /// A message to display if the assertion fails. This message can be seen in the unit test results. /// An array of parameters to use when formatting . message = this._FormatMessage(1, arguments); ok(!bool, message); } } Assert = System.TestTools.UnitTesting.Assert; //test( name, expected, test ) //Add a test to run. //asyncTest( name, expected, test ) //Add an asynchronous test to run. The test must include a call to start(). //expect( amount ) //Specify how many assertions are expected to run within a test. //module( name, lifecycle ) //Separate tests into modules. //init( ) //Initialize the test runner (if the runner has already run it'll be re-initialized, effectively resetting it). This method does not need to be called in the normal use of QUnit. //============================================================================== // END //------------------------------------------------------------------------------ //%>dayster/Music import React, { Component } from 'react' import { withRouter } from 'react-router-dom' import { connect } from 'react-redux' import { getSearchedArtists, getSearchedTracks, getSearchedPlaylists } from '../actions/search_actions' import { setActiveTracklistSolo } from '../actions/track_actions' import Track from './Track' class Search extends Component { state = { loadingTracks: false, loadingArtists: false, loadingPlaylists: false } componentWillMount() { window.scroll(0, 0) this.makeSearch(this.props) } makeSearch = async props => { this.props.getSearchedArtists(props.location.search.slice(3)) this.props.getSearchedPlaylists(props.location.search.slice(3)) await this.props.getSearchedTracks(props.location.search.slice(3)) let tracklist = { owner: {}, name: '', tracks: { items: [] } } this.props.searchedTracks.map(track => { tracklist.tracks.items.push({ track: track }) }) this.props.setActiveTracklistSolo(tracklist) } componentWillUpdate(nextProps) { if ( nextProps.location.search.slice(3) !== this.props.location.search.slice(3) ) { this.makeSearch(nextProps) window.scroll(0, 0) } } componentWillUnmount() { this.props.setActiveTracklistSolo(null) } navigateToArtistDetailPage = id => { this.props.history.push(`/app/artists/${id}`) } navigateToPlaylist = (userId, playlistId) => { this.props.history.push(`/app/playlists/${userId}/${playlistId}`) } renderArtists = () => { return this.props.searchedArtists.map((artist, index) => { return (
  • this.navigateToArtistDetailPage(artist.id)} className="artist-result" >

    {artist.name}

  • ) }) } renderTracks = () => { return this.props.searchedTracks.map((track, index) => { if (track !== null) { return } }) } renderPlaylists = () => { return this.props.searchedPlaylists.map((playlist, index) => { return (
  • this.navigateToPlaylist(playlist.owner.id, playlist.id) } className="playlist-result" >

    {playlist.name.length > 30 ? playlist.name.substr(0, 27) + '...' : playlist.name}

  • ) }) } render() { return (

    Result for:

    {this.props.location.search.slice(3)}

    Artists

      {this.props.searchedArtists.length > 0 ? ( this.renderArtists() ) : (
    • No matching artists
    • )}

    Tracks

      {this.props.searchedTracks.length > 0 ? ( this.renderTracks() ) : (
    • No matching tracks
    • )}

    Playlists

      {this.props.searchedPlaylists.length > 0 ? ( this.renderPlaylists() ) : (
    • No matching playlists
    • )}
    ) } } const mapStateToProps = ({ search }) => { return { searchedArtists: search.searchedArtists, searchedPlaylists: search.searchedPlaylists, searchedTracks: search.searchedTracks } } export default withRouter( connect(mapStateToProps, { getSearchedArtists, getSearchedTracks, getSearchedPlaylists, setActiveTracklistSolo })(Search) ) import { ipcRenderer as ipc } from 'electron'; import { stream } from 'kefir'; import initialState from './fsm/initial' export default stream(emitter => { let stateHandler = initialState; ipc.on('stdout', (evt, ch) => { const charCode = ch.charCodeAt(0); stateHandler = stateHandler(charCode, emitter); }); }); util/mailer.js0 const nodemailer = require('nodemailer'); const { formatDailyEmail } = require('../emailTemplates/dailyEmail'); const { config } = require ('../config'); const transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, // true for 465, false for other ports auth: { user: `${config.emailSender}`, // generated ethereal user pass: `${config.}`, // generated ethereal password }, }); exports.makeEmail = (actionValue, emailContent)=> { switch(actionValue) { case 'sendDailyEmail': const title = "BE 進度" const sortedContent = CategorizeItems(emailContent); const emailBody = formatDailyEmail(sortedContent); sendMail(transporter, title, emailBody); break; case 'sendWeeklyEmail': // const title = "BE 上週進度" // const content = formatWeeklyMail(emailContent); // sendMail(transporter, content); break; default: } } function CategorizeItems(emailContent) { const itemCollection = {} const items = emailContent.split("\n"); for(let i=0; i0) { let [leftBracketPosition, rightBracketPosition] = [0, 0] if (item.match(/\[/)) { leftBracketPosition = item.match(/\[/).index } if (item.match(/]/)) { rightBracketPosition = item.match(/]/).index } if (leftBracketPosition==0 && rightBracketPosition!=0) { const itemCategory = item.slice(leftBracketPosition,rightBracketPosition+1).concat(" "); let itemContent = item.slice(rightBracketPosition+1,item.length); itemContent = itemCategory + (itemContent.replace(/\+/g," ")).trim(); itemCollection[itemCategory]=itemCollection[itemCategory]?itemCollection[itemCategory]:{}; itemCollection[itemCategory][itemContent]={"title":itemContent}; } else { if(i>0){ const previousItem = items[i-1]; const previousItemCategory = previousItem.slice(previousItem.match(/\[/).index,previousItem.match(/]/).index+1).concat(" "); let previousItemContent = previousItem.slice(previousItem.match(/]/).index+1,previousItem.length); previousItemContent = previousItemCategory + (previousItemContent.replace(/\+/g," ")).trim(); itemCollection[previousItemCategory][previousItemContent]["note"]= item } } } } // console.log('CategorizeItems: ',itemCollection) return itemCollection } function sendMail(transporter,title, content) { transporter.sendMail({ from: `"${config.emailSenderName}" <${config.sender}>`, // sender address to: config.emailReceivers, subject: title, // text: JSON.stringify(context) html: content // to: context.receiver, // list of receivers // subject: context.subject, // Subject line // text: context.body, // plain text body // html: "Hello world?", // html body }); } import Validator from '../../../popup/RegExpWidget/RegExpValidator'; describe("замена . на [^]", function () { let regexp1 = '^wo(.*)rd$'; let reference1 = '^wo([^]*)rd$'; it(`замена одиночного символа в ${regexp1} должна вернуть ${reference1}`, function () { expect(Validator.replaceAllDotsInRegexp(regexp1)).toBe(reference1); }); let regexp2 = '^wo(\\.*)rd$'; let reference2 = '^wo(\\.*)rd$'; it(`замена c одиночным экранированием ${regexp2} должна вернуть ${reference2}`, function () { expect(Validator.replaceAllDotsInRegexp(regexp2)).toBe(reference2); }); let regexp3 = '^wo(\\\\.*)rd$'; let reference3 = '^wo(\\\\[^]*)rd$'; it(`замена c двойным экранированием ${regexp3} должна вернуть ${reference3}`, function () { expect(Validator.replaceAllDotsInRegexp(regexp3)).toBe(reference3); }); let regexp4 = '^wo(\\\\\\.*)rd$'; let reference4 = '^wo(\\\\\\.*)rd$'; it(`замена c тройным экранированием ${regexp4} должна вернуть ${reference4}`, function () { expect(Validator.replaceAllDotsInRegexp(regexp4)).toBe(reference4); }); let regexp5 = '^wo(.*)rd$'; let source = 'wo\n\n\n\nrd'; it(`валидация с ресурсом с переносом строки должна работать, regexp:${regexp5}, source:${source}`, ()=> { expect(Validator.validate(source, regexp5)[0]).toBe(source); // сматчилась вся строка }); });import React from 'react'; //import RanfiltratorWidget from './RanfiltratorWidget'; import AssetWidget from './AssetWidget'; //import DiceWidget from './DiceWidget'; // intentionally using different style from actiontypes // to test differences export const WidgetFactories = { AssetWidget: React.createFactory(AssetWidget), // DiceWidget: React.createFactory(DiceWidget), //RanfiltratorWidget: React.createFactory(RanfiltratorWidget), }; attilahorvath/systems-offlinesrc/Timer.js1-10 export default class { constructor(timeout, callback = null, repeating = false) { this.timeout = timeout; this.callback = callback; this.repeating = repeating; this.progress = 0; this.enabled = true; } update() { if (!this.enabled) { return; } this.progress += TIME_STEP; if (this.progress >= this.timeout) { if (this.repeating) { this.progress -= this.timeout; } else { this.enabled = false; } if (this.callback) { this.callback(); } } } reset() { this.enabled = true; this.progress = 0; } } RafaelGiro/5pots-cms10-100 import React from 'react'; import styled from 'styled-components'; function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } var _templateObject; var StyledLightbox = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n position: fixed;\n top: 0;\n left: 0;\n width: 100vw;\n height: 100vh;\n background-color: #000;\n\n z-index: 99999999999999999;\n"]))); var Lightbox = function Lightbox() { return /*#__PURE__*/React.createElement(StyledLightbox, null, "Funfou"); }; export default Lightbox; 1-10 import { Route } from 'svc-route' import Tpl from './webtpl' /* global location global XMLHttpRequest */ let tpl = new Tpl() function _$ (selector) { return document.querySelector('#SUBVIEW_' + this.parentPathName + ' ' + (selector || '')) } function _moveNodes (to, from) { while (from.childNodes.length > 0) { to.appendChild(from.childNodes[0]) } } function _setData (values) { let routeChanged = false let path = null for (let key in values) { this.data[key] = values[key] // 绑定的参数反向同步到路由 if (this.routeBinds && this.routeBinds.indexOf(key) !== -1) { // 查找当前路由节点 if (path === null) { for (let p of this.route._routeHistories[this.route._routeHistoryPos]) { if (p.pathName === this.pathName) { path = p } } } // 比较数据是否变更 if (path) { if (path.args[key] !== this.data[key]) { path.args[key] = this.data[key] routeChanged = true } } } // 数据变化后反向同步到路由 if (routeChanged) { this.route.remakeRouteUrl() location.hash = '#' + this.route.routeUrl } } return this.refreshView() } function _refreshView () { return new Promise((resolve, reject) => { if (!this._refreshViewCallbacks) this._refreshViewCallbacks = [] this._refreshViewCallbacks.push([resolve, reject]) if (!this._refreshViewTID) { setTimeout(function () { try { let datas = this.datas || {} datas.data = this.data tpl.make(this.$(), datas) for (let callbacks of this._refreshViewCallbacks) { callbacks[0]() } } catch (err) { for (let callbacks of this._refreshViewCallbacks) { callbacks[1](err) } } finally { this._refreshViewTID = 0 this._refreshViewCallbacks = [] } }.bind(this), 0) } }) } export default class extends Route { constructor (states) { super() this.states = states this._prevPaths = [] } bindHash () { let that = this this.bind('*', (paths) => { if (that.makeRoute(paths)) { location.hash = '#' + this.routeUrl } else { setTimeout(function () { that.go(-1) }) } }) window.addEventListener('hashchange', () => { this.go(location.hash.substr(1)) }) } makeRoute (paths) { // 预处理 let parentView = this.Root let availablePaths = [] let samePos = -1 if (window._cachedViews === undefined) window._cachedViews = {ROOT: this.Root} for (let i = 0; i < paths.length; i++) { let path = paths[i] let prevPath = this._prevPaths[i] let view = window._cachedViews[path.pathName] if (!view) { if (parentView.getSubView) view = parentView.getSubView(path.name) if (!view) break // 生成dom节点 view.dom = document.createElement('div') if (view.html) { if (/\.html\s*$/.test(view.html)) { let xhr = new XMLHttpRequest() xhr.open('GET', view.html, false) xhr.send() view.html = xhr.responseText } view.dom.innerHTML = view.html.replace(/\$this/g, 'window._cachedViews[\'' + path.pathName + '\']').replace('id="SUBVIEW"', 'id="SUBVIEW_' + path.pathName + '"') } window._cachedViews[path.pathName] = view // 新路由节点调用 onCreate if (view.onCreate) { view.onCreate(path) } if (!view.data) { view.data = {} } view.route = this view.$ = _$ view.setData = _setData view.refreshView = _refreshView } view.pathName = path.pathName availablePaths.push(path) parentView = view if (prevPath && prevPath.url === path.url && samePos === i - 1) { samePos = i } } // 旧路由中不一样的部分调用 canHide,确认允许跳转 for (let i = this._prevPaths.length - 1; i > samePos; i--) { let path = i === -1 ? {pathName: 'ROOT'} : this._prevPaths[i] let view = i === -1 ? this.Root : window._cachedViews[path.pathName] if (view.canHide) { if (!view.canHide(path, paths)) { return false } } } // 旧路由中不一样的部分调用 onHide for (let i = this._prevPaths.length - 1; i > samePos; i--) { let path = i === -1 ? {pathName: 'ROOT'} : this._prevPaths[i] let view = i === -1 ? this.Root : window._cachedViews[path.pathName] let prevPath = (i === 0 ? {pathName: 'ROOT'} : this._prevPaths[i - 1]) || null // let prevView = prevPath ? _cachedViews[prevPath.pathName] : null if (view.stateRegisters) { for (let bindKey in view.stateRegisters) { this.states.unbind(bindKey, view.stateRegisters[bindKey]) } } if (view.stateBinds) { this.states.unbind(view.stateBinds, view) } if (view.onHide) view.onHide(path) if (prevPath) { let container = document.querySelector('#SUBVIEW_' + prevPath.pathName) if (container) { _moveNodes(view.dom, container) } } } // 新路由中不一样的部分调用 onShow for (let i = samePos; i < availablePaths.length; i++) { let path = i === -1 ? {pathName: 'ROOT'} : availablePaths[i] let view = window._cachedViews[path.pathName] let nextPath = availablePaths[i + 1] || null let nextView = nextPath ? window._cachedViews[nextPath.pathName] : null if (nextView) { nextView.parentPathName = path.pathName if (view.data) { // 默认维护 subName view.data.subName = nextPath.name } // nextView.$ = this.$ let container = document.querySelector('#SUBVIEW_' + path.pathName) if (container) { _moveNodes(container, nextView.dom) } } // 路由参数并入 view.data if (view.routeBinds) { for (let k of view.routeBinds) { view.data[k] = path.args[k] } } if (i > samePos) { if (view.onShow) view.onShow(path, nextPath, nextView) // 自动绑定state,并触发一次所有绑定事件 if (view.stateRegisters) { for (let bindKey in view.stateRegisters) { let bindTarget = view.stateRegisters[bindKey] this.states.bind(bindKey, bindTarget) if (typeof bindTarget === 'function') { bindTarget(this.states.get(bindKey)) } else if (bindTarget instanceof Array && bindTarget.length === 2) { if (typeof bindTarget[1] === 'function') { bindTarget[1].apply(bindTarget[0], this.states.get(bindKey)) } else if (typeof bindTarget[0][bindTarget[1]] === 'function') { bindTarget[0][bindTarget[1]].apply(bindTarget[0], this.states.get(bindKey)) } } else if (typeof bindTarget === 'object' && typeof bindTarget.setData === 'function') { bindTarget.setData(this.states.get(bindKey)) } } } if (view.stateBinds) { this.states.bind(view.stateBinds, view) for (let bind of view.stateBinds) { if (typeof bind === 'string') { view.data[bind] = this.states.state[bind] } else if (bind instanceof Array && bind.length === 2) { view.data[bind[1]] = this.states.state[bind[0]] } } } } if (view.refreshView) view.refreshView() } this._prevPaths = availablePaths return true } } repos/react-redux/test/react-native/batch-integration.js import React, { Component, useLayoutEffect } from 'react' import { View, Button, Text, unstable_batchedUpdates } from 'react-native' import { createStore, applyMiddleware } from 'redux' import { Provider as ProviderMock, connect, batch, useSelector, useDispatch, } from '../../src/index.js' import { useIsomorphicLayoutEffect } from '../../src/utils/useIsomorphicLayoutEffect' import * as rtl from '@testing-library/react-native' import '@testing-library/jest-native/extend-expect' describe('React Native', () => { const propMapper = (prop) => { switch (typeof prop) { case 'object': case 'boolean': return JSON.stringify(prop) case 'function': return '[function ' + prop.name + ']' default: return prop } } class Passthrough extends Component { render() { return ( {Object.keys(this.props).map((prop) => ( {propMapper(this.props[prop])} ))} ) } } function stringBuilder(prev = '', action) { return action.type === 'APPEND' ? prev + action.body : prev } afterEach(() => rtl.cleanup()) describe('batch', () => { it('batch should be RN unstable_batchedUpdates', () => { expect(batch).toBe(unstable_batchedUpdates) }) }) describe('useIsomorphicLayoutEffect', () => { it('useIsomorphicLayoutEffect should be useLayoutEffect', () => { expect(useIsomorphicLayoutEffect).toBe(useLayoutEffect) }) }) describe('Subscription and update timing correctness', () => { it('should pass state consistently to mapState', () => { const store = createStore(stringBuilder) rtl.act(() => { store.dispatch({ type: 'APPEND', body: 'a' }) }) let childMapStateInvokes = 0 @connect((state) => ({ state })) class Container extends Component { emitChange() { store.dispatch({ type: 'APPEND', body: 'b' }) } render() { return ( {" "}
    {playlist.name}
    ); }; return (
    {playlists.length > 0 ? playlists.map(renderPlaylists) : "Your collection is empty"}
    ); } export default PlaylistManager; 0 export const vi={ commons:{ 'en':'English', 'de': 'Deutsch', 'vi': 'Tiếng Việt', 'jp': '日本語', 'cn': '中文', 'address': 'Địa chỉ', 'restaurant_name': '', 'opening_hours': 'Giờ mở cửa', 'delivery_hours': 'Giờ giao hàng', 'delivery_radius': 'trong bán kính 5km', 'delivery_min_order_value': 'Đơn hàng tối thiểu: 12,-€', 'delivery_shipping_cost': 'Phí vận chuyển: 1,50 €', 'opening_hours_monday': 'Thứ 2', 'opening_hours_days_1': 'Thứ 2 - CN', 'delivery_hours_days_1': 'Thứ 4 - CN', 'opening_hours_tuesday_friday': 'Thứ 3 - Thứ 6', 'opening_hours_saturday': 'Thứ 7', 'opening_hours_sunday_holiday': 'Chủ nhật, ngày lễ', 'closed': 'Đóng cửa', 'nav_about':'Giới thiệu', 'nav_gallery':'Hình ảnh', 'nav_gallery_description':'Tinh tế ẩm thực Việt Nam trong nhà hàng Hội An', 'nav_imprint':'Imprint', 'nav_contact':'Liên lạc', 'nav_team_description':'Đầu Bếp Huỳnh Quốc Bình', 'nav_restaurant_menu':'Thực đơn', 'nav_restaurant_menu_description': 'Khám phá thực đơn nhà hàng chúng tôi và khám phá ẩm thực truyền thống Việt Nam', 'nav_meet_our_chefs': 'Đầu Bếp Chính', 'header_our_restaurant': 'Nhà hàng ', 'header_awarded_chefs': 'đầu bếp chuyên nghiệp', 'long_intro_restaurant':'' + 'Chào mừng quý khách đến nhà hàng
    ' + 'Đến với nhà hàng chúng tôi, quý khách sẽ được phục vụ các đặc sản đặc sản truyền thống Việt Nam do chính các đầu bếp chuyên nghiệp từ trong nước thực hiện.
    ' + 'Chúng tôi tin chắc rằng thành công của nhà hàng luôn được đảm bảo bằng việc LUÔN duy trì ổn định chất lượng món ăn kết hợp với phong cách phục vụ thân thiện và chuyên nghiệp.
    ' + 'Các nguyên liệu đều được chế biến tươi sống trong ngày, và món ăn rất ít chất béo và giàu dinh dưỡng.
    ' + 'Chúng tôi hy vọng sẽ với phương châm làm việc như vậy sẽ làm hài lòng mọi đối tượng khách hàng.
    ' + '
    ' + 'Hãy đến với Hội An Restaurant và thưởng thức sự khác biệt của ẩm thực Việt!', 'tooltip_spicy_1': 'Cay', }, restaurant_menu: { 'menu_section_lunch': 'Ăn Trưa', 'menu_section_starters': 'Khai vị', 'menu_section_summertime_rolls': 'Gỏi cuốn ', 'menu_section_salads': 'Gỏi', 'menu_section_soups': 'Các món súp', 'menu_section_pho': 'Phở', 'menu_section_chicken': 'Thit ga', 'menu_section_duck': 'Thit vit', 'menu_section_beef': 'Thit bo', 'menu_section_seafood': 'Hai san', 'menu_section_veggie': 'Mon chay', 'menu_section_desserts': 'Trang mieng', 'menu_section_wine': 'Ruou', 'menu_section_softdrinks': 'Nuoc uong co ga', 'menu_section_warmdrinks': 'Nuoc uong nong', } }; mpal9000/amaze /** * Module dependencies */ import hg from 'mercury'; import { TARGET_EVENTS } from './setup'; /** * */ export default hg.BaseEvent(handleDrag); // TODO: Allow to be able to specify the events that we want // to listent to, via `this.data`. // If not specified listen to all `TARGET_EVENTS` function handleDrag(ev, broadcast) { // Ignore other events if (!isDragEvent(ev)) return; const data = this.data; const delegator = hg.Delegator(); const _target = ev.currentTarget/* || ev.target*/; let listenersAdded = false; // TODO: Check if can remove this if (ev.type === 'dragenter') { const triggerDragenter = !listenersAdded; addListeners(); if (triggerDragenter) dragenter(ev); } function dragenter(e) { if (!isRootElementOfEvent(e)) return; broadcast(addData({ type: 'dragenter', target: e.target, })); } function dragover(e) { if (!isRootElementOfEvent(e)) return; const raw = e._rawEvent; // Allows us to drop if (e.preventDefault) e.preventDefault(); else if (raw.preventDefault) raw.preventDefault(); raw.dataTransfer.dropEffect = 'move'; // broadcast(addData({ // type: 'dragover', // target: e.target, // dataTransfer: raw.dataTransfer, // })); // //REF// return false; } function dragleave(e) { if (!isRootElementOfEvent(e)) return; removeListeners(); broadcast(addData({ type: 'dragleave', target: e.target, })); } function drop(e) { if (!isRootElementOfEvent(e)) return; const raw = e._rawEvent; // Stops the browser from redirecting if (e.stopPropagation) e.stopPropagation(); else if (raw.stopPropagation) raw.stopPropagation(); removeListeners(); broadcast(addData({ type: 'drop', target: e.target, dataTransfer: raw.dataTransfer, })); } function addData(additional) { return Object.assign({}, data, additional); } function isRootElementOfEvent(e) { return e.target === _target; } function addListeners() { if (listenersAdded) return; delegator.addGlobalEventListener('dragenter', dragenter); delegator.addGlobalEventListener('dragover', dragover); delegator.addGlobalEventListener('dragleave', dragleave); delegator.addGlobalEventListener('drop', drop); listenersAdded = true; } function removeListeners() { if (!listenersAdded) return; delegator.removeGlobalEventListener('dragenter', dragenter); delegator.removeGlobalEventListener('dragover', dragover); delegator.removeGlobalEventListener('dragleave', dragleave); delegator.removeGlobalEventListener('drop', drop); listenersAdded = false; } } /** * */ function isDragEvent(ev) { return ~TARGET_EVENTS.indexOf(ev.type); } client/action-creators/eventsConnections.js1-10 import * as types from "../actions/actionTypes"; // sample response from get to '/' //{ //  data: [ (array of Instances) //   { //    instanceId: number, //    keyspaces: [ (array of Keyspaces) //      { //      eventTotal: 6347 (number), //       pageSize: 50 (number), //     pageNum: 4 (number), //     data: [ (Array of Key Details) //    { //    key: string, //    event: string, //    timestamp: Date //     } //     ] //     }, //      {eventTotal, pageSize, pageNum, data: [etc]} //    ] //   }, //   { //   instanceId: number, //   keyspaces: [..etc] //   } //  ] // } export const loadAllEventsActionCreator = () => (dispatch) => { fetch("/api/v2/events") .then((res) => res.json()) .then((response) => { console.log("response in loadAllEventsActionCreator", response); let allEvents = response.data; dispatch({ type: types.LOAD_ALL_EVENTS, payload: { events: allEvents, }, }); }); }; // response for refresh: Object containing an event log subset, based on the page parameters and any filters. Event details are stored in the data property as an array of event objects, where each event object has the properties: // * key: name of the key // * event: type of the event // * timestamp: time when the event occurred export const refreshKeyspaceActionCreator = (instanceId, dbIndex, pageSize, pageNum, refreshData) => (dispatch) => { fetch( `api/v2/events/${instanceId}/${dbIndex}/?pageSize=${pageSize}&pageNum=${pageNum}&refreshScan=${refreshData}` ) .then((res) => res.json()) .then((response) => { // response should be console.log("response in refreshEventsActionCreator", response); let refreshEvents = response; dispatch({ type: types.REFRESH_EVENTS, payload: { events: refreshEvents, currInstance: instanceId, currDatabase: dbIndex, }, }); }); }; //change the page and handle the filters for keyspace //requirements: instanceId, dbIndex, page Size, page num, keyname filter, keytype filter, refreshScan = 0 - need to know whether there is a //OPTIONS PARAMETER BEING USED HERE CALLED QUERYOPTIONS //response: // { // keyTotal: 6347, // pageSize: 50, // pageNum: 4, // data: [ // { // key: '', // value: '', // type: any, // } // ] // } export const changeEventsPageActionCreator = (instanceId, dbIndex, queryParams) => (dispatch) => { let URI = `api/v2/events/${instanceId}/${dbIndex}/?`; //this may have an issue in here - be aware of queryParams if (queryParams.pageSize) URI += `pageSize=${queryParams.pageSize}`; if (queryParams.pageNum) URI += `&pageNum=${queryParams.pageNum}`; if (queryParams.keyNameFilters) URI += `&keyNameFilter=${queryParams.keyNameFilters}`; if (queryParams.keyTypeFilter) URI += `&keyTypeFilter=${queryParams.keyTypeFilter}`; if (queryParams.refreshData) URI += `&refreshData=${queryParams.refreshData}`; fetch(URI) .then((res) => res.json()) .then((response) => { console.log("response in changeEventsPageActionCreator", response); let nextPageEvents = response; dispatch({ type: types.CHANGE_EVENTS_PAGE, payload: { events: nextPageEvents, currInstance: instanceId, currDatabase: dbIndex, }, }); }); }; export const getTotalEventsActionCreator = (instanceId, dbIndex, queryParams) => (dispatch) => { console.log("in getTotalEventsActionCreator"); let URI = `api/v2/events/${instanceId}/${dbIndex}/`; if (queryParams){ if (queryParams.eventTotal) { if (queryParams.eventTypes) URI += `?eventTotal=${queryParams.eventTotal}/&${queryParams.eventTypes}`; if (queryParams.keynameFilter) URI += `?eventTotal=${queryParams.eventTotal}/&keynameFilter=${queryParams.keynameFilter}`; else { URI += `?eventTotal=${queryParms.eventTotal}`; } } if (queryParams.timeInterval) { if (queryParams.eventTypes) URI += `?timeInterval=${queryParams.timeInterval}/&${queryParams.eventTypes}`; if (queryParams.keynameFilter) URI += `?timeInterval=${queryParams.timeInterval}/&keynameFilter=${queryParams.keynameFilter}`; else { URI += `?timeInterval=${queryParms.timeInterval}`; } } } console.log("URI in eventTotalsActionCreator", URI); fetch(URI) .then((res) => res.json()) .then((response) => { console.log("response in getTotalEventsActionCreator", response); let allEvents = response.data; dispatch({ type: types.LOAD_ALL_EVENTS, payload: { totalEvents: allEvents, currInstance: instanceId, currDatabase: dbIndex, }, }); }); }; import React, { Component } from 'react'; import { getRPanelView } from '../ViewsResolver'; export default class RPanel extends Component { constructor(props) { super(props); this.view =
    ; this.state = { viewChange: false, } } componentDidMount() { this.handleDisplay(this.props) } UNSAFE_componentWillReceiveProps(props) { this.handleDisplay(props) } handleDisplay = (props) => { if(props.navItem === "project" && props.navSubItem === "current_project") { document.getElementById('rPanel').style.left = "100vw" } else { //get view this.view = getRPanelView( props ); this.setState((prevState) => { return { viewChange: !prevState.viewChange, //just to cause re-render } }, () => { document.getElementById('rPanel').style.left = "0"; document.getElementById('rPanel').children[0].focus(); }) } } render() { return (
    {this.view}
    ) } } backend/src/routes.js const routes = require('express').Router(); const path = require('path'); const multer = require('multer'); const fs = require('fs/promises'); const { readFile, writeFile } = require('fs'); const { promisify } = require('util'); const readFileAsync = promisify(readFile); const writeFileAsync = promisify(writeFile); const data = require('../data.json'); const multerConfig = require('./config/multer'); const localData = path.resolve(__dirname, '..', 'data.json'); // rotas get routes.get('/api/products', (req, res) => { res.json(data); }); // rotas post routes.post( '/products', multer(multerConfig).array('file'), async (req, res) => { const arquivo = await readFileAsync(localData, 'utf8'); const { product, price } = req.body; const files = req.files; const images = files.map(item => item.filename); const newProduct = [ ...JSON.parse(arquivo), { id: new Date(Date.now()), product, price, images, }, ]; await writeFileAsync(localData, JSON.stringify(newProduct)); res.send(); }, ); // rotas delete routes.delete('/products/:id', async (req, res) => { // 2021-05-19T01:32:51.173Z const id = req.params.id; const arquivo = await readFileAsync(localData, 'utf8'); // deletar o objeto const parsedFile = JSON.parse(arquivo.toString()); const indice = parsedFile.findIndex(item => item.id === id); if (indice === -1) { return res.send('O usuario não existe'); } const images = parsedFile[indice].images; console.log(images); parsedFile.splice(indice, 1); const newProduct = [...parsedFile]; await writeFileAsync(localData, JSON.stringify(newProduct)); // deletar cada imagem do array images.map(async image => { const imageFile = path.resolve(__dirname, '..', 'uploads', image); try { await fs.unlink(imageFile); // console.log('Arquivo deletado com sucesso'); } catch (error) { console.error('Ocorreu um erro: ', error.message); } }); res.send(); }); module.exports = routes; app.js0 const port = process.env.PORT || 8333; const path = require('path'); const favicon = require('serve-favicon'); const express = require('express'); const server = express(); server.use(express.static(path.join(__dirname, 'public'))); server.use(favicon(__dirname + '/favicon.ico')); require('./routes/index')(server); server.listen(port, () => { console.log('服务已启动,端口号:' + port); });davidruvolo51/shinytools //////////////////////////////////////////////////////////////////////////////// // FILE: get_attribs.js // AUTHOR: // CREATED: 2020-11-07 // MODIFIED: 2020-11-07 // PURPOSE: gather and expose html attribs for use in the shiny server // DEPENDENCIES: // STATUS: // COMMENTS: //////////////////////////////////////////////////////////////////////////////// const get_attribs = new Shiny.InputBinding(); $.extend(get_attribs, { find: function (scope) { return $(scope).find("span[data-browsertools-indexible='true']").parent(); }, initialize: function (el) { this.getValue(el); }, getValue: function (el) { let attributes = $(el.attributes); let out = {}, attr; attributes.map(a => { attr = attributes[a]; out[`${attr.name}`] = attr.value }) return out; }, subscribe: function (el, callback) { const mutationCallback = function (mutationsList) { for (const mutation of mutationsList) { if (mutation.type === "attributes") { callback() } } } const observer = new MutationObserver(mutationCallback); observer.observe($(el)[0], { attributes: true }); }, unsubscribe: function (el) { $(el).off(".get_attribs"); this.subscribe.observer.disconnect(); } }); export default get_attribs;import React from 'react' const App = () => ( <>

    It's amazing React boilerplate

    You can start putting your files inside src folder

    ) export default App /** * Кнопка вставки ol. * * @author <.> */ Ext.define( 'FBEditor.view.panel.main.editor.button.ol.Ol', { extend: 'FBEditor.view.panel.main.editor.button.AbstractLiHolderButton', requires: [ 'FBEditor.view.panel.main.editor.button.ol.OlController' ], xtype: 'main-editor-button-ol', controller: 'main.editor.button.ol', html: '', tooltipText: 'Нумерованный список', elementName: 'ol' } );deepmacDetailCallback("0050c2a99000/36",[{"a":"4445 Garand Montreal QC CA H4R 2H9","o":"Haivision Systems Inc","d":"2009-04-12","t":"add","s":"ieee","c":"CA"}]); /* * Header Messages * * This contains all the text for the Header component. */ import { defineMessages } from 'react-intl' export const scope = 'app.components.Header' export default defineMessages({ home: { id: `${scope}.home`, defaultMessage: 'Home', }, newBooking: { id: `${scope}.newBooking`, defaultMessage: 'New Booking', }, calendar: { id: `${scope}.calendar`, defaultMessage: 'Calendar', }, search: { id: `${scope}.search`, defaultMessage: 'Search', }, }) daithiw44/now import { createSelector } from 'reselect'; import { formatDate, dateSort } from '../../utils' export const getFormattedMessages = emails => emails.map((msg) => { if(msg.timestamp !== undefined) { msg.dtFormat = formatDate(msg.timestamp) } return msg; }).sort(dateSort); // Create Selector Return Function export const createSelectorFunction = (emailsMsg, members) => { const items = emailsMsg.map(item => { let {email, avatar, firstName, lastName} = members.find(m => m.id === item.userId) || {}; // Handle null avatar with default image if(avatar === null) avatar = 'https://media.gettyimages.com/photos/republican-presidential-candidate-donald-trump-speaks-during-a-rally-picture-id488226322?s=612x612'; return { ...item, email, avatar, firstName, lastName } }) return items; }; export const emailsSelector = (state) => getFormattedMessages(state.messages.messages); export const usersSelector = (state) => state.messages.users; export const usersEmailSelector = () => createSelector(emailsSelector , usersSelector, createSelectorFunction ); import React, { Component } from "react"; import { Editor } from "proto-editor"; import "./App.css"; export default class App extends Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); } handleSubmit(cards) { console.log(cards); } render() { let cards = [ { type: "card", attrs: { url: "https://cdn.protograph.pykih.com/99e448b6fcb668c5a3d4/index.html?view_cast_id=7a312bd07ab133968703ec4e&base_url=https://www.responsiblebiz.org", size: 75, height: 419, align: "center", caption: "", "data-card-id": 62499, "data-template-id": 47, }, }, { type: "paragraph", attrs: { class: null, "data-card-id": 62494 }, content: [ { type: "text", text: "As the entire nation, especially Northern states rose to ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.hindustantimes.com/india-news/north-india-exposed-to-severe-air-pollution-levels-morning-after-diwali/story-5WgmdmAN6jTOlYoBNmxNhP.html", title: null, target: "_top", }, }, ], text: "alarmingly spiked levels of air pollution", }, { type: "text", text: " a day after Diwali, the spotlight has again moved to India’s pollution problem. According to the recent ", }, { type: "text", marks: [ { type: "link", attrs: { href: "http://www.who.int/ceh/publications/air-pollution-child-health/en/", title: null, target: "_top", }, }, ], text: "WHO report", }, { type: "text", text: ", a whopping nine in 10 people on Earth breathe highly polluted air. But even among countries gasping for breath, ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.vox.com/2018/5/8/17316978/india-pollution-levels-air-delhi-health", title: null, target: "_top", }, }, ], text: "India stands out for air", }, { type: "text", text: " that is consistently, especially terrible.", }, ], }, { type: "heading", attrs: { level: 2, id: null, "data-card-id": 62495 }, content: [{ type: "text", text: "What Is Causing Pollution In India" }], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "A 2011" }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.hindustantimes.com/delhi-news/blame-industry-not-cars-for-pollution/story-wzXK7KskS8vEBqsSpL04ZO.html", title: null, target: "_top", }, }, ], text: " Source Appropriation Study", }, { type: "text", text: " in seven mega cities by the then Ministry of Environment clearly stated that though Indian cities see a large fleet of vehicles on road every day; contrary to the popular belief industrial emission and road dust ( caused by industries ) are prominent causes of pollution.", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "Industrial pollution continues to be the main cause and ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.conserve-energy-future.com/causes-effects-of-industrial-pollution.php", title: null, target: "_top", }, }, ], text: "goes unharnessed", }, { type: "text", text: " in dearth of lack of policies, usage of outdated technologies and unplanned waste disposal practices.", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "A government body Environment Pollution (Prevention & Control) Authority (EPCA) for the NCR last year also ", }, { type: "text", marks: [ { type: "link", attrs: { href: "http://www.epca.org.in/CS-haryana.pdf", title: null, target: "_top", }, }, ], text: "mentioned ", }, { type: "text", text: "various industrial factors—like dust emanated by brick kilns, hot mix plants, stone crushers, etc —that were responsible for the ‘severe’ air quality of the region. However, there is no evidence of any compliance by the authorities, industries or the environment body itself.", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "The" }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.downtoearth.org.in/blog/environment/environmental-governance-in-india-pushes-industries-to-face-stricter-pollution-norms-53999", title: null, target: "_top", }, }, ], text: " environmental regulation", }, { type: "text", text: " has shown many improvements, pollution limits of many industries have been tightened but a lot remains to be done in this regard.", }, ], }, { type: "heading", attrs: { level: 2, id: null, "data-card-id": 62496 }, content: [{ type: "text", text: "What Are We Reading:" }], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [ { type: "text", text: "How India can use better data and regulations to stop industries from choking its cities", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "Fourteen of the world’s 20 cities with highest air pollution are in ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://indianexpress.com/article/india/14-of-indias-cities-are-among-the-top-20-most-polluted-ones-globally-heres-the-list-5159794/", title: null, target: "_top", }, }, ], text: "India.", }, { type: "text", text: " Why is this the case, when India has set pollution limits and stipulated strict criminal punishments to enforce them? A ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://indianexpress.com/article/opinion/how-india-can-use-better-data-and-regulations-to-stop-industries-from-choking-its-cities/", title: null, target: "_top", }, }, ], text: "report", }, { type: "text", text: " in " }, { type: "text", marks: [{ type: "em" }], text: "The Indian Express", }, { type: "text", text: " digs into loopholes in regulations and its implementation.", }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [ { type: "text", text: "India needs transparent industrial pollution data, regulation reforms", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "How much information about pollution from industries is available to the public? How industries perform on pollution, remains a black box. This kind of monitoring has to be done manually and is a resource intensive and time consuming process. This ", }, { type: "text", marks: [{ type: "em" }], text: "Hindustan Times", }, { type: "text", text: " " }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.hindustantimes.com/india-news/india-needs-transparent-industrial-pollution-data-regulation-reforms/story-W71D1PYWBSqfcaYZ56YcLL.html", title: null, target: "_top", }, }, ], text: "piece", }, { type: "text", text: " talks of a lack of confidence in the data, and incomplete information, prevents it from being put to its best use: ensuring industries comply with standards and lowering pollution levels.", }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [{ type: "text", text: "Building from debris" }], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "Delhi’s air pollution is in no small measure due to the high presence of particulate matter (PM 2.5 and PM 10), resulting from the construction debris strewn around the city. Construction and demolition waste is an environment and public health hazard.", }, { type: "text", marks: [{ type: "em" }], text: " The Indian Express", }, { type: "text", text: " " }, { type: "text", marks: [ { type: "link", attrs: { href: "https://indianexpress.com/article/opinion/columns/building-from-debris/", title: null, target: "_top", }, }, ], text: "article", }, { type: "text", text: " argues that recycling and reuses offers a sustainable solution and companies should take a cue and work towards a sustainable future. ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://indianexpress.com/article/opinion/columns/india-urbanisation-urbanisation-waste-management-environment-pollution-5415096/", title: null, target: "_top", }, }, ], text: "A proactive effort", }, { type: "text", text: " from municipalities and citizens towards recycling of construction and demolition waste will go a long way in curbing pollution.", }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [ { type: "text", text: "Decentralisation of Environmental Regulations in India", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "The decentralisation of Environment Impact Assessment processes has improved the enforcement of environmental regulations and been successful in reducing polluting activities in India. Evidence suggests that decentralisation was associated with relatively fewer firm births in states with stricter environmental law enforcement. This ", }, { type: "text", marks: [{ type: "em" }], text: "Economic and Political Weekly", }, { type: "text", text: " " }, { type: "text", marks: [ { type: "link", attrs: { href: "https://www.epw.in/journal/2018/43/perspectives/decentralisation-environmental.html", title: null, target: "_top", }, }, ], text: "article", }, { type: "text", text: " takes a close look." }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [ { type: "text", text: "Can India’s solar revolution help meet its Paris Agreement emission goals?", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "Being a coal-obsessed nation with tremendous aspirations for cars and fast bikes, India’s greenhouse gas emissions recorded an annual growth of 5.6 percent between 2005 and 2013. With frenzied expansion of solar parks and a hold on new coal-fired power plants, there is hope that India may be able to fulfill its commitment to reduce emissions as per the 2015 Paris Agreement, ", }, { type: "text", marks: [ { type: "link", attrs: { href: "https://india.mongabay.com/2018/10/22/can-indias-solar-revolution-help-meet-its-paris-agreement-emission-goals/", title: null, target: "_top", }, }, ], text: "reports", }, { type: "text", text: " " }, { type: "text", marks: [{ type: "em" }], text: "Mongabay India.", }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [ { type: "text", text: "EPCA was specially empowered to deal with air pollution crises. Is it working?", }, ], }, { type: "paragraph", attrs: { class: null, "data-card-id": null }, content: [ { type: "text", text: "Despite being vested with enormous powers, the EPCA has been reluctant to proactively rein in the 'airpocalypse' in the National Capital Region. Based on RTI replies by the body, ", }, { type: "text", marks: [{ type: "em" }], text: "The Wire", }, { type: "text", text: " " }, { type: "text", marks: [ { type: "link", attrs: { href: "https://thewire.in/government/epca-was-specially-empowered-to-deal-with-air-pollution-crises-is-it-working", title: null, target: "_top", }, }, ], text: "report", }, { type: "text", text: " probes the its performance, reluctant to issue any directions vis-à-vis environmental quality, restriction of activities, control over emissions and other subjects the authority has mandate over.", }, ], }, { type: "heading", attrs: { level: 3, id: null, "data-card-id": null }, content: [{ type: "hard_break" }], }, ]; return (
              {/* {this.state && {JSON.stringify(this.state.doc.view.state.doc, null, 2)}} */}
            
    ); } } import { connect } from 'react-redux'; import SettingsCreatorPage from './view'; import { doOpenModal } from 'redux/actions/app'; import { doCommentBlockWords, doCommentUnblockWords, doCommentModAddDelegate, doCommentModRemoveDelegate, doCommentModListDelegates, doFetchCreatorSettings, doUpdateCreatorSettings, } from 'redux/actions/comments'; import { selectActiveChannelClaim } from 'redux/selectors/app'; import { selectSettingsByChannelId, selectFetchingCreatorSettings, selectFetchingBlockedWords, selectModerationDelegatesById, } from 'redux/selectors/comments'; const select = (state) => ({ activeChannelClaim: selectActiveChannelClaim(state), settingsByChannelId: selectSettingsByChannelId(state), fetchingCreatorSettings: selectFetchingCreatorSettings(state), fetchingBlockedWords: selectFetchingBlockedWords(state), moderationDelegatesById: selectModerationDelegatesById(state), }); const perform = (dispatch) => ({ commentBlockWords: (channelClaim, words) => dispatch(doCommentBlockWords(channelClaim, words)), commentUnblockWords: (channelClaim, words) => dispatch(doCommentUnblockWords(channelClaim, words)), fetchCreatorSettings: (channelClaimId) => dispatch(doFetchCreatorSettings(channelClaimId)), updateCreatorSettings: (channelClaim, settings) => dispatch(doUpdateCreatorSettings(channelClaim, settings)), commentModAddDelegate: (modChanId, modChanName, creatorChannelClaim) => dispatch(doCommentModAddDelegate(modChanId, modChanName, creatorChannelClaim)), commentModRemoveDelegate: (modChanId, modChanName, creatorChannelClaim) => dispatch(doCommentModRemoveDelegate(modChanId, modChanName, creatorChannelClaim)), commentModListDelegates: (creatorChannelClaim) => dispatch(doCommentModListDelegates(creatorChannelClaim)), doOpenModal: (modal, props) => dispatch(doOpenModal(modal, props)), }); export default connect(select, perform)(SettingsCreatorPage); import React from "react" import { StaticQuery, graphql } from "gatsby" import Layout from "../components/layout" // import Image from "../components/image" import SEO from "../components/seo" import HeaderSection from '../components/headerSection' import Layer from '../components/mota/Layer' import Gallery from '../components/Gallery' import Image from '../components/image' const mainColor = '#FF2164' const Mota = () => (
    Tenemos muchos espacios de oportunidad, por lo que con toda la información generamos un MODELO DE TRABAJO que nos ayudará a organizar las ideas de innovación y sobre todo aprovechar el BLENDED WORLD (entre más combinaciones hagamos mayor oportunidad de innovación)
    ¿EN QUÉ CONSISTE?
    • Permite identificar y ordenar de manera sencilla los espacios de oportunidad (producto, consumidor, sociedad y planeta) para el desarrollo de iniciativas
    • Brinda argumentos para la ideación en función de una estructura de múltiples layers en los que se puede intervenir a partir de diferentes operaciones de valor
    ¿CÓMO SE LEE?
    • Conformado por 4 niveles, que retoman las 2 dimensiones de necesidades y los espacios de oportunidad: de las necesidades más individuales a las más colectivas
    • La innovación, puede construirse independiente o combinado ya que eso irá potenciando la iniciativa
    Storydoing
    Contribuir de manera activa al cuidado y sostenibilidad de los recursos naturales.
    Storytelling
    Proveer de argumentos y herramientas para sostener un discurso social de compromiso por el bienestar de las personas y la sociedad.
    Motivaciones y escenas de consumo
    Facilitar o mejorar la experiencia de convivencia, uso o consumo del producto para el usuario.
    Diferenciación
    Generar, mantener o reforzar las cualidades del producto desde el empaque
    { const {nodes} = data.allMotaJson return ( nodes.map((node,key) => { return } ) ) }} />

    Nota: Estos son primeros ejemplos de combinaciones entre corredores y layers que detonamos con consumidores, especialistas y team HSS.

    Nos ayuda a visualizar lo que podemos desarrollar: provee ideas infinitas y además nos ayuda a sumar elementos como: marcas, categorías, ventas, etc. Para poder aterrizar propuestas de innovación en la segunda parte estratégica del proyecto.

    ) export default Mota import mutations from '~/whats_new/store/mutations'; import createState from '~/whats_new/store/state'; import * as types from '~/whats_new/store/mutation_types'; describe('whats new mutations', () => { let state; beforeEach(() => { state = createState; }); describe('openDrawer', () => { it('sets open to true', () => { mutations[types.OPEN_DRAWER](state); expect(state.open).toBe(true); }); }); describe('closeDrawer', () => { it('sets open to false', () => { mutations[types.CLOSE_DRAWER](state); expect(state.open).toBe(false); }); }); }); import Route from '@ember/routing/route'; export default class DocsClusteringRoute extends Route { controllerName = 'docs'; } const inquirer = require('inquirer'); const mysql = require('mysql2'); const table = require('console.table'); // const db = require('./scripts/connection'); const util = require('util'); const { exit } = require('process'); require('dotenv').config(); const db = mysql.createConnection( { host: process.env.DB_HOST, user: process.env.DB_USER, password: , database: process.env.DB_NAME }, ); db.query = util.promisify(db.query); async function actionPrompt() { inquirer.prompt([ { name: "task", message: "What would you like to do?", type: 'list', choices: [ "View All Departments", "View All Roles", "View All Employees", "Add A Department", "Add A Role", "Add an Employee", "Update An Employee Role", "Exit", ] } ]) .then((choice) => { // each choice corresponds to an action function switch(choice.task) { case "View All Departments": viewAllDepartments(); break; case "View All Roles": viewAllRoles(); break; case "View All Employees": viewAllEmployees(); break; case "Add A Department": addADepartment(); break; case "Add A Role": addARole(); break; case "Add an Employee": addAnEmployee(); break; case "Update An Employee Role": updateAnEmployeeRole(); break; case "Exit": process.exit(); } }) } // functions in order // View functions function viewAllDepartments() { db.query('SELECT department.id AS ID, department.name AS DEPARTMENT FROM department', function (err, results) { console.table('\n', results, '\n'); actionPrompt(); }) } function viewAllRoles() { db.query(`SELECT role.id, role.title, role.salary, department.name FROM role JOIN department ON role.department_id = department.id ORDER BY role.id ASC`, function (err, results) { console.table('\n', results, '\n'); actionPrompt(); }); } function viewAllEmployees() { db.query(`SELECT employee.id AS ID, employee.first_name AS "", employee.last_name AS "", role.title AS "TITLE", role.salary AS "SALARY", department.name AS "DEPARTMENT", CONCAT(manager.first_name, " ", manager.last_name) AS "MANAGER NAME" FROM employee LEFT JOIN employee manager ON manager.id = employee.manager_id INNER JOIN role ON employee.role_id = role.id INNER JOIN department ON role.department_id = department.id`, function (err, results) { console.table('\n', results, '\n'); actionPrompt(); }); } // Add functions function addADepartment() { inquirer.prompt([ { name: "departmentName", message: "What is the new department name?", type: "input" } ]) .then((result) => { let department = result.departmentName; db.query(`INSERT INTO department (name) VALUES (?); `, department , function (err, result) { console.log('\n', `Department ${department} has been added.`, '\n'); actionPrompt(); }); }) } async function addARole() { // queries database to get the choices let departments = await db.query('SELECT * FROM department'); inquirer.prompt([ { name: "roleName", message: "What is the name of the role?", type: "input" }, { name: "salary", message: "What is the salary of the role?", type: "number" }, { name: "departmentName", message: "Which department does the role belong to?", type: "list", choices: departments.map((department) => { return { name: department.department_name, value: department.name } }) } ]) .then((results) => { let { roleName, salary } = results; // corresponds the department string to its ID let foundDepartmentID = departments.find(department => department.name === results.departmentName ).id; db.query(`INSERT INTO role (title, salary, department_id) VALUES (?, ?, ?)`, [roleName, salary, foundDepartmentID], function (err, results) { console.log('\n', `${roleName} has been added.`, '\n'); actionPrompt(); }); }) } async function addAnEmployee() { // queries databases to get the role's choices and manager's choices let roles = await db.query('SELECT * FROM role'); let employees = await db.query(`SELECT employee.id AS id, employee.first_name AS "firstName", employee.last_name AS "lastName", CONCAT(employee.first_name, " ", employee.last_name) AS "employeeName" FROM employee LEFT JOIN employee manager ON manager.id = employee.manager_id INNER JOIN role ON employee.role_id = role.id INNER JOIN department ON role.department_id = department.id`); inquirer.prompt([ { name: "firstName", message: "What is the employee's first name?", type: "input" }, { name: "lastName", message: "What is the employee's last name?", type: "input" }, { name: "roleName", message: "What is the employee's role?", type: "list", choices: roles.map((role) => { return { name: role.title } }) }, { name: "managerName", message: "Who is the employee's manager?", type: "list", choices: employees.map((employee) => { return { name: `${employee.firstName} ${employee.lastName}` } }) } ]) .then((results) => { let { firstName, lastName } = results; // corresponds the roleName string to the database ID let foundRoleID = roles.find(role => role.title === results.roleName).id; // corresponds the manager's name string to the database ID let foundManagerID = employees.find(employee => employee.employeeName === results.managerName).id; db.query(`INSERT INTO employee (first_name, last_name, role_id, manager_id) VALUES (?, ?, ?, ?)`, [firstName, lastName, foundRoleID, foundManagerID], function (err, results) { console.log('\n', `${firstName} ${lastName} has been added.`, '\n'); actionPrompt(); }); }) } //Update functions async function updateAnEmployeeRole() { let roles = await db.query('SELECT * FROM role'); let employees = await db.query(`SELECT employee.id AS id, employee.first_name AS "firstName", employee.last_name AS "lastName", CONCAT(employee.first_name, " ", employee.last_name) AS "employeeName" FROM employee LEFT JOIN employee manager ON manager.id = employee.manager_id INNER JOIN role ON employee.role_id = role.id INNER JOIN department ON role.department_id = department.id`); inquirer.prompt([ { name: "name", message: "Which employee's role do you want to update?", type: "list", choices: employees.map((employee) => { return { name: `${employee.firstName} ${employee.lastName}` } }) }, { name: "roleName", message: "Which role do you want to update?", type: "list", choices: roles.map((role) => { return { name: role.title } }) } ]) .then((results) => { // new Role ID let foundRoleID = roles.find(role => role.title === results.roleName).id; // corresponding the selected employee to its ID let foundEmployeeID = employees.find(employee => employee.employeeName === results.name).id; db.query(`UPDATE employee SET role_id = ? WHERE employee.id = ?`, [foundRoleID, foundEmployeeID], function () { console.log('\n', `${results.name}'s role has been updated.`, '\n'); actionPrompt(); }); }) } //init function const init = async () => { try { console.log('\n', "----------------------------------------", '\n'); console.log('\n', " Welcome to Employee Tracker ", '\n'); console.log('\n', "----------------------------------------", '\n'); actionPrompt(); } catch (err) { console.log(err); } }; init(); 'use strict'; /** * promise-deferred.js * ------------------- * * @flow */ const Promise = require('bluebird'); /*:: type resolveHandler = (value: ?any) => void type rejectHandler = (error: Error) => void type DeferredPromise = Promise & { resolve: (value: ?any) => void, reject: (error: Error) => void, } */ function defer() /*: { promise: Promise, resolve: resolveHandler, reject: rejectHandler }*/ { let resolve, reject; const promise = new Promise((...args) => [ resolve, reject ] = args); return { promise, resolve, reject }; } function DeferredPromise() /*: DeferredPromise*/ { const { promise, resolve, reject } = defer(); Object.defineProperties(promise, { resolve: { value: resolve }, reject: { value: reject }, }); return promise; } module.exports = DeferredPromise; module.exports.defer = defer; trdlab/linkstate_scalable_networkingdijkstra.js0 /* * Dijkstra Module */ module.exports = { shortestPath : function(edges, numVertices, startVertex) { var done = new Array(numVertices); done[startVertex] = true; var pathLengths = new Array(numVertices); var predecessors = new Array(numVertices); for (var i = 0; i < numVertices; i++) { pathLengths[i] = edges[startVertex][i]; if (edges[startVertex][i] != Infinity) { predecessors[i] = startVertex; } } pathLengths[startVertex] = 0; for (var i = 0; i < numVertices - 1; i++) { var closest = -1; var closestDistance = Infinity; for (var j = 0; j < numVertices; j++) { if (!done[j] && pathLengths[j] < closestDistance) { closestDistance = pathLengths[j]; closest = j; } } done[closest] = true; for (var j = 0; j < numVertices; j++) { if (!done[j]) { var possiblyCloserDistance = pathLengths[closest] + edges[closest][j]; if (possiblyCloserDistance < pathLengths[j]) { pathLengths[j] = possiblyCloserDistance; predecessors[j] = closest; } } } } return { "startVertex": startVertex, "pathLengths": pathLengths, "predecessors": predecessors }; }, constructPath: function(shortestPathInfo, endVertex) { var path = []; while (endVertex != shortestPathInfo.startVertex) { path.unshift(endVertex); endVertex = shortestPathInfo.predecessors[endVertex]; } return path; } } src/scenes/Subreddit/scenes/Post/index.js import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import Post from './Post' import * as PostActions from 'Actions/post' const mapStateToProps = (state, ownProps) => { const post = state.posts.byId[ownProps.id] || {} return { ...post, id: ownProps.id } } const mapDispatchToProps = dispatch => ({ actions: bindActionCreators(PostActions, dispatch) }) export default connect(mapStateToProps, mapDispatchToProps, null, { pure: false })(Post) import _ from "lodash"; import { matcherHint, EXPECTED_COLOR, RECEIVED_COLOR, } from "jest-matcher-utils"; import { prettyFormat, INDENT_ALL } from "../utils"; function withoutMethods(obj) { return _.cloneDeepWith(obj, function customizer(v) { if (v && v.$$typeof === Symbol.for("jest.asymmetricMatcher")) { return v; } if (_.isObject(v)) { return _.cloneDeepWith(_.omitBy(v, _.isFunction), _.after(2, customizer)); } return undefined; }); } function predicate(received, expected) { return _.isEqualWith(received, expected, function customizer(first, second) { if (_.isFunction(first) && (_.isFunction(second) || _.isNil(second))) { return true; } if (_.isFunction(second) && (_.isFunction(first) || _.isNil(first))) { return true; } if (first && first.$$typeof === Symbol.for("jest.asymmetricMatcher")) { return first.asymmetricMatch(second); } if (second && second.$$typeof === Symbol.for("jest.asymmetricMatcher")) { return second.asymmetricMatch(second); } if (_.isPlainObject(first) && _.isPlainObject(second)) { return _.transform( _.union(Object.keys(first), Object.keys(second)), (result, key) => { // This is how _.transform is meant to be used // eslint-disable-next-line no-return-assign, no-param-reassign return (result.current = predicate(first[key], second[key])); }, { current: true }, ).current; } return undefined; }); } function message(received, expected, inverse) { return () => `${matcherHint( `${inverse ? ".not" : ""}.toEqualWithoutMethods`, "received", "expected", )}\n\nExpected object without methods to${ inverse ? " NOT " : " " }be the same as:\n${INDENT_ALL( EXPECTED_COLOR(prettyFormat(withoutMethods(expected))), )}\nbut ${inverse ? "it was the same:" : "instead received:"}\n${INDENT_ALL( RECEIVED_COLOR(prettyFormat(withoutMethods(received))), )}\nand original object was:\n${INDENT_ALL( RECEIVED_COLOR(prettyFormat(received)), )}`; } class Methodlessly { constructor(sample, inverse = false) { this.$$typeof = Symbol.for("jest.asymmetricMatcher"); this.sample = sample; this.inverse = inverse; } asymmetricMatch(other) { return this.inverse ? !predicate(this.sample, other) : predicate(this.sample, other); } toString() { return `WithoutMethods${this.inverse ? "Not" : ""}SameAs`; } toAsymmetricMatcher() { return `WithoutMethods${this.inverse ? "Not" : ""}SameAs<${prettyFormat( this.sample, )}>`; } // eslint-disable-next-line class-methods-use-this getExpectedType() { return "object"; } } export default { symmetric: { toEqualWithoutMethods(received, expected) { const pass = predicate(received, expected); return { pass, message: message(received, expected, pass), }; }, }, asymmetric: { methodlessly: Methodlessly, }, }; src/components/Icon/index.js import React from 'react' const Icon = props => { const properties = {} }src/translator/index.js const i18n = require('i18next'); const Path = require('path'); const Paths = require('../paths'); const Utils = require('../utils'); const Translation = require('./translation'); const superTranslate = i18n.t.bind(i18n); (function () { i18n.init({ lng: 'en', initImmediate: true, resources: { en: { translation: getTranslationResource('en') }, he: { translation: getTranslationResource('he') }, }, }); }()); // Gets a locale and returns the full resource object function getTranslationResource(locale) { paths = Paths; if (process.env.TORTILLA_CWD) { paths = Paths.resolveProject(process.env.TORTILLA_CWD); } paths = [ // Static locales Path.resolve(paths.tortilla.translator.locales, `${locale}.json`), // User defined locales Path.resolve(paths.locales, `${locale}.json`), ]; // Unite all resources and return a single one return paths.reduce((resource, path) => { // Clear cache so files can be properly reloaded try { delete require.cache[require.resolve(path)]; const extension = require(path); Utils.merge(resource, extension); } catch (err) { } return resource; }, {}); } // Returns i18n translation wrapped with some extra functionality function translate() { const result = superTranslate(...arguments); return result && new Translation(result); } // Any translation would be done using the provided locale function scopeLanguage(language, fn) { if (!language) { return fn(); } const oldLanguage = i18n.translator.language; try { i18n.translator.changeLanguage(language); fn(); } finally { i18n.translator.changeLanguage(oldLanguage); } } // Shallow cloning i18n so it won't be changed module.exports = Utils.extend(i18n, { translate, scopeLanguage, }); "use strict"; class Battle { constructor(attacker, defender) { if (customization) return; closeDialogs(".stable"); customization = 13; // enter customization to avoid unwanted dialog closing Battle.prototype.context = this; // store context this.iteration = 0; this.x = defender.x; this.y = defender.y; this.cell = findCell(this.x, this.y); this.attackers = {regiments:[], distances:[], morale:100, casualties:0, power:0}; this.defenders = {regiments:[], distances:[], morale:100, casualties:0, power:0}; this.addHeaders(); this.addRegiment("attackers", attacker); this.addRegiment("defenders", defender); this.place = this.definePlace(); this.defineType(); this.name = this.defineName(); this.randomize(); this.calculateStrength("attackers"); this.calculateStrength("defenders"); this.getInitialMorale(); $("#battleScreen").dialog({ title: this.name, resizable: false, width: fitContent(), position: {my: "center", at: "center", of: "#map"}, close: () => Battle.prototype.context.cancelResults() }); if (modules.Battle) return; modules.Battle = true; // add listeners document.getElementById("battleType").addEventListener("click", ev => this.toggleChange(ev)); document.getElementById("battleType").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changeType(ev)); document.getElementById("battleNameShow").addEventListener("click", () => Battle.prototype.context.showNameSection()); document.getElementById("battleNamePlace").addEventListener("change", ev => Battle.prototype.context.place = ev.target.value); document.getElementById("battleNameFull").addEventListener("change", ev => Battle.prototype.context.changeName(ev)); document.getElementById("battleNameCulture").addEventListener("click", () => Battle.prototype.context.generateName("culture")); document.getElementById("battleNameRandom").addEventListener("click", () => Battle.prototype.context.generateName("random")); document.getElementById("battleNameHide").addEventListener("click", this.hideNameSection); document.getElementById("battleAddRegiment").addEventListener("click", this.addSide); document.getElementById("battleRoll").addEventListener("click", () => Battle.prototype.context.randomize()); document.getElementById("battleRun").addEventListener("click", () => Battle.prototype.context.run()); document.getElementById("battleApply").addEventListener("click", () => Battle.prototype.context.applyResults()); document.getElementById("battleCancel").addEventListener("click", () => Battle.prototype.context.cancelResults()); document.getElementById("battleWiki").addEventListener("click", () => wiki("Battle-Simulator")); document.getElementById("battlePhase_attackers").addEventListener("click", ev => this.toggleChange(ev)); document.getElementById("battlePhase_attackers").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "attackers")); document.getElementById("battlePhase_defenders").addEventListener("click", ev => this.toggleChange(ev)); document.getElementById("battlePhase_defenders").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "defenders")); document.getElementById("battleDie_attackers").addEventListener("click", () => Battle.prototype.context.rollDie("attackers")); document.getElementById("battleDie_defenders").addEventListener("click", () => Battle.prototype.context.rollDie("defenders")); } defineType() { const attacker = this.attackers.regiments[0]; const defender = this.defenders.regiments[0]; const getType = () => { const typesA = Object.keys(attacker.u).map(name => options.military.find(u => u.name === name).type); const typesD = Object.keys(defender.u).map(name => options.military.find(u => u.name === name).type); if (attacker.n && defender.n) return "naval"; // attacker and defender are navals if (typesA.every(t => t === "aviation") && typesD.every(t => t === "aviation")) return "air"; // if attackers and defender have only aviation units if (attacker.n && !defender.n && typesA.some(t => t !== "naval")) return "landing"; // if attacked is naval with non-naval units and defender is not naval if (!defender.n && pack.burgs[pack.cells.burg[this.cell]].walls) return "siege"; // defender is in walled town if (P(.1) && [5,6,7,8,9,12].includes(pack.cells.biome[this.cell])) return "ambush"; // 20% if defenders are in forest or marshes return "field"; } this.type = getType(); this.setType(); } setType() { document.getElementById("battleType").className = "icon-button-" + this.type; const sideSpecific = document.getElementById("battlePhases_"+this.type+"_attackers"); const attackers = sideSpecific ? sideSpecific.content : document.getElementById("battlePhases_"+this.type).content; const defenders = sideSpecific ? document.getElementById("battlePhases_"+this.type+"_defenders").content : attackers; document.getElementById("battlePhase_attackers").nextElementSibling.innerHTML = ""; document.getElementById("battlePhase_defenders").nextElementSibling.innerHTML = ""; document.getElementById("battlePhase_attackers").nextElementSibling.append(attackers.cloneNode(true)); document.getElementById("battlePhase_defenders").nextElementSibling.append(defenders.cloneNode(true)); } definePlace() { const cells = pack.cells, i = this.cell; const burg = cells.burg[i] ? pack.burgs[cells.burg[i]].name : null; const getRiver = i => {const river = pack.rivers.find(r => r.i === i); return river.name + " " + river.type}; const river = !burg && cells.r[i] ? getRiver(cells.r[i]) : null; const proper = burg || river ? null : Names.getCulture(cells.culture[this.cell]); return burg ? burg : river ? river : proper; } defineName() { if (this.type === "field") return "Battle of " + this.place; if (this.type === "naval") return "Naval Battle of " + this.place; if (this.type === "siege") return "Siege of "+ this.place; if (this.type === "ambush") return this.place + " Ambush"; if (this.type === "landing") return this.place + " Landing"; if (this.type === "air") return `${this.place} ${P(.8) ? "Air Battle" : "Dogfight"}`; } getTypeName() { if (this.type === "field") return "field battle"; if (this.type === "naval") return "naval battle"; if (this.type === "siege") return "siege"; if (this.type === "ambush") return "ambush"; if (this.type === "landing") return "landing"; if (this.type === "air") return "battle"; } addHeaders() { let headers = ""; for (const u of options.military) { const label = capitalize(u.name.replace(/_/g, ' ')); headers += `${u.icon}`; } headers += "Total"; battleAttackers.innerHTML = battleDefenders.innerHTML = headers; } addRegiment(side, regiment) { regiment.casualties = Object.keys(regiment.u).reduce((a,b) => (a[b]=0,a), {}); regiment.survivors = Object.assign({}, regiment.u); const state = pack.states[regiment.state]; const distance = Math.hypot(this.y-regiment.by, this.x-regiment.bx) * distanceScaleInput.value | 0; // distance between regiment and its base const color = state.color[0] === "#" ? state.color : "#999"; const icon = ` ${regiment.icon}`; const body = ``; let initial = `${icon}${regiment.name.slice(0, 24)}`; let casualties = `${state.fullName.slice(0, 26)}`; let survivors = `Distance to base: ${distance} ${distanceUnitInput.value}`; for (const u of options.military) { initial += `${regiment.u[u.name]||0}`; casualties += `0`; survivors += `${regiment.u[u.name]||0}`; } initial += `${regiment.a||0}`; casualties += `0`; survivors += `${regiment.a||0}`; const div = side === "attackers" ? battleAttackers : battleDefenders; div.innerHTML += body + initial + casualties + survivors + ""; this[side].regiments.push(regiment); this[side].distances.push(distance); } addSide() { const body = document.getElementById("regimentSelectorBody"); const context = Battle.prototype.context; const regiments = pack.states.filter(s => s.military && !s.removed).map(s => s.military).flat(); const distance = reg => rn(Math.hypot(context.y-reg.y, context.x-reg.x) * distanceScaleInput.value) + " " + distanceUnitInput.value; const isAdded = reg => context.defenders.regiments.some(r => r === reg) || context.attackers.regiments.some(r => r === reg); body.innerHTML = regiments.map(r => { const s = pack.states[r.state], added = isAdded(r), dist = added ? "0 " + distanceUnitInput.value : distance(r); return `
    ${s.name.slice(0, 11)}
    ${r.icon}
    ${r.name.slice(0, 24)}
    ${r.a}
    ${dist}
    `; }).join(""); $("#regimentSelectorScreen").dialog({ resizable: false, width: fitContent(), title: "Add regiment to the battle", position: {my: "left center", at: "right+10 center", of: "#battleScreen"}, close: addSideClosed, buttons: { "Add to attackers": () => addSideClicked("attackers"), "Add to defenders": () => addSideClicked("defenders"), Cancel: () => $("#regimentSelectorScreen").dialog("close") } }); applySorting(regimentSelectorHeader); body.addEventListener("click", selectLine); function selectLine(ev) { if (ev.target.className === "inactive") {tip("Regiment is already in the battle", false, "error"); return}; ev.target.classList.toggle("selected"); } function addSideClicked(side) { const selected = body.querySelectorAll(".selected"); if (!selected.length) {tip("Please select a regiment first", false, "error"); return} $("#regimentSelectorScreen").dialog("close"); selected.forEach(line => { const state = pack.states[line.dataset.s]; const regiment = state.military.find(r => r.i == +line.dataset.i); Battle.prototype.addRegiment.call(context, side, regiment); Battle.prototype.calculateStrength.call(context, side); Battle.prototype.getInitialMorale.call(context); // move regiment const defenders = context.defenders.regiments, attackers = context.attackers.regiments; const shift = side === "attackers" ? attackers.length * -8 : (defenders.length-1) * 8; regiment.px = regiment.x; regiment.py = regiment.y; Military.moveRegiment(regiment, defenders[0].x, defenders[0].y + shift); }); } function addSideClosed() { body.innerHTML = ""; body.removeEventListener("click", selectLine); } } showNameSection() { document.querySelectorAll("#battleBottom > button").forEach(el => el.style.display = "none"); document.getElementById("battleNameSection").style.display = "inline-block"; document.getElementById("battleNamePlace").value = this.place; document.getElementById("battleNameFull").value = this.name; } hideNameSection() { document.querySelectorAll("#battleBottom > button").forEach(el => el.style.display = "inline-block"); document.getElementById("battleNameSection").style.display = "none"; } changeName(ev) { this.name = ev.target.value; $("#battleScreen").dialog({"title":this.name}); } generateName(type) { const place = type === "culture" ? Names.getCulture(pack.cells.culture[this.cell], null, null, "") : Names.getBase(rand(nameBases.length-1)); document.getElementById("battleNamePlace").value = this.place = place; document.getElementById("battleNameFull").value = this.name = this.defineName(); $("#battleScreen").dialog({"title":this.name}); } getJoinedForces(regiments) { return regiments.reduce((a, b) => { for (let k in b.survivors) { if (!b.survivors.hasOwnProperty(k)) continue; a[k] = (a[k] || 0) + b.survivors[k]; } return a; }, {}); } calculateStrength(side) { const scheme = { // field battle phases "skirmish": {"melee":.2, "ranged":2.4, "mounted":.1, "machinery":3, "naval":1, "armored":.2, "aviation":1.8, "magical":1.8}, // ranged excel "melee": {"melee":2, "ranged":1.2, "mounted":1.5, "machinery":.5, "naval":.2, "armored":2, "aviation":.8, "magical":.8}, // melee excel "pursue": {"melee":1, "ranged":1, "mounted":4, "machinery":.05, "naval":1, "armored":1, "aviation":1.5, "magical":.6}, // mounted excel "retreat": {"melee":.1, "ranged":.01, "mounted":.5, "machinery":.01, "naval":.2, "armored":.1, "aviation":.8, "magical":.05}, // reduced // naval battle phases "shelling": {"melee":0, "ranged":.2, "mounted":0, "machinery":2, "naval":2, "armored":0, "aviation":.1, "magical":.5}, // naval and machinery excel "boarding": {"melee":1, "ranged":.5, "mounted":.5, "machinery":0, "naval":.5, "armored":.4, "aviation":0, "magical":.2}, // melee excel "chase": {"melee":0, "ranged":.15, "mounted":0, "machinery":1, "naval":1, "armored":0, "aviation":.15, "magical":.5}, // reduced "withdrawal": {"melee":0, "ranged":.02, "mounted":0, "machinery":.5, "naval":.1, "armored":0, "aviation":.1, "magical":.3}, // reduced // siege phases "blockade": {"melee":.25, "ranged":.25, "mounted":.2, "machinery":.5, "naval":.2, "armored":.1, "aviation":.25, "magical":.25}, // no active actions "sheltering": {"melee":.3, "ranged":.5, "mounted":.2, "machinery":.5, "naval":.2, "armored":.1, "aviation":.25, "magical":.25}, // no active actions "sortie": {"melee":2, "ranged":.5, "mounted":1.2, "machinery":.2, "naval":.1, "armored":.5, "aviation":1, "magical":1}, // melee excel "bombardment": {"melee":.2, "ranged":.5, "mounted":.2, "machinery":3, "naval":1, "armored":.5, "aviation":1, "magical":1}, // machinery excel "storming": {"melee":1, "ranged":.6, "mounted":.5, "machinery":1, "naval":.1, "armored":.1, "aviation":.5, "magical":.5}, // melee excel "defense": {"melee":2, "ranged":3, "mounted":1, "machinery":1, "naval":.1, "armored":1, "aviation":.5, "magical":1}, // ranged excel "looting": {"melee":1.6, "ranged":1.6, "mounted":.5, "machinery":.2, "naval":.02, "armored":.2, "aviation":.1, "magical":.3}, // melee excel "surrendering": {"melee":.1, "ranged":.1, "mounted":.05, "machinery":.01, "naval":.01, "armored":.02, "aviation":.01, "magical":.03}, // reduced // ambush phases "surprise": {"melee":2, "ranged":2.4, "mounted":1, "machinery":1, "naval":1, "armored":1, "aviation":.8, "magical":1.2}, // increased "shock": {"melee":.5, "ranged":.5, "mounted":.5, "machinery":.4, "naval":.3, "armored":.1, "aviation":.4, "magical":.5}, // reduced // langing phases "landing": {"melee":.8, "ranged":.6, "mounted":.6, "machinery":.5, "naval":.5, "armored":.5, "aviation":.5, "magical":.6}, // reduced "flee": {"melee":.1, "ranged":.01, "mounted":.5, "machinery":.01, "naval":.5, "armored":.1, "aviation":.2, "magical":.05}, // reduced "waiting": {"melee":.05, "ranged":.5, "mounted":.05, "machinery":.5, "naval":2, "armored":.05, "aviation":.5, "magical":.5}, // reduced // air battle phases "maneuvering": {"melee":0, "ranged":.1, "mounted":0, "machinery":.2, "naval":0, "armored":0, "aviation":1, "magical":.2}, // aviation "dogfight": {"melee":0, "ranged":.1, "mounted":0, "machinery":.1, "naval":0, "armored":0, "aviation":2, "magical":.1} // aviation }; const forces = this.getJoinedForces(this[side].regiments); const phase = this[side].phase; const adjuster = Math.max(populationRate.value / 10, 10); // population adjuster, by default 100 this[side].power = d3.sum(options.military.map(u => (forces[u.name] || 0) * u.power * scheme[phase][u.type])) / adjuster; const UIvalue = this[side].power ? Math.max(this[side].power|0, 1) : 0; document.getElementById("battlePower_"+side).innerHTML = UIvalue; } getInitialMorale() { const powerFee = diff => Math.min(Math.max(100 - diff ** 1.5 * 10 + 10, 50), 100); const distanceFee = dist => Math.min(d3.mean(dist) / 50, 15); const powerDiff = this.defenders.power / this.attackers.power; this.attackers.morale = powerFee(powerDiff) - distanceFee(this.attackers.distances); this.defenders.morale = powerFee(1 / powerDiff) - distanceFee(this.defenders.distances); this.updateMorale("attackers"); this.updateMorale("defenders"); } updateMorale(side) { const morale = document.getElementById("battleMorale_"+side); morale.dataset.tip = morale.dataset.tip.replace(morale.value, ""); morale.value = this[side].morale | 0; morale.dataset.tip += morale.value; } randomize() { this.rollDie("attackers"); this.rollDie("defenders"); this.selectPhase(); this.calculateStrength("attackers"); this.calculateStrength("defenders"); } rollDie(side) { const el = document.getElementById("battleDie_"+side); const prev = +el.innerHTML; do {el.innerHTML = rand(1, 6)} while (el.innerHTML == prev) this[side].die = +el.innerHTML; } selectPhase() { const i = this.iteration; const morale = [this.attackers.morale, this.defenders.morale]; const powerRatio = this.attackers.power / this.defenders.power; const getFieldBattlePhase = () => { const prev = [this.attackers.phase || "skirmish", this.defenders.phase || "skirmish"]; // previous phase // chance if moral < 25 if (P(1 - morale[0] / 25)) return ["retreat", "pursue"]; if (P(1 - morale[1] / 25)) return ["pursue", "retreat"]; // skirmish phase continuation depends on ranged forces number if (prev[0] === "skirmish" && prev[1] === "skirmish") { const forces = this.getJoinedForces(this.attackers.regiments.concat(this.defenders.regiments)); const total = d3.sum(Object.values(forces)); // total forces const ranged = d3.sum(options.military.filter(u => u.type === "ranged").map(u => u.name).map(u => forces[u])) / total; // ranged units if (P(ranged) || P(.8-i/10)) return ["skirmish", "skirmish"]; } return ["melee", "melee"]; // default option } const getNavalBattlePhase = () => { const prev = [this.attackers.phase || "shelling", this.defenders.phase || "shelling"]; // previous phase if (prev[0] === "withdrawal") return ["withdrawal", "chase"]; if (prev[0] === "chase") return ["chase", "withdrawal"]; // withdrawal phase when power imbalanced if (!prev[0] === "boarding") { if (powerRatio < .5 || P(this.attackers.casualties) && powerRatio < 1) return ["withdrawal", "chase"]; if (powerRatio > 2 || P(this.defenders.casualties) && powerRatio > 1) return ["chase", "withdrawal"]; } // boarding phase can start from 2nd iteration if (prev[0] === "boarding" || P(i/10 - .1)) return ["boarding", "boarding"]; return ["shelling", "shelling"]; // default option } const getSiegePhase = () => { const prev = [this.attackers.phase || "blockade", this.defenders.phase || "sheltering"]; // previous phase let phase = ["blockade", "sheltering"] // default phase if (prev[0] === "retreat" || prev[0] === "looting") return prev; if (P(1 - morale[0] / 30) && powerRatio < 1) return ["retreat", "pursue"]; // attackers retreat chance if moral < 30 if (P(1 - morale[1] / 15)) return ["looting", "surrendering"]; // defenders surrendering chance if moral < 15 if (P((powerRatio-1) / 2)) return ["storming", "defense"]; // start storm if (prev[0] !== "storming") { const machinery = options.military.filter(u => u.type === "machinery").map(u => u.name); // machinery units const attackers = this.getJoinedForces(this.attackers.regiments); const machineryA = d3.sum(machinery.map(u => attackers[u])); if (i && machineryA && P(.9)) phase[0] = "bombardment"; const defenders = this.getJoinedForces(this.defenders.regiments); const machineryD = d3.sum(machinery.map(u => defenders[u])); if (machineryD && P(.9)) phase[1] = "bombardment"; if (i && prev[1] !== "sortie" && machineryD < machineryA && P(.25) && P(morale[1]/70)) phase[1] = "sortie"; // defenders sortie } return phase; } const getAmbushPhase = () => { const prev = [this.attackers.phase || "shock", this.defenders.phase || "surprise"]; // previous phase if (prev[1] === "surprise" && P(1-powerRatio*i/5)) return ["shock", "surprise"]; // chance if moral < 25 if (P(1 - morale[0] / 25)) return ["retreat", "pursue"]; if (P(1 - morale[1] / 25)) return ["pursue", "retreat"]; return ["melee", "melee"]; // default option } const getLandingPhase = () => { const prev = [this.attackers.phase || "landing", this.defenders.phase || "defense"]; // previous phase if (prev[1] === "waiting") return ["flee", "waiting"]; if (prev[1] === "pursue") return ["flee", P(.3) ? "pursue" : "waiting"]; if (prev[1] === "retreat") return ["pursue", "retreat"]; if (prev[0] === "landing") { const attackers = P(i/2) ? "melee" : "landing"; const defenders = i ? prev[1] : P(.5) ? "defense" : "shock"; return [attackers, defenders]; } if (P(1 - morale[0] / 40)) return ["flee", "pursue"]; // chance if moral < 40 if (P(1 - morale[1] / 25)) return ["pursue", "retreat"]; // chance if moral < 25 return ["melee", "melee"]; // default option } const getAirBattlePhase = () => { const prev = [this.attackers.phase || "maneuvering", this.defenders.phase || "maneuvering"]; // previous phase // chance if moral < 25 if (P(1 - morale[0] / 25)) return ["retreat", "pursue"]; if (P(1 - morale[1] / 25)) return ["pursue", "retreat"]; if (prev[0] === "maneuvering" && P(1-i/10)) return ["maneuvering", "maneuvering"]; return ["dogfight", "dogfight"]; // default option } const phase = function(type) { switch (type) { case "field": return getFieldBattlePhase(); case "naval": return getNavalBattlePhase(); case "siege": return getSiegePhase(); case "ambush": return getAmbushPhase(); case "landing": return getLandingPhase(); case "air": return getAirBattlePhase(); default: getFieldBattlePhase(); } }(this.type); this.attackers.phase = phase[0]; this.defenders.phase = phase[1]; const buttonA = document.getElementById("battlePhase_attackers"); buttonA.className = "icon-button-" + this.attackers.phase; buttonA.dataset.tip = buttonA.nextElementSibling.querySelector("[data-phase='"+phase[0]+"']").dataset.tip; const buttonD = document.getElementById("battlePhase_defenders"); buttonD.className = "icon-button-" + this.defenders.phase; buttonD.dataset.tip = buttonD.nextElementSibling.querySelector("[data-phase='"+phase[1]+"']").dataset.tip; } run() { // validations if (!this.attackers.power) {tip("Attackers army destroyed", false, "warn"); return} if (!this.defenders.power) {tip("Defenders army destroyed", false, "warn"); return} // calculate casualties const attack = this.attackers.power * (this.attackers.die / 10 + .4); const defense = this.defenders.power * (this.defenders.die / 10 + .4); // casualties modifier for phase const phase = { "skirmish":.1, "melee":.2, "pursue":.3, "retreat":.3, "boarding":.2, "shelling":.1, "chase":.03, "withdrawal": .03, "blockade":0, "sheltering":0, "sortie":.1, "bombardment":.05, "storming":.2, "defense":.2, "looting":.5, "surrendering":.5, "surprise":.3, "shock":.3, "landing":.3, "flee":0, "waiting":0, "maneuvering":.1, "dogfight":.2}; const casualties = Math.random() * (Math.max(phase[this.attackers.phase], phase[this.defenders.phase])); // total casualties, ~10% per iteration const casualtiesA = casualties * defense / (attack + defense); // attackers casualties, ~5% per iteration const casualtiesD = casualties * attack / (attack + defense); // defenders casualties, ~5% per iteration this.calculateCasualties("attackers", casualtiesA); this.calculateCasualties("defenders", casualtiesD); this.attackers.casualties += casualtiesA; this.defenders.casualties += casualtiesD; // change morale this.attackers.morale = Math.max(this.attackers.morale - casualtiesA * 100 - 1, 0); this.defenders.morale = Math.max(this.defenders.morale - casualtiesD * 100 - 1, 0); // update table values this.updateTable("attackers"); this.updateTable("defenders"); // prepare for next iteration this.iteration += 1; this.selectPhase(); this.calculateStrength("attackers"); this.calculateStrength("defenders"); } calculateCasualties(side, casualties) { for (const r of this[side].regiments) { for (const unit in r.u) { const rand = .8 + Math.random() * .4; const died = Math.min(Pint(r.u[unit] * casualties * rand), r.survivors[unit]); r.casualties[unit] -= died; r.survivors[unit] -= died; } } } updateTable(side) { for (const r of this[side].regiments) { const tbody = document.getElementById("battle" + r.state + "-" + r.i); const battleCasualties = tbody.querySelector(".battleCasualties"); const battleSurvivors = tbody.querySelector(".battleSurvivors"); let index = 3; // index to find table element easily for (const u of options.military) { battleCasualties.querySelector(`td:nth-child(${index})`).innerHTML = r.casualties[u.name] || 0; battleSurvivors.querySelector(`td:nth-child(${index})`).innerHTML = r.survivors[u.name] || 0; index++; } battleCasualties.querySelector(`td:nth-child(${index})`).innerHTML = d3.sum(Object.values(r.casualties)); battleSurvivors.querySelector(`td:nth-child(${index})`).innerHTML = d3.sum(Object.values(r.survivors)); } this.updateMorale(side); } toggleChange(ev) { ev.stopPropagation(); const button = ev.target; const div = button.nextElementSibling; const hideSection = function() {button.style.opacity = 1; div.style.display = "none"} if (div.style.display === "block") {hideSection(); return} button.style.opacity = .5; div.style.display = "block"; document.getElementsByTagName("body")[0].addEventListener("click", hideSection, {once: true}); } changeType(ev) { if (ev.target.tagName !== "BUTTON") return; this.type = ev.target.dataset.type; this.setType(); this.selectPhase(); this.calculateStrength("attackers"); this.calculateStrength("defenders"); this.name = this.defineName(); $("#battleScreen").dialog({"title":this.name}); } changePhase(ev, side) { if (ev.target.tagName !== "BUTTON") return; const phase = this[side].phase = ev.target.dataset.phase; const button = document.getElementById("battlePhase_"+side); button.className = "icon-button-" + phase; button.dataset.tip = ev.target.dataset.tip; this.calculateStrength(side); } applyResults() { const battleName = this.name; const maxCasualties = Math.max(this.attackers.casualties, this.attackers.casualties); const relativeCasualties = this.defenders.casualties / (this.attackers.casualties + this.attackers.casualties); const battleStatus = getBattleStatus(relativeCasualties, maxCasualties); function getBattleStatus(relative, max) { if (isNaN(relative)) return ["standoff", "standoff"]; // if no casualties at all if (max < .05) return ["minor skirmishes", "minor skirmishes"]; if (relative > 95) return ["attackers flawless victory", "disorderly retreat of defenders"]; if (relative > .7) return ["attackers decisive victory", "defenders disastrous defeat"]; if (relative > .6) return ["attackers victory", "defenders defeat"]; if (relative > .4) return ["stalemate", "stalemate"]; if (relative > .3) return ["attackers defeat", "defenders victory"]; if (relative > 0.5) return ["attackers disastrous defeat", "decisive victory of defenders"]; if (relative >= 0) return ["attackers disorderly retreat", "flawless victory of defenders"]; return ["stalemate", "stalemate"]; // exception } this.attackers.regiments.forEach(r => applyResultForSide(r, "attackers")); this.defenders.regiments.forEach(r => applyResultForSide(r, "defenders")); function applyResultForSide(r, side) { const id = "regiment" + r.state + "-" + r.i; // add result to regiment note const note = notes.find(n => n.id === id); if (note) { const status = side === "attackers" ? battleStatus[0] : battleStatus[1]; const losses = r.a ? Math.abs(d3.sum(Object.values(r.casualties))) / r.a : 1; const regStatus = losses === 1 ? "is destroyed" : losses > .8 ? "is almost completely destroyed" : losses > .5 ? "suffered terrible losses" : losses > .3 ? "suffered severe losses" : losses > .2 ? "suffered heavy losses" : losses > .05 ? "suffered significant losses" : losses > 0 ? "suffered unsignificant losses" : "left the battle without loss"; const casualties = Object.keys(r.casualties).map(t => r.casualties[t] ? `${Math.abs(r.casualties[t])} ${t}` : null).filter(c => c); const casualtiesText = casualties.length ? " Casualties: " + list(casualties) + "." : ""; const legend = `\r\n\r\n${battleName} (${options.year} ${options.eraShort}): ${status}. The regiment ${regStatus}.${casualtiesText}`; note.legend += legend; } r.u = Object.assign({}, r.survivors); r.a = d3.sum(Object.values(r.u)); // reg total armies.select(`g#${id} > text`).text(Military.getTotal(r)); // update reg box } // append battlefield marker void function addMarkerSymbol() { if (svg.select("#defs-markers").select("#marker_battlefield").size()) return; const symbol = svg.select("#defs-markers").append("symbol").attr("id", "marker_battlefield").attr("viewBox", "0 0 30 30"); symbol.append("path").attr("d", "M6,19 l9,10 L24,19").attr("fill", "#000000").attr("stroke", "none"); symbol.append("circle").attr("cx", 15).attr("cy", 15).attr("r", 10).attr("fill", "#ffffff").attr("stroke", "#000000").attr("stroke-width", 1); symbol.append("text").attr("x", "50%").attr("y", "52%").attr("fill", "#000000").attr("stroke", "#3200ff").attr("stroke-width", 0) .attr("font-size", "12px").attr("dominant-baseline", "central").text("⚔️"); }() const getSide = (regs, n) => regs.length > 1 ? `${n ? "regiments" : "forces"} of ${list([... new Set(regs.map(r => pack.states[r.state].name))])}` : getAdjective(pack.states[regs[0].state].name) + " " + regs[0].name; const getLosses = casualties => Math.min(rn(casualties * 100), 100); const status = battleStatus[+P(.7)]; const result = `The ${this.getTypeName(this.type)} ended in ${status}`; const legend = `${this.name} took place in ${options.year} ${options.eraShort}. It was fought between ${getSide(this.attackers.regiments, 1)} and ${getSide(this.defenders.regiments, 0)}. ${result}. \r\nAttackers losses: ${getLosses(this.attackers.casualties)}%, defenders losses: ${getLosses(this.defenders.casualties)}%`; const id = getNextId("markerElement"); notes.push({id, name:this.name, legend}); tip(`${this.name} is over. ${result}`, true, "success", 4000); markers.append("use").attr("id", id) .attr("xlink:href", "#marker_battlefield").attr("data-id", "#marker_battlefield") .attr("data-x", this.x).attr("data-y", this.y).attr("x", this.x - 15).attr("y", this.y - 30) .attr("data-size", 1).attr("width", 30).attr("height", 30); $("#battleScreen").dialog("destroy"); this.cleanData(); } cancelResults() { // move regiments back to initial positions this.attackers.regiments.concat(this.defenders.regiments).forEach(r => Military.moveRegiment(r, r.px, r.py)); $("#battleScreen").dialog("close"); this.cleanData(); } cleanData() { battleAttackers.innerHTML = battleDefenders.innerHTML = ""; // clean DOM customization = 0; // exit edit mode // clean temp data this.attackers.regiments.concat(this.defenders.regiments).forEach(r => { delete r.px; delete r.py; delete r.casualties; delete r.survivors; }); delete Battle.prototype.context; } }import fs from 'fs'; import test from 'tape'; import glob from 'glob'; import path from 'path'; import load from 'load-json-file'; import write from 'write-json-file'; import { point, featureCollection } from '../helpers'; import voronoi from '.'; const directories = { in: path.join(__dirname, 'test', 'in') + path.sep, out: path.join(__dirname, 'test', 'out') + path.sep }; const fixtures = fs.readdirSync(directories.in).map(filename => { return {filename, geojson: load.sync(directories.in + filename)}; }); test('turf-voronoi', t => { for (const {filename, geojson} of fixtures) { const results = voronoi(geojson, {bbox: geojson.bbox}); if (process.env.REGEN) write.sync(directories.out + filename, results); const expected = load.sync(directories.out + filename); t.deepEquals(results, expected, path.parse(filename).name); }; t.end(); }); test('turf-voronoi - test properties', t => { const result = voronoi(featureCollection([point([145, -37], {foo: 'bar'})]), { bbox: [140, -40, 160, -30], addPropertiesToPolygons: true }); t.equal(result.features[0].properties.foo, 'bar') const result2 = voronoi(featureCollection([point([145, -37], {foo: 'bar'})]), { bbox: [140, -40, 160, -30], addPropertiesToPolygons: false }); t.equal(Object.keys(result2.features[0].properties).length, 0) t.end(); });matthewpaulin/BoardzillaApplication/server/config/environment.js0 process.env.DATABASE_URL = process.env.DATABASE_URL || "mongodb://127.0.0.1:27017/boardzilla"; process.env.NODE_ENV = process.env.NODE_ENV || "development"; process.env.PORT = process.env.PORT || 3000; process.env.SECRET = process.env.SECRET || "secret"; process.env.NEWS_KEY = process.env.NEWS_KEY || ""; process.env.STOCK_KEY = process.env.STOCK_KEY || "5KO3BAP8N60LIR0T"; process.env.WEATHER_KEY = process.env.WEATHER_KEY || ""; process.env.GEO_KEY = process.env.GEO_KEY || ""; const mongoose = require('mongoose'); const URL = 'mongodb://localhost/clinicaDB'; /*mongoose.connect(URI) .then(db => console.log('DB is connected')) .catch(err => console.error(err));*/ mongoose.connect(URL, { useNewUrlParser: true }, (err, res) => { if (err) throw err; console.log('DB is connected'); process.on('SIGINT', () => { mongoose.connection.close(() => { console.log('Mongo is disconnected'); process.exit(0); }) }) }); module.exports = mongoose;1-10 "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var bn_js_1 = __importDefault(require("bn.js")); var address_1 = require("../address"); var big_uint_1 = require("../big-uint"); var crypto_utils_1 = require("../crypto-utils"); var solidity_helpers_1 = require("./solidity-helpers"); var plasma_cash_pb_1 = require("../proto/plasma_cash_pb"); var PlasmaCashTx = /** @class */ (function () { function PlasmaCashTx(params) { this.slot = params.slot; this.prevBlockNum = params.prevBlockNum; this.denomination = new bn_js_1.default(params.denomination); this.newOwner = params.newOwner; this.prevOwner = params.prevOwner; this.sigBytes = params.sig; this.proofBytes = params.proof; } PlasmaCashTx.prototype.rlpEncode = function () { var data = [ this.slot.toArrayLike(Buffer, 'be'), this.prevBlockNum.toNumber(), this.denomination.toNumber(), this.newOwner ]; console.log("This is screwed up"); return '0x'; //+ rlp.encode(data).toString('hex') }; Object.defineProperty(PlasmaCashTx.prototype, "sig", { /** * Hex encoded signature of the tx, prefixed by "0x". */ get: function () { return '0x' + (this.sigBytes ? crypto_utils_1.bytesToHex(this.sigBytes) : ''); }, enumerable: true, configurable: true }); Object.defineProperty(PlasmaCashTx.prototype, "proof", { /** * Hex encoded merkle proof of the tx, prefixed by "0x". */ get: function () { return '0x' + (this.proofBytes ? crypto_utils_1.bytesToHex(this.proofBytes) : ''); }, enumerable: true, configurable: true }); Object.defineProperty(PlasmaCashTx.prototype, "hash", { /** * Hex encoded hash of the tx, prefixed by "0x". */ get: function () { if (this.prevBlockNum.cmp(new bn_js_1.default(0)) === 0) { return solidity_helpers_1.soliditySha3({ type: 'uint64', value: this.slot }); } return solidity_helpers_1.soliditySha3({ type: 'bytes', value: this.rlpEncode() }); }, enumerable: true, configurable: true }); /** * Signs the tx. * @param signer Signer to use for signing the tx. */ PlasmaCashTx.prototype.signAsync = function (signer) { return __awaiter(this, void 0, void 0, function () { var _a; return __generator(this, function (_b) { switch (_b.label) { case 0: _a = this; return [4 /*yield*/, signer.signAsync(this.hash)]; case 1: _a.sigBytes = _b.sent(); return [2 /*return*/]; } }); }); }; return PlasmaCashTx; }()); exports.PlasmaCashTx = PlasmaCashTx; function unmarshalPlasmaTxPB(rawTx) { if (!rawTx.hasNewOwner()) { throw new Error('Invalid PlasmaTx: missing new owner'); } var tx = new PlasmaCashTx({ slot: new bn_js_1.default(rawTx.getSlot()), prevBlockNum: rawTx.hasPreviousBlock() ? big_uint_1.unmarshalBigUIntPB(rawTx.getPreviousBlock()) : new bn_js_1.default(0), denomination: rawTx.hasDenomination() ? big_uint_1.unmarshalBigUIntPB(rawTx.getDenomination()) : new bn_js_1.default(0), newOwner: address_1.Address.UmarshalPB(rawTx.getNewOwner()).local.toString(), sig: rawTx.getSignature_asU8(), proof: rawTx.getProof_asU8() }); var sender = rawTx.getSender(); if (sender) { tx.prevOwner = address_1.Address.UmarshalPB(sender).local.toString(); } return tx; } exports.unmarshalPlasmaTxPB = unmarshalPlasmaTxPB; function marshalPlasmaTxPB(tx) { var owner = new address_1.Address('eth', address_1.LocalAddress.fromHexString(tx.newOwner)); var pb = new plasma_cash_pb_1.PlasmaTx(); // TODO: protoc TypeScript plugin does't seem to understand annotations in .proto so the type // definition is wrong for the slot, it's actually a string that represents a 64-bit number... // should fix the plugin or use a different one. pb.setSlot(tx.slot.toString(10)); pb.setPreviousBlock(big_uint_1.marshalBigUIntPB(tx.prevBlockNum)); pb.setDenomination(big_uint_1.marshalBigUIntPB(tx.denomination)); pb.setNewOwner(owner.MarshalPB()); if (tx.prevOwner) { var sender = new address_1.Address('eth', address_1.LocalAddress.fromHexString(tx.prevOwner)); pb.setSender(sender.MarshalPB()); } if (tx.sigBytes) { pb.setSignature(crypto_utils_1.bufferToProtobufBytes(tx.sigBytes)); } if (tx.proofBytes) { pb.setProof(crypto_utils_1.bufferToProtobufBytes(tx.proofBytes)); } return pb; } exports.marshalPlasmaTxPB = marshalPlasmaTxPB; //# sourceMappingURL=plasma-cash-tx.js.map1-10 import React from 'react'; import { Link } from 'react-router-dom'; // import{Switch, Route}from "react-router-dom"; // import FormList from './Formlist'; // import ContactDetails from './ContactDetails'; function Contact(props) { return (

    MY STORY

    In 2006, I began a short internship with the prestigious SlickForce Studio's in Los Angeles, studying under . After just three months, I became a member of the SlickForce Team, which began my journey into mastering all phases of what is required in the photography field, moving through the stages of grip gear, lighting, casting, business management, location scouting, and pro retouching. Not long after I was co-publishing with the my mentor in the Kardashian Konfidential Book. After three years with SlickForce Studios, I decided to move to Las Vegas, and start Esko Photography.



    derek eskridge and <NAME>

      I specialize in:

    • Real Estate Photography,
    • Portfolios,
    • Product/Company Branding,
    • Videography,
    • Photo Retouching/Editing,
    • Graphic Design,
    • Marketing/Advertising,
    • SEO/Google Analytics/Adwords

    , Owner of Esko Photography

    • OK Magazine
    • Celeb-Life Magazine
    • Peta Campaigns
    • Breast Cancer Awareness Campaigns
    • Kardashian's Konfidential Book
    • WMB3D Magazine
    {/*

    Other Places you can find my work:

    */} {/*
    */}
    Connect with Esko Photography on Social Media


    Admin Access Only

    ) } export default Contact;/** * Fiber History Collection * @class * @extends {$RouterCollection} */ Fiber.HistoryCollection = $RouterCollection.extend({ /** * Default Model * @type {History} */ model: Fiber.HistoryItem, /** * History size * @type {number} */ historySize: 20, /** * Add a model, or list of models to the set. `models` may be Fiber * Models or raw JavaScript objects to be converted to Models, or any * combination of the two. * * Also checks history size and reduces it if needed * * @param {Object.|Array} models * @param {?Object} [options] */ add: function(models, options) { this.handleSize(); return this.$super('add', arguments); }, /** * Handles size of the history collection * @return {Fiber.HistoryCollection} */ handleSize: function() { if (this.length >= this.historySize) this.shift(); return this; } }); var structlibwifi__reassoc__req__fixed__parameters = [ [ "capabilities_information", "structlibwifi__reassoc__req__fixed__parameters.html#aede0979fbb40ebb30d818619802fbdfa", null ], [ "current_ap_address", "structlibwifi__reassoc__req__fixed__parameters.html#a7761b0189db533b128943f589a7425e3", null ], [ "listen_interval", "structlibwifi__reassoc__req__fixed__parameters.html#aa8c60d188ee66e47eced3868eff98b3c", null ] ];import React from "react"; import { Route, Switch, Redirect } from "react-router-dom"; import "./App.css"; import PrivateRoute from "./components/private-route"; import Login from "./pages/login"; import SignUp from "./pages/sign-up"; import PlantsPage from "./pages/plants/"; import Navigation from "./components/navigation"; import EditUser from "./components/edit-user"; function NoRoute() { return ; } function App() { return (
    ); } export default App; import { LitElement, html } from 'lit'; export class RandomWord extends LitElement { static get tag() { return 'random-word'; } constructor() { super(); this.key = null; this.phrases = {}; this.word = null; } static get properties() { return { key: { type: String }, phrases: { type: Object }, word: { type: String }, }; } updated(changedProperties) { changedProperties.forEach((oldValue, propName) => { if (['key', 'phrases'].includes(propName)) { this.getNewWord(); } // wipe slot and rebuild if (propName === 'word' && this[propName]) { this.innerHTML = ''; this.innerHTML = this.word; // inform others if they want to tap into events this.dispatchEvent( new CustomEvent('word-changed', { detail: this.word }) ); } }); } getNewWord() { if (this.phrases && this.key && this.phrases[this.key]) { this.word = this.phrases[this.key][ Math.floor(Math.random() * this.phrases[this.key].length) ]; } } render() { return html``; } } customElements.define(RandomWord.tag, RandomWord); const target = "fi"; import(`translations/${target}.json`) .then(/* ... */) .catch(/*... */); import { Action } from '../../lib'; import { replaceAll } from '../../lib/utils'; /** * TODO: Describe action */ class ObsAction extends Action { /** * Instantiates a new Obs * Action */ constructor() { super('OBS Action', 'core.rosie.obs.action') } /** * Executes the action. * @param {string} message */ execute(intent, params) { console.log(intent, params); if (typeof intent === "string") { let message = intent; if (params && !!params.length) { let entries = Object.entries(params[0]); for (let i = 0; i < entries.length; i++) { const [key, value] = entries[i]; message = replaceAll(message, `{{${key}}}`, value); } } if (intent === '{{obs-scene}}') { this.$store.dispatch('obs/changescene', message); } else { console.log('unknown intent'); } } else { if (intent.action) { switch (intent.action) { case 'switch': if (!~intent.exception.findIndex(d=>d===this.$store.state.obs.currentScene)) { this.$store.dispatch('obs/changescene', intent.scene); } break; case 'previous': if (this.$store.state.obs.previousScene) { this.$store.dispatch('obs/changescene', this.$store.state.obs.previousScene); } break; default: console.log('unknown intent'); break; } } } } } export default new ObsAction();import "../../../node_modules/n-carousel/n-carousel.js";/* @adobe/react-spectrum-workflow (c) by Adobe @adobe/react-spectrum-workflow is licensed under a Creative Commons Attribution-NoDerivatives 4.0 International License. You should have received a copy of the license along with this work. If not, see . */ import React from 'react'; import {viewBoxes} from './util'; export function A4uDataUser({scale = 'M', color = 'LIGHT', ...props}) { return ( ); } src/api/product/tradeMark.js import request from '@/utils/request'; export const reqTRadeMarkList = (page,limit)=>request({ url:`/admin/product/baseTrademark/${page}/${limit}`,method:'get' }) // 添加 // /admin/product/baseTrademark/save // 修改 // /admin/product/baseTrademark/update export const reqAddOrUpdateTradeMark = (tradeMark)=>{ if(tradeMark.id){ return request({ url:`/admin/product/baseTrademark/update`,method:'put',data:tradeMark }); }else{ return request({ url:`/admin/product/baseTrademark/save`,method:'post',data:tradeMark }); } } // 删除 // /admin/product/baseTrademark/remove/{id} export const reqDeleteTradeMark =(id)=>request({ url:`/admin/product/baseTrademark/remove/${id}`,method:'delete', }); xiongmeiqiang123/serverRender import React from 'react' import { render } from 'react-dom' import Application from "./Application" render(
    , document.getElementById("content") ); (function() { var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var tslint = require('gulp-tslint'); var appDev = './src/main/webapp/'; var appProd = './src/main/webapp/dist/'; /* Mixed */ var ext_replace = require('gulp-ext-replace'); /* CSS */ var postcss = require('gulp-postcss'); var sourcemaps = require('gulp-sourcemaps'); var autoprefixer = require('autoprefixer'); var precss = require('precss'); var cssnano = require('cssnano'); /* JS & TS */ var typescript = require('gulp-typescript'); /* Images */ var imagemin = require('gulp-imagemin'); var tsProject = typescript.createProject('src/main/webapp/ts/tsconfig.json'); gulp.task('build-css', function() { return gulp.src(appDev + 'scss/*.scss') .pipe(sourcemaps.init()) .pipe(postcss([precss, autoprefixer, cssnano])) .pipe(sourcemaps.write('.')) .pipe(ext_replace('.css')) .pipe(gulp.dest(appProd + 'css/')) .pipe($.size({'title': 'css'})); }); gulp.task('build-ts', function() { var result = gulp.src([appDev + 'ts/**/*.ts']) .pipe(tslint()) .pipe(tslint.report("verbose")) .pipe(sourcemaps.init()) .pipe(typescript(tsProject)); // pipe the js files to dist folder result.dts.pipe(gulp.dest(appProd + 'js')); return result.js .pipe(sourcemaps.write('.')) .pipe(gulp.dest(appProd + 'js')) .pipe($.size({'title': 'ts'})); }); gulp.task('build', [ 'build-ts', 'build-css', 'build-img', 'build-fonts', 'build-locale' ], function() { return gulp.src(appDev + 'index.html') .pipe($.useref({'searchPath': './'})) .pipe(gulp.dest(appProd)) .pipe($.size({'title': 'html'})); }); /*gulp.task('build-ang-dependencies', function () { return gulp.src([ 'node_modules/moment/moment.js' ]) .pipe(concat('vendor.min.js')) .pipe(uglify()).on('error', onError) .pipe(gulp.dest(appProd)) });*/ gulp.task('build-img', function() { return gulp.src(appDev + 'img/**/*') .pipe(imagemin({progressive: true})) .pipe(gulp.dest(appProd + 'img/')); }); gulp.task('build-fonts', function() { return gulp.src(appDev + 'fonts/**/*') .pipe(gulp.dest(appProd + 'fonts/')); }); gulp.task('build-locale', function() { return gulp.src(appDev + 'locale/**/*') .pipe(gulp.dest(appProd + 'locale/')); }); gulp.task('clean', function() { return gulp.src(appProd, {read: false}) .pipe($.clean()); }); gulp.task('watch', function() { gulp.watch(appDev + '**/*.ts', ['build-ts']); gulp.watch(appDev + 'scss/**/*.scss', ['build-css']); gulp.watch(appDev + 'img/*', ['build-img']); }); gulp.task('default', ['build-html']); }()) #!/usr/bin/env node console.log( Number(process.argv[2]) + Number(process.argv[3]) ) Computer-Science-Build-Week/CS-Build-Week-FE import React from 'react'; import { withRouter } from 'react-router-dom'; import { GameArena, GameContainer } from './ViewStyles/GameStyles'; import { Border } from '../components/Border'; import useMaze from '../state/state'; import { Character } from '../components/Character'; import Dashboard from '../components/Dashboard'; const Game = ({history}) => { const { x, y, maze, loaded, directions } = useMaze(); return ( {loaded && ( )} ); }; export default withRouter(Game); describe('The SCBD Header Desktop', () => { beforeEach(() => { cy.viewport('macbook-15') }) it('Header Element Loads', () => { cy.visit('/') cy.get('footer') .should('have.id', 'pageFooter') }) it('It should contain 8 navs', () => { cy.get('nav') .should(($nav) => { expect($nav).to.have.length(8) }) }) it('it takes screen shots', () => { cy.screenshot('footer') }) })kaoscript/kaoscript var {Helper, Type} = require("@kaoscript/runtime"); module.exports = function() { let Writer = Helper.class({ $name: "Writer", $create: function() { this.__ks_init(); this.__ks_cons(arguments); }, __ks_init: function() { }, __ks_cons_0: function(Line) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(Line === void 0 || Line === null) { throw new TypeError("'Line' is not nullable"); } else if(!Type.isClass(Line)) { throw new TypeError("'Line' is not of type 'Class'"); } this.Line = Line; }, __ks_cons: function(args) { if(args.length === 1) { Writer.prototype.__ks_cons_0.apply(this, args); } else { throw new SyntaxError("Wrong number of arguments"); } }, __ks_func_newLine_0: function() { let args = Array.prototype.slice.call(arguments, 0, arguments.length); return Helper.create(this.Line, args); }, newLine: function() { return Writer.prototype.__ks_func_newLine_0.apply(this, arguments); } }); };import SignupActions from "../actions/SignupActions"; import axios from "axios"; import bluebird from "bluebird"; import { apihost as host } from "../constants"; import u2f from "../lib/u2f"; import { AuthyHelper } from "./AuthyHelper"; export const SignupSource = { signup: { remote(state, username, password) { return axios.post(`${host}/accounts`, { username: username.trim().toLowerCase(), password: password }) }, success: SignupActions.signupCompleted, error: SignupActions.signupErrored, }, registerSms: { remote(state, phoneNumber) { return axios.post(`${host}/sms/enable`, { phone_number: phoneNumber }) }, success: SignupActions.signupSmsCompleted, error: SignupActions.signupSmsErrored, }, enableBackupCodes: { remote(state) { return axios.post(`${host}/codes/enable`) }, success: SignupActions.signupBackupCodesCompleted, error: SignupActions.signupBackupCodesErrored, }, enableTotp: { remote(state) { return axios.post(`${host}/totp/enable`); }, success: SignupActions.signupTotpCompleted, error: SignupActions.signupTotpErrored, }, registerU2F: { async remote(state) { // await u2f.ensureSupport(); // console.log("U2F: Yes it is supported"); const response = await axios.post(`${host}/u2f/beginenable`) const registrationRequest = response.data; console.log("here is the registration request", registrationRequest); const appId = response.data["appId"]; const registerRequests = response.data["registerRequests"]; const regResponse = await new Promise((resolve, reject) => { const waitForYubiKey = () => { u2f.register(appId, registerRequests, [], (chromeResponse) => { if (chromeResponse["errorCode"]) { console.error("We had a U2F error, but ignoring it...", chromeResponse); setTimeout(waitForYubiKey, 0); } else { resolve(chromeResponse); } }); } setTimeout(waitForYubiKey, 0); }); return await axios.post(`${host}/u2f/completeenable`, regResponse); }, success: SignupActions.signupU2FCompleted, error: SignupActions.signupU2FErrored, }, registerPush: { async remote(state, phoneNumber) { await axios.post(`${host}/push/beginenable`, { "phone_number": phoneNumber, }); return await AuthyHelper.check_authy_status(); }, success: SignupActions.signupPushCompleted, error: SignupActions.signupPushErrored, } } web/add-user-to-views/index.js 'use strict' const _ = require('lodash') function register (server, options) { server.ext('onPreResponse', (request, h) => { const response = request.response // rendering a view? then add the user object if (response.variety && _.isEqual(response.variety, 'view')) { response.source.context = response.source.context || {} if (request.auth.isAuthenticated) { response.source.context.user = request.auth.credentials return h.continue } } return h.continue }) server.log('info', 'Plugin add user!') } exports.plugin = { name: 'add-user-object-to-views', version: '1.0.0', register } import React from 'react'; import {connect} from "react-redux"; import {reset} from "redux-form"; import {getUserInfo} from "../../common/selectors/userSelector"; import DepEdit from "../components/DepEdit"; import {getAllOrgForNew} from "../selectors/organisationsSelector"; import {getAllFacForNewByOrgId} from "../selectors/facultiesSelector"; import {clearDepState, saveDep, updateDep} from "../actions/depEditActions"; import {clearOrgIdSelected, setOrgIdSelected} from "../actions/organisationsActions"; import {getDepById} from "../selectors/departmentsSelector"; const mapStateToProps = (state, ownProps) => { const {depId} = ownProps; return { userInfo: getUserInfo(state), depEdit: state.depEdit, organisations: getAllOrgForNew(state), // Nullable faculties: getAllFacForNewByOrgId(state), // Nullable dep: depId ? getDepById(state, ownProps) : null } } const mapDispatchToProps = dispatch => { return { saveDep: (depDTO) => dispatch(saveDep(depDTO)), updateDep: (depDTO) => dispatch(updateDep(depDTO)), clearDepState: ()=>dispatch(clearDepState()), setOrgIdSelected: (orgId) => dispatch(setOrgIdSelected(orgId)), clearOrgIdSelected: () => dispatch(clearOrgIdSelected()), resetForm: ()=>dispatch(reset('dep-edit')), } } const DepEditContainer = connect(mapStateToProps, mapDispatchToProps)(DepEdit); export default DepEditContainer;var app = require('./config/custom-express')(); app.listen(3000,function(){ console.log("Server started!"); }); (window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/orders/Order.vue?vue&type=script&lang=js&": /*!******************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/orders/Order.vue?vue&type=script&lang=js& ***! \******************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "./node_modules/@babel/runtime/regenerator/index.js"); /* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); /* harmony import */ var _services_order_service__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../services/order_service */ "./resources/js/services/order_service.js"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // /* harmony default export */ __webpack_exports__["default"] = ({ name: "Order", data: function data() { return { listOrders: {}, errors: {}, orderDetailData: {}, listTrangThai: [{ id: 1, 'Ten': 'Chờ xác nhận' }, { id: 2, 'Ten': 'Đã xác nhận' }, { id: 3, 'Ten': 'Đã giao hàng' }, { id: 4, 'Ten': 'Bị hủy' }, { id: 5, 'Ten': 'Hoàn thành' }] }; }, mounted: function mounted() { this.getListOrders(); }, methods: { statusOrder: function statusOrder(status) { switch (status) { case 2: return "\u0110\xE3 x\xE1c nh\u1EADn"; break; case 3: return "\u0110\xE3 giao h\xE0ng"; break; case 4: return "B\u1ECB h\u1EE7y"; break; case 5: return "Ho\xE0n th\xE0nh"; break; default: return "Ch\u1EDD x\xE1c nh\u1EADn"; break; } }, formatPrice: function formatPrice(price) { var val = (price / 1).toFixed(2).replace('.', ','); return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); }, getListOrders: function () { var _getListOrders = _asyncToGenerator( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() { var response; return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.prev = 0; _context.next = 3; return _services_order_service__WEBPACK_IMPORTED_MODULE_1__["getListOrders"](); case 3: response = _context.sent; this.listOrders = response.data; _context.next = 10; break; case 7: _context.prev = 7; _context.t0 = _context["catch"](0); swal("Thất bại", "Một số lỗi đã xảy ra, xin vui lòng tải lại", "error"); case 10: case "end": return _context.stop(); } } }, _callee, this, [[0, 7]]); })); function getListOrders() { return _getListOrders.apply(this, arguments); } return getListOrders; }(), showOrderDetailModal: function showOrderDetailModal() { this.$refs['orderDetailModal'].show(); }, orderDetail: function orderDetail(order) { this.showOrderDetailModal(); this.orderDetailData = _objectSpread({}, order); }, hideOrderDetailModal: function hideOrderDetailModal() { this.$refs['orderDetailModal'].hide(); } // createBoSuuTap: async function() { // try { // const formData = new FormData(); // formData.append('TenBST',this.boSuuTapData.TenBST); // formData.append('MoTa',this.boSuuTapData.MoTa); // formData.append('AnhChinh',this.boSuuTapData.AnhChinh); // // const response = await boSuuTapService.createBoSuuTap(formData); // this.listBoSuuTap.unshift(response.data); // // this.hideNewBoSuuTapModal(); // this.errors = {}; // this.boSuuTapData = { // TenBST: '', // MoTa: '' // }; // // swal("Thành công", "Thêm bộ sưu tập thành công", "success"); // } catch (error) { // switch (error.response.status) { // case 422: // this.errors = error.response.data.errors; // break; // case 500: // swal("Thất bại", "Thêm bộ sưu tập thất bại, xin vui lòng thử lại!", "error"); // break; // default: // swal("Thất bại", "Một số lỗi đã xảy ra, xin vui lòng Thử lại", "error"); // break; // } // } // }, // showEditBoSuuTapModal() { // this.$refs['editBoSuuTapModal'].show(); // }, // hideEditBoSuuTapModal() { // this.$refs['editBoSuuTapModal'].hide(); // }, // editBoSuuTap(boSuuTap) { // this.editBoSuuTapData = {...boSuuTap}; // this.showEditBoSuuTapModal(); // }, // updateBoSuuTap: async function() { // try { // const formData = new FormData(); // formData.append('TenBST',this.editBoSuuTapData.TenBST); // formData.append('MoTa',this.editBoSuuTapData.MoTa); // formData.append('AnhChinh',this.editBoSuuTapData.AnhChinh); // formData.append('_method','put'); // // const response = await boSuuTapService.updateBoSuuTap(this.editBoSuuTapData.id, formData); // // this.listBoSuuTap.map(boSuuTap => { // if (boSuuTap.id == response.data.id) { // for (let key in response.data) { // boSuuTap[key] = response.data[key]; // } // } // }); // // this.hideEditBoSuuTapModal(); // this.errors = {}; // // swal("Thành công", "Cập nhật bộ sưu tập thành công", "success"); // } catch (error) { // switch (error.response.status) { // case 422: // this.errors = error.response.data.errors; // break; // case 500: // swal("Thất bại", "Thêm bộ sưu tập thất bại, xin vui lòng thử lại!", "error"); // break; // default: // swal("Thất bại", "Một số lỗi đã xảy ra, xin vui lòng Thử lại", "error"); // break; // } // } // }, // deleteBoSuuTap: async function(boSuuTap) { // if (!confirm('Bạn có chất muốn xóa danh mục này')) { // return // } // // try { // await boSuuTapService.deleteBoSuuTap(boSuuTap.id); // // this.listBoSuuTap = this.listBoSuuTap.filter(obj => { // return obj.id != boSuuTap.id; // }); // // swal("Thành công", "Xóa bộ sưu tập thành công", "success"); // } catch (error) { // switch (error.response.status) { // case 500: // swal("Thất bại", error.response.data.message, "error"); // break; // default: // swal("Thất bại", "Một số lỗi đã xảy ra, xin vui lòng Thử lại", "error"); // break; // } // } // }, } }); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true&": /*!**********************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true& ***! \**********************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c( "div", { staticClass: "container-fluid" }, [ _c("div", { staticClass: "card shadow mb-4" }, [ _vm._m(0), _vm._v(" "), _c("div", { staticClass: "card-body" }, [ _c("div", { staticClass: "table-responsive" }, [ _c( "table", { staticClass: "table table-bordered", attrs: { id: "dataTable", width: "100%", cellspacing: "0" } }, [ _vm._m(1), _vm._v(" "), _c( "tbody", _vm._l(_vm.listOrders, function(order, index) { return _c("tr", { key: index }, [ _c("td", [_vm._v(_vm._s(index + 1))]), _vm._v(" "), _c("td", [_vm._v(_vm._s(order.name))]), _vm._v(" "), _c("td", [_vm._v(_vm._s(order.phone))]), _vm._v(" "), _c("td", [_vm._v(_vm._s(order.NgayTao))]), _vm._v(" "), _c("td", [ _c("div", { domProps: { innerHTML: _vm._s(_vm.statusOrder(order.TrangThai)) } }) ]), _vm._v(" "), _c("td", [ _vm._v(_vm._s(_vm.formatPrice(order.TongGia)) + " vnđ") ]), _vm._v(" "), _c("td", [ _c( "button", { staticClass: "btn btn-primary btn-sm", attrs: { title: "Chi tiết đơn hàng" }, on: { click: function($event) { return _vm.orderDetail(order) } } }, [_c("span", { staticClass: "fa fa-edit" })] ) ]) ]) }), 0 ) ] ) ]) ]) ]), _vm._v(" "), _c( "b-modal", { ref: "orderDetailModal", attrs: { "hide-footer": "", title: "Thông tin đơn hàng" } }, [ _c( "form", { on: { submit: function($event) { $event.preventDefault() return _vm.updateBoSuuTap($event) } } }, [ _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "name" } }, [ _vm._v("Tên khách hàng") ]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.name, expression: "orderDetailData.name" } ], staticClass: "form-control", attrs: { type: "text" }, domProps: { value: _vm.orderDetailData.name }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set(_vm.orderDetailData, "name", $event.target.value) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "phone" } }, [ _vm._v("Số điện thoại") ]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.phone, expression: "orderDetailData.phone" } ], staticClass: "form-control", attrs: { type: "text" }, domProps: { value: _vm.orderDetailData.phone }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set( _vm.orderDetailData, "phone", $event.target.value ) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "address" } }, [_vm._v("Địa chỉ")]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.address, expression: "orderDetailData.address" } ], staticClass: "form-control", attrs: { type: "text" }, domProps: { value: _vm.orderDetailData.address }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set( _vm.orderDetailData, "address", $event.target.value ) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "city" } }, [_vm._v("Thành phố")]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.city, expression: "orderDetailData.city" } ], staticClass: "form-control", attrs: { type: "text" }, domProps: { value: _vm.orderDetailData.city }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set(_vm.orderDetailData, "city", $event.target.value) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "district" } }, [_vm._v("Quận")]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.district, expression: "orderDetailData.district" } ], staticClass: "form-control", attrs: { type: "text" }, domProps: { value: _vm.orderDetailData.district }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set( _vm.orderDetailData, "district", $event.target.value ) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "TongGia" } }, [_vm._v("Đơn giá")]), _vm._v(" "), _c("input", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.TongGia, expression: "orderDetailData.TongGia" } ], staticClass: "form-control", attrs: { type: "text", readonly: "" }, domProps: { value: _vm.orderDetailData.TongGia }, on: { input: function($event) { if ($event.target.composing) { return } _vm.$set( _vm.orderDetailData, "TongGia", $event.target.value ) } } }) ]), _vm._v(" "), _c("div", { staticClass: "form-group" }, [ _c("label", { attrs: { for: "TrangThai" } }, [ _vm._v("Trạng thái") ]), _vm._v(" "), _c( "select", { directives: [ { name: "model", rawName: "v-model", value: _vm.orderDetailData.TrangThai, expression: "orderDetailData.TrangThai" } ], staticClass: "form-control", on: { change: function($event) { var $$selectedVal = Array.prototype.filter .call($event.target.options, function(o) { return o.selected }) .map(function(o) { var val = "_value" in o ? o._value : o.value return val }) _vm.$set( _vm.orderDetailData, "TrangThai", $event.target.multiple ? $$selectedVal : $$selectedVal[0] ) } } }, _vm._l(_vm.listTrangThai, function(trangThai) { return _c("option", { domProps: { value: trangThai.id } }, [ _vm._v(_vm._s(trangThai.Ten)) ]) }), 0 ) ]), _vm._v(" "), _c("div", { staticClass: "float-right" }, [ _c( "button", { staticClass: "btn btn-danger", attrs: { type: "button" }, on: { click: _vm.hideOrderDetailModal } }, [_vm._v("Đóng")] ) ]) ] ) ] ) ], 1 ) } var staticRenderFns = [ function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("div", { staticClass: "card-header py-3 d-flex" }, [ _c("h6", { staticClass: "m-0 font-weight-bold text-primary" }, [ _vm._v("Quản lý đơn hàng") ]) ]) }, function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h return _c("thead", [ _c("tr", [ _c("th", [_vm._v("#")]), _vm._v(" "), _c("th", [_vm._v("Tên khách hàng")]), _vm._v(" "), _c("th", [_vm._v("SĐT")]), _vm._v(" "), _c("th", [_vm._v("Ngày đặt hàng")]), _vm._v(" "), _c("th", [_vm._v("Trạng thái")]), _vm._v(" "), _c("th", [_vm._v("Đơn giá")]), _vm._v(" "), _c("th", [_vm._v("Hành động")]) ]) ]) } ] render._withStripped = true /***/ }), /***/ "./resources/js/services/order_service.js": /*!************************************************!*\ !*** ./resources/js/services/order_service.js ***! \************************************************/ /*! exports provided: getListOrders */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getListOrders", function() { return getListOrders; }); /* harmony import */ var _http_service__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./http_service */ "./resources/js/services/http_service.js"); function getListOrders() { return Object(_http_service__WEBPACK_IMPORTED_MODULE_0__["http"])().get('get-list-orders'); } /***/ }), /***/ "./resources/js/views/orders/Order.vue": /*!*********************************************!*\ !*** ./resources/js/views/orders/Order.vue ***! \*********************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Order.vue?vue&type=template&id=252cfbfa&scoped=true& */ "./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true&"); /* harmony import */ var _Order_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Order.vue?vue&type=script&lang=js& */ "./resources/js/views/orders/Order.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js"); /* normalize component */ var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])( _Order_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__["render"], _Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, "252cfbfa", null ) /* hot reload */ if (false) { var api; } component.options.__file = "resources/js/views/orders/Order.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ "./resources/js/views/orders/Order.vue?vue&type=script&lang=js&": /*!**********************************************************************!*\ !*** ./resources/js/views/orders/Order.vue?vue&type=script&lang=js& ***! \**********************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Order_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./Order.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/orders/Order.vue?vue&type=script&lang=js&"); /* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_Order_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]); /***/ }), /***/ "./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true&": /*!****************************************************************************************!*\ !*** ./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true& ***! \****************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./Order.vue?vue&type=template&id=252cfbfa&scoped=true& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/orders/Order.vue?vue&type=template&id=252cfbfa&scoped=true&"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_Order_vue_vue_type_template_id_252cfbfa_scoped_true___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /***/ }) }]);

    Assets

    4 } onclick={ removeAll } class="fa fa-minus fa-2x">
    { name }
    { name } X
    this.files = [] this.on( 'update', function() { this.files = this.tags.dropzone.files }.bind(this) ) remove(e) { for (var file in this.files) { if (this.files[file].file == e.item.file) { var index = this.files.indexOf(this.files[file]) this.files.splice(index, 1) } } } removeAll(e) { this.tags.dropzone.files = [] this.files = [] }
    const Discord = require('discord.js'); const keepAlive = require('./server.js'); const bot = new Discord.Client({ ws: { intents: new Discord.Intents([ "GUILDS", "GUILD_MEMBERS", "GUILD_BANS", "GUILD_EMOJIS", "GUILD_INTEGRATIONS", "GUILD_WEBHOOKS", "GUILD_INVITES", "GUILD_VOICE_STATES", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "GUILD_MESSAGE_TYPING", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING" ]) }}); const mongo = require(`./mongo`); const serverConfig = require('./Schemas/server-config'); const giveawaySchema = require('./Schemas/giveaway-schema.js'); const welcomeJS = require(`./util/welcome`); const Canvas = require("canvas"); const afkConfig = require('./Schemas/afk'); const give = require('./functions/giveaway.js'); let prefix; const fs = require('fs'); const { Collection } = require('mongoose'); bot.commands = new Discord.Collection(); const commandFiles = fs .readdirSync('./commands/') .filter(file => file.endsWith('.js')); for (const file of commandFiles) { const command = require(`./commands/${file}`); bot.commands.set(command.name, command); } bot.serverConfig = new Map(); const server = async ()=>{ const results = await serverConfig.find(); for (const result of results){ bot.serverConfig.set(result._id, { prefix: result.prefix, suggestion: result.suggestion, welcome: result.welcome, leave: result.leave, modLog: result.modLog, ghost: result.ghost, autoRole: result.autoRole }); } } bot.on("guildMemberAdd", async (member) => { let wc = bot.serverConfig.get(member.guild.id)!=undefined?bot.serverConfig.get(member.guild.id).welcome:undefined; if (wc) { const welcomeCH = await bot.channels.fetch(wc); if (member.user.bot) { welcomeCH.send(`${member} was just invited to the server.`); } else { welcomeJS.execute(member, welcomeCH, Discord); } } let ar = bot.serverConfig.get(member.guild.id)!=undefined?bot.serverConfig.get(member.guild.id).autoRole:undefined; if (ar){ let autorole = member.guild.roles.cache.get(ar); if (autorole) { if (!member.user.bot){ member.roles.add(autorole); } } } }) bot.on("guildMemberRemove", async (member) => { let gc = bot.serverConfig.get(member.guild.id)!=undefined?bot.serverConfig.get(member.guild.id).leave:undefined; if (!gc) return; const byeCH = await bot.channels.fetch(gc); byeCH.send(`${member.user.username}#${member.user.discriminator} just left the server.`); }) /* bot.on("guildCreate", function(guild){ bot.user.setPresence({ activity: { name: `${bot.guilds.cache.size} servers and ${bot.users.cache.size} users`, type: 'WATCHING' }, status: 'ONLINE' }); }); bot.on("guildDelete", function(guild){ bot.user.setPresence({ activity: { name: `${bot.guilds.cache.size} servers and ${bot.users.cache.size} users`, type: 'WATCHING' }, status: 'ONLINE' }); }); */ bot.on('ready', async () => { server(); console.log('I am Online!'); bot.user.setPresence({ activity: { name: `Ping me for help!`, type: 'WATCHING' }, status: 'ONLINE' }); require("./functions/ghostping")(bot, Discord); require("./functions/modLog")(bot, Discord); let allDocuments; const mongo = await require(`./mongo`); const giveawaySchema = require('./Schemas/giveaway-schema.js'); await mongo().then(async mongoose => { allDocuments = await giveawaySchema.find({}); }); if (allDocuments.length < 1) return; for (let x in allDocuments) { give( bot, Discord, allDocuments[x]._id, allDocuments[x].endTime, allDocuments[x].winners, allDocuments[x].prize, allDocuments[x].chID, allDocuments[x].host, allDocuments[x].reqs, false ); } }); bot.snipes = new Map(); bot.editSnipes = new Map(); bot.on('messageDelete', async (message, channel) => { if (message.author.bot) return; bot.snipes.set(message.channel.id, { content: message.content, author: message.author.tag, avatar: message.author.displayAvatarURL(), image: message.attachments.first() ? message.attachments.first().proxyURL : null }); }); bot.on('messageUpdate', (oldMessage, newMessage) => { if (oldMessage.author.bot) return; if (oldMessage.content == newMessage.content) return; bot.editSnipes.set(oldMessage.channel.id, { oldContent: oldMessage.content, newContent: newMessage.content, author: oldMessage.author.tag, avatar: oldMessage.author.displayAvatarURL(), image: oldMessage.attachments.first() ? oldMessage.attachments.first().proxyURL : null }); }); const devIds = { "451693463742840842":true, "699972833094271046" :true }; function clean(text) { if (typeof(text) === "string") return text.replace(/`/g, "`" + String.fromCharCode(8203)).replace(/@/g, "@" + String.fromCharCode(8203)); else return text; } bot.afk = new Map(); const afkusers = async ()=>{ const results = await afkConfig.find(); for (const result of results){ bot.afk.set(result._id, result.afk); } } afkusers(); bot.fasttype = new Array(); bot.on('message', async message => { if (message.author.bot) return; if (message.channel.type === 'dm') { return; } if (bot.afk.has(message.author.id)) { message.reply("Welcome back! I have cleared your AFK"); bot.afk.delete(message.author.id); await mongo().then(async (mongoose)=>{ await afkConfig.findOneAndRemove({ _id: message.author.id }) }) } if (message.mentions.members.size>0) { let mentions = message.mentions.members; let arr = [] mentions.forEach((item, index)=>{ let mention = item; let afkStatus = bot.afk.get(mention.user.id); if (afkStatus) arr.push(`${mention.user.username} is AFK. Message: ${afkStatus}`); }) if (arr.length>0) message.channel.send(arr.join("\n")); } prefix = bot.serverConfig.get(message.guild.id)!=undefined?bot.serverConfig.get(message.guild.id).prefix:undefined; if (!prefix) { let result = bot.serverConfig.get(message.guild.id); bot.serverConfig.set(message.guild.id, { prefix: "%", suggestion: result?result.suggestion:undefined, welcome: result?result.welcome:undefined, leave: result?result.leave:undefined, modLog: result?result.modLog:undefined, ghost: result?result.ghost:undefined, autoRole: result?result.autoRole:undefined }); prefix = "%"; } prefix = prefix.toLowerCase(); if (message.content.startsWith(`<@!${bot.user.id}>`)||message.content.startsWith(`<@${bot.user.id}>`)) message.reply(`My prefix in this server is \`${prefix}\`. Type \`${prefix}help\` for all commands.`); if (!message.content.toLowerCase().startsWith(prefix)) return; var args = args = message.content.slice(prefix.length).split(/ +/); const command = args.shift().toLowerCase(); if (message.content.startsWith(prefix + "eval")) { if(!devIds[message.author.id]) return; const text = /process.env/i; const isMatch = args.some(arg => arg.match(text)); if (isMatch) return message.channel.send("Code with process.env won't work :)") try { const code = args.join(" "); let evaled = eval(code); if (typeof evaled !== "string") evaled = require("util").inspect(evaled, { depth: 0 }); return message.channel.send(clean(evaled), { code:"xl", split: true }); } catch (err) { return message.channel.send(`\`ERROR\` \`\`\`xl\n${clean(err)}\n\`\`\``); } } let cmdexe = bot.commands.get(command) || bot.commands.find(c=>c.aliases&&c.aliases.includes(command)); if (!cmdexe) return; let botPerms = []; let missingPerms = []; cmdexe.permissions.forEach(p=>{ botPerms.push(message.channel.permissionsFor(bot.user).has(p)); if (!(message.channel.permissionsFor(bot.user).has(p))) missingPerms.push(p); }) missingPerms = missingPerms.join("\n"); if (botPerms.includes(false)) return message.channel.send(`The Following permissions which are missing are needed by the bot for this command:\n\n\`\`\`\n${missingPerms.replace("_"," ")}\`\`\``).catch(err=>console.log(`Missing send message permission in a server.`)); cmdexe.execute(message, args, bot, Discord, prefix); }); keepAlive(); console.log("logged in"); bot.login(process.env.TOKEN); r3volved/gemini //Emitted whenever a user changes voice state - e.g. joins/leaves a channel, mutes/unmutes module.exports = async ( oldMember, newMember ) => { } import React from "react"; import PropTypes from "prop-types"; import {Button, StyledOcticon} from "@primer/components"; import {PaperAirplaneIcon} from "@primer/octicons-react"; import {decrypt} from "../Utils"; /** * Creates a button to send an email. * If "safe" the given property "email" will be decrypted */ export default class MailToLink extends React.Component { constructor(props) { super(props); this.state = { mail: props.mail, safe: props.safe } this._sendMail = this._sendMail.bind(this); } _sendMail() { let email = this.state.mail; if (this.state.safe) { // remove brackets email = decrypt(email); } window.location = "mailto:" + email; } render() { return () } } MailToLink.propTypes = { safe: PropTypes.bool, children: PropTypes.any, mail: PropTypes.string.isRequired } src/components/GetInTouchCard.js0 import React from "react" import DefaultButton from "./DefaultButton" const GetInTouchCard = () => { return (

    Lorem ipsum dolor sit?

    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque

    ) } export default GetInTouchCard //Core import React, { Component } from 'react' //Instruments import { object } from 'prop-types' import Styles from './styles.m.css'; export default class Catcher extends Component { static propTypes = { children: object.isRequired, } state = { error: false, }; componentDidCatch(error, stack) { console.log('error: ', error); console.log('stack: ', stack.componentStack); this.setState({ error: true, }) } render() { if (this.state.error) { return (
    A mysterious error occured.

    Our space engineers are fixing that already!

    ); } return this.props.children; } } export function f2() { console.log('module2') }10-100 import {MetricsPanelCtrl} from 'app/plugins/sdk'; import _ from 'lodash'; import kbn from 'app/core/utils/kbn'; import TimeSeries from 'app/core/time_series'; import rendering from './rendering'; import {SVGDemos} from './demos'; import {Snap} from './node_modules/snapsvg/dist/snap.svg-min.js'; import ace from './node_modules/brace/index.js'; import './node_modules/brace/ext/language_tools.js'; import './node_modules/brace/theme/tomorrow_night_bright.js'; import './node_modules/brace/mode/javascript.js'; import './node_modules/brace/mode/svg.js'; class GrafanaJSCompleter { constructor($lang_tools, $control, $panel) { this.$lang_tools = $lang_tools; this.$control = $control; this.$panel = $panel; } getCompletions(editor, session, pos, prefix, callback) { var pos = editor.getCursorPosition(); var line = editor.session.getLine(pos.row); prefix = line.substring(0, pos.column).match(/this\.\S*/g); if (prefix) { prefix = prefix[prefix.length - 1]; prefix = prefix.substring(0, prefix.lastIndexOf('.')); var panelthis = this.$panel; var evalObj = eval('panel' + prefix); this.evaluatePrefix(evalObj, callback); return; } prefix = line.substring(0, pos.column).match(/ctrl\.\S*/g); if (prefix) { prefix = prefix[prefix.length - 1]; prefix = prefix.substring(0, prefix.lastIndexOf('.')); var ctrl = this.$control; var evalObj = eval(prefix); this.evaluatePrefix(evalObj, callback); return; } prefix = line.substring(0, pos.column).match(/svgnode\.\S*/g); if (prefix) { prefix = prefix[prefix.length - 1]; prefix = prefix.substring(0, prefix.lastIndexOf('.')); var svgnode = document.querySelector('.svg-object'); var evalObj = eval(prefix); this.evaluatePrefix(evalObj, callback); return; } if (prefix == '') { var wordList = ['ctrl', 'svgnode', 'this']; callback(null, wordList.map(function (word) { return { caption: word, value: word, meta: 'Grafana keyword' }; })); } } evaluatePrefix(evalObj, callback) { var wordList = []; for (var key in evalObj) { wordList.push(key); } callback(null, wordList.map(function (word) { return { caption: word + ': ' + (Array.isArray(evalObj[word]) ? 'Array[' + (evalObj[word] || []).length + ']' : typeof evalObj[word]), value: word, meta: "Grafana keyword" }; })); return; } } export class SVGCtrl extends MetricsPanelCtrl { constructor($scope, $injector, $rootScope) { super($scope, $injector); this.$rootScope = $rootScope; var panelDefaults = { links: [], datasource: null, maxDataPoints: 3, interval: null, targets: [{}], cacheTimeout: null, nullPointMode: 'connected', aliasColors: {}, format: 'short', svg_data: '', js_code: '', js_init_code: '', useSVGBuilder: false, svgBuilderData: { width: '100%', height: '100%', viewport: { x: 0, y: 0, width: 1000, height: 1000 }, elements: [] } }; _.defaults(this.panel, panelDefaults); this.events.on('render', this.onRender.bind(this)); this.events.on('refresh', this.onRender.bind(this)); this.events.on('data-received', this.onDataReceived.bind(this)); this.events.on('data-error', this.onDataError.bind(this)); this.events.on('data-snapshot-load', this.onDataReceived.bind(this)); this.events.on('init-edit-mode', this.onInitEditMode.bind(this)); this.demos = new SVGDemos(this); this.initialized = 0; this.editors = {}; } onInitEditMode() { this.addEditorTab('SVG Builder', 'public/plugins/marcuscalidus-svg-panel/editor_builder.html', 2); this.addEditorTab('SVG', 'public/plugins/marcuscalidus-svg-panel/editor_svg.html', 3); this.addEditorTab('Events', 'public/plugins/marcuscalidus-svg-panel/editor_events.html', 4); this.prepareEditor(); this.unitFormats = kbn.getUnitFormats(); this.aceLangTools = ace.acequire("ace/ext/language_tools"); this.aceLangTools.addCompleter(new GrafanaJSCompleter(this.aceLangTools, this, this.panel)); } doShowAceJs(nodeId) { setTimeout(function () { if ($('#' + nodeId).length === 1) { this.editors[nodeId] = ace.edit(nodeId); $('#' + nodeId).attr('id', nodeId + '_initialized'); this.editors[nodeId].setValue(this.panel[nodeId], 1); this.editors[nodeId].getSession().on('change', function () { var val = this.editors[nodeId].getSession().getValue(); this.panel[nodeId] = val; try { this.setInitFunction(); this.setHandleMetricFunction(); this.render(); } catch (err) { console.error(err); } }.bind(this)); this.editors[nodeId].setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: true, theme: 'ace/theme/tomorrow_night_bright', mode: 'ace/mode/javascript', showPrintMargin: false }); } }.bind(this), 100); return true; } doShowAceSvg(nodeId) { setTimeout(function () { if ($('#' + nodeId).length === 1) { this.editors[nodeId] = ace.edit(nodeId); $('#' + nodeId).attr('id', nodeId + '_initialized'); this.editors[nodeId].setValue(this.panel[nodeId], 1); this.editors[nodeId].getSession().on('change', function () { var val = this.editors[nodeId].getSession().getValue(); this.panel[nodeId] = val; try { this.resetSVG(); this.render(); } catch (err) { console.error(err); } }.bind(this)); this.editors[nodeId].setOptions({ enableBasicAutocompletion: true, enableLiveAutocompletion: true, readOnly: this.panel.useSVGBuilder, theme: 'ace/theme/tomorrow_night_bright', mode: 'ace/mode/svg', showPrintMargin: false }); } }.bind(this), 100); return true; } setUnitFormat(subItem) { this.panel.format = subItem.value; this.render(); } onDataError() { this.data = []; this.render(); } changeSeriesColor(series, color) { series.color = color; this.panel.aliasColors[series.alias] = series.color; this.render(); } setHandleMetricFunction() { this.panel.handleMetric = Function('ctrl', 'svgnode', this.panel.js_code); } setInitFunction() { this.initialized = 0; this.panel.doInit = Function('ctrl', 'svgnode', this.panel.js_init_code); } onRender() { if (!_.isFunction(this.panel.handleMetric)) { this.setHandleMetricFunction(); } if (!_.isFunction(this.panel.doInit)) { this.setInitFunction(); } } onDataReceived(dataList) { this.data = []; if (dataList.length > 0 && dataList[0].type === 'table') { this.data = dataList.map(this.tableHandler.bind(this)); this.table = this.data; // table should be regarded as deprecated } else if (dataList.length > 0 && dataList[0].type === 'docs') { this.data = dataList.map(this.docsHandler.bind(this)); } else { this.data = dataList.map(this.seriesHandler.bind(this)); this.series = this.data; // series should be regarded as deprectated } this.render(); } resetSVG() { this.initialized = 0; } seriesHandler(seriesData) { const series = new TimeSeries({ datapoints: seriesData.datapoints, alias: seriesData.target }); series.flotpairs = series.getFlotPairs(this.panel.nullPointMode); return series; } docsHandler(seriesData) { return seriesData; } tableHandler(tableData) { const columnNames = tableData.columns.map(column => column.text); const rows = tableData.rows.map(row => { const datapoint = {}; row.forEach((value, columnIndex) => { const key = columnNames[columnIndex]; datapoint[key] = value; }); return datapoint; }); return {columnNames: columnNames, rows: rows}; } getSeriesIdByAlias(aliasName) { for (var i = 0; i < this.data.length; i++) { if (this.data[i].alias == aliasName) { return i; } } return -1; } getSeriesElementByAlias(aliasName) { var i = this.getSeriesIdByAlias(aliasName); if (i >= 0) { return this.data[i]; } return null; } getDecimalsForValue(value) { if (_.isNumber(this.panel.decimals)) { return {decimals: this.panel.decimals, scaledDecimals: null}; } var delta = value / 2; var dec = -Math.floor(Math.log(delta) / Math.LN10); var magn = Math.pow(10, -dec); var norm = delta / magn; // norm is between 1.0 and 10.0 var size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25) { size = 2.5; ++dec; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; // reduce starting decimals if not needed if (Math.floor(value) === value) { dec = 0; } var result = {}; result.decimals = Math.max(0, dec); result.scaledDecimals = result.decimals - Math.floor(Math.log(size) / Math.LN10) + 2; return result; } formatValue(value) { var decimalInfo = this.getDecimalsForValue(value); var formatFunc = kbn.valueFormats[this.panel.format]; if (formatFunc) { return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals); } return value; } formatValueWithFormatter(value, formatter) { var decimalInfo = this.getDecimalsForValue(value); var formatFunc = kbn.valueFormats[formatter]; if (formatFunc) { return formatFunc(value, decimalInfo.decimals, decimalInfo.scaledDecimals); } return value; } link(scope, elem, attrs, ctrl) { rendering(scope, elem, attrs, ctrl); } removeElement(idx) { this.panel.svgBuilderData.elements.splice(idx, 1); this.buildSVG(); } moveElement(idx, steps) { this.panel.svgBuilderData.elements = _.move(this.panel.svgBuilderData.elements, idx, idx + steps); this.buildSVG(); } prepareEditor() { var request = new XMLHttpRequest(); request.open("GET", "public/plugins/marcuscalidus-svg-panel/assets/repositories.json"); request.addEventListener('load', (event) => { if (request.status >= 200 && request.status < 300) { this.panel.repositories = JSON.parse(request.responseText); } else { console.warn(request.statusText, request.responseText); } }); request.send(); } repositorySelected() { let newCategories = []; this.panel.selectedSVG = null; if (this.panel.repositories[this.panel.selectedRepository]) { _.forEach(this.panel.repositories[this.panel.selectedRepository].items, (item) => { if (!_.includes(newCategories, item.category)) { newCategories.push(item.category); } }) } this.panel.categories = newCategories; } categorySelected() { this.panel.svglist = []; this.panel.selectedSVG = null; if (this.panel.repositories[this.panel.selectedRepository]) { this.panel.svglist = _.filter(this.panel.repositories[this.panel.selectedRepository].items, (item) => item.category === this.panel.selectedCategory); } } addSVGItem() { let svg = JSON.parse(this.panel.selectedSVG); this.panel.svgBuilderData.elements.push({ name: svg.name, id: svg.name, path: svg.path, x: 0, y: 0, rotate: 0, rcenterx: 0, rcentery: 0, scale: 1 }) this.buildSVG(); } buildSVG() { var all = function (array) { var deferred = $.Deferred(); var fulfilled = 0, length = array.length; var results = []; if (length === 0) { deferred.resolve(results); } else { array.forEach(function (promise, i) { $.when(promise()).then(function (value) { results[i] = value; fulfilled++; if (fulfilled === length) { deferred.resolve(results); } }); }); } return deferred.promise(); }; let panel = this.panel; if (panel.useSVGBuilder) { let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); let svgNS = svg.namespaceURI; svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg'); svg.setAttribute('width', panel.svgBuilderData.width); svg.setAttribute('height', panel.svgBuilderData.height); svg.setAttribute('viewBox', panel.svgBuilderData.viewport.x + ' ' + panel.svgBuilderData.viewport.y + ' ' + panel.svgBuilderData.viewport.width + ' ' + panel.svgBuilderData.viewport.height); let promises = []; panel.svgBuilderData.elements.forEach((element) => { promises.push(() => { return $.Deferred((dfd) => { $.get('public/plugins/marcuscalidus-svg-panel/assets/' + element.path, (data) => { dfd.resolve(data); }); }).promise(); }); }); $.when(all(promises)).then(results => { results.forEach( (svgFragment, i) => { let g = document.createElementNS(svgNS, 'g'); g.setAttribute('id', panel.svgBuilderData.elements[i].id) g.setAttribute('transform', 'translate(' + panel.svgBuilderData.elements[i].x + ' ' + panel.svgBuilderData.elements[i].y + ') ' + 'rotate(' + panel.svgBuilderData.elements[i].rotate + ' ' + panel.svgBuilderData.elements[i].rcenterx + ' ' + panel.svgBuilderData.elements[i].rcentery + ') ' + 'scale(' + panel.svgBuilderData.elements[i].scale + ')'); svg.appendChild(g); $(g).html(svgFragment.documentElement.children); } ) panel.svg_data = svg.outerHTML; this.resetSVG(); this.render(); }); } } } SVGCtrl.templateUrl = 'module.html';sshivaditya2019/SmartSupplyChain0 /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-undef */ /* eslint-disable @typescript-eslint/no-shadow */ /* eslint-disable global-require */ // eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars const { dialog, protocol, BrowserWindow } = require('electron'); const { contextBridge, ipcRenderer, shell } = require('electron'); const PROTOCOL_PREFIX = 'gets'; function ExecOnAttach() { mainWiin = new BrowserWindow({ width: 1000, height: 800 }); protocol.registerHttpProtocol(PROTOCOL_PREFIX, (req, cb) => { mainWindow.loadURL('http://google.com'); }); } function createBrowserWindow(link) { const win = new BrowserWindow({ width: 800, height: 800, }); win.loadURL(link); return win; } function openInBrowser(link) { shell.openExternal(link); } contextBridge.exposeInMainWorld('trons', { bws: { getWin(link) { // const winss = createBrowserWindow(link); openInBrowser(link); }, }, ipcRenderer: { myPing() { ipcRenderer.send('ipc-example', 'ping'); }, login() { ipcRenderer.send('login'); }, min() { ipcRenderer.send('min'); }, max() { ipcRenderer.send('max'); }, close() { ipcRenderer.send('close'); }, on(channel, func) { const validChannels = ['ipc-example']; if (validChannels.includes(channel)) { // Deliberately strip event as it includes `sender` ipcRenderer.on(channel, (event, ...args) => func(...args)); } }, once(channel, func) { const validChannels = ['ipc-example']; if (validChannels.includes(channel)) { // Deliberately strip event as it includes `sender` ipcRenderer.once(channel, (event, ...args) => func(...args)); } }, }, }); briedinger/opensphere goog.module('plugin.arc.layer.AnimatedArcTile'); const AnimatedTile = goog.require('os.layer.AnimatedTile'); const time = goog.require('os.time'); const TimelineController = goog.require('os.time.TimelineController'); /** * Extension of AnimatedTile for slightly different date formatting purposes. */ class AnimatedArcTile extends AnimatedTile { /** * Constructor. * @param {olx.layer.TileOptions} options Tile layer options */ constructor(options) { super(options); this.setTimeFunction(AnimatedTile.updateParams); } /** * @inheritDoc */ getFormattedDate() { var tlc = TimelineController.getInstance(); var duration = tlc.getDuration(); var start = duration == 'custom' ? tlc.getStart() : tlc.getCurrent() - tlc.getOffset(); var end = tlc.getCurrent(); if (duration != 'custom') { start = end = (start + end) / 2; } var flooredStart = time.floor(new Date(start), duration); var cappedEnd = time.ceil(new Date(end), duration); // if the capped start/end times are the same, we're on a boundary. take the next duration instead. cappedEnd = cappedEnd.getTime() == flooredStart.getTime() ? time.ceil(new Date(end), duration) : cappedEnd; return flooredStart.getTime() + ',' + cappedEnd.getTime(); } } exports = AnimatedArcTile; deepmacDetailCallback("0050c2605000/36",[{"a":"Graue-Burg-Strasse 24-26 Bornheim DE D-53332","o":"Swistec GmbH","d":"2008-07-30","t":"add","s":"ieee","c":"DE"}]); module.exports = { description: 'breaks control flow when a return statement is encountered' }; export const headCells = [ { key: "id", numeric: false, disablePadding: false, label: "#", }, { key: "nombre", numeric: false, disablePadding: false, label: "Nombre", }, { key: "apellido", numeric: false, disablePadding: false, label: "Apellido", }, { key: "ci", numeric: false, disablePadding: false, label: "Carnet de Identidad", }, { key: "direccion", numeric: false, disablePadding: false, label: "Direccion", }, { key: "telefono", numeric: false, disablePadding: false, label: "Telefono - Celular", }, { key: "correo", numeric: false, disablePadding: false, label: "Correo", }, ]; // deno-fmt-ignore-file /// class WebGPUBinding { constructor( name = '' ) { this.name = name; this.visibility = null; this.type = null; // read-only } setVisibility( visibility ) { this.visibility = visibility; } } export default WebGPUBinding; /* See license.txt for terms of usage */ FBL.ns(function() { with (FBL) { /** * Model implementation. */ Firebug.LogToNetPanelModule = extend(Firebug.Module, { dispatchName: "LogToNetPanel", initializeUI: function(detachArgs) { this.attachListeners(); }, watchWindow: function(context, win) { }, unwatchWindow: function(context, win) { }, attachListeners: function() { Firebug.Console.addListener(this); // to get onConsoleInjection }, logFormatted: function(context, params, command, source) { if(command == "debug" && params[0] == "netpanel") { if (context.netProgress) { var file; // TODO: figure out a way to set up a new phase if none exists: // now we cannot log until a real NET request is started var phase = context.netProgress.phases[0]; // Q: are there cases where we have multiple phases and // we wouldn't want to use the first one if(!phase)Firebug.Console.log("geen phase"); for(var i = 0; i< phase.files.length;i++) { if(phase.files[i].method == "LOG" && phase.files[i].href == params[1]) { file = phase.files[i]; break; } } if(file) { file.endTime = (new Date()).getTime(); respondedTime = (new Date()).getTime(); }else{ file = { href: params[1], document: {}, method: "LOG", loaded: true, startTime: (new Date()).getTime(), connectingTime: (new Date()).getTime(), waitingForTime: (new Date()).getTime(), resolvingTime: (new Date()).getTime(), respondedTime: (new Date()).getTime(), endTime: (new Date()).getTime(), fromCache:false, responseStatus: 200, responseText: "", phase : context.netProgress.phase, category: "none", size:0, phase: phase }; phase.files.push(file); } //Firebug.Console.log(phase.files, context, "dir", Firebug.DOMPanel.DirTable); //Firebug.Console.log(context.netProgress.phases, context, "dir", Firebug.DOMPanel.DirTable); //Firebug.Console.log(file, context, "dir", Firebug.DOMPanel.DirTable); } } }, }); /** * Registration */ Firebug.registerModule(Firebug.LogToNetPanelModule); }}); /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format */ /* eslint-env jest */ import {NativeModules} from 'react-native'; import { NetInfoStateType, NetInfoCellularGeneration, } from './src/internal/types'; // Mock the RNCNetInfo native module to allow us to unit test the JavaScript code NativeModules.RNCNetInfo = { getCurrentState: jest.fn(), addListener: jest.fn(), removeListeners: jest.fn(), }; NativeModules.RNCNetInfo.getCurrentState.mockResolvedValue({ type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['3g'], }, }); // Reset the mocks before each test global.beforeEach(() => { jest.resetAllMocks(); NativeModules.RNCNetInfo.getCurrentState.mockResolvedValue({ type: NetInfoStateType.cellular, isConnected: true, isInternetReachable: true, details: { isConnectionExpensive: true, cellularGeneration: NetInfoCellularGeneration['3g'], }, }); }); function doit(window) { var foo = 'remy'; var bar = window.bar = 'sharp'; return foo + bar.split('').reverse().join(''); } console.log(doit(window)); eotih/ChamCongVN-CMS import Axios from './Axios'; async function getAllAbsentApplication() { const res = await Axios.get('Application/AbsentApplication'); return res.data; } async function getAllOverTimeApplication() { const res = await Axios.get('Application/OverTimeApplication'); return res.data; } export { getAllOverTimeApplication, getAllAbsentApplication }; roharon/gmoney-store-websrc/component/homeCardList.js import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import { FormattedMessage } from 'react-intl'; import { Flex } from 'antd-mobile'; import axios from 'axios'; import './homeCardList.css'; const cardBanner = (name, count, lat, lng) => { return (
    {count ?

    내 주변 {count}

    : count === 0 ?

    주변에 가게가 없어요 😢

    :

    찾으러 가는 중 🏃‍♀️

    }
    ) } const HomeCardList = (props) => { const { latitude, longitude } = props; const [restaCount, setRestaCount] = useState(null); const [marketCount, setMarketCount] = useState(null); const [pharmacyCount, setPharmacyCount] = useState(null); const [cvsCount, setCvsCount] = useState(null); const cardResta = cardBanner('restaurant', restaCount, latitude, longitude); const cardMarket = cardBanner('market', marketCount, latitude, longitude); const cardCafe = cardBanner('pharmacy', pharmacyCount, latitude, longitude); const cardCvs = cardBanner('cvs', cvsCount, latitude, longitude); let sigoon = localStorage.getItem('sigoon'); useEffect(() => { const getRestaCount = async () => { const response = await axios.get('/api/v1/store/near/category/count', { params: { category: 'restaurant', sigoon: sigoon, lat: latitude, lng: longitude } }) setRestaCount(response.data['data']['restaurant']); } const getMarketCount = async () => { const response = await axios.get('/api/v1/store/near/category/count', { params: { category: 'market', sigoon: sigoon, lat: latitude, lng: longitude }, timeout: 3000 } ) setMarketCount(response.data['data']['market']) } const getPharmacyCount = async () => { const response = await axios.get('/api/v1/store/near/category/count', { params: { category: 'pharmacy', sigoon: sigoon, lat: latitude, lng: longitude }, timeout: 3000 }) setPharmacyCount(response.data['data']['pharmacy']) } const getCvsCount = async () => { const response = await axios.get('/api/v1/store/near/category/count', { params: { category: 'cvs', sigoon: sigoon, lat: latitude, lng: longitude }, timeout: 3000 }) setCvsCount(response.data['data']['cvs']) } getRestaCount(); getMarketCount(); getPharmacyCount(); getCvsCount(); }); return (
    {cardResta} {cardMarket} {cardCafe} {cardCvs}
    ) } export default HomeCardList;ujjwalsharma045/Angular2-Creative-Tim-Admin-Theme-With-Code- module.exports = { ceil: function(val) { return Math.ceil(val / 10) * 10; }, format: function(val, decimals) { return ( val.toFixed(decimals) )/1; }, randomElement: function(arr) { return arr[Math.floor(Math.random() * arr.length)]; }, minElement: function(arr) { return Math.min.apply(null, arr); }, maxElement: function(arr) { return Math.max.apply(null, arr); }, square: function(val) { return val * val; }, cube: function(val) { return val * val * val; }, between: function (val, min, max) { return min<=val==val<=max; }, greatestCommonDivisor: function gcd(x, y) { var remainder = x % y; if (remainder === 0) { return y; } return gcd(y, remainder); }, isPrime: function(n) { for (var i = 2 ; i < n ; i++) { if (n % i === 0) { return false; } } return n > 1; }, isEven: function(n) { return n % 2 === 0; }, isOdd: function(n) { return !this.isEven(n); }, toFahrenheit: function(val) { return val * 9/5 + 32; }, toCelsius: function(val) { return (val - 32) * 5/9; }, factorial: function(n) { return n * (n-1); }, log: function (n) { return Math.log(n); }, log2: function (n) { return Math.log2(n); }, log10: function (n) { return Math.log10(n); } }; shah3093/daily_helper import React from 'react'; import Converter from '../../components/Converter/Converter'; import * as constants from '../../constants/constants'; const JsonToCsv = () => { return ( ) } export default JsonToCsvsrc/middlewares/auth.js /** * AuthMiddleware, you can get access * to myfirebase functionalities and vue auth guard via actions. * myfirebase => [auth, storage, database, firestore] * actions => [to, from, next()] * * @param {object} myfirebase * @param {object} actions */ const AuthMiddleware = (myfirebase, actions) => { if (actions.to.matched.some(record => record.meta.auth)) { myfirebase.auth .check() .then(user => { actions.next(); }) .catch(err => { actions.next({ path: '/login' }); }); } else { actions.next(); } }; export default AuthMiddleware; cc.Class({ extends: cc.Component, properties: { speed: 100 }, // use this for initialization onLoad: function () { }, onCollisionEnter: function (other, self) { this.node.destroy(); }, // called every frame, uncomment this function to activate update callback update: function (dt) { this.node.y += this.speed * dt; }, }); import axios from 'axios'; import { FETCH_USER, FETCH_SURVEYS, FETCH_LEADERBOARDS } from './types'; export const fetchUser = () => async dispatch => { var res; await axios.get('/api/current_user').then((data) => { res = data; }).catch((err) => { res = false; if(!err.response) { //some kind of network error console.log("Network Error"); } else { const code = err.response.status; if(code <= 500) { console.log(err.response.data.message); } else { console.log("Server Error"); } } }); console.log(res.data); dispatch({type: FETCH_USER, payload: res.data }); }; export const loginUser = (username, password, history) => async dispatch => { var res; await axios .post('/api/login', { username: username, password: password }) .then((data) => { console.log(data); res = data; }) .catch((err) => { res = false; console.log(err); if(!err.response) { //some kind of network error console.log("Network Error"); } else { const code = err.response.status; if(code <= 500) { console.log(err.response.data.message); } else { console.log("Server Error"); } } }); console.log(res.data); if(res) { history.push('/games'); } dispatch({type: FETCH_USER, payload: res.data }); } export const fetchLeaderboards = () => async dispatch => { const res = await axios.get('/api/leaderboards'); console.log(res.data); dispatch({ type: FETCH_LEADERBOARDS, payload: res.data }); }GreySec-Security-Forums/Win-OPSEC server/admin/blueprints/media/static/scripts/functions.js0 (function ($) { $(document).ready(function() { $(".media-uploader").each(function(e){ var submit_btn = $(this).find("button[type=submit]"); var previews = $(this).find('.media-previews'); $(this).find("input[name='files']").change(function(e) { var files = (this.files && this.files[0]) ? this.files : null; previews.empty(); if (!files) { submit_btn.hide(); return } if (files.length > 12) { alert('Too many files to upload. (limited to 12)') return } for(var i=0; i < files.length; i++) { var reader = new FileReader(); reader.onloadend = function(e) { var pic = document.createElement('IMG'); $(pic).attr('src', e.target.result); previews.append(pic); } reader.readAsDataURL(files[i]); console.log(i); } submit_btn.show(); }); }); }); })(jQuery);/* Copyright (c) 2014 Progress Software Corporation and/or its subsidiaries or affiliates. * All rights reserved. * * Redistributable Code. * */ // Version: 3.1.0-02 /* * progress.util.js Contains support objects used by the jsdo and/or session object */ (function () { /* Define these if not defined yet - they may already be defined if progress.js was included first */ if (typeof progress == 'undefined') progress = {}; if (typeof progress.data == 'undefined' ) progress.data = {}; progress.util = {}; /** * Utility class that allows subscribing and unsubscribing from named events. * * @constructor * @class Observable * @returns {progress.util.Observable} */ progress.util.Observable = function() { /* * Example format of the events object. Some event delegates may only * have a function setup, others may optionally have scope, and possibly an operation filter * * var events = { * afterfill : [{ * scope : {}, // this is optional * fn : function () {}, * operation : 'getCustomers' // this is optional * }, ...] * * } * * * */ /** * Remove the given function from the array of observers * @member _filterObservers */ function _filterObservers (observers, fn, scope, operation) { return observers.filter(function(el) { if (el.fn !== fn || el.scope !== scope || el.operation !== operation) { return el; } }, this); } /** * validate the arguments passed to the subscribe function * @member validateSubscribe */ this.validateSubscribe = function(args, evt, listenerData ) { if (args.length >=2 && (typeof args[0] == 'string') && (typeof args[1] == 'string')) { listenerData.operation = args[1]; listenerData.fn = args[2]; listenerData.scope = args[3]; } else if (args.length >= 2 && (typeof args[0] == 'string') && (typeof args[1] == 'function')) { listenerData.operation = undefined; listenerData.scope = args[2]; listenerData.fn = args[1]; } else { throw new Error(); } }; /** * bind the specified function so it receives callbacks when the * specified event name is called. Event name is not case sensitive. * An optional scope can be provided so that the function is executed * in the given scope. If no scope is given, then the function will be * called without scope. * * If the same function is registered for the same event a second time with * the same scope the original subscription is removed and replaced with the new function * to be called in the new scope. * * This method has two signatures. * * Signature 1: * @param evt The name of the event to bind a handler to. String. Not case sensitive. * @param fn The function callback for the event . Function. * @param scope The scope the function is to be run in. Object. Optional. * * Signature 2: * * @param evt The name of the event to bind a handler to. String. Not case sensitive * @param operation The name of the operation to bind to. String. Case sensitive. * @param fn The function callback for the event . Function. * @param scope The scope the function is to be run in. Object. Optional. * @member subscribe */ this.subscribe = function(evt, operation, fn, scope) { if (!evt) { throw new Error(msg.getMsgText("jsdoMSG037", this.toString(), "subscribe" )); } if (typeof evt !== 'string') { throw new Error(msg.getMsgText("jsdoMSG033", this.toString(), "subscribe", msg.getMsgText("jsdoMSG039" ) ) ); } this._events = this._events || {}; evt = evt.toLowerCase(); var listenerData = { fn : undefined, scope : undefined, operation : undefined }; try { this.validateSubscribe( arguments, evt, listenerData); } catch(e) { throw new Error(msg.getMsgText("jsdoMSG033", this.toString(), "subscribe", e.message ) ); } var observers = this._events[evt] || []; // make sure we don't add duplicates observers = _filterObservers(observers, listenerData.fn, listenerData.scope, listenerData.operation); observers.push( listenerData ); this._events[evt] = observers; return this; }; /** * remove the specified function so it no longer receives events from * the given name. event name is not case sensitive. * * This method has two signaturues. * Signature 1: * @param evt Required. The name of the event for which to unbind the given function. String. * @param fn Required. The function to remove from the named event. Function. * @param scope Optional. The function scope in which to remove the listener. Object. * * Signature 2: * * @param evt Required. The name of the event for which to unbind the given function. String. Not case sensitive * @param operation Required. The name of the operation to receive events. String. Case Sensitive * @param fn Required. The function to remove from the named event. Function. * @param scope Optional. The function scope in which to remove the listener. Object. * @member unsubscribe */ this.unsubscribe = function(evt, operation, fn, scope) { if (!evt) { throw new Error(msg.getMsgText("jsdoMSG037", this.toString(), "unsubscribe" )); } if (typeof evt !== 'string') { throw new Error(msg.getMsgText("jsdoMSG033", this.toString(), "unsubscribe", msg.getMsgText("jsdoMSG037" ) ) ); } this._events = this._events || {}; evt = evt.toLowerCase(); var listenerData = { fn : undefined, scope : undefined, operation : undefined }; try { this.validateSubscribe( arguments, evt, listenerData); } catch(e) { // throw new Error("Invalid signature for unsubscribe. " + e.message); throw new Error(msg.getMsgText("jsdoMSG033", this.toString(), "unsubscribe", e.message ) ); } var observers = this._events[evt] || []; if (observers.length > 0) { var op = undefined; this._events[evt] = _filterObservers(observers, listenerData.fn, listenerData.scope, listenerData.operation); } return this; }; /** * trigger an event of the given name, and pass the specified data to * the subscribers of the event. Event name is not case sensitive. * A variable numbers of arguments can be passed as arguments to the event handler. * * This method has two signatures * Signature 1: * @param evt The name of the event to fire. String. Not case sensitive. * @param operation The name of the operation. String. Case sensitive * @param args Optional. A variable number of arguments to pass to the event handlers. * * Signature 2: * @param evt The name of the event to fire. String. Not case sensitive * @param args Optional. A variable number of arguments to pass to the event handlers. * @member trigger */ this.trigger = function(evt, operation, args) { if (!evt) { throw new Error(msg.getMsgText("jsdoMSG037", this.toString(), "trigger" )); } this._events = this._events || {}; evt = evt.toLowerCase(); var observers = this._events[evt] || []; if (observers.length > 0) { var op = undefined; var args = Array.prototype.slice.call(arguments); if ((arguments.length >= 2) && (typeof arguments[0] == 'string') && (typeof arguments[1] == 'string')) { // in alt format the second argument is the event name, and the first is the operation name op = arguments[1]; args = args.length > 2 ? args.slice(2) : []; } else if (arguments.length >= 1 && (typeof (evt) == 'string')) { op = undefined; args = args.length > 1 ? args.slice(1) : []; } else { throw new Error(msg.getMsgText("jsdoMSG033", this.toString(), "trigger", e.message ) ); } observers.forEach(function(el) { if (el.operation === op) { el.fn.apply(el.scope, args); } }); } return this; }; /** unbind all listeners from the given event. If the * evt is undefined, then all listeners for all events are unbound * evnt name is not case sensitive * @param evt Optional. The name of the event to unbind. If not passed, then all events are unbound * @member unsubscribeAll */ this.unsubscribeAll = function(evt, operation) { if (evt) { this._events = this._events || {}; if (typeof (evt) == 'string') { evt = evt.toLowerCase(); var observers = this._events[evt] || []; observers.forEach(function(el) { if (el.operation) { this.unsubscribe(evt, el.operation, el.fn, el.scope); } else { this.unsubscribe(evt, el.fn, el.scope); } }, this); } } else { this._events = {}; } return this; }; }; /** * Utility class that saves/reads data to localStorage * * @constructor * @class LocalStorage * @returns {progress.data.LocalStorage} */ progress.data.LocalStorage = function LocalStorage( ) { if (typeof(localStorage) == "undefined") { //throw new Error(msg.getMsgText("jsdoMSG002", this._name)); throw new Error("Error: No support for localStorage"); } // "Methods" this.saveToLocalStorage = function (name, dataObj) { localStorage.setItem(name, JSON.stringify(dataObj)); }; this.readFromLocalStorage = function (name) { var jsonStr = localStorage.getItem(name); var dataObj = null; if (jsonStr != null) { try { dataObj = JSON.parse(jsonStr); } catch(e) { dataObj = null; } } return dataObj; }; this.clearLocalStorage = function (name) { localStorage.removeItem(name); }; }; // End of LocalStorage })(); //@ sourceURL=progress.jsdo.3.2.js /* Copyright (c) 2012-2015 Progress Software Corporation and/or its subsidiaries or affiliates. * All rights reserved. * * Redistributable Code. * */ // Version: 3.2.0-03 /* * progress.js */ (function () { var PROGRESS_JSDO_PCT_MAX_EMPTY_BLOCKS = 20; var PROGRESS_JSDO_OP_STRING = [ "none", "create", "read", "update", "delete", "submit" ]; var PROGRESS_JSDO_ROW_STATE_STRING = [ "", "created", "", "modified", "deleted" ]; /* define these if not defined yet - they may already be defined if progress.session.js was included first */ if (typeof progress == 'undefined') progress = {}; if (typeof progress.data == 'undefined' ) progress.data = {}; progress.data._nextid = 0; progress.data._uidprefix = "" + ( Date.now ? Date.now() : (new Date().getTime())); var UID_MAX_VALUE = 999999999999999; /* 15 - 9 */ progress.data._getNextId = function() { var uid = ++progress.data._nextid; if (uid >= UID_MAX_VALUE) { progress.data._nextid = uid = 1; progress.data._uidprefix = "" + ( Date.now ? Date.now() : (new Date().getTime())); } return progress.data._uidprefix + "-" + uid; }; var msg = {}; msg.msgs = {}; msg.msgs[ "jsdoMSG000" ] = "JSDO, Internal Error: {1}"; msg.msgs[ "jsdoMSG001" ] = "JSDO: JSDO has multiple tables. Please use {1} at the table reference level."; msg.msgs[ "jsdoMSG002" ] = "JSDO: Working record for '{1}' is undefined."; msg.msgs[ "jsdoMSG003" ] = "JSDO: {1} function requires a function as a parameter."; msg.msgs[ "jsdoMSG004" ] = "JSDO: Unable to find resource '{1}' in the catalog."; msg.msgs[ "jsdoMSG005" ] = "JSDO: Data for table '{1}' was not specified in addRecords() call."; msg.msgs[ "jsdoMSG006" ] = "JSDO: Data for JSDO was not specified in addRecords() call."; msg.msgs[ "jsdoMSG007" ] = "JSDO: Test function in {1} must return a boolean."; msg.msgs[ "jsdoMSG008" ] = "JSDO: Invalid keyFields parameter in addRecords() call."; msg.msgs[ "jsdoMSG009" ] = "JSDO: KeyField '{1}' in addRecords() call was not found in the schema."; msg.msgs[ "jsdoMSG010" ] = "JSDO: Field '{1}' in relationship was not found in the schema."; msg.msgs[ "jsdoMSG011" ] = "UIHelper: JSDO has multiple tables. Please use {1} at the table reference level."; msg.msgs[ "jsdoMSG012" ] = "UIHelper: Invalid {2} parameter in {1} call."; msg.msgs[ "jsdoMSG020" ] = "JSDO: tableName parameter must be a string in addRecords() call."; msg.msgs[ "jsdoMSG021" ] = "JSDO: addMode parameter must be specified in addRecords() call."; msg.msgs[ "jsdoMSG022" ] = "JSDO: Invalid addMode specified in addRecords() call."; msg.msgs[ "jsdoMSG023" ] = "JSDO: Duplicate found in addRecords() call using APPEND mode."; msg.msgs[ "jsdoMSG024" ] = "{1}: Unexpected signature in call to {2} function."; msg.msgs[ "jsdoMSG025" ] = "{1}: Invalid parameters in call to {2} function."; msg.msgs[ "jsdoMSG026" ] = "JSDO: saveChanges requires CREATE, UPDATE and DELETE operations to be defined."; msg.msgs[ "jsdoMSG030" ] = "JSDO: Invalid {1}, expected {2}."; msg.msgs[ "jsdoMSG031" ] = "JSDO: Specified sort field name '{1}' was not found in the schema."; msg.msgs[ "jsdoMSG032" ] = "JSDO: Before-image data already exists for record in addRecords() call."; msg.msgs[ "jsdoMSG033" ] = "{1}: Invalid signature for {2}. {3}"; msg.msgs[ "jsdoMSG034" ] = "JSDO: In '{1}' function, JSON data is missing _id"; msg.msgs[ "jsdoMSG035" ] = "JSDO: In '{1}' function, before-image JSON data is missing prods:clientId"; msg.msgs[ "jsdoMSG036" ] = "JSDO: '{1}' can only be called for a dataset"; msg.msgs[ "jsdoMSG037" ] = "{1}: Event name must be provided for {2}."; msg.msgs[ "jsdoMSG038" ] = "Too few arguments. There must be at least {1}."; msg.msgs[ "jsdoMSG039" ] = "The name of the event is not a string."; msg.msgs[ "jsdoMSG040" ] = "The event listener is not a function."; msg.msgs[ "jsdoMSG041" ] = "The event listener scope is not an object."; msg.msgs[ "jsdoMSG042" ] = "'{1}' is not a defined event for this object."; msg.msgs[ "jsdoMSG043" ] = "{1}: A session object was requested to check the status of a Mobile Service named '{2}', but it has not loaded the definition of that service."; msg.msgs[ "jsdoMSG100" ] = "JSDO: Unexpected HTTP response. Too many records."; msg.msgs[ "jsdoMSG101" ] = "Network error while executing HTTP request."; msg.msgs[ "jsdoMSG110" ] = "Catalog error: idProperty not specified for resource '{1}'. idProperty is required {2}."; msg.msgs[ "jsdoMSG111" ] = "Catalog error: Schema '{1}' was not found in catalog."; msg.msgs[ "jsdoMSG112" ] = "Catalog error: Output parameter '{1}' was not found for operation '{2}'."; msg.msgs[ "jsdoMSG113" ] = "Catalog error: Found xType '{1}' for output parameter '{2}' for operation '{3}' but xType DATASET, TABLE or ARRAY was expected."; msg.msgs[ "jsdoMSG114" ] = "JSDO: idProperty '{1}' is missing from '{2}' record."; msg.msgs[ "jsdoMSG115" ] = "JSDO: Invalid option specified in {1}() call."; msg.msgs[ "jsdoMSG116" ] = "JSDO: {1} parameter must be a string in {2} call."; msg.msgs[ "jsdoMSG117" ] = "JSDO: Schema from storage area '{1}' does not match JSDO schema"; msg.msgs[ "jsdoMSG998" ] = "JSDO: JSON object in addRecords() must be DataSet or Temp-Table data."; msg.getMsgText = function(n, args) { var text = msg.msgs[n]; if (!text) throw new Error("Message text was not found by getMsgText()"); for (var i=1;i= PROGRESS_JSDO_PCT_MAX_EMPTY_BLOCKS) this._needCompaction = true; return newDataArray; } return data; }; this._recToDataObject = function(record, includeChildren) { var array = [ record ]; var dataObject = array; if (typeof(includeChildren) == 'undefined') { includeChildren = false; } if (this._jsdo._dataSetName) { dataObject = {}; dataObject[this._jsdo._dataSetName] = {}; dataObject[this._jsdo._dataSetName][this._name] = array; if (includeChildren && this._children.length > 0) { var jsrecord = this._findById(record._id, false); if (jsrecord) { for (var i = 0; i < this._children.length; i++) { var tableName = this._children[i]; dataObject[this._jsdo._dataSetName][tableName] = this._jsdo._buffers[tableName]._getRelatedData(jsrecord); } } } } else { if (this._jsdo._dataProperty) { dataObject = {}; dataObject[this._jsdo._dataProperty] = array; } } return dataObject; }; this._recFromDataObject = function (dataObject) { var data = {}; if (dataObject) { if (this._jsdo._dataSetName) { if (dataObject[this._jsdo._dataSetName]) data = dataObject[this._jsdo._dataSetName][this._name]; } else { if (this._jsdo._dataProperty) { if (dataObject[this._jsdo._dataProperty]) data = dataObject[this._jsdo._dataProperty]; } else if (dataObject.data) { data = dataObject.data; } else { data = dataObject; } } } return data instanceof Array ? data[0] : data; }; // Property: schema this.getSchema = function () { return this._schema; }; this.setSchema = function (schema) { this._schema = schema; }; this.add = function (values) { return this._add(values, true, true); }; this._add = function (values, trackChanges, setWorkingRecord) { if (typeof(trackChanges) == 'undefined') { trackChanges = true; } if (typeof(setWorkingRecord) == 'undefined') { setWorkingRecord = true; } var record = {}; // Assign values from the schema var schema = this.getSchema(); for(var i = 0; i < schema.length; i++) { var fieldName = schema[i].name; if (schema[i].type == "array") { record[fieldName] = []; if (schema[i].maxItems) { for (var j = 0; j < schema[i].maxItems; j++) { record[fieldName][j] = schema[i]["default"]; } } } else { if ((schema[i].type == "string") && schema[i].format && (schema[i].format.indexOf("date") != -1) && (schema[i]["default"])) { var initialValue = schema[i]["default"].toUpperCase(); switch(initialValue) { case "NOW": record[fieldName] = new Date().toISOString(); break; case "TODAY": var t = new Date(); var m = String((t.getMonth()+1)); if (m.length == 1) m = '0' + m; var d = String((t.getDate())); if (d.length == 1) d = '0' + d; record[fieldName] = t.getFullYear()+'-'+m+'-'+d; break; default: record[fieldName] = schema[i]["default"]; } } else record[fieldName] = schema[i]["default"]; } } // Assign values based on a relationship if (this._jsdo.useRelationships && this._relationship && this._parent) { if (this._jsdo._buffers[this._parent].record) { for (var j = 0; j < this._relationship.length; j++) { record[this._relationship[j].childFieldName] = this._jsdo._buffers[this._parent].record.data[this._relationship[j].parentFieldName]; } } else throw new Error(msg.getMsgText("jsdoMSG002", this._parent)); } // Assign values from object parameter for (var v in values) { record[v] = values[v]; } // Specify _id field - do not use schema default var id; var idProperty; if ((idProperty = this._jsdo._resource.idProperty) != undefined) { id = record[idProperty]; } if (!id) { id = progress.data._getNextId(); } else { id += ""; } record._id = id; if (this.autoSort && this._sortRecords && (this._sortFn != undefined || this._sortObject.sortFields != undefined)) { if (this._needsAutoSorting) { this._data.push(record); this._sort(); } else { // Find position of new record in _data and use splice for (var i=0; i 0) { for (var j = 0; j < this._children.length; j++) { var childBuf = this._jsdo._buffers[this._children[j]]; if (childBuf._isNested) { // If child is nested, then we should walk child records to find matches for (var k = 0; k < childBuf._data.length; k++) { var childRecord= childBuf._data[k]; if (!childRecord) continue; var match = false; for (var m = 0; m < childBuf._relationship.length; m++) { match = (parentRecord[childBuf._relationship[m].parentFieldName] == childRecord[childBuf._relationship[m].childFieldName]); if (!match) break; } if (match) { // Make sure that this parentRecord has an array for its child rows if (!parentRecord[childBuf._name]) { parentRecord[childBuf._name] = []; } parentRecord[childBuf._name].push(childRecord); } } // end for; finished adding all child rows for parentRecord // The child table may have its own nested children so call recursively // Use child row array in current parentRecord if (childBuf._hasNestedChild()) { childBuf._getDataWithNestedChildren(parentRecord[childBuf._name]); } } // end if (childBuf._isNested) } } } return data; } this._findFirst = function() { if (this._jsdo.useRelationships && this._relationship && this._parent) { if (this._jsdo._buffers[this._parent].record) { // Filter records using relationship for (var i = 0; i < this._data.length; i++) { var block = this._data[i]; if (!block) continue; var match = false; for (var j = 0; j < this._relationship.length; j++) { match = (this._jsdo._buffers[this._parent].record.data[this._relationship[j].parentFieldName] == this._data[i][this._relationship[j].childFieldName]); if (!match) break; } if (match) { return new progress.data.JSRecord(this, this._data[i]); } } } } else { for (var i = 0; i < this._data.length; i++) { var block = this._data[i]; if (!block) continue; return new progress.data.JSRecord(this, this._data[i]); } } return undefined; }; this._setRecord = function(jsrecord, ignoreRelationships) { if (jsrecord) { this.record = jsrecord; } else { this.record = undefined; } // Set child records only if useRelationships is true if (this._jsdo.useRelationships) { ignoreRelationships = ((typeof(ignoreRelationships) == 'boolean') && ignoreRelationships); if (this._children && this._children.length > 0) { for (var i=0; i= PROGRESS_JSDO_PCT_MAX_EMPTY_BLOCKS) this._needCompaction = true; }; this._equalRecord = function (rec1, rec2, keyFields) { var field; var match = true; for (var i=0; i < keyFields.length; i++) { var fieldName = keyFields[i]; var value1 = rec1[fieldName]; var value2 = rec2[fieldName]; if (!jsdo[tableName].caseSensitive) { field = jsdo[tableName]._fields[fieldName.toLowerCase()]; if (field && field.type == "string") { if (value1 != null) value1 = value1.toUpperCase(); if (value2 != null) value2 = value2.toUpperCase(); } } match = (value1 == value2); if (!match) return false; } return true; }; // Private method to merge changes using merge modes: APPEND, EMPTY, MERGE and REPLACE this._getKey = function (record, keyFields) { var keyObject = {}; for (var i=0; i < keyFields.length; i++) { var fieldName = keyFields[i]; var value = record[fieldName]; if (!jsdo[tableName].caseSensitive) { field = jsdo[tableName]._fields[fieldName.toLowerCase()]; if (field && field.type == "string") { if (value != null) value = value.toUpperCase(); } } keyObject[fieldName] = value; } return JSON.stringify(keyObject); }; this._getCompareFn = function(sortObject) { if (typeof sortObject == 'function') { return function(rec1, rec2) { if (rec1 == null) return 1; if (rec2 == null) return -1; var jsrec1 = new progress.data.JSRecord(this, rec1); var jsrec2 = new progress.data.JSRecord(this, rec2); return sortObject(jsrec1, jsrec2); }; } else return function(rec1, rec2) { var tableRef = sortObject.tableRef; var sortFields = sortObject.sortFields; if (!(sortFields instanceof Array)) return 0; var sortAscending = sortObject.sortAscending; if (rec1 == null) return 1; if (rec2 == null) return -1; var field; for (var i=0; i < sortFields.length; i++) { var fieldName = sortFields[i]; var value1 = rec1[fieldName]; var value2 = rec2[fieldName]; if (!tableRef.caseSensitive) { field = tableRef._fields[fieldName.toLowerCase()]; if (field && field.type == "string") { if (value1 != null) value1 = value1.toUpperCase(); if (value2 != null) value2 = value2.toUpperCase(); } } if (value1 > value2 || value1 == null) return sortAscending[i] ? 1 : -1; else if (value1 < value2 || value2 == null) return sortAscending[i] ? -1 : 1; } return 0; }; }; this._sortObject = {}; this._sortObject.tableRef = this; this._sortObject.sortFields = undefined; this._sortObject.sortAscending = undefined; this._compareFields = this._getCompareFn(this._sortObject); // _sortRecords - Tells the table reference whether to sort on add, assign and addRecords this._sortRecords = true; this._needsAutoSorting = false; // Tells the table reference whether an autoSort is required on an add or assign this._sortFn = undefined; if ((typeof Object.defineProperty) == 'function') { this._autoSort = true; Object.defineProperty ( this, "autoSort", { get: function() { return this._autoSort; }, set: function(value) { if (value) { this._autoSort = true; if (this._sortFn || this._sortObject.sortFields) { this._sort(); this._createIndex(); } } else this._autoSort = false; }, enumerable: true, writeable: true }); this._caseSensitive = false; Object.defineProperty ( this, "caseSensitive", { get: function() { return this._caseSensitive; }, set: function(value) { if (value) { this._caseSensitive = true; } else this._caseSensitive = false; if (this.autoSort && (this._sortObject.sortFields && !this._sortFn)) { this._sort(); this._createIndex(); } }, enumerable: true, writeable: true }); } else { this.autoSort = true; this.caseSensitive = false; // caseSensitive is false by default } this._processSortFields = function(sortFields) { var sortObject = {}; if (sortFields instanceof Array) { sortObject.sortFields = sortFields; sortObject.sortAscending = []; sortObject.fields = {}; for (var i=0;i 1 || (arg1 == undefined) || (!(arg1 instanceof Array) && typeof(arg1) != 'function')) throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", "sort()")); if (arg1 == undefined) throw new Error(msg.getMsgText("jsdoMSG025", "JSDO", "sort()")); if (arg1 instanceof Array) { var sortObject = this._processSortFields(arg1); if (sortObject.sortFields && sortObject.sortFields.length > 0) this._sort(sortObject); } else { this._sort(arg1); } this._createIndex(); }; this._sort = function(arg1) { if (arguments.length == 0 && (!this.autoSort || (this._sortFn == undefined && this._sortObject.sortFields == undefined))) return; if (arguments.length == 0) { if (this._sortFn) { // Sort using function this._data.sort(this._sortFn); } else { // Sort using sort fields this._data.sort(this._compareFields); } this._needsAutoSorting = false; } else { if (typeof(arg1) == 'function') { // Sort using function this._data.sort(this._getCompareFn(arg1)); } else { // Sort using sort fields arg1.tableRef = this; this._data.sort(this._getCompareFn(arg1)); } if (this.autoSort) this._needsAutoSorting = true; } }; /** * Reads a JSON object into the JSDO memory for the specified table reference. * @member addRecords */ this.addRecords = function (jsonObject, addMode, keyFields, trackChanges, isInvoke) { this._jsdo._addRecords(this._name, jsonObject, addMode, keyFields, trackChanges, isInvoke); }; /** * Accepts changes for the specified table reference. * @member acceptChanges */ this.acceptChanges = function() { var tableRef = this; // First, let's remove any "prods:" properties from created and updated records. // Don't have to worry about deleted records, since they're going away. for (var id in tableRef._beforeImage) { // Create if (tableRef._beforeImage[id] === null) { var jsrecord = tableRef._findById(id, false); if (jsrecord != null) { tableRef._jsdo._deleteProdsProperties(jsrecord.data, true); } } // Update else if (this._changed[id] != undefined) { var jsrecord = this._findById(id, false); if (jsrecord != null) { tableRef._jsdo._deleteProdsProperties(jsrecord.data, true); } } } tableRef._processed = {}; tableRef._added = []; tableRef._changed = {}; tableRef._deleted = []; tableRef._beforeImage = {}; }; /** * Rejects changes for the specified table reference. * @member rejectChanges */ this.rejectChanges = function() { // Reject changes for (var id in this._beforeImage) { if (this._beforeImage[id] === null) { // Undo create this._jsdo._undoCreate(this, id); } else if (this._changed[id] != undefined) { // Undo update this._jsdo._undoUpdate(this, id, true); } else { // Undo delete this._jsdo._undoDelete(this, id, true); } } var tableRef = this; tableRef._processed = {}; tableRef._added = []; tableRef._changed = {}; tableRef._deleted = []; }; this.hasChanges = function() { return (Object.keys(this._beforeImage).length != 0); }; this.getChanges = function() { var result = []; for (var id in this._beforeImage) { var item = { rowState: "", record: null }; // Create if (this._beforeImage[id] === null) { item.rowState = PROGRESS_JSDO_ROW_STATE_STRING[progress.data.JSDO._OP_CREATE]; item.record = this._findById(id, false); } // Update else if (this._changed[id] != undefined) { item.rowState = PROGRESS_JSDO_ROW_STATE_STRING[progress.data.JSDO._OP_UPDATE]; item.record = this._findById(id, false); } // Delete else { item.rowState = PROGRESS_JSDO_ROW_STATE_STRING[progress.data.JSDO._OP_DELETE]; item.record = new progress.data.JSRecord(this, this._beforeImage[id]); } result.push(item); } return result; }; /** * Private method to apply changes for the specified table reference. * If _errorString has been set for a row, row change is rejected. * If it has not been set, acceptRowChanges() is called. * @member _applyChanges */ this._applyChanges = function() { for (var id in this._beforeImage) { // Create if (this._beforeImage[id] === null) { var jsrecord = this._findById(id, false); if (jsrecord != null) { if (jsrecord.data._errorString != undefined) { this._jsdo._undoCreate(this, id); } else { jsrecord.acceptRowChanges(); } } else { // Record not present in JSDO memory // Delete after Create var found = false; for (var i = 0; i < this._deleted.length; i++) { if (found = (this._deleted[i].data._id == id)) break; } if (!found) { throw new Error(msg.getMsgText("jsdoMSG000", "Created record appears to be deleted without a delete operation.")); } } } // Update else if (this._changed[id] != undefined) { var jsrecord = this._findById(id, false); if (jsrecord != null) { // Record found in JSDO memory if (jsrecord.data._errorString != undefined) { this._jsdo._undoUpdate(this, id); } else { jsrecord.acceptRowChanges(); } } else { // Record not present in JSDO memory // Delete after Update if (this._beforeImage[id]._errorString != undefined) { this._jsdo._undoDelete(this, id); } else { var found = false; for (var i = 0; i < this._deleted.length; i++) { if (found = (this._deleted[i].data._id == id)) break; } if (!found) { throw new Error(msg.getMsgText("jsdoMSG000", "Updated record appears to be deleted without a delete operation.")); } } } } // Delete else { if (this._beforeImage[id]._errorString != undefined) { this._jsdo._undoDelete(this, id); } } } var tableRef = this; tableRef._processed = {}; tableRef._added = []; tableRef._changed = {}; tableRef._deleted = []; tableRef._beforeImage = {}; }; /** * Accepts row changes for the working record at the table reference level. * @member acceptRowChanges */ this.acceptRowChanges = function () { if (this.record) return this.record.acceptRowChanges(); throw new Error(msg.getMsgText("jsdoMSG002", this._name)); }; /** * Rejects row changes for the working record at the table reference level. * @member rejectRowChanges */ this.rejectRowChanges = function () { if (this.record) return this.record.rejectRowChanges(); throw new Error(msg.getMsgText("jsdoMSG002", this._name)); }; /** This method returns true if this table has any child tables and at least one of those tables is nested. * Else if returns false. * @member _hasNestedChild */ this._hasNestedChild = function() { var hasNestedChild = false; var childBufObj; // If table has children, see if any relationship is NESTED if (this._children.length > 0) { for (var i = 0; i < this._children.length; i++) { childBufObj = this._jsdo._buffers[this._children[i]]; if (childBufObj._isNested) { hasNestedChild = true; break; } } } return hasNestedChild; } }; /** * Returns a JSRecord for the specified JSDO. * @constructor * @class JSRecord * @param jsdo the JSDO * @param record the values of the record */ progress.data.JSRecord = function JSRecord(tableRef, record) { this._tableRef = tableRef; this.data = record; this.getId = function () { return this.data._id ? this.data._id : null; }; this.getErrorString = function () { return this.data._errorString ? this.data._errorString : null; }; /** * Saves a copy of the current record to the before image. * @member _saveBeforeImageUpdate */ this._saveBeforeImageUpdate = function() { // Save before image if (this._tableRef._beforeImage[this.data._id] === undefined) { // this.data._index = index; var copy = {}; this._tableRef._jsdo._copyRecord( this._tableRef, this.data, copy); this._tableRef._beforeImage[this.data._id] = copy; } if (this._tableRef._changed[this.data._id] === undefined) { this._tableRef._changed[this.data._id] = this.data; } // End - Save before image }; /* * */ this._sortRecord = function(fields) { var index = this._tableRef._index[this.data._id].index; var record = this._tableRef._data[index]; if (this._tableRef.autoSort && this._tableRef._sortRecords && (this._tableRef._sortFn != undefined || this._tableRef._sortObject.sortFields != undefined)) { if (this._tableRef._sortObject.fields) { if (typeof fields == 'string') { if (this._tableRef._sortObject.fields[fields] == undefined) return; // Only sort records if the the specified field is in the sort fields } else if (fields instanceof Array) { var found = false; for(var i=0;i index) { i--; } if (i != index) { this._tableRef._data.splice(index, 1); this._tableRef._data.splice(i, 0, record); this._tableRef._createIndex(); } } } }; /** * Assigns the specified values. * @param record parameter with the record values * @member assign */ this.assign = function (record) { if (record === undefined) throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", "assign()")); this._saveBeforeImageUpdate(); var fieldName; var value; var schema = this._tableRef.getSchema(); if (record) { for(var i = 0; i < schema.length; i++) { fieldName = schema[i].name; value = record[fieldName]; if (typeof value != "undefined") { if (typeof value == 'string' && schema[i].type != 'string') { value = this._tableRef._jsdo._convertType(value, schema[i].type, schema[i].items ? schema[i].items.type : null); } this.data[fieldName] = value; } } this._sortRecord(); } return true; }; /** * Removes the JSRecord. * @member remove */ this.remove = function () { return this._remove(true); } this._remove = function (bTrackChanges) { if (typeof(bTrackChanges) == 'undefined') { bTrackChanges= true; } var index = this._tableRef._index[this.data._id].index; var jsrecord = this._tableRef._findById(this.data._id, false); if (bTrackChanges) { // Save before image var record = this._tableRef._beforeImage[this.data._id]; if (record === undefined) { // Record does not exist in the before image this.data._index = index; this._tableRef._beforeImage[this.data._id] = this.data; } else { // Record exists in the before image if (record) { // Record is not null - a null entry in the before image indicates corresponds to an add // Save the index of the record // so that an undo would restore the record in the same position in _data record._index = index; } } // End - Save before image this._tableRef._deleted.push(jsrecord); } // Set entry to null instead of removing entry - index requires positions to be persistent this._tableRef._data[index] = null; this._tableRef._hasEmptyBlocks = true; delete this._tableRef._index[this.data._id]; // Set record property this._tableRef._setRecord( null ); return true; }; /** * Accepts row changes for the specified record. * @member acceptRowChanges */ this.acceptRowChanges = function () { var id = this.data._id; if (this._tableRef._beforeImage[id] !== undefined) { if (this._tableRef._beforeImage[id] === null) { // Accept create // Remove element from _added for (var i = 0; i < this._tableRef._added.length; i++) { if (this._tableRef._added[i] == id) { this._tableRef._added.splice(i, 1); break; } } this._tableRef._jsdo._deleteProdsProperties(this.data, true); } else if (this._tableRef._changed[id] != undefined) { // Accept update delete this._tableRef._changed[id]; this._tableRef._jsdo._deleteProdsProperties(this.data, true); } else { // Accept delete // Remove element from _deleted for (var i = 0; i < this._tableRef._deleted.length; i++) { if (this._tableRef._deleted[i].data._id == id) { this._tableRef._deleted.splice(i, 1); break; } } } delete tableRef._beforeImage[id]; } }; /** * Rejects row changes for the specified record. * @member rejectRowChanges */ this.rejectRowChanges = function () { var id = this.data._id; if (this._tableRef._beforeImage[id] !== undefined) { if (this._tableRef._beforeImage[id] === null) { // Undo create this._tableRef._jsdo._undoCreate(this._tableRef, id); // Remove element from _added for (var i = 0; i < this._tableRef._added.length; i++) { if (this._tableRef._added[i] == id) { this._tableRef._added.splice(i, 1); break; } } } else if (this._tableRef._changed[id] != undefined) { // Undo update this._tableRef._jsdo._undoUpdate(this._tableRef, id, true); delete this._tableRef._changed[id]; } else { // Undo delete this._tableRef._jsdo._undoDelete(this._tableRef, id, true); // Remove element from _deleted for (var i = 0; i < this._tableRef._deleted.length; i++) { if (this._tableRef._deleted[i].data._id == id) { this._tableRef._deleted.splice(i, 1); break; } } } delete tableRef._beforeImage[id]; } }; }; /** * Returns a JSDO for the specified resource. * @constructor * @class JSDO * @param resNameOrParmObj: the resource name or an object that contains the initial values for the JSDO * (if this is an object, it should include the name property with the resource name * @param serviceName : name of service (ignored if 1st param is an object containing the initial values) */ progress.data.JSDO = function JSDO(resNameOrParmObj, serviceName ) { if (typeof progress.data.Session == 'undefined') { throw new Error ('ERROR: You must include progress.session.js'); } this._defineProperty = function(tableName, fieldName) { Object.defineProperty ( this._buffers[tableName], fieldName, { get: function fnGet() { if (this.record) return this.record.data[fieldName]; else return null; }, set: function(value) { if (this.record) { this.record._saveBeforeImageUpdate(); this.record.data[fieldName] = value; this.record._sortRecord( fieldName ); } }, enumerable: true, writeable: true }); }; // Initial values this._buffers = {}; // Object of table references this._numBuffers = 0; this._defaultTableRef = null; this._async = true; this._dataProperty = null; this._dataSetName = null; this.operations = []; this.useRelationships = true; this._session = null; this._needCompaction = false; this._hasCUDOperations = false; this._hasSubmitOperation = false; this._useSubmit = false; // For saving saveChanges(useSubmit) param this.autoApplyChanges = true; // default should be true to support 11.2 behavior this._lastErrors = []; this._localStorage = null; var autoFill = false; // Initialize JSDO using init values if ( !arguments[0] ) { throw new Error("JSDO: Parameters are required in constructor."); } if ( typeof(arguments[0]) == "string") { this.name = arguments[0]; // if ( arguments[1] && (typeof(arguments[1]) == "string") ) // localServiceName = serviceName; } else if ( typeof(arguments[0]) == "object" ) { var args = arguments[0]; for (var v in args) { switch(v) { case 'autoFill': autoFill = args[v]; break; case 'events': this._events = {}; for (var eventName in args[v]) { this._events[eventName.toLowerCase()] = args[v][eventName]; } break; case 'dataProperty': this._dataProperty = args[v]; break; default: this[v] = args[v]; } } } /* error out if caller didn't pass the resource name */ if ( (!this.name) /*|| !(this._session)*/ ) { // make this error message more specific? throw new Error( "JSDO: JSDO constructor is missing the value for 'name'" ); } /* perform some basic validation on the event object for the proper structure if provided */ if (this._events) { if ((typeof this._events) !== 'object') { throw new Error("JSDO: JSDO constructor event object is not defined as an object"); } /* make sure all the event handlers are sane */ for (var prop in this._events) { var evt = this._events[prop]; if (!(evt instanceof Array)) { throw new Error('JSDO: JSDO constructor event object for ' + prop + ' must be an array'); } evt.forEach(function (el) { if ((typeof el) !== 'object') { throw new Error("JSDO: JSDO constuctor event object for " + prop + " is not defined as an object"); } /* listener must have at least fn property defined as a function */ if ((typeof el.fn) !== 'function') { throw new Error("JSDO: JSDO event listener for " + prop + " is not a function."); } /* scope is optional, but must be an object if provided */ if (el.scope && (typeof el.scope) !== 'object') { throw new Error("JSDO: JSDO event listener scope for " + prop + " is not an object."); } }); } } if (this.name) { // Read resource definition from the Catalog - save reference to JSDO // Enhance this to deal with multiple services loaded and the same resource // name is used by more than one service (use the local serviceName var) this._resource = progress.data.ServicesManager.getResource(this.name); if (this._resource) { if (!this.url) this.url = this._resource.url; if (!this._dataSetName && this._resource._dataSetName) { // Catalog defines a DataSet this._dataSetName = this._resource._dataSetName; // Define TableRef property in the JSDO if (this._resource.dataProperty) { var buffer = this[this._resource.dataProperty] = new progress.data.JSTableRef(this, this._resource.dataProperty); this._buffers[this._resource.dataProperty] = buffer; } else { for (var tableName in this._resource.fields) { var buffer = this[tableName] = new progress.data.JSTableRef(this, tableName); this._buffers[tableName] = buffer; } } } if (!this._dataProperty && this._resource.dataProperty) this._dataProperty = this._resource.dataProperty; if (!this._dataSetName) { var tableName = this._dataProperty?this._dataProperty:""; this._buffers[tableName] = new progress.data.JSTableRef(this, tableName); if (tableName) this[tableName] = this._buffers[tableName]; } // Add functions for operations to JSDO object for (fnName in this._resource.fn) { this[fnName] = this._resource.fn[fnName]["function"]; } // Check if CUD operations have been defined this._hasCUDOperations = this._resource.generic["create"] != undefined || this._resource.generic["update"] != undefined || this._resource.generic["delete"] != undefined; this._hasSubmitOperation = this._resource.generic["submit"] != undefined; /* get a session object, using name of the service to look it up in the list of * sessions maintained by the ServicesManager */ if ( !this._session ) { var myservice = progress.data.ServicesManager.getService( this._resource.service.name ); this._session = myservice._session; this._session._pushJSDOs( this ); } } else { throw new Error(msg.getMsgText("jsdoMSG004", this.name)); } } else { this._buffers[""] = new progress.data.JSTableRef(this, ""); } if ( !this._session) { throw new Error("JSDO: Unable to get user session for resource '" + this.name + "'"); } // Calculate _numBuffers and _defaultTableRef for (var buf in this._buffers) { this._buffers[buf]._parent = null; this._buffers[buf]._children = []; // The _relationship object is only specified for the child buffer. // Currently it is limited to only a single relationship. ie. It does not support the // where the child buffer is involved in more than one data-relation this._buffers[buf]._relationship = null; this._buffers[buf]._isNested = false; if (!this._defaultTableRef) this._defaultTableRef = this._buffers[buf]; this._numBuffers++; } if (this._numBuffers != 1) this._defaultTableRef = null; else { // record is used to represent the current record for a table reference // data corresponds to the values (JSON object) of the data this.record = null; } // Define caseSensitive property at the JSDO level if ((typeof Object.defineProperty) == 'function') { this._caseSensitive = false; // caseSensitive is false by default Object.defineProperty ( this, "caseSensitive", { get: function() { return this._caseSensitive; }, set: function(value) { this._caseSensitive = value ? true : false; for (var buf in this._buffers) { this._buffers[buf].caseSensitive = this._caseSensitive; } }, enumerable: true, writeable: true }); this._autoSort = true; // autoSort is true by default Object.defineProperty ( this, "autoSort", { get: function() { return this._autoSort; }, set: function(value) { this._autoSort = value ? true : false; for (var buf in this._buffers) { this._buffers[buf].autoSort = this._autoSort; } }, enumerable: true, writeable: true }); } // Set schema for TableRef if (this._resource && this._resource.fields) { for (var buf in this._buffers) { this._buffers[buf]._schema = this._resource.fields[buf]; this._buffers[buf]._primaryKeys = this._resource.primaryKeys[buf]; if (this._buffers[buf]._schema && (typeof Object.defineProperty) == 'function') { // Add fields as properties of the TableRef object for (var i=0; i 1) { for (var buf in this._buffers) { var fields = []; var found = false; for (var i = 0; i < this._buffers[buf]._schema.length; i++) { var field = this._buffers[buf]._schema[i]; if (field.items && field.type == "array" && field.items.$ref) { if (this._buffers[field.name]) { found = true; this._buffers[field.name]._isNested = true; } } else fields.push(field); } // Replace list of fields - removing nested datasets from schema if (found) this._buffers[buf]._schema = fields; } } // Process relationships if (this._resource && this._resource.relations) { for (var i = 0; i < this._resource.relations.length; i++) { var relationship = this._resource.relations[i]; if (relationship.childName && relationship.parentName) { // Set casing of fields in relationFields to be the same as in the schema if (relationship.relationFields instanceof Array) { for (var j = 0; j < relationship.relationFields.length; j++) { var fieldName; var field; if (this._buffers[relationship.parentName]._fields) { fieldName = relationship.relationFields[j].parentFieldName; field = this._buffers[relationship.parentName]._fields[fieldName.toLowerCase()]; if (field) { relationship.relationFields[j].parentFieldName = field.name; } else throw new Error(msg.getMsgText("jsdoMSG010", fieldName)); } if (this._buffers[relationship.childName]._fields) { fieldName = relationship.relationFields[j].childFieldName; field = this._buffers[relationship.childName]._fields[fieldName.toLowerCase()]; if (field) { relationship.relationFields[j].childFieldName = field.name; } else throw new Error(msg.getMsgText("jsdoMSG010", fieldName)); } } } this._buffers[relationship.childName]._parent = relationship.parentName; this._buffers[relationship.childName]._relationship = relationship.relationFields; this._buffers[relationship.parentName]._children.push(relationship.childName); } } } this.isDataSet = function() { return this._dataSetName ? true: false; }; /** handler for invoke operation complete */ this._invokeComplete = function (jsdo, success, request) { // only fire on async requests if (request.async && request.fnName) { jsdo.trigger('afterInvoke', request.fnName, jsdo, success, request); } }; /** handler for invoke operation success */ this._invokeSuccess = function (jsdo, success, request) { // do nothing }; /** handler for invoke operation error */ this._invokeError = function (jsdo, success, request) { // do nothing }; /** * Performs an HTTP request using the specified parameters. This is * used to perform remote calls for the JSDO for operations defined. * @member _httpRequest */ this._httpRequest = function (xhr, method, url, reqBody, request) { // if xhr wasn't passed we'll create our own since this is an invoke operation // if xhr is passed, then it is probably a CRUD operation which is setup with XHR // in call to session if (!xhr) { xhr = new XMLHttpRequest(); // only setup the callback handlers if we're responsible for creating the // xhr call which happens on invoke operations...which is the normal case // the CRUD operations setup their own callbacks and they have their own // event handlers so we don't use them here. xhr.onCompleteFn = this._invokeComplete; xhr.onSuccessFn = this._invokeSuccess; xhr.onErrorFn = this._invokeError; xhr.onreadystatechange = this.onReadyStateChangeGeneric; // for invokes we always fire the invoke when doing async if (request.async && request.fnName) { this.trigger('beforeInvoke', request.fnName, this, request); } // For Invoke operations, wrap reqBody in a request object // This is not required for CRUD operations since the whole // reqBody is mapped to the parameter if (reqBody) { if (this._resource && this._resource.service) { var useRequest = this._resource.service.useRequest; if (this._resource.service.settings && this._resource.service.settings.useRequest != undefined) { useRequest = this._resource.service.settings.useRequest; } if (useRequest) { reqBody = { request: reqBody }; } } } } xhr.request = request; xhr.jsdo = this; request.jsdo = this; request.xhr = xhr; this._session._openRequest(xhr, method, url, request.async); var input = null; if (reqBody) { xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); input = JSON.stringify(reqBody); } try { xhr.send(input); } catch (e) { request.success = false; request.exception = e; xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // let Session check for online/offline } return request; }; // This method currently is just used by the JSDOReadService. // It returns data in its non-nested (default) format this._getDataObject = function() { var dataObject = {}; if (this._dataSetName) { dataObject[this._dataSetName] = {}; var oldUseRelationships = this.useRelationships; // Turn off useRelationships so that getData() returns all the records try { this.useRelationships = false; for (var buf in this._buffers) { dataObject[this._dataSetName][buf] = this._buffers[buf].getData(); } } finally { // Restore useRelationships this.useRelationships = oldUseRelationships; } } else { if (this._dataProperty) { dataObject[this._dataProperty] = this.getData(); } else return this.getData(); // Array } return dataObject; }; // This method currently is just used by the JSDOReadService. // Now that the JSDO Services support nested data, we want to return data nested for those // relationships that are marked nested. // // This method returns a data object containing the nested data. // If a parent row is involved in nested relationship, then references to its child rows are added to the parent row in a child table array // (providing the nested format). // We are using the internal jsdo _data arrays, and adding a child table array to each parent row that has children. // Once the caller is done with the nested data, they can call jsdo._unnestData() which removes these child table references // this._getDataObjectAsNested = function() { var dataObject = {}; if (this._dataSetName) { dataObject[this._dataSetName] = {}; try { // First walk thru all buffers. We need to determine if any of the buffers are // involved in a nested relationship. If so, we want to return the child's // data in nested format. for (var buf in this._buffers) { var bufObj = this._buffers[buf]; // If this is a child table, and its involved in a nested relationship, // then just skip. // This table's data will be nested within each parent row when we // process the parent table. if (bufObj._isNested) continue; this._nestChildren = false; // default to false // If table has children, see if any relationship is NESTED if (bufObj._children.length > 0) { for (var i = 0; i < bufObj._children.length; i++) { var childBufObj = this._buffers[bufObj._children[i]]; if (childBufObj._isNested) { this._nestChildren = true; break; } } } dataObject[this._dataSetName][buf] = this._buffers[buf].getData(); } } catch(e) { throw new Error(msg.getMsgText("jsdoMSG000", e.message)); } finally { // Set back to default avlue this._nestChildren = false; } } else { if (this._dataProperty) { dataObject[this._dataProperty] = this.getData(); } else return this.getData(); // Array } return dataObject; }; // This method is used in conjunction with _getDataObjectAsNested() in the JSDOReadService. // _getDataObjectAsNested() adds arrays of child row references to their parent rows. // Once the JSDOReadService has done its data mapping, we need to remove the references since // internally the JSDO stores its data in unnested format. this._unnestData= function() { if (this._dataSetName) { var parentRecord; var bufObj; var childBufObj; // First walk thru all buffers. We need to determine if any of the buffers are parent // buffers involved in a nested relationship. If so, then we'll look for any child row arrays // to delete for (var buf in this._buffers) { bufObj = this._buffers[buf]; // If we know this table has at least one nested child table, we'll walk thru // all its rows to determine if the rows have any child row arrays. // It's more efficient to just walk thru the parent row list once, so we'll // check for all child row arrays here if (bufObj._hasNestedChild()) { // Now must walk thru the parent rows and delete any child row arrays for (var i = 0; i < bufObj._data.length; i++) { parentRecord = bufObj._data[i]; for (var j = 0; j < bufObj._children.length; j++) { childBufObj = this._buffers[bufObj._children[j]]; if (parentRecord[childBufObj._name]) { delete parentRecord[childBufObj._name]; } } } } } // end for } } this._recToDataObject = function(record, includeChildren) { if (this._defaultTableRef) return this._defaultTableRef._recToDataObject(record, includeChildren); throw new Error(msg.getMsgText("jsdoMSG001", "_recToDataObject()")); }; this._recFromDataObject = function (dataObject) { if (this._defaultTableRef) return this._defaultTableRef._recFromDataObject(dataObject); throw new Error(msg.getMsgText("jsdoMSG001", "_recFromDataObject()")); }; this.add = function(obj) { if (this._defaultTableRef) return this._defaultTableRef.add(obj); throw new Error(msg.getMsgText("jsdoMSG001", "add()")); }; this.hasData = function() { for (var buf in this._buffers) { if (this._buffers[this._buffers[buf]._name].hasData()) return true; } return false; } this.getData = function() { if (this._defaultTableRef) return this._defaultTableRef.getData(); throw new Error(msg.getMsgText("jsdoMSG001", "getData()")); }; this.getSchema = function () { if (this._defaultTableRef) return this._defaultTableRef.getSchema(); throw new Error(msg.getMsgText("jsdoMSG001", "getSchema()")); }; this.findById = function (id) { if (this._defaultTableRef) return this._defaultTableRef.findById(id); throw new Error(msg.getMsgText("jsdoMSG001", "findById()")); }; this._convertType = function (value, type, itemType) { if ((typeof value != 'string') || (type == null)) return value; var result = value; try { if (type == 'array') { var result = []; // PSC00319759 First strip out '[' and ']' from string value = value.slice(1, value.length - 1); var elements = value.split(','); var convertItem = (itemType && (itemType != 'string')); for (var i = 0; i < elements.length; i++) { result[i] = convertItem ? this._convertType(elements[i], itemType, null) : elements[i]; } } else if (type == 'integer') { result = parseInt(value); } else if (type == 'number') { result = parseFloat(value); } else { result = value; } } catch (e) { throw new Error(msg.getMsgText("jsdoMSG000", "Error converting string to native type: " + e.message)); } return result; }; this.assign = function (values) { if (this._defaultTableRef) { return this._defaultTableRef.assign(values); } else throw new Error(msg.getMsgText("jsdoMSG001", "assign()")); }; this.remove = function () { if (this._defaultTableRef) { return this._defaultTableRef.remove(); } else throw new Error(msg.getMsgText("jsdoMSG001", "remove()")); }; this.getId = function () { if (this._defaultTableRef) return this._defaultTableRef.getId(); throw new Error(msg.getMsgText("jsdoMSG001", "getId()")); }; this.getErrorString = function () { if (this._defaultTableRef) return this._defaultTableRef.getErrorString(); throw new Error(msg.getMsgText("jsdoMSG001", "getErrorString()")); }; /** * Finds a record in the JSDO memory using the specified function to determine the record. * @member find */ this.find = function (fn) { if (this._defaultTableRef) return this._defaultTableRef.find(fn); throw new Error(msg.getMsgText("jsdoMSG001", "find()")); }; this.foreach = function(fn) { if (this._defaultTableRef) return this._defaultTableRef.foreach(fn); throw new Error(msg.getMsgText("jsdoMSG001", "foreach()")); }; this.setSortFields = function(sortFields) { if (this._defaultTableRef) return this._defaultTableRef.setSortFields(sortFields); throw new Error(msg.getMsgText("jsdoMSG001", "setSortFields()")); }; this.setSortFn = function(fn) { if (this._defaultTableRef) return this._defaultTableRef.setSortFn(fn); throw new Error(msg.getMsgText("jsdoMSG001", "setSortFn()")); }; this.sort = function(arg1) { if (this._defaultTableRef) return this._defaultTableRef.sort(arg1); throw new Error(msg.getMsgText("jsdoMSG001", "sort()")); }; /** * Loads data from the HTTP resource. * @member fill */ this.fill = function () { var objParam; this._lastErrors = []; // Process parameters if (arguments.length != 0) { // Call to fill() has parameters switch(typeof(arguments[0])) { case 'function': throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", "fill()")); default: // fill( string); var filter; if (arguments[0] == null) { filter = ""; } else if (typeof(arguments[0]) == 'string') { filter = arguments[0]; } else { throw new Error(msg.getMsgText("jsdoMSG025", "JSDO", "fill()")); } objParam = { filter: filter }; break; } } else { // fill(); objParam = null; } var xhr = new XMLHttpRequest(); var request = { xhr : xhr, jsdo : this, objParam : objParam }; xhr.request = request; xhr.jsdo = this; xhr.onSuccessFn = this._fillSuccess; xhr.onErrorFn = this._fillError; xhr.onCompleteFn = this._fillComplete; xhr.onreadystatechange = this.onReadyStateChangeGeneric; this.trigger("beforeFill", this, request); if (this._resource) { if (typeof(this._resource.generic.read) == "function") { xhr.objParam = objParam; this._resource.generic.read(xhr, this._async); } else { throw new Error("JSDO: READ operation is not defined."); } } else { this._session._openRequest(xhr, 'GET', this.url, this._async); try { xhr.send(null); } catch(e) { request.exception = e; xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // get the Client Context ID (AppServer ID) } } }; /** * Clears all data (including any pending changes) for each buffer in JSDO * @member _clearData */ this._clearData = function() { for (var buf in this._buffers) { this._buffers[buf]._clearData(); } }; /** * Executes a CRUD operation using the built-in API. * @member _execGenericOperation */ this._execGenericOperation = function( operation, objParam, request, onCompleteFn, onSuccessFn, onErrorFn) { var xhr = new XMLHttpRequest(); request.xhr = xhr; request.jsdo = this; request.objParam = objParam; request.operation = operation; xhr.jsdo = this; xhr.onCompleteFn = onCompleteFn; xhr.onSuccessFn = onSuccessFn; xhr.onErrorFn = onErrorFn; xhr.onreadystatechange = this.onReadyStateChangeGeneric; xhr.request = request; var operationStr; switch(operation) { case progress.data.JSDO._OP_READ: case progress.data.JSDO._OP_CREATE: case progress.data.JSDO._OP_UPDATE: case progress.data.JSDO._OP_DELETE: case progress.data.JSDO._OP_SUBMIT: operationStr = PROGRESS_JSDO_OP_STRING[operation]; break; default: throw new Error("JSDO: Unexpected operation " + operation + " in HTTP request."); } if (this._resource) { if (typeof(this._resource.generic[operationStr]) == "function") { xhr.objParam = objParam; this._resource.generic[operationStr](xhr, this._async); } else { throw new Error("JSDO: " + operationStr.toUpperCase() + " operation is not defined."); } } }; this._undefWorkingRecord = function () { // Set record property for (var buf in this._buffers) { this._buffers[buf]._setRecord( null ); } }; /** * Saves changes in the JSDO. Save any outstanding changes for CREATES, UPDATE, and DELETEs * @member saveChanges */ this.saveChanges = function (useSubmit) { this._lastErrors = []; if (useSubmit == undefined) { useSubmit = false; } else if (typeof(useSubmit) != 'boolean') { throw new Error(msg.getMsgText("jsdoMSG025", "JSDO", "saveChanges()")); } this._useSubmit = useSubmit; // _fireCUDTriggersForSubmit() needs to know how saveChanges() was called if (!this._hasCUDOperations) throw new Error(msg.getMsgText("jsdoMSG026")); var request = { jsdo : this }; this.trigger("beforeSaveChanges", this, request); if (useSubmit) { /* Pass in request object. Need to use same request object so before and after saveChanges events * are in sync in JSDO Submit Service. */ this._syncDataSetForSubmit(request); } else if (this._dataSetName) this._syncDataSetForCUD(); else this._syncSingleTable(); }; /** * Synchronizes changes for a TableRef * * @param operation HTTP operation to be performed * @param tableRef Handle to the TableRef * @param batch Optional. batch information associated with the sync operation. If not specified a new one will be created. Used for saving datasets. * @member _syncTableRef */ this._syncTableRef = function(operation, tableRef, batch) { if (tableRef._visited) return; tableRef._visited = true; //ensure batch object is sane if (!batch) { batch = { operations : [] }; } else if (!batch.operations) { batch.operations = []; } // Before children // Create parent records before children switch(operation) { case progress.data.JSDO._OP_CREATE: for (var i = 0; i < tableRef._added.length; i++) { var id = tableRef._added[i]; var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[id]) continue; tableRef._processed[id] = jsrecord.data; var jsonObject; if (this.isDataSet()) { jsonObject = {}; if (this._useBeforeImage("create")) { jsonObject[this._dataSetName] = {}; var dataSetObject = jsonObject[this._dataSetName]; dataSetObject["prods:hasChanges"] = true; dataSetObject[tableRef._name] = []; var rowData = {}; // Dont need to send prods:id for create, no before table or error table to match // Dont need to send prods:clientId - since only sending one record rowData["prods:rowState"] = "created"; rowData["prods:clientId"] = jsrecord.data._id; tableRef._jsdo._copyRecord(tableRef, jsrecord.data, rowData); delete rowData["_id"]; dataSetObject[tableRef._name].push(rowData); } else { jsonObject[tableRef._name] = []; jsonObject[tableRef._name].push(jsrecord.data); } } else jsonObject = jsrecord.data; var request = { operation : operation, batch : batch, jsrecord : jsrecord, jsdo : this }; batch.operations.push(request); jsrecord._tableRef.trigger("beforeCreate", this, jsrecord, request); this.trigger("beforeCreate", this, jsrecord, request); this._execGenericOperation( progress.data.JSDO._OP_CREATE, jsonObject, request, this._createComplete, this._createSuccess, this._createError); } break; case progress.data.JSDO._OP_UPDATE: for (var id in tableRef._changed) { var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[id]) continue; tableRef._processed[id] = jsrecord.data; var jsonObject = {}; var requestData = {}; var useBeforeImageFormat = false; if (this.isDataSet()) { if (this._useBeforeImage("update")) { useBeforeImageFormat = true; jsonObject[this._dataSetName] = {}; var dataSetObject = jsonObject[this._dataSetName]; dataSetObject["prods:hasChanges"] = true; dataSetObject[tableRef._name] = []; var rowData = {}; // Dont need to send prods:clientId - since only sending one record rowData["prods:id"] = jsrecord.data._id; rowData["prods:rowState"] = "modified"; rowData["prods:clientId"] = jsrecord.data._id tableRef._jsdo._copyRecord(tableRef, jsrecord.data, rowData); delete rowData["_id"]; dataSetObject[tableRef._name].push(rowData); // Now create before-table data dataSetObject["prods:before"] = {}; var beforeObject = dataSetObject["prods:before"]; beforeObject[tableRef._name] = []; var beforeRowData = {}; // Dont need to send prods:clientId - since only sending one record beforeRowData["prods:id"] = jsrecord.data._id; tableRef._jsdo._copyRecord(tableRef, tableRef._beforeImage[jsrecord.data._id], beforeRowData); delete beforeRowData["_id"]; beforeObject[tableRef._name].push(beforeRowData); } } if (!useBeforeImageFormat) { if (this._resource.service && this._resource.service.settings && this._resource.service.settings.sendOnlyChanges) { tableRef._jsdo._copyRecord(tableRef, jsrecord.data, requestData, tableRef._beforeImage[jsrecord.data._id]); if (this._resource.idProperty) { requestData[this._resource.idProperty] = jsrecord.data[this._resource.idProperty]; } else { throw new Error(msg.getMsgText("jsdoMSG110", this._resource.name, " for sendOnlyChanges property")); } } else requestData = jsrecord.data; if (this.isDataSet()) { jsonObject[tableRef._name] = []; jsonObject[tableRef._name].push(requestData); } else { requestData = jsrecord.data; jsonObject = requestData; } } var request = { jsrecord : jsrecord, operation : operation, batch : batch, jsdo : this }; batch.operations.push(request); jsrecord._tableRef.trigger("beforeUpdate", this, jsrecord, request); this.trigger("beforeUpdate", this, jsrecord, request); this._execGenericOperation( progress.data.JSDO._OP_UPDATE, jsonObject, request, this._updateComplete, this._updateSuccess, this._updateError); } break; } // Call _syncTableRef on child tables for (var i = 0; i < tableRef._children.length; i++) { var childTableName = tableRef._children[i]; this._syncTableRef( operation, this._buffers[childTableName], batch); } // After children // Delete parent records after children if (operation == progress.data.JSDO._OP_DELETE) { for (var i = 0; i < tableRef._deleted.length; i++) { var id = tableRef._deleted[i]._id; var jsrecord = tableRef._deleted[i]; if (!jsrecord) continue; tableRef._processed[id] = jsrecord.data; var jsonObject = {}; var requestData = {}; var useBeforeImageFormat = false; if (this.isDataSet()) { if (this._useBeforeImage("delete")) { useBeforeImageFormat = true; jsonObject[this._dataSetName] = {}; var dataSetObject = jsonObject[this._dataSetName]; dataSetObject["prods:hasChanges"] = true; // There is no after tables for deletes, so just create before-table data dataSetObject["prods:before"] = {}; var beforeObject = dataSetObject["prods:before"]; beforeObject[tableRef._name] = []; var rowData = jsrecord.data; var beforeRowData = {}; // Dont need to send prods:id for delete, no after table or error table to match // Dont need to send prods:clientId - since only sending one record beforeRowData["prods:rowState"] = "deleted"; beforeRowData["prods:clientId"] = jsrecord.data._id; tableRef._jsdo._copyRecord(tableRef, tableRef._beforeImage[rowData._id], beforeRowData); beforeObject[tableRef._name].push(beforeRowData); } } if (!useBeforeImageFormat) { if (this._resource.service && this._resource.service.settings && this._resource.service.settings.sendOnlyChanges) { if (this._resource.idProperty) { requestData[this._resource.idProperty] = jsrecord.data[this._resource.idProperty]; } else { throw new Error(msg.getMsgText("jsdoMSG110", this._resource.name, " for sendOnlyChanges property")); } } else requestData = jsrecord.data; if (this.isDataSet()) { jsonObject[tableRef._name] = []; jsonObject[tableRef._name].push(requestData); } else { requestData = jsrecord.data; jsonObject = requestData; } } var request = { batch : batch, jsrecord : jsrecord, operation : operation, jsdo : this }; batch.operations.push(request); jsrecord._tableRef.trigger("beforeDelete", this, jsrecord, request); this.trigger("beforeDelete", this, jsrecord, request); this._execGenericOperation( progress.data.JSDO._OP_DELETE, jsonObject, request, this._deleteComplete, this._deleteSuccess, this._deleteError); } } }; /** * Returns true if the specified operation type was specified in the catalog as useBeforeImage, * else it returns false. * @member _useBeforeImage */ this._useBeforeImage = function(opType) { for (var idx = 0; idx < this._resource.operations.length; idx++){ if (this._resource.operations[idx].type == opType) { return this._resource.operations[idx].useBeforeImage; } } return false; } /** * Synchronizes changes for a DataSet. This is called when we send over one row at at time * to Create, Update and Delete methods. * It handles row with or without before-image data. * @member _syncDataSetForCUD */ this._syncDataSetForCUD = function() { var batch = { operations : [] }; // Process buffers // Synchronize deletes for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._syncTableRef( progress.data.JSDO._OP_DELETE, tableRef, batch); } // Synchronize adds for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._syncTableRef( progress.data.JSDO._OP_CREATE, tableRef, batch); } // Synchronize updates for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._syncTableRef( progress.data.JSDO._OP_UPDATE, tableRef, batch); } if (this.autoApplyChanges) { for (var buf in this._buffers) { var tableRef = this._buffers[buf]; tableRef._processed = {}; tableRef._added = []; tableRef._changed = {}; tableRef._deleted = []; } } // OE00229270 If _async is false, this ensures that afterSaveChanges() is called just once // We now do this after all operations have been processed if (!this._async) { if (this._isBatchComplete(batch)) { var success = this._isBatchSuccess(batch); var request = { batch : batch, success : success }; this._undefWorkingRecord(); this._fireAfterSaveChanges(success, request); } } // end OE00229270 }; /** * Synchronizes changes for a single table * @member _syncSingleTable */ this._syncSingleTable = function() { if (!this._defaultTableRef) return; var tableRef = this._defaultTableRef; var batch = { operations : [] }; var fireAfterSaveChanges = false; // Skip delete for records that were added // mark them as processed var addedRecords = {}; for(var i = 0; i < tableRef._added.length; i++) { var id = tableRef._added[i]; addedRecords[id] = id; } for(var i = 0; i < tableRef._deleted.length; i++) { var jsrecord = tableRef._deleted[i]; if (!jsrecord) continue; var id = jsrecord.data._id; if (addedRecords[id]) { // Set request object // Properties async, fnName, objParam, and response are not set when the HTTP request is suppressed var request = { success: true, xhr : undefined, operation : progress.data.JSDO._OP_DELETE, batch : batch, jsrecord : jsrecord, jsdo : this }; batch.operations.push(request); tableRef._processed[id] = jsrecord.data; var jsdo = request.jsdo; try { request.jsrecord._tableRef.trigger("afterDelete", jsdo, request.jsrecord, request.success, request); jsdo.trigger("afterDelete", jsdo, request.jsrecord, request.success, request); } finally { request.complete = true; } fireAfterSaveChanges = true; } } addedRecords = null; // Synchronize deletes for(var i = 0; i < tableRef._deleted.length; i++) { var jsrecord = tableRef._deleted[i]; if (!jsrecord) continue; var id = jsrecord.data._id; if (tableRef._processed[id]) continue; tableRef._processed[id] = jsrecord.data; fireAfterSaveChanges = false; var xhr = new XMLHttpRequest(); xhr.jsdo = this; var request = { xhr : xhr, operation : progress.data.JSDO._OP_DELETE, batch : batch, jsrecord : jsrecord, jsdo : this }; batch.operations.push(request); xhr.onCompleteFn = this._deleteComplete; xhr.onSuccessFn = this._deleteSuccess; xhr.onErrorFn = this._deleteError; xhr.onreadystatechange = this.onReadyStateChangeGeneric; xhr.request = request; jsrecord._tableRef.trigger("beforeDelete", this, jsrecord, request); this.trigger("beforeDelete", this, jsrecord, request); var requestData = {}; if (this._resource.service && this._resource.service.settings && this._resource.service.settings.sendOnlyChanges) { if (this._resource.idProperty) { requestData[this._resource.idProperty] = jsrecord.data[this._resource.idProperty]; } else { throw new Error(msg.getMsgText("jsdoMSG110", this._resource.name, " for sendOnlyChanges property")); } } else requestData = jsrecord.data; if (this._resource) { if (typeof(this._resource.generic["delete"]) == "function") { xhr.objParam = requestData; this._resource.generic["delete"](xhr, this._async); } else { throw new Error("JSDO: DELETE operation is not defined."); } } else { this._session._openRequest(xhr, 'DELETE', this.url + '/' + id, true); try { xhr.send(null); } catch (e) { request.success = false; request.exception = e; xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // let Session check for online/offline } } } // Synchronize adds for(var i = 0; i < tableRef._added.length; i++) { var id = tableRef._added[i]; var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[id]) continue; tableRef._processed[id] = jsrecord.data; fireAfterSaveChanges = false; var xhr = new XMLHttpRequest(); xhr.jsdo = this; var request = { xhr : xhr, jsrecord : jsrecord, batch : batch, operation : progress.data.JSDO._OP_CREATE, jsdo : this }; batch.operations.push(request); xhr.onCompleteFn = this._createComplete; xhr.onSuccessFn = this._createSuccess; xhr.onErrorFn = this._createError; xhr.onreadystatechange = this.onReadyStateChangeGeneric; xhr.request = request; jsrecord._tableRef.trigger("beforeCreate", this, jsrecord, request); this.trigger("beforeCreate", this, jsrecord, request); if (this._resource) { if (typeof(this._resource.generic.create) == "function") { var copy = {}; if (this._resource.idProperty != undefined && jsrecord.data._id != undefined) { this._copyRecord(jsrecord._tableRef, jsrecord.data, copy); delete copy._id; xhr.objParam = copy; } else { xhr.objParam = jsrecord.data; } this._resource.generic.create(xhr, this._async); } else { throw new Error("JSDO: CREATE operation is not defined."); } } else { this._session._openRequest(xhr, 'POST', this.url, true); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); var input = JSON.stringify(jsrecord.data); try { xhr.send(input); } catch (e) { request.success = false; request.exception = e; xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // let Session check for online/offline } } } // Synchronize updates for(var id in tableRef._changed) { var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[id]) continue; tableRef._processed[id] = jsrecord.data; fireAfterSaveChanges = false; var xhr = new XMLHttpRequest(); var request = { xhr : xhr, jsrecord : jsrecord, operation : progress.data.JSDO._OP_UPDATE, batch : batch, jsdo : this, }; xhr.request = request; xhr.jsdo = this; batch.operations.push(request); xhr.onCompleteFn = this._updateComplete; xhr.onSuccessFn = this._updateSuccess; xhr.onErrorFn = this._updateError; xhr.onreadystatechange = this.onReadyStateChangeGeneric; jsrecord._tableRef.trigger("beforeUpdate", this, jsrecord, request); this.trigger("beforeUpdate", this, jsrecord, request); var requestData = {}; if (this._resource.service && this._resource.service.settings && this._resource.service.settings.sendOnlyChanges) { tableRef._jsdo._copyRecord(tableRef, jsrecord.data, requestData, tableRef._beforeImage[jsrecord.data._id]); if (this._resource.idProperty) { requestData[this._resource.idProperty] = jsrecord.data[this._resource.idProperty]; } else { throw new Error(msg.getMsgText("jsdoMSG110", this._resource.name, " for sendOnlyChanges property")); } } else requestData = jsrecord.data; if (this._resource) { if (typeof(this._resource.generic.update) == "function") { xhr.objParam = requestData; this._resource.generic.update(xhr, this._async); } else { throw new Error("JSDO: UPDATE operation is not defined."); } } else { this._session._openRequest(xhr, 'PUT', this.url + '/' + id, this._async); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8"); var input = JSON.stringify(jsrecord.data); try { xhr.send(input); } catch (e) { request.success = false; request.exception = e; xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // let Session check for online/offline } } } if (this.autoApplyChanges) { // Arrays to keep track of changes tableRef._beforeImage = {}; tableRef._added = []; tableRef._changed = {}; tableRef._deleted = []; tableRef._processed = {}; } // OE00229270 If _async is false, fire afterSaveChanges() after all operations are processed if (!this._async) fireAfterSaveChanges = true; if (fireAfterSaveChanges) { var jsdo = this; var request = { batch : batch, success : true }; jsdo._undefWorkingRecord(); jsdo._fireAfterSaveChanges(request.success, request); } }; /** * Synchronizes changes for a DataSet, sending over the entire change-set to saveChanges() on server * Sends over before-image and after-image data. * @member _syncDataSetForSubmit */ this._syncDataSetForSubmit = function(request) { request.jsrecords = []; // First thing to do is to create jsonObject with before and after image data for all // records in change-set (creates, updates and deletes) var jsonObject = this._createChangeSet(this._dataSetName, false, request); this._execGenericOperation(progress.data.JSDO._OP_SUBMIT, jsonObject, request, this._saveChangesComplete, this._saveChangesSuccess, this._saveChangesError); } /** * Private method that creates a jsonObject with before and after image data for all * records in change-set (creates, updates and deletes) * * Params: dataSetName is required. * alwaysCreateTable is required. If true, always create table array (even if no data/changes) * request is optional * @member _createChangeSet */ this._createChangeSet = function(dataSetName, alwaysCreateTable, request) { var changeSetJsonObject = {}; changeSetJsonObject[dataSetName] = {}; var dataSetJsonObject = changeSetJsonObject[dataSetName]; var hasChanges = dataSetJsonObject["prods:hasChanges"] = this._hasChanges(); if (hasChanges) { if ((alwaysCreateTable == true)) { for (var buf in this._buffers) { dataSetJsonObject[this._buffers[buf]._name] = []; } } // First do deletes //for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._addDeletesToChangeSet(tableRef, dataSetJsonObject, request); } // Adds //for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._addCreatesToChangeSet(tableRef, dataSetJsonObject, request); } // Updates //for (var buf in this._buffers) { this._buffers[buf]._visited = false; } for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._addChangesToChangeSet(tableRef, dataSetJsonObject, request) } // Clear _processed map for (var buf in this._buffers) { this._buffers[buf]._processed = {}; } } // Check if change set is empty // A saveChanges() with a delete of new record would result in an empty change set // An empty DataSet is sent to the server to ensure that AfterSaveChanges fires var keys = Object.keys(changeSetJsonObject[dataSetName]); if (keys.length == 1 && keys[0] == "prods:hasChanges") { for (var buf in this._buffers) { dataSetJsonObject[this._buffers[buf]._name] = []; } dataSetJsonObject["prods:hasChanges"] = false; } return changeSetJsonObject; } /** * * Private method that creates a jsonObject with data and also before image data * for all records in change-set (creates, updates and deletes) * * Params: dataSetName is required. * It returns jsonObject that can be used as input to addRecords() * @member _createDataAndChangeSet */ this._createDataAndChangeSet = function(dataSetName) { var jsonObject = {}; jsonObject[dataSetName] = {}; var dataSetJsonObject = jsonObject[dataSetName]; /* We always want to create tables (even if there's no data) so we can compare schemas * of data in local storage to JSDO's schema */ for (var buf in this._buffers) dataSetJsonObject[this._buffers[buf]._name] = []; if (this._hasChanges()) { dataSetJsonObject["prods:hasChanges"] = true; } // Add data from each table. This will also add bi data for any created or updated rows for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._addRecordsToObject(tableRef, dataSetJsonObject); } // Now do deletes for (var buf in this._buffers) { var tableRef = this._buffers[buf]; this._addDeletesToChangeSet(tableRef, dataSetJsonObject); } // Clear _processed map for (var buf in this._buffers) { this._buffers[buf]._processed = {}; } return jsonObject; } // This method adds all record for specified table into dataSetJsonObject. // If record has bi data, it adds that as well this._addRecordsToObject = function(tableRef, dataSetJsonObject) { if (tableRef._data.length > 0 && !dataSetJsonObject[tableRef._name]) dataSetJsonObject[tableRef._name] = []; for (var i=0; i < tableRef._data.length; i++) { var record = tableRef._data[i]; if (!record) continue; // Check if record has bi data, can only determine if it's created or changed since // deleted rows are not in after data if (this._doesRecordHaveCreateBIData(tableRef, record._id) === true) { var jsrecord = tableRef._findById(record._id, false); if (!jsrecord) continue; if (tableRef._processed[jsrecord.data._id]) continue; this._addCreatedRowToChangeSet(tableRef, jsrecord, dataSetJsonObject); } if (this._doesRecordHaveUpdateBIData(tableRef, record._id) === true) { var jsrecord = tableRef._findById(record._id, false); if (!jsrecord) continue; if (tableRef._processed[jsrecord.data._id]) continue; this._addChangedRowToChangeSet(tableRef, jsrecord, dataSetJsonObject); } else { if (tableRef._processed[record._id]) continue; tableRef._processed[record._id] = record; var rowData = {}; tableRef._jsdo._copyRecord(tableRef, record, rowData); delete rowData["_id"]; dataSetJsonObject[tableRef._name].push(rowData); } } } // Check if specified after record has bi data for newly created record. // Returns True if after record has corresponding bi data, else false this._doesRecordHaveCreateBIData = function(tableRef, id) { for (var i = 0; i < tableRef._added.length; i++) { if (tableRef._added[i] === id) return true; } return false; } // Check if specified after record has bi data for updated record. // Returns True if after record has corresponding bi data, else false this._doesRecordHaveUpdateBIData = function(tableRef, id) { for (var changedId in tableRef._changed) { if (changedId === id) return true; } return false; } // If a create, remove or update exists, method returns true, else returns false this._hasChanges = function() { var hasChanges = false; for (var buf in this._buffers) { var tableRef = this._buffers[buf]; var hasUpdates = false; for (var id in tableRef._changed) { hasUpdates = true; break; } if (tableRef._deleted.length > 0 || tableRef._added.length > 0 || hasUpdates) { hasChanges = true; break; } } return hasChanges; } // This method is used when saveChanges() is called, and also when storing data to local storage. // The request param should be defined for saveChanges(), but not needed when storing data to local storage this._addDeletesToChangeSet = function(tableRef, dataSetJsonObject, request) { // There is no after table for deletes, so just create before-table data for (var i = 0; i < tableRef._deleted.length; i++) { var jsrecord = tableRef._deleted[i]; if (!jsrecord) continue; if (jsrecord.data && jsrecord.data._id != undefined && tableRef._beforeImage[jsrecord.data._id] === null) { // Deleted record is for a new record - do not send deleted record to server continue; } this._addDeletedRowToChangeSet(tableRef, jsrecord, dataSetJsonObject, request); } } this._addDeletedRowToChangeSet = function(tableRef, jsrecord, dataSetJsonObject, request) { tableRef._processed[jsrecord.data._id] = jsrecord.data; // Store jsrecord in request object so we can access it when saveChanges completes, // in order to run afterDelete events jsrecord.data["prods:rowState"] = "deleted"; if (typeof(request) != 'undefined') { request.jsrecords.push(jsrecord); // Need to call beforeDelete trigger if saveChanges(true) is called jsrecord._tableRef.trigger("beforeDelete", this, jsrecord, request); this.trigger("beforeDelete", this, jsrecord, request); } var beforeRowData = {}; // AppServer will roundtrip this back to jsdo client beforeRowData["prods:clientId"] = jsrecord.data._id; beforeRowData["prods:rowState"] = "deleted"; var beforeTableJsonObject = this._getTableInBeforeJsonObject(dataSetJsonObject, tableRef._name); tableRef._jsdo._copyRecord(tableRef, tableRef._beforeImage[jsrecord.data._id], beforeRowData); delete beforeRowData["_id"]; beforeTableJsonObject.push(beforeRowData); } // This method is used when saveChanges() is called, and also when storing data to local storage. // The request param should be defined for saveChanges(), but not needed when storing data to local storage this._addCreatesToChangeSet = function(tableRef, dataSetJsonObject, request) { // There is no before table for creates, so just create after-table data for (var i = 0; i < tableRef._added.length; i++) { var id = tableRef._added[i]; var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[jsrecord.data._id]) continue; this._addCreatedRowToChangeSet(tableRef, jsrecord, dataSetJsonObject, request); } } this._addCreatedRowToChangeSet = function(tableRef, jsrecord, dataSetJsonObject, request) { tableRef._processed[jsrecord.data._id] = jsrecord.data; if (!dataSetJsonObject[tableRef._name]) { dataSetJsonObject[tableRef._name] = []; } // Store jsrecord in request object so we can access it when saveChanges completes, // in order to run afterCreate events jsrecord.data["prods:rowState"] = "created"; if (typeof(request) != 'undefined') { request.jsrecords.push(jsrecord); // Need to call beforeCreate trigger when saveChanges(true) is called jsrecord._tableRef.trigger("beforeCreate", this, jsrecord, request); this.trigger("beforeCreate", this, jsrecord, request); } var rowData = {}; // AppServer will roundtrip this back to jsdo client rowData["prods:clientId"] = jsrecord.data._id; rowData["prods:rowState"] = "created"; tableRef._jsdo._copyRecord(tableRef, jsrecord.data, rowData); delete rowData["_id"]; dataSetJsonObject[tableRef._name].push(rowData); } // This method is used when saveChanges() is called, and also when storing data to local storage. // The request param should be defined for saveChanges(), but not needed when storing data to local storage this._addChangesToChangeSet = function(tableRef, dataSetJsonObject, request) { // For Changes, there is both before and after table data for (var id in tableRef._changed) { var jsrecord = tableRef._findById(id, false); if (!jsrecord) continue; if (tableRef._processed[jsrecord.data._id]) continue; this._addChangedRowToChangeSet(tableRef, jsrecord, dataSetJsonObject, request); } } this._addChangedRowToChangeSet = function(tableRef, jsrecord, dataSetJsonObject, request) { tableRef._processed[jsrecord.data._id] = jsrecord.data; if (!dataSetJsonObject[tableRef._name]) { dataSetJsonObject[tableRef._name] = []; } // Store jsrecord in request object so we can access it when saveChanges completes, in order // to run afterUpdate events jsrecord.data["prods:rowState"] = "modified"; if (typeof(request) != 'undefined') { request.jsrecords.push(jsrecord); // Need to call beforeUpdate trigger when saveChanges(true) is called jsrecord._tableRef.trigger("beforeUpdate", this, jsrecord, request); this.trigger("beforeUpdate", this, jsrecord, request); } var rowData = {}; // Required by AppServer in before-image data. Matches before row rowData["prods:id"] = jsrecord.data._id; // AppServer will roundtrip this back to jsdo client rowData["prods:clientId"] = jsrecord.data._id; rowData["prods:rowState"] = "modified"; tableRef._jsdo._copyRecord(tableRef, jsrecord.data, rowData); delete rowData["_id"]; dataSetJsonObject[tableRef._name].push(rowData); // Now add before-image data var beforeTableJsonObject = this._getTableInBeforeJsonObject(dataSetJsonObject, tableRef._name); var beforeRowData = {}; // Required by AppServer in before-image data. Matches after row beforeRowData["prods:id"] = jsrecord.data._id; tableRef._jsdo._copyRecord(tableRef, tableRef._beforeImage[jsrecord.data._id], beforeRowData); //delete beforeRowData["_id"]; beforeTableJsonObject.push(beforeRowData); } // Private method to get table's json object from the specified dataset json object. // If it hasn't been created yet, this method creates it. this._getTableInBeforeJsonObject = function (dataSetJsonObject, tableName) { var tableJsonObject; if (!dataSetJsonObject["prods:before"]) { dataSetJsonObject["prods:before"] = {}; } var beforeObject = dataSetJsonObject["prods:before"]; if (!beforeObject[tableName]) { beforeObject[tableName] = []; } return beforeObject[tableName]; }; /** * Reads a JSON object into the JSDO memory. * @member addRecords */ this.addRecords = function (jsonObject, addMode, keyFields, trackChanges, isInvoke) { if (this.isDataSet()) { if (jsonObject instanceof Array) { if (!this._defaultTableRef) { throw new Error(msg.getMsgText("jsdoMSG998")); } } else { if (jsonObject == null) { jsonObject = {}; } if (jsonObject[this._dataSetName]) { jsonObject = jsonObject[this._dataSetName]; } } // Allow empty object in addRecords with MODE_EMPTY if (addMode != progress.data.JSDO.MODE_EMPTY) { if (Object.keys(jsonObject).length == 0) throw new Error(msg.getMsgText("jsdoMSG006")); } var oldUseRelationships = this.useRelationships; // Turn off useRelationships since addRecords() does not use the working record this.useRelationships = false; try { for (var buf in this._buffers) { // Read data for tables in JSON object if (jsonObject[this._buffers[buf]._name]) this._addRecords(this._buffers[buf]._name, jsonObject, addMode, keyFields, trackChanges, isInvoke); else if (addMode == progress.data.JSDO.MODE_EMPTY) { this._buffers[this._buffers[buf]._name]._clearData(); } } } finally { // Restore useRelationships this.useRelationships = oldUseRelationships; } } else if (this._defaultTableRef) { this._addRecords(this._defaultTableRef._name, jsonObject, addMode, keyFields, trackChanges, isInvoke); } }; /** * Copies the fields of the source record to the target record. * Preserves the _id of the target record. * @member _copyRecord */ this._copyRecord = function (tableRef, source, target, onlyChangesRecord) { for (var field in source) { if (onlyChangesRecord != undefined) { if (source[field] == onlyChangesRecord[field]) continue; } // Fix for PSC00277769 if (source[field] == null) { target[field] = source[field]; } else if (typeof source[field] === 'object') { var newObject = source[field] instanceof Array ? [] : {}; this._copyRecord(tableRef, source[field], newObject); target[field] = newObject; } else target[field] = source[field]; } }; /** * Deletes the "prods:" properties when no longer needed, typically when doing acceptChanges, rejectChanges, or _applyChanges. * These properties are used to transfer before-image info between client JSDO and AppServer. * * Also, it optionally clears out the errorString field depending upon value of clearErrorString. To be consistent with the handling of * the ABL's Buffer ERROR-STRING attribute, the errorString field should be cleared out when doing acceptChanges() or rejectChanges(). * @member _deleteProdsProperties */ this._deleteProdsProperties = function (record, clearErrorString) { /* Default to false */ if (typeof(clearErrorString) == 'undefined') { clearErrorString = false; } if (record) { delete record["prods:id"]; delete record["prods:rowState"]; delete record["prods:hasErrors"]; delete record["prods:clientId"]; if (clearErrorString && record._errorString) { record._errorString = undefined; } } }; this._addRecords = function (tableName, jsonObject, addMode, keyFields, trackChanges, isInvoke) { var beforeImageJsonObject = null; var beforeImageJsonIndex = null; if (jsonObject && (this._dataSetName != undefined)) { if (jsonObject[this._dataSetName] && jsonObject[this._dataSetName]["prods:hasChanges"]) { beforeImageJsonObject = jsonObject; beforeImageJsonIndex = {}; } else if (jsonObject["prods:hasChanges"]) { beforeImageJsonObject = {}; beforeImageJsonObject[this._dataSetName] = jsonObject; beforeImageJsonIndex = {}; } } if (typeof(tableName) != 'string') throw new Error(msg.getMsgText("jsdoMSG020")); if (!addMode) throw new Error(msg.getMsgText("jsdoMSG021")); switch (addMode) { case progress.data.JSDO.MODE_APPEND: case progress.data.JSDO.MODE_EMPTY: case progress.data.JSDO.MODE_MERGE: case progress.data.JSDO.MODE_REPLACE: break; default: throw new Error(msg.getMsgText("jsdoMSG022")); break; } if (!keyFields) keyFields = []; else { if (!(keyFields instanceof Array) && (typeof(keyFields) == 'object')) { if (keyFields[tableName]) { keyFields = keyFields[tableName]; } else { keyFields = []; } } } if (!(keyFields instanceof Array)) { throw new Error(msg.getMsgText("jsdoMSG008")); } // Check that the specified field names are in the schema if (this._buffers[tableName]._fields) { for ( var i = 0; i < keyFields.length; i++) { var field = this._buffers[tableName]._fields[keyFields[i].toLowerCase()]; if (field == undefined) { throw new Error(msg.getMsgText("jsdoMSG009", keyFields[i])); } else { keyFields[i] = field.name; } } } trackChanges = trackChanges ? true : false; if (tableName) { if (!(jsonObject instanceof Array)) { var data = null; if (jsonObject == null) { jsonObject = {}; } if (this.isDataSet()) { if (jsonObject[this._dataSetName]) data = jsonObject[this._dataSetName][tableName]; else if (jsonObject[tableName]) data = jsonObject[tableName]; } else { if (this._dataProperty) data = jsonObject[this._dataProperty]; else if (jsonObject.data) data = jsonObject.data; } if (data instanceof Array) { saveJsonObject = jsonObject; jsonObject = data; } else if ((addMode == progress.data.JSDO.MODE_EMPTY) && (typeof (jsonObject) == 'object') && (Object.keys(jsonObject).length == 0)) { jsonObject = []; // Allow empty object in addRecords with // MODE_EMPTY } // Allow empty object when called by restoreChangesOnlyForTable() // where there are only deletes - in bi data else if ((addMode == progress.data.JSDO.MODE_REPLACE) && (typeof (jsonObject) == 'object') && (beforeImageJsonObject)) { jsonObject = []; } } if (!(jsonObject instanceof Array)) { throw new Error(msg.getMsgText("jsdoMSG005", tableName)); } var dataHasBeenProcessed = false; try { this._buffers[tableName]._sortRecords = false; if (keyFields.length == 0 || addMode == progress.data.JSDO.MODE_EMPTY) { // Quick merge if (addMode == progress.data.JSDO.MODE_EMPTY) { this._buffers[tableName]._clearData(); } // APPEND, MERGE, REPLACE for (var i=0; i < jsonObject.length; i++) { var jsrecord = this._buffers[tableName]._add(jsonObject[i], trackChanges, false); jsonObject[i]._id = jsrecord.data._id; if (beforeImageJsonIndex && jsonObject[i]["prods:id"]) { beforeImageJsonIndex[jsonObject[i]["prods:id"]] = jsrecord.data._id; } if (beforeImageJsonObject) { this._deleteProdsProperties(jsrecord.data); } } } else { // Build temporary index var tmpIndex; if (this._buffers[tableName]._data.length * jsonObject.length >= 10) { tmpIndex = {}; for (var i=0; i < this._buffers[tableName]._data.length; i++) { var record = this._buffers[tableName]._data[i]; if (!record) continue; var key = this._buffers[tableName]._getKey(record, keyFields); tmpIndex[key] = record; } } else tmpIndex = null; // Do not use an index var checkBeforeImage = (Object.keys(this._buffers[tableName]._beforeImage).length != 0); for (var i=0; i < jsonObject.length; i++) { var match = false; var record = null; // Check for duplicates if (tmpIndex) { var key = this._buffers[tableName]._getKey(jsonObject[i], keyFields); record = tmpIndex[key]; match = (record != undefined); } else { for (var j=0; j < this._buffers[tableName]._data.length; j++) { record = this._buffers[tableName]._data[j]; if (!record) continue; match = (this._buffers[tableName]._equalRecord(jsonObject[i], record, keyFields)); if (match) { // Duplicate found break; } } } if (match) { if (isInvoke && (this._resource.idProperty != undefined) && (jsonObject[i]._id == undefined)) { // Add _id to jsonObject jsonObject[i]._id = record._id; } // If beforeRecord is null, there is entry in _beforeImage for a create. // If beforeRecord is undefined, there is no entry var beforeRecord = this._buffers[tableName]._beforeImage[record._id]; if (checkBeforeImage && (jsonObject[i]["prods:id"] !== undefined) && (typeof beforeRecord !== 'undefined')) { // Only throw exception if the existing bi data is not the same as the new bi data var isAfterSame = this._sameData(jsonObject[i], record); var isBeforeSame = true; // For creates, beforeRecord will be null if (beforeRecord) { var beforeObject = this._getBeforeRecordFromObject(jsonObject[i], beforeImageJsonObject, tableName); if (beforeObject) isBeforeSame = this._sameData(beforeObject, beforeRecord); } if (!isAfterSame || !isBeforeSame) throw new Error(msg.getMsgText("jsdoMSG032")); } switch (addMode) { case progress.data.JSDO.MODE_APPEND: throw new Error (msg.getMsgText("jsdoMSG023")); break; case progress.data.JSDO.MODE_MERGE: /* Ignore duplicate */ if (beforeImageJsonIndex && jsonObject[i]["prods:id"]) { beforeImageJsonIndex[jsonObject[i]["prods:id"]] = record._id; } break; case progress.data.JSDO.MODE_REPLACE: if (beforeImageJsonIndex && jsonObject[i]["prods:id"]) { beforeImageJsonIndex[jsonObject[i]["prods:id"]] = record._id; } if (jsonObject[i]._id == undefined) jsonObject[i]._id = record._id; this._copyRecord( this._buffers[tableName], jsonObject[i], record); this._deleteProdsProperties(record); break; default: break; } } else { // Add record var jsrecord = this._buffers[tableName]._add(jsonObject[i], trackChanges, false); jsonObject[i]._id = jsrecord.data._id; if (beforeImageJsonIndex && jsonObject[i]["prods:id"]) { beforeImageJsonIndex[jsonObject[i]["prods:id"]] = jsrecord.data._id; } if (beforeImageJsonObject) { this._deleteProdsProperties(jsrecord.data); } if (tmpIndex) { var key = this._buffers[tableName]._getKey(jsrecord.data, keyFields); tmpIndex[key] = jsrecord.data; } } } tmpIndex = null; } dataHasBeenProcessed = true; } finally { this._buffers[tableName]._sortRecords = true; this._buffers[tableName]._sort(); this._buffers[tableName]._createIndex(); if (dataHasBeenProcessed && beforeImageJsonObject) { this._buffers[tableName]._loadBeforeImageData(beforeImageJsonObject, beforeImageJsonIndex, keyFields); } } } }; // This method returns corresponding bi record of the afterRecord from specified jsonObject this._getBeforeRecordFromObject = function (afterRecord, jsonObject, tablename) { var beforeData = jsonObject[this._dataSetName]["prods:before"]; var id = afterRecord["prods:id"] var beforeRecord = undefined; if (!beforeData) return beforeRecord; // First check to see if the before data is the same for (var i=0;i < beforeData[tablename].length; i++) { var record = beforeData[tablename][i]; if (record["prods:id"] && id == record["prods:id"]) { beforeRecord = record; break; } } return beforeRecord; } this._sameData = function (record1, record2) { var value1, value2; for (var fieldName in record1) { if (fieldName.substring(0,5) != "prods" && fieldName != "_id") { value1 = record1[fieldName]; value2 = record2[fieldName]; if (value1 > value2 || value1 == null) return false; else if (value1 < value2 || value2 == null) return false; } } return true; } // private method to merge changes after a read operation this._mergeRead = function (jsonObject, xhr) { if (this.isDataSet()) { if (this._dataProperty) { var datasetBuffer = this._buffers[this._dataProperty]; datasetBuffer._data = jsonObject[this._dataSetName][this._dataProperty]; if (datasetBuffer.autoSort) { datasetBuffer._sort(); } datasetBuffer._createIndex(); } else { // Load data from JSON object into _data for (var buf in this._buffers) { var data; if (jsonObject[this._dataSetName]) data = jsonObject[this._dataSetName][buf]; else data = null; data = data?data:[]; this._buffers[buf]._data = data; if (this._buffers[buf].autoSort) { this._buffers[buf]._sort(); } this._buffers[buf]._createIndex(); if (jsonObject[this._dataSetName] && jsonObject[this._dataSetName]["prods:hasChanges"]) { this._buffers[buf]._loadBeforeImageData(jsonObject); } } // Load nested data into _data if (this._numBuffers > 1) { for (var buf in this._buffers) { if (this._buffers[buf]._isNested && this._buffers[buf]._parent && this._buffers[this._buffers[buf]._parent]) { var srcData = this._buffers[this._buffers[buf]._parent]._data; var data = []; for (var i = 0; i < srcData.length; i++) { if (srcData[i][buf] != undefined) { for (var j = 0; j < srcData[i][buf].length; j++) { data.push(srcData[i][buf][j]); } delete srcData[i][buf]; } } this._buffers[buf]._data = data; if (this._buffers[buf].autoSort) { this._buffers[buf]._sort(); } this._buffers[buf]._createIndex(); } } } } } else { if (jsonObject instanceof Array) { this._defaultTableRef._data = jsonObject; } else { if (this._dataProperty) this._defaultTableRef._data = jsonObject[this._dataProperty]; else if (jsonObject.data) this._defaultTableRef._data = jsonObject.data; else { this._defaultTableRef._data = []; this._defaultTableRef._data[0] = jsonObject; } } } for (var buf in this._buffers) { if (this._buffers[buf].autoSort) { this._buffers[buf]._sort(); } this._buffers[buf]._createIndex(); } }; /** * Replace existing record data and index entry with new record data. * @member _mergeUpdateRecord */ this._mergeUpdateRecord = function (tableRef, recordId, record) { var index = tableRef._index[recordId].index; record._id = recordId; tableRef._data[index] = record; if (tableRef._jsdo._resource.idProperty != undefined) { var id = tableRef._data[index][tableRef._jsdo._resource.idProperty]; if (id != undefined) { delete tableRef._index[recordId]; id += ""; tableRef._index[id] = new progress.data.JSIndexEntry(index); record._id = id; } } return record; }; /** * update existing record data with specified error string * @member _setErrorString */ this._setErrorString = function (tableRef, recordId, errorString, setInBeforeTable) { if (setInBeforeTable) { tableRef._beforeImage[recordId]._errorString = errorString; } else { var index = tableRef._index[recordId].index; tableRef._data[index]._errorString = errorString; } }; /** * Returns the array with the data from the specified dataObject. * @member _arrayFromDataObject */ this._arrayFromDataObject = function(dataObject, tableRef) { var data = undefined; if (dataObject == undefined) return undefined; if (this._dataSetName) { if (dataObject[this._dataSetName]) data = dataObject[this._dataSetName][tableRef._name]; } else { // check if data returned as array if (dataObject instanceof Array) { data = dataObject; } else { // or if data property is set if (this._dataProperty) { data = dataObject[this._dataProperty]; } else if (dataObject.data) { // or just try with 'data' as the data property name data = dataObject.data; } } } return data; }; ///////////////////////////////////////////////////////////////////////////////////////////// // // Private method to merge changes after a create or update operation. // This method is called to merge changes when server's Create or Update methods were called. // // It returns true if it found error for row in before-image data (prods:hasErrors = true) // It returns false if there is no before-image data or prods:hasErrors property is absent this._mergeUpdateForCUD = function (jsonObject, xhr) { var hasError = false; // Update dataset with changes from server if (this._dataSetName) { var dataSetJsonObject = jsonObject[this._dataSetName]; var beforeJsonObject = dataSetJsonObject["prods:before"]; // only updates the specified record var tableRef = xhr.request.jsrecord._tableRef; var tableJsonObject = this._arrayFromDataObject(jsonObject, tableRef); if (tableJsonObject instanceof Array) { if (tableJsonObject.length > 1) { xhr.request.success = false; throw new Error(msg.getMsgText("jsdoMSG100")); } for (var i = 0; i < tableJsonObject.length; i++) { var recordId = xhr.request.jsrecord.getId(); if (!recordId) { throw new Error(msg.getMsgText("jsdoMSG034", "_mergeUpdateForCUD()")); } // Determine if error string (get prods_id before _mergeUpdateRecord() is called, since // it removes all prods properties) var errorString = undefined; if (tableJsonObject[i]["prods:hasErrors"]) { var prods_id = tableJsonObject[i]["prods:id"]; errorString = this._getErrorStringFromJsonObject(dataSetJsonObject, tableRef, prods_id); hasError = true; } var record = this._mergeUpdateRecord(tableRef, recordId, tableJsonObject[i]); if (errorString) this._setErrorString(tableRef, recordId, errorString, false); xhr.request.jsrecord = new progress.data.JSRecord(tableRef, record); } } } else { // update single record with changes from server var tableRef = this._defaultTableRef; var data = this._arrayFromDataObject(jsonObject); if (data instanceof Array) { if (data.length > 1) { xhr.request.success = false; throw new Error(msg.getMsgText("jsdoMSG100")); } for (var i = 0; i < data.length; i++) { var recordId = xhr.request.jsrecord.getId(); if (!recordId) { throw new Error(msg.getMsgText("jsdoMSG034", "_mergeUpdateForCUD()")); } var record = this._mergeUpdateRecord(tableRef, recordId, data[i]); xhr.request.jsrecord = new progress.data.JSRecord(tableRef, record); } } } return hasError; }; ///////////////////////////////////////////////////////////////////////////////////////////// // // Private method to determine if deleted row (from delete operation) returned from AppServer was returned // with an error in the before-image data. // // It returns true if it found an error for row in before-image data (prods:hasErrors = true) // It returns false if there is no before-image data or prods:hasErrors property is absent this._checkForDeleteError = function (dataSetJsonObject, xhr) { var hasError = false; var tableRef = xhr.request.jsrecord._tableRef; beforeJsonObject = dataSetJsonObject["prods:before"]; // No merge is necessary for deletes, but we need to see if there are any errors on deletes records. // delete records are not in after table, only in before table if (beforeJsonObject) { var beforeTableJsonObject = beforeJsonObject[tableRef._name]; if (beforeTableJsonObject.length > 1) { xhr.request.success = false; throw new Error(msg.getMsgText("jsdoMSG100")); } // clientId is same as _id var recordId = beforeTableJsonObject[0]["prods:clientId"]; if (!recordId) { throw new Error(msg.getMsgText("jsdoMSG035", "_checkForDeleteError()")); } // Determine if row was returned with error string if (beforeTableJsonObject[0]["prods:hasErrors"]) { var prods_id = beforeTableJsonObject[0]["prods:id"]; var errorString = this._getErrorStringFromJsonObject(dataSetJsonObject, tableRef, prods_id); this._setErrorString(tableRef, recordId, errorString, true); hasError = true; } } return hasError; }; ///////////////////////////////////////////////////////////////////////////////////////////// // // Private method to merge changes after a call to saveChanges. // This method is called when saveChanges(useSubmit) was called with useSubmit=true. // This can process/merge one or more created, deleted or updated records. // In order for a jsonObject to have before-image data, it must be associated with a dataset. // // It only merges changes in the after table. But we need to look at before-image table to see if there // were any errors passed back for the deletes // this._mergeUpdateForSubmit = function (jsonObject, xhr) { //if (!this._dataSetName || !jsonObject[this._dataSetName]["prods:hasChanges"]) if (!this._dataSetName) { // "_mergeUpdateForSubmit() can only be called for a dataset" throw new Error(msg.getMsgText("jsdoMSG036", "_mergeUpdateForSubmit()")); } // response is sent back with extra dataset object wrapper var dataSetJsonObject = jsonObject[this._dataSetName]; if (dataSetJsonObject[this._dataSetName]) dataSetJsonObject = dataSetJsonObject[this._dataSetName]; var beforeJsonObject = dataSetJsonObject["prods:before"]; for (var buf in this._buffers) { var tableRef = this._buffers[buf]; var tableJsonObject = dataSetJsonObject[tableRef._name]; if (tableJsonObject instanceof Array) { for (var i = 0; i < tableJsonObject.length; i++) { var recordId = tableJsonObject[i]["prods:clientId"]; if (!recordId) { throw new Error(msg.getMsgText("jsdoMSG035", "_mergeUpdateForSubmit()")); } // Determine if error string (get prods_id before _mergeUpdateRecord() is called, since // it removes all prods properties) var errorString = undefined; if (tableJsonObject[i]["prods:hasErrors"]) { var prods_id = tableJsonObject[i]["prods:id"]; errorString = this._getErrorStringFromJsonObject(dataSetJsonObject, tableRef, prods_id); } var record = this._mergeUpdateRecord(tableRef, recordId, tableJsonObject[i]); if (errorString) this._setErrorString(tableRef, recordId, errorString, false); // Now need to update jsrecords. We use this data when we fire create, update and delete events. // Updating so that it contains latest data (data sent back from server) var jsrecords = xhr.request.jsrecords; for (var idx = 0; idx < jsrecords.length; idx++) { if (jsrecords[idx].data["_id"] == recordId) { jsrecords[idx] = new progress.data.JSRecord(tableRef, record); break; } } } } } // No merge is necessary for deletes, but we need to see if there are any errors on deletes records. // delete records are not in after table, only in before table if (beforeJsonObject) { for (var buf in this._buffers) { var tableRef = this._buffers[buf]; var beforeTableJsonObject = beforeJsonObject[tableRef._name]; if (beforeTableJsonObject instanceof Array) { for (var i = 0; i < beforeTableJsonObject.length; i++) { if (beforeTableJsonObject[i]["prods:rowState"] == "deleted") { var recordId = beforeTableJsonObject[i]["prods:clientId"]; if (!recordId) { throw new Error(msg.getMsgText("jsdoMSG035", "_mergeUpdateForSubmit()")); } // If row was returned with error string, just copy that over to jsdo record if (beforeTableJsonObject[i]["prods:hasErrors"]) { var prods_id = beforeTableJsonObject[i]["prods:id"]; var errorString = this._getErrorStringFromJsonObject(dataSetJsonObject, tableRef, prods_id); this._setErrorString(tableRef, recordId, errorString, true); } } } } } } }; ///////////////////////////////////////////////////////////////////////////////////////////// // // Private method that fires afterCreate, afterUpdate and afterDelete (CUD) triggers after // saveChanges(true) is called. We must fire create, update and delete triggers // for each record that was sent to backend submit operation this._fireCUDTriggersForSubmit = function (request) { for (var idx = 0; idx < request.jsrecords.length; idx++) { var jsrecord = request.jsrecords[idx]; switch (jsrecord.data["prods:rowState"]) { case "created": jsrecord._tableRef.trigger("afterCreate", this, jsrecord, request.success, request); this.trigger("afterCreate", this, jsrecord, request.success, request); break; case "modified": jsrecord._tableRef.trigger("afterUpdate", this, jsrecord, request.success, request); this.trigger("afterUpdate", this, jsrecord, request.success, request); break; case "deleted": jsrecord._tableRef.trigger("afterDelete", this, jsrecord, request.success, request); this.trigger("afterDelete", this, jsrecord, request.success, request); break; } } } ////////////////////////////////////////////////////////////////////////////////////////////// // // Private method to return error for specified row from jsonObject's prods:errors object (before-data) sent over // from AppServer // this._getErrorStringFromJsonObject = function (dataSetJsonObject, tableRef, prods_id) { var tableJsonObject = undefined; var errorsJsonObject = dataSetJsonObject["prods:errors"]; if (errorsJsonObject) { tableJsonObject = errorsJsonObject[tableRef._name]; } if (tableJsonObject instanceof Array) { for (var i = 0; i < tableJsonObject.length; i++) { var id = tableJsonObject[i]["prods:id"]; if (id === prods_id) { var errorString = tableJsonObject[i]["prods:error"]; return errorString === null ? "Server returned unspecified error. Please check log files." : errorString; } } } return undefined; } this._fillSuccess = function (jsdo, success, request) { var xhr = request.xhr; jsdo._clearData(); jsdo._mergeRead(request.response, xhr); // Set working record for (var buf in jsdo._buffers) { if (!jsdo._buffers[buf]._parent || !jsdo.useRelationships) { jsdo._buffers[buf]._setRecord ( jsdo._buffers[buf]._findFirst() ); } } }; this._fillComplete = function (jsdo, success, request) { jsdo.trigger("afterFill", jsdo, request.success, request); }; this._fillError = function (jsdo, success, request) { jsdo._clearData(); }; this._undoCreate = function (tableRef, id) { // Undo operation // Remove record from JSDO memory var entry = tableRef._index[id]; if (entry != undefined) { var index = entry.index; tableRef._data[index] = null; } tableRef._hasEmptyBlocks = true; delete tableRef._index[id]; delete tableRef._beforeImage[id]; // End - Undo operation }; this._undoUpdate = function (tableRef, id, deleteProdsProps) { /* Default to false */ if (typeof(deleteProdsProps) == 'undefined') { deleteProdsProps = false; } // Undo operation // Restore from before image var record = tableRef._beforeImage[id]; // Before image points to an existing record if (record) { var index = tableRef._index[id].index; tableRef._jsdo._copyRecord(tableRef, record, tableRef._data[index]); if (deleteProdsProps) tableRef._jsdo._deleteProdsProperties(tableRef._data[index], true); } delete tableRef._beforeImage[id]; // End - Restore before image }; this._undoDelete = function (tableRef, id, deleteProdsProps) { /* Default to false */ if (typeof(deleteProdsProps) == 'undefined') { deleteProdsProps = false; } // Restore from before image var record = tableRef._beforeImage[id]; // Before image points to an existing record if (record) { var index = record._index; delete record._index; if (deleteProdsProps) tableRef._jsdo._deleteProdsProperties(record, true); if ((index != undefined) && (tableRef._data[index] == null)) { tableRef._data[index] = record; } else { tableRef._data.push(record); index = tableRef._data.length - 1; } tableRef._index[id] = new progress.data.JSIndexEntry(index); } delete tableRef._beforeImage[id]; // End - Restore before image }; this._deleteComplete = function (jsdo, success, request) { var xhr = request.xhr; try { request.jsrecord._tableRef.trigger("afterDelete", jsdo, request.jsrecord, request.success, request); jsdo.trigger("afterDelete", jsdo, request.jsrecord, request.success, request); } finally { request.complete = true; jsdo._checkSaveComplete(xhr); } }; this._deleteSuccess = function (jsdo, success, request) { var xhr = request.xhr; var jsonObject = request.response; var beforeJsonObject = null; var dataSetJsonObject = null; var data; //Even though this is _deleteSuccess, if before-image data is returned, the call of // delete operation could return a success, but we have to check if error was returned // in before-image data var hasError = false; if (jsdo._useBeforeImage("delete")) { dataSetJsonObject = jsonObject[jsdo._dataSetName]; beforeJsonObject = dataSetJsonObject["prods:before"]; if (beforeJsonObject) { data = beforeJsonObject[request.jsrecord._tableRef._name]; } } else { data = jsdo._arrayFromDataObject(jsonObject, request.jsrecord._tableRef); } if (data instanceof Array) { if (data.length > 1) { request.success = false; throw new Error(msg.getMsgText("jsdoMSG100")); } } if (beforeJsonObject) { hasError = jsdo._checkForDeleteError(dataSetJsonObject, xhr); } if (hasError) request.success = false; if (jsdo.autoApplyChanges) { if (!hasError) { // Clear before image delete request.jsrecord._tableRef._beforeImage[request.jsrecord.data._id]; // End - Clear before image } else { jsdo._deleteError(jsdo, success, request); } } }; this._deleteError = function (jsdo, success, request) { if (jsdo.autoApplyChanges) { jsdo._undoDelete(request.jsrecord._tableRef, request.jsrecord.data._id); } }; this._createComplete = function (jsdo, success, request) { var xhr = request.xhr; try { request.jsrecord._tableRef.trigger("afterCreate", jsdo, request.jsrecord, request.success, request); jsdo.trigger("afterCreate", jsdo, request.jsrecord, request.success, request ); } finally { request.complete = true; jsdo._checkSaveComplete(xhr); } }; this._createSuccess = function (jsdo, success, request) { var xhr = request.xhr; var record = request.response; var hasError = jsdo._mergeUpdateForCUD(record, xhr); if (hasError) request.success = false; if (jsdo.autoApplyChanges) { if (!hasError) { // Clear before image delete request.jsrecord._tableRef._beforeImage[request.jsrecord.data._id]; // End - Clear before image } else { jsdo._createError(jsdo, success, request); } } }; this._createError = function (jsdo, success, request) { if (jsdo.autoApplyChanges) { jsdo._undoCreate(request.jsrecord._tableRef, request.jsrecord.data._id); } }; this._updateComplete = function (jsdo, success, request) { var xhr = request.xhr; try { request.jsrecord._tableRef.trigger("afterUpdate", jsdo, request.jsrecord, request.success, request); jsdo.trigger("afterUpdate", jsdo, request.jsrecord, request.success, request); } finally { request.complete = true; jsdo._checkSaveComplete(xhr); } }; this._updateSuccess = function (jsdo, success, request) { var xhr = request.xhr; var hasError = jsdo._mergeUpdateForCUD(request.response, xhr); if (hasError) request.success = false; if (jsdo.autoApplyChanges) { if (!hasError) { request.success = true; // Clear before image delete request.jsrecord._tableRef._beforeImage[request.jsrecord.data._id]; // End - Clear before image } else { jsdo._updateError(jsdo, success, request); } } }; this._updateError = function (jsdo, success, request) { var makeSuccessFalse = true; if (jsdo.autoApplyChanges) { request.success = false; jsdo._undoUpdate(request.jsrecord._tableRef, request.jsrecord.data._id); } }; this._saveChangesSuccess = function (jsdo, success, request) { var records = request.response; jsdo._mergeUpdateForSubmit(records, request.xhr); // Save _errorString jsdo._lastErrors = []; var changes = jsdo.getChanges(); jsdo._updateLastErrors(jsdo, null, changes); if (jsdo.autoApplyChanges) { jsdo._applyChanges(); } }; this._saveChangesError = function (jsdo, success, request) { if (jsdo.autoApplyChanges) { jsdo.rejectChanges(); } }; this._saveChangesComplete = function (jsdo, success, request) { // Success with errors if ((request.xhr.status >= 200 && request.xhr.status < 300) && jsdo._lastErrors.length > 0) { request.success = false; } // If saveChanges(true) was called, then we must fire create, update and delete triggers // for each record that was sent to submit operation if (jsdo._useSubmit == true) { jsdo._fireCUDTriggersForSubmit(request); } jsdo._undefWorkingRecord(); jsdo._fireAfterSaveChanges(request.success, request); }; this._fireAfterSaveChanges = function (success, request) { this.trigger("afterSaveChanges", this, success, request); // Now that all event handling triggers have run, can delete the prods properties var clearErrorString = this.autoApplyChanges ? true : false; // This will be set if submit operation was performed if (request.jsrecords) { for (var idx = 0; idx < request.jsrecords.length; idx++) { var jsrecord = request.jsrecords[idx]; this._deleteProdsProperties(jsrecord.data, clearErrorString); } } else if (request.batch && request.batch.operations) { for (var i = 0; i < request.batch.operations.length; i++) { var operRequest = request.batch.operations[i]; this._deleteProdsProperties(operRequest.jsrecord.data, clearErrorString); } } } this._updateLastErrors = function(jsdo, batch, changes) { if (batch) { if (batch.operations == undefined) return; for (var i = 0; i < batch.operations.length; i++) { var request = batch.operations[i]; if (!request.success && request.xhr && request.xhr.status == 500) { var errors = ""; try { var responseObject = JSON.parse(request.xhr.responseText); if (responseObject._errors instanceof Array) { for (var j = 0; j < responseObject._errors.length; j++) { errors += responseObject._errors[j]._errorMsg + '\n'; } } if (responseObject._retVal) { errors += responseObject._retVal; } } catch (e) { // Ignore exceptions } if (request.exception) { if (errors.length == 0) errors = request.exception; else errors += "\n" + request.exception; } jsdo._lastErrors.push({errorString: errors}); } } } else if (changes != undefined && changes.length > 0) { for (var i = 0; i < changes.length; i++) { if (changes[i].record && changes[i].record.data._errorString != undefined) { jsdo._lastErrors.push({errorString: changes[i].record.data._errorString}); } } } }; // Check if all the xhr operations associated with the batch for which // this xhr object is related have completed (not necessarily to success). // If all XHR operations have completed this fires 'afterSaveChanges' event this._checkSaveComplete = function(xhr) { if (xhr.request) { var jsdo = xhr.request.jsdo; var batch = xhr.request.batch; // OE00229270 Should only do afterSaveChanges if _async if (jsdo && batch && jsdo._async) { if (jsdo._isBatchComplete(batch)) { var success = jsdo._isBatchSuccess(batch); var request = { batch : batch, success : success }; jsdo._undefWorkingRecord(); // Save error messages jsdo._lastErrors = []; if (!success && batch.operations) { jsdo._updateLastErrors(jsdo, batch, null); } jsdo._fireAfterSaveChanges(success, request); } } } }; /** * determine if a batch of XHR requests has completed in which all requests are successful * @member _isBatchSuccess */ this._isBatchSuccess = function (batch) { if (batch.operations) { for (var i = 0; i < batch.operations.length; i++) { if (!batch.operations[i].success) { return false; } } } return true; }; /** * determine if all XHR requests from the batch of saves have completed (not necessarily to success) * @member _isBatchComplete */ this._isBatchComplete = function (batch) { if (batch.operations) { for (var i = 0; i < batch.operations.length; i++) { var request = batch.operations[i]; // we have to check against the 'complete' flag because xhr.readyState might be set async by the browser // while we're still in the middle of processing some other requests's response if (!request.complete) { return false; } } } return true; }; this._mergeInvoke = function(jsonObject, xhr) { var operation; if (xhr.request.fnName != undefined && xhr.jsdo._resource.fn[xhr.request.fnName] != undefined) { operation = xhr.jsdo._resource.fn[xhr.request.fnName].operation; } else operation = null; if (operation === undefined) { operation = null; // Operation data is only required for invoke operations with mergeMode: true for (var i=0;i < xhr.jsdo._resource.operations.length; i++) { if (xhr.jsdo._resource.operations[i].name == xhr.request.fnName) { operation = xhr.jsdo._resource.operations[i]; break; } } xhr.jsdo._resource.fn[xhr.request.fnName].operation = operation; } if (operation != null && operation.mergeMode) { try { var mergeMode = progress.data.JSDO["MODE_"+operation.mergeMode.toUpperCase()]; if (mergeMode == null) { throw new Error(msg.getMsgText("jsdoMSG030", "mergeMode property", "EMPTY, APPEND, MERGE or REPLACE")); } if (xhr.jsdo._resource.idProperty == undefined) { throw new Error(msg.getMsgText("jsdoMSG110", this._resource.name, " by mergeMode property in invoke operation")); } var dataParameterName; if (xhr.jsdo.isDataSet()) { dataParameterName = xhr.jsdo._resource._dataSetName; } else if (xhr.jsdo._resource.dataProperty != undefined) { dataParameterName = xhr.jsdo._resource.dataProperty; } else if (xhr.jsdo._resource._tempTableName != undefined) { dataParameterName = xhr.jsdo._resource._tempTableName; } else { throw new Error(msg.getMsgText("jsdoMSG111", "")); } var found = false; for (var i=0;i < operation.params.length; i++) { if (operation.params[i].name == dataParameterName) { if (operation.params[i].type.indexOf('RESPONSE_BODY') != -1) { if ((operation.params[i].xType != undefined) && (operation.params[i].xType != 'DATASET') && (operation.params[i].xType != 'TABLE') && (operation.params[i].xType != 'ARRAY')) { throw new Error(msg.getMsgText("jsdoMSG113", operation.params[i].xType, dataParameterName, xhr.request.fnName)); } found = true; break; } } } if (!found) { throw new Error(msg.getMsgText("jsdoMSG112", dataParameterName, xhr.request.fnName)); } xhr.jsdo.addRecords(xhr.request.response[dataParameterName], mergeMode, [ xhr.jsdo._resource.idProperty ], false, true); } catch (e) { xhr.request.success = false; xhr.request.exception = e; } } }; this.onReadyStateChangeGeneric = function () { var xhr = this; if (xhr.readyState == 4) { var request = xhr.request; /* try to parse response even if request is considered "failed" due to http status */ try { request.response = JSON.parse(xhr.responseText); // in some cases the object back from appserver has a "response" property which represents // the real content of the JSON...happens when multiple output parameters are returned. // this of course assumes no one names their root object "response". if (request.response && request.response.response) { request.response = request.response.response; } } catch(e) { request.response = undefined; } try { if ((xhr.status >= 200 && xhr.status < 300) || (xhr.status == 0 && xhr.responseText != "")) { request.success = true; xhr.jsdo._session._saveClientContextId( xhr ); // get the Client Context ID (AppServer ID) if ((typeof xhr.onSuccessFn) == 'function') { var operation; if (xhr.request.fnName != undefined && xhr.jsdo._resource.fn[xhr.request.fnName] != undefined) { operation = xhr.jsdo._resource.fn[xhr.request.fnName].operation; } else operation = null; if ((operation === undefined) || (operation != null && operation.mergeMode)) xhr.jsdo._mergeInvoke(request.response, xhr); if (request.success) xhr.onSuccessFn(xhr.jsdo, request.success, request); else if ((typeof xhr.onErrorFn) == 'function') xhr.onErrorFn(xhr.jsdo, request.success, request); } } else { request.success = false; if (xhr.status == 0) { request.exception = new Error(msg.getMsgText("jsdoMSG101")); } if ((typeof xhr.onErrorFn) == 'function') { xhr.onErrorFn(xhr.jsdo, request.success, request); } } } catch(e) { request.exception = e; if ((typeof xhr.onErrorFn) == 'function') { xhr.onErrorFn(xhr.jsdo, request.success, request); } } xhr.jsdo._session._checkServiceResponse( xhr, request.success, request ); // get the Client Context ID (AppServer ID) if ((typeof xhr.onCompleteFn) == 'function') { xhr.onCompleteFn(xhr.jsdo, request.success, request); } } }; /** * Accepts changes for all table references in the JSDO. * @member acceptChanges */ this.acceptChanges = function() { for (var buf in this._buffers) { this._buffers[this._buffers[buf]._name].acceptChanges(); } }; /** * Rejects changes for the table references in the JSDO. * @member rejectChanges */ this.rejectChanges = function() { for (var buf in this._buffers) { this._buffers[this._buffers[buf]._name].rejectChanges(); } }; /** * Returns an array with changes for all table references in the JSDO. * @member getChanges */ this.getChanges = function() { var result = []; for (var buf in this._buffers) { var changes = this._buffers[this._buffers[buf]._name].getChanges(); result = result.concat(changes); } return result; }; this.hasChanges = function() { for (var buf in this._buffers) { if (this._buffers[this._buffers[buf]._name].hasChanges()) return true; } return false; } /** * Private method to apply changes for all table references in the JSDO. * If _errorString has been set for a row, rejectRowChanges() is called. * If it has not been set, acceptRowChanges() is called. * @member _applyChanges */ this._applyChanges = function() { for (var buf in this._buffers) { this._buffers[this._buffers[buf]._name]._applyChanges(); } }; /** * Accepts row changes for the working record using the JSDO reference. * @member acceptRowChanges */ this.acceptRowChanges = function () { if (this._defaultTableRef) return this._defaultTableRef.acceptRowChanges(); throw new Error(msg.getMsgText("jsdoMSG001", "acceptRowChanges()")); }; /** * Reject row changes for the working record using the JSDO reference. * @member rejectRowChanges */ this.rejectRowChanges = function () { if (this._defaultTableRef) return this._defaultTableRef.rejectRowChanges(); throw new Error(msg.getMsgText("jsdoMSG001", "rejectRowChanges()")); }; /////////////////////////////////////////////////////////////////////////// // // The following methods provide support for Object Pesistence /** * Saves JSDO memory (and optionally pending changes) to local storage. * * saveLocal() * saveLocal(name) * saveLocal(dataMode) * saveLocal(name, dataMode) * @member saveLocal */ this.saveLocal = function saveLocal(arg1, arg2) { var name; var dataMode; if (arguments.length > 2) { throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", arguments.callee.name + "()")); } if (typeof(arg1) == 'string' || arg1 == undefined) { name = arg1; dataMode = arg2; } else { name = null; dataMode = arg1; } if (typeof(name) == 'undefined' || name == null || name == "") { name = "jsdo_" + this._resource.service.name + "_" + this._resource.name; } if (typeof(dataMode) == 'undefined') { dataMode = progress.data.JSDO.ALL_DATA; } else { switch (dataMode) { case progress.data.JSDO.ALL_DATA: case progress.data.JSDO.CHANGES_ONLY: break; default: throw new Error(msg.getMsgText("jsdoMSG115", arguments.callee.name)); break; } } if (this._localStorage == null) { // Must first instantiate _localStorage object this._localStorage = new progress.data.LocalStorage(); } var dataObj = this._prepareDataObjectForLocalStorage(dataMode); this._localStorage.saveToLocalStorage(name, dataObj); }; /** * Reads localStorage (based upon name) into JSDO memory (localStorage may or may not have pending changes). * * readLocal() * readLocal(name) * @member readLocal */ this.readLocal = function readLocal(name) { if (arguments.length > 1) { throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", arguments.callee.name + "()")); } if (typeof(name) == 'undefined' || name == null || name == "") { name = "jsdo_" + this._resource.service.name + "_" + this._resource.name; } else if (typeof(name) != 'string') { throw new Error(msg.getMsgText("jsdoMSG116", "name", arguments.callee.name + "()")); } if (this._localStorage == null) { this._localStorage = new progress.data.LocalStorage(); } var object = this._localStorage.readFromLocalStorage(name); // If storage area does not exist (i.e. object = null) then don't update JSDO local memory if (object) { if (this._hasMatchingSchema(object) == false) throw new Error(msg.getMsgText("jsdoMSG117", name)); // For readLocal(), JSDO should first be emptied of data, so using MODE_EMPTY this._restoreFromLocalStorage(object, progress.data.JSDO.MODE_EMPTY); } return object != null; }; /** * Reads localStorage (based upon name) into JSDO memory (localStorage may or may not have pending changes). * * addLocalRecords(addMode) * addLocalRecords(addMode, keyFields) * addLocalRecords(name, addMode) * addLocalRecords(name, addMode, keyFields) * @member addLocalRecords */ this.addLocalRecords = function addLocalRecords(arg1, arg2, arg3) { var name; var addMode; var keyFields; if (arguments.length < 1) { throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", arguments.callee.name + "()")); } if (typeof(arg1) == 'string') { name = arg1; addMode = arg2; keyFields = arg3; } else { name = "jsdo_" + this._resource.service.name + "_" + this._resource.name; addMode = arg1; keyFields = arg2; } if (typeof(name) == 'undefined' || name == null || name == "") { name = "jsdo_" + this._resource.service.name + "_" + this._resource.name; } else if (typeof(name) != 'string') { throw new Error(msg.getMsgText("jsdoMSG116", "name", arguments.callee.name + "()")); } switch (addMode) { case progress.data.JSDO.MODE_REPLACE: break; default: throw new Error(msg.getMsgText("jsdoMSG115", arguments.callee.name)); break; } if (this._localStorage == null) { this._localStorage = new progress.data.LocalStorage(); } var object = this._localStorage.readFromLocalStorage(name); // If storage area does not exist (i.e. object = null) then don't update JSDO local memory if (object) { if (this._hasMatchingSchema(object) == false) throw new Error(msg.getMsgText("jsdoMSG117", name)); try { this._restoreFromLocalStorage(object, addMode, keyFields); } catch (e) { var text = e.message; throw new Error(text.replace(new RegExp('addRecords','g'), 'addLocalRecords')); } } return object != null; } /** * This method returns True if each buffer in the jsdo contains a primary key. * @member _containsPrimaryKeys */ this._containsPrimaryKeys = function _containsPrimaryKeys() { for (var buf in this._buffers) { if (this._buffers[buf]._primaryKeys == null) return false; } return true; } /** * Compares JSDO's dataset/table names with those in specified storage object. * Returns true if they match (or if storageObject is null or empty), else false. * @member _hasMatchingSchema */ this._hasMatchingSchema = function _hasMatchingSchema(storageObject) { var isValid = true; if (storageObject == null || (Object.keys(storageObject).length == 0)) return true; if (this._dataSetName) { if (storageObject[this._dataSetName]) { for (var buf in this._buffers) if (storageObject[this._dataSetName][buf] == undefined) { isValid = false; break; } } else isValid = false; // dataset should be in storage area } else if (this._dataProperty) { // If array, we had to wrap in "fake" dataset, so unwrap it storageObject = storageObject["_localStorage"]; if (storageObject == undefined || storageObject[this._dataProperty] == undefined) isValid = false; } else { // If temp-table, we had to wrap in "fake" dataset, so unwrap it storageObject = storageObject["_localStorage"]; if (storageObject == undefined || storageObject[this._defaultTableRef._name] == undefined) isValid = false; } return isValid; } /** * Clears the data saved to local storage. * * deleteLocal() * deleteLocal(name) * @member deleteLocal */ this.deleteLocal = function deleteLocal(name) { if (arguments.length > 1) { throw new Error(msg.getMsgText("jsdoMSG024", "JSDO", arguments.callee.name + "()")); } if (typeof(name) == 'undefined' || name == null || name == "") { name = "jsdo_" + this._resource.service.name + "_" + this._resource.name; } else if (typeof(name) != 'string') { throw new Error(msg.getMsgText("jsdoMSG116", "name", arguments.callee.name + "()")); } if (this._localStorage == null) { this._localStorage = new progress.data.LocalStorage(); } this._localStorage.clearLocalStorage(name); } // This method is used by saveLocal() to return a jsonObject with current JSDO data based upon option. // // In order to take advantage of existing code (createChangeSet() and addRecords()) and particularly // to use the processing of before-data in addRecords(), for tables and arrays, we create a dummy // dataset name: _localStorage. this._prepareDataObjectForLocalStorage = function(option) { var storageObject = {}; // DataSets if (this._dataSetName) { switch(option) { case progress.data.JSDO.ALL_DATA: storageObject = this._createDataAndChangeSet(this._dataSetName); break; case progress.data.JSDO.CHANGES_ONLY: storageObject = this._createChangeSet(this._dataSetName, true); break; } } // Arrays else if (this._dataProperty) { switch(option) { case progress.data.JSDO.ALL_DATA: storageObject = this._createDataAndChangeSet("_localStorage"); break; case progress.data.JSDO.CHANGES_ONLY: storageObject = this._createChangeSet("_localStorage", true); break; } } // Temp Tables else { switch(option) { case progress.data.JSDO.ALL_DATA: storageObject = this._createDataAndChangeSet("_localStorage"); break; case progress.data.JSDO.CHANGES_ONLY: storageObject = this._createChangeSet("_localStorage", true); break; } } return storageObject; }; // Restore the data retrieved from local storage to the JSDO based upon the specified addMode this._restoreFromLocalStorage = function(storageObject, addMode, keyFields) { if (storageObject && (Object.keys(storageObject).length > 0)) { if (this._dataSetName) { // Walk thru all tables to retrieve data for (var buf in this._buffers) this._restoreDataForTable(this._buffers[buf], storageObject, addMode, keyFields); } // Either temp-table or array else this._restoreDataForTable(this._defaultTableRef, storageObject, addMode, keyFields); } else if (addMode === progress.data.JSDO.MODE_EMPTY) this._clearData(); }; this._restoreDataForTable = function(tableRef, jsonObject, addMode, keyFields) { // If primaryKeys not found, check if the idProperty is there keyFields = keyFields != undefined ? keyFields : tableRef._primaryKeys; if (keyFields == undefined && this._resource.idProperty) { keyFields = []; keyFields[0] = this._resource.idProperty; } if (this._dataSetName) { var oldUseRelationships = this.useRelationships; // Turn off useRelationships since addRecords() does not use the working record this.useRelationships = false; try { tableRef.addRecords(jsonObject, addMode, keyFields); } finally { // Restore useRelationships this.useRelationships = oldUseRelationships; } } // else it's either an array (this._dataProperty) or a temp-table else { // Creating dummy dataset name: "_localStorage" for tables and arrays this._dataSetName = "_localStorage"; tableRef.addRecords(jsonObject, addMode, keyFields); this._dataSetName = null; } } /////////////////////////////////////////////////////////////////////////// // Load data if (autoFill) this.fill(); }; // End of JSDO // Constants for progress.data.JSDO if ((typeof Object.defineProperty) == 'function') { Object.defineProperty(progress.data.JSDO, 'MODE_APPEND', { value : 1, enumerable : true }); Object.defineProperty(progress.data.JSDO, 'MODE_EMPTY', { value : 2, enumerable : true }); Object.defineProperty(progress.data.JSDO, 'MODE_MERGE', { value : 3, enumerable : true }); Object.defineProperty(progress.data.JSDO, 'MODE_REPLACE', { value : 4, enumerable : true }); } else { progress.data.JSDO.MODE_APPEND = 1; progress.data.JSDO.MODE_EMPTY = 2; progress.data.JSDO.MODE_MERGE = 3; progress.data.JSDO.MODE_REPLACE = 4; } /* CRUD */ progress.data.JSDO._OP_CREATE = 1, progress.data.JSDO._OP_READ = 2, progress.data.JSDO._OP_UPDATE = 3, progress.data.JSDO._OP_DELETE = 4, progress.data.JSDO._OP_SUBMIT = 5; /* Offline support: saving data to local storage */ progress.data.JSDO.ALL_DATA = 1; progress.data.JSDO.CHANGES_ONLY = 2; // setup inheritance for JSDO progress.data.JSDO.prototype = new progress.util.Observable(); progress.data.JSDO.prototype.constructor = progress.data.JSDO; progress.data.JSDO.prototype.toString = function( radix ){ return "JSDO"; }; // setup inheritance for table reference progress.data.JSTableRef.prototype = new progress.util.Observable(); progress.data.JSTableRef.prototype.constructor = progress.data.JSTableRef; progress.data.JSTableRef.prototype.toString = function( radix ){ return "JSTableRef"; }; if (typeof progress.ui == 'undefined') progress.ui = {}; /** * UITableRef class * @class UITableRef * @constructor */ progress.ui.UITableRef = function UITableRef(tableRef) { this._tableRef = tableRef; this._listview = null; this._detailPage = null; this._listviewContent = undefined; this.addItem = function(format) { var detailForm; if (!this._tableRef.record) throw new Error(msg.getMsgText("jsdoMSG002", this._name)); if (!this._listview) return; format = format ? format : this._listview.format; detailForm = (this._detailPage && this._detailPage.name) ? this._detailPage.name : ""; if (this._listviewContent === undefined) { this.clearItems(); } var text = this._listview.itemTemplate ? this._listview.itemTemplate : progress.ui.UIHelper._itemTemplate; text = text.replace( new RegExp('{__format__}', 'g'), format); text = text.replace( new RegExp('{__id__}', 'g'), this._tableRef.record.data._id); text = text.replace( new RegExp('{__page__}', 'g'), detailForm); for (field in this._tableRef.record.data) { var value = this._tableRef.record.data[field]; text = text.replace( new RegExp('{' + field + '}', 'g'), value != null ? value : ""); } this._listviewContent += text; }; this.clearItems = function() { if (this._listview) { this._listviewContent = ''; var listviewElement = document.getElementById(this._listview.name); if (listviewElement) { listviewElement.innerHTML = ''; } } }; this._getFormFieldValue = function (fieldName, detailPageName) { var value = null; if (detailPageName == undefined) { if (this._detailPage && this._detailPage.name) detailPageName = this._detailPage.name; } if (typeof($) == 'function' && detailPageName) { field = $("#" + detailPageName + " #" + fieldName); if (!field || field.length == 0) field = $("#" + detailPageName + ' [dsid="' + fieldName + '"]'); if (field && field.length == 1) value = field.val(); } else { field = document.getElementById(fieldName); if (field) { value = field.value; } } return value; }; this._setFormField = function (fieldName, value, detailPageName) { var field = null; if (detailPageName == undefined) { if (this._detailPage && this._detailPage.name) detailPageName = this._detailPage.name; } if (typeof($) == 'function' && detailPageName) { field = $("#" + detailPageName + " #" + fieldName); if (!field || field.length == 0) field = $("#" + detailPageName + ' [dsid="' + fieldName + '"]'); if (field && field.length == 1) field.val(value); } else { field = document.getElementById(fieldName); if (field) { field.value = value; } } }; /** * Assigns field values from the form. * @member assign */ this.assign = function (detailPageName) { if (!this._tableRef.record) throw new Error(msg.getMsgText("jsdoMSG002", this._tableRef._name)); if ((arguments.length != 0) && (typeof detailPageName != 'string')) throw new Error(msg.getMsgText("jsdoMSG024", "UIHelper", "assign()")); // Ensure creation of before image record this._tableRef.record.assign(null); var fieldName; var schema = this._tableRef.getSchema(); for(var i = 0; i < schema.length; i++) { fieldName = schema[i].name; if (fieldName == '_id') continue; var value =this._getFormFieldValue(fieldName, detailPageName); // CR OE00241289 Should always copy over field value unless undefined, user may have explicitly set it to blank if (typeof value != 'undefined') { if (typeof value == 'string' && schema[i].type != 'string') { value = this._tableRef._jsdo._convertType(value, schema[i].type, schema[i].items ? schema[i].items.type : null); } this._tableRef.record.data[fieldName] = value; } } // Ensure order of record this._tableRef.record._sortRecord(); return true; }; this.display = function (pageName) { if (!this._tableRef.record) throw new Error(msg.getMsgText("jsdoMSG002", this._tableRef._name)); // Display record to form var schema = this._tableRef.getSchema(); for(var i = 0; i < schema.length; i++) { this._setFormField(schema[i].name, this._tableRef.record.data[schema[i].name], pageName); } this._setFormField('_id', this._tableRef.record.data._id, pageName); }; this.showListView = function () { if (!this._listview) return; var uiTableRef = this; var listviewElement; if (typeof($) == 'function') { listviewElement = $("#"+this._listview.name); if (listviewElement && listviewElement.length == 1) { listviewElement.html(this._listviewContent ? this._listviewContent : ''); try { if (listviewElement.attr("data-filter") === "true" && typeof listviewElement.filterable === "function") { listviewElement.filterable("refresh"); } else { listviewElement.listview("refresh"); } } catch(e) { // Workaround for issue with JQuery Mobile throwning exception on refresh } } if (this._listview.autoLink) { // Add trigger for 'tap' event to items $("#" + this._listview.name + " li").each ( function (index) { $(this).bind('click', function (event,ui) { var jsrecord = uiTableRef.getListViewRecord(this); uiTableRef.display(); if (typeof(uiTableRef._listview.onSelect) == 'function') { uiTableRef._listview.onSelect(event, this, jsrecord); } }); }); } } else { listviewElement = document.getElementById(this._listview.name); if (listviewElement) { listviewElement.innerHTML = this._listviewContent; } if (this._listview.autoLink) { var element = document.getElementById(this._listview.name); if (element && element.childElementCount > 0) { for (var i = 0; i < element.children.length; i++) { element.children[i].onclick = function() { var jsrecord = uihelper.getListViewRecord(this); uihelper.display(); if (typeof(uiTableRef._listview.onSelect) == 'function') { uiTableRef._listview.onSelect(event, this, jsrecord); } }; } } } } this._listviewContent = undefined; }; this.getFormFields = function (fields) { if (!this._tableRef._schema) return ''; if (!(fields instanceof Array)) fields = null; else { var tmpFields = {}; for (var i = 0; i < fields.length; i++) { tmpFields[fields[i]] = fields[i]; } fields = tmpFields; } var htmltext; if (!fields || fields['_id']) { htmltext = ''; } else htmltext = ''; htmltext += '
    '; for(var i = 0; i < this._tableRef._schema.length; i++) { var fieldName = this._tableRef._schema[i].name; if (fieldName == '_id') continue; if (fieldName.length > 0 && fieldName.charAt(0) == '_') continue; if (fields && fields[fieldName] === undefined) continue; var fieldLabel = this._tableRef._schema[i].title ? this._tableRef._schema[i].title : this._tableRef._schema[i].name; var text = (this._detailPage && this._detailPage.fieldTemplate) ? this._detailPage.fieldTemplate : progress.ui.UIHelper._fieldTemplate; text = text.replace( new RegExp('{__label__}', 'g'), fieldLabel); text = text.replace( new RegExp('{__name__}', 'g'), this._tableRef._schema[i].name); htmltext += text; } htmltext += '
    '; fields = null; return htmltext; }; this.getListViewRecord = function(htmlIElement) { var id = htmlIElement.getAttribute('data-id'); return this._tableRef.findById(id); }; this.getFormRecord = function(detailPageName) { var id = this._getFormFieldValue('_id', detailPageName); return this._tableRef.findById(id); }; this._getIdOfElement = function(name) { if (typeof($) == 'function') { var element = $("#" + name); if (!element || element.length == 0) { element = $('[dsid="' + name + '"]'); if (element && element.length == 1) { var id = element.attr("id"); if (id) return id; } } } return name; }; this.setDetailPage = function setDetailPage(obj) { if (!obj || (typeof(obj) != 'object')) throw new Error(msg.getMsgText("jsdoMSG012", arguments.callee.name, "object")); if (!obj.name || (typeof(obj.name) != 'string')) throw new Error(msg.getMsgText("jsdoMSG012", arguments.callee.name, "name")); this._detailPage = obj; this._detailPage.name = this._getIdOfElement(this._detailPage.name); }; this.setListView = function setListView(obj) { if (!obj || (typeof(obj) != 'object')) throw new Error(msg.getMsgText("jsdoMSG012", arguments.callee.name, "object")); if (!obj.name || (typeof(obj.name) != 'string')) throw new Error(msg.getMsgText("jsdoMSG012", arguments.callee.name, "name")); if (obj.format && (typeof(obj.name) != 'string')) throw new Error(msg.getMsgText("jsdoMSG012", arguments.callee.name, "format")); this._listview = obj; this._listview.name = this._getIdOfElement(this._listview.name); if (!this._listview.format) { if (typeof($) == 'function') { for(var i = 0; i < this._tableRef._schema.length; i++) { var fieldName = this._tableRef._schema[i].name; field = $("#" + this._listview.name + ' [dsid="' + fieldName + '"]'); if (field && field.length == 1) { field.html('{' + fieldName + '}'); } } } var text = document.getElementById(this._listview.name).innerHTML; var pos = text.indexOf('
  • = 0 ) { _pingInterval = newval; if ( newval > 0) { _timeoutID = setTimeout( this._autoping, newval); } else if ( newval === 0 ) { clearTimeout( _timeoutID ); _pingInterval = 0; } else { throw new Error("Error setting Session.pingInterval. '" + newval + "' is an invalid value."); } } }, enumerable: true } ); } else { this.userName = null; this.loginTarget= '/static/home.html'; this.serviceURI = null; this.catalogURIs = []; this.services = []; this.loginResult = null; this.loginHttpStatus = null; this.clientContextId = null; this.authenticationModel = progress.data.Session.AUTH_TYPE_ANON; this.lastSessionXHR = null; } function setUserName(newname, sessionObject) { if (defPropSupported) { _userName = newname; } else { sessionObject.userName = newname; } } function setLoginTarget(target, sessionObject) { if (defPropSupported) { _loginTarget = target; } else { sessionObject.loginTarget = target; } } function setServiceURI(url, sessionObject) { if (defPropSupported) { _serviceURI = url; } else { sessionObject.serviceURI = url; } } function pushCatalogURIs( url, sessionObject ) { if (defPropSupported) { _catalogURIs.push(url); } else { sessionObject.catalogURIs.push(url); } } function pushService( serviceObject, sessionObject ) { if (defPropSupported) { _services.push( serviceObject); } else { sessionObject.services.push( serviceObject ); } } function findService( serviceName ) { for (var prop in _services) { var srv = _services[prop]; if (srv.name === serviceName) { return srv; } } return null; } function setLoginResult( result, sessionObject ) { if (defPropSupported) { _loginResult = result; } else { sessionObject.loginResult = result; } } function setLoginHttpStatus( status, sessionObject ) { if (defPropSupported) { _loginHttpStatus = status; } else { sessionObject.loginHttpStatus = status; } } function setClientContextIDfromXHR ( xhr, sessionObject ) { if ( xhr ) { setClientContextID( xhr.getResponseHeader( "X-CLIENT-CONTEXT-ID" ), sessionObject ); } }; function setClientContextID ( ccid, sessionObject ) { if (defPropSupported) { _clientContextId = ccid; } else { sessionObject.clientContextId = ccid; } }; function setLastSessionXHR ( xhr, sessionObject ) { if (defPropSupported) { _lastSessionXHR= xhr; } else { sessionObject.lastSessionXHR = xhr; }; }; // "Methods" this._pushJSDOs = function( jsdo ) { _jsdos.push(jsdo); }; /** (intended for progress.data library use only) * calls open() for an xhr -- the assumption is that this is an xhr for a JSDO, and we need to add * some session management information for the request, such as user credentials and a session ID if * there is one * @member _openRequest */ this._openRequest = function (xhr, verb, url, async) { if ( this.loginResult !== progress.data.Session.LOGIN_SUCCESS && this.authenticationModel ) { throw new Error("Attempted to make server request when there is no active session."); } // if resource url is not absolute, add the REST app url to the front var urlPlusCCID = this._prependAppURL( url ); // add CCID as JSESSIONID query string to url urlPlusCCID = this._addCCIDtoURL( urlPlusCCID ); // add time stamp to the url if (progress.data.Session._useTimeStamp) urlPlusCCID = this._addTimeStampToURL( urlPlusCCID ); this._setXHRCredentials( xhr, verb, urlPlusCCID, this.userName, _password, async); if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { _addWithCredentialsAndAccept( xhr, "application/json" ); } // add CCID header if ( this.clientContextId && (this.clientContextId !== "0") ) { xhr.setRequestHeader( "X-CLIENT-CONTEXT-ID", this.clientContextId); } if ( this.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", this.xClientProps); } if (typeof this.onOpenRequest === 'function') { var params = { "xhr": xhr, "verb": verb, "uri": urlPlusCCID, "async": async, "formPreTest": false, "session": this }; this.onOpenRequest( params ); // xhr = params.xhr; //Note that, currently, this would have no effect in the caller. } }; /* * login */ // callback used in login to determine whether ping is available on server this.pingTestCallback = function( cbArgs ) { if (cbArgs.pingResult) { oepingAvailable = true; } else { oepingAvailable = false; }; }; // generic async callback, currently used by login(), addCatalog(), and logout() this._onReadyStateChangeGeneric = function () { var xhr = this; var result; var errorObject; if (xhr.readyState == 4) { result = null; errorObject = null; // initial processing of the response from the Web application if ((typeof xhr.onResponseFn) == 'function') { try { result = xhr.onResponseFn(xhr); // ( note that result will remain null if this is a logout() ) } catch(e) { errorObject = e; } } // handle the results of the processing (e.g., fire any events required) if ((typeof xhr.onResponseProcessedFn) == 'function') { if ( !result ) { result = progress.data.Session.GENERAL_FAILURE; } xhr.onResponseProcessedFn(xhr.pdsession, result, errorObject); } } }; var pwSave = null; // store password here until successful login; only then do we store it in the Session object var unameSave = null; // store user name here until successful login; only then do we store it in the Session object this.login = function ( serviceURI, loginUserName, loginPassword, loginTarget ) { var uname; var pw; var isAsync = false; var args = []; pwSave = null; // in case these are left over from a previous login unameSave = null; if ( this.loginResult === progress.data.Session.LOGIN_SUCCESS) { throw new Error("Attempted to call login() on a Session object that is already logged in."); } if ( !defPropSupported ) { // this is here on the presumably slim chance that we're running with a // version of JavaScript that doesn't support defineProperty (otherwise // the lower casing will have already happened). When we decide that it's // OK to remove our conditionalization of property definitions, we should // get rid of this whole conditional this.authenticationModel = this.authenticationModel.toLowerCase(); } if ( arguments.length > 0) { if ( arguments[0] && typeof(arguments[0]) === 'object') { if (arguments[0].serviceURI) { args[0] = arguments[0].serviceURI; args[1] = arguments[0].userName; args[2] = arguments[0].password; args[3] = arguments[0].loginTarget; args[4] = arguments[0].async; } } else { args = arguments; } } if ( args.length > 0) { if ( args[0] ) { var restURLtemp = args[0]; // get rid of trailing '/' because appending service url that starts with '/' // will cause request failures if ( restURLtemp[restURLtemp.length - 1] === "/") { restURLtemp = restURLtemp.substring(0, restURLtemp.length - 1); } setServiceURI( restURLtemp, this ); } else { setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, this); throw new Error( "Session.login() is missing the serviceURI argument." ); } if ( args[1] ) { uname = args[1]; } if ( args[2]) { pw = args[2]; } if ( args[3]) { setLoginTarget(args[3], this); } if ( args[4]) { if ( typeof(args[4]) === 'boolean' ) { isAsync = args[4]; } else { throw new Error("Session.login() was passed an async setting that is not a boolean."); } } } else { setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, this); throw new Error( "Session.login() is missing the serviceURI argument." ); } // use these temp cred variables later; if login succeeds, we'll use them to set the // real credentials unameSave = uname; pwSave = pw; if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_ANON || this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { /* anonymous should NOT have a username and password passed (this is probably unnecessary because the XHR seems to send the request without credentials first, then intercept the 401 if there is one and try again, this time with credentials. Just making sure. */ /* For form authentication, we may as well not send the user name and password * on this request, since we are just trying to test whether the authentication * has already happened and they are therefore irrelevant */ uname = null; pw = null; } var xhr = new XMLHttpRequest(); xhr.pdsession = this; try { this._setXHRCredentials( xhr, 'GET', this.serviceURI + this.loginTarget, uname, pw, isAsync); xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("Pragma", "no-cache"); if ( this.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", this.xClientProps); } if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { _addWithCredentialsAndAccept( xhr, "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } xhr._isAsync = isAsync; if (isAsync ) { xhr.onreadystatechange = this._onReadyStateChangeGeneric; if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { xhr.onResponseFn = this._afterFormPretestLogin; } else { xhr.onResponseFn = this._processLoginResult; xhr.onResponseProcessedFn = this._loginComplete; } } if (typeof this.onOpenRequest === 'function') { var isFormPreTest = false; if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { isFormPreTest = true; } // set this here in case onOpenRequest checks it setLastSessionXHR (xhr, this); var params = { "xhr": xhr, "verb": "GET", "uri": this.serviceURI + this.loginTarget, "async": false, "formPreTest": isFormPreTest, "session": this }; this.onOpenRequest( params ); xhr = params.xhr; // just in case it has been changed } setLastSessionXHR (xhr, this); xhr.send(null); } catch (e) { setLoginHttpStatus(xhr.status, this); setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, this); unameSave = null; pwSave = null; throw e; } if (isAsync) { return progress.data.Session.ASYNC_PENDING; } else { setLoginHttpStatus(xhr.status, this); if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { return (this._afterFormPretestLogin(xhr) ); } else { return (this._processLoginResult(xhr) ); } } }; this._afterFormPretestLogin = function( xhr ) { var pdsession = xhr.pdsession; setLoginHttpStatus(xhr.status, xhr.pdsession); var formLoginParams = { "xhr": xhr, "pw": pwSave, "uname": unameSave, "theSession": pdsession}; try { return doFormLogin( formLoginParams ); } catch(e) { pwSave = null; unameSave = null; throw e; } }; /** * This function handles logging in to a service that uses form-based authentication. It's separate * from the main login function because it's long. One of the things it does is examine the * response from an initial attempt to get the login target without credentials (done in the main * login() function) to determine whether the user has already been authenticated. Although a * current OE Mobile Web application (as of 5/30/2013) will return an error if authentication * failed on a form login, previous versions and non-OE servers return a * redirect to a login page and the user agent (browser or native wrapper) * usually then fetches the redirect location and returns it along with a * 200 Success status, when in fcat it was an authentication failure. Hence * the need to analyze the response to try to figure out what we get back. * @member doFormLogin */ function doFormLogin ( args ){ var xhr = args.xhr; var theSession = args.theSession; var oldXHR; // check whether we got the OE REST Form based error response var contentType = null; var needAuth = false; var params = { "session": theSession, "xhr": xhr, "statusFromjson": null }; contentType = xhr.getResponseHeader( "Content-Type" ); if ( contentType && contentType.indexOf("application/json") >= 0 ) { handleJSONLoginResponse( params ); if ( !params.statusFromjson || params.statusFromjson === 401) { needAuth = true; } else { // either the response shows that we're already authenticated, or // there's some error other than an authentication error setLoginHttpStatus(params.statusFromjson, theSession); } } else { if (theSession.loginHttpStatus == 200 ) { // need to do only 200 for async to work with MWA down if (_gotLoginForm(xhr) ) { needAuth = true; } // else we are assuming we truly retrieved the login target and // therefore we were previously authenticated } // else had an error, just return it } if ( needAuth ) { // create new XHR, because if this is an async call we don't want to // confuse things by using this xhr to send another request while we're // still processing its old request (this function, doFormLogin(), may // have been called from onReadyStateChangeGeneric and it's conceivable // that that function has more code to execute involving this xhr) oldXHR = xhr; xhr = new XMLHttpRequest(); args.xhr = xhr; params.xhr = xhr; // need to transfer any properties that the Sessioon code stored in the // the xhr that need to persist across the 2 requests made by a our // login implementation for Form auth xhr.pdsession = oldXHR.pdsession; xhr._isAsync = oldXHR._isAsync; xhr.open('POST', theSession.serviceURI + "/static/auth/j_spring_security_check", xhr._isAsync); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.setRequestHeader("Cache-Control", "max-age=0"); if ( theSession.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", theSession.xClientProps); } _addWithCredentialsAndAccept( xhr, "application/json" ); try { // Note: this gives a developer a way to change certain aspects of how we do the form-based // login, but we will still be assuming that we are going directly to // j_spring_security_check and including credentials in the body. They really should not // try to change that. // if (typeof theSession.onOpenRequest === 'function') { var cbparams = { "xhr": xhr, "verb": "POST", "uri": theSession.serviceURI + "/static/auth/j_spring_security_check", "async": xhr._isAsync, "formPreTest": false, "session": theSession }; theSession.onOpenRequest( cbparams ); xhr = cbparams.xhr; } if (xhr._isAsync) { xhr.onreadystatechange = theSession._onReadyStateChangeGeneric; xhr.onResponseFn = theSession._afterFormLogin; xhr.onResponseProcessedFn = theSession._loginComplete; } // j_username=username&j_password=password&submit=Submit xhr.send("j_username=" + args.uname + "&j_password=" + args.pw + "&submit=Submit"); } catch(e) { setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, theSession); setLoginHttpStatus(xhr.status, theSession); // null the temporary credentials variables unameSave = null; pwSave = null; throw e; } } if ( xhr._isAsync && !needAuth ) { xhr.onResponseProcessedFn = theSession._loginComplete; return theSession._afterFormLogin( xhr ); } if ( !xhr._isAsync ) { return theSession._afterFormLogin( xhr ); } }; this._afterFormLogin = function( xhr ){ // check what we got var theSession = xhr.pdsession; var params = { "session": theSession, "xhr": xhr, "statusFromjson": null }; var contentType = xhr.getResponseHeader( "Content-Type" ); if ( contentType && contentType.indexOf("application/json") >= 0 ) { handleJSONLoginResponse( params); if ( !params.statusFromjson ) { throw new Error( "Internal OpenEdge Mobile client error handling login response. HTTP status: " + xhr.status + "."); } else { setLoginHttpStatus(params.statusFromjson, theSession); } } else { if (xhr.status == 200 || xhr.status == 0) { // Was the response actually the login failure page or the login page itself (in case // the appSecurity config file sets the login failure url so the server sends the login // page again)? If so, call it an error because the credentials apparently failed to be // authenticated if ( _gotLoginFailure(xhr) || _gotLoginForm(xhr) ) { setLoginHttpStatus(401, theSession); } else { setLoginHttpStatus(xhr.status, theSession); } } } return theSession._processLoginResult( xhr ); }; this._processLoginResult = function( xhr ) { /* OK, one way or another, by hook or by crook, the Session object's loginHttpStatus * has been set to the value that indicates the real outcome of the * login, after adjusting for form-based authentication and anything * else. At this point, it should be just a matter of examining * this.loginHttpStatus, using it to set this.loginResult, maybe doing * some other work appropriate to the outcome of the login, and returning * this.loginResult. */ var pdsession = xhr.pdsession; setLoginHttpStatus(xhr.status, xhr.pdsession); if (pdsession.loginHttpStatus == 200) { setLoginResult(progress.data.Session.LOGIN_SUCCESS, pdsession); restApplicationIsOnline = true; setUserName( unameSave, pdsession); _password = ; pdsession._saveClientContextId( xhr ); var pingTestArgs = { pingURI : null, async : true, onCompleteFn : null, fireEventIfOfflineChange : true, onReadyStateFn : pdsession._pingtestOnReadyStateChange }; pingTestArgs.pingURI = pdsession._makePingURI( ); pdsession._sendPing( pingTestArgs ); // see whether the ping feature is available } else { if (pdsession.loginHttpStatus == 401) { setLoginResult(progress.data.Session.LOGIN_AUTHENTICATION_FAILURE, pdsession); } else { setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, pdsession); } } setLastSessionXHR (xhr, pdsession); // null the temporary credentials variables unameSave = null; pwSave = null; // return loginResult even if it's an async operation -- the async handler // (e.g., onReadyStateChangeGeneric) will just ignore return pdsession.loginResult; }; this._loginComplete = function ( pdsession, result, errObj ) { pdsession.trigger("afterLogin", pdsession, result, errObj ); }; /** * logout * @member logout */ this.logout = function () { var isAsync = false; var errorObject = null; var xhr = null; if ( this.loginResult !== progress.data.Session.LOGIN_SUCCESS && this.authenticationModel ) { throw new Error("Attempted to call logout when there is no active session."); } if ( arguments.length > 0) { if (typeof(arguments[0]) === 'object') { isAsync = arguments[0].async; if ( isAsync && (typeof isAsync != 'boolean') ) { throw new Error(jsdoMSG033, 'Session', 'logout', 'The async argument was invalid.'); } } } var xhr = new XMLHttpRequest(); xhr.pdsession = this; try { /* logout when auth model is anonymous is a no-op on the server side */ if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM || this.authenticationModel === progress.data.Session.AUTH_TYPE_BASIC) { if (isAsync) { xhr.onreadystatechange = this._onReadyStateChangeGeneric; xhr.onResponseFn = this._processLogoutResult; xhr.onResponseProcessedFn = this._logoutComplete; } xhr.open('GET', this.serviceURI + "/static/auth/j_spring_security_logout", false); /* instead of calling _addWithCredentialsAndAccept, we code the withCredentials * and setRequiestHeader inline so we can do it slightly differently. That * function deliberately sets the request header inside the try so we don't * run into a FireFox oddity that would give us a successful login and then * a failure on getCatalog (see the comment on that function). On logout, * however, we don't care -- just send the Accept header so we can get a 200 * response */ try { xhr.withCredentials = true; } catch(e){} xhr.setRequestHeader("Accept", "application/json"); if ( this.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", this.xClientProps); } if (typeof this.onOpenRequest === 'function') { setLastSessionXHR (xhr, this); var params = { "xhr": xhr, "verb": "GET", "uri": this.serviceURI + "/static/auth/j_spring_security_logout", "async": false, "formPreTest": false, "session": this }; this.onOpenRequest( params ); xhr = params.xhr; } setLastSessionXHR (xhr, this); xhr.send(); } else { xhr._anonymousLogoutOK = true; } } catch(e) { this._reinitializeAfterLogout( this, false); throw e; } if ( !isAsync ) { try { this._processLogoutResult( xhr ); } catch(e) { throw e; } } if (isAsync && this.authenticationModel === progress.data.Session.AUTH_TYPE_ANON ) { // fake async for Anonymous -- fire afterLogout event try { this._processLogoutResult( xhr ); } catch(e) { errorObject = e; } this._logoutComplete(this, null, errorObject); } }; this._logoutComplete = function( pdsession, result, errorObject ) { // ignore result, it doesn't apply to logout -- is probably null or GENERAL_FAILURE // we include it so onReadyStateChangeGeneric calls this correctly pdsession.trigger("afterLogout", pdsession, errorObject ); }; this._processLogoutResult = function( xhr ) { var logoutSucceeded; var pdsession = xhr.pdsession; var basicStatusOK = false; if ( xhr._anonymousLogoutOK ) { logoutSucceeded = true; } else if ( (xhr.status != 200) && (xhr.status != 0) ) { /* Determine whether an error returned from the server is really an error * Errors on logout from any auth model will go through here, but * only Basic requires checking. */ if ( pdsession.authenticationModel === progress.data.Session.AUTH_TYPE_BASIC ) { /* If the Auth model is Basic, we probably got back a 404 Not found. * But that's OK, because logout from Basic is meaningless on the * server side unless it happens to be stateful, which is the only * reason we even try calling j_spring_security_logout */ if ( xhr.status === 404 ) { logoutSucceeded = true; } else { logoutSucceeded = false; throw new Error("Error logging out, HTTP status = " + xhr.status); } } } else { logoutSucceeded = true; } pdsession._reinitializeAfterLogout( pdsession, logoutSucceeded); }; this._reinitializeAfterLogout = function( pdsession, success) { setLoginResult( null, pdsession ); setLoginHttpStatus( null, pdsession); setClientContextID ( null, pdsession ); setUserName( null, pdsession); _password = ; if ( success ) { oepingAvailable = false; partialPingURI = defaultPartialPingURI; setLastSessionXHR (null, pdsession); } }; /** * addCatalog * @member addCatalog */ this.addCatalog = function ( ) { var catalogURI; var catalogUserName; var catalogPassword; var isAsync = false; if ( this.loginResult !== progress.data.Session.LOGIN_SUCCESS && this.authenticationModel ) { throw new Error("Attempted to call addCatalog when there is no active session."); } // check whether the args were passed in a single object. If so, copy them // to the named arguments and a variable if ( arguments.length > 0) { if (typeof(arguments[0]) === 'object') { catalogURI = arguments[0].catalogURI; if ( !catalogURI || (typeof catalogURI != 'string') ) { throw new Error(jsdoMSG033, 'Session', 'addCatalog', 'The catalogURI argument was missing or invalid.'); } catalogUserName = arguments[0].userName; if ( catalogUserName && (typeof catalogUserName != 'string') ) { throw new Error(jsdoMSG033, 'Session', 'addCatalog', 'The catalogUserName argument was invalid.'); } catalogPassword = arguments[0].password; if ( catalogPassword && (typeof catalogPassword != 'string') ) { throw new Error(jsdoMSG033, 'Session', 'addCatalog', 'The catalogPassword argument was invalid.'); } isAsync = arguments[0].async; if ( isAsync && (typeof isAsync != 'boolean') ) { throw new Error(jsdoMSG033, 'Session', 'addCatalog', 'The async argument was invalid.'); } } else { catalogURI = arguments[0]; if ( typeof catalogURI != 'string' ) { throw new Error("First argument to Session.addCatalog must be the URL of the catalog."); } catalogUserName = arguments[1]; if ( catalogUserName && (typeof catalogUserName != 'string') ) { throw new Error("Second argument to Session.addCatalog must be a user name string."); } catalogPassword = arguments[2]; if ( catalogPassword && (typeof catalogPassword!= 'string') ) { throw new Error("Third argument to Session.addCatalog must be a password string."); } } } else { throw new Error("Session.addCatalog is missing its first argument, the URL of the catalog."); } if ( !catalogUserName ) { catalogUserName = this.userName; } if ( !catalogPassword ) { catalogPassword = _password; } // for now we don't support multiple version of the catalog across sessions if (progress.data.ServicesManager.getSession(catalogURI) != undefined) { if (isAsync) { // attempt to get the event to fire AFTER this call returns ASYNC_PENDING setTimeout( this._addCatalogComplete, 10, this, progress.data.Session.CATALOG_ALREADY_LOADED, null ); return progress.data.Session.ASYNC_PENDING; } return progress.data.Session.CATALOG_ALREADY_LOADED; } /* should we check whether catalog already loaded? */ var xhr = new XMLHttpRequest(); xhr.pdsession = this; xhr._catalogURI = catalogURI; this._setXHRCredentials( xhr, 'GET', catalogURI, catalogUserName, catalogPassword, isAsync); // Note that we are not adding the CCID to the URL or as a header, because the catalog may not // be stored with the REST app and even if it is, the AppServer ID shouldn't be relevant /* This is here as much for CORS situations as the possibility that there might be an out of date * cached version of the catalog. The CORS problem happens if you have accessed the catalog * locally and then run an app on a different server that requests the catalog. Your browser already * has the catalog, but the request used to get it was a non-CORS request and the browser will * raise an error */ xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("Pragma", "no-cache"); if ( this.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", this.xClientProps); } if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { _addWithCredentialsAndAccept( xhr, "application/json" ); } if (isAsync ) { xhr.onreadystatechange = this._onReadyStateChangeGeneric; xhr.onResponseFn = this._processAddCatalogResult; xhr.onResponseProcessedFn = this._addCatalogComplete; } try { if (typeof this.onOpenRequest === 'function') { setLastSessionXHR (xhr, this); var params = { "xhr": xhr, "verb": "GET", "uri": catalogURI, "async": false, "formPreTest": false, "session": this }; this.onOpenRequest( params ); xhr = params.xhr; } setLastSessionXHR(xhr, this); xhr.send(null); } catch(e) { throw new Error("Error retrieving catalog '" + catalogURI + "'.\n" + e.message); } if ( isAsync ) { return progress.data.Session.ASYNC_PENDING; } else { return this._processAddCatalogResult( xhr ); } }; this._processAddCatalogResult = function ( xhr ) { var _catalogHttpStatus = xhr.status; var theSession = xhr.pdsession; var servicedata; var catalogURI = xhr._catalogURI; setLastSessionXHR (xhr, theSession); if ((_catalogHttpStatus == 200) || (_catalogHttpStatus == 0)) { servicedata = theSession._parseCatalog( xhr ); var serviceURL; try { progress.data.ServicesManager.addCatalog( servicedata, theSession ); } catch(e) { throw new Error("Error processing catalog '" + catalogURI + "'. \n" + e.message); } // create a mobile service object and add it to the Session's array of same for (var i = 0; i < servicedata.length; i++ ) { serviceURL = theSession._prependAppURL( servicedata[i].address ); pushService( new progress.data.MobileServiceObject( { name :servicedata[i].name, uri : serviceURL} ), theSession); if (servicedata[i].settings && servicedata[i].settings.useXClientProps && !theSession.xClientProps) { console.warn("Catalog warning: Service settings property 'useXClientProps' is true but 'xClientProps' property has not been set."); } } pushCatalogURIs( catalogURI, theSession ); progress.data.ServicesManager.addSession(catalogURI, theSession); } else if (_catalogHttpStatus == 401) { return progress.data.Session.AUTHENTICATION_FAILURE; } else { throw new Error( "Error retrieving catalog '" + catalogURI + "'. Http status: " + _catalogHttpStatus + "."); } return progress.data.Session.SUCCESS; }; this._addCatalogComplete = function( pdsession, result, errObj ) { pdsession.trigger("afterAddCatalog", pdsession, result, errObj); }; /** * ping -- determine whether the Mobile Web Application that the Session object represents * is available, which includes determining whether its associated AppServer is running * Also determine whether the Mobile services managed by this Session object are available * (which means simply that they're known to the Mobile Web Application) * (Implementation note: be sure that this Session object's "connected" * property retains its current value until the end of this function, where * it gets updated, if necessary, after calling _isOnlineStateChange * * Signatures : * @param arg * There are 2 signatures -- * - no argument -- do an async ping of the Session's Mobile Web application. The only effect * of the ping will be firing an offline or an online event, if appropriate * The ping function itself will return false to the caller * - object argument -- the object's properties provide the input args. They are all * optional (if for some reason the caller passes an object that has no properties, it's * the same as passing no argument at all). The properties may be: * async -- tells whether to execute the ping asynchronously (which is the default) * onCompleteFn -- if async, this will be called when response returns * doNotFireEvent -- used internally, controls whether the ping method causes an offline * or online event to be fired if there has been a change (the default is that it * does, but our Session._checkServiceResponse() sets this to true so that it can * control the firing of the event) * offlineReason -- if present, and if the ping code discovers that teh server is offline, * the ping code will set this with its best guess as to the reason the server is offline * @member ping */ this.ping = function ( args ) { var pingResult = false; var pingArgs = { pingURI : null, async : true, onCompleteFn : null, fireEventIfOfflineChange : true, onReadyStateFn : this._onReadyStateChangePing, offlineReason : null}; if ( args ) { if ( args.async !== undefined ) { // when we do background pinging (because pingInterval is set), // we pass in an arg that is just an object that has an async property, // set to true. This can be expanded to enable other kinds of ping calls // to be done async (so that application developers can do so, if we decide // to support that) pingArgs.async = args.async; } if ( args.doNotFireEvent !== undefined ) { pingArgs.fireEventIfOfflineChange = !args.doNotFireEvent; } if (args.onCompleteFn && (typeof args.onCompleteFn) == 'function') { pingArgs.onCompleteFn = args.onCompleteFn; } } /* Ping the Mobile Web Application (this will also determine whether AppServer is available) * Call _processPingResult() if we're synchronous, otherwise the handler for the xhr.send() * will call it */ pingArgs.pingURI = myself._makePingURI( ); myself._sendPing( pingArgs ); if ( !pingArgs.async ) { if (pingArgs.xhr) { pingResult = myself._processPingResult( pingArgs ); if (args.offlineReason !== undefined) { args.offlineReason = pingArgs.offlineReason; } } else { pingResult = false; // no xhr returned from _sendPing, something must have gone wrong } } // else it's async, deliberately returning false so developer not misled into thinking the ping succeeded return pingResult; }; // "protected" Functions /** * given a value of true or false for being online for the Mobile Web Application * managed by this Session object, determine whether that changes the current * state of being offline or online. * Returns true if the input state is a change from the current state * * Signature : * @param isOnline Required. True to determine whether online is a state change, false to * determine whether offline constitutes a state change. Boolean. * @member _isOnlineStateChange */ this._isOnlineStateChange = function( isOnline ) { var stateChanged = false; if (isOnline && !(this.connected) ) { stateChanged = true; } else if ( !isOnline && ( this.connected ) ) { stateChanged = true; } return stateChanged; }; /** * given information about the response from a request made to a service, * do the following: * * determine whether the online status of the Session has changed, and * set the Session's Connected property accordingly * if the Session's online status has changed, fire the appropriate event * * Signature : * @param xhr Required. The xhr that was used to make the request. Object * @param success Required. True if caller regards the request as having succeeded. Boolean * @param request Required. The JSDO request object created for making the request. Object. * @member _checkServiceResponse */ this._checkServiceResponse = function(xhr, success, request) { var offlineReason = null; var wasOnline = this.connected; /* first of all, if there are no subscriptions to offline or online events, don't * bother -- we don't want to run the risk of messing things up by calling ping * if the app developer isn't interested (especially because that may mean that * ping isn't enabled on the server, anyway) */ if ( !this._events ) { return; } var offlineObservers = this._events["offline"] || []; var onlineObservers = this._events["online"] || []; if ( (offlineObservers.length === 0) && (onlineObservers.length === 0) ) { return; } /* even though this function gets called as a result of trying to * contact the server, don't bother to change anything if we already * know that the device (or user agent, or client machine) is offline. * We can't assume anything about the state of the server if we can't * even get to the internet from the client */ // if the call to the server was a success, we will assume we are online, // both server and device if (success) { restApplicationIsOnline = true; deviceIsOnline = true; // presumably this is true (probably was already true) } else { /* Request failed, determine whether it's because server is offline * Do this even if the Session was already in an offline state, because * we need to determine whether the failure was due to still being * offline, or whether it's now possible to communicate with the * server but the problem was something else. */ if ( deviceIsOnline ) { /* ping the server to get better information on whether this is an offline case * NB: synchronous ping for simplicity, maybe should consider async so as not * to potentially freeze UI */ var localPingArgs = { doNotFireEvent : true, // do in this fn so we have the request offlineReason : null, async : false}; if ( !(myself.ping( localPingArgs ) ) ) { offlineReason = localPingArgs.offlineReason; restApplicationIsOnline = false; } else { // ping returned true, so even though the original request failed, // we are online and the failure must have been due to something else restApplicationIsOnline = true; } } // else deviceIsOnline was already false, so the offline event should already have // been fired for that reason and there is no need to do anything else } if ( wasOnline && !this.connected ) { this.trigger("offline", this, offlineReason, request); } else if ( !wasOnline && this.connected ) { this.trigger("online", this, request); } }; /** Decide whether, on the basis of information returned by a ping request, the * Mobile Web Application managed by this Session object is online, where online * means that the ping response was a 200 and, IF the body of the response contains * JSON with an AppServerStatus property, that AppServerStatus Status property has * a pingStatus property set to true * i.e., the body has an AppServerStatus.PingStatus set to true * (if the body doesn't contain JSON with an AppServerStatus, we use just the HTTP * response status code to decide) * Return true if the response meets these conditions, false if it doesn't * @member _processPingResult */ this._processPingResult = function( args ) { var xhr = args.xhr; var pingResponseJSON; var appServerStatus = null; var wasOnline = this.connected; /* first determine whether the Web server and the Mobile Web Application (MWA) * are available */ if ( xhr.status >= 200 && xhr.status < 300 ) { if (oepingAvailable) { try { pingResponseJSON = JSON.parse(xhr.responseText); appServerStatus = pingResponseJSON.AppServerStatus; } catch(e) { /* We got a successful response from calling our ping URI, but it * didn't return valid JSON. If we think that the oeping REST API * is available on the server (so we should have gotten valid * json), log this to the console. * */ console.error( "Unable to parse ping response." ); } } restApplicationIsOnline = true; } else { if ( deviceIsOnline ) { if ( xhr.status === 0 ) { args.offlineReason = progress.data.Session.SERVER_OFFLINE; restApplicationIsOnline = false; } else if ( (xhr.status === 404) || (xhr.status === 410) ) { /* if we get a 404, it means the Web server is up, but it * can't find the resource we requested (either _oeping or * the login target), therefore the Mobile Web application * must be unavailable (410 is Gone) */ args.offlineReason = progress.data.Session.WEB_APPLICATION_OFFLINE; restApplicationIsOnline = false; } else { /* There's some error, but we can't say for sure that it's because * the Web application is unavailable. May be an authentication problem, * internal server error, or for some reason our ping request was * invalid (unlikely to happen if it previously succeeded). * In particular, if the server uses Form authentication, it * may have come back online but now the session id * is no longer valid. */ restApplicationIsOnline = true; } } else { args.offlineReason = progress.data.Session.DEVICE_OFFLINE; } } // is the AppServer online? appServerStatus will be non-null only // if the ping request returned 200, meaning the other things are OK // (connection to server, Tomcat, Mobile Web application) if ( appServerStatus ) { if (appServerStatus.PingStatus === "false") { args.offlineReason = progress.data.Session.APPSERVER_OFFLINE; restApplicationIsOnline = false; } else { restApplicationIsOnline = true; } } if ((typeof xhr.onCompleteFn) == 'function') { xhr.onCompleteFn( { pingResult : this.connected, xhr : xhr, offlineReason : args.offlineReason}); } // decide whether to fire an event, and if so do it if ( args.fireEventIfOfflineChange ) { if ( wasOnline && !this.connected ) { myself.trigger("offline", myself, args.offlineReason, null); } else if ( !wasOnline && this.connected ) { myself.trigger("online", myself, null); } } return this.connected; }; this._onReadyStateChangePing = function () { var xhr = this; var args; if (xhr.readyState == 4) { args = { xhr : xhr, fireEventIfOfflineChange: true, offlineReason : null }; myself._processPingResult( args ); if ( _pingInterval > 0) { _timeoutID = setTimeout( myself._autoping, _pingInterval); } } }; this._pingtestOnReadyStateChange = function () { var xhr = this; if (xhr.readyState == 4) { if ( xhr.status >= 200 && xhr.status < 300) { oepingAvailable = true; } else { oepingAvailable = false; // should be false anyway, just being sure partialPingURI = myself.loginTarget; console.warn("Default ping target not available, will use loginTarget instead."); } } }; /** * args: pingURI * async * onCompleteFn used only if async is true * * (deliberately not catching thrown error) * @member _sendPing */ this._sendPing = function( args ) { var xhr = new XMLHttpRequest(); try { this._setXHRCredentials( xhr, "GET", args.pingURI, this.userName, _password, args.async); if (args.async) { xhr.onreadystatechange = args.onReadyStateFn; xhr.onCompleteFn = args.onCompleteFn; } xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("Pragma", "no-cache"); if ( this.xClientProps ) { xhr.setRequestHeader("X-CLIENT-PROPS", this.xClientProps); } if ( this.authenticationModel === progress.data.Session.AUTH_TYPE_FORM ) { _addWithCredentialsAndAccept( xhr, "application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); } xhr.send(null); } catch(e) { args.error = e; } // ASYNC?? args.xhr = xhr; }; this._makePingURI = function( ) { var pingURI = this.serviceURI + partialPingURI; pingURI = this._addTimeStampToURL(pingURI); // had caching problem with Firefox in its offline mode return pingURI; }; /** * autoping -- callback * @member _autoping */ this._autoping = function() { myself.ping( { async : true } ); }; /** _setXHRCredentials (intended for progress.data library use only) * set credentials as needed, both via the xhr's open method and setting the * Authorization header directly * @member _setXHRCredentials */ this._setXHRCredentials = function( xhr, verb, uri, userName, password, async ) { // note that we do not set credentials if userName is null. Null userName indicates that the developer is depending on the browser to // get and manage the credentials, and we need to make sure we don't interfere with that if ( userName && this.authenticationModel === progress.data.Session.AUTH_TYPE_BASIC) { xhr.open(verb, uri, async, userName, password); // set Authorization header var auth = _make_basic_auth(userName, password); xhr.setRequestHeader('Authorization', auth); } else { xhr.open(verb, uri, async); } }; /** _addCCIDtoURL (intended for progress.data library use only) * Add the Client Context ID being used by a session on an OE REST application, if we have * previously stored one from a response from the server * @member _addCCIDtoURL */ this._addCCIDtoURL = function ( url ) { if ( this.clientContextId && (this.clientContextId !== "0") ) { // Should we test protocol, host and port in addition to path to ensure that jsessionid is only sent // when request applies to the REST app (it might not be if the catalog is somewhere else) if ( url.substring(0, this.serviceURI.length) == this.serviceURI ) { var jsessionidStr = "JSESSIONID=" + this.clientContextId + ";"; var index = url.indexOf('?'); if (index == -1) { url += "?" + jsessionidStr; } else { url = url.substring(0, index + 1) + jsessionidStr + url.substring(index + 1); } } } return url; }; var SEQ_MAX_VALUE = 999999999999999; /* 15 - 9 */ var _tsseq = SEQ_MAX_VALUE; /* Initialized to SEQ_MAX_VALUE to initialize values. */ var _tsprefix1 = 0; var _tsprefix2 = 0; this._getNextTimeStamp = function() { var seq = ++_tsseq; if (seq >= SEQ_MAX_VALUE) { _tsseq = seq = 1; var t = Math.floor(( Date.now ? Date.now() : (new Date().getTime())) / 10000); if (_tsprefix1 == t) { _tsprefix2++; if (_tsprefix2 >= SEQ_MAX_VALUE) { _tsprefix2 = 1; } } else { _tsprefix1 = t; Math.random(); // Ignore call to random _tsprefix2 = Math.round(Math.random() * 10000000000); } } return _tsprefix1 + "-" + _tsprefix2 + "-" + seq; }; /** * _addTimeStampToURL (intended for progress.data library use only) * Add a time stamp to the a URL to prevent caching of the request. * Set progress.data.Session._useTimeStamp = false to turn off. * @member _addTimeStampToURL */ this._addTimeStampToURL = function ( url ) { var timeStamp = "_ts=" + this._getNextTimeStamp(); url += ((url.indexOf('?') == -1) ? "?" : "&") + timeStamp; return url; }; /** _saveClientContextId (intended for progress.data library use only) * If the CCID hasn't been set for the session yet, check the xhr for it and store it. * (If it has been set, assume that the existing one is correct and do nothing. We could * enhance this function by checking to see whether the new one matches the existing one. * Not sure what to do if that's the case -- overwrite the old one? ignore the new one? * Should at least log a warning or error * @member _saveClientContextId */ this._saveClientContextId = function( xhr ) { // do this unconditionally (even if there is already a client-context-id), because // if basic authentication is set up such that it uses sessions, and cookies are disabled, // the server will generate a different session on each request and the X-CLIENT-CONTEXT-ID // will therefore be different setClientContextIDfromXHR( xhr, this ); }; this._parseCatalog= function ( xhr ) { var jsonObject; var catalogdata; try { jsonObject = JSON.parse(xhr.responseText); catalogdata = jsonObject.services; } catch(e) { console.error( "Unable to parse response. Make sure catalog has correct format." ); catalogdata = null; } return catalogdata; }; /** _prependAppURL * Prepends the URL of the Web application (the 1st parameter passed to login, stored in this.serviceURI) * to whatever string is passed in. If the string passed in is an absolute URL, this function does * nothing except return a copy. This function ensures that the resulting URL has the correct number * of slashes between the web app url and the string passed in (currently that means that if what's * passed in has no initial slash, the function adds one) * @member _prependAppURL */ this._prependAppURL = function( oldURL ) { if ( !oldURL ) { /* If oldURL is null, just return the app URL. (It's not the responsibility of this * function to decide whether having a null URL is an error. Its only responsibility * is to prepend the App URL to whatever it gets passed (and make sure the result is a valid URL) */ return this.serviceURI; } var newURL = oldURL; var pat = /^https?:\/\//i; if ( !pat.test(newURL) ) { if (newURL.indexOf("/") !== 0) { newURL = "/" + newURL; } newURL = this.serviceURI + newURL; } return newURL; }; // Functions // Set an XMLHttpRequest object's withCredentials attribute and Accept header, // using a try-catch so that if setting withCredentials throws an error it doesn't // interrupt execution (this is a workaround for the fact that Firefox doesn't // allow you to set withCredentials when you're doing a synchronous operation) // The setting of the Accept header is included here, and happens after the // attempt to set withCredentials, to make the behavior in 11.3.0 match // the behavior in 11.2.1 -- for Firefox, in a CORS situation, login() will // fail. (If we allowed the Accept header to be set, login() would succeed // because of that but addCatalog() would fail because no JSESSIONID would // be sent due to withCredentials not being true) function _addWithCredentialsAndAccept( xhr, acceptString ) { try { xhr.withCredentials = true; xhr.setRequestHeader("Accept", acceptString); } catch(e){} } // from http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html function _make_basic_auth(user, pw) { var tok = user + ':' + pw; // var hash = base64_encode(tok); var hash = btoa(tok); return "Basic " + hash; } /** The next 2 functions, _gotLoginForm() and _gotLoginFailure(), attempt to determine whether * a server response consists of * the application's login page or login failure page. Currently (release 11.2), this * is the only way we have of determining that a request made to the server that's * configured for form-based authentication failed due to authentication (i.e., * authentication hadn't happened before the request and either invalid credentials or * no credentials were sent to the server). That's because, due to the fact that the browser * or native wrapper typically intercepts the redirect involved in an unauthenticated request * to a server that's using using form auth, all we see in the XHR is a success status code * plus whatever page we were redirected to. * In the future, we expect to enhance the OE REST adapter so that it will return a status code * indicating failure for form-based authentication, and we can reimplement these functions so * they check for that code rather than do the simplistic string search. */ // Determines whether the content of the xhr is the login page. Assumes // use of a convention for testing for login page var loginFormIDString = "j_spring_security_check"; function _gotLoginForm(xhr) { // is the response contained in an xhr actually the login page? return _findStringInResponseHTML( xhr, loginFormIDString ); } // Determines whether the content of the xhr is the login failure page. Assumes // use of a convention for testing for login fail page var loginFailureIdentificationString = "login failed"; function _gotLoginFailure(xhr) { return _findStringInResponseHTML( xhr, loginFailureIdentificationString ); } // Does a given xhr contain html and does that html contain a given string? function _findStringInResponseHTML( xhr, searchString ) { if ( !xhr.responseText ) { return false; } var contentType = xhr.getResponseHeader( "Content-Type" ); if ( (contentType.indexOf("text/html") >= 0) && (xhr.responseText.indexOf(searchString) >= 0) ) { return true; } return false; } /** sets the statusFromjson property in the params object to indicate * the status of a response from an OE Mobile Web application that has * to do with authentication (the response to a login request, or a * response to a request for a resource where there was an error having * to do with authentication * @member handleJSONLoginResponse */ function handleJSONLoginResponse( params ) { // Parse the json in the response to see whether it's the special OE REST service // response. If it is, check the result (which should be consistent with the status from // the xhr) var jsonObject; params.statusFromjson = null; try { jsonObject = JSON.parse(params.xhr.responseText); if ( jsonObject.status_code !== undefined && jsonObject.status_txt !== undefined ){ params.statusFromjson = jsonObject.status_code; } } catch(e) { // invalid json setLoginResult(progress.data.Session.LOGIN_GENERAL_FAILURE, params.session); setLoginHttpStatus(xhr.status, params.session); throw new Error("Unable to parse login response from server."); } } }; // End of Session progress.data.Session._useTimeStamp = true; // Constants for progress.data.Session if ((typeof Object.defineProperty) == 'function') { Object.defineProperty( progress.data.Session, 'LOGIN_SUCCESS', { value: 1, enumerable: true } ); Object.defineProperty( progress.data.Session, 'LOGIN_AUTHENTICATION_FAILURE', { value: 2, enumerable: true } ); Object.defineProperty( progress.data.Session, 'LOGIN_GENERAL_FAILURE', { value: 3, enumerable: true }); Object.defineProperty( progress.data.Session, 'CATALOG_ALREADY_LOADED', { value: 4, enumerable: true }); Object.defineProperty( progress.data.Session, 'ASYNC_PENDING', { value: 5, enumerable: true }); Object.defineProperty( progress.data.Session, 'SUCCESS', { value: 1, enumerable: true } ); Object.defineProperty( progress.data.Session, 'AUTHENTICATION_FAILURE', { value: 2, enumerable: true } ); Object.defineProperty( progress.data.Session, 'GENERAL_FAILURE', { value: 3, enumerable: true } ); Object.defineProperty( progress.data.Session, 'AUTH_TYPE_ANON', { value: "anonymous", enumerable: true } ); Object.defineProperty( progress.data.Session, 'AUTH_TYPE_BASIC', { value: "basic", enumerable: true } ); Object.defineProperty( progress.data.Session, 'AUTH_TYPE_FORM', { value: "form", enumerable: true }); Object.defineProperty( progress.data.Session, 'DEVICE_OFFLINE', { value: "Device is offline", enumerable: true } ); Object.defineProperty( progress.data.Session, 'SERVER_OFFLINE', { value: "Cannot contact server", enumerable: true } ); Object.defineProperty( progress.data.Session, 'WEB_APPLICATION_OFFLINE', { value: "Mobile Web Application is not available", enumerable: true }); Object.defineProperty( progress.data.Session, 'SERVICE_OFFLINE', { value: "REST web Service is not available", enumerable: true }); Object.defineProperty( progress.data.Session, 'APPSERVER_OFFLINE', { value: "AppServer is not available", enumerable: true }); } else { progress.data.Session.LOGIN_SUCCESS = 1; progress.data.Session.LOGIN_AUTHENTICATION_FAILURE = 2; progress.data.Session.LOGIN_GENERAL_FAILURE = 3; progress.data.Session.CATALOG_ALREADY_LOADED = 4; progress.data.Session.SUCCESS = 1; progress.data.Session.AUTHENTICATION_FAILURE = 2; progress.data.Session.GENERAL_FAILURE = 3; progress.data.Session.AUTH_TYPE_ANON = "anonymous"; progress.data.Session.AUTH_TYPE_BASIC= "basic"; progress.data.Session.AUTH_TYPE_FORM = "form"; /* deliberately not including the "offline reasons" that are defined in the * 1st part of the conditional. We believe that we can be used only in environments where * ECMAScript 5 is supported, so let's put that assumption to the test */ } //setup inheritance for Session -- specifically for incorporating an Observable object progress.data.Session.prototype = new progress.util.Observable(); progress.data.Session.prototype.constructor = progress.data.Session; function validateSessionSubscribe(args, evt, listenerData ) { listenerData.operation = undefined; var found = false; // make sure this event is one that we support for(var i = 0; i < this._eventNames.length; i++) { if ( evt === this._eventNames[i].toLowerCase() ) { found = true; break; } } if ( !found ) { throw new Error( progress.data._getMsgText("jsdoMSG042", evt) ); } if (args.length < 2) { throw new Error( progress.data._getMsgText("jsdoMSG038", 2) ); } if (typeof args[0] !== 'string') { throw new Error( progress.data._getMsgText("jsdoMSG039") ); } if (typeof args[1] !== 'function') { throw new Error( progress.data._getMsgText("jsdoMSG040") ); } else { listenerData.fn = args[1]; } if (args.length > 2) { if (typeof args[2] !== 'object') { throw new Error( progress.data._getMsgText("jsdoMSG041", evt) ); } else { listenerData.scope = args[2]; } } } progress.data.Session.prototype._eventNames = ["offline", "online", "afterLogin", "afterAddCatalog", "afterLogout"]; // events supported by Session progress.data.Session.prototype.validateSubscribe = validateSessionSubscribe; // callback to validate subscribe and unsubscribe progress.data.Session.prototype.toString = function( radix ){ return "progress.data.Session"; }; })(); import React from 'react'; import Layout from '../components/layout'; import "../components/layout.css"; const NotFoundPage = () => (

    Sorry that doesn't exist...

    ) export default NotFoundPage js/index.js import Vue from "vue/dist/vue.js"; import { BootstrapVue } from "bootstrap-vue"; import App from "./App.vue"; import "../css/styles.css"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap-vue/dist/bootstrap-vue.css"; Vue.use(BootstrapVue); import("../pkg/index.js") .then(function (wasm) { wasm.load(); new Vue({ el: "#app", render: (h) => h(App, { props: { wasm }, }), }); }) .catch(console.error); pocka/ts-raytrace-study0 import * as vector from './vector.js' export const sphere = (center, radius, surface) => { const radius2 = radius * radius const thing = { intersect(ray) { const eo = vector.minus(center, ray.start) const v = vector.dot(eo, ray.direction) let dist = 0 if (v >= 0) { const disc = radius2 - (vector.dot(eo, eo) - v * v) if (disc >= 0) { dist = v - Math.sqrt(disc) } } return dist === 0 ? null : { thing, ray, dist } }, normal(pos) { return vector.norm(vector.minus(pos, center)) }, surface } return thing } export const plane = (norm, offset, surface) => { const thing = { intersect(ray) { const denom = vector.dot(norm, ray.direction) if (denom > 0) { return null } const dist = (vector.dot(norm, ray.start) + offset) / -denom return { thing, ray, dist } }, normal(pos) { return norm }, surface } return thing } const { Cilent, Message, MessageEmbed } = require('discord.js'); module.exports = { name: "bot-guilds", aliases: ['botguilds', 'top-guilds', 'topguilds'], /** * @param {Client} client * @param {Message} message * @param {String[]} args */ run: async (client, message, args) => { const guilds = client.guilds.cache .sort((a, b) => b.memberCount - a.memberCount) .first(15); const description = guilds.map((guild, index) => { return `${index+1}) ${guild.name}: ${guild.memberCount} members` }).join('\n') message.channel.send( new MessageEmbed() .setTitle("Cleckzie's top Guilds") .setThumbnail("https://cdn.discordapp.com/avatars/790269534141284454/b15a9f7480d7a59380e82f3467fe84fa.webp?size=4096") .setColor("RANDOM") .setDescription(description) ) } }1-10 var D = { name: 'd', aValue: A.name, bValue: new B().name };'use strict'; import React from 'react'; import FluxibleApp from 'fluxible'; import AppComponent from './components/Application.jsx'; import AppStore from './stores/ApplicationStore'; var app = new FluxibleApp({ appComponent: React.createFactory(AppComponent) }); app.registerStore(AppStore); export default app; // @ flow import React from 'react'; import {GeoJSON} from 'react-leaflet'; import {formatDate, formatNumber, getLabelOfOption} from '$util/helpers'; import type {LeafletGeoJson} from '$src/types'; type Props = { color: string, defaultPlot?: number, plotsGeoJson: LeafletGeoJson, typeOptions: Array, } const PlotsLayer = ({ color, defaultPlot, plotsGeoJson, typeOptions, }: Props) => { const onMouseOver = (e) => { const layer = e.target; layer.setStyle({ fillOpacity: 0.7, }); }; const onMouseOut = (e) => { const layer = e.target; layer.setStyle({ fillOpacity: 0.2, }); }; return ( { if (feature.properties) { const {area, id, identifier, registration_date, repeal_date, section_area, type} = feature.properties; const popupContent = `

    ${getLabelOfOption(typeOptions, type) || '-'}

    Id: ${id}

    Tunnus: ${identifier}

    Kokonaisala: ${(area || area === 0) ? `${formatNumber(area)} m²` : ''}

    Leikkausala: ${(section_area || section_area === 0) ? `${formatNumber(section_area)} m²` : ''}

    Rekisteröintipvm: ${formatDate(registration_date) || '-'}

    Kumoamispvm: ${formatDate(repeal_date) || '-'}

    `; layer.bindPopup(popupContent); if(id === defaultPlot) { layer.setStyle({ fillOpacity: 0.9, }); setTimeout(() => { layer.openPopup(); }, 100); } } layer.on({ mouseover: onMouseOver, mouseout: onMouseOut, }); }} style={{ color: color, }} /> ); }; export default PlotsLayer; minefled/SaranaJS /* | SaranaJS | | copyright minefled, 2021 | Released under the MIT License */ (()=>{function r(t){return typeof t=="number"}function e(t){return typeof t=="string"}function o(){return new Date}function n(){return new Date(0)}var i={isNumber:r,isString:e,now:o,epoch:n},d=i;})(); mikedotexe/sender-wallet-extension export default class Account { constructor({ accountId, mnemonic, network, balance, secretKey, publicKey, validators, totalPending, totalAvailable, totalUnstaked, totalStaked, totalUnclaimed, tokens, transactions, }) { this.accountId = accountId; // Account id this.mnemonic = mnemonic; // Account's mnemonic this.network = network; // Account's network this.balance = balance; // Account's balance this.secretKey = secretKey; // Account's secret key this.publicKey = publicKey; // Account's public key this.totalPending = totalPending; // Pending withdrawal this.totalAvailable = totalAvailable; // Available for withdrawal this.totalUnstaked = totalUnstaked; // Available to be staked this.totalStaked = totalStaked; // Staked balance this.totalUnclaimed = totalUnclaimed; // Total rewards paid out - staking deposits made this.validators = validators; // Account's validators information this.tokens = tokens; // Account's owned tokens this.transactions = transactions; // Account's transactions } }juanfelipe82193/opensap /*! * SAP APF Analysis Path Framework * * (c) Copyright 2012-2014 SAP AG. All rights reserved */ /*global sap*/ jQuery.sap.require("sap.apf.modeler.ui.utils.textManipulator"); jQuery.sap.require("sap.apf.utils.utils"); sap.ui.define([ "sap/apf/modeler/ui/controller/propertyType" ], function(BaseController) { "use strict"; var oTextManipulator = sap.apf.modeler.ui.utils.textManipulator; return BaseController.extend("sap.apf.modeler.ui.controller.representationProperty", { onBeforeRendering : function() { var oController = this; if (oController.byId("idLabelDisplayOptionType")) { oController.byId("idLabelDisplayOptionType").destroy(); } oController.byId("idPropertyTypeLayout").setSpan("L4 M4 S4"); }, getAllPropertiesAsPromise : function() { var oController = this, sSelectedKey, aPropertiesWithSelectedKey, aProperties = []; var oStep = oController.oStepPropertyMetadataHandler.oStep; var deferred = jQuery.Deferred(); oStep.getConsumablePropertiesForRepresentation(oController.oRepresentation.getId()).done(function(oResponse) { oResponse.consumable.forEach(function(sProperty) { oController.oStepPropertyMetadataHandler.getProperties().forEach(function(sSelectProperty) { if (sProperty === sSelectProperty) { aProperties.push(sProperty); } }); }); sSelectedKey = oController.getSelectedProperty(); if (sSelectedKey !== oController.oTextReader("none") && sSelectedKey !== undefined) { aPropertiesWithSelectedKey = aProperties.indexOf(sSelectedKey) !== -1 ? aProperties : aProperties.concat(sSelectedKey); if (oResponse.available.indexOf(sSelectedKey) !== -1 || sSelectedKey === oController.oTextReader("none")) { aProperties = aPropertiesWithSelectedKey; } else { aProperties = aProperties.concat(oTextManipulator.addPrefixText([ sSelectedKey ], oController.oTextReader)); sSelectedKey = oTextManipulator.addPrefixText([ sSelectedKey ], oController.oTextReader)[0]; } } if (oController.oStepPropertyMetadataHandler.getStepType() === "hierarchicalStep") { aProperties.splice(0, 0, oController.oTextReader("none")); } deferred.resolve({ aAllProperties : aProperties, sSelectedKey : sSelectedKey }); }); return deferred.promise(); }, getPropertyTextLabelKey : function(sPropertyName) { var oController = this; return oController.oRepresentation.getPropertyTextLabelKey(sPropertyName); }, updatePropertiesInConfiguration : function(aPropertiesInformation) { var oController = this; oController.oRepresentation.getProperties().forEach(function(sMeasure) { oController.oRepresentation.removeProperty(sMeasure); }); aPropertiesInformation.forEach(function(oPropertiesInformation) { oController.oRepresentation.addProperty(oPropertiesInformation.sProperty); oController.oRepresentation.setPropertyKind(oPropertiesInformation.sProperty, oPropertiesInformation.sKind); oController.oRepresentation.setPropertyTextLabelKey(oPropertiesInformation.sProperty, oPropertiesInformation.sTextLabelKey); }); }, createNewPropertyInfoAsPromise : function(sNewProperty) { var oController = this, oNewPropertyInfo = {}; oNewPropertyInfo.sProperty = sNewProperty; oNewPropertyInfo.sKind = oController.getView().getViewData().oPropertyTypeData.sContext; oNewPropertyInfo.sTextLabelKey = undefined; return sap.apf.utils.createPromise(oNewPropertyInfo); }, setPropertyTextLabelKey : function(sPropertyName, sLabelTextKey) { var oController = this; oController.oRepresentation.setPropertyTextLabelKey(sPropertyName, sLabelTextKey); }, setNextPropertyInParentObject : function() { var oController = this; oController.updateOfConfigurationObjectAsPromise().then(function() { oController.setDetailData(); }); }, removePropertyFromParentObject : function() { var oController = this; oController.oRepresentation.removeProperty(oTextManipulator.removePrefixText(oController.byId("idPropertyType").getSelectedKey(), oController.oTextReader(sap.apf.modeler.ui.utils.CONSTANTS.texts.NOTAVAILABLE))); }, addPropertyAsPromise : function() { var oController = this, aProperties = []; var oStep = oController.oStepPropertyMetadataHandler.oStep; var oConstants = sap.apf.modeler.ui.utils.CONSTANTS; oStep.getConsumablePropertiesForRepresentation(oController.oRepresentation.getId()).done(function(oResponse) { oResponse.consumable.forEach(function(sProperty) { oController.oStepPropertyMetadataHandler.getProperties().forEach(function(sSelectProperty) { if (sProperty === sSelectProperty) { aProperties.push(sProperty); } }); }); oController.getView().fireEvent(oConstants.events.ADDPROPERTY, { "sProperty" : aProperties[0], "sContext" : oController.getView().getViewData().oPropertyTypeData.sContext }); oController.oConfigurationEditor.setIsUnsaved(); }); } }); });10-100 function autoQuality (width, height) { // console.log('初始宽高', width, height) // 宽高比 let ratio = width / height // 目标大小 let targetW = 1280 let targetH = 1280 // 宽高均 <= 1280,图片尺寸大小保持不变 if (width < 1280 && height < 1280) { return {width, height} } if (width > 1280 && height > 1280) { // 宽高均 > 1280 && 宽高比 > 2, if (ratio > 2) { // 宽大于高 取较小值(高)等于1280,较大值等比例压缩 targetH = 1280 targetW = targetH * ratio } else { // 高大于宽 取较小值(宽)等于1280,较大值等比例压缩 (宽高比在0.5到2之间 ) targetW = 1280 targetH = targetW / ratio } } else { // 宽或高 > 1280 if (ratio > 2) { // 宽图 图片尺寸大小保持不变 targetW = width targetH = height } else if (ratio < 0.5) { // 长图 图片尺寸大小保持不变 targetW = width targetH = height } else if (ratio > 1) { // 宽大于高 取较大值(宽)等于1280,较小值等比例压缩 targetW = 1280 targetH = targetW / ratio } else { // 高大于宽 取较大值(高)等于1280,较小值等比例压缩 targetH = 1280 targetW = targetH * ratio } } targetW = Math.round(targetW) targetH = Math.round(targetH) return {width: targetW, height: targetH} } export default autoQuality "use strict"; const globby = require("globby"); const unified = require("unified"); const rehype = require("rehype-parse"); const santize = require("rehype-sanitize"); const { readSync: toVfile } = require("to-vfile"); const { writeFile } = require("fs").promises; const { basename } = require("path"); const { select: hSelect, selectAll: hSelectAll } = require("hast-util-select"); const { selectAll: uSelectAll } = require("unist-util-select"); const find = require("unist-util-find"); const reporter = require("vfile-reporter"); const findAllBetween = require("unist-util-find-all-between"); const location = require("vfile-location"); const titleRegex = /title:\w*(.+)/i; const authorRegex = /author:\w*(.+)/i; let toOffset; function bookAuthorAndTitle(ast, vfile) { try { // find preformatted metadata tag const metadataList = hSelectAll("pre, p", ast); let author, title; if (metadataList.length < 1) { vfile.fail("could not find metadata", ast); } // look for text that looks like title and author const titleNode = metadataList.reduce( (acc, metadata) => acc || find(metadata, n => { return titleRegex.test(n.value); }), null ); const authorNode = metadataList.reduce( (acc, metadata) => acc || find(metadata, n => authorRegex.test(n.value)), null ); if (titleNode) { // extract the raw text title = titleRegex.exec(titleNode.value)[1].trim(); } else { // error when missing vfile.fail("missing title", ast); } if (authorNode) { // extract the raw text author = authorRegex.exec(authorNode.value)[1].trim(); } else { // error when missing vfile.fail("missing author", ast); } return { author, title }; } catch (err) { if (err.reason) { throw err; } vfile.fail("could not find metadata", ast); } } function bookChapters(ast, vfile) { try { // use headers as chapter markers const chapters = hSelectAll("h1, h2, h3, h4, h5, h6", ast); // if no headers found, no chapters if (chapters.length < 1) { vfile.fail("no chapters", ast); } // order chapters by their location in the document // prevents paragraph duplication between chapters chapters.sort(byPosition); // extract level and title for chapter return chapters.map((node, index, list) => ({ type: "chapter", title: uSelectAll("text", node) .map(n => n.value) .join(" "), level: node.tagName, children: bookChapterParagraphs(vfile, node, index, list) })); } catch (err) { if (err.reason) { throw err; } // stack overflow means no chapters vfile.fail("exception parsing chapters", ast); } } // sort nodes by their starting position in the document, in ascending order function byPosition(a, b) { return toOffset(a.position.start) - toOffset(b.position.start); } function bookChapterParagraphs(vfile, chapter, chapterIndex, chapterList) { try { // find the chapter content using the header as the start let end; if (chapterIndex + 2 < chapterList.length) { // use the next chapter as the end end = chapterList[chapterIndex + 1]; } else { // when there are no more chapters, use last child of chapter's parent as the end const finalNodes = hSelectAll(":last-child", chapter.parent); end = finalNodes[finalNodes.length - 1]; } if (chapter.parent !== end.parent) { vfile.info( "cannot handle chapters where end is in a different section", chapter ); return []; } const chapterContent = findAllBetween(chapter.parent, chapter, end); // find all paragraphs in chapter return chapterContent .filter(n => n.tagName === "p") .map(n => ({ type: "paragraph", // extract only the text from the paragraph, no styling or tags value: uSelectAll("text", n) .map(n => n.value) .join(" ") })); } catch (err) { if (err.reason) { throw err; } vfile.fail("could not match", chapter); } } const simplifier = () => (ast, vfile) => { // add parent information to each node, needed to determine end of last chapter ast = require("unist-util-parents")(ast); // allow offset to be determined from position, used for sorting of chapters toOffset = location(vfile).toOffset; // lookup author and title const { author, title } = bookAuthorAndTitle(ast, vfile); // parse chapters and paragraphs const children = bookChapters(ast, vfile); // book is root node return { type: "book", author, title, children }; }; const emptyBookChecker = () => (ast, vfile) => { const paragraphs = ast.children.reduce( (counter, chapter) => counter + chapter.children.length, 0 ); if (paragraphs < 1) { vfile.fail("all chapters are empty"); } if (paragraphs < ast.children.length) { vfile.fail("less paragraphs than chapters"); } return ast; }; (async () => { // find html files const paths = await globby(["extracted/**/*.{html,htm}"]); const processor = unified() .use(rehype) // parse HTML .use(santize) // remove fluff content .use(simplifier) // reformat to new tree format .use(emptyBookChecker); // ensures there is some content in the book processor.Compiler = JSON.stringify; processor.freeze(); for (const p of paths) { try { // read and process file const content = await processor.process(toVfile(p)); // write new file in json folder await writeFile("json/" + basename(p) + ".json", content); } catch (err) { console.error(reporter(err)); } } })(); import {getSign, ifX, ifY} from './axis-util'; import {Value, one, zero} from './constants'; import guideMark from './guide-mark'; import {lookup} from './guide-util'; import {addEncoders} from '../encode/util'; import {RuleMark} from '../marks/marktypes'; import {AxisGridRole} from '../marks/roles'; import {isSignal} from '../../util'; import {extend, isObject} from 'vega-util'; export default function(spec, config, userEncode, dataRef, band) { var _ = lookup(spec, config), orient = spec.orient, vscale = spec.gridScale, sign = getSign(orient, 1, -1), offset = offsetValue(spec.offset, sign), encode, enter, exit, update, tickPos, gridStart, gridEnd, sz; encode = { enter: enter = {opacity: zero}, update: update = {opacity: one}, exit: exit = {opacity: zero} }; addEncoders(encode, { stroke: _('gridColor'), strokeCap: _('gridCap'), strokeDash: _('gridDash'), strokeDashOffset: _('gridDashOffset'), strokeOpacity: _('gridOpacity'), strokeWidth: _('gridWidth') }); tickPos = { scale: spec.scale, field: Value, band: band.band, extra: band.extra, offset: band.offset, round: _('tickRound') }; sz = ifX(orient, {signal: 'height'}, {signal: 'width'}); gridStart = vscale ? {scale: vscale, range: 0, mult: sign, offset: offset} : {value: 0, offset: offset}; gridEnd = vscale ? {scale: vscale, range: 1, mult: sign, offset: offset} : extend(sz, {mult: sign, offset: offset}); enter.x = update.x = ifX(orient, tickPos, gridStart); enter.y = update.y = ifY(orient, tickPos, gridStart); enter.x2 = update.x2 = ifY(orient, gridEnd); enter.y2 = update.y2 = ifX(orient, gridEnd); exit.x = ifX(orient, tickPos); exit.y = ifY(orient, tickPos); return guideMark({ type: RuleMark, role: AxisGridRole, key: Value, from: dataRef, encode }, userEncode); } function offsetValue(offset, sign) { if (sign === 1) { // no further adjustment needed, just return offset } else if (!isObject(offset)) { offset = isSignal(sign) ? {signal: `(${sign.signal}) * (${offset || 0})`} : sign * (offset || 0); } else { let entry = offset = extend({}, offset); while (entry.mult != null) { if (!isObject(entry.mult)) { entry.mult = isSignal(sign) // no offset if sign === 1 ? {signal: `(${entry.mult}) * (${sign.signal})`} : entry.mult * sign; return offset; } else { entry = entry.mult = extend({}, entry.mult); } } entry.mult = sign; } return offset; } davidsims9t/devine-v0-app import React, { View, Text, TouchableHighlight, Component, AlertIOS, PushNotificationIOS, DeviceEventEmitter } from 'react-native' import t from 'tcomb-form-native' import VerifyUser from '../verify-user' import { Email, Password } from '../../utils/validation' import FormTemplate from '../../components/form-template' import SaveBtn from '../../components/save-btn' import BaseStyles from '../../themes/default/base' import SignUpStyles from '../../themes/default/signup' const Form = t.form.Form t.form.Form.stylesheet = SignUpStyles t.form.Form.templates = FormTemplate import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import { getUser, signUpUser } from '../../actions/user' import { postPushInstallation } from '../../actions/push' const mapStateToProps = state => ({ user: state.user.user, isUpdating: state.user.isUpdating, isSignedUp: state.user.isSignedUp, installation: state.push.installation }) const mapDispatchToProps = dispatch => { return bindActionCreators({ getUser, signUpUser, postPushInstallation }, dispatch) } /** * This class is responsble for allowing users to sign up. */ class SignUp extends Component { /** * Stores form value, sign up state, phone & email verification. * * @param {object} props * @return {void} */ constructor(props) { super(props) this.state = { value: null, isSignUpBtnDisabled: true, isPhoneVerified: true, isEmailVerified: true, signUpBtnLocation: 0 } } /** * Add keyboard listener. * * @return {void} */ componentWillMount() { DeviceEventEmitter.addListener('keyboardWillShow', this.keyboardWillShow.bind(this)) DeviceEventEmitter.addListener('keyboardWillHide', this.keyboardWillHide.bind(this)) } /** * Remove Push notification listener on unmount. * * @return {void} */ componentWillUnmount() { PushNotificationIOS.removeEventListener('register') } /** * Display sign up button above keyboard when the keyboard appears. * * @param {object} e - event object * @return {void} */ keyboardWillShow(e) { this.setState({signUpBtnLocation: e.endCoordinates.height - 48}) } /** * Remove the sign up back to the bottom when the keyboard disappears. * * @param {object} e - event object * @return {void} */ keyboardWillHide(e) { this.setState({signUpBtnLocation: 0}) } /** * Handles the user ValidationUtilsand sign-up process. * * @return {object} */ onSignUp() { const form = this.refs.form.getValue() if (form.email) { this.props.getUser({email: form.email}) this.setState({ isEmailVerified: false }) } if (form.phone) { this.props.getUser({phone: form.phone}) this.setState({ isPhoneVerified: false }) } if (!this.props.user || !this.props.user.length) { this.props.signUpUser(form) if (this.props.isSignedUp) { this.props.verifyUserModal.toggleVisbility() } else { AlertIOS.alert("Failed to sign up.") } } else { AlertIOS.alert("Username, email, or phone taken.") } } /** * After the user has signed up. Prompt them with the option to subscribe to push notifications. * * @return {void} */ onAfterValidation() { PushNotificationIOS.requestPermissions() PushNotificationIOS.addEventListener('register', (token) => { let date = new Date() const timeZone = date.getTimezoneOffset() / 60 this.props.postPushInstallation({ "deviceType": "ios", "deviceToken": token, "user": { "className": "_User", "__type": "Pointer", "objectId": this.props.user.id }, "timeZone": timeZone }) }) } /** * Validates and updates sign up button enabled state. * * @return {void} */ canSignUp() { const form = this.refs.form.getValue() this.setState({isSignUpBtnDisabled: form && form.errors && form.errors.length}) } /** * Specific form options for the registration form. * * @return {object} options */ getOptions() { const self = this return { auto: 'placeholders', fields: { username: { placeholder: 'Username (optional)', autoCorrect: false, autoCapitalize: "none", selectTextOnFocus: true, onBlur(e) { // self.props.getUser({username: e.nativeEvent.text}) } }, email: { placeholder: 'Email', autoCorrect: false, autoCapitalize: "none", keyboardType: 'email-address', selectTextOnFocus: true, onBlur(e) { // self.props.getUser({email: e.nativeEvent.text}) } }, phone: { placeholder: 'Phone', autoCorrect: false, keyboardType: 'phone-pad', selectTextOnFocus: true, onBlur(e) { // self.props.getUser({phone: e.nativeEvent.text}) } }, password: { placeholder: 'Password', secureTextEntry: true, selectTextOnFocus: true } } } } /** * Handles form update changes. * * @param {object} value - form field and value. * @return {void} */ onChange(value) { this.setState({value}) this.canSignUp() } /** * Render the sign up form. * * @return {object} */ render() { const SignUpForm = t.struct({ username: t.maybe(t.Str), email: t.maybe(Email), phone: t.maybe(t.Num), password: Password }) return ( By signing up, you agree to the Devine terms of service. ) } } export default connect(mapStateToProps, mapDispatchToProps)(SignUp) ihinsdale/mean-local-auth 'use strict'; angular.module('mean-local-authApp.controllers') .controller('NavCtrl', function($scope, $location, AuthService) { $scope.initialLoadUp = true; var refreshAuthStatus = function(isFirstRefresh) { AuthService.isAuthenticated().then(function(authStatus){ $scope.isAuthenticated = authStatus; if (isFirstRefresh) { $scope.initialLoadUp = false; } }, function(reason){ console.log('Error determining authentication status:', reason); $scope.isAuthenticated = null; if (isFirstRefresh) { $scope.initialLoadUp = false; } }); }; // set initial authentication status refreshAuthStatus(true); $scope.$on('signedIn', function(){ console.log('NavCtrl heard signedIn event'); // this event is emitted by our signup/signin functions refreshAuthStatus(); }); $scope.$on('notAuthorized', function(){ console.log('NavCtrl heard notAuthorized event'); // this event is broadcast by our 401 response interceptor if (AuthService.currentUser) { // if client-side thinks it's logged in, revise that AuthService.currentUser = null; } refreshAuthStatus(); }); $scope.signout = function() { AuthService.signout().then(function() { // update isAuthenticated status refreshAuthStatus(); // take user back to homepage $location.path('/'); }, function(reason) { console.log('Error signing out:', reason); }); }; }); import * as React from 'react' import { render } from 'react-testing-library' import SingleLineStringField from './' describe('components:SingleLineStringField', () => { it('works', () => { const { container } = render( null} /> ) expect(container).toMatchSnapshot() }) }) dabbers/dab.irc.managerbin/src/ChannelManager.js "use strict"; const Core = require('dab.irc.core/src'); const Parser = require('dab.irc.parser/src'); const UserManager_1 = require('./UserManager'); const ManagedChannel_1 = require('./ManagedChannel'); class ChannelManager { constructor(userManager = new UserManager_1.UserManager()) { this._channels = []; this._channelsProxy = new Proxy({}, { get: (proxy, name) => { return this._channels.filter((c) => c.display.toLocaleLowerCase() == name.toString().toLocaleLowerCase())[0]; } }); this._users = userManager; } get users() { return this._users; } get channels() { return this._channels; } get channel() { return this._channelsProxy; } register(server) { server.on(Parser.Events.JOIN, this.bindJoin.bind(this)); server.on(Parser.Events.PART, this.bindPart.bind(this)); server.on(Parser.Events.MODE, this.bindMode.bind(this)); server.on(Parser.Numerics.NAMREPLY, this.bindNames.bind(this)); } unregister(server) { server.removeListener(Parser.Events.JOIN, this.bindJoin); server.removeListener(Parser.Events.PART, this.bindJoin); server.removeListener(Parser.Events.MODE, this.bindMode); server.removeListener(Parser.Numerics.NAMREPLY, this.bindNames); } join(channel) { if (this._channels.filter((v, id, ar) => v.display.toLocaleLowerCase() == channel.display.toLocaleLowerCase()).length > 0) { return false; } if (channel instanceof ManagedChannel_1.ManagedChannel) { this._channels.push(channel); } else { this._channels.push(new ManagedChannel_1.ManagedChannel(channel.display, this)); } return true; } bindNickChange(s, m) { let msg = m; this._users.rename(msg.from.nick, msg.destination.nick); } bindJoin(s, m) { let msg = m; this._users.join(msg, msg.destination); } bindPart(s, m) { let msg = m; this._users.part(msg, msg.destination); } bindMode(s, m) { let msg = m; if (msg.destination instanceof Core.Channel) { let ch = this._channels.filter((v, i, a) => v.display.toLocaleLowerCase() == s.display.toLocaleLowerCase()); if (ch.length > 0) { ch[0].modeChanged(msg.modes); } } } bindNames(s, m) { let msg = m; for (let i in msg.users) { this._users.nameAdd(msg.users[i], msg.destination); } } part(channel) { let i = 0; for (i in this._channels) { if (this._channels[i].display == channel.display) { break; } } let res = this._channels[i].partMe(); if (res) { this._channels.splice(i, 1); } } } exports.ChannelManager = ChannelManager; //# sourceMappingURL=ChannelManager.js.mapexport const fakeLiveScan = [ { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi368039740.jpg", liveCallSign: null, liveCourse: 250.9, liveDirection: "upriver", liveDraft: null, liveEvent: "camanche", liveEvents: [ {camanche: 1645582322} ], liveInitLat: 41.786653333333334, liveInitLon: -90.24742, liveInitTS: 1645582281, liveIsLocal: false, liveLastLat: 41.786665, liveLastLon: -90.24739333333333, liveLastTS: 1645582322, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 368039740, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/no-image-placard.jpg", liveCallSign: null, liveCourse: 360, liveDirection: "undetermined", liveDraft: null, liveInitLat: 42.062215, liveInitLon: -90.17094166666666, liveInitTS: 1645582333, liveIsLocal: false, liveLastTS: 1645582333, liveLength: null, liveLocation: "Out back yonder", liveName: "", liveSpeed: 0, liveVesselID: 367520810, liveWidth: null, type: "Other Type" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi366970820.jpg", liveCallSign: null, liveCourse: 32.2, liveDirection: "upriver", liveDraft: null, liveEvent: "m512ua", liveEvents: [ {m512ua: 1645582285} ], liveInitLat: 41.78609333333333, liveInitLon: -90.24452, liveInitTS: 1645582264, liveIsLocal: true, liveLastLat: 41.78613166666667, liveLastLon: -90.24451, liveLastTS: 1645582284, liveLength: null, liveLocation: "At M-512 by Camanche marina 6 miles below Clinton drawbridge", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "Terrebonne", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 366970820, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi366986460.jpg", liveCallSign: null, liveCourse: 331.5, liveDirection: "downriver", liveDraft: null, liveEvent: "camanche", liveEvents:[ {camanche: 1645582293} ], liveInitLat: 41.79203666666667, liveInitLon: -90.24426666666666, liveInitTS: 1645582271, liveIsLocal: false, liveLastLat: 41.79204333333333, liveLastLon: -90.24426333333334, liveLastTS: 1645582293, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 366986460, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi368039740.jpg", liveCallSign: null, liveCourse: 250.9, liveDirection: "upriver", liveDraft: null, liveEvent: "camanche", liveEvents: [ {camanche: 1645582322} ], liveInitLat: 41.786653333333334, liveInitLon: -90.24742, liveInitTS: 1645582281, liveIsLocal: false, liveLastLat: 41.786665, liveLastLon: -90.24739333333333, liveLastTS: 1645582322, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 368039740, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi368039740.jpg", liveCallSign: null, liveCourse: 250.9, liveDirection: "upriver", liveDraft: null, liveEvent: "camanche", liveEvents: [ {camanche: 1645582322} ], liveInitLat: 41.786653333333334, liveInitLon: -90.24742, liveInitTS: 1645582281, liveIsLocal: false, liveLastLat: 41.786665, liveLastLon: -90.24739333333333, liveLastTS: 1645582322, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 368039740, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/no-image-placard.jpg", liveCallSign: null, liveCourse: 360, liveDirection: "undetermined", liveDraft: null, liveInitLat: 42.062215, liveInitLon: -90.17094166666666, liveInitTS: 1645582333, liveIsLocal: false, liveLastTS: 1645582333, liveLength: null, liveLocation: "The moon", liveName: "Plunderer", liveSpeed: 0, liveVesselID: 367520810, liveWidth: null, type: "Other Type" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi366970820.jpg", liveCallSign: null, liveCourse: 32.2, liveDirection: "upriver", liveDraft: null, liveEvent: "m512ua", liveEvents: [ {m512ua: 1645582285} ], liveInitLat: 41.78609333333333, liveInitLon: -90.24452, liveInitTS: 1645582264, liveIsLocal: true, liveLastLat: 41.78613166666667, liveLastLon: -90.24451, liveLastTS: 1645582284, liveLength: null, liveLocation: "At M-512 by 6 miles below Clinton drawbridge", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "Take Me To Dinner", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 366970820, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi368039740.jpg", liveCallSign: null, liveCourse: 250.9, liveDirection: "upriver", liveDraft: null, liveEvent: "camanche", liveEvents: [ {camanche: 1645582322} ], liveInitLat: 41.786653333333334, liveInitLon: -90.24742, liveInitTS: 1645582281, liveIsLocal: false, liveLastLat: 41.786665, liveLastLon: -90.24739333333333, liveLastTS: 1645582322, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "Bubbalicious", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 368039740, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi368039740.jpg", liveCallSign: null, liveCourse: 250.9, liveDirection: "upriver", liveDraft: null, liveEvent: "camanche", liveEvents: [ {camanche: 1645582322} ], liveInitLat: 41.786653333333334, liveInitLon: -90.24742, liveInitTS: 1645582281, liveIsLocal: false, liveLastLat: 41.786665, liveLastLon: -90.24739333333333, liveLastTS: 1645582322, liveLength: null, liveLocation: "In Camanche Harbor", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "Croakalopis", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 368039740, liveWidth: null, type: "Towing" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/no-image-placard.jpg", liveCallSign: null, liveCourse: 360, liveDirection: "undetermined", liveDraft: null, liveInitLat: 42.062215, liveInitLon: -90.17094166666666, liveInitTS: 1645582333, liveIsLocal: false, liveLastTS: 1645582333, liveLength: null, liveLocation: "At M-512 by 6 miles below Clinton drawbridge", liveName: "", liveSpeed: 0, liveVesselID: 367520810, liveWidth: null, type: "Other Type" }, { imageUrl: "https://storage.googleapis.com/www.clintonrivertraffic.com/images/vessels/mmsi366970820.jpg", liveCallSign: null, liveCourse: 32.2, liveDirection: "upriver", liveDraft: null, liveEvent: "m512ua", liveEvents: [ {m512ua: 1645582285} ], liveInitLat: 41.78609333333333, liveInitLon: -90.24452, liveInitTS: 1645582264, liveIsLocal: true, liveLastLat: 41.78613166666667, liveLastLon: -90.24451, liveLastTS: 1645582284, liveLength: null, liveLocation: "At M-512 by 6 miles below Clinton drawbridge", liveMarkerAlphaTS: null, liveMarkerAlphaWasReached: false, liveMarkerBravoTS: null, liveMarkerBravoWasReached: false, liveMarkerCharlieTS: null, liveMarkerCharlieWasReached: false, liveMarkerDeltaTS: null, liveMarkerDeltaWasReached: false, liveName: "Roadster", livePassageWasSaved: false, liveSpeed: 0, liveVesselID: 366970820, liveWidth: null, type: "Towing" } ]0 'use strict'; angular.module('myCollectionsApp', ['ui.router','ngResource','ngDialog','facebook']) .config(function(FacebookProvider) { // Set your appId through the setAppId method or // use the shortcut in the initialize method directly. var appId = '123123'; FacebookProvider.init(appId); }) .config(function($stateProvider, $urlRouterProvider) { $stateProvider // route for the home page .state('app', { url:'/', views: { 'header': { templateUrl : 'partials/header', controller : 'HeaderController' }, 'content': { templateUrl : 'partials/home', controller : 'HomeController' }, 'footer': { templateUrl : 'partials/footer', } } }) /** * Collections To Cash */ // route for the collections page .state('app.collections', { url: 'collections', views: { 'content@': { templateUrl : 'partials/collection', controller : 'CollectionController' } } }) // route for the collectiondetail page .state('app.collectiondetails', { url: 'collections/:id', views: { 'content@': { templateUrl : 'partials/collectiondetail', controller : 'CollectionDetailController' } } }) // route for the new collection page .state('app.newcollection', { url:'new', views: { 'content@': { templateUrl : 'partials/newcollection', controller : 'CollectionDetailController' } } }) // route for the edit collection page .state('app.editcollection', { url:'collections/:id/edit', views: { 'content@': { templateUrl : 'partials/editcollection', controller : 'CollectionDetailController' } } }) ; $urlRouterProvider.otherwise('/'); }) ; 0 (function () { var arM = angular.module('gsar.custdir.apiresolve'); arM.directive('paginationResolve', [function(){ return { scope: { 'resolveValue': '=', 'resolvePagination': '=' }, // {} = isolate, true = child, false/undefined = no change // CompanyList, controller: function($scope, $element, $attrs, $transclude, CompanyAPI, $timeout) { $scope.companyAll = $scope.resolveValue; $scope.pageAll = $scope.resolvePagination; console.log('$scope.companyAll --> ', $scope.companyAll); console.log('$scope.pageAll --> ', $scope.pageAll); // This is for displaying... $scope.setPerPage = function (itemEachPage) { var iep = parseInt(itemEachPage); $scope.pageAll.page_size = iep; $scope.pageAll.page_number = 1; }; $scope.$watch('pageAll', function (nv, ov) { if (nv !== ov) { var howManyItemsPerPage = $scope.pageAll.page_size; var howManyPagesWouldBeTurnedEachTime = $scope.pageAll.page_number; CompanyAPI.contentQuery(howManyItemsPerPage, howManyPagesWouldBeTurnedEachTime) .then(function (res) { $scope.companyAll = res.data; }); } else{ console.log('pagination doesn\'t change.'); } }, true); $scope.reformatAddress = function (companyAddress) { var addr = []; // these expressions are correct, but jshint prefer function... companyAddress.address1 ? addr.push(companyAddress.address1) : null; companyAddress.address2 ? addr.push(companyAddress.address2) : null; companyAddress.suburb ? addr.push(companyAddress.suburb) : null; companyAddress.state ? addr.push(companyAddress.state.split('-')[1]) : null; companyAddress.country ? addr.push(companyAddress.country) : null; companyAddress.postcode ? addr.push(companyAddress.postcode) : null; return addr.join(', '); }; }, // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment // template: '', templateUrl: './templates/partials/p2/p2Right/pagination-resolve.html', // replace: true, // transclude: true, // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})), link: function($scope, iElm, iAttrs, controller) { } }; }]); arM.directive('spinnerLoader', [function(){ return { scope: {}, // {} = isolate, true = child, false/undefined = no change controller: function($scope, $element, $attrs, $transclude, countLoad) { $scope.loadCountFunc = countLoad.getCounter; console.log('$scope.loadCountFunc --> ', $scope.loadCountFunc()); $scope.counterNum = countLoad.getCounter(); }, // require: 'ngModel', // Array = multiple requires, ? = optional, ^ = check parent elements restrict: 'E', // E = Element, A = Attribute, C = Class, M = Comment // template: '', templateUrl: './templates/partials/p2/p2Right/spinner-loader.html', // replace: true, // transclude: true, // compile: function(tElement, tAttrs, function transclude(function(scope, cloneLinkingFn){ return function linking(scope, elm, attrs){}})), link: function($scope, iElm, iAttrs, controller) { } }; }]); })();var middlewares = {}; middlewares.requestIndentifier = require('./requestIndentifier.js'); middlewares.workerIdentifier = require('./workerIdentifier.js'); module.exports = exports = middlewares; 1-10 export default [ '1', '4', '6', '8', '10', '12', '14', '16', '18', '20', '22', '24', '26', '28', '30', '32', '34', '36', '38', '40', '42', '44', '46', '48', '50', 'CP 10', 'CP 20', 'CP 30', 'CP 40', 'CP 50', 'CP 60', 'CP 70', 'CP 80', 'CP 90', 'CP 100', 'CP 110', 'CP 120', 'CP 130', 'CP 140', 'CP 150', 'CP 160' ]const map = new mapboxgl.Map({ container: 'map', style: 'https://basemaps.cartocdn.com/gl/positron-gl-style/style.json', center: [-122.42, 37.77], zoom: 12 }); carto.setDefaultAuth({ user: 'cartovl', apiKey: 'default_public' }); const source = new carto.source.Dataset('sf_stclines'); const s = carto.expressions; const viz = new carto.Viz({ width: 3, color: s.hsv(0.2, 1, .9) }); const layer = new carto.Layer('myCartoLayer', source, viz); layer.addTo(map); layer.on('loaded', () => window.loaded = true); // Used by screenshot testing utility 1-10 /* zephir_phpize_fix */ var PHP_ANALYZER = 'disabled'; var PHP_PGO = 'no'; var PHP_PGI = 'no'; kol-tools/MegSpot import Vue from 'vue'; import Vuex from 'vuex'; import { isExist } from '../utils/file'; // 注释这个的原因是因为会导致vuex操作失败 import { createPersistedState } from 'vuex-electron'; import modules from './modules'; Vue.use(Vuex); const store = new Vuex.Store({ modules, // 如果使用插件 vuex 无法使用console.log debugger 进行调试 plugins: [createPersistedState()], strict: process.env.NODE_ENV !== 'production' }); const checkStore = function(pathList = [], removeFnName = '') { let removeList = []; pathList.forEach(item => { if (!item || !isExist(item)) { removeList.push(item); } }); store.dispatch(removeFnName, removeList); }; // 校验文件/文件夹存在性 移除不存在的 todo:改成单次不展示 const { imageStore = {}, videoStore = {} } = store.state; const { imageFolders = [], imageList = [] } = imageStore; const { videoFolders = [], videoList = [] } = videoStore; checkStore(imageFolders, 'imageStore/removeImageFolders'); checkStore(imageList, 'imageStore/removeImages'); checkStore(videoFolders, 'videoStore/removeVideoFolders'); checkStore(videoList, 'videoStore/removeVideos'); export default store; src/apex/force-app/main/default/aura/DataGeneratorButton/DataGeneratorButtonController.js10-100 ({ doInit: function (component) { var action = component.get('c.getTaskStatus'), objectId = component.get('v.recordId'); action.setParams({ id: objectId }); action.setCallback(this, function (data) { var taskStatus = data.getReturnValue(); if (taskStatus === 'NOT STARTED') { component.set('v.show', true); } }); $A.enqueueAction(action); }, handleClick: function (component, event, handler) { var action = component.get('c.generateData'), stepEvent = component.get('c.sendInitialPlatformEvent'), objectId = component.get('v.recordId'); action.setParams({ id: objectId }); stepEvent.setParams({ id: objectId }); $A.enqueueAction(action); $A.enqueueAction(stepEvent); }, handleStepEvent: function (component, event, handler) { var status = event.getParam('status'), eventId = event.getParam('id'), objectId = component.get('v.recordId'); if (eventId != null && eventId === objectId) { component.set('v.show', false); } } }) const assert = require('assert'); const {Readable} = require('stream'); const Aline = require('../index.js'); function combineData(stream) { return new Promise((resolve, reject) => { const chunks = []; stream.on('data', data => chunks.push(data.toString())); stream.on('end', () => resolve(chunks)); stream.on('error', err => reject(err)); }); } [ ['should align single new lines to chunks', async function* () { yield 'foo\nba'; yield 'ar\nbaz'; }, ['foo\n', 'baar\n', 'baz']], ['should align multiple new lines to chunks', async function* () { yield 'foo\nbar\nbam\nra'; yield 'am\nbaz'; }, [ 'foo\nbar\nbam\n', 'raam\n', 'baz' ]], ['should align single chunk', async function* () { yield 'foo\nbar\nbam\nram'; }, [ 'foo\nbar\nbam\n', 'ram' ]], ['should return empty array', async function* () { yield ''; }, []], ['should return array with single word', async function* () { yield 'foo'; }, ['foo']], ['should align new line on last char', async function* () { yield 'foo\n'; }, ['foo\n']], ['should align new line on first char', async function* () { yield '\nfoo'; }, ['\n', 'foo']], ['should align new line on first and last char', async function* () { yield '\nfoo\n'; }, ['\nfoo\n']] ].forEach(([name, generate, target]) => it(name, async() => assert.deepStrictEqual(target, await combineData(Readable.from(generate()).pipe(new Aline()))))); lib/main.js var data = require('sdk/self').data; var buttons = require('sdk/ui/button/toggle'); var panels = require('sdk/panel'); var pageMods = require('sdk/page-mod'); var ss = require('sdk/simple-storage'); var hotkeys = require('sdk/hotkeys'); var ENABLE_CONVERSION_EVENT = "enable.event"; var CHANGE_CURRENCY_EVENT = "change.currency.event"; var CHANGE_RATE_USD_EVENT = "change.rate.usd.event"; var CHANGE_RATE_EUR_EVENT = "change.rate.eur.event"; var ENABLE_IFRAMES_CONVERSION_EVENT = "iframes.enable.event"; var CHANGE_RATE_EVENT = "change.rate.event"; var CHANGE_SELECTOR_EVENT = "change.selector.event"; var CHANGE_REGEXP_EVENT = "change.regexp.event"; var ENABLE_HOTKEY_EVENT = "hotkey.enable"; var ENABLED_PROP = "enabled"; var RATE_USD_PROP = "rate.usd"; var RATE_EUR_PROP = "rate.eur"; var CURRENCY_PROP = "currency"; var REGEXP_STR_PROP = "regexp.str"; var REGEXP_STR_DEFAULT_PROP = "regexp.str.default"; var REGEXP_FLAGS_PROP = "regexp.flags"; var REGEXP_FLAGS_DEFAULT_PROP = "regexp.flags.default"; var SELECTOR_PROP = "selector"; var SELECTOR_DEFAULT_PROP = "selector.default"; var CONVERT_IFRAMES_PROP = "convert_iframes"; var HOTKEY_ENABLED_PROP = "hotkey.enabled"; var HOTKEY_MODIFIERS_PROP = "hotkey.modifiers"; var HOTKEY_KEY_PROP = "hotkey.key"; var currency = { usd : "USD", eur : "EUR" }; var changeStateEventHandlers = getChangeStateEventHandlers(); var iconSet = {'16': data.url('icon-16.png'), '32': data.url('icon-32.png')}; var iconTurnedSet = {'16': data.url('icon-16-on.png'), '32': data.url('icon-32-on.png')}; initDefaultOptions(); var turnedOn = ss.storage[ENABLED_PROP] || false; var pageMod = null; var pageModOptions = null; var workers = []; var mainButton = initMainButton(); var menu = initMenu(); var hotkey = initHotkey(); if (turnedOn) { pageMod = createNewPageMod(); } function initMainButton() { var mainButton = buttons.ToggleButton({ id: 'SqC-main-link', label: 'Convert squirrels', icon: turnedOn ? iconTurnedSet : iconSet, onChange: function(state) { if (state.checked) { menu.show(); } } }); return mainButton; } function initMenu() { var menu = panels.Panel({ contentURL: data.url('menu.html'), contentScriptOptions: getMenuOptions(), position: mainButton, height: 400, onHide: function() { updateMainBtnIcon(false); } }); menu.port.on('change-state-event', function(event) { changeStateEventHandlers[event.type](event.data); }); return menu; } function initHotkey() { if (ss.storage[HOTKEY_ENABLED_PROP]) { return hotkeys.Hotkey({ combo: getHotkeyCombo(), onPress: function() { changeStateEventHandlers[ENABLE_CONVERSION_EVENT](!turnedOn, true); } }); } else { return null; } } function destroyHotkey() { if (hotkey != null) { hotkey.destroy(); hotkey = null; } } function getHotkeyCombo() { console.log((ss.storage[HOTKEY_MODIFIERS_PROP] & 2 ? 'accel-' : '') + (ss.storage[HOTKEY_MODIFIERS_PROP] & 1 ? 'alt-' : '') + (ss.storage[HOTKEY_MODIFIERS_PROP] & 4 ? 'shift-' : '') + ss.storage[HOTKEY_KEY_PROP].toLowerCase()); return (ss.storage[HOTKEY_MODIFIERS_PROP] & 2 ? 'accel-' : '') + (ss.storage[HOTKEY_MODIFIERS_PROP] & 1 ? 'alt-' : '') + (ss.storage[HOTKEY_MODIFIERS_PROP] & 4 ? 'shift-' : '') + ss.storage[HOTKEY_KEY_PROP].toLowerCase(); } function createNewPageMod() { console.log("[ADDON] createNewPageMod()"); pageModOptions = getPageModeOptions(); var attachTargets = ["existing", "top"]; if (ss.storage[CONVERT_IFRAMES_PROP]) { attachTargets.push("frame"); } return pageMods.PageMod({ include: '*.onliner.by', contentScriptFile: [data.url('jquery-1.11.2.min.js'), data.url('common.js'), data.url('onlinerBy_catalog.js')], contentStyleFile: data.url('common.css'), attachTo: attachTargets, contentScriptWhen: 'ready', contentScriptOptions: pageModOptions, onAttach: function(worker) { console.log('[ADDON] New worker attached'); console.log('[ADDON] Existing workers: ' + workers); workers.push(worker); worker.on('detach', function () { console.log('[ADDON] Recieved detach from PageMod'); detachWorker(this, workers); }); } }); } function destroyPageMod() { console.log("[ADDON] destroyPageMod()"); for (var i = 0; i < workers.length; ++i) { workers[i].port.emit('detach-custom', {}); workers[i].destroy(); // Sends 'detach' message to content scripts } pageMod.destroy(); // Doesn't send detach message to workers as well as to scripts pageMod = null; pageModOptions = null; workers = []; } function refreshPageMod(eventType, eventData) { console.log("[ADDON] refreshPageMod()"); for (var i = 0; i < workers.length; ++i) { workers[i].port.emit('change-state-event', {'type': eventType, 'data': eventData}); } } function detachWorker(worker, workerArray) { console.log("[ADDON] detachWorker()"); var index = workerArray.indexOf(worker); if(index != -1) { workerArray.splice(index, 1); } } function getChangeStateEventHandlers() { var handlers = {}; handlers[ENABLE_CONVERSION_EVENT] = function(enabled, uncheckMainBtn) { console.log("[ADDON] Received enable-conversion message: " + enabled); ss.storage[ENABLED_PROP] = enabled; turnedOn = enabled; updateMainBtnIcon(!uncheckMainBtn); if (enabled) { pageMod = createNewPageMod(); } else if (pageMod) { destroyPageMod(); } }; handlers[CHANGE_CURRENCY_EVENT] = function(newCurrency) { console.log("[ADDON] Received change-currency message: " + newCurrency); ss.storage[CURRENCY_PROP] = newCurrency; var rate = newCurrency == currency.usd ? ss.storage[RATE_USD_PROP] : ss.storage[RATE_EUR_PROP]; if (turnedOn) { refreshPageMod(CHANGE_CURRENCY_EVENT, {"currency" : newCurrency, "rate" : rate}); pageModOptions.currency = newCurrency; pageModOptions.rate = rate; } }; handlers[CHANGE_RATE_USD_EVENT] = function(rate) { console.log("[ADDON] Received change-rate-usd message"); ss.storage[RATE_USD_PROP] = rate; if (turnedOn && ss.storage[CURRENCY_PROP] == currency.usd) { refreshPageMod(CHANGE_RATE_EVENT, rate); pageModOptions.rate = rate; } }; handlers[CHANGE_RATE_EUR_EVENT] = function(rate) { console.log("[ADDON] Received change-rate-eur message"); ss.storage[RATE_EUR_PROP] = rate; if (turnedOn && ss.storage[CURRENCY_PROP] == currency.eur) { refreshPageMod(CHANGE_RATE_EVENT, rate); pageModOptions.rate = rate; } }; handlers[ENABLE_IFRAMES_CONVERSION_EVENT] = function(checked) { console.log("[ADDON] Recieved enable-iframes-conversion event" + checked); ss.storage[CONVERT_IFRAMES_PROP] = checked; if (turnedOn) { destroyPageMod(); pageMod = createNewPageMod(); } }; handlers[CHANGE_REGEXP_EVENT] = function(regexpData) { console.log("[ADDON] Recieved change-regexp event: " + JSON.stringify(regexpData)); ss.storage[REGEXP_STR_PROP] = regexpData.str; ss.storage[REGEXP_FLAGS_PROP] = regexpData.flags; if (turnedOn) { refreshPageMod(CHANGE_REGEXP_EVENT, regexpData); pageModOptions["regexp.str"] = regexpData.str; // todo: hardcoded strings! pageModOptions["regexp.flags"] = regexpData.flags; // todo: hardcoded strings! } }; handlers[CHANGE_SELECTOR_EVENT] = function(newSelector) { console.log("[ADDON] Recieved change-selector event: " + newSelector); ss.storage[SELECTOR_PROP] = newSelector; if (turnedOn) { refreshPageMod(CHANGE_SELECTOR_EVENT, newSelector); pageModOptions.selector = newSelector; // todo: change selector to [] with corresponding property } }; handlers[ENABLE_HOTKEY_EVENT] = function(data) { console.log("[ADDON] Recieved enable-hotkey event: " + JSON.stringify(data)); ss.storage[HOTKEY_ENABLED_PROP] = data.enabled; ss.storage[HOTKEY_MODIFIERS_PROP] = data.modifiers; ss.storage[HOTKEY_KEY_PROP] = data.key; if (data.enabled) { hotkey = initHotkey(); } else { destroyHotkey(); } }; return handlers; } function initDefaultOptions() { console.log('[ADDON] initDefaultOptions() ss.storage: ' + JSON.stringify(ss.storage)); if (ss.storage[REGEXP_STR_DEFAULT_PROP] == undefined) { ss.storage[REGEXP_STR_DEFAULT_PROP] = "(\\d(?:\\d|\\s| |\\.)*)(?:\\s| )*(?:<\\/\\w*>)?(тыс|тысяч|млн|миллион|млрд|миллиард)?(?:\\s| )*((?:(?:<\\w*>)?(?:\\s| )*руб\\.?)|-|–)"; } if (ss.storage[REGEXP_FLAGS_DEFAULT_PROP] == undefined) { ss.storage[REGEXP_FLAGS_DEFAULT_PROP] = "gim"; } if (ss.storage[SELECTOR_DEFAULT_PROP] == undefined) { ss.storage[SELECTOR_DEFAULT_PROP] = ".pprice_byr,.pprice,.price,.cost,.b-seller-block-1__sellers>ul>li>a,tr.pline2:last>td:not(.pdinfohead),.b-offers-desc__info-price,sup,.b-offers-desc__info-price a"; } if (ss.storage[ENABLED_PROP] == undefined) { ss.storage[ENABLED_PROP] = false; } if (ss.storage[RATE_USD_PROP] == undefined) { ss.storage[RATE_USD_PROP] = 15000; } if (ss.storage[RATE_EUR_PROP] == undefined) { ss.storage[RATE_EUR_PROP] = 15000; } if (ss.storage[CURRENCY_PROP] == undefined) { ss.storage[CURRENCY_PROP] = currency.usd; } if (ss.storage[REGEXP_STR_PROP] == undefined) { ss.storage[REGEXP_STR_PROP] = ss.storage[REGEXP_STR_DEFAULT_PROP]; } if (ss.storage[REGEXP_FLAGS_PROP] == undefined) { ss.storage[REGEXP_FLAGS_PROP] = ss.storage[REGEXP_FLAGS_DEFAULT_PROP]; } if (ss.storage[SELECTOR_PROP] == undefined) { ss.storage[SELECTOR_PROP] = ss.storage[SELECTOR_DEFAULT_PROP]; } if (ss.storage[CONVERT_IFRAMES_PROP] == undefined) { ss.storage[CONVERT_IFRAMES_PROP] = false; } if (ss.storage[HOTKEY_ENABLED_PROP] == undefined) { ss.storage[HOTKEY_ENABLED_PROP] = false; } if (ss.storage[HOTKEY_MODIFIERS_PROP] == undefined) { ss.storage[HOTKEY_MODIFIERS_PROP] = 0; // 000 in binary representation carrying the following sense: shift-false, accel-false, alt-false } if (ss.storage[HOTKEY_KEY_PROP] == undefined) { ss.storage[HOTKEY_KEY_PROP] = ""; } } function getPageModeOptions() { return { "rate" : getRateForCurrentCurrency(), "currency" : ss.storage[CURRENCY_PROP], "regexp.str" : ss.storage[REGEXP_STR_PROP], "regexp.flags" : ss.storage[REGEXP_FLAGS_PROP], "selector" : ss.storage[SELECTOR_PROP] }; } function getMenuOptions() { return { "enabled" : ss.storage[ENABLED_PROP], "rate.usd" : ss.storage[RATE_USD_PROP], "rate.eur" : ss.storage[RATE_EUR_PROP], "currency" : ss.storage[CURRENCY_PROP], "regexp.str" : ss.storage[REGEXP_STR_PROP], "regexp.str.default" : ss.storage[REGEXP_STR_DEFAULT_PROP], "regexp.flags" : ss.storage[REGEXP_FLAGS_PROP], "regexp.flags.default" : ss.storage[REGEXP_FLAGS_DEFAULT_PROP], "selector" : ss.storage[SELECTOR_PROP], "selector.default" : ss.storage[SELECTOR_DEFAULT_PROP], "convert_iframes" : ss.storage[CONVERT_IFRAMES_PROP], "hotkey.enabled": ss.storage[HOTKEY_ENABLED_PROP], "hotkey.modifiers" : ss.storage[HOTKEY_MODIFIERS_PROP], "hotkey.key" : ss.storage[HOTKEY_KEY_PROP] }; } function updateMainBtnIcon(checked) { mainButton.state('window', { icon: turnedOn ? iconTurnedSet : iconSet, checked: checked }); } function getRateForCurrentCurrency() { var rateProp = ss.storage[CURRENCY_PROP] == currency.usd ? RATE_USD_PROP : RATE_EUR_PROP; return ss.storage[rateProp]; }import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import { withStyles } from '@material-ui/styles'; import { Card, CardContent, CardActions, Typography, Grid, Divider } from '@material-ui/core'; import AccessTimeIcon from '@material-ui/icons/AccessTime'; import BookmarksIcon from '@material-ui/icons/Bookmarks'; const styles = theme => ({ root: {}, imageContainer: { height: 64, width: 64, margin: '0 auto', border: `1px solid ${theme.palette.divider}`, borderRadius: '5px', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }, image: { width: '100%' }, statsItem: { display: 'flex', alignItems: 'center' }, statsIcon: { color: theme.palette.icon, marginRight: theme.spacing(1) } }); class DatasetCard extends React.Component { render() { const { className, dataset, classes, ...rest } = this.props; return (
    Dataset
    {dataset.title} {dataset.user} {dataset.description.slice(0, 175) + '...'}
    Updated 2hr ago {dataset.totalDownloads} Bookmarks
    ); } } DatasetCard.propTypes = { className: PropTypes.string, classes: PropTypes.object, dataset: PropTypes.object.isRequired }; export default withStyles(styles)(DatasetCard); frontend/src/reducers/posts.js import { ADD_POST, DOWNVOTE_POST, EDIT_POST, FETCHING_POSTS, POST_COUNT_DOWN, POST_COUNT_UP, REMOVE_POST, SET_POSTS, UPVOTE_POST } from "../actions/posts"; const INITIAL_STATE = { postsList: {posts: [], loading: false} }; export default function posts(state = INITIAL_STATE, action) { switch (action.type) { case SET_POSTS: return { ...state, postsList: {posts: action.posts, loading: false} }; case FETCHING_POSTS: return { ...state, postsList: {posts: [], loading: true} }; case UPVOTE_POST: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.map( (post) => post.id === action.postId ? { ...post, voteScore: post.voteScore + 1 } : post ) } }; case DOWNVOTE_POST: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.map( (post) => post.id === action.postId ? { ...post, voteScore: post.voteScore - 1 } : post ) } }; case REMOVE_POST: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.filter((post) => post.id !== action.postId) } }; case ADD_POST: let newArray = state.postsList.posts.slice(); newArray.push(action.post); return { ...state, postsList: { ...state.postsList, posts: newArray } }; case EDIT_POST: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.map( (post) => post.id === action.postUpdate.id ? { ...post, title: action.postUpdate.title, body: action.postUpdate.body } : post ) } }; case POST_COUNT_UP: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.map( (post) => post.id === action.postId ? { ...post, commentCount: post.commentCount + 1 } : post ) } }; case POST_COUNT_DOWN: return { ...state, postsList: { ...state.postsList, posts: state.postsList.posts.map( (post) => post.id === action.postId ? { ...post, commentCount: post.commentCount - 1 } : post ) } }; default: return state; } }marketing-analytics/activation/data-tasks-coordinator/src/tasks/bigquery/export_schema_task.js100-1000 // Copyright 2019 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. /** * @fileoverview Export task class. */ 'use strict'; const {Table} = require('@google-cloud/bigquery'); const {File} = require('@google-cloud/storage'); const {BigQueryAbstractTask} = require('./bigquery_abstract_task.js'); const { TaskType, BigQueryTableConfig, StorageFileConfig, } = require('../../task_config/task_config_dao.js'); /** * @typedef {{ * type:TaskType.EXPORT_SCHEMA, * source:!BigQueryTableConfig, * destination:!StorageFileConfig, * appendedParameters:(Object|undefined), * next:(string|!Array|undefined), * }} */ let ExportSchemaTaskConfig; /** BigQuery get table schema to Cloud Storage task class. */ class ExportSchemaTask extends BigQueryAbstractTask { /** @override */ getBigQueryForTask() { /** @const {BigQueryTableConfig} */ const sourceTable = this.config.source; return this.getBigQuery(sourceTable); } /** * Exports a BigQuery Table schema into Cloud Storage file. * @override */ async doTask() { /** @const {BigQueryTableConfig} */ const source = this.config.source; /** @const {StorageFileConfig} */ const destination = this.config.destination; /** @const {Table} */ const sourceTable = this.getBigQueryForTask() .dataset(source.datasetId) .table(source.tableId); /** @const {File} */ const file = this.getStorage(destination) .bucket(destination.bucket) .file(destination.name); const [{metadata: {schema}}] = await sourceTable.get(); this.logger.debug('Get schema of ', source); this.logger.debug(schema); await file.save(JSON.stringify(schema)); return { parameters: this.appendParameter({schemaFile: destination}), }; } /** @override */ async isDone() { return true; } } module.exports = { ExportSchemaTaskConfig, ExportSchemaTask, }; 'use strict'; const {test, stub} = require('supertape'); const {stopAll, reRequire} = require('mock-require'); test('putout: cli: cache files: is changed: isNodeModulesChanged: cannot find', async (t) => { const fileCache = { canUseCache: stub(), setInfo: stub(), reconcile: stub(), }; const findUp = stub(); const {isNodeModulesChanged} = reRequire('./is-changed'); const result = await isNodeModulesChanged(fileCache, {findUp}); stopAll(); t.notOk(result); t.end(); }); test('putout: cli: cache files: is changed: isNodeModulesChanged', async (t) => { const fileCache = { canUseCache: stub(), setInfo: stub(), reconcile: stub(), }; const findUp = stub().returns('xx'); const {isNodeModulesChanged} = reRequire('./is-changed'); const result = await isNodeModulesChanged(fileCache, {findUp}); stopAll(); t.ok(result); t.end(); }); test('putout: cli: cache files: is changed: isEslintChanged: cannot find', async (t) => { const fileCache = { canUseCache: stub(), setInfo: stub(), reconcile: stub(), }; const findUp = stub(); const {isEslintChanged} = reRequire('./is-changed'); const result = await isEslintChanged(fileCache, {findUp}); stopAll(); t.notOk(result); t.end(); }); test('putout: cli: cache files: is changed: isEslintChanged', async (t) => { const fileCache = { canUseCache: stub(), setInfo: stub(), reconcile: stub(), }; const findUp = stub().returns('xxx'); const {isEslintChanged} = reRequire('./is-changed'); const result = await isEslintChanged(fileCache, {findUp}); stopAll(); t.ok(result); t.end(); }); test('putout: cli: cache files: is changed', async (t) => { const fileCache = { canUseCache: stub(), setInfo: stub(), reconcile: stub(), }; const findUp = stub(); const isChanged = reRequire('./is-changed'); const result = await isChanged(fileCache, {findUp}); stopAll(); t.notOk(result); t.end(); }); 'use strict'; const Logger = require('../').Logger; const logger = new Logger('your-namespace'); // The following will write messages into log file // You can use LOGGER_TYPES=* node dummy.js or LOGGER_TYPES=info,error node dummy.js // to output message into console logger.warning('w', 'Warning message'); logger.alert('a', 'Alert message'); logger.error('e', 'Error message'); logger.critical('c', 'Critical message'); logger.info('i', 'Info message'); logger.notice('n', 'Notice message'); logger.success('s', 'Success message'); logger.badrequest('b', 'Badrequest message'); logger.unauthorized('login', {username: 'dummy', password: ''}); // The debug behave just like node debug module // and you should use the DEBUG variable // DEBUG=your-namespace node dummy.js or DEBUG=* node dummy.js // Note: the debug method does not write message into log file logger.debug('Debug message'); // Or you can combine all of them like: // DEBUG=* LOGGER_TYPES=* node dummy.js // ENJOY THE RAINBOW :D documentation/html/class_convex_hull_graphix.js0 var class_convex_hull_graphix = [ [ "ConvexHullGraphix", "class_convex_hull_graphix.html#a0788aec48348b01f660d3f6e08724c0c", null ], [ "add_edge", "class_convex_hull_graphix.html#ab86fe28af236abd45c987599920bfe39", null ], [ "add_edge", "class_convex_hull_graphix.html#abd57f96a83ba7c4aa4da7cc00bf1530f", null ], [ "init_points", "class_convex_hull_graphix.html#ac9c25b9e69637f4ffa4cb9515a0fb221", null ], [ "remove_edge", "class_convex_hull_graphix.html#a80800d54bcbd5031eaef916d52c73139", null ], [ "remove_edge", "class_convex_hull_graphix.html#a35c4a800c524d5ff2001d3724791bf66", null ], [ "update_event", "class_convex_hull_graphix.html#a72101c075bb4fca0db552e888d1530b3", null ], [ "update_pivot_point", "class_convex_hull_graphix.html#a463b42e0cafea416fa9a193e5efed532", null ] ];import React, { Component } from 'react'; import { View, Text, ActivityIndicator } from 'react-native'; import Gallery from 'react-native-image-gallery'; export default class DemoGallery extends Component { constructor (props) { super(props); this.state = { index: 0, images: [ // { // caption: 'This image is bundled with the app, so you must provide dimensions for it', // source: require('./static/images/placehold.jpg'), // dimensions: { width: 540, height: 720 } // }, { caption: 'This image has a broken URL', source: { uri: 'http://wrongdomain.tld/images/wrongimage.jpg' } }, { caption: 'Remote image with supplied dimensions', source: { uri: 'http://i.imgur.com/gSmWCJF.jpg' }, dimensions: { width: 1200, height: 800 } }, { caption: 'Caption 4', source: { uri: 'http://i.imgur.com/XP2BE7q.jpg' } }, { caption: 'Caption 5', source: { uri: 'http://i.imgur.com/5nltiUd.jpg' } }, { caption: 'Caption 6', source: { uri: 'http://i.imgur.com/6vOahbP.jpg' } }, { caption: 'Caption 7', source: { uri: 'http://i.imgur.com/kj5VXtG.jpg' } }, { caption: 'Caption 8', source: { uri: 'http://i.imgur.com/BN8RVGa.jpg' } }, { caption: 'Caption 9', source: { uri: 'http://i.imgur.com/jXbhTbv.jpg' } }, { caption: 'Caption 10', source: { uri: 'http://i.imgur.com/30s12Qj.jpg' } }, { caption: 'Caption 11', source: { uri: 'http://i.imgur.com/4A1Q49y.jpg' } }, { caption: 'Caption 12', source: { uri: 'http://i.imgur.com/JfVDTF9.jpg' } }, { caption: 'Caption 13', source: { uri: 'http://i.imgur.com/Vv4bmwR.jpg' } } ] }; this.onChangeImage = this.onChangeImage.bind(this); // this.addImages(); // this.removeImages(); // this.removeImage(2, 3000); } addImages () { // Debugging helper : keep adding images at the end of the gallery. setInterval(() => { const newArray = [...this.state.images, { source: { uri: 'http://i.imgur.com/DYjAHAf.jpg' } }]; this.setState({ images: newArray }); }, 5000); } removeImage (slideIndex, delay) { // Debugging helper : remove a given image after some delay. // Ensure the gallery doesn't crash and the scroll is updated accordingly. setTimeout(() => { const newArray = this.state.images.filter((element, index) => index !== slideIndex); this.setState({ images: newArray }); }, delay); } removeImages () { // Debugging helper : keep removing the last slide of the gallery. setInterval(() => { const { images } = this.state; console.log(images.length); if (images.length <= 1) { return; } const newArray = this.state.images.filter((element, index) => index !== this.state.images.length - 1); this.setState({ images: newArray }); }, 2000); } onChangeImage (index) { this.setState({ index }); } renderError () { return ( This image cannot be displayed... ... but this is fine :) ); } get caption () { const { images, index } = this.state; return ( { (images[index] && images[index].caption) || '' } ); } get galleryCount () { const { index, images } = this.state; return ( { index + 1 } / { images.length } ); } render () { return ( { this.galleryCount } { this.caption } ); } }0 const ProfileModel = require('../models/ProfileModel'); async function getAllProfiles() { try { return await ProfileModel.find({}); } catch (err) { throw err; } } async function getProfileByName(name) { try { return await ProfileModel.findOne({"name": name}); } catch (err) { throw err; } } module.exports.getAllProfiles = getAllProfiles; module.exports.getProfileByName = getProfileByName; let array = [ "assests/1.jpg", "assests/2.jpg", "assests/3.jpg", "assests/4.jpg", "assests/5.jpg", ]; const section = document.getElementById("section"); const next = document.getElementById("next"); const back = document.getElementById("back"); let current = +section.getAttribute("data-current"); next.addEventListener("click", function lis() { current++; if (current >= array.length) { current = 0; } section.setAttribute("data-current", current); section.innerHTML = ""; }); back.addEventListener("click", function () { var current = +section.getAttribute("data-current"); current--; if (current < 0) { current = array.length - 1; } section.setAttribute("data-current", current); section.innerHTML = ""; }); /***************************************************************************** * Open MCT Web, Copyright (c) 2014-2015, United States Government * as represented by the Administrator of the National Aeronautics and Space * Administration. All rights reserved. * * Open MCT Web is 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. * * Open MCT Web includes source code licensed under additional open source * licenses. See the Open Source Licenses file (LICENSES.md) included with * this source code distribution or the Licensing information page available * at runtime from the About dialog for additional information. *****************************************************************************/ /*global define*/ define( function () { "use strict"; var DEFAULT_IDENTITY = { key: "user", name: "" }, DIALOG_STRUCTURE = { name: "Identify Yourself", sections: [{ rows: [ { name: "User ID", control: "textfield", key: "key", required: true }, { name: "Human name", control: "textfield", key: "name", required: true } ]}] }; /** * Example implementation of an identity service. This prompts the * user to enter a name and user ID; in a more realistic * implementation, this would be read from a server, possibly * prompting for a user name and password (or similar) as * appropriate. * * @implements {IdentityService} * @memberof platform/identity */ function ExampleIdentityProvider(dialogService) { // Handle rejected dialog messages by treating the // current user as undefined. function echo(v) { return v; } function giveUndefined() { return undefined; } this.userPromise = dialogService.getUserInput(DIALOG_STRUCTURE, DEFAULT_IDENTITY) .then(echo, giveUndefined); } ExampleIdentityProvider.prototype.getUser = function () { return this.userPromise; }; return ExampleIdentityProvider; } ); mrtonyhuynh/pubnow-frontend const data = [ { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Cộng hòa xã hội chủ nghĩa việt nam độc lập tự do hạnh phúc', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam', 'độc lập'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: [ 'cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam', 'độc lập', 'tự do', 'hạnh phúc', 'tôi', 'nói', 'đồng bào', 'có nghe', 'rõ không', 'hả', 'nếu không', 'nghe', 'rõ', ], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, { avatar: 'https://bulma.io/images/placeholders/128x128.png', author: '', date: '13 tháng 9 năm 2019', title: 'Có mắt như mù', tags: ['cộng hòa', 'xã hội', 'chủ nghĩa', 'việt nam'], views: 12, clips: 25, comments: 153, posts: 12, claps: 1563, }, ] export default data xyla-io/datadragon0 const mongoose = require('mongoose'); const Schema = mongoose.Schema; const Q = require('q'); let AdjustCredentialSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'User', required: 'Please provide a user', }, credentialCreationDate: { type: Date, default: () => new Date(), }, name: { type: 'string', required: 'Please provide a credential name', }, userToken: { type: 'string', required: 'Please provide a user token', }, appToken: { type: 'string', required: 'Please provide an app token', }, lastRevenueReportDate: { type: Date, }, }); AdjustCredentialSchema.index({ user: 1, name: 1}, { unique: true }); let AdjustCredential = mongoose.model('AdjustCredential', AdjustCredentialSchema, 'adjustCredentials'); AdjustCredential.createCredential = function(newCredential) { return newCredential.save(); }; AdjustCredential.deleteById = function(credentialID) { return AdjustCredential.findById(credentialID).then(credential => credential.remove()); }; AdjustCredential.getCredentialById = function(credentialID) { return AdjustCredential.findById(credentialID); }; AdjustCredential.getUserCredentials = function(userID) { return AdjustCredential.find({ user: new mongoose.Types.ObjectId(userID) }); }; AdjustCredential.deleteUserCredentials = function(userID) { return AdjustCredential.find({ user: new mongoose.Types.ObjectId(userID) }).then( credentials => Q.allSettled(credentials.map(credential => credential.remove())).then( results => { console.log('finished deleting user adjust credentials'); let errors = results.filter(result => result.state === 'rejected').map(result => result.reason); if (errors.count) { throw new Error('Failed to delete user adjust credentials. Errors:\n\n' + errors.join('\n')) } return null; })); }; module.exports.AdjustCredential = AdjustCredential;/* @flow */ export default (input: string | Array, size: number = 5) => { if (Array.isArray(input)) { input = input.join('') } size = parseInt(size) const groups = [] for (let k = 0; k < input.length; k += size) { groups.push(input.substr(k, size)) } return groups } (function() { var data = {}, chunk_size = 32, seed = 0, size = 32, chunk_x = 0, chunk_y = 0, water = 0, roughness = 1, map = document.getElementById("map"), max_height = 0; function val(x, y, v) { var index = x + '_' + y; if (typeof(v) != 'undefined') { //console.log('val: base declared'); data[index] = Math.max(0.0, Math.min(1.0, v)); } else if (x <= 0 || y <= 0 || x >= size-1 || y >= size-1) { //console.log('val: bound coords'); data[index] = Math.max(0.0, Math.min(1.0, water)); } else { if (x <= 0 || x >= size || y <= 0 || y >= size) return 0.0; var base; if (data[index] == null) { // К этому блоку мы ещё вернемся ниже. base = 1; while (((x & base) == 0) && ((y & base) == 0)) base <<= 1; if (((x & base) != 0) && ((y & base) != 0)) squareStep(x, y, base); else diamondStep(x, y, base); } } max_height < data[index] && (max_height = data[index]); return data[index]; } function displace(v, blockSize, x, y) { return (v + (randFromPair(x, y, seed) - 0.5) * blockSize * 2 / size * roughness); } function squareStep(x, y, blockSize) { if (data[x + '_' + y] == null) { val(x, y, displace((val(x - blockSize, y - blockSize) + val(x + blockSize, y - blockSize) + val(x - blockSize, y + blockSize) + val(x + blockSize, y + blockSize)) / 4, blockSize, x, y)); } } function diamondStep(x, y, blockSize) { if (data[x + '_' + y] == null) { val(x, y, displace((val(x - blockSize, y) + val(x + blockSize, y) + val(x, y - blockSize) + val(x, y + blockSize)) / 4, blockSize, x, y)); } } function randFromPair(x, y) { for (var i = 0; i < 32; i++) { var xm7 = x % 7; var xm13 = x % 13; var xm1301081 = x % 1301081; var ym8461 = y % 8461; var ym105467 = y % 105467; var ym105943 = y % 105943; y = x + seed; x += (xm7 + xm13 + xm1301081 + ym8461 + ym105467 + ym105943); } return (xm7 + xm13 + xm1301081 + ym8461 + ym105467 + ym105943) / 1520972.0; } document.querySelector('button.generator').onclick = function() { var button = this, form = button.form, count = 0; //data = {}; //max_height = 0; seed = +form.seed.value; size = +form.size.value; chunk_size = +form.chunk_size.value; chunk_x = +form.chunk_x.value; chunk_y = +form.chunk_y.value; water = +form.base.value; roughness = +form.roughness.value; console.log('chunk',[Math.max(0,chunk_x*chunk_size),Math.max(0,chunk_y*chunk_size)],[Math.min(size,(+chunk_x+1)*chunk_size),Math.min(size,(+chunk_y+1)*chunk_size)]); for (var i = Math.max(0,chunk_x*chunk_size); i < Math.min(size,(chunk_x+1)*chunk_size); i++) { for (var j = Math.max(0,chunk_y*chunk_size); j < Math.min(size,(chunk_y+1)*chunk_size); j++) { if ( ! data[i+'_'+j]) { /*if (i == 0 || j == 0 || i == size-1 || j == size-1) { val(i,j,base); } else {*/ val(i,j); //} count++; } } } console.log(seed,size,roughness,data,count,max_height); return false; }; document.querySelector('button.render').onclick = function() { var button = this, form = button.form, size = form.size.value; map.innerHTML = ''; for (var i = 0; i < size; i++) { for (var j = 0; j < size; j++) { var v = data[i+'_'+j]; if (v) { var cell = document.createElement('span'), color = Math.floor(255*(1-v));///(max_height>0?max_height:1))); cell.className = 'map-cell'; cell.style = 'background: rgb('+color+','+color+','+color+');'; map.appendChild(cell); } else { var cell = document.createElement('span'); cell.className = 'map-cell'; map.appendChild(cell); } } map.appendChild(document.createElement('br')); } return false; }; document.querySelector('button.reset').onclick = function() { data = {}; max_height = 0; return false; }; })();vendor/rest_api/navbarUpdate.js0 let $signupButton = $('#signupButton'); let $loginButton = $('#loginButton'); let $logoutButton = $('#logoutButton'); let $profileButton = $('#profileButton'); let $welcomeUsername = $('#welcomeUsername'); let $navUsername = $('#navUsername'); let $navAccountType = $('#navAccountType '); let token = Cookies.get('token'); let username = Cookies.get('username'); let account_type = Cookies.get('account_type'); if (token != null ) { console.log('User logged in as ' + username); $signupButton.hide(); $loginButton.hide(); $logoutButton.removeClass('d-none'); $navUsername.text(username); $navAccountType.text(account_type); $welcomeUsername.text(username); } else { $profileButton.hide(); url = window.location.href; current_location = url.substring(url.lastIndexOf('/') + 1); console.log(current_location); console.log('User not logged in'); if (current_location === 'profile.html') { console.log('Redirecting'); window.location.href = '/'; } } $(document).ready(function() { var date = function(dateObject) { var d = new Date(dateObject.substring(0, 10)); var day = d.getDate(); var month = d.getMonth() + 1; var year = d.getFullYear(); if (day < 10) { day = "0" + day; } if (month < 10) { month = "0" + month; } var date = year + "-" + month + "-" + day; return date; }; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $(document).on('click', '.kiemkehethong', function() { $.ajax({ type: 'post', url: '/kiemkehethong', data: { 'tungay': $("#TuNgay").val(), 'denngay': $("#DenNgay").val() }, success: function(resp) { var headers = ''; var trHTML = ''; $.each(resp, function (i, userData) { trHTML += ''; }); $('.listkiemke').empty().append(headers + trHTML); $('.dataTables-example').DataTable({ pageLength: 10, responsive: true, dom: '<"html5buttons"B>lTfgitp', buttons: [ { extend: 'copy'}, {extend: 'excel', title: 'FileKiemKe'}, {extend: 'pdf', title: 'ExampleFile'}, {extend: 'print', customize: function (win){ $(win.document.body).addClass('white-bg'); $(win.document.body).css('font-size', '10px'); $(win.document.body).find('table') .addClass('compact') .css('font-size', 'inherit'); } } ] }); } }); }); $(document).on('click', '.kiemkecuahang', function() { $.ajax({ type: 'post', url: '/kiemkecuahang', data: { 'tungay': $("#TuNgay").val(), 'denngay': $("#DenNgay").val(), 'kho': $("#Kho").val() }, success: function(resp) { var headers = '
    STTMã Sản PhẩmTên Sản PhẩmSố Lượng
    ' + userData.hanghoa.MaHH + '' + userData.hanghoa.TenHH + '' + userData.SoLuong + '
    '; var trHTML = ''; total = 0; $.each(resp, function (i, userData) { trHTML += ''; total += userData.SoLuong; }); var footer = ''; $('.listkiemke').empty().append(headers+trHTML+footer); $('.dataTables-example').DataTable({ pageLength: 10, responsive: true, dom: '<"html5buttons"B>lTfgitp', buttons: [ { extend: 'copy'}, {extend: 'excel', title: 'FileKiemKe', exportOptions: { orthogonal: 'sort' }, customizeData: function ( data ) { for (var i=0; i'; }); $('.listkiemke').empty().append(headers+trHTML); $('.dataTables-example').DataTable({ pageLength: 10, responsive: true, dom: '<"html5buttons"B>lTfgitp', buttons: [ { extend: 'copy'}, {extend: 'excel', title: 'FileKiemKe'}, {extend: 'pdf', title: 'ExampleFile'}, {extend: 'print', customize: function (win){ $(win.document.body).addClass('white-bg'); $(win.document.body).css('font-size', '10px'); $(win.document.body).find('table') .addClass('compact') .css('font-size', 'inherit'); } } ] }); } }); }); $(document).on('click', '.kiemkemhkh', function() { if($("#HangHoa").val().length == 0){ hanghoa = 1; }else{ hanghoa = $("#HangHoa").val(); } console.log(hanghoa); $.ajax({ type: 'post', url: '/kiemkemhkh', data: { 'tungay': $("#TuNgay").val(), 'denngay': $("#DenNgay").val(), 'hanghoa': hanghoa, 'kho': $("#Kho").val(), 'nhanvien': $("#NhanVien").val() }, success: function(resp) { var headers = '
    STTMã Hàng HóaMã Nội BộTên Hàng HóaSố Lượng
    ' + userData.hanghoa.MaHH + '' + userData.hanghoa.MaGoiNho + '' + userData.hanghoa.TenHH + '' + userData.SoLuong + '
    Total: '+total+'
    ' + userData.hanghoa.TenHH + '' + userData.SoLuong + '' + userData.NgayKiemKe + '' + userData.kho.TenKho + '' + userData.TenKeHang + '
    '; var trHTML = ''; total = 0; $.each(resp, function (i, userData) { trHTML += ''; total += userData.SoLuong; }); var footer = ''; $('.listkiemke').empty().append(headers+trHTML+footer); $('.dataTables-example').DataTable({ pageLength: 10, responsive: true, dom: '<"html5buttons"B>lTfgitp', buttons: [ { extend: 'copy'}, {extend: 'excel', title: 'FileKiemKe', exportOptions: { orthogonal: 'sort' }, customizeData: function ( data ) { for (var i=0; i (this.dialogRef = el)} title="LayoutExample"> LayoutExample was toggled! ) } toggle = () => { logger.debug('dialog was toggled!') const { dialogRef } = this if (!dialogRef.isShown) { dialogRef.showDialog() } else { dialogRef.dismissDialog() } } } /** * @typedef {import('hast').Element} Element * @typedef {import('hast').Root} Root * @typedef Options options * Configuration. * @property {boolean} [showLineNumbers] * Set `showLineNumbers` to `true` to always display line number * @property {boolean} [ignoreMissing] * Set `ignoreMissing` to `true` to ignore unsupported languages and line highlighting when no language is specified */ import { visit } from 'unist-util-visit' import { toString } from 'hast-util-to-string' import { filter } from 'unist-util-filter' import rangeParser from 'parse-numeric-range' /** * @param {Element} node * @return {string|null} */ const getLanguage = (node) => { const className = node.properties.className //@ts-ignore for (const classListItem of className) { if (classListItem.slice(0, 9) === 'language-') { return classListItem.slice(9).toLowerCase() } } return null } /** * Create a closure that determines if we have to highlight the given index * * @param {string} meta * @return { (index:number) => boolean } */ const calculateLinesToHighlight = (meta) => { const RE = /{([\d,-]+)}/ // Remove space between {} e.g. {1, 3} const parsedMeta = meta .split(',') .map((str) => str.trim()) .join() if (RE.test(parsedMeta)) { const strlineNumbers = RE.exec(parsedMeta)[1] const lineNumbers = rangeParser(strlineNumbers) return (index) => lineNumbers.includes(index + 1) } else { return () => false } } /** * Check if we want to start the line numbering from a given number or 1 * showLineNumbers=5, will start the numbering from 5 * @param {string} meta * @returns {number} */ const calculateStartingLine = (meta) => { const RE = /showLineNumbers=(?\d+)/i // pick the line number after = using a named capturing group if (RE.test(meta)) { const { groups: { lines }, } = RE.exec(meta) return Number(lines) } return 1 } /** * Split line to div node with className `code-line` * * @param {string} text * @return {Element[]} */ const splitLine = (text) => { // Xdm Markdown parses every code line with \n const textArray = text.split(/\n/) // Remove last line \n which results in empty array if (textArray[textArray.length - 1].trim() === '') { textArray.pop() } // Empty array are actually line segments so we convert them back to newlines return textArray.map((line) => { return { type: 'element', tagName: 'span', properties: { className: ['code-line'] }, children: [{ type: 'text', value: line }], } }) } /** * Add a node start and end line position information for each text node * * @return { (ast:Element['children']) => Element['children'] } * */ const addNodePositionClosure = () => { let startLineNum = 1 /** * @param {Element['children']} ast * @return {Element['children']} */ const addNodePosition = (ast) => { // @ts-ignore return ast.reduce((result, node) => { if (node.type === 'text') { const value = /** @type {string} */ (node.value) const numLines = (value.match(/\n/g) || '').length node.position = { // column: 0 is to make the ts compiler happy but we do not use this field start: { line: startLineNum, column: 0 }, end: { line: startLineNum + numLines, column: 0 }, } startLineNum = startLineNum + numLines result.push(node) return result } if (Object.prototype.hasOwnProperty.call(node, 'children')) { const initialLineNum = startLineNum // @ts-ignore node.children = addNodePosition(node.children, startLineNum) result.push(node) node.position = { start: { line: initialLineNum, column: 0 }, end: { line: startLineNum, column: 0 }, } return result } result.push(node) return result }, []) } return addNodePosition } /** * Split multiline text nodes into individual nodes with positioning * * @param {Element['children']} ast * @return {Element['children']} */ const splitTextByLine = (ast) => { //@ts-ignore return ast.reduce((result, node) => { if (node.type === 'text') { if (node.value.indexOf('\n') === -1) { result.push(node) return result } const lines = node.value.split('\n') for (const [i, line] of lines.entries()) { result.push({ type: 'text', value: i === lines.length - 1 ? line : line + '\n', position: { start: { line: node.position.start.line + i }, end: { line: node.position.start.line + i }, }, }) } return result } if (Object.prototype.hasOwnProperty.call(node, 'children')) { // @ts-ignore node.children = splitTextByLine(node.children) result.push(node) return result } result.push(node) return result }, []) } /** * Rehype prism plugin generator that highlights code blocks with refractor (prismjs) * * Pass in your own refractor object with the required languages registered: * https://github.com/wooorm/refractor#refractorregistersyntax * * @param {import('refractor/lib/core').Refractor} refractor * @return {import('unified').Plugin<[Options?], Root>} */ const rehypePrismGenerator = (refractor) => { return (options = {}) => { return (tree) => { visit(tree, 'element', visitor) } /** * @param {Element} node * @param {number} index * @param {Element} parent */ function visitor(node, index, parent) { if (!parent || parent.tagName !== 'pre' || node.tagName !== 'code') { return } let meta = node.data && node.data.meta ? /** @type {string} */ (node.data.meta) : '' // Coerce className to array if (node.properties.className) { if (typeof node.properties.className === 'boolean') { node.properties.className = [] } else if (!Array.isArray(node.properties.className)) { node.properties.className = [node.properties.className] } } else { node.properties.className = [] } node.properties.className.push('code-highlight') const lang = getLanguage(node) /** @type {Element} */ let refractorRoot let langError = false // Syntax highlight if (lang) { try { // @ts-ignore refractorRoot = refractor.highlight(toString(node), lang) // @ts-ignore className is already an array parent.properties.className = (parent.properties.className || []).concat( 'language-' + lang ) } catch (err) { if (options.ignoreMissing && /Unknown language/.test(err.message)) { langError = true refractorRoot = node } else { throw err } } } else { refractorRoot = node } const nodeWithPosition = addNodePositionClosure()(refractorRoot.children) refractorRoot.children = splitTextByLine(nodeWithPosition) if (refractorRoot.children.length > 0) { refractorRoot.position = { start: { line: refractorRoot.children[0].position.start.line, column: 0 }, end: { line: refractorRoot.children[refractorRoot.children.length - 1].position.end.line, column: 0, }, } } const shouldHighlightLine = calculateLinesToHighlight(meta) const startingLineNumber = calculateStartingLine(meta) const codeLineArray = splitLine(toString(node)) for (const [i, line] of codeLineArray.entries()) { // Code lines if ( meta.toLowerCase().includes('showLineNumbers'.toLowerCase()) || options.showLineNumbers ) { line.properties.line = [(i + startingLineNumber).toString()] // @ts-ignore line.properties.className.push('line-number') } // Line highlight if (shouldHighlightLine(i)) { // @ts-ignore line.properties.className.push('highlight-line') } if (lang === 'diff' && toString(line).substring(0, 1) === '-') { // @ts-ignore line.properties.className.push('deleted') } else if (lang === 'diff' && toString(line).substring(0, 1) === '+') { // @ts-ignore line.properties.className.push('inserted') } // Syntax highlight const treeExtract = filter( refractorRoot, (node) => node.position.start.line <= i + 1 && node.position.end.line >= i + 1 ) line.children = treeExtract.children } node.children = codeLineArray } } } export default rehypePrismGenerator watermelon555/vue-ts-admin import fs from 'fs'; import path from 'path'; import Sequelize from 'sequelize'; const db = {}; export function initModel(sequelize) { fs.readdirSync(__dirname) .filter( (file) => file.indexOf('.') !== -1 && file.slice(-3) === '.js' && file !== 'index.js' ) .forEach((file) => { const model = sequelize.import(path.join(__dirname, file)); db[model.name] = model; }); Object.keys(db).forEach((moduleName) => { if (db[moduleName].associate) { db[moduleName].associate(db); } }); db.sequelize = sequelize; db.Sequelize = Sequelize; } export default db; // @flow function foo1(o: { x: number }) { if (o.p1) { // OK, this is an idiomatic way of testing property existence o.x; } } function foo2(o: { x: number }) { if (o.p2) { // OK o.p2.x; // error, since o.p2's type is unknown (e.g., could be `number`) } } function foo3(o: { x: number }) { o.p3.x; // usual error outside conditional } function foo4(o: $Exact<{ x: number }>) { if (o.p4) { // OK o.p4.x; // currently OK, should be unreachable } else { o.p4.x; // error } } function foo5() { const o = { }; _foo5(); if (o.p) { o.p(); } function _foo5() { o.p = function() { } } } function foo6(o: mixed) { if (o.bar) {} // error, any lookup on mixed is unsafe } function foo7(o: mixed) { if (typeof o.bar === 'string') {} // error if (o && typeof o.bar === 'string') {} // ok if (o != null && typeof o.bar === 'string') {} // ok if (o !== null && o !== undefined && typeof o.bar === 'string') {} // ok } function foo8(o: { p: mixed }) { if (o.p && o.p.q) {} // this is ok because o.p is truthy, so o.p.q is safe if (o.p && o.p.q && o.p.q.r) {} } type Foo9Expected = { foo: string, } function foo9() { const actual = {}; if (actual.foo === undefined) { actual.foo = 'foo'; } (actual: Foo9Expected); } src/components/sidenav.js import * as React from 'react'; import { Component } from 'react-simplified'; import { Card, List, Row, Column, NavBar, Button, Form } from '../widgets'; import { history } from '../index.js'; import { loginService } from '../services/LoginService'; import { cartService } from '../services/CartService'; import confirmBox from '../services/confirmBox'; import varsel from '../services/notifications.js'; //activeStyle funk ikkje class Sidenav extends Component { render() { return (
    Ny bestilling Leieperiode Kunde Sykkel Ekstrautstyr Pakketilbud Handlekurv
    ); } bestill() { if (cartService.kunde == null && cartService.startdato == null && cartService.handlekurv.length == 0) { history.push('/leieperiode'); } else { confirmBox('Varsel', 'Ønsker du å starte en ny bestilling?', res => { if (res == 1) { cartService.dropOrder(); varsel('Suksess!', 'Du startet en ny bestilling', 'vrsl-success'); } }); } } } export default Sidenav; Bojne/project-ideasnode_modules/graphql-type-json/lib/index.js1-10 'use strict'; exports.__esModule = true; var _graphql = require('graphql'); var _language = require('graphql/language'); function identity(value) { return value; } function parseLiteral(ast, variables) { switch (ast.kind) { case _language.Kind.STRING: case _language.Kind.BOOLEAN: return ast.value; case _language.Kind.INT: case _language.Kind.FLOAT: return parseFloat(ast.value); case _language.Kind.OBJECT: { var value = Object.create(null); ast.fields.forEach(function (field) { value[field.name.value] = parseLiteral(field.value, variables); }); return value; } case _language.Kind.LIST: return ast.values.map(function (n) { return parseLiteral(n, variables); }); case _language.Kind.NULL: return null; case _language.Kind.VARIABLE: { var name = ast.name.value; return variables ? variables[name] : undefined; } default: return undefined; } } exports.default = new _graphql.GraphQLScalarType({ name: 'JSON', description: 'The `JSON` scalar type represents JSON values as specified by ' + '[ECMA-404](http://www.ecma-international.org/' + 'publications/files/ECMA-ST/ECMA-404.pdf).', serialize: identity, parseValue: identity, parseLiteral: parseLiteral }); module.exports = exports['default'];import { expect } from '../test_helper'; import MockStore from '../mock_store'; import responseTypesFromQuestions from '../../../webpack/middleware/response_types_from_questions'; import { FETCH_QUESTIONS_FULFILLED, FETCH_RESPONSE_TYPE_FULFILLED } from '../../../webpack/actions/types'; describe('responseTypesFromQuestions middleware', () => { let store; let action; const next = () => { 1 + 1; //do nothing }; beforeEach(() => { store = new MockStore(); action = { type: FETCH_QUESTIONS_FULFILLED, payload: {data: [ {"id":1,"content":"Test question","responseType":{"id":1,"name":"Response Type 1"}}, {"id":2,"content":"Test question","responseType":{"id":2,"name":"Response Type 2"}} ]} }; }); it('will dispatch action for response type in question', () => { responseTypesFromQuestions(store)(next)(action); let dispatchedAction = store.dispatchedActions.find((a) => a.type === FETCH_RESPONSE_TYPE_FULFILLED); expect(dispatchedAction).to.exist; expect(dispatchedAction.payload.data.name).to.equal('Response Type 1'); }); it('will transform the question payload', () => { responseTypesFromQuestions(store)(next)(action); const qs = action.payload.data; expect(qs[0].responseTypeId).to.equal(1); expect(qs[1].responseTypeId).to.equal(2); }); }); $(document).ready(function() { var oldestClients = clientRetriever.getOldestClients(5); var bestClients = clientRetriever.getBestClients(5); var clients = clientRetriever.getClients(); var onSelectHome = function() { $(".panel-heading").html("Welcome"); $(".panel-body").html("

    There are " + clients.length + " clients.

    "); }; $("#home-btn").click(onSelectHome); $("#oldest-clients-btn").click(function() { $(".panel-heading").html("Top 5 oldest clients with name, id and type"); var displayContent = "
    • " + _.map(oldestClients, function(client) { return transformations.getContactNameIdAndType(client); }).join('
    • ') + "
    "; $(".panel-body").html(displayContent); }); $("#best-clients-btn").click(function() { $(".panel-heading").html("Top 5 best clients with name, id and type"); var displayContent = "
    • " + _.map(bestClients, function(client) { return transformations.getContactNameIdAndType(client); }).join('
    • ') + "
    "; $(".panel-body").html(displayContent); }); onSelectHome(); });module.exports = 'angular.module(\'angular-jsvat\', [\'angular-jsvat-input\'])' + '\n\r .factory(\'JsVatFactory\', function () {' + '\n\r<%= contents %>' + '\n\r return jsvat;' + '});';0 const mongoose = require("mongoose"); const userProfileSchema = mongoose.Schema({ userId : {type: mongoose.Schema.Types.ObjectId , ref:"user", required: true}, firstName: { type: String, trim: true, }, middleName: { type: String, trim: true, }, lastName: { type: String, trim: true, }, gender: { type: String, trim: true, }, category: { type: String, trim: true, }, currentAddress: { type: String, trim: true, }, permanentAddress: { type: String, trim: true, }, isAddressSame : { type: Boolean, }, phoneNumber: { type: String, trim: true, }, emailId: { type: String, trim: true, }, dateOfBirth : { type: Date, }, dateOfJoining : { type: Date, }, idProofNumber : { type: String, }, idProofType: { type: String, }, userType: { type: String, } },{timestamps : true}); const UserProfile = mongoose.model("UserProfile", userProfileSchema); (async () => { await UserProfile.createCollection(); }) module.exports = UserProfile; define(['react'], function(React) { var OverlayModule=React.createClass({ componentDidMount: function () { $(this.refs.modal.getDOMNode()).modal({ backdrop: "static", show: true, keyboard:true, background:true }); }, // componentDidUnmount: function () { // $(this.refs.modal.getDOMNode()).off(); // }, render:function(){ return( ); }, show: function () { $(this.refs.modal.getDOMNode()).modal("show"); }, hide: function () { $(this.refs.modal.getDOMNode()).modal("hide"); } }); return OverlayModule; }); component/import/TimestampParamBehavior.js /** * @copyright Copyright (c) 2020 <> */ 'use strict'; const Base = require('./BaseParam'); module.exports = class TimestampParamBehavior extends Base { async execute () { await super.execute(); await this.resolveClassAttrByName('createdAttr'); await this.resolveClassAttrByName('updatedAttr'); } };angular.module('mol.indicators') .filter('trustUrl', function($sce) { return function(url) { return $sce.trustAsResourceUrl(url); }; }) .filter('unsafe', function($sce) { return function(str) { return $sce.trustAsHtml(str); }; }) .filter('numberEx', ['numberFilter', '$locale', function(number, $locale) { var formats = $locale.NUMBER_FORMATS; return function(input, fractionSize) { //Get formatted value var formattedValue = number(input, fractionSize); //get the decimalSepPosition var decimalIdx = formattedValue.indexOf(formats.DECIMAL_SEP); //If no decimal just return if (decimalIdx == -1) return formattedValue; var whole = formattedValue.substring(0, decimalIdx); var decimal = (Number(formattedValue.substring(decimalIdx)) || "").toString(); return whole + decimal.substring(1); }; } ]); src/App.js0 // eslint-disable-next-line import React, { useState } from "react"; // CSS Component Imports import "./App.css"; // Component Imports import Sidebar from "./Components/Sidebar/Sidebar"; import Chat from "./Components/Chat/Chat"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import Login from "./Components/Login/Login"; import { useStateValue } from "./StateProvider"; function App() { // eslint-disable-next-line const [{ user }, dispatch] = useStateValue(); return ( // BEM naming convention
    {!user ? ( ) : (
    {/* */} {/* */}
    )}
    ); } export default App; import 'aws-sdk/dist/aws-sdk'; const AWS = window.AWS; const Cookies = require('js-cookie'); class TomboFSAWSClient { constructor (userId, appId, apiURI) { let guid_regex = /^[a-z0-9\-]+$/; if (guid_regex.test(userId)) { this.userId = userId; } if (guid_regex.test(appId)) { this.appId = appId; } this.apiURI = apiURI; this.expiration = 0; this.fetchingCredentials = false; } setCredentials ( bucket, region, endpoint, accessKeyId, secretAccessKey, sessionToken, expiration ) { // expiration should be ISO-8601 format string. // ex.) 2011-07-15T23:28:33.359Z console.log(`setCredentials(${bucket}, ${region}, ${endpoint}, ${accessKeyId}, ${secretAccessKey}, ${sessionToken}, ${expiration})`); this.bucket = bucket; this.region = region; this.endpoint = endpoint; this.accessKeyId = accessKeyId; this.secretAccessKey = secretAccessKey; this.sessionToken = sessionToken; this.expiration = Date.parse(expiration); } haveValidCredentials () { const now = Date.now(); // 60 secs is the margin to avoid errors. const result = !!(now < (this.expiration - 60) && this.accessKeyId && this.secretAccessKey && this.sessionToken); console.log(`haveValidCredentials() -> ${result}`); return result; } validS3Client () { if (this.haveValidCredentials() && this.s3) { // if credential is valid and there is an old S3 client instance, // we can reuse it. return this.s3; } this.invalidateS3Client(); return null; } invalidateS3Client () { this.s3 = null; // NOTE: Do not initialize accessKeyId for sending it on fetchCredentials() // this.accessKeyId = null; this.secretAccessKey = null; this.sessionToken = null; this.expiration = 0; } createS3Client () { if (!this.accessKeyId || !this.secretAccessKey || !this.sessionToken) { console.log('ERROR: invalid credentials'); return null; } const credentials = new AWS.Credentials( this.accessKeyId, this.secretAccessKey, this.sessionToken ); this.s3 = new AWS.S3({ credentials: credentials, endpoint: this.endpoint, region: this.region }); return this.s3; } fetchCredentials () { console.log('AWS fetchCredentials()') const lockedFetchCredentials = (resolve, reject) => { if (!this.apiURI) { return reject(new Error('Empty apiURI to fetch credentials for the remote file system.')); } // mutex if (this.fetchingCredentials) { setTimeout(() => { lockedFetchCredentials(resolve, reject); }, 0); return; } if (this.haveValidCredentials()) { console.log('already fetched credentials'); return resolve(); } const user_jwt = Cookies.get('user_jwt'); if (!user_jwt || /^[A-Za-z0-9_\-]+$/.test(user_jwt)) { return reject(new Error('Cannot get user_jwt cookie.')); } this.fetchingCredentials = true; let params = ''; if (this.accessKeyId) { params = '&access_key_id=${this.accessKeyId}'; } const url = this.apiURI + `file_systems/credential?user_jwt=${user_jwt}&application_id=${this.appId}${params}`; return fetch(url).then((response) => { if (response.ok) { return response.json(); } this.fetchingCredentials = false; return Promise.reject(new Error('API response is not ok')); }).then((body) => { if ( body['data']['type'] != 'credential' || !body['data']['attributes']['bucket'] || !body['data']['attributes']['region'] || !body['data']['attributes']['endpoint'] || !body['data']['attributes']['access_key_id'] || !body['data']['attributes']['secret_access_key'] || !body['data']['attributes']['session_token'] || !body['data']['attributes']['expiration'] ) { this.fetchingCredentials = false; return Promise.reject(new Error('Failed to parse the response from remote filesystem credential API.')); } this.setCredentials( body['data']['attributes']['bucket'], body['data']['attributes']['region'], body['data']['attributes']['endpoint'], body['data']['attributes']['access_key_id'], body['data']['attributes']['secret_access_key'], body['data']['attributes']['session_token'], body['data']['attributes']['expiration'] ); this.fetchingCredentials = false; resolve(); }); }; return new Promise(lockedFetchCredentials); } getClient () { return new Promise((resolve, reject) => { let s3client = this.validS3Client(); if (s3client) { return resolve(s3client); } this.fetchCredentials().then(() => { resolve(this.createS3Client()); }).catch((e) => { console.log('getClient() failed'); reject(e); }); }); } userPathPrefix () { if (!this.userId) { throw new Error('AWS userPathPrefix(): empty userId'); } return `${this.userId}/`; } appPathPrefix () { if (!this.appId) { throw new Error('AWS appPathPrefix(): empty appId'); } return `${this.userPathPrefix()}${this.appId}/`; } getObject (key) { return this.getClient().then((client) => { const actualKey = this.appPathPrefix() + key; console.log(`AWS getObject(${key}): ${actualKey}`); return new Promise((resolve, reject) => { client.getObject({ Bucket: this.bucket, Key: actualKey, // NOTE: do not cache ResponseCacheControl: 'No-cache', ResponseExpires: 0, }, (err, data) => { if (err) { return reject(err); } resolve(data); }); }); }); } putObject (key, body) { return this.getClient().then((client) => { const actualKey = this.appPathPrefix() + key; console.groupCollapsed(`AWS putObject(${key}, body): ${actualKey}`); console.log(body); console.groupEnd(); return new Promise((resolve, reject) => { client.putObject({ Bucket: this.bucket, Key: actualKey, Body: body }, (err, data) => { if (err) { return reject(err); } resolve(data); }); }); }); } deleteObject (key) { return this.getClient().then((client) => { const actualKey = this.appPathPrefix() + key; console.log(`AWS deleteObject(${key}): ${actualKey}`); return new Promise((resolve, reject) => { client.deleteObject({ Bucket: this.bucket, Key: actualKey // TODO: Support VersionId }, (err, data) => { if (err) { return reject(err); } resolve(data); }); }); }); } deleteObjects (keys) { return this.getClient().then((client) => { const objects = keys.map((key) => { const actualKey = this.appPathPrefix() + key; return { Key: actualKey // TODO: Support VersionId }; }); console.groupCollapsed('AWS deleteObjects(keys)'); console.log({ keys: keys, objects: objects }); console.groupEnd(); return new Promise((resolve, reject) => { client.deleteObjects({ Bucket: this.bucket, Delete: { Objects: objects } }, (err, data) => { if (err) { return reject(err); } resolve(data); }); }); }); } listObjects (prefix) { return this.getClient().then((client) => { let params = { Bucket: this.bucket, Delimiter: '/', Prefix: this.appPathPrefix() + prefix }; let contents = []; return new Promise((resolve, reject) => { client.listObjects(params).eachPage((err, data) => { if (err) { return reject(err); } if (data === null) { return resolve(contents); } contents = contents.concat(data.Contents); }); }); }); } pathToKeyPrefix (path) { // NOTE: for deletion // TODO: Handle directory correctly return `entries${path}/`; } pathAndEntryToKey (path, entry) { // NOTE: Is the timestamp on a millisecond basis is enough? if (!entry.timestamp || typeof entry.timestamp.getTime !== 'function') { throw new Error('AWS pathAndEntryToKey: entry must have `timestamp` of Date object.'); } return `entries${path}/${entry.timestamp.getTime()}`; } getFile (path, entry) { return this.getObject(this.pathAndEntryToKey(path, entry)); } putFile (path, entry) { if (!entry.contents) { return Promise.reject(new Error('AWS putFile(): entry must have `contents`')); } return this.putObject(this.pathAndEntryToKey(path, entry), entry.contents); } deleteFiles (paths) { // NOTE: paths is enough for deletion because all the file versions // under the path will be deleted. return this.deleteObjects(paths.map(this.pathToKeyPrefix)); } getManifest () { console.log('AWS getManifest()'); // This manifest file contains entries per mountpoint return this.getObject('tombofs.manifest').then((data) => { if (data.Body) { return JSON.parse(data.Body); } else { return Promise.reject(new Error('Invalid manifest file')); } }).catch((err) => { // If manifest file doesn't exist, initialize if (err.code === 'NoSuchKey') { console.log('AWS getManifest(): Initialize manifest'); return { mountpoints: {} }; } // rethrow return Promise.reject(err); }); } putManifest (content) { console.groupCollapsed('AWS putManifest()'); console.log(content); console.groupEnd(); return this.putObject('tombofs.manifest', JSON.stringify(content)).then((data) => { return data; }); } heartbeat () { console.log('AWS heartbeat()'); return this.getClient().then(() => { const user_jwt = Cookies.get('user_jwt'); return fetch(this.apiURI + `heartbeat?user_jwt=${user_jwt}&application_id=${this.appId}&aws_access_key_id=${this.accessKeyId}`).then((response) => { if (response.ok) { return response.json().then((json) => { if (json.errors && json.errors[0]) { console.log('AWS heartbeat() error'); return Promise.reject(new Error(json.errors[0])); } else { console.log('AWS heartbeat() OK'); return json; } }); } this.invalidateS3Client(); console.log('AWS heartbeat() NG'); return Promise.reject(new Error('heartbeat response is not ok')); }); }); } } module.exports = TomboFSAWSClient; 1-10 var searchData= [ ['detail_1484',['detail',['../dd/d39/namespacedetail.html',1,'']]], ['details_1485',['details',['../db/d1b/namespacedetails.html',1,'']]] ]; import { RleParser } from "./rle-parser.js"; export class PatternLoader { constructor(collectionsUrl) { this.parser = new RleParser(); this.collectionsUrl = collectionsUrl; } async getRleData(collectionName, patternName) { const parser = this.parser; const url = `${this.collectionsUrl}/patterns/${collectionName}/${patternName}.rle`; return fetch(url) .then(response => { return response.text(); }) .then(function(rleData) { const {pattern, width, height} = parser.parse(rleData); return { pattern: parser.toOnCells(pattern), width, height }; }); } async getPatternIndex() { return fetch(`${this.collectionsUrl}/index.json`) .then(response => response.json()); } }/* * Copyright (c) 2008-2016, Massachusetts Institute of Technology (MIT) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the copyright holder 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ define(['ext', 'ol', "iweb/CoreModule", "nics/modules/UserProfileModule", "./TokenManager"], function(Ext, ol, Core, UserProfile, TokenManager){ return Ext.define('modules.datalayer.DatasourceImportController', { extend : 'Ext.app.ViewController', alias: 'controller.datalayer.datasourceimportcontroller', init: function() { this.dataSourceType = this.getView().dataSourceType; this.capabilitiesFormat = this.getView().capabilitiesFormat; this.workspaceId = this.getView().workspaceId; this.tokenHandlerTopic = "nics.datasource.token." + this.dataSourceType; this.mediator = Core.Mediator.getInstance(); this.updateGridTitle(); this.bindEvents(); this.loadDataSources(); }, bindEvents: function(){ //Bind UI Elements Core.EventManager.addListener("nics.data.loaddatasources." + this.dataSourceType, this.onLoadDataSources.bind(this)); Core.EventManager.addListener("nics.data.adddatasource." + this.dataSourceType, this.onAddDatasource.bind(this)); Core.EventManager.addListener("nics.data.adddatalayer." + this.dataSourceType, this.onAddDatalayer.bind(this)); Core.EventManager.addListener(this.tokenHandlerTopic, this.tokenHandler.bind(this)); }, updateGridTitle: function() { var panelTitle = this.getView().getTitle(); var grid = this.getView().getGrid(); var gridTitle = grid.getTitle(); grid.setTitle(panelTitle + ' ' + gridTitle); }, loadDataSources: function() { var url = Ext.String.format('{0}/datalayer/{1}/sources/{2}', Core.Config.getProperty(UserProfile.REST_ENDPOINT), UserProfile.getWorkspaceId(), this.dataSourceType); this.mediator.sendRequestMessage(url , 'nics.data.loaddatasources.' + this.dataSourceType); }, onLoadDataSources: function(evt, data) { this.getView().getGrid().getStore().loadRawData(data.datasources); }, onAddDataSourceClick: function() { var grid = this.getView().getGrid(), store = grid.getStore(), rowEditPlugin = grid.getPlugin('rowediting'); var newRecords = store.getNewRecords(); if (newRecords && newRecords.length) { rowEditPlugin.startEdit(newRecords[0], 0); } else { var records = store.insert(0, {}); rowEditPlugin.startEdit(records[0], 0); } }, onGridBeforeEdit: function(editor, context, eOpts) { var record = context.record; //only allow editing phantom records return record.phantom; }, onGridCancelEdit: function(editor, context, eOpts) { var record = context.record; //remove phantom on cancel edit record.store.remove(record); }, onGridEdit: function(editor, context, eOpts) { var record = context.record; Ext.Msg.show({ title:'Secure', message: 'Would you like to secure the datasource?', buttons: Ext.Msg.YESNO, icon: Ext.Msg.QUESTION, fn: function(btn) { if (btn === 'yes') { this.requestAuthentication(record); } else if (btn === 'no') { this.getCapabilities(record, function(){ this.storeDatasource(record); }, function(){ var rowEditPlugin = this.getView().getGrid().getPlugin('rowediting'); rowEditPlugin.startEdit(record, 0); }); } }, scope: this }); }, requestAuthentication: function(record){ var _this = this; Ext.create('Ext.window.Window', { height: 200, width: 300, layout: 'fit', modal: true, buttonAlign: 'center', referenceHolder: true, items: [ { xtype: 'form', frame: false, reference: 'authForm', record: record, border: 0, layout: { type: 'hbox', align: 'middle' }, fieldDefaults: { msgTarget: 'side', labelWidth: 55 }, items: [ { xtype: 'container', flex: 1, padding: 10, layout: { type: 'vbox' }, items: [ { xtype: 'textfield', name: 'username', fieldLabel: 'Username', allowBlank: false },{ xtype: 'textfield', name: 'password', fieldLabel: 'Password', inputType: 'password', allowBlank: false } ] } ] } ], buttons: [{ text: 'Save', handler: function () { var component = this.up('window').items.get(0); var internalurl = component.record.data.internalurl; var username = component.getForm().findField("username").getValue(); var password = component.getForm().findField("password").getValue(); var endpoint = Core.Config.getProperty(UserProfile.REST_ENDPOINT); var url = Ext.String.format("{0}/datalayer/{1}/token?internalurl={2}&" + "username={3}&password={4}", endpoint, UserProfile.getWorkspaceId(), internalurl, username, encodeURIComponent(password)); var topic = Core.Util.generateUUID(); Core.EventManager.createCallbackHandler(topic, _this, _this.handleTokenResponse, [component.record, username, password]); Core.Mediator.getInstance().sendRequestMessage(url, topic); //Close the window this.up('window').close(); } } ] }).show(); }, handleTokenResponse: function(record, username, password, evt, response){ if(response.token){ record.set("secure", true); TokenManager.addToken(record.get("datasourceid"), response); this.getCapabilities(record, function(){ this.storeDatasource(record, username, password); }, function(){ var rowEditPlugin = this.getView().getGrid().getPlugin('rowediting'); rowEditPlugin.startEdit(record, 0); }); }else{ Ext.MessageBox.alert("Authentication Error", "The username and password were not valid."); var rowEditPlugin = this.getView().getGrid().getPlugin('rowediting'); rowEditPlugin.startEdit(record, 0); } }, storeDatasource: function(record, username, password) { var values = { displayname: record.get('displayname'), internalurl: record.get('internalurl'), legend: record.get('legend') }; if(username && password){ values.username = username; values.password = password; } var url = Ext.String.format('{0}/datalayer/{1}/sources/{2}', Core.Config.getProperty(UserProfile.REST_ENDPOINT), UserProfile.getWorkspaceId(), this.dataSourceType); this.mediator.sendPostMessage(url, 'nics.data.adddatasource.' + this.dataSourceType, values); }, onAddDatasource: function(evt, response) { var newSources = response.datasources; if (newSources.length) { var grid = this.getView().getGrid(); var newRecord = grid.getStore().getNewRecords()[0]; newRecord.set(newSources[0]); newRecord.commit(); this.getView().getGrid().getSelectionModel().deselect(newRecord); } else { Ext.Msg.show({ title: 'Data Source', message: 'There was a problem saving the datasource', buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR }); } }, tokenHandler: function(evt, params){ this.getCapabilities(params[0], params[1], params[2]); }, getCapabilities: function(record, success, failure) { var url = ""; if(this.dataSourceType == 'arcgisrest'){ url = Ext.String.format('{0}?f=json', record.get('internalurl')); } else{ url = Ext.String.format('{0}?service={1}&request=GetCapabilities', record.get('internalurl'), this.dataSourceType); } if(record.get('secure')){ var token = TokenManager.getToken(record.get('datasourceid'),{ topic: this.tokenHandlerTopic, params: [record, success, failure] }); //The function will be called again if //a token is successfully retrieved if(token == null){ return; }else{ url = url + "&token=" + token; } } var dataSourceType = this.dataSourceType; Ext.Ajax.request({ url: window.location.protocol + '//' + window.location.host + '/nics/proxy' , method: 'GET', dataSourceType: dataSourceType, params : { url: url }, success: function(response) { //can't use responseXML becaue the proxy doesn't return the correct content type var caps; if(dataSourceType != 'arcgisrest') { var xmlDoc = new DOMParser().parseFromString(response.responseText, 'application/xml'); caps = this.capabilitiesFormat.read(xmlDoc); } else { caps = this.capabilitiesFormat.read(response.responseText); } if (!caps || !caps.layers) { throw new Error("Failed to parse capabilities"); } var layers = caps.layers, version = caps.version; //ensure every layer has a title to display layers.forEach(function(layer){ if (!layer.Title && layer.Name) { layer.Title = layer.Name; } if(dataSourceType == 'arcgisrest') { layer.Title = layer.name; layer.Name = layer.id; } }); record.set('layers', layers, {silent:true}); record.set('version', version, {silent:true}); success && success.call(this); }, failure: function(fp, o) { record.set('layers', [], {silent:true}); Ext.Msg.show({ title: 'Data Source', message: 'Failed to retrieve service capabilities', buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR }); failure && failure.call(this); }, scope: this }); }, onGridSelectionChange: function(store, selected, eOpts) { var record = selected.length && selected[0]; if (record && !record.phantom) { this.focusOnRecord(record); } else { this.setFormDisabled(true); } }, focusOnRecord: function(record) { var layers = record.get('layers'); if (layers != null) { this.getView().getLayerCombo().getStore().loadData(layers); this.setFormDisabled(false); this.resetDatalayerForm(); } else { this.getCapabilities(record, function(){ if (!record.phantom) { this.focusOnRecord(record); } }); } }, onComboChange: function (combo, newValue, oldValue, eOpts) { //default the display name to the combo display value var input = this.getView().getLabelInput(); input.setValue(combo.getRawValue()); }, onFormValidityChange: function(field, valid, eOpts) { var combo = this.getView().getLayerCombo(), input = this.getView().getLabelInput(); var bothValid = combo.isValid() && input.isValid(); this.getView().getImportButton().setDisabled(!bothValid); }, onImportClick: function(){ var grid = this.getView().getGrid(), combo = this.getView().getLayerCombo(), input = this.getView().getLabelInput(), legend = this.getView().getLegendInput(), refreshRate = this.getView().getRefreshRateCombo(); var record = grid.getSelectionModel().getSelection()[0]; var datasourceid = record.getId(); var userSessionId = UserProfile.getUserSessionId(); var values = { displayname: input.getValue(), baselayer: false, usersessionid: userSessionId, datalayersource: { layername: combo.getValue(), usersessionid: userSessionId, refreshrate: refreshRate.getValue() }, legend: legend.getValue() }; var version = record.get('version'); if (version) { values.datalayersource.attributes = JSON.stringify({ 'version': version }); } var url = Ext.String.format('{0}/datalayer/{1}/sources/{2}/layer', Core.Config.getProperty(UserProfile.REST_ENDPOINT), UserProfile.getWorkspaceId(), datasourceid); this.mediator.sendPostMessage(url, 'nics.data.adddatalayer.' + this.dataSourceType, values); }, onAddDatalayer: function(evt, response) { var newLayers = response.datalayers; if (newLayers.length) { Ext.Msg.show({ title: 'Data Layer', message: 'Your new data layer has been created', buttons: Ext.Msg.OK, icon: Ext.Msg.INFO }); this.resetDatalayerForm(); } else { Ext.Msg.show({ title: 'Data Layer', message: 'There was a problem saving the datasource', buttons: Ext.Msg.OK, icon: Ext.Msg.ERROR }); } }, resetDatalayerForm: function() { this.getView().getLabelInput().setValue(''); this.getView().getLayerCombo().reset(); this.getView().getImportButton().disable(); this.getView().getLegendInput().reset(); this.getView().getRefreshRateCombo().reset(); }, /** * Sets whether all out form elements should be disabled or not * * Necessary because fieldset.disable also mask all our inputs */ setFormDisabled: function(disabled) { this.getView().getLabelInput().setDisabled(disabled); this.getView().getLayerCombo().setDisabled(disabled); this.getView().getImportButton().setDisabled(disabled); this.getView().getLegendInput().setDisabled(disabled); this.getView().getRefreshRateCombo().setDisabled(disabled); } }); }); Roxyhuang/AntdDeomopages/about/index.js import React, { PropTypes } from 'react'; import Layout from '../../components/Layout'; import {Row, Col, Form, Icon, Input, Button } from 'antd'; const FormItem = Form.Item; import s from './styles.css'; // import cx from 'classnames'; class AboutPage extends React.Component { static propTypes = { }; componentDidMount() { } render() { return ( {/**/} {/**/} {/*

    */} {/*

    */} {/*简单表单*/} {/**/} {/**/} {/**/} {/**/} {/**/} {/*/!**!/*/} {/**/} {/**/} {/*} placeholder="Username" />*/} {/**/} {/**/} {/**/} {/**/} {/*} type="password" placeholder="Password" />*/} {/**/} {/**/} {/**/} {/**/} {/*} type="password" placeholder="Password" />*/} {/**/} {/**/} {/**/} {/**/} {/*} type="password" placeholder="Password" />*/} {/**/} {/**/} {/*/!**!/*/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/} {/**/}

    简单响应式 ColColColCol ); } } export default AboutPage; YouYiLucifer/react-todolist import React from 'react' import { Icon, Popconfirm, Tag, message } from 'antd'; import './todo-list.less' import tags from './todo-tags' export default class TodoList extends React.Component { handleCheckedChange = id => { this.props.onCheckedChange(id) } handleTodoDelete = todo => { this.props.onTodoDelete(todo.id) } handleTodoRemove = todo => { message.success('已删除') this.props.onTodoRemove(todo.id) } render () { const todo = this.props.todo const isChecked = todo.status === '已完成' ? 'isChecked' : '' return (
    {todo.status !== '已删除' ? this.handleCheckedChange(todo.id)} type={todo.status === '未完成' ? 'border' : 'check-square'} /> : '' }
    {todo.title} {todo.tag ? {todo.tag} : '' }
    {todo.createTime}
    {todo.status !== "已删除" ? this.handleTodoDelete(todo)} /> : this.handleTodoRemove(todo)} okText="确定" cancelText="取消" icon={} > }
    ) } }/* * * ReferPage reducer * */ import { map } from 'lodash'; import { DEFAULT_COMPANY_TYPES, FETCH_COMPANY_TYPES_SUCCESS, } from '../../containers/ReferPage/constants'; const initialState = { companyTypes: DEFAULT_COMPANY_TYPES, }; function referPageReducer(state = initialState, action) { switch (action.type) { case FETCH_COMPANY_TYPES_SUCCESS: return { ...state, companyTypes: map(action.payload, 'type'), }; default: return state; } } export default referPageReducer; import React from "react"; import { Edit, SimpleForm, TextInput } from "react-admin"; const AccidentEdit = (props) => { return ( ); }; export default AccidentEdit; lib/TwoToneAvTimer.js "use strict"; var _babelHelpers = require("./utils/babelHelpers.js"); exports.__esModule = true; var _react = _babelHelpers.interopRequireDefault(require("react")); var _Icon = require("./Icon"); var _fragments = require("./fragments"); var TwoToneAvTimer = /*#__PURE__*/ function TwoToneAvTimer(props) { return _react.default.createElement(_Icon.Icon, props, _react.default.createElement("path", { d: "M12 21" + _fragments.bkf + "h-1v4h2V5.08c3.39.49 6 3.39 6 6.92 0 3.87-3.13 7-7 7s-7-3.13-7-7c0-1.68.59-3.22 1.58-4.42L12 13l1.41-1.41-6.8-6.8v.02C4.42 6.45 3 9.05 3 12c0 4.97 4.02 9 9 9z" }), _react.default.createElement("circle", { cx: "12", cy: "17", r: "1" }), _react.default.createElement("circle", { cx: "17", cy: "12", r: "1" }), _react.default.createElement("circle", { cx: "7", cy: "12", r: "1" })); }; exports.TwoToneAvTimer = TwoToneAvTimer;0 import express from 'express'; import { addPlayer, getAll } from '../controllers/userController'; let userRouter = express.Router(); //userRouter.post('/', addPlayer); userRouter.get('/', getAll); export default userRouter;index.js var fetch = require('node-fetch'); var nodemailer = require('nodemailer'); var transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: ', pass: ]' } }); var mailOptions = { from: '[your mail]', to: 'email1, email2, email3', subject: 'Binance NEW VOTE', text: 'Link to the vote https://binance.com/vote.html' }; let coins = ["RaiBlocks (XRB)", "Experience Points (XP)", "DragonChain (DRGN)", "DeepBrain Chain (DBC)", "ReddCoin (RDD)", "Storm (STORM)", "Civic (CVC)", "ZenCash (ZEN)", "BLOCKv (VEE)", "Rise (RISE)", "Ubiq (UBQ)", "CloakCoin (CLOAK)", "WeTrust (TRST)", "Augur (REP)", "Aventus (AVT)", "SIBCoin (SIB)", "Blocknet (BLOCK)"]; //coins = ["1", "2", "3"]; function sendEmail() { transporter.sendMail(mailOptions, function(error, info){ if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); } function getVote() { fetch('https://www.binance.com/vote/getVote.html', {method: 'GET'}) .then(result => { if (result.status != 200) return; return result.json(); }) .then(function(json) { const optionList = json.voteList[0].optionList; let array = []; for (var i = 0; i < optionList.length; i++) { array.push(optionList[i].optionName); } if (array.length != coins.length) { console.log("VOTE changed 1"); coins = array; sendEmail(); return; } for (var k = 0; k < array.length; k++) { if (coins.indexOf(array[k]) < 0) { console.log("VOTE changed 2"); coins = array; sendEmail(); return; } } console.log("VOTE the same") }) .catch(error => { console.log('error:'); console.log(error); }); } var timerId = setInterval(getVote, 60 * 1000); getVote(); console.log("START getVote...") var rectColor = '#80FF00'; var draw = SVG().addTo('#svgPane').size(600, 300); var rectObjs = []; UIkit.util.on('#refreshbtn', 'click', function () { refreshValues(); }); UIkit.util.on('#playbtn', 'click', function () { console.log('Play'); bubbleSort(); }); UIkit.util.on('#deletebtn', 'click', function () { console.log('clear'); $("#svgPane").empty(); }); document.onkeyup = function(e) { if (e.key == 'r') { refreshValues(); } else if (e.key == 'p') { bubbleSort(); } }; function refreshValues() { const num = Math.floor(Math.random() * 10) + 10; draw.clear(); rectObjs = []; for (var i=0; i!=num; i++){ const h = Math.floor(Math.random() * 300) + 1; var rect = draw.rect(10, h).fill(rectColor).move(20 + i*20, 300-h); var rectObj = {value: h, rect: rect}; rectObjs.push(rectObj); } } function bubbleSort() { var color1 = '#81F7F3'; var color2 = '#FA58F4'; var timeline = new SVG.Timeline(); var swapCount = 0; for(var i=0; i!=rectObjs.length; ++i) { for(var j=i+1; j!=rectObjs.length; ++j) { var value1 = rectObjs[i].value; var value2 = rectObjs[j].value; if (value1 > value2) { rectObjs[i].value = value2; rectObjs[j].value = value1; const rect1 = rectObjs[i].rect; const rect2 = rectObjs[j].rect; rect1.timeline(timeline) rect2.timeline(timeline) rect1.animate(500, swapCount*3000, 'absolute').attr({ fill: color1 }) .animate(2000, swapCount*3000, 'absolute') .attr({ height: value2, fill: color2, y: 300 - value2 }) .animate(0, swapCount*3000 + 2500, 'absolute').attr({ fill: rectColor }); rect2.animate(500, swapCount*3000, 'absolute').attr({ fill: color2 }) .animate(2000, swapCount*3000, 'absolute') .attr({ height: value1, fill: color1, y: 300 - value1 }) .animate(0, swapCount*3000 + 2000, 'absolute').attr({ fill: rectColor }); ++swapCount; } } } } define({ "taskUrl": "Viewshed Service URL", "portalURL": "Specificare l'URL dell'organizzazione ArcGIS Online o Portal for ArcGIS", "portalURLError": "L'URL dell'organizzazione ArcGIS Online o di Portal for ArcGIS configurato non è valido.", "privilegeError": "Il ruolo utente assegnato non consente di eseguire analisi. Per poter eseguire l'analisi, l'amministratore dell'organizzazione deve concedere all’utente determinati privilegi.", "noServiceError": "Servizio di analisi elevazione non disponibile. Verificare le configurazioni dell’organizzazione ArcGIS Online o di Portal for ArcGIS.", "serviceURLPlaceholder": "Inserire l’URL dell’attività del campo di visibilità", "setTask": "Imposta", "setTaskTitle": "Inserire l’attività del campo di visibilità", "serviceURLError": "L’attività di geoprocessing che si sta tentando di configurare con questo widget non è valida. Selezionare un URL valido per l’attività di geoprocessing del campo di visibilità.", "defaultMilsForAnglesLabel": "Imposta miglia per angoli come impostazione predefinita", "defaultObserverHeightLabel": "Unità altezza dell’osservatore predefinita", "defaultObservableDistanceLabel": "Unità distanza dell’osservatore predefinita", "units": { "miles": "Miglia", "kilometers": "Chilometri", "feet": "Piedi", "meters": "Metri", "yards": "Iarde", "nauticalMiles": "Miglia nautiche" }, "helpIconTooltip": "L'elenco dei layer operativi è popolato con i layer della mappa Web corrente che sono di tipo a geometria poligonale.", "selectOperationalLayerLabel": "Selezionare un layer operativo per i risultati" });import {createContext, useReducer} from "react"; import { resultsReducer } from "../reducers/ResultsReducer"; export const ResultsContext = createContext(null) const initialState = [] const ResultsContextProvider = (props) => { const [resultsList, dispatch] = useReducer(resultsReducer, initialState) return ( {props.children} ) } export default ResultsContextProvider; riipandi/varlet-website import Head from 'next/head' import Link from 'next/link' // import SampleHomepage from '../components/sample-homepage' import SiteLayout from '../components/site-layout' import { SectionCta } from './../components/section-cta' // import { SectionNewsletter } from './../components/section-newsletter' export default function Home() { return ( Varlet - Minimalism web development stack {/* */}

    Minimalism web development stack.

    Varlet is a web development environment for minimalists, inspired from Laravel Valet and Laragon.

    Feature Highlights

    Has your local development environment gotten needlessly complex? Varlet completely manages all of the command-line complexity so you can get back to work.

    {/* Heroicon name: check */}
    Blazing fast
    Tempor tellus in aliquet eu et sit nulla tellus. Suspendisse est, molestie blandit quis ac. Lacus.
    {/* Heroicon name: check */}
    Simple, beautiful UI
    Ornare donec rhoncus vitae nisl velit, neque, mauris dictum duis. Nibh urna non parturient.
    {/* Heroicon name: check */}
    Completely self-contained
    Etiam cras augue ornare pretium sit malesuada morbi orci, venenatis. Dictum lacus.
    {/* Heroicon name: check */}
    Flexibility
    Magna a vel sagittis aliquam eu amet. Et lorem auctor quam nunc odio. Sed bibendum.
    {/* Heroicon name: check */}
    Integrations
    Sed mi, dapibus turpis orci posuere integer. A porta viverra posuere adipiscing turpis.
    {/* Heroicon name: check */}
    Mobile app
    Quisque sapien nunc nisl eros. Facilisis sagittis maecenas id dignissim tristique proin sed.
    {/*
    */}
    ) } const requestFullscreen = function (ele) { ele.classList.add('videoWrapper__fullscreen'); if (!document.fullscreenElement && ele.requestFullscreen) { ele.requestFullscreen().catch(err => { console.log(`Error attempting to enable full-screen mode: ${err.message} (${err.name})`); }); } else if (!document.fullscreenElement && ele.webkitRequestFullscreen) { ele.webkitRequestFullscreen(); } else if (!document.fullscreenElement && ele.mozRequestFullScreen) { ele.mozRequestFullScreen(); } else if (!document.fullscreenElement && ele.msRequestFullscreen) { ele.msRequestFullscreen(); } else { console.log('Fullscreen API is not supported.'); } }; const exitFullscreen = function (ele) { ele.classList.remove('videoWrapper__fullscreen'); // Check if fullscreen is actually activated (if user pressed ESC, it may not be) if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement) { return null; } if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else { console.log('Fullscreen API is not supported.'); } }; export { requestFullscreen, exitFullscreen };src/NumberInput/withFormField.js import { NumberInput } from 'grommet' import wrapComponentWithFormField from '../wrapComponentWithFormField' import mapProps from './mapProps' export default wrapComponentWithFormField(NumberInput, mapProps) function toHMS(ms) { let s = ms / 1000 >> 0; ms = ms % 1000; const result = []; let index = 0; while (s > 0 && index < 3) { const time = s % 60; s = s / 60 >> 0; index += 1; result.push(time); } if (result.length === 0) { result.push(0); } return result.reverse().join(':') + '.' + ms; } module.exports = { toHMS, }; jstests/tool/dumprestore1.js // dumprestore1.js t = new ToolTest( "dumprestore1" ); c = t.startDB( "foo" ); assert.eq( 0 , c.count() , "setup1" ); c.save( { a : 22 } ); assert.eq( 1 , c.count() , "setup2" ); t.runTool( "dump" , "--out" , t.ext ); c.drop(); assert.eq( 0 , c.count() , "after drop" ); t.runTool( "restore" , "--dir" , t.ext ); assert.soon( "c.findOne()" , "no data after sleep" ); assert.eq( 1 , c.count() , "after restore 2" ); assert.eq( 22 , c.findOne().a , "after restore 2" ); // ensure that --collection is used with --db. See SERVER-7721 var ret = t.runTool( "dump" , "--collection" , "col" ); assert.neq( ret, 0, "mongoldump should return failure code" ); t.stop(); // Ensure that --db and --collection are provided when filename is "-" (stdin). ret = t.runTool( "restore" , "--collection" , "coll", "--dir", "-" ); assert.neq( ret, 0, "mongolrestore should return failure code" ); t.stop(); ret = t.runTool( "restore" , "--db" , "db", "--dir", "-" ); assert.neq( ret, 0, "mongolrestore should return failure code" ); t.stop(); deswan/vue-pagium1-10 const utils = require('./utils') const { getIsValid } = require('../type_parser') function checkData(data, allComsConfig, allPages, noCheckConfig) { let page = data.page; if (page && typeof page !== 'string') { throw new Error('page字段格式不合法') } if (page && !allPages[page]) { if (!noCheckConfig) throw new Error(`不存在根组件 ${page}`) } if(data.components) checkComponents(data.components || []) function checkComponents(components, allComsConfig, noCheckConfig) { if (!Array.isArray(components)) { throw new Error('components字段格式不合法') } components.forEach(item => { try { checkItem(item); } catch (err) { throw new Error(JSON.stringify(item, null, 2) + "\n" + err.message) } if (item.children) { checkComponents(item.children, allComsConfig, noCheckConfig) } }) } function checkItem(item) { if (!item.type) { throw new Error('type 不能为空') } if (typeof item.type != 'string') { throw new Error('type 不合法') } if (!item.name) { throw new Error('name 不能为空') } if (typeof item.name != 'string' || !utils.isValidIdentifier(item.name)) { throw new Error('name 不合法(必须为合法js标识符)') } let config = allComsConfig[item.type]; if (!config) { if (noCheckConfig) return; throw new Error(`组件 ${item.type} 未定义`) } if (item.props && !noCheckConfig) { checkProps(item.props, config, item.type) } } function checkProps(props, config, comName) { if (!utils.isPlainObject(props)) { throw new Error(`props属性不合法`) } Object.keys(props).forEach(propName => { let conf = utils.getConfByPropName(propName, config) //验证组件是否存在该prop if (!conf) { throw new Error(`组件 ${comName} 不存在 prop: ${propName}`) } if (!getIsValid(conf.type).call(conf, props[propName])) { throw new Error(`prop ${propName} 的值不符合对应的类型`) } }) } } module.exports = checkDataexport default function ExampleComponent({ data }) { return (
    COMPONENT EXAMPLE: {`The ${data.speed} ${data.color} ${data.animal}`}
    ) } var fs = require('fs-extra'); var path = require('path'); var mkdirp = require('mkdirp'); fs.readdirSync(__dirname).forEach(function(test) { var testPath = path.join(__dirname, test); if (fs.statSync(testPath).isDirectory()) { if (test === 'testLib') return; // update this manually when a new version comes out var expectedOutput = path.join(testPath, 'expectedOutput-3.3'), newExpectedOutput = path.join(testPath, 'expectedOutput-3.4'); mkdirp.sync(newExpectedOutput); fs.copySync(expectedOutput, newExpectedOutput); } }); // ***************************************************************************** // Copyright 2013-2020 Aerospike, 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. // ***************************************************************************** 'use strict' const pThrottle = require('p-throttle') const Aerospike = require('../../lib/aerospike') const Record = require('../../lib/record') const helper = require('../test_helper') function createRecords (putCall, generator, recordsToCreate, maxConcurrent, callback) { var currentRecordNo = 0 var inFlight = 0 var creator = function (record, err) { if (err) { console.error('ERROR: %s [%d] in %s at %s:%d\n%s', err.message, err.code, err.func, err.file, err.line, err.stack) throw err } if (record) { callback(record) inFlight-- } currentRecordNo++ if (currentRecordNo <= recordsToCreate && inFlight < maxConcurrent) { record = new Record(generator.key(), generator.bins(), generator.metadata()) const putCb = creator.bind(this, record) const policy = generator.policy() const meta = { ttl: record.ttl, gen: record.gen } putCall(record.key, record.bins, meta, policy, putCb) inFlight++ } else if (currentRecordNo > recordsToCreate && inFlight === 0) { callback(null) } } for (var i = 0; i < Math.min(maxConcurrent, recordsToCreate); i++) { creator(null, null) } } function put (n, options, callback) { const policy = options.policy || new Aerospike.WritePolicy({ totalTimeout: 1000, exists: Aerospike.policy.exists.CREATE_OR_REPLACE }) const generator = { key: options.keygen, bins: options.recgen, metadata: options.metagen, policy: function () { return policy } } let putCall = helper.client.put.bind(helper.client) if (options.throttle) { const { limit, interval } = options.throttle putCall = pThrottle(putCall, limit, interval) } if (callback) { createRecords(putCall, generator, n, 200, callback) } else { return new Promise((resolve, reject) => { const records = [] createRecords(putCall, generator, n, 200, record => { if (record) { records.push(record) } else { resolve(records) } }) }) } } module.exports = { put } import React from 'react'; import { Box } from '@material-ui/core'; import { useHistory } from 'react-router-dom'; import DateRangeIcon from '@material-ui/icons/DateRange'; import './style.css'; function InformationUserForm() { const history = useHistory() return (
    Đặt Phòng
    ); } export default InformationUserForm; "use strict" Object.defineProperty(exports, "__esModule", { value: true, }) exports.StreetViewPanorama = undefined var _defineProperty2 = require("babel-runtime/helpers/defineProperty") var _defineProperty3 = _interopRequireDefault(_defineProperty2) var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of") var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf) var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck") var _classCallCheck3 = _interopRequireDefault(_classCallCheck2) var _createClass2 = require("babel-runtime/helpers/createClass") var _createClass3 = _interopRequireDefault(_createClass2) var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn") var _possibleConstructorReturn3 = _interopRequireDefault( _possibleConstructorReturn2 ) var _inherits2 = require("babel-runtime/helpers/inherits") var _inherits3 = _interopRequireDefault(_inherits2) var _invariant = require("invariant") var _invariant2 = _interopRequireDefault(_invariant) var _react = require("react") var _react2 = _interopRequireDefault(_react) var _propTypes = require("prop-types") var _propTypes2 = _interopRequireDefault(_propTypes) var _MapChildHelper = require("../utils/MapChildHelper") var _constants = require("../constants") function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj } } /** * A wrapper around `google.maps.StreetViewPanorama` * * @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#StreetViewPanorama */ var StreetViewPanorama = (exports.StreetViewPanorama = (function( _React$PureComponent ) { ;(0, _inherits3.default)(StreetViewPanorama, _React$PureComponent) function StreetViewPanorama(props, context) { ;(0, _classCallCheck3.default)(this, StreetViewPanorama) var _this = (0, _possibleConstructorReturn3.default)( this, ( StreetViewPanorama.__proto__ || (0, _getPrototypeOf2.default)(StreetViewPanorama) ).call(this, props, context) ) ;(0, _invariant2.default)( !!_this.context[_constants.MAP], "Did you render as a child of with withGoogleMap() HOC?" ) ;(0, _MapChildHelper.construct)( StreetViewPanorama.propTypes, updaterMap, _this.props, _this.context[_constants.MAP].getStreetView() ) return _this } ;(0, _createClass3.default)(StreetViewPanorama, [ { key: "getChildContext", value: function getChildContext() { return (0, _defineProperty3.default)( {}, _constants.MAP, this.context[_constants.MAP].getStreetView() ) }, }, { key: "componentDidMount", value: function componentDidMount() { ;(0, _MapChildHelper.componentDidMount)( this, this.context[_constants.MAP].getStreetView(), eventMap ) }, }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { ;(0, _MapChildHelper.componentDidUpdate)( this, this.context[_constants.MAP].getStreetView(), eventMap, updaterMap, prevProps ) }, }, { key: "componentWillUnmount", value: function componentWillUnmount() { ;(0, _MapChildHelper.componentWillUnmount)(this) var streetViewPanorama = this.context[_constants.MAP].getStreetView() if (streetViewPanorama) { streetViewPanorama.setVisible(false) } }, }, { key: "render", value: function render() { var children = this.props.children return _react2.default.createElement("div", null, children) }, /** * Returns the set of navigation links for the Street View panorama. * @type Array * @public */ }, { key: "getLinks", value: function getLinks() { return this.context[_constants.MAP].getLinks() }, /** * Returns the StreetViewLocation of the current panorama. * @type StreetViewLocation * @public */ }, { key: "getLocation", value: function getLocation() { return this.context[_constants.MAP].getLocation() }, /** * Returns the state of motion tracker. If true when the user physically moves the device and the browser supports it, the Street View Panorama tracks the physical movements. * @type boolean * @public */ }, { key: "getMotionTracking", value: function getMotionTracking() { return this.context[_constants.MAP].getMotionTracking() }, /** * Returns the current panorama ID for the Street View panorama. This id is stable within the browser's current session only. * @type string * @public */ }, { key: "getPano", value: function getPano() { return this.context[_constants.MAP].getPano() }, /** * Returns the heading and pitch of the photographer when this panorama was taken. For Street View panoramas on the road, this also reveals in which direction the car was travelling. This data is available after the `pano_changed` event. * @type StreetViewPovpano_changed * @public */ }, { key: "getPhotographerPov", value: function getPhotographerPov() { return this.context[_constants.MAP].getPhotographerPov() }, /** * Returns the current `LatLng` position for the Street View panorama. * @type LatLngLatLng * @public */ }, { key: "getPosition", value: function getPosition() { return this.context[_constants.MAP].getPosition() }, /** * Returns the current point of view for the Street View panorama. * @type StreetViewPov * @public */ }, { key: "getPov", value: function getPov() { return this.context[_constants.MAP].getPov() }, /** * Returns the status of the panorama on completion of the `setPosition()` or `setPano()` request. * @type StreetViewStatussetPosition()setPano() * @public */ }, { key: "getStatus", value: function getStatus() { return this.context[_constants.MAP].getStatus() }, /** * Returns `true` if the panorama is visible. It does not specify whether Street View imagery is available at the specified position. * @type booleantrue * @public */ }, { key: "getVisible", value: function getVisible() { return this.context[_constants.MAP].getVisible() }, /** * Returns the zoom level of the panorama. Fully zoomed-out is level 0, where the field of view is 180 degrees. Zooming in increases the zoom level. * @type number * @public */ }, { key: "getZoom", value: function getZoom() { return this.context[_constants.MAP].getZoom() }, }, ]) return StreetViewPanorama })( _react2.default.PureComponent )) /* * ----------------------------------------------------------------------------- * This file is auto-generated from the corresponding file at `src/macros/`. * Please **DO NOT** edit this file directly when creating PRs. * ----------------------------------------------------------------------------- */ StreetViewPanorama.propTypes = { /** * @type Array */ defaultLinks: _propTypes2.default.any, /** * @type boolean */ defaultMotionTracking: _propTypes2.default.bool, /** * @type StreetViewPanoramaOptions */ defaultOptions: _propTypes2.default.any, /** * @type string */ defaultPano: _propTypes2.default.string, /** * @type LatLng|LatLngLiteral */ defaultPosition: _propTypes2.default.any, /** * @type StreetViewPov */ defaultPov: _propTypes2.default.any, /** * @type boolean */ defaultVisible: _propTypes2.default.bool, /** * @type number */ defaultZoom: _propTypes2.default.number, /** * @type Array */ links: _propTypes2.default.any, /** * @type boolean */ motionTracking: _propTypes2.default.bool, /** * @type StreetViewPanoramaOptions */ options: _propTypes2.default.any, /** * @type string */ pano: _propTypes2.default.string, /** * @type LatLng|LatLngLiteral */ position: _propTypes2.default.any, /** * @type StreetViewPov */ pov: _propTypes2.default.any, /** * @type boolean */ visible: _propTypes2.default.bool, /** * @type number */ zoom: _propTypes2.default.number, /** * function */ onCloseClick: _propTypes2.default.func, /** * function */ onPanoChanged: _propTypes2.default.func, /** * function */ onPositionChanged: _propTypes2.default.func, /** * function */ onPovChanged: _propTypes2.default.func, /** * function */ onResize: _propTypes2.default.func, /** * function */ onStatusChanged: _propTypes2.default.func, /** * function */ onVisibleChanged: _propTypes2.default.func, /** * function */ onZoomChanged: _propTypes2.default.func, } StreetViewPanorama.contextTypes = (0, _defineProperty3.default)( {}, _constants.MAP, _propTypes2.default.object ) StreetViewPanorama.childContextTypes = (0, _defineProperty3.default)( {}, _constants.MAP, _propTypes2.default.object ) exports.default = StreetViewPanorama var eventMap = { onCloseClick: "closeclick", onPanoChanged: "pano_changed", onPositionChanged: "position_changed", onPovChanged: "pov_changed", onResize: "resize", onStatusChanged: "status_changed", onVisibleChanged: "visible_changed", onZoomChanged: "zoom_changed", } var updaterMap = { links: function links(instance, _links) { instance.setLinks(_links) }, motionTracking: function motionTracking(instance, _motionTracking) { instance.setMotionTracking(_motionTracking) }, options: function options(instance, _options) { instance.setOptions(_options) }, pano: function pano(instance, _pano) { instance.setPano(_pano) }, position: function position(instance, _position) { instance.setPosition(_position) }, pov: function pov(instance, _pov) { instance.setPov(_pov) }, visible: function visible(instance, _visible) { instance.setVisible(_visible) }, zoom: function zoom(instance, _zoom) { instance.setZoom(_zoom) }, } pushkar8723/ngBgloader /** * Created by pushkar on 6/21/16. */ (function () { 'use-strict'; angular.module('ngBgloader', ['ngAnimate']).directive('bgLoader', function() { return { restrict: 'E', scope: { placeholder: '=placeholder', src: '=src', givenStyles: '=?styles', placeholderStyles: '=?placeholderStyles' }, controller: ['$scope', '$http', function($scope, $http) { $scope.loadComplete = false; if ($scope.placeholderStyles != null) { $scope.styles = JSON.parse(JSON.stringify($scope.placeholderStyles)); } else if ($scope.givenStyles != null) { $scope.styles = JSON.parse(JSON.stringify($scope.givenStyles)); } else { $scope.styles = {}; } if ($scope.styles['background-size'] == null) $scope.styles['background-size'] = 'cover'; if ($scope.styles['position'] == null) $scope.styles['position'] = 'absolute'; if ($scope.styles['top'] == null) $scope.styles['top'] = '0px'; if ($scope.styles['left'] == null) $scope.styles['left'] = '0px'; if ($scope.styles['right'] == null) $scope.styles['right'] = "0px"; if ($scope.styles['bottom'] == null) $scope.styles['bottom'] = "0px"; $scope.styles['background-image'] = 'url('+$scope.placeholder+')'; setTimeout(function () { $scope.$apply(); }, 100); $http({ url: $scope.src, method: "GET", responseType: "blob" }).then(function (data) { var reader = new FileReader(); reader.addEventListener("load", function () { if ($scope.givenStyles == null) { $scope.newStyles = {}; } else { $scope.newStyles = JSON.parse(JSON.stringify($scope.givenStyles)); } if ($scope.newStyles['background-size'] == null) $scope.newStyles['background-size'] = 'cover'; if ($scope.newStyles['position'] == null) $scope.newStyles['position'] = 'absolute'; if ($scope.newStyles['top'] == null) $scope.newStyles['top'] = '0px'; if ($scope.newStyles['left'] == null) $scope.newStyles['left'] = '0px'; if ($scope.newStyles['right'] == null) $scope.newStyles['right'] = "0px"; if ($scope.newStyles['bottom'] == null) $scope.newStyles['bottom'] = "0px"; $scope.fullImageStyles = JSON.parse(JSON.stringify($scope.newStyles)); $scope.fullImageStyles['background-image'] = 'url('+reader.result+')'; $scope.loadComplete = true; $scope.$apply(); }, false); reader.readAsDataURL(data.data); }); }], template: '
    ' + '' }; }); })();/* eslint-env node, mocha */ var assert = require('assert'); var Client = require('./helpers/index'); var processHelper = require('./helpers/process'); describe('policies', function() { var policyApp = processHelper('policyApp'); var client; before(function(done) { policyApp.start(8054).done(function() { client = new Client('localhost', 8054); done(); }); }); it('named policy', function(done) { client.socket.emit('policy:named', {msg: 'let me pass'}).asCallback(function(err, data) { if (err) { return done(err); } assert(data); assert.strictEqual(data.response, 'OK'); done(); }); }); it('named policy forbidden', function(done) { client.socket.emit('policy:named', {msg: 'do not let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#FORBIDDEN'); done(); }); }); it('inline policy', function(done) { client.socket.emit('policy:inline', {msg: 'let me pass'}).asCallback(function(err, data) { if (err) { return done(err); } assert(data); assert.strictEqual(data.response, 'OK'); done(); }); }); it('inline policy forbidden', function(done) { client.socket.emit('policy:inline', {msg: 'do not let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#FORBIDDEN'); done(); }); }); it('mixed policy', function(done) { client.socket.emit('policy:mixed', {msg: 'let me pass'}).asCallback(function(err, data) { if (err) { return done(err); } assert(data); assert.strictEqual(data.response, 'OK'); done(); }); }); it('mixed policy forbidden', function(done) { client.socket.emit('policy:mixed', {msg: 'do not let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#FORBIDDEN'); done(); }); }); it('unknown policy', function(done) { client.socket.emit('policy:unknown', {msg: 'let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#INTERNAL_SERVER_ERROR'); done(); }); }); it('mixed unknown', function(done) { client.socket.emit('policy:mixedUnknown', {msg: 'let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#INTERNAL_SERVER_ERROR'); done(); }); }); it('empty policy', function(done) { client.socket.emit('policy:empty', {msg: 'let me pass'}).asCallback(function(err, data) { if (err) { return done(err); } assert(data); assert.strictEqual(data.response, 'OK'); done(); }); }); it('wrong type policy', function(done) { client.socket.emit('policy:wrongType', {msg: 'let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#INTERNAL_SERVER_ERROR'); done(); }); }); it('policy throw error', function(done) { client.socket.emit('policy:throw', {msg: 'let me pass'}).asCallback(function(err, data) { assert(!data); assert(err); assert.strictEqual(err.message, '#INTERNAL_SERVER_ERROR'); done(); }); }); after(function(done) { policyApp.stop().asCallback(done); }); }); 1-10 'use strict'; // Load modules const Hoek = require('hoek'); // Declare internals const internals = {}; // https://tools.ietf.org/html/rfc7231#section-5.3.5 // Accept-Language: da, en-gb;q=0.8, en;q=0.7 exports.language = function (header, preferences) { Hoek.assert(!preferences || Array.isArray(preferences), 'Preferences must be an array'); const languages = exports.languages(header); if (languages.length === 0) { languages.push(''); } // No preferences. Take the first charset. if (!preferences || preferences.length === 0) { return languages[0]; } // If languages includes * return first preference if (languages.indexOf('*') !== -1) { return preferences[0]; } // Try to find the first match in the array of preferences preferences = preferences.map((str) => str.toLowerCase()); for (let i = 0; i < languages.length; ++i) { if (preferences.indexOf(languages[i].toLowerCase()) !== -1) { return languages[i]; } } return ''; }; exports.languages = function (header) { if (header === undefined || typeof header !== 'string') { return []; } return header .split(',') .map(internals.getParts) .filter(internals.removeUnwanted) .sort(internals.compareByWeight) .map(internals.partToLanguage); }; internals.getParts = function (item) { const result = { weight: 1, language: '' }; const match = item.match(internals.partsRegex); if (!match) { return result; } result.language = match[1]; if (match[2] && internals.isNumber(match[2])) { const weight = parseFloat(match[2]); if (weight === 0 || (weight >= 0.001 && weight <= 1)) { result.weight = weight; } } return result; }; // 1: token 2: qvalue internals.partsRegex = /\s*([^;]+)(?:\s*;\s*[qQ]\=([01](?:\.\d*)?))?\s*/; internals.removeUnwanted = function (item) { return item.weight !== 0 && item.language !== ''; }; internals.compareByWeight = function (a, b) { return b.weight - a.weight; }; internals.partToLanguage = function (item) { return item.language; }; internals.isNumber = function (n) { return !isNaN(parseFloat(n)); }; Travelbanda/Client 'use strict'; /*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ import Store from 'core/store'; import iBlock from 'super/i-block/i-block'; import { component } from 'core/component'; export const $$ = new Store(); @component() export default class bUp extends iBlock { /** @inheritDoc */ static mods = { hidden: [ ['true'], 'false' ] }; /** @inheritDoc */ mounted() { const {async: $a} = this; $a.on(document, 'scroll', { label: $$.scroll, fn: () => this.setMod('hidden', !(pageYOffset > innerHeight / 3)) }); $a.on(this.$el, 'click', { label: $$.up, fn: () => window.scrollTo(0, 0) }); } } build/package/nginx/content/static/js/ctrl.js const URL_PARAMS = new URLSearchParams(window.location.search); let output; let input; let roomNameInput; let roomPasswdInput; let roomUserNameInput; let messageTextInput; let messageTextEditInput; let messageTextDeleteInput; let messageTextSupportRejectInput; let textMessageOutput; let srvErrorText; let wsErrorText; function init () { document.getElementById('rooms_list_link') .setAttribute("href", './ctrl_rooms?' + URL_PARAM_BACKEND_HOST + '=' + URL_PARAMS.get(URL_PARAM_BACKEND_HOST)) output = document.getElementById("raw_output"); input = document.getElementById("raw_input"); roomNameInput = document.getElementById("r_name"); roomPasswdInput = document.getElementById("r_passwd"); roomUserNameInput = document.getElementById("r_user_name"); messageTextInput = document.getElementById("text_message"); messageTextEditInput = document.getElementById("text_message_edit"); messageTextDeleteInput = document.getElementById("text_message_delete"); messageTextSupportRejectInput = document.getElementById("text_message_support_reject"); textMessageOutput = document.getElementById("text_msg_output"); srvErrorText = document.getElementById("srv_error_txt"); wsErrorText = document.getElementById("ws_error_txt"); keepAlive(); } function keepAlive () { console.log(getCurrentTimeStr() + ": start keepAlive, timeoutId: " + keepAliveTimerID); if (ws) { switch (ws.readyState) { case ws.OPEN: console.log(getCurrentTimeStr() + ": keepalive"); ws.send(KEEP_ALIVE_BEACON); break case ws.CLOSED: case ws.CLOSING: console.log(getCurrentTimeStr() + ": socket closed"); break } } keepAliveTimerID = setTimeout(keepAlive, KEEPALIVE_INTERVAL_MS); console.log(getCurrentTimeStr() + ": end keepAlive, timeoutId: " + keepAliveTimerID); } function cancelKeepAlive () { if (keepAliveTimerID) { clearTimeout(keepAliveTimerID); } } window.onbeforeunload = function (e) { cancelKeepAlive(); if (ws) { ws.close(WS_CLOSE_CODE_NORMAL); } return null; } window.addEventListener( "beforeunload", function (e) { cancelKeepAlive(); if (ws) { ws.close(WS_CLOSE_CODE_NORMAL); } return null; }, false ); function applyCallbacks () { ws.onopen = function(evt) { outputLog("++ OPENED" + "\n"); sendData(ws, JSON.stringify({ p: 'unknown' }) ); } ws.onclose = function(evt) { outputLog("++ CLOSED" + "\n"); } ws.onmessage = function(evt) { let messageJson = evt.data; if (messageJson.startsWith("{\"c\":\"ER\"")) { const newErrBlock = document.createElement("div"); newErrBlock.textContent = messageJson; srvErrorText.appendChild(newErrBlock); } else if (messageJson.startsWith("{\"c\":\"TM\"")) { let messageObj = JSON.parse(messageJson); if (messageObj.m.length < 1) { const newErrBlock = document.createElement("div"); newErrBlock.textContent = "got zero size messages array"; srvErrorText.appendChild(newErrBlock); return } let message = messageObj.m[0]; const textMsgBlock = document.createElement("div"); textMsgBlock.textContent = "[" + message.uId + " | " + getTimeStrFromNano(message.cAt) + "]: #" + message.id + " " + decodeURI(message.t); textMessageOutput.appendChild(textMsgBlock); } else if (messageJson.startsWith("{\"c\":\"ALL_TM\"")) { let messageObj = JSON.parse(messageJson); let roomMessages = messageObj.m; if (roomMessages) { roomMessages.forEach(function (nextMessage) { const textMsgBlock = document.createElement("div"); textMsgBlock.textContent = "[" + nextMessage.uId + " | " + getTimeStrFromNano(nextMessage.cAt) + "]: #" + nextMessage.id + " " + decodeURI(nextMessage.t); textMessageOutput.appendChild(textMsgBlock); }); } } outputLog("----------------------------"); outputLog(messageJson); } ws.onerror = function(evt) { const newErrBlock = document.createElement("div"); newErrBlock.textContent = evt.data; wsErrorText.append(newErrBlock); } } function initWebSocket () { if (ws) { ws.close(WS_CLOSE_CODE_NORMAL); } ws = new WebSocket(WS_ENDPOINT + '?' + URL_PARAM_BACKEND_HOST + '=' + URL_PARAMS.get(URL_PARAM_BACKEND_HOST)); applyCallbacks(); } function sendData (ws, inputStr) { ws.send(inputStr); outputLog("++ SENT '" + inputStr + "', " + (inputStr ? inputStr.length : -1) + " symbols\n"); return false; } function outputLog (message) { let d = document.createElement("div"); d.textContent = message; output.prepend(document.createElement("br")); output.prepend(d); } function createOrJoinRoom () { initWebSocket(); setTimeout(function () { sendData(ws, JSON.stringify({ c: "R_C_J", uN: roomUserNameInput.value, r: { n: roomNameInput.value, p: roomPasswdInput.value } }) ); }, 100); } function createRoom () { initWebSocket(); setTimeout(function () { sendData(ws, JSON.stringify({ c: "R_C", r: { n: roomNameInput.value, p: roomPasswdInput.value } }) ); }, 100); } function joinRoom () { initWebSocket(); setTimeout(function () { sendData(ws, JSON.stringify({ c: "R_J", uN: roomUserNameInput.value, r: { n: roomNameInput.value, p: roomPasswdInput.value } }) ); }, 100); } function changeRoomUserName () { setTimeout(function () { sendData(ws, JSON.stringify({ c: "R_CH_UN", uN: roomUserNameInput.value, r: { n: roomNameInput.value, } }) ); }, 100); } function sendMsg () { setTimeout(function () { let messageEditId = messageTextEditInput.value; let messageDeleteId = messageTextDeleteInput.value; if (messageEditId) { sendData(ws, JSON.stringify({ c: "TM_E", r: { n: roomNameInput.value }, m: { id: parseInt(messageEditId), t: messageTextInput.value } }) ); } else if (messageDeleteId) { sendData(ws, JSON.stringify({ c: "TM_D", r: { n: roomNameInput.value }, m: { id: parseInt(messageDeleteId) } }) ); } else { sendData(ws, JSON.stringify({ c: "TM", r: { n: roomNameInput.value }, m: { t: encodeURI(messageTextInput.value) } }) ); } }, 100); } function supportRejectMsg (isSupport) { setTimeout(function () { let messageId = messageTextSupportRejectInput.value; sendData(ws, JSON.stringify({ c: "TM_S_R", r: { n: roomNameInput.value }, srM: isSupport, m: { id: parseInt(messageId) } }) ); }, 100); } // Callbacks function onManualReconnect () { initWebSocket(); return false; } function onManualSend () { if (!ws) { initWebSocket(); } setTimeout(function () { sendData(ws, input.value) }, 100); return false; } function onChangeBackend () { const updatedQueryStr = replaceQueryParam( 'backendHost', document.getElementById("backend_instance_host").value, window.location.search ); window.location = window.location.protocol + '//' + window.location.host + window.location.pathname + updatedQueryStr; return false; } // Util function getTimeStrFromNano (nanoTimestamp) { const date = new Date(Math.trunc(nanoTimestamp / 1000000)); return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); } function getCurrentTimeStr () { const today = new Date(); return today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds(); } function getCookie (name) { const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)')); if (match) return match[2]; } function setCookie (name, value) { document.cookie = name + '=' + value; } function replaceQueryParam (param, newval, search) { const regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?"); const query = search.replace(regex, "$1").replace(/&$/, ''); return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : ''); }import artifactsApi from '../api/artifacts-api' import { CLOSE_ARTIFACT_PREVIEW, FETCH_ARTIFACTS_BEGIN, FETCH_ARTIFACTS_FAILURE, FETCH_ARTIFACTS_SUCCESS, FETCH_DATASETS_BEGIN, FETCH_DATASETS_FAILURE, FETCH_DATASETS_SUCCESS, FETCH_FILES_BEGIN, FETCH_FILES_FAILURE, FETCH_FILES_SUCCESS, FETCH_MODELS_BEGIN, FETCH_MODELS_FAILURE, FETCH_MODELS_SUCCESS, REMOVE_ARTIFACTS, REMOVE_DATASETS, SHOW_ARTIFACT_PREVIEW, SET_ARTIFACT_FILTER, REMOVE_FILES, REMOVE_MODELS } from '../constants' import { filterArtifacts } from '../utils/filterArtifacts' const artifactsAction = { closeArtifactsPreview: item => ({ type: CLOSE_ARTIFACT_PREVIEW, payload: item }), fetchArtifacts: item => dispatch => { dispatch(artifactsAction.fetchArtifactsBegin()) return artifactsApi .getArtifacts(item) .then(({ data }) => { let artifacts = filterArtifacts(data.artifacts) dispatch(artifactsAction.fetchArtifactsSuccess(artifacts)) return artifacts }) .catch(err => { dispatch(artifactsAction.fetchArtifactsFailure(err)) }) }, fetchArtifactsBegin: () => ({ type: FETCH_ARTIFACTS_BEGIN }), fetchArtifactsFailure: error => ({ type: FETCH_ARTIFACTS_FAILURE, payload: error }), fetchArtifactsSuccess: artifactsList => ({ type: FETCH_ARTIFACTS_SUCCESS, payload: artifactsList }), fetchDataSets: project => dispatch => { dispatch(artifactsAction.fetchDataSetsBegin()) return artifactsApi .getArtifactsDataSets(project) .then(({ data }) => { let dataSets = filterArtifacts(data.artifacts) dispatch(artifactsAction.fetchDataSetsSuccess(dataSets)) return dataSets }) .catch(err => { dispatch(artifactsAction.fetchDataSetsFailure(err)) }) }, fetchDataSetsBegin: () => ({ type: FETCH_DATASETS_BEGIN }), fetchDataSetsFailure: () => ({ type: FETCH_DATASETS_FAILURE }), fetchDataSetsSuccess: dataSets => ({ type: FETCH_DATASETS_SUCCESS, payload: dataSets }), fetchFiles: project => dispatch => { dispatch(artifactsAction.fetchFilesBegin()) return artifactsApi .getArtifactsFiles(project) .then(({ data }) => { let files = filterArtifacts(data.artifacts) dispatch(artifactsAction.fetchFilesSuccess(files)) return files }) .catch(err => { dispatch(artifactsAction.fetchFilesFailure(err)) }) }, fetchFilesBegin: () => ({ type: FETCH_FILES_BEGIN }), fetchFilesFailure: () => ({ type: FETCH_FILES_FAILURE }), fetchFilesSuccess: files => ({ type: FETCH_FILES_SUCCESS, payload: files }), fetchModels: project => dispatch => { dispatch(artifactsAction.fetchModelsBegin()) return artifactsApi .getArtifactsModels(project) .then(({ data }) => { let models = filterArtifacts(data.artifacts) dispatch(artifactsAction.fetchModelsSuccess(models)) return models }) .catch(err => { dispatch(artifactsAction.fetchModelsFailure(err)) }) }, fetchModelsBegin: () => ({ type: FETCH_MODELS_BEGIN }), fetchModelsFailure: () => ({ type: FETCH_MODELS_FAILURE }), fetchModelsSuccess: models => ({ type: FETCH_MODELS_SUCCESS, payload: models }), removeArtifacts: () => ({ type: REMOVE_ARTIFACTS }), removeDataSets: () => ({ type: REMOVE_DATASETS }), removeFiles: () => ({ type: REMOVE_FILES }), removeModels: () => ({ type: REMOVE_MODELS }), setArtifactFilter: filter => ({ type: SET_ARTIFACT_FILTER, payload: filter }), showArtifactsPreview: item => ({ type: SHOW_ARTIFACT_PREVIEW, payload: item }) } export default artifactsAction niuyi1017/myBlog0 const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, output: process.stdout }) let lineNum = 0 let elementNum = 0 let stdArr = [] let testNum = 0 let testArr = [] let result = null rl.on('line', data => { lineNum++ if (lineNum == 1) elementNum = Number(data.trim()) else if (lineNum == 2) stdArr = data.trim().split(' ') else if (lineNum == 3) testNum = Number(data.trim()) else { testNum -- testArr = data.trim().split(' ') console.log(handle(testArr)) if (testNum == 0) { process.exit(0) } } }) function handle(testArr) { let count = 0 testArr.forEach(item => { if (stdArr.includes(item)){ count++ } }) return count }/** * @author <> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Class = require('../../../utils/Class'); var GetFastValue = require('../../../utils/object/GetFastValue'); var ShaderSourceFS = require('../shaders/Mesh-frag.js'); var ShaderSourceVS = require('../shaders/Mesh-vert.js'); var WebGLPipeline = require('../WebGLPipeline'); /** * @classdesc * TODO * * @class MeshPipeline * @extends Phaser.Renderer.WebGL.WebGLPipeline * @memberof Phaser.Renderer.WebGL.Pipelines * @constructor * @since 3.50.0 * * @param {Phaser.Types.Renderer.WebGL.WebGLPipelineConfig} config - The configuration options for this pipeline. */ var MeshPipeline = new Class({ Extends: WebGLPipeline, initialize: function MeshPipeline (config) { var gl = config.game.renderer.gl; config.fragShader = GetFastValue(config, 'fragShader', ShaderSourceFS), config.vertShader = GetFastValue(config, 'vertShader', ShaderSourceVS), config.vertexCapacity = GetFastValue(config, 'vertexCapacity', 2048 * 8), config.vertexSize = GetFastValue(config, 'vertexSize', 32), config.attributes = GetFastValue(config, 'attributes', [ { name: 'aVertexPosition', size: 3, type: gl.FLOAT, normalized: false, offset: 0, enabled: false, location: -1 }, { name: 'aVertexNormal', size: 3, type: gl.FLOAT, normalized: false, offset: 12, enabled: false, location: -1 }, { name: 'aTextureCoord', size: 2, type: gl.FLOAT, normalized: false, offset: 24, enabled: false, location: -1 } ]); WebGLPipeline.call(this, config); /** * Float32 view of the array buffer containing the pipeline's vertices. * * @name Phaser.Renderer.WebGL.Pipelines.MeshPipeline#vertexViewF32 * @type {Float32Array} * @since 3.0.0 */ this.vertexViewF32 = new Float32Array(this.vertexData); this.forceZero = true; }, /** * Called every time the pipeline is bound by the renderer. * Sets the shader program, vertex buffer and other resources. * Should only be called when changing pipeline. * * @method Phaser.Renderer.WebGL.Pipelines.MeshPipeline#bind * @since 3.50.0 * * @param {boolean} [reset=false] - Should the pipeline be fully re-bound after a renderer pipeline clear? * * @return {this} This WebGLPipeline instance. */ bind: function (reset) { if (reset === undefined) { reset = false; } WebGLPipeline.prototype.bind.call(this, reset); var gl = this.gl; gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); return this; }, /** * This method is called every time a Game Object asks the Pipeline Manager to use this pipeline. * * Unlike the `bind` method, which is only called once per frame, this is called for every object * that requests it, allowing you to perform per-object GL set-up. * * @method Phaser.Renderer.WebGL.Pipelines.MeshPipeline#onBind * @since 3.50.0 * * @param {Phaser.GameObjects.Mesh} mesh - The Mesh that requested this pipeline. * * @return {this} This WebGLPipeline instance. */ onBind: function (mesh) { var program = this.program; var renderer = this.renderer; var camera = mesh.camera; var light = mesh.light; renderer.setMatrix4(program, 'uViewProjectionMatrix', false, camera.viewProjectionMatrix.val); renderer.setFloat3(program, 'uLightPosition', light.x, light.y, light.z); renderer.setFloat3(program, 'uLightAmbient', light.ambient.x, light.ambient.y, light.ambient.z); renderer.setFloat3(program, 'uLightDiffuse', light.diffuse.x, light.diffuse.y, light.diffuse.z); renderer.setFloat3(program, 'uLightSpecular', light.specular.x, light.specular.y, light.specular.z); renderer.setFloat3(program, 'uCameraPosition', camera.x, camera.y, camera.z); }, drawModel: function (mesh, model) { var program = this.program; var renderer = this.renderer; renderer.setMatrix4(program, 'uModelMatrix', false, model.transformMatrix.val); renderer.setMatrix4(program, 'uNormalMatrix', false, model.normalMatrix.val); renderer.setFloat3(program, 'uMaterialAmbient', model.ambient.x, model.ambient.y, model.ambient.z); renderer.setFloat3(program, 'uMaterialDiffuse', model.diffuse.x, model.diffuse.y, model.diffuse.z); renderer.setFloat3(program, 'uMaterialSpecular', model.specular.x, model.specular.y, model.specular.z); renderer.setFloat1(program, 'uMaterialShine', model.shine); renderer.setTextureZero(model.frame.glTexture); renderer.setInt1(program, 'uTexture', 0); // All the uniforms are finally bound, so now lets draw our faces! var vertexViewF32 = this.vertexViewF32; var vertices = model.vertices; for (var i = 0; i < vertices.length; i++) { if (this.shouldFlush(1)) { this.flush(); } var vertexOffset = (this.vertexCount * this.vertexComponentCount) - 1; var vert = vertices[i]; vertexViewF32[++vertexOffset] = vert.x; vertexViewF32[++vertexOffset] = vert.y; vertexViewF32[++vertexOffset] = vert.z; vertexViewF32[++vertexOffset] = vert.nx; vertexViewF32[++vertexOffset] = vert.ny; vertexViewF32[++vertexOffset] = vert.nz; vertexViewF32[++vertexOffset] = vert.u; vertexViewF32[++vertexOffset] = vert.v; this.vertexCount++; } this.flush(); } }); module.exports = MeshPipeline; // Copyright (c) Microsoft. All rights reserved. import { HttpClient } from './httpClient'; import { toReadValueModel } from './models'; import Config from 'app.config'; const ENDPOINT_TWINS = Config.serviceUrls.twins; /** * Contains methods for calling the device simulation microservice */ export class TwinService { static browseNode(endpointId, nodeId) { const queryString = nodeId ? `?nodeId=${encodeURIComponent(nodeId)}` : ''; return HttpClient.get(`${ENDPOINT_TWINS}/v2/browse/${endpointId}${queryString}`, undefined) .map(({ node, references }) => ({ node, references })); } static readNodeValue(endpointId, nodeId) { const queryString = nodeId ? `?nodeId=${encodeURIComponent(nodeId)}` : ''; return HttpClient.get(`${ENDPOINT_TWINS}/v2/read/${endpointId}${queryString}`, undefined) .map(toReadValueModel); } static writeNodeValue(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/write/${endpointId}`, payload); } static callNodeMethodMetadata(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/call/${endpointId}/metadata`, payload); } static callNodeMethod(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/call/${endpointId}`, payload); } static publishNodeValues(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/publish/${endpointId}/start`, payload); } static unPublishNodeValues(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/publish/${endpointId}/stop`, payload); } static getPublishedNodes(endpointId, payload) { return HttpClient.post(`${ENDPOINT_TWINS}/v2/publish/${endpointId}`, payload); } } index.js 'use strict'; var path = require('path'); var fs = require('fs'); function mkdirP(p, options, callback, made) { if (typeof options === 'function') { callback = options; options = {}; } else if (!options || typeof options !== 'object') { options = { mode: options }; } var mode = options.mode; var fs_ = options.fs || fs; if (mode === undefined) { mode = 0x1ff & ~process.umask(); } if (!made) { made = null; } if (!callback) { callback = function () {}; } p = path.resolve(p); fs_.mkdir(p, mode, function (error) { if (!error) { made = made || p; return callback(null, made); } if (error.code === 'ENOENT') { mkdirP(path.dirname(p), options, function (error, made) { if (error) { callback(error, made); } else { mkdirP(p, options, callback, made); } }); return; } // In the case of any other error, just see if there's a dir // there already. If so, then hooray! If not, then something // is borked. fs_.stat(p, function (er2, stat) { // if the stat fails, then that's super weird. // let the original error be the failure reason. if (er2 || !stat.isDirectory()) { callback(error, made); } else { callback(null, made); } }); }); } module.exports = mkdirP; web/js/admin/socketTransmit.js var socket; const callbacks = {}; export function connectToSocket(href){ var url = href; var arr = url.split("/"); var result = arr[0] + "//" + arr[2]; // eslint-disable-next-line no-undef socket = io(result + "/"); // On connection socket.on('connect', () => callbacks.onConnected(socket.id)); // On loss of connection socket.on('disconnect', () => callbacks.onDisconnected(socket.id)); socket.on("initFinished", (data) => callbacks.onInitFinished(data)); socket.on("serverQueueFinished", (data) => callbacks.onServerQueueFinished(data)); socket.on("serverQueueStatus", (data) => callbacks.onServerQueueStatus(data)); socket.on("serverQueueVideos", (data) => callbacks.onServerQueueVideos(data)); socket.on("serverClients", (data) => callbacks.onServerClients(data)); socket.on("serverCurrentVideo", (data) => callbacks.onServerCurrentVideo(data)); socket.on("serverNewVideo", (data) => callbacks.onServerNewVideo(data)); } export function disconnectFromSocket() { socket.disconnect(); } export function sendEvent(eventName, data){ if (!data){ socket.binary(false).emit(eventName); } else { socket.binary(false).emit(eventName, data); } } export function sendEventWithCallback(eventName, data, callback){ socket.binary(false).emit(eventName, data, callback); } export function onConnected(callback) { callbacks.onConnected = callback; } export function onDisonnected(callback) { callbacks.onDisconnected = callback; } export function onInitFinished(callback) { callbacks.onInitFinished = callback; } export function onServerQueueFinished(callback) { callbacks.onServerQueueFinished = callback; } export function onServerQueueStatus(callback) { callbacks.onServerQueueStatus = callback; } export function onServerQueueVideos(callback) { callbacks.onServerQueueVideos = callback; } export function onServerClients(callback) { callbacks.onServerClients = callback; } export function onServerCurrentVideo(callback) { callbacks.onServerCurrentVideo = callback; } export function onServerNewVideo(callback) { callbacks.onServerNewVideo = callback; }module.exports.customError=(errorCode,status)=> { let tempError=new Error(); tempError.customCode=errorCode; tempError.status=status; return tempError; }import isNumber from '../../src/utils/isNumber'; describe('utils isNumber operator', () => { test('should return true for number argument', () => { expect(isNumber(3)).toBeTruthy(); }); test('should return true for float argument', () => { expect(isNumber(3.6)).toBeTruthy(); }); test('should return false for string argument', () => { expect(isNumber('not a number')).toBeFalsy(); }); test('should return false for true argument', () => { expect(isNumber(true)).toBeFalsy(); }); test('should return false for false argument', () => { expect(isNumber(false)).toBeFalsy(); }); test('should return false for object argument', () => { expect(isNumber({ foo: 'baz' })).toBeFalsy(); }); }); src/App.js import { Component } from 'react'; import { connect } from 'react-redux'; import { compose } from 'redux'; import './App.css'; import ModalContainer from './components/ModalContainer/ModalContainer'; import Preloader from './components/Preloader/Preloader'; import SelectedCardContainer from './components/SelectedCard/SelectedCardContainer'; import Table from './components/Table/Table'; import TotalPowerContainer from './components/TotalPower/TotalPowerContainer'; import Decks from './components/UserDeck/Decks'; import UserHand from './components/UserHand/UserHand'; import { deployGame } from './redux/appReducer'; import { hideModal } from './redux/modalReducer'; class App extends Component { componentDidMount() { this.props.deployGame(); } render() { if (!this.props.deploymentSuccess) { return } return (
    STTMã Hàng HóaMã Nội BộTên Hàng HóaSố LượngNhân ViênKhu VựcKhoThời Gian
    ' + userData.hanghoa.MaHH + '' + userData.hanghoa.MaGoiNho + '' + userData.hanghoa.TenHH + '' + userData.SoLuong + '' + userData.user.Ten + '' + userData.TenKeHang + '' + userData.kho.TenKho + '' + userData.NgayKiemKe + '
    Total:'+total+'
    ) } } const mapStateToProps = (state) => ({ deploymentSuccess: state.app.deploymentSuccess }); export default compose( connect(mapStateToProps, { deployGame, hideModal }) )(App); golota60/ui import { render, fireEvent } from '@testing-library/react'; import Anchor from '../src/Anchor'; describe('Anchor', () => { it('renders an anchor tag', () => { const { container } = render(); container.firstChild.tagName.should.equal('A'); }); it('forwards provided href', () => { const { container } = render(); container.firstChild.getAttribute('href').should.equal('http://google.com'); }); // xit('ensures that an href is provided', () => { // mount() // .getDOMNode() // .hasAttribute('href').should.be.true; // }); it('forwards onClick handler', () => { const handleClick = sinon.spy(); const { container } = render(); fireEvent.click(container.firstChild); handleClick.should.have.been.calledOnce; }); it('provides onClick handler as onKeyDown handler for "space"', () => { const handleClick = sinon.spy(); const { container } = render(); fireEvent.keyDown(container.firstChild, { key: ' ' }); handleClick.should.have.been.calledOnce; }); it('should call onKeyDown handler when href is non-trivial', () => { const onKeyDownSpy = sinon.spy(); const { container } = render( , ); fireEvent.keyDown(container.firstChild, { key: ' ' }); onKeyDownSpy.should.have.been.calledOnce; }); it('prevents default when no href is provided', () => { const handleClick = sinon.spy(); const { container, rerender } = render(); fireEvent.click(container.firstChild); rerender(); fireEvent.click(container.firstChild); expect(handleClick).to.have.been.calledTwice; expect(handleClick.getCall(0).args[0].isDefaultPrevented()).to.be.true; expect(handleClick.getCall(1).args[0].isDefaultPrevented()).to.be.true; }); it('does not prevent default when href is provided', () => { const handleClick = sinon.spy(); fireEvent.click( render().container.firstChild, ); expect(handleClick).to.have.been.calledOnce; expect(handleClick.getCall(0).args[0].isDefaultPrevented()).to.be.false; }); it('forwards provided role', () => { render().getByRole('test'); }); it('forwards provided role with href', () => { render().getByRole('test'); }); it('set role=button with no provided href', () => { const wrapper = render(); wrapper.getByRole('button'); wrapper.rerender(); wrapper.getByRole('button'); }); it('sets no role with provided href', () => { expect( render( , ).container.firstChild.hasAttribute('role'), ).to.be.false; }); }); /* eslint-disable max-len */ import React from 'react'; import SvgIcon from '@material-ui/core/SvgIcon'; import IconComposer from '../IconComposer'; const Print = props => { return ( ); }; Print.defaultProps = { viewBox: '0 0 24 24', }; export default IconComposer(Print); 1-10 exports.render = function (req, res) { if (req.session.lastVisit) { console.log("last visit:", req.session.lastVisit); } req.session.lastVisit = new Date(); res.render('index', { title: 'Welcome to CyMol' }); }; exports.viewerIo = function (io, socket) { io.emit('loadPDB', { }); };execucao/node_modules/static/index.js1-10 var handlebars = require('handlebars'), async = require('async'), cheerio = require('cheerio'), marked = require('marked'), path = require('path'), fs = require('fs'), _ = require('underscore'), highlight = require('highlight.js'); var config = { addIdsToHeadings: true, gfm: true, //github flavored markdown highlight: function(code, lang) { return highlight.highlight('javascript', code).value; } }; var jqueryPath = './lib/jquery.js', asyncTolkens = {}, markdownCallbacks = []; var transforms = {}; function addTransform(name, callback) { transforms[name] = callback; } addTransform('html', function(buffer, complete, context, data) { return complete(buffer.toString()); }); addTransform('md', function(buffer, complete, context, data) { var html = marked(buffer.toString(), { gfm: config.gfm, highlight: config.highlight }); async.series(_.map(markdownCallbacks, function(callback) { return function(next) { callback(html, function(modifiedHTML) { html = modifiedHTML; next(); }); } }), function() { complete(html); }); }); addTransform('hbs', function(buffer, complete, context, data) { var output = handlebars.compile(buffer.toString(), { data: true })(context, { data: data }); var filteredAsyncTolkens = {}; _.each(asyncTolkens, function(tolkenData, tolken) { if (data.file === tolkenData.file) { filteredAsyncTolkens[tolken] = tolkenData; } }); if (!_.keys(filteredAsyncTolkens).length) { complete(output); } else { async.series(_.map(filteredAsyncTolkens, function(tolkenData, tolken) { return function(next) { var args = tolkenData.args; args.push(function(callbackOutput) { output = output.replace(tolken, callbackOutput.toString()); next(); }); tolkenData.callback.apply(tolkenData.callback, args); }; }), function() { complete(output); }); } }); function $(html, callback) { callback(cheerio.load(html)); } function modifyDocumentFragment(html, callback, next) { $(html, function($) { callback($); next($.html()); }); } function removeOuterBodyTag(html) { return html.replace(/^\s*\/, '').replace(/\<\/body\>\s*$/, ''); } handlebars.registerAsyncHelper = function(name, callback) { handlebars.registerHelper(name, function() { var tolken = String(new Date().getTime() + Math.random()); var args = _.toArray(arguments), data = args[args.length - 1].data; asyncTolkens[tolken] = { file: data.file, args: args, callback: callback }; return tolken; }); }; handlebars.registerHelper('require', function(file, options) { var filePath = path.join(path.dirname(options.data.file), file); require(filePath)(module.exports); return ''; }); handlebars.registerAsyncHelper('include', function(file, options, callback) { var filePath = path.join(path.dirname(options.data.file), file); transform(filePath, function(fileData) { var selector = options.hash.select; if (selector) { $(fileData.toString(), function($) { var generatedHTML = ''; $(selector).each(function() { // make more like a regular dom object this.attributes = this[0].attribs; this.id = this[0].attribs.id; this.tagName = this[0].name; this.innerHTML = this.html(); generatedHTML += options.fn(this); }); callback(generatedHTML); }); } else { callback(fileData.toString()); } }, options.hash, options.data); }); function transform(source, callback, options) { fs.readFile(source, function(err, data) { if (err) { console.trace(); throw err; } var extensions = source.split('/').pop().split('.'); var callbacks = _.filter(extensions, function(extension) { return extension in transforms; }).map(function(extension) { return function(next) { transforms[extension](data, next, options || {}, { file: source }); }; }); async.series(callbacks, callback); }); } function onMarkdown(callback) { markdownCallbacks.push(callback); } onMarkdown(function(html, next) { if (config.addIdsToHeadings) { modifyDocumentFragment(html, function($) { if (config.addIdsToHeadings) { addIdsToHeadings($); } }, next); } else { next(html); } }); function addIdsToHeadings($) { $('h1,h2,h3,h4,h5,h6').each(function() { var text = $(this).html().split('<').shift(); var id = text.replace(/(^\s+|\s+$)/g, '').replace(/[\s]+/g, '-').replace(/([a-z])([A-Z])/g, function() { return arguments[1] + '-' + arguments[2].toLowerCase(); }).toLowerCase(); if (id.match(/^\s+$/) || !id) { return; } $(this).attr('id', id); }); } module.exports = { config: config, transform: transform, handlebars: handlebars, $: $, modifyDocumentFragment: modifyDocumentFragment, onMarkdown: onMarkdown, addTransform: addTransform };Toufiklamghari1/IT_departement export function getRowNumber(row){ var id1 = $(row).attr('id').match(/(\d+)/); var id=""; for(var i=0;itest/index.test.js0 const chai = require('chai'); const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const expect = chai.expect; chai.use(sinonChai); const SUT = require('../index'); describe('Test concurrency limiter', () => { const listOfValues = [ 'a', 'b', 'c']; let resolveValues = listOfValues.map(v => `resolved-${v}`); let rejectReasons = listOfValues.map(v => `error-${v}`); let promises; let asynFnStub; beforeEach(() => { // promiseWrappers = []; resolveValues = listOfValues.map((value) => `result-of-${value}`); asynFnStub = sinon.stub(); promises = {}; asynFnStub.callsFake((input) => { const thenCallbacks = []; const catchCallbacks = []; const fakePromise = { then(callback) { thenCallbacks.push(callback); return this; }, catch(callback) { catchCallbacks.push(callback); return this; }, resolve() { const index = listOfValues.indexOf(input); thenCallbacks[0](resolveValues[index]); thenCallbacks[1](); }, reject() { const index = listOfValues.indexOf(input); catchCallbacks[0](rejectReasons[index]); thenCallbacks[1](); } }; promises[input] = fakePromise; return fakePromise; }) }); describe('WHEN function called with default options', () => { describe('AND WHEN all the asyn function calls are resolved', () => { it('should only call the function third time if any previous finished and should eventually resolve with a Promise.allSettled compatible result', async () => { // WHEN const result = SUT(listOfValues, asynFnStub, 2); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[0]); expect(asynFnStub).to.have.been.calledWith(listOfValues[1]); expect(asynFnStub.callCount).to.equal(2); // WHEN promises[listOfValues[0]].resolve(); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[2]); expect(asynFnStub.callCount).to.equal(3); // WHEN promises[listOfValues[2]].resolve(); // THEN expect(asynFnStub.callCount).to.equal(3); // WHEN promises[listOfValues[1]].resolve(); // THEN const endResult = await result; expect(endResult.length).to.equal(3); expect(endResult).to.have.same.deep.members(listOfValues.map((v, index) => ({ status: 'fulfilled', value: resolveValues[index] }))); }); }); describe('AND WHEN the first async call is rejected', () => { it('should only call the function third time if any previous finished', async () => { // WHEN const result = SUT(listOfValues, asynFnStub, 2); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[0]); expect(asynFnStub).to.have.been.calledWith(listOfValues[1]); expect(asynFnStub.callCount).to.equal(2); // WHEN promises[listOfValues[0]].reject(); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[2]); expect(asynFnStub.callCount).to.equal(3); // WHEN promises[listOfValues[2]].resolve(); // THEN expect(asynFnStub.callCount).to.equal(3); // WHEN promises[listOfValues[1]].resolve(); // THEN const endResult = await result; expect(endResult.length).to.equal(3); expect(endResult).to.have.same.deep.members([ { status: 'rejected', reason: rejectReasons[0] }, { status: 'fulfilled', value: resolveValues[1] }, { status: 'fulfilled', value: resolveValues[2] } ]); }); }); }); describe('WHEN function called with failFast options', () => { describe('AND WHEN all promises are resolved', () => { it('should eventually resolve with a Promise.all compatible result', async () => { // WHEN const result = SUT(listOfValues, asynFnStub, 2, { failFast: true }); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[0]); expect(asynFnStub).to.have.been.calledWith(listOfValues[1]); expect(asynFnStub.callCount).to.equal(2); // WHEN promises[listOfValues[0]].resolve(); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[2]); expect(asynFnStub.callCount).to.equal(3); // WHEN promises[listOfValues[1]].resolve(); promises[listOfValues[2]].resolve(); const endResult = await result; expect(endResult).to.have.all.members(resolveValues); }); }); describe('AND WHEN one of the promises is rejected', () => { it('should eventually reject with the reason of the first failing promise', async () => { // WHEN const result = SUT(listOfValues, asynFnStub, 2, { failFast: true }); // THEN expect(asynFnStub).to.have.been.calledWith(listOfValues[0]); expect(asynFnStub).to.have.been.calledWith(listOfValues[1]); expect(asynFnStub.callCount).to.equal(2); // WHEN promises[listOfValues[0]].reject(); // WHEN promises[listOfValues[1]].resolve(); try { await result; throw 'The result Promise should not be resolved at all.'; } catch (error) { // THEN expect(asynFnStub).not.to.have.been.calledWith(listOfValues[2]); expect(asynFnStub.callCount).to.equal(2); expect(error).to.equal(rejectReasons[0]); } }); }); }); describe('WHEN an onProgress callback is given', () => { describe('AND WHEN all promises are resolved', () => { it('should call the onProgress callback for all the elements', async () => { // GIVEN const onProg = sinon.stub(); // WHEN const result = SUT(listOfValues, asynFnStub, 2, { failFast: true, onProgress: onProg }); promises[listOfValues[1]].resolve(); // THEN expect(onProg).to.have.been.calledWith({ percentage: 33.33, done: 1, total: 3, finishedItem: listOfValues[1] }); // WHEN promises[listOfValues[0]].resolve(); // THEN expect(onProg).to.have.been.calledWith({ percentage: 66.67, done: 2, total: 3, finishedItem: listOfValues[0] }); // WHEN promises[listOfValues[2]].resolve(); // THEN expect(onProg).to.have.been.calledWith({ percentage: 100, done: 3, total: 3, finishedItem: listOfValues[2] }); }); }); describe('AND WHEN one of the promises is rejected', () => { it('should call the onProgress for all the done promises which closed before fast fail', async () => { // GIVEN const onProg = sinon.stub(); // WHEN const result = SUT(listOfValues, asynFnStub, 2, { failFast: true, onProgress: onProg }); promises[listOfValues[1]].resolve(); // THEN expect(onProg).to.have.been.calledWith({ percentage: 33.33, done: 1, total: 3, finishedItem: listOfValues[1] }); // WHEN promises[listOfValues[0]].reject(); promises[listOfValues[2]].resolve(); try { await result; throw 'It should be rejected'; } catch (error) { expect(asynFnStub).to.have.been.calledWith(listOfValues[2]); expect(asynFnStub.callCount).to.equal(3); expect(onProg.callCount).to.equal(1); } }); }); }); });logimw/cosmo-group.eu import React from "react"; import styles from "../../css/values.module.css"; import values from "../../constants/values"; // import { graphql } from "gatsby"; const Values = () => { return (
    {values.map((item, index) => { return (
    {`Icon

    {item.title}

    {item.text}

    ); })}
    ); }; export default Values; resources/js/components/students/Update.js import React, {Component} from "react"; import {Link} from 'react-router-dom'; import axios from "axios"; import Swal from "sweetalert2"; class StudentUpdate extends Component { state = { id:this.props.match.params.id, name:"", email:"", course:"", phone:"", errorList: {}, } async componentDidMount() { const {data} = await axios.get(`/api/students/edit/${this.state.id}`) if(data.status === 200) { let {student} = data; this.setState({ name: student.name, email: student.email, course: student.course, phone: student.phone, }) } else if (data.status === 404) { this.props.history.push('/students'); await Swal.fire({ title: 'Oops!', text: data.message, icon: 'error', showConfirmButton: false, timer: 3000 }) } } handleInput = (e) => { this.setState({ [e.target.name]: e.target.value }); } updateStudent = async (e) => { e.preventDefault(); document.getElementById('btn-update').disabled = true; document.getElementById('btn-update').innerText = "Updating..."; const {data} = await axios.put(`/api/students/update/${this.state.id}`, this.state); if (data.status) { this.props.history.push('/students'); await Swal.fire({ title: 'Updated!', text: data.message, icon: 'success', showConfirmButton: false, timer: 1500 }) } else if(data.hasOwnProperty('inputError')) { this.setState({errorList: data.inputError}) document.getElementById('btn-update').innerText = "Update"; document.getElementById('btn-update').disabled = false; } else { await Swal.fire({ title: 'Error!', text: data.message || "Something went wrong", icon: 'error', confirmButtonText: 'Ok' }) document.getElementById('btn-update').innerText = "Update"; document.getElementById('btn-update').disabled = false; } } render() { const {state} = this; return (

    Update Student

    All Student
    {state.errorList.name}
    {state.errorList.email}
    {state.errorList.course}
    {state.errorList.phone}
    ) } } export default StudentUpdate; import {validateEmail as email, validateEmailFormat as emailFormat} from './rules/email' import {validateEntered as entered} from './rules/entered' import {validateNumber as number, validateNumberRange as numberRange} from './rules/number' import {validateTel as tel} from './rules/tel' import {validateUrl as url} from './rules/url' import {validateZipcode as zipcode} from './rules/zipcode' export { email, emailFormat, entered, number, numberRange, tel, url, zipcode, } 0 module.exports = { '/notification': { get: { tags: ['Notification'], summary: 'Get All Notification', produces: ['application/json'], security: [ { auth_token: [], }, ], parameters: [ { $ref: '#/components/parameters/page', }, { $ref: '#/components/parameters/pageSize', }, { $ref: '#/components/parameters/filtered', }, { $ref: '#/components/parameters/sorted', }, ], responses: { 200: { description: 'Get All Notification', }, }, }, post: { tags: ['Notification'], summary: 'Create New Notification', security: [ { auth_token: [], }, ], requestBody: { required: true, content: { 'application/x-www-form-urlencoded': { schema: { type: 'object', properties: { UserId: { type: 'string', }, title: { type: 'string', }, text: { type: 'string', }, html: { type: 'string', }, type: { type: 'string', enum: ['all', 'user'], }, isRead: { type: 'boolean', }, sendAt: { type: 'string', }, isSend: { type: 'boolean', }, }, required: ['title', 'text', 'html', 'type'], }, }, }, }, responses: { 201: { description: 'Create New Notification', }, }, }, }, '/notification/multiple/soft-delete': { post: { tags: ['Notification'], summary: 'Multiple Soft Delete Notification', security: [ { auth_token: [], }, ], requestBody: { required: true, content: { 'application/x-www-form-urlencoded': { schema: { type: 'object', properties: { ids: { type: 'string', description: '["id_1", "id_2"]', }, }, required: ['ids'], }, }, }, }, responses: { 200: { description: 'Multiple Soft Delete Notification', }, }, }, }, '/notification/multiple/restore': { post: { tags: ['Notification'], summary: 'Multiple Restore Notification', security: [ { auth_token: [], }, ], requestBody: { required: true, content: { 'application/x-www-form-urlencoded': { schema: { type: 'object', properties: { ids: { type: 'string', description: '["id_1", "id_2"]', }, }, required: ['ids'], }, }, }, }, responses: { 200: { description: 'Multiple Restore Notification', }, }, }, }, '/notification/multiple/force-delete': { post: { tags: ['Notification'], summary: 'Multiple Force Delete Notification ( Forever )', security: [ { auth_token: [], }, ], requestBody: { required: true, content: { 'application/x-www-form-urlencoded': { schema: { type: 'object', properties: { ids: { type: 'string', description: '["id_1", "id_2"]', }, }, required: ['ids'], }, }, }, }, responses: { 200: { description: 'Multiple Force Delete Notification ( Forever )', }, }, }, }, '/notification/{id}': { get: { tags: ['Notification'], summary: 'Get Notification By Id', produces: ['application/json'], security: [ { auth_token: [], }, ], parameters: [ { in: 'path', name: 'id', required: true, schema: { type: 'string', }, description: 'Notification Id', }, ], responses: { 200: { description: 'Get Notification By Id', }, }, }, put: { tags: ['Notification'], summary: 'Update Data Notification', security: [ { auth_token: [], }, ], parameters: [ { in: 'path', name: 'id', required: true, schema: { type: 'string', }, description: 'Notification Id', }, ], requestBody: { required: true, content: { 'application/x-www-form-urlencoded': { schema: { type: 'object', properties: { UserId: { type: 'string', }, title: { type: 'string', }, text: { type: 'string', }, html: { type: 'string', }, type: { type: 'string', enum: ['all', 'user'], }, isRead: { type: 'boolean', }, sendAt: { type: 'string', }, isSend: { type: 'boolean', }, }, required: ['title', 'text', 'html', 'type'], }, }, }, }, responses: { 200: { description: 'Update Data Notification', }, }, }, }, '/notification/soft-delete/{id}': { delete: { tags: ['Notification'], summary: 'Soft Delete Notification By Id', security: [ { auth_token: [], }, ], produces: ['application/json'], parameters: [ { in: 'path', name: 'id', required: true, schema: { type: 'string', }, description: 'Notification Id', }, ], responses: { 200: { description: 'Soft Delete Notification By Id', }, }, }, }, '/notification/restore/{id}': { put: { tags: ['Notification'], summary: 'Restore Notification By Id', security: [ { auth_token: [], }, ], produces: ['application/json'], parameters: [ { in: 'path', name: 'id', required: true, schema: { type: 'string', }, description: 'Notification Id', }, ], responses: { 200: { description: 'Restore Notification By Id', }, }, }, }, '/notification/force-delete/{id}': { delete: { tags: ['Notification'], summary: 'Force Delete Notification By Id ( Forever )', security: [ { auth_token: [], }, ], produces: ['application/json'], parameters: [ { in: 'path', name: 'id', required: true, schema: { type: 'string', }, description: 'Notification Id', }, ], responses: { 200: { description: 'Force Delete Notification By Id ( Forever )', }, }, }, }, } /** * Copyright Mind Powered Corporation 2020 * * https://mindpowered.dev/ */ const maglev = require('@mindpowered/maglev'); const electricalc = require('../lib/electricalc.js'); /** * A library for calculations related to electrical wiring and circuits */ class ElectriCalc { constructor() { let bus = maglev.maglev.MagLev.getInstance('default'); let lib = new electricalc.electricalc.ElectricalCalculator(bus); } /** * Convert from Phase Angle to Power Factor * @param {number} phaseAngle Phase Angle in degrees * @return {Promise} Power Factor Promise will resolve to type number. */ ConvertPhaseAngleToPowerFactor(phaseAngle) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [phaseAngle]; let ret = jsbus.call('ElectriCalc.ConvertPhaseAngleToPowerFactor', args); return ret; } /** * Convert from Power Factor to Phase Angle * @param {number} powerFactor Power Factor * @return {Promise} Phase Angle in degrees Promise will resolve to type number. */ ConvertPowerFactorToPhaseAngle(powerFactor) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [powerFactor]; let ret = jsbus.call('ElectriCalc.ConvertPowerFactorToPhaseAngle', args); return ret; } /** * Calcualte single phase power based on measured voltage and current * @param {number} voltage Measured voltage in Volts * @param {number} current Measured current in Amps * @return {Promise} Apparent Power in VA Promise will resolve to type number. */ CalculateSinglePhasePower(voltage, current) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [voltage, current]; let ret = jsbus.call('ElectriCalc.CalculateSinglePhasePower', args); return ret; } /** * Calcualte three phase power based on measured voltage and current * @param {number} voltage Measured voltage in Volts * @param {string} lineTo Which voltage was measured. Must be "line" or "netural" * @param {number} current Measured current in Amps * @return {Promise} Apparent Power in VA Promise will resolve to type number. */ CalculateThreePhasePower(voltage, lineTo, current) { let jsbus = maglev.maglev.MagLevJs.getInstance('default'); let args = [voltage, lineTo, current]; let ret = jsbus.call('ElectriCalc.CalculateThreePhasePower', args); return ret; } } module.exports = ElectriCalc; src/routers/config.js /* eslint-disable import/extensions */ import { lazy } from 'react'; import BasicLayout from '@/layouts/BasicLayout'; import BlankLayout from '@/layouts/BlankLayout'; const config = [ { path: '/', component: BlankLayout, // 空白页布局 childRoutes: [ // 子菜单路由 { path: '/login', // 路由路径 name: '登录页', // 菜单名称 (不设置,则不展示在菜单栏中) icon: 'setting', // 菜单图标 component: lazy(() => import('@/pages/Login')), // 懒加载 路由组件 }, { path: '/', // exact: true, component: BasicLayout, // 基本布局 childRoutes: [ { path: '/map', name: '污染分布', icon: 'home', component: lazy(() => import('@/pages/Map')), }, { path: '/welcome', name: '欢迎页', icon: 'smile', component: lazy(() => import('@/pages/Welcome')), }, { path: '/home', name: 'home主页', icon: 'home', component: lazy(() => import('@/pages/Home')), }, { path: '/formDemo', name: '表单演示', icon: 'form', component: lazy(() => import('@/pages/FormDemo')), }, { path: '/system', name: '系统管理', icon: 'setting', childRoutes: [ { path: '/system/groovySet', name: 'Groovy脚本管理', component: lazy(() => import('@/pages/System/GroovySet')), }, { path: '/system/user', name: '用户配置', icon: 'user', component: lazy(() => import('@/pages/System/User')), }, { path: '/system/star', name: '个人中心', icon: 'star', component: lazy(() => import('@/pages/System/Star')), }, ], }, { path: '/exception', name: '异常页', // exact: true, icon: 'warning', childRoutes: [ { path: '/exception/403', name: '403', icon: 'frown', component: lazy(() => import('@/pages/Exception/403')), }, { path: '/exception/404', name: '404', exact: true, icon: 'frown', component: lazy(() => import('@/pages/Exception/404')), }, { path: '/exception/500', name: '500', icon: 'frown', component: lazy(() => import('@/pages/Exception/500')), }, ], }, { path: '/', exact: true, redirect: '/welcome' }, { path: '*', exact: true, redirect: '/exception/404' }, ], }, ], }, ]; export default config; 10-100 import React from 'react' import { mount } from 'enzyme' import { BrowserRouter as Router } from 'react-router-dom' import Button from '..' describe(') expect(wrapper.contains('Button')).toEqual(true) }) it('sets `disabled` on `button`', () => { const wrapper = mount() expect(wrapper.find('button').prop('disabled')).toBe(true) }) it('removes all props if `disabled`', () => { const wrapper = mount( ) expect(wrapper.find('button').prop('onClick')).toBe(undefined) }) it('renders as `button` without props', () => { const wrapper = mount() expect(wrapper).toMatchSnapshot() }) it('renders as `Link` with `to` prop', () => { const wrapper = mount( ) expect(wrapper).toMatchSnapshot() }) it('renders as `button` with `onClick` prop', () => { const wrapper = mount() expect(wrapper).toMatchSnapshot() }) it('renders as `a` with `href` prop', () => { const wrapper = mount() expect(wrapper).toMatchSnapshot() }) it('simulates click events', () => { const onButtonClick = jest.fn() const wrapper = mount() wrapper.simulate('click') expect(onButtonClick).toHaveBeenCalled() }) }) import React from "react" import './footer.css' import { Container } from "react-bootstrap" const Footer = () => { return (

    Quantial technology solutions

    Innovative, Professional IT
    Solutions for every business

    © {new Date().getFullYear()}, Quantial Technology solutions. All Rights Reserved.
    Designed and developed by
    ) } export default Footer function readSettings(file){ var xmlObj; if(window.XMLHttpRequest){ xmlObj = new XMLHttpRequest(); } else if(window.ActiveXObject){ xmlObj = new ActiveXObject("Microsoft.XMLHTTP"); } else { return; } xmlObj.onreadystatechange = function(){ if(xmlObj.readyState == 4){ const arraySettings = xmlObj.responseXML.getElementsByTagName('root'); document.querySelector('title').innerHTML = arraySettings[0].getElementsByTagName("name")[0].innerHTML; document.querySelector('#logo img').src = '../img/' + arraySettings[0].getElementsByTagName("logo")[0].innerHTML; } } xmlObj.open ('GET', file, true); xmlObj.send (); } readSettings('xml/settings.xml'); function getCookie(name) { let matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; } const numOrder = getCookie('num'); const dateOrder = getCookie('date'); function ajaxRead(file){ var xmlObj; if(window.XMLHttpRequest){ xmlObj = new XMLHttpRequest(); } else if(window.ActiveXObject){ xmlObj = new ActiveXObject("Microsoft.XMLHTTP"); } else { return; } xmlObj.onreadystatechange = function(){ if(xmlObj.readyState == 4){ const statusOrder = xmlObj.responseXML.getElementsByTagName('status')[0].firstChild.data; var messageOrder = document.getElementById('messageOrder'); messageOrder.innerHTML = 'Order №' + numOrder + '

    ' + statusOrder + '

    '; if(statusOrder == 'Awaiting verification') document.getElementById('statusImg').className = 'check'; if(statusOrder == 'Cooking') document.getElementById('statusImg').className = 'cook'; if(statusOrder == 'Sent by courier') document.getElementById('statusImg').className = 'check'; if(statusOrder == 'Delivered') document.getElementById('statusImg').className = 'check'; if(statusOrder == 'Cancelled') document.getElementById('statusImg').className = 'cancel'; } } xmlObj.open ('GET', file, true); xmlObj.send (); } const fileRead = 'xml/this/' + dateOrder + 'order' + numOrder + '.xml'; setInterval(function(){ajaxRead(fileRead)}, 5000); setInterval(function(){document.getElementById('messageOrder').classList.remove('preloader');}, 5000); mihaidma/seneca-store-query 'use strict' var _ = require('lodash') var actionRole = 'sql' var name = 'store-query' module.exports = function queryBuilder (options) { var seneca = this function specificTypes (storeName) { var sTypes = { escape: '"', prepared: '$' } sTypes.name = storeName if (storeName === 'mysql-store') { sTypes.escape = '`' sTypes.prepared = '?' } return sTypes } seneca.ready(function () { var QueryBuilder = require('./lib/query-builder')(seneca, options) seneca.add({role: actionRole, hook: 'load'}, function (args, done) { var qent = args.qent var sTypes = specificTypes(args.target) var q = _.clone(args.q) q.limit$ = 1 QueryBuilder.selectstm(qent, q, sTypes, function (err, query) { return done(err, {query: query}) }) }) seneca.add({role: actionRole, hook: 'list'}, function (args, done) { var qent = args.qent var q = args.q var sTypes = specificTypes(args.target) QueryBuilder.buildSelectStatement(qent, q, sTypes, function (err, query) { return done(err, {query: query}) }) }) }) return { name: name } } describe('Domain page', () => { it('Check that the page is rendered', () => { cy.visit('/domains'); cy.findByText('Your Domains'); }); }); import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; import { bem } from '../../utils'; import styles from './TextArea.scss'; import { CONTEXTS, SIZES } from '../../constants'; const { block } = bem('TextArea', styles); export const TextArea = forwardRef((props, ref) => { const { context, disabled, isBlock, size, ...rest } = props; return
    可以按enter发送
    ); } send(){ var value = $(this.refs.text).val(); socket.emit("message",value); } press(e){ if(e.keyCode == 13){ this.send(); return false; } } } export default chat;import { createContext, useContext, useState, useEffect } from 'react'; import { createClient } from '@supabase/supabase-js'; import { api } from '../api/api'; export const ChatContext = createContext({}); const superbaseClient = createClient( process.env.NEXT_PUBLIC_API_URL, process.env.NEXT_PUBLIC_API_KEY ); function realTimeMessages(addMessage) { return superbaseClient .from('messages') .on('INSERT', (response) => { addMessage(response.new); }) .subscribe(); } export function ChatProvider(props) { const [user, setUser] = useState(''); const [message, setMessage] = useState(''); const [listMessages, setListMessages] = useState([]); const [info, setInfo] = useState([]); const handleChange = async (user) => { setUser(user); try { const response = await api.get(`/users/${user}`); const { data } = response; setInfo({ name: data.name, username: data.login, followers: data.followers, following: data.following, }); console.log(info); } catch (error) { // console.log(error); } }; useEffect(() => { superbaseClient .from('messages') .select('*') .order('id', { ascending: false }) .then((response) => { const { data } = response; setListMessages(data); }); const subscribe = realTimeMessages((message) => { setListMessages((newList) => { return [message, ...newList]; }); }); return () => { subscribe.unsubscribe(); }; }, []); function handleMessage(message) { if (message.trim()) { const newMessage = { text: message, author: `${user}`, }; superbaseClient .from('messages') .insert([newMessage]) .then((response) => { // const { data } = response; // setListMessages([data[0], ...listMessages]); }); setMessage(''); } } function handleRemoveMessage(id) { const filteredMessage = listMessages.filter((message) => message.id !== id); setListMessages(filteredMessage); } return ( {props.children} ); } export function useProps() { const context = useContext(ChatContext); return context; } /** * Criar sessão amigos do github */ src/js/components/TestButton.js import React from "react"; import { connect } from "react-redux"; import { showText } from "../actions/showText"; export class TestButton extends React.Component { showText() { this.props.showText("This text comes from Redux"); } render() { return ( ); } } const mapStateToProps = (state) => ({ testText: state.test.text }); export default connect(mapStateToProps, { showText })(TestButton);define('static/index/index', function(require, exports, module) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _commonVue = require('static/common/vue'); var _commonVue2 = _interopRequireDefault(_commonVue); var _componentsAjaxIndex = require('static/components/ajax/index'); var _componentsAjaxIndex2 = _interopRequireDefault(_componentsAjaxIndex); console.log(_componentsAjaxIndex2['default'], 9090909); new _commonVue2['default']({ delimiters: ['{%', '%}'], el: '#app', data: { token: pageConfig.token, url: "", file: "" }, created: function created() { alert(222); }, methods: { imgChange: function imgChange(event) { // console.log(event); // postfile{event.target.files[0]} this.file = event.target.files[0]; console.log(this.file); }, postfile: function postfile() { var file = this.file; var self = this; var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { self.url = e.target.result; }; console.log(file); var form = new FormData(); form.append('file', file); form.append("_token", self.token); console.log(form.get(file)); var oReq = new XMLHttpRequest(); oReq.open("POST", "/imageupload", true); oReq.onload = function (oEvent) { if (oReq.status == 200) { // oOutput.innerHTML = "Uploaded!" ; } else { // oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.
    "; } }; oReq.send(form); } }, components: {} }); }); module.exports = function(app, fs) { app.get('/', function(req, res) { res.render('main', { title: "sulgibread", body: '' }); }); app.get('/list', function(req, res) { fs.readFile(__dirname + "/../data/user.json", 'utf8', function(err, data){ var json = JSON.parse(data); res.json(json); // json 형식으로 떨어짐. }); }); app.get('/user/:username', function(req, res) { fs.readFile(__dirname + "/../data/user.json", 'utf8', function(err, data){ var users = JSON.parse(data); res.json(users[req.params.username]); // json 형식으로 떨어짐. }); }); app.post('/post', function(req, res) { if(postCheck(req.body)) { res.end('ok'); } else { res.end('ng'); } }); } function postCheck(data) { console.log(data); if(data["name"] && data["age"] && data["email"]) { return true; } else { return false; } } // res.render() 드로잉 // res.end() 단순 text 전달 // res.json() json 전달 // GET – 조회 // PUT – 생성 및 업데이트 // DELETE – 제거 // POST – 생성const maxSumRangeQuery = require("./../main/maxSumRangeQuery"); // Question // We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. // The ith request asks for the sum of nums[starti] + nums[starti + 1] + ... + nums[endi - 1] + nums[endi]. // Both starti and endi are 0-indexed. // Return the maximum total sum of all requests among all permutations of nums. // Since the answer may be too large, return it modulo 109 + 7. describe("任意の順列から得られる最大の合計数を返却する", () => { describe("maxSumRangeQuery(number[] nums, number[][] requests) を実行するとき", () => { test("nums = [1,2,3,4,5], requests = [[1,3],[0,1]] を入力して19が返却されること", () => { expect( maxSumRangeQuery( [1, 2, 3, 4, 5], [ [1, 3], [0, 1], ] ) ).toBe(19); }); test("nums = [1,2,3,4,5,6], requests = [[0,1]] を入力して11が返却されること", () => { expect(maxSumRangeQuery([1, 2, 3, 4, 5, 6], [[0, 1]])).toBe(11); }); test("nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]] を入力して47が返却されること", () => { expect( maxSumRangeQuery( [1, 2, 3, 4, 5, 10], [ [0, 2], [1, 3], [1, 1], ] ) ).toBe(47); }); }); }); src/utils/date.js import { parse, format, parseISO } from 'date-fns'; const date = { // Formats a date to YYYY/MM/DD formatToDDMMYYYY: (value) => { return format(parseISO(value), 'dd/MM/yyyy'); }, // Formats a date from DD/MM/YYYY to YYYY/MM/DD formatToYYYYMMDD: (date) => { return format(parse(date, 'dd/MM/yyyy', new Date()), 'yyyy/MM/dd'); }, }; export default date; express-gym/SchoolYardRecycling import React from "react"; import homeImage from "./assets/teacherTools.png"; import "../App.css"; import { Button, Container, Grid, Header, Image, Segment, } from "semantic-ui-react"; import { borderRadius } from "@mui/system"; const Home = () => (
    Five interesting facts about recycling!

    The United States annually recycles enough iron and steel scrap metals (known as ferrous scrap), by weight, to build more than 900 Golden Gate Bridges — a bridge stretching nearly 9,000 feet.

    More than 52 million tons of paper products were recycled in 2018. That’s roughly the same weight as almost 350,000 blue whales.

    Recycling one aluminum can saves enough energy to run a 55-inch HDTV to watch your favorite movie. If we recycled all of the aluminum cans in the U.S., the energy saved could power 4.1 million homes for a full year.

    Recycling helps save energy. If you recycle one glass bottle, it saves enough energy to light a 100-watt bulb for four hours, power a computer for 30 minutes, or a television for 20 minutes.

    Cardboard (also known as corrugated) boxes can be recycled at least seven times and can be used to make new packaging boxes and even furniture.

    "We Love how all of our house plants are all in one location! Makes watering much easier!"
    "Loved every minute of using PlantHub!"

    Jen Member since 2021

    ); export default Home; subramaniashiva/quotes-pwa0 /* Static file. Returns an array of quote Used when the API call fails */ const backup_quotes = [{ content: { rendered: 'A computer lets you make more mistakes faster than any other invention in human history, with the possible exceptions of handguns and tequila.', }, title: { rendered: '' } }, { content: { rendered: '

    Everything is possible, that’s what science is all about. No, that’s what’s being a Magical Elf is all about.

    ', }, title: { rendered: 'The Professor (on Futurama)' } }, { content: { rendered: '

    The process is really just Iterate, Iterate, Iterate.

    ', }, title: { rendered: '', } }]; export default backup_quotes; /*global after, describe, it */ 'use strict'; var assert = require('assert'); var fs = require('fs'); var Imagemin = require('../'); var path = require('path'); var rm = require('rimraf'); describe('Imagemin()', function () { after(function (cb) { rm(path.join(__dirname, 'tmp'), cb); }); it('should optimize a GIF', function (cb) { var imagemin = new Imagemin(); imagemin .src(path.join(__dirname, 'fixtures/test.gif')) .dest(path.join(__dirname, 'tmp/test.gif')) .use(Imagemin.gifsicle()) .optimize(function () { assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size); assert(fs.statSync(imagemin.dest()).size > 0); cb(); }); }); it('should optimize a JPG', function (cb) { var imagemin = new Imagemin(); imagemin .src(path.join(__dirname, 'fixtures/test.jpg')) .dest(path.join(__dirname, 'tmp/test.jpg')) .use(Imagemin.jpegtran()) .optimize(function () { assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size); assert(fs.statSync(imagemin.dest()).size > 0); cb(); }); }); it('should optimize a PNG', function (cb) { var imagemin = new Imagemin(); imagemin .src(path.join(__dirname, 'fixtures/test.png')) .dest(path.join(__dirname, 'tmp/test.png')) .use(Imagemin.optipng()) .optimize(function () { assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size); assert(fs.statSync(imagemin.dest()).size > 0); cb(); }); }); it('should optimize a SVG', function (cb) { var imagemin = new Imagemin(); imagemin .src(path.join(__dirname, 'fixtures/test.svg')) .dest(path.join(__dirname, 'tmp/test.svg')) .use(Imagemin.svgo()) .optimize(function () { assert(fs.statSync(imagemin.dest()).size < fs.statSync(imagemin.src()).size); assert(fs.statSync(imagemin.dest()).size > 0); cb(); }); }); it('should optimize a image using Buffer', function (cb) { var buf = fs.readFileSync(path.join(__dirname, 'fixtures/test.jpg')); var imagemin = new Imagemin(); imagemin .src(buf) .use(Imagemin.jpegtran()) .optimize(function (err, file) { assert(file.contents.length < buf.length); cb(); }); }); }); import { OrmRelationBuilder } from "./orm-relation-builder.js"; export class TransactionHandling extends OrmRelationBuilder { constructor() { super(...arguments); this.transaction = null; } /** * Retrieves current transaction and if ne transaction exists then creates new one. * * @param stores * @param mode * @param overwrite */ getTransaction(stores, mode, overwrite = false) { if (this.transaction === null || overwrite) { this.transaction = this.createTransaction(stores, mode); } return this.transaction; } /** * Sets transaction for the model * @param transaction */ setTransaction(transaction) { this.transaction = transaction; } /** * Creates new transaction * @param stores * @param mode */ createTransaction(stores, mode) { const transaction = this.db.transaction(stores, mode); this.setTransaction(transaction); return transaction; } } //# sourceMappingURL=transaction-handling.js.mapsrc/pages/Tests/Tests.js import React, { useState, useEffect, useCallback, useMemo } from "react"; import { navigate } from "@reach/router"; import styled from "styled-components"; import { timer } from "rxjs"; import anonymus from "anonymus"; import { getTestsList } from "./testsList"; import SignalQuality from "../../components/notion/SignalQuality/SignalQualityCard"; import { notion, useNotion, deviceApp } from "../../services/notion"; import { Nav } from "../../components/Nav"; const RightContainer = styled.div` border: 1px solid darkgray; height: 300px; width: 100%; display: flex; justify-content: center; align-items: center; font-size: 21px; & img { height: 298px !important; width: auto !important; } `; const TestLabel = styled.span.attrs({ className: "label label-default", })` position: relative; left: 10px; top: -5px; padding: 4px 9px; border-radius: 4px; `; const Content = styled.div` & .card { min-height: 171px; margin-bottom: 0; } `; export function Tests() { const { status, selectedDevice, userClaims, user } = useNotion(); useEffect(() => { if (!user) { navigate("/login"); } }, [user]); const tests = useMemo( () => getTestsList({ selectedDevice, userClaims }), [selectedDevice, userClaims] ); const { sleepMode } = status || {}; return (
    {user ?

    Tests

    {tests.map((test) => ( ))}
    ); } function Test({ test, sleepMode }) { const [passed, setPassed] = useState(null); const [status, setStatus] = useState("ready"); const [activeInstruction, setActiveInstruction] = useState(null); const [testing, setTesting] = useState(false); const [testResults, setTestResults] = useState(null); const [instructionsState, setInstructionsState] = useState({}); const [instructionsSettings, setInstructionsSettings] = useState({}); const [instructions, testDuration] = useMemo(() => { const instructions = typeof test.instructions === "function" ? test.instructions(instructionsSettings) : test.instructions; const testDuration = instructions.reduce( (acc, { duration }) => acc + duration, 0 ); const mappedInstructions = instructions.map((instruction, i) => ({ ...instruction, id: i, })); return [mappedInstructions, testDuration]; }, [instructionsSettings]); const stop = useCallback(() => { setStatus("completed"); setActiveInstruction(null); }, []); // on complete test useEffect(() => { if (status !== "completed") { return; } if (test.experimentId === "signal-quality") { setTesting(true); } else if ("onFinish" in test) { setTesting(true); test.onFinish(instructionsState).then((passed) => { setTesting(false); setPassed(passed); }); } else { setPassed(true); } }, [status, instructionsState, test, setTesting, setPassed]); useEffect(() => { if (!activeInstruction) { return; } const isLastInstruction = activeInstruction.id === instructions[instructions.length - 1].id; timer(activeInstruction.duration).subscribe(() => { if (isLastInstruction) { stop(); } else { const currentInstructionIndex = instructions.findIndex( (instruction) => instruction.id === activeInstruction.id ); setActiveInstruction(instructions[currentInstructionIndex + 1]); } }); }, [activeInstruction, setActiveInstruction, instructions, stop]); const start = useCallback(async () => { setStatus("started"); setActiveInstruction(instructions[0]); if (!test.recordData) { return; } const memory = await notion.dispatchAction({ command: "brainwaves", action: "record", responseRequired: true, responseTimeout: testDuration + 10000, message: { name: anonymus.create(), experimentId: test.experimentId, label: instructionsSettings?.label ?? test.experimentId, duration: testDuration, }, }); if (test.experimentId === "external-trigger") { } }, [setStatus, test, setActiveInstruction, instructionsSettings]); const reset = useCallback(() => { setPassed(null); setStatus("ready"); setActiveInstruction(null); setTesting(false); setTestResults(null); }, [setPassed, setStatus, setActiveInstruction, setTesting, setTestResults]); return (

    {test.name} {test?.isInternal ? Internal : null}

    {test?.settings ? ( ) : null} {instructions.map((instruction, index) => (

    {activeInstruction && instruction.id === activeInstruction.id ? ( {index + 1}) {instruction.description} ) : ( {index + 1}) {instruction.description} )}

    ))}
    {activeInstruction ? ( ) : null}
      {status === "completed" ? ( ) : null}
    {testing ? ( Testing... ) : null} {passed === null ? null : ( {passed ? "Passed" : "failed"} )}
    {testResults ? ( <>
    {JSON.stringify(testResults, null, 2)}
    ) : null}
    ); } generator/navbar.js0 (function() { 'use strict'; angular.module('QQappQQ').directive('myNav', myNav); myNav.$inject = []; function myNav() { return { restrict: 'E', templateUrl: 'navbar/navbar.html', controller: 'NavbarCtrl', controllerAs: 'nav', link: function(scope, element, attrs, tabsCtrl) { }, }; } })(); 'use strict' const types = require('./types') const DataStore = function () { const data = [] this.getData = function () { return data } } DataStore.prototype.save = function (browser, result) { if (!result.success && !result.skipped && result.suite.length > 0) { const suite = this.findSuiteInResult(result) return this.saveResultToSuite(suite, browser, result) } } DataStore.prototype.saveResultToSuite = function (suite, browser, result) { suite.tests = (!suite.tests) ? [] : suite.tests const test = this.findTestByName(suite.tests, result.description) test.depth = suite.depth + 1 const browserInfo = this.findBrowserByName(test.browsers, browser.name) browserInfo.depth = test.depth + 1 if (result.log && result.log[0] !== null) { browserInfo.errors = result.log[0].split('\n') } return { suite, test, browser: browserInfo } } DataStore.prototype.findSuiteInResult = function (result) { let suite const self = this let searchArray = self.getData() result.suite.forEach(function (suiteName, i) { suite = self.findSuiteByName(searchArray, suiteName) suite.depth = i suite.suites = (!suite.suites) ? [] : suite.suites searchArray = suite.suites }) return suite } DataStore.prototype.findByName = function (arr, name, Constructor) { let it // Look through the array for an object with a // 'name' property that matches the 'name' arg arr.every(function (el) { if (el.name === name) { it = el return false } return true }) // If a matching object is not found, create a // new one and push it to the provided array if (!it) { it = new Constructor(name) arr.push(it) } // return the object return it } DataStore.prototype.findSuiteByName = function (arr, name) { return this.findByName(arr, name, types.Suite) } DataStore.prototype.findTestByName = function (arr, name) { return this.findByName(arr, name, types.Test) } DataStore.prototype.findBrowserByName = function (arr, name) { return this.findByName(arr, name, types.Browser) } exports.getInstance = function () { return new DataStore() } 'use strict'; /* jasmine specs for filters go here */ describe('filter', function() { beforeEach(module('mobyle')); describe('kwSearch', function() { it('should not filter if no query provided', inject(function(kwSearchFilter) { var services = [{'name':'test1'},{'name':'test2'}]; var q = ''; expect(kwSearchFilter(services,q)).toEqual(services); })); it('should filter only the matching service', inject(function(kwSearchFilter) { var matchingService = {'name':'test1', 'description': 'matching description'}; var matchedServices = [{'name':'test1', 'description': 'matching description', 'descriptionHl': 'matching description', 'found': true}]; var nonMatchingService = {'name':'test1', 'description': 'nothing to match'}; var services = [matchingService,nonMatchingService]; var q = 'matching'; expect(kwSearchFilter(services,q,['name','description'])).toEqual(matchedServices); })); }); }); var $j = jQuery.noConflict(); $j( document ).ready( function() { "use strict"; // Carousel oceanwpInitCarousel(); } ); /* ============================================== CAROUSEL ============================================== */ function oceanwpInitCarousel( $context ) { "use strict" var $carousel = $j( '.gallery-format, .product-entry-slider', $context ); // If RTL if ( $j( 'body' ).hasClass( 'rtl' ) ) { var rtl = true; } else { var rtl = false; } // Return autoplay to false if woo slider if ( $carousel.hasClass( 'woo-entry-image' ) ) { var autoplay = false; } else { var autoplay = true; } // Slide speed var speed = 7000; // Gallery slider $carousel.imagesLoaded( function() { $carousel.slick( { autoplay: autoplay, autoplaySpeed: speed, prevArrow: '', nextArrow: '', rtl: rtl, } ); } ); }src/contexts/apis-instance.js import React, { createContext, useContext, useReducer } from 'react' import { APIS_APP_REG_ENDPOINT } from '../constants' const ApisInstanceStateContext = createContext() const SetApisInstanceContext = createContext() const defaultLimit = 1000 const initialState = { availableInstances: {}, selected: undefined, meta: { loading: false, error: null, }, } const actions = { SET_AVAILABLE_INSTANCES: 'SET_AVAILABLE_INSTANCES', SET_AVAILABLE_INSTANCES_PENDING: 'SET_AVAILABLE_INSTANCES_PENDING', SET_AVAILABLE_INSTANCES_ERROR: 'SET_AVAILABLE_INSTANCES_ERROR', SELECT_INSTANCE: 'SELECT_INSTANCE', ADD_EXTRA_INSTANCE: 'ADD_EXTRA_INSTANCE', } const apisReducer = (state, action) => { switch (action.type) { case actions.SET_AVAILABLE_INSTANCES: { return { ...state, availableInstances: action.payload.reduce( (acc, instance) => { acc[instance.app_id] = { ...instance, basePath: instance.app_url, defaultLimit, } return acc }, { ...state.availableInstances } ), meta: { loading: false, error: null, }, } } case actions.SET_AVAILABLE_INSTANCES_PENDING: { return { ...state, meta: { loading: true, error: null, }, } } case actions.SET_AVAILABLE_INSTANCES_ERROR: { const error = action.payload return { ...state, meta: { loading: false, error, }, } } case actions.SELECT_INSTANCE: { return { ...state, selected: action.payload, } } case actions.ADD_EXTRA_INSTANCE: { return { ...state, availableInstances: { ...state.availableInstances, extraInstance: { basePath: action.payload, title: 'Supersecret APIS instance', }, }, } } default: throw new Error(`Unrecognized action type ${action.type}`) } } export const ApisInstanceProvider = ({ children }) => { const [apisInstances, dispatch] = useReducer(apisReducer, initialState) return ( {children} ) } export const useApisInstanceState = () => { const context = useContext(ApisInstanceStateContext) if (context === undefined) { throw new Error( 'useApisInstanceState must be nested in an ApisInstanceProvider.' ) } return context } export const useSetApisInstance = () => { const context = useContext(SetApisInstanceContext) if (context === undefined) { throw new Error( 'useApisInstanceState must be nested in an ApisInstanceProvider.' ) } return context } export const useApisInstance = () => { return [useApisInstanceState(), useSetApisInstance()] } export const fetchApisInstances = async dispatch => { dispatch({ type: actions.SET_AVAILABLE_INSTANCES_PENDING }) try { const results = await fetch(APIS_APP_REG_ENDPOINT) const data = await results.json() dispatch({ type: actions.SET_AVAILABLE_INSTANCES, payload: data }) } catch (error) { dispatch({ type: actions.SET_AVAILABLE_INSTANCES_ERROR, error: true, payload: error, }) } } /** * Copyright (c) 2014-2015, CKSource - . All rights reserved. * Licensed under the terms of the MIT License (see LICENSE.md). * * @file Page builder responsible for manual tests */ 'use strict'; var marked = require( 'marked' ), path = require( 'path' ); /** * @module pagebuilders/manual */ module.exports = { name: 'bender-pagebuilder-manual', /** * Include manual test script and template in a test page * @param {Object} data Test page data * @return {Object} */ build: function( data ) { var bender = this, pattern = /@bender\-([\w\-]+)\:([\w \-\.\/\\\:\?\+\$@~_,=#%';!]+)/gi, file; if ( !data.manual ) { return data; } file = data.snapshot ? path.join( '.bender/jobs/', data.jobId, '/tests/', data.script ) : data.script; // removes bender directives (@bender-*) from the script function stripDirectives( content ) { return content.replace( pattern, '' ); } var promise = bender.files.readString( path.join( __dirname, '../../static/manual.html' ) ) .then( function( template ) { file = bender.files.get( file ); return file.read() .then( function( content ) { return bender.utils.template( template.toString(), { SCRIPT: marked( stripDirectives( content.toString() ) ) } ); } ); } ); data.parts.push( promise ); return data; } }; hrdipto/ohif-viewer import FuseScrollbars from '@fuse/core/FuseScrollbars'; import { useTheme, ThemeProvider } from '@material-ui/core/styles'; import { selectContrastMainTheme } from 'app/store/fuse/settingsSlice'; import clsx from 'clsx'; import { useSelector } from 'react-redux'; function FusePageCardedSidebarContent(props) { const theme = useTheme(); const contrastTheme = useSelector(selectContrastMainTheme(theme.palette.primary.main)); const { classes } = props; return ( <> {props.header && (
    {props.header}
    )} {props.content && ( {props.content} )} ); } export default FusePageCardedSidebarContent; import React from 'react' import { Field, Form } from 'react-final-form' import FormControlLabel from '@material-ui/core/FormControlLabel' import Switch from '~/pages/profile/components/Switch' import { TextField } from 'final-form-material-ui' import Button from '@material-ui/core/Button' import { makeStyles } from '@material-ui/core/styles' import { useStore } from 'effector-react' import { pick, mapValues, join, get, identity } from 'lodash' import { FORM_ERROR } from 'final-form' import CircularProgress from '@material-ui/core/CircularProgress' import MenuItem from '@material-ui/core/MenuItem' import Typography from '@material-ui/core/Typography' import { $profile, updateProfile } from '~/data/stores/profile' import { PaddedAlert } from '~/pages/profile/components/PaddedAlert' import { CountrySelect } from '~/pages/profile/components/CountrySelect' import { FruitsSelect } from '~/pages/profile/components/FruitsSelect' import { Select } from '~/pages/profile/components/Select' import { PLAY_DAYS, PLAYTIME } from '~/data/constants' const useStyles = makeStyles((theme) => ({ formPaper: { margin: '64px auto', padding: 32, maxWidth: 640, }, form: { marginTop: 32, display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, field: { marginBottom: 32, }, flexField: { flex: '1 0 auto', }, fieldsGroup: { marginBottom: 16, display: 'flex', flexDirection: 'column', alignItems: 'stretch', }, sideLabel: { marginTop: 16, marginRight: 8, }, fieldsRow: { display: 'flex', flexDirection: 'row', alignItems: 'stretch', }, })) export const ProfileForm = () => { const classes = useStyles() const profile = useStore($profile) const onProfileSubmit = (profileData) => updateProfile(profileData) .then( (resp) => new Promise((resolve) => setTimeout(() => resolve(resp), 1500)) ) .catch((error) => { if (error.response) { const fieldsWithErrors = get(error, 'response.data') return mapValues(fieldsWithErrors, join) } else { return { [FORM_ERROR]: 'Error occurred during form submit 😓' } } }) const initialValues = pick(profile, [ 'id', 'is_visible', 'nickname', 'friend_code', 'language', 'commentary', 'fruits', 'playtime', 'playdays', ]) return (
    ( } label='Show my profile in public players list on main page' className={classes.field} />
    I usually play {PLAYTIME.map(({ id, value }) => ( {value} ))} {PLAY_DAYS.map(({ id, value }) => ( {value} ))}
    {submitSucceeded && ( Profile updated )} {submitError && ( {submitError} )} )} /> ) } GodefroiRoussel/prello_option1_groupe4server/server/Team/model.js import {Meteor} from 'meteor/meteor'; import SimpleSchema from "simpl-schema"; const Team = new Meteor.Collection('team'); const teamSchema = new SimpleSchema({ nameTeam: {type: String}, visibilityTeam: {type: Boolean, defaultValue: false}, seedTeam: {type: String, optional: true}, invitationsOpenedTeam: {type: Boolean, optional: true}, isArchived: {type: Boolean, defaultValue: false}, idBoards: {type: Array, optional: true}, 'idBoards.$': {type: String}, ownerTeam: {type: String}, members: {type: Array}, 'members.$': {type: String}, }); Team.attachSchema(teamSchema); export default Team;Ext.define('CustomApp', { extend: 'Rally.app.App', componentCls: 'app', launch: function() { //save app preferences Rally.data.PreferenceManager.update({ appID: this.getAppId(), filterByUser: true, settings: { myTag: 'Spike One', }, success: function(updatedRecords, notUpdatedRecords) { console.log('updated prefs'); Rally.data.PreferenceManager.load({ appID: this.getAppId(), filterByUser: true, success: function(prefs) { this._makeGrid(prefs) },scope:this }); },scope:this }); }, _makeGrid:function(prefs){ console.log('prefs', prefs) this.add({ xtype: 'rallygrid', columnCfgs: [ 'FormattedID', 'Name', 'Owner', 'Tags' ], context: this.getContext(), enableEditing: false, showRowActionsColumn: false, storeConfig: { model: 'userstory', filters:[ { property:'Tags.Name', operator: 'contains', value: prefs.myTag } ] } }); } }); import Vue from 'vue'; import VueCompositionAPI from '@vue/composition-api'; import { mount } from '@vue/test-utils'; import { useTable } from 'src'; const fetchList = function(page, filter) { return Promise.resolve({ page, filter, result: [ { id: 1000, status: 1, name: 'A' }, { id: 2000, status: 1, name: 'B' }, { id: 3000, status: 1, name: 'C' }, { id: 4000, status: 0, name: 'D' } ] }); }; const TestComponent = { template: `
    • {{ item.name }}
    `, setup() { const table = useTable({ // uniqueKey: 'id', sortKeys: { order: 'order', orderBy: 'prop', asc: 'ascending', desc: 'descending' } }); const { state, customPageSorter, setList, setPage, resetPage, setInitialPage, setFilter, resetFilter, setInitialFilter, setPageSort, setPageSize, setPageNo, setSelection, addCrossPageSelection, removeCrossPageSelection, clearCrossPageSelection, triggerUpdate, watchUpdate } = table; return { table, state, customPageSorter, setList, setPage, resetPage, setInitialPage, setFilter, resetFilter, setInitialFilter, setPageSort, setPageSize, setPageNo, setSelection, addCrossPageSelection, removeCrossPageSelection, clearCrossPageSelection, triggerUpdate, watchUpdate }; }, data() { return {}; }, created() { this.watchUpdate(() => { this.fetchList(); }); this.setInitialPage({ pageNo: 1, pageSize: 5, orderBy: 'id', order: 'asc' }); this.setInitialFilter({ status: 1 }); this.triggerUpdate(); }, methods: { fetchList() { const { page, filter } = this.state; return fetchList(page, filter).then(data => { this.setList(data); }); } } }; let wrapper = null; let vm = null; beforeEach(() => { wrapper = mount(TestComponent); vm = wrapper.vm; }); afterEach(() => { wrapper.destroy(); }); beforeAll(() => { Vue.use(VueCompositionAPI); }); describe('use table', () => { test('initialize table', () => { expect(vm.state.filter).toEqual({ status: 1 }); expect(vm.state.page).toEqual({ pageNo: 1, pageSize: 5, orderBy: 'id', order: 'asc' }); expect(vm.customPageSorter).toEqual({ prop: 'id', order: 'ascending' }); }); test('set page', () => { expect(vm.state.page.pageNo).toBe(1); expect(vm.state.page.pageSize).toBe(5); vm.setPageNo(10); vm.setPageSize(80); expect(vm.state.page.pageNo).toBe(10); expect(vm.state.page.pageSize).toBe(80); // invalid sorter vm.setPageSort({ prop: 'time' }); expect(vm.state.page.order).toBe('asc'); expect(vm.state.page.orderBy).toBe('id'); vm.setPageSort({ prop: 'time', order: 'desending' }); expect(vm.state.page.order).toBe('desc'); expect(vm.state.page.orderBy).toBe('time'); expect(vm.customPageSorter).toEqual({ prop: 'time', order: 'descending' }); vm.setPageSort({ prop: 'status', order: 'ascending' }); expect(vm.state.page.order).toBe('asc'); expect(vm.state.page.orderBy).toBe('status'); expect(vm.customPageSorter).toEqual({ prop: 'status', order: 'ascending' }); vm.setPage( { pageNo: 2, pageSize: 40, orderBy: 'id', order: 'desc' }, { merge: false } ); expect(vm.state.page).toEqual({ pageNo: 2, pageSize: 40, orderBy: 'id', order: 'desc' }); vm.setPage(); expect(vm.state.page).toEqual({ pageNo: 2, pageSize: 40, orderBy: 'id', order: 'desc' }); vm.resetPage(); expect(vm.state.page).toEqual({ pageNo: 1, pageSize: 5, orderBy: 'id', order: 'asc' }); }); test('set filter', () => { expect(vm.state.filter.status).toBe(1); vm.setFilter({ id: 1000 }); expect(vm.state.filter.id).toBe(1000); vm.setFilter( { type: 1, status: 0 }, { merge: false } ); expect(vm.state.filter).toEqual({ type: 1, status: 0 }); vm.setFilter(); expect(vm.state.filter).toEqual({ type: 1, status: 0 }); vm.resetFilter(); expect(vm.state.filter).toEqual({ status: 1 }); }); test('cross page selection', () => { expect(vm.state.selection).toEqual([]); expect(vm.state.crossPageSelection).toEqual([]); vm.setSelection([{ id: 1 }]); expect(vm.state.selection).toEqual([{ id: 1 }]); vm.addCrossPageSelection([{ id: 1 }, { id: 3 }]); vm.addCrossPageSelection(); expect(vm.state.crossPageSelection).toEqual([{ id: 1 }, { id: 3 }]); vm.removeCrossPageSelection([{ id: 1 }]); vm.removeCrossPageSelection(); expect(vm.state.crossPageSelection).toEqual([{ id: 3 }]); vm.setSelection(); vm.clearCrossPageSelection(); expect(vm.state.selection).toEqual([]); expect(vm.state.crossPageSelection).toEqual([]); }); }); node_modules/@fluentui/react-icons/lib/cjs/components/ImageEdit16Regular.js "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const wrapIcon_1 = require("../utils/wrapIcon"); const rawSvg = (iconProps) => { const { className, primaryFill } = iconProps; return React.createElement("svg", { width: 16, height: 16, viewBox: "0 0 16 16", xmlns: "http://www.w3.org/2000/svg", className: className }, React.createElement("path", { d: "M11.5 5.5a1 1 0 11-2 0 1 1 0 012 0zM2 4.5A2.5 2.5 0 014.5 2h7A2.5 2.5 0 0114 4.5v1.56a2.57 2.57 0 00-1-.02V4.5c0-.83-.67-1.5-1.5-1.5h-7C3.67 3 3 3.67 3 4.5v7c0 .23.05.45.15.64L6.8 8.5a1.7 1.7 0 012.4 0l.34.34-.7.71-.35-.34a.7.7 0 00-.99 0l-3.65 3.65c.2.1.42.15.65.15h1.8l-.25 1H4.5A2.5 2.5 0 012 11.5v-7zM13.26 7a1.56 1.56 0 00-.92.45l-4.3 4.3c-.34.34-.59.77-.71 1.25l-.01.03-.3 1.21a.6.6 0 00.73.74l1.22-.3c.48-.12.93-.38 1.29-.73l4.28-4.29a1.56 1.56 0 00-1.28-2.65z", fill: primaryFill })); }; const ImageEdit16Regular = wrapIcon_1.default(rawSvg({}), 'ImageEdit16Regular'); exports.default = ImageEdit16Regular; window.addEventListener( "pageshow", function ( event ) { var historyTraversal = event.persisted || ( typeof window.performance != "undefined" && window.performance.navigation.type === 2 ); if ( historyTraversal ) { // Handle page restore. window.location.reload(); } }); $(function () { $('[data-toggle="tooltip"]').tooltip() $('[data-toggle="popover"]').popover(); }) // like api function likeit(id) { $.ajax({ url: '/user/post/api/like/', method:'GET', data:{'post_id':id}, beforeSend: function(re){ $(`#like_${id}`).html('') }, success: function(re) { $(`#like_${id}`).html(` ${re.likes>0 ? re.likes : ''} `) re.status ? $(`#like_${id}`).addClass('active') : $(`#like_${id}`).removeClass('active'); }, error: function(re) { console.log('connection problem!'); } }) } function showShare(id) { $(`${id} div[data-network="sharethis"]`).click(); } function get_template(name, since,about, img_url, top_stories, followers_num) { let date = new Date(since) date = date.toDateString().split(' ') let temp1 = `
    ${name}
    Member since ${date[1]+" "+date[3]}
    ${about}
    ` let list =''; if (top_stories.length > 0) { list = `

    Top Stories

      ` for(let i of top_stories) { list+=`
    1. ${i[1].slice(0,40)}
    2. ` } list+='
    ' } let temp3 = `

    Followed by ${followers_num} people

    ` return temp1+list+temp3; } $(document).ready(function(){ $('#left-toggle').click(function(){ $('#left-bar').toggle('fast','linear'); if (window.innerWidth < 400) {$(".navbar-toggler").toggle();} }); // for search api var obj = { start : `
    Peoples
    `, middle: `
    view all people
    Posts
    `, end:`
    view all` } $("#search_bar").on('keydown paste change focus', function(e){ $('#search_sync').show(); $(document).click(function(e){ if (e.target.nodeName != "A") { $('#search_sync').hide(); } }) $.ajax({ url: '/api/search', method: 'GET', data: {'data':$(this).val()}, beforeSend: function() { $('div#search_sync').html(''); }, success: function(result){ let ppl = '', pst = ''; for(let i=0;i < result.peoples.length; i++) { ppl += `
    ${result.peoples[i].name} (${result.peoples[i].username}) programmer with passion
    `; } for(let i=0;i < result.posts.length; i++) { pst += `
    ${result.posts[i].title} (${result.posts[i].subtitle})
    `; } if(!result.peoples) { ppl = '

    No Result Found!

    ' } if (!result.posts) { pst = '

    No Result Found!

    ' } $('div#search_sync').html(''); $('div#search_sync').append(obj.start + ppl + obj.middle + pst + obj.end); }, error: function(result) { $('div#search_sync').html('

    No Result Found!

    '); } }) }); }) function pop(e) { $('[data-user]').not(this).popover('hide'); $('.container-fluid, .container').click(function(ev){$('#'+e.id).popover('hide')}); let obj; $.ajax({ url:'/api/userdetail', method:'GET', data:{'username':$('#'+e.id).attr('data-user')}, success: function(re) { console.log(re) obj = { html:true, content: get_template(re.name, re.joined, re.about, re.profile_pic, re["top-posts"], re.followers), placement:'bottom', trigger:'focus', // title:'hurr hurr dabang dabang', template:`` } $('#'+e.id).popover(obj); $('#'+e.id).popover('show'); }, error: function(re) { console.log('Connection Problem'); } }); } // for follow api function follow(id, csrf) { $.ajax({ url: '/api/follow', method:'POST', data:{'csrfmiddlewaretoken':csrf,'user_id':id}, success: function(re) { re.status ? $('#follow_btn').val('Unfollow') : $('#follow_btn').val('Follow'); location.reload(); }, error: function(re) { console.log('connection problem!'); } }) } // for bookmark api function bookmark(id,status) { $.ajax({ url: '/api/bookmark', method:'GET', data:{'post_id':id}, beforeSend: function(re){ $(`#bookmark_${id}`).html('') }, success: function(re) { re.status ? $(`#bookmark_${id}`).html('').attr('title','Remove Bookmark') : $(`#bookmark_${id}`).html('').attr('title','add Bookmark'); if(status) {location.reload();} }, error: function(re) { console.log('connection problem!'); } }) } // for draft api function draft(id, csrf) { $.ajax({ url: '/api/draft', method:'POST', data:{'csrfmiddlewaretoken':csrf, 'post_id':id}, beforeSend: function(re){ $(`#draft_${id}`).html('') }, success: function(re) { $(`#draft_${id}`).html('') re.status ? $(`#draft_${id}`).html(' Draft') : $(`#draft_${id}`).html(' Live'); }, error: function(re) { console.log('connection problem!'); } }) } // reply api function reply(id) { r = $("#reply_box").val(); $.ajax({ url:'/api/reply', method:"POST", data: {'reply':r, 'comment_id':id}, success:function(re) { $(re).insertAfter('#reply_form'); $('#reply_form').remove(); }, error: function() { console.log('problem') } }) } // comment api function comment(id) { c = $("#comment-area").val(); console.log(c) $.ajax({ url:'/api/comment', method:"POST", data: {'comment':c, 'post':id}, success:function(re) { if (typeof(re)=='string') { $('#comments_container').prepend(re); } else { alert('There is some problem. we are checking...') } }, error: function() { console.log('problem') } }) $("#comment-area").val(''); } // remove comment api function remove_comment(id) { $.ajax({ url:'/api/comment_remove', method:'POST', data:{'id':id}, success: function(re){ if (re.status==true) { $('#c_'+id).remove(); } }, }) } // remove reply api function remove_reply(id) { $.ajax({ url:'/api/reply_remove', method:'POST', data:{'id':id}, success: function(re){ console.log(re) if (re.status==true) { $('#r_'+id).remove(); } }, error:function(){ console.log('problem') } }) }// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示: const Koa = require('koa'); // 创建一个Koa对象表示web app本身: const app = new Koa(); const router = require('./middleware/router'); const koaBody = require('koa-body'); //解析上传文件的插件 const cors = require('koa-cors'); //使用koa-cors解决跨域请求问题 const staticFiles = require('koa-static'); const session=require('koa-session'); app.use(cors({ origin: function (ctx) { return "*"; // return 'http://localhost:8080'; }, exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'], maxAge: 5, credentials: true, allowMethods: ['GET', 'POST', 'DELETE'], //设置允许的HTTP请求类型 allowHeaders: ['Content-Type', 'Authorization', 'Accept'], })); app.keys = ['this is my secret key']; app.use(session({ key: 'koa:sess', /** cookie的名称,可以不管 */ maxAge: 1800000, /** (number) maxAge in ms (default is 1 days),cookie的过期时间,这里表示半个小时 */ overwrite: true, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ },app)); app.use(staticFiles(__dirname+"/public")) app.use(koaBody()); app.use(router.routes()); // 在端口3000监听: app.listen(3000); console.log('app started at port 3000...');jarvelov/veggivore import { UserProfile } from 'components/User' const ViewUser = { name: 'ViewUser', render (h) { return (
    ) } } export default ViewUser gao-hub/cr-parking-admin0 import request from '@/utils/request'; import { _baseApi } from '@/defaultSettings.js'; // 获取兑换活动详情 export async function getExchangeInfo(params) { return request(`${_baseApi}/activityCode/info`, { method: 'POST', body: params, }); } // 兑换活动新增 export async function addExchange(params) { return request(`${_baseApi}/activityCode/add`, { method: 'POST', body: params, }); } // 编辑兑换活动 export async function editExchange(params) { return request(`${_baseApi}/activityCode/update`, { method: 'POST', body: params, }); } Object.assign(exports, (function() { const DRIVERS = 'drivers'; const NODE = '/usr/bin/node'; const LOGGING = false; const DEBUGGING = false; const VERBOSE = false; const {KEYS, VALUES, isFalse, isEqual, isFunction, isObject, isString, isArray, assign, iterable, includes, inject, events, bind, setOrGet, initKey, chain, dir, run} = require('helpers'); const {parse, stringify} = JSON; const nsresolution = 1000000000; // max time to live for requests const maxTTL = 20 * nsresolution; function errorLog(e) { LOGGING && e && console.error(e); return (e && e.toString && e.toString() || e); } function debugLog(...messages) { DEBUGGING && console.debug(...messages); } function verboseLog(...messages) { VERBOSE && console.debug(...messages); } function activityLog(...messages) { LOGGING && console.log(...messages); } class IPC { // interprocess communication and process control layer // this class is designed to run in a child process controlled by a parent instance of the Router class trigger(type, data = {}) { const listener = this.listeners[type]||false; isFunction(listener) && listener.call(this, data); return this; } end() { // this void method should be overridden by subclasses to inject a graceful shutdown procedure } destroy(message) { this.log(message); try {this.end();} catch(e) {this.log(e);} process.exit(); } get node() { return this.remote; } get domain() { return this.type; } get SessionID() { return this.id; } on(type, listener) { this.listeners[type] = listener; return this; } executeAsync(fork) { isFunction(fork) && (setTimeout(fork.bind(this), 0)); return this; } import(properties) { return assign(properties).to(this); } send(event) { try {stringify(event) && process.send(event);} catch(e) {this.trigger('exit', e);} return this; } emit(type, message) { this.send({type, message}); } response(response) { this.emit('response', response); return this; } flags(flags) { this.emit('flags', flags); return this; } error(error) { error && this.flags({error}); this.destroy(error); } poll(poll) { if (isFunction(poll)) { let repeat; // establish polling cycle this.interval && (repeat = setTimeout(() => this.poll(poll), this.interval*1000)); this.stop = () => clearInterval(repeat); try { poll.call(this); this.ready(); } catch(e) {this.error(e);} } } stop() {} setInterval(query) { this.interval = +(query.interval); return this; } async request() { // this void method should be overridden by subclasses } ready() { if (!this.isReady) { const ready = this.isReady = true; this.trigger('ready').flags({ready}); return true; } return false; } async connect(init) { try { if (isFunction(init)) { this.trigger('connect'); await init(); } } catch(error) {this.error(error);} } constructor(devices = {}) { const {argv} = process; const len = argv.length; // if called without remote server name argument, emit devices and exit if (len < 3) { console.log(stringify(devices)); process.exit(); } this.log = (...messages) => activityLog(...this.prefix.concat(messages)); this.debug = (...messages) => debugLog(...this.prefix.concat(messages)); this.verbose = (...messages) => verboseLog(...this.prefix.concat(messages)); const {basename} = require('path'); // get script name from first commandline parameter this.type = basename(argv[1], '.js'); // get remote server name from second commandline parameter this.remote = argv[2] || ''; const domain = this.type+'.'+this.remote; // get optional id from third commandline parameter this.id = argv[3] || domain; this.prefix = [domain, '->']; // handle events from parent process const parent = { message:message => { if (message) {for (const type of iterable(this.listeners, KEYS)) {includes(type).in(message) && this.trigger(type, message[type]);}} return this; }, disconnect:() => this.destroy('received disconnect signal'), SIGINT:() => this.destroy('received interrupt signal'), SIGTERM:() => this.destroy('received terminate signal') }; // global listeners are reserved and should not be overridden this.listeners = { request({key, request}) {this.request(request, key).then(result => ({key, result}), error => ({key, error})).then(response => this.response(response));}, exit(message) {this.destroy(message);} }; bind(parent).to(process); this.events = events; this.bind = events; } } class Passthrough extends IPC { // simple message forwarding class intended to run inside a child-process driver module // this is designed to cascade to a downstream SecureChannel server end() { this.channel.disconnect(); this.log('exiting gracefully'); } message(type, message) { this.channel.message(type, message); } query(request, key, abort = false) { this.message(abort ? 'abort' : 'request', {key, request}) } request(request, key) { this.query(request, key); } abort(request, key) { this.query(request, key, true); } constructor(devices) { super(devices); // node (host name) and SessionID (connection name) are provided by IPC superclass const {node, SessionID} = this; const connected = true; const events = { outgoing: { message:({type, message}) => this.message(type, message), request:({key, request}) => this.request(request, key), abort:({key, request}) => this.abort(request, key), }, incoming: { connect:() => this.flags({connected}), error:({reason}) => this.error(reason), up:() => this.ready() && this.message('render', {}), down:() => this.error('remote connection dropped'), message:({type, message}) => this.emit(type, message), response:response => this.response(response), heartbeat:() => this.debug('heartbeat received') } }; this.bind(events.outgoing); !node && this.trigger('exit', 'unspecified node'); // create dedicated communication channel this.channel = new SecureChannel(events.incoming, SessionID); } } class SecureChannel { // provides the following upgrades to the basic WebSocket class: // client establishes a persistent connection with the server when a keepalive value > 0 is specified // enables heartbeat telemetry by default when establishing persistent connections // provides connection latency tracking (using heartbeat mechanism) // named connections provide basis for stateful connection tracking // unique event listeners can be triggered on user-definable message types // bridging connections and passing messages between sockets is simplified // a single class instance can simultaneously connect to one remote host and service multiple remote clients on a local port toSQLDate() { // this = date object return this.toJSON().slice(0, 19).replace('T', ' '); } time(time = new Date()) { return assign({toSQL:() => this.toSQLDate.call(time)}).to(time); } get clients() { return this.wss && this.wss.clients || []; } sockets(action) { if (isFunction(action)) {for (const socket of this.clients) {action.call(socket);}} } terminate() { return function() {this.terminate();} } list() { return function() {debugLog(this.SessionID);} } purge(id) { return function() {isEqual(this.SessionID, id) && this.close(3000, 'client migrated to new socket');} } formMessage(type, payload) { return (isString(type) && isObject(payload) || isArray(payload)) ? stringify({type, payload}) : false; } message(event, message) { message = this.formMessage(event, message); if (message) { this.ws && this.write(message).call(this.ws); this.wss && this.sockets(this.write(message)); return true; } return false; } data(type, message) { return this.message('data', {type, message}); } noop() {} constructor(routes = {}, SessionID = false) { const channel = this; const WebSocket = require('ws'); const {createServer} = require('https'); const {randomBytes} = require('crypto'); const generateKey = () => randomBytes(16).toString('base64'); const timestamp = () => this.time().toSQL(); // provide means to attach event listeners this.events = events; this.on = (event, listener) => { routes[event] = listener; return this; }; // call the function returned by write with a websocket context to send the message on that context this.write = message => function() {this.isActive() ? this.send(message, error => error && this.trigger('error', error)) : this.close(3001, 'socket not ready');}; // socketMethods operate under a WebSocket context as they extend the WebSocket prototype const socketMethods = { isActive() {return isEqual(this.readyState, WebSocket.OPEN);}, // propagate new event to local event listener trigger(event, message) { if (event) { const method = routes[event]; isFunction(method) ? method.call(this, {...message, timestamp:timestamp()}) : debugLog(`no listener for ${event} event in`, routes); } else { debugLog('unknown event for message:', message); } }, // propagate new event to remote host (converse of parseMessage) message(event, message) { verboseLog(event, '<<', message, this.SessionID); message = channel.formMessage(event, message); if (message) { channel.write(message).call(this); return true; } return false; }, // append channel data method to all WebSockets data:this.data, // derive events from raw message content parseMessage(message, address) { try { const {type, payload} = parse(message); if (type) { if (isEqual('sessionid', type)) { // client wants to establish a unique session const SessionID = `${payload.SessionID}@${address}`; // temporarily set the socket SessionID to a random key this.SessionID = generateKey(); // purge sockets with the same SessionID to drop any stale connections channel.sockets(channel.purge(SessionID)); // set the socket SessionID to the requested value this.SessionID = SessionID; channel.sessions(this); } if (isEqual('newsession', type)) { this.message('up', {timestamp:timestamp(), SessionID:generateKey()}); } else if (isEqual('up', type)) { // name the connection using the client-provided value or fallback to the server-provided value or fallback further to a randomly generated key const SessionID = this.SessionID || payload.SessionID || generateKey(); this.SessionID = SessionID; // send the SessionID to the server to name the link at both ends this.message('sessionid', {SessionID}); } else { // forward raw message before generating local event this.trigger('message', {type, message:payload}); } const {SessionID} = this; verboseLog(type, '>>', payload, SessionID); this.trigger(type, {...payload, address, SessionID}); } return true; } catch(_) {return false;} } }; // bind custom methods to all WebSocket objects assign(socketMethods).to(WebSocket.prototype); // SecureChannel server this.listen = options => { const keepalive = options.keepalive||0; const {address, port, cert, key} = options; debugLog('server options', {address, port, keepalive}); const path = options.path || '/'; const ready = () => isFunction(routes.listening) && routes.listening.call(this, {address, port, timestamp:timestamp()}); const ping = () => function () { if (isEqual(this.isAlive, false)) {return this.terminate();} this.isAlive = false; channel.sendTime = Date.now(); this.ping(channel.noop); }; function host(req) { const forwarded = req.headers['x-forwarded-for']; const address = forwarded ? forwarded.split(/\s*,\s*/)[0] : req.connection.remoteAddress; const SessionID = address; assign({isAlive:true, SessionID}).to(this); const listeners = { close(code, reason) { this.trigger('close', {address, sessionid:this.SessionID, reason:reason||code}); channel.sessions(this); }, error(e) {this.trigger('error', {address, sessionid:this.SessionID, reason:e.Error});}, message(message) {this.parseMessage(message, address);}, pong() {(this.isAlive = true) && this.trigger('heartbeat', {address, sessionid:this.SessionID, latency:(Date.now()-channel.sendTime)/2});} }; // bind events to websocket bind(listeners).to(this); // inform server that new client has connected this.trigger('open', {address}); channel.sessions(this); // inform client that connection is ready this.message('up', {timestamp:timestamp(), SessionID:generateKey()}); } this.sessions = ws => { const sessions = []; channel.sockets(function() {sessions.push(this.SessionID);}); ws.trigger('sessions', {sessions}); }; this.destroy = () => { clearInterval(this.healthCheck); this.sockets(this.terminate()); return true; }; const server = this.server = createServer({cert, key}).listen(port, address, ready); this.wss = new WebSocket.Server({server, path}).on('connection', (ws, req) => host.call(ws, req)); keepalive && (this.healthCheck = setInterval(() => this.sockets(ping()), keepalive*1000)); return this; }; // SecureChannel client this.connect = options => { const {address, port} = options; const path = options.path||''; const keepalive = options.keepalive||0; const reconnect = options.reconnect||5; const rejectUnauthorized = options.enforceSSLVerification||false; const service = `${address}:${port}`; const url = `wss://${service}${path}`; const origin = `https://${service}`; debugLog('client options', {address, port, keepalive, reconnect}); this.ws = { terminate:channel.noop, isActive() {return false;}, readyState:false, SessionID }; const init = () => { // if socket is open then do nothing if (this.ws.isActive()) {return;} // rejectUnauthorized:false allows connections to a server using a self-signed cert // traffic is strongly encrypted, but TLS will not attempt to verify authenticity of the certificate chain this.ws = assign({SessionID}).to(new WebSocket(url, {origin, rejectUnauthorized})); // listeners run under websocket context const listeners = { ping() { const timedout = () => { this.trigger('error', {address, reason:'no heartbeat received for '+keepalive+' seconds'}); this.terminate(); }; if (keepalive) { clearTimeout(this.pingTimeout); this.pingTimeout = setTimeout(timedout, keepalive*1000+1000); this.trigger('heartbeat', {address}); } }, message(message) {this.parseMessage(message, address);}, open() { clearTimeout(this.respawnTimeout); this.respawnTimeout = false; this.ping(); // the 'connect' message is only a confirmation that the local end of the connection is established // the connection is not considered up until an 'up' message arrives from the server this.trigger('connect', {address}); }, close() { clearTimeout(this.pingTimeout); if (keepalive) {this.respawnTimeout = setTimeout(init, reconnect*1000);} // 'down' messages are generated locally when a connection is severed for any reason this.trigger('down', {address}); }, error(reason) {this.trigger('error', {address, reason});} }; // bind events to websocket bind(listeners).to(this.ws); this.disconnect = () => this.ws.terminate(); }; init(); return this; } } } class Queue { // dynamic action queue framework // allow reading of queue length get length() { return this.actions.length; } // add actions to top of queue first(...actions) { this.actions.unshift(...actions); } // add action to bottom of queue defer(...actions) { this.actions.push(...actions); } // execute next queued entry next() { if (0 < this.actions.length) { const action = this.actions.shift(); isFunction(action) && action(); } } // populate new queue with 0 or more actions constructor(...actions) { this.actions = [...actions]; } } class Response extends Queue { // promise-based response handler with queueing extension settle(path, response) { // cancel timeout, if still ticking clearTimeout(this.timeout); // clear busy flag and continue processing any queued requests in order of receipt this.busy = false; this.next(); // settle current request and return response isFunction(path) && path(response); } process(query, timeout = 0) { // request events temporarily hijack the dispatcher event stream to intercept result messages and errors // other message types pass through seamlessly without interrupting request processing return new Promise((resolve, reject) => { // requests can only be processed serially // push request on the stack if waiting for prior request to settle if (this.busy) {return this.defer(() => this.process(query).then(resolve, reject));} else { // block simultaneous requests while the current request is processing this.busy = true; // fail if timeout fires before request settles timeout && (this.timeout = setTimeout(() => this.settle(reject, 'timeout'), timeout*1000)); // capture success or failure, whichever occurs first const triggers = {result:r => this.settle(resolve, r), error:e => this.settle(reject, e)}; bind(triggers).to(this.dispatcher); // initiate query if (!query()) {return this.settle(reject, 'communication fault');} } }); } constructor(dispatcher) { super() this.timeout = false; this.busy = false; this.dispatcher = dispatcher; } } class Dispatcher { // abstraction layer between an input stream and event consumers // facilitates agile message interception and redirection without creating temporary event listeners on the input stream timer(mode, abort = () => {}, timeout = 120) { clearTimeout(this.timeout); switch(mode) { case 'set': { this.complete = false; mode = 'reset'; break; } case 'reset': { if (!this.complete) {this.timeout = setTimeout(abort, timeout*1000);} break; } case 'clear': { this.complete = true; break; } } return this; } trigger(type, event) { debugLog({type, event}); isFunction(this.listeners[type]) && this.listeners[type].call(this, event); return this; } sink(source) { // propagate unprocessed messages using generic data event source && this.trigger('data', source); return false; } use(parser) { // specify custom message parser // parser priority is the inverse of the order in which it is added to the chain // therefore, the highest priority parser should be added last if (isFunction(parser)) {this.parsers.unshift(parser);} } reduce(message) { // custom reduce function that aborts processing on conditional match for (const parser of this.parsers) { if (isFalse(message)) {break;} message = parser(message); } } on(event, listener) { // specify listener for trapped event this.listeners[event] = listener; return this; } constructor() { this.parsers = [this.sink.bind(this)]; this.listeners = {}; this.events = events; this.bind = events; } } class Driver extends Dispatcher { // closes the communication loop with a child process running an instance of the IPC superclass get key() { const [s, ns] = process.hrtime(); return s * nsresolution + ns; } send(message) { if (isObject(this.child) && isFunction(this.child.send)) { this.child.send(message); return true; } errorLog('Worker process not running'); return false; } emit(type, message) { verboseLog({[type]:message}); return this.send({[type]:message}); } destroy() { clearInterval(this.freeResources); try {this.child.kill();} catch(_) {return;} } commit(request) { const {key, queue, domain} = this; return new Promise((result, error) => { activityLog(domain, '>>', request); // add response object to queue queue[key] = {request, result, error}; // commit request this.emit('request', {key, request}); }); } abort(request) { const {domain} = this; activityLog(domain, '>>', 'abort' , request); return this.emit('abort', {request}); } response(response) { const {domain, queue} = this; const {key, result, error} = response; if (key) { if (includes(key).in(queue)) { const {request} = response = queue[key]; response = error ? response.error : response.result; isFunction(response) && response(error || result); activityLog(domain, '<<', error ? {failed:request} : {succeeded:request}); // remove response object from queue delete queue[key]; } } } import(subject) { return assign(subject).to(this); } timeout() { const {key, queue} = this; for (const signature of iterable(queue, 'keys')) {if (key > (signature+maxTTL)) {this.response({key, error:'timed out'});}} } end() { this.emit('exit', true) || this.destroy(); } // abstraction layer to manage communication with a child process constructor(events, sessionid, domain, node, respawn = 10, path = 'drivers') { const {fork} = require('child_process'); const {join} = require('path'); const driver = join(path, domain+'.js'); respawn = +respawn; super(); // create call stack for requests this.import({domain, node, queue:{}}); this.bind(events); const connect = () => { try { this.child = bind(handlers).to(fork(driver, [node, sessionid])); this.trigger('connect', 'spawned worker process'); } catch(error) { this.trigger('flags', {error}) && errorLog(error), handlers.close(); } }; const handlers = { close:() => { const connected = false; this.trigger('flags', {connected}); respawn && setTimeout(() => connect(), respawn*1000); }, error:error => this.trigger('flags', {error}) && errorLog(error), message:({type, message}) => includes(type).in(this.listeners) && this.trigger(type, message) }; connect(); // start polling cycle to clean up dead requests this.freeResources = setInterval(this.timeout.bind(this), 1000); } } class Router { // central message router handles communication between a SecureChannel server and multiple data sources // each data source type is classified as a domain and has a dedicated child process that communicates with the router via IPC static async getDevices(path) { // this method gathers device metadata from all drivers found in the specified path (works with IPC class) const extension = '.js'; const jsFiles = name => /.js$/.test(name); const stripJS = name => name.replace(extension, ''); const devices = {}; try { const files = await dir(path); const domains = files.filter(jsFiles).map(stripJS).sort(); for (const domain of domains) { devices[domain] = {}; const nodes = await run(`${NODE} ${path}/${domain}${extension}`); for (const [node, data] of iterable(nodes)) {inject(devices[domain], node, isObject(data) ? data : {});} } debugLog({devices}); } catch(e) {errorLog(e)} return devices; } import(subject) { return assign(subject).to(this); } cache() { // this method has variable arity // if the first argument is a regular object (not an array) then the object is assigned to the server value // if the first argument is an array then there is no server value, and the array is assigned to the path value const args = Array.from(arguments); const server = (args.length && isObject(args[0])) ? args.shift() : null; // args.shift() produces a null value if args is empty const path = args.shift(); const state = setOrGet(this.state.cache, path, args.shift(), args.shift()); if (server && isFunction(server.emit)) { if (isEqual(path.length, 3)) { const domain = path[0]; const node = path[1]; const type = path[2]; server.emit(server, {[domain]:{[type]:{[node]:state}}}); } else if (isEqual(path.length, 2)) { const domain = path[0]; const type = path[1]; server.emit(server, {[domain]:{[type]:state}}); } else if (isEqual(path.length, 1)) { const domain = path[0]; server.emit(server, {[domain]:state}); } } return state; } nodes(...args) { const server = (args.length && isObject(args[0])) ? args.shift() : null; const path = args.shift(); const flag = args.shift(); const overwrite = args.shift(); if (server && isEqual(path.length, 3)) { const [domain, node, type] = path; isFunction(server.dispatch) && server.dispatch(server, {nodes:{[type]:{domain, node, flag}}}); } return setOrGet(this.state.nodes, path, flag, overwrite); } reply(response, result) { response.header('Content-Type', 'application/json'); response.send(result); } async ready() { // delay event until application ready return this.initialized ? true : await new Promise(resolve => this.queue.push(resolve)); } bind(listeners) { if (!Object(listeners)) {throw new Error('Required listeners object is empty');} let found = false; const {servers} = this; for (const [channel, response] of iterable(listeners)) { if (includes(channel).in(servers)) { const wss = servers[channel]; // bind custom request handler to SecureChannel https server if (isObject(wss)) { const {server} = wss; if (isFunction(Object(server).on)) {server.on('request', response);} else {throw new Error('Could not bind requests to route');} } found = true; } } if (!found) {throw new Error('Matching channel not found');} return this; } end(code) { activityLog('Shutting down all channels'); const {channels, servers} = this; for (const [channel, instance] of iterable(channels)) { const {devices} = instance; activityLog(`Closing ${channel} workers`); for (const workers of iterable(devices, VALUES)) {for (const worker of iterable(workers, VALUES)) {isFunction(Object(worker).destroy) && worker.destroy();}} const server = servers[channel]||{}; server.destroy && server.destroy(); } process.exit(code); } constructor(options) { const defaults = { channels:{}, servers:{}, state:{}, driverPath:DRIVERS, respawnTime:10 }; const application = this.import({...defaults, ...options}); // ensure that required root properties exist in state object for (const key of ['cache', 'nodes']) {initKey(this.state, key);} // append chain function to native methods this.chain = chain; // create ready queue this.queue = []; const {channels, servers, state} = this; const signalReady = () => { if (!this.initialized) { for (const nodes of iterable(state.nodes, VALUES)) { for (const {ready, error} of iterable(nodes, VALUES)) { if (!ready && !error) {return false;} } } this.initialized = true; while (0 < this.queue.length) { const ready = this.queue.pop(); isFunction(ready) && ready(true); } activityLog('server initialized'); } }; function iteratorFactory(socket) { return (handler, message) => handler.call(socket, message); } // routes message to correct handler based on metadata envelope function walk(handlers, data, iterator) { for (const [domain, state] of iterable(data)) { if (includes(domain).in(handlers)) { for (const [type, message] of iterable(state)) { if (includes(type).in(handlers[domain])) { const handler = handlers[domain][type]; isFunction(handler) && iterator(handler, message); } } } } } const workers = { // worker methods run under the global channel context and broadcast to all sockets listening to the channel spawn(channel, domain, node, workers) { this.channel = channel; const {sources, sinks} = channels[channel]; const {state} = application; application.nodes([domain, node], {connected:false, error:false, ready:false}); const listen = type => { // some tests can be skipped for the collector method since the loop calling the listen function is walking the same source object const collector = sources[domain][type]; // a corresponding emitter method may not exist if an application does not need to echo a particular data type to clients const emitter = includes([domain, type]).in(sinks) && sinks[domain][type]; return async data => { if (isFunction(collector)) { // allow the collector method to complete before attempting to call a corresponding emitter await collector.call(this, {node, data}); // an emitter method should always fire after a corresponding collector method to ensure that clients are kept in sync if (isFunction(emitter)) { // the application.cache method will allocate cache storage in the process of walking the cache path // don't create storage here for message types that don't need to be cached by the application // allow the application to create cache entries only for things that need it let cache; includes([domain, type]).in(state.cache) && (cache = application.cache([domain, type])); emitter.call(this, cache); } } }; }; // global message types appended to sources for all domains // these are reserved types and should not be overridden unless you know what you're doing! const routes = { flags:flags => { for (const [type, flag] of iterable(flags)) {application.nodes(this, [domain, node, type], flag);} // trigger any routines waiting for ready const {ready, error} = flags; (ready || error) && signalReady(); }, response:response => device.response(response) }; // decorate routes with listeners for defined domain sources for (const type of iterable(sources[domain], KEYS)) {routes[type] = listen(type);} debugLog({routes, [domain]:node}); // spawn a child process to manage device messaging and control const device = assign(workers[node]).to(new Driver(routes, channel, domain, node, this.respawnTime, this.driverPath)); workers[node] = device; }, // client -> core logic request({request, response}) { const {channel} = this; const {sources} = channels[channel]; if (includes('request').in(sources)) { const methods = sources.request; // wrap methods using chain function to capture and forward errors and normal responses for (const [type, method] of iterable(methods)) {includes(type).in(request) && chain(method.call(this, request[type]), response);} } }, // core logic -> driver async query(query) { const {channel} = this; for (const [domain, commands] of iterable(query)) { const {devices} = channels[channel]; if (includes(domain).in(devices)) { const workers = devices[domain]; for (const [command, args] of iterable(commands)) { let node, request; if (isObject(args)) { // accept query in the form of {[domain]:{[command]:{node, ...}}} node = args.node; delete args.node; request = {command, ...args}; } else { // accept query in the form of {[domain]:{[command]:node}} node = args; request = command; } if (node && isString(node) && includes(node).in(workers)) { const device = workers[node]; return await device.commit(request); } throw new Error(`node ${node} is invalid`); } throw new Error(`domain ${domain} is invalid`); } throw new Error('no command specified'); } throw new Error('no domain specified'); }, // driver -> core logic // this executes the source method on the passed data structure dispatch(socket, data) { const {channel} = this; const {sources} = channels[channel]; walk(sources, data, iteratorFactory(socket)); }, // core logic -> client // this executes the sink method on the passed data structure emit(socket, data) { const {channel} = this; const {sinks} = channels[channel]; walk(sinks, data, iteratorFactory(socket)); } }; for (const [channel, {sources, devices, events, connection}] of iterable(channels)) { if (!Object(devices)) {throw new Error('required devices object is empty');} if (!Object(connection)) {throw new Error('required connection object is empty');} // create https and ws channel server // decorate channel object with child worker communication methods and identity const server = servers[channel] = assign({channel, ...workers}).to(new SecureChannel(events)); const client = { // client methods run under a specific socket context and only respond to the socket from which a request arrived methods() { // expose backend request methods to the client frontend const methods = isObject(sources) && isObject(sources.request) ? iterable(sources.request, KEYS) : []; this.message('methods', {methods}); }, render() { // push the current application state to the client for (const [domain, types] of iterable(state.cache)) {server.emit(this, {[domain]:types});} for (const [domain, nodes] of iterable(state.nodes)) { for (const [node, flags] of iterable(nodes)) { for (const [type, flag] of iterable(flags)) { server.emit(server, {nodes:{[type]:{domain, node, flag}}}); } } } }, action(request) { if (isObject(request)) { const {signature} = request; // process user events const reflect = result => this.message('action', {signature, result}); const discard = () => {}; const response = signature ? reflect : discard; // call request event handler server.request({request, response}); } } }; // bind client events to channel bind(client).to(server); // start worker processes for (const [domain, workers] of iterable(devices)) { for (const node of iterable(workers, KEYS)) {server.spawn(channel, domain, node, workers);} } // start listeneng for events server.listen(connection); } activityLog('process context:', process.env.USER); } } return ({IPC, Passthrough, SecureChannel, Dispatcher, Driver, Queue, Response, Router}); })()); tonysyu/scrappyr-app import React from 'react'; // eslint-disable-line no-unused-vars import { render } from 'react-dom'; import Modal from 'react-modal'; import store from './store'; import ScrapList from './components/scrap_list'; import ScrapEditor from '../scrap_editor/components/editor'; import { createReactReduxApp } from '../utils/react_utils'; import * as actionCreators from './actions'; function mapStateToProps(state) { return { scrapEditor: state.scrapEditor, scraps: state.scraps, }; } class App extends React.Component { render() { const { isOpen } = this.props.scrapEditor; return (
    ); } } store.dispatch(actionCreators.receiveScraps(window.props.scraps)); const reactReduxApp = createReactReduxApp(App, store, mapStateToProps, actionCreators); render(reactReduxApp, document.getElementById('react-scrap-list')); /*! * gulp-format-md * * Copyright (c) 2015, . * Licensed under the MIT License. */ 'use strict'; const through = require('through2'); const middleware = require('./middleware'); module.exports = config => { let fn = middleware(config); return through.obj((file, enc, next) => fn(file, next)); }; gentlyawesome/globalcitydata1-10 import React from 'react'; import { graphql } from 'gatsby'; import { withStyles } from '@material-ui/core/styles'; import { Typography } from '@material-ui/core'; import withRoot from '../utils/withRoot'; // Components import Container from '../components/container'; import Hero from '../components/hero'; import Layout from '../components/layout'; import SEO from '../components/seo'; import Markdown from '../components/markdown'; import ContactForm from '../components/contact/contactForm'; const styles = { msg: { textAlign: 'center', fontSize: '1.3rem', margin: '0 auto', maxWidth: '700px', }, }; const Contact = ({ data, showProgress, classes }) => { const { name, body, backgroundImage } = data.contentfulPage; const { html } = body ? body.childMarkdownRemark : null; return ( {html && ( {html} )} ); }; export default withRoot(withStyles(styles)(Contact)); export const query = graphql` query { contentfulPage(identifier: { eq: "contact" }) { name body { childMarkdownRemark { html } } backgroundImage { fluid(maxWidth: 2000) { ...GatsbyContentfulFluid_withWebp } } } } `; const schema = require('./notes-schema.js'); class Note { constructor () { } get(category) { // const category = query.category; if (category) { return schema.find( { category }); } else { return schema.find(); } } create(note) { const newNote = new schema(note); return newNote.save() } update(_id, note) { // console.log('in update',_id, note); return schema.findByIdAndUpdate(_id, note, { new: true}); } delete(_id) { return schema.findByIdAndDelete(_id); } } module.exports = Note;/* * @author */ 'use strict'; const assert = require('assert'); const Request = require('../../src/Request'); const asserts = require('../../src/testTools/asserts'); describe('asserts', function () { describe('isText()', function () { it('should return true, only when its a text message ', function () { assert.ok(asserts.isText(Request.text(123, 'hello')), 'this should be text'); const res = asserts.isText(Request.quickReply(123, 'hello'), false); assert.ok(!res, 'this should not be text'); assert.throws(() => { asserts.isText(Request.quickReply(123, 'hello')); }); }); }); describe('genericTemplate()', function () { it('should should fail, when bad data are tested', function () { assert.throws(() => { asserts.genericTemplate({}); }); }); it('should should fail, when bad data are tested', function () { const data = { message: { attachment: { type: 'template', payload: { template_type: 'any', elements: [] } } } }; assert.strictEqual(asserts.genericTemplate(data, 1, false), false); assert.throws(() => { asserts.genericTemplate(data, 1); }); }); it('should should fail, when bad data are tested', function () { const data = { message: { attachment: { type: 'template', payload: { template_type: 'generic', elements: [] } } } }; assert.strictEqual(asserts.genericTemplate(data, null, false), true); assert.strictEqual(asserts.genericTemplate(data, 1, false), false); assert.throws(() => { asserts.genericTemplate(data, 1); }); }); }); describe('buttonTemplate()', function () { it('should should fail, when bad data are tested', function () { assert.strictEqual(asserts.buttonTemplate({}, 1, null, false), false); assert.throws(() => { asserts.buttonTemplate({}, 'text'); }); }); it('should should fail, when bad data are tested', function () { const data = { message: { attachment: { type: 'template', payload: { template_type: 'any', buttons: [] } } } }; assert.strictEqual(asserts.buttonTemplate(data, 'text', 1, false), false); assert.throws(() => { asserts.buttonTemplate(data, 'text', 1); }); }); it('should should fail, when bad data are tested', function () { const data = { message: { attachment: { type: 'template', payload: { template_type: 'button', text: 'text', buttons: [] } } } }; assert.strictEqual(asserts.buttonTemplate(data, 'text', null, false), true); assert.strictEqual(asserts.buttonTemplate(data, 'text', 1, false), false); assert.strictEqual(asserts.buttonTemplate(data, 'bla', 0, false), false); assert.throws(() => { asserts.buttonTemplate(data, 1); }); }); }); }); 1-10 var searchData= [ ['size',['size',['../structqueue__t.html#a83a13b888f9d4ef127d706559818b779',1,'queue_t']]] ]; window.alpine = {}; window.alpine.filter = function() { return { country:'', planetype:'', location:'', filterNotification: '', currentCount: '', updateResultsCount: function() { this.currentCount = [...document.querySelectorAll('.js-talk')] .filter(talk => window.getComputedStyle(talk).display !== 'none') .length; this.filterNotification = this.currentCount ? `${this.currentCount} ${this.currentCount === 1 ? 'talk' : 'talks'} found.` : `No talks found. Try to change your filters!`; } } }import parser from 'cheerio-without-node-native' import newsParser from '../community' export default function (html) { // const $ = parser.load(html, { // decodeEntities: true // }) const $ = parser.load(html) const result = [] $('ul.newlist li').each(function (i, elem) { const $this = $(this) const img = $this.find('img').attr('src') const text = $this.text() const arr = text.split('\n').map(item => item.replace(/\t/g, '').trim()).filter(item => item) const href = $this.find('a.touch').attr('href') || '' const matched = href.match(/\d+/) const type = href.includes('/gene/') ? 'gene' : 'community' const id = matched ? matched[0] : arr[1] + arr[2] // console.log(arr) const mock = { count: arr.slice().pop(), views: 1, title: arr.slice(0, -3).join('\n'), psnid: arr.slice(0, -2).pop(), date: arr.slice(0, -1).pop(), avatar: img, id, type, newsType: type, thumbs: Array.from($this.find('.thumb img').map(function(){ return $(this).attr('src')})) } // console.log(mock) result.push(mock) }) return result } coderaiser/restboxlib/rest/delete.spec.js 'use strict'; const test = require('supertape'); const stub = require('@cloudcmd/stub'); const mockRequire = require('mock-require'); const {reRequire} = mockRequire; const restbox = require('../restbox'); const {request} = require('serve-once')(restbox); const pathDelete = './delete'; const pathRestbox = '../restbox'; const resolve = async () => {}; test('restbox: delete: no token', async (t) => { const {body} = await request.delete('/dropbox/fs/temp'); t.equal(body, 'token should be a string!', 'should return error message'); t.end(); }); test('restbox: delete: dropbox.remove', async (t) => { const remove = stub(resolve); mockRequire('@cloudcmd/dropbox', { remove, }); reRequire(pathDelete); const restbox = reRequire(pathRestbox); const {request} = reRequire('serve-once')(restbox); const token = 'hello'; const options = { token, }; await request.delete('/dropbox/fs/', { options, }); t.calledWith(remove, [token, '/'], 'should call remove with token'); t.end(); }); test('restbox: delete: root: dropbox.remove', async (t) => { const remove = stub(resolve); mockRequire('@cloudcmd/dropbox', { remove, }); reRequire(pathDelete); const restbox = reRequire(pathRestbox); const {request} = reRequire('serve-once')(restbox); const token = 'hello'; const options = { token, root: '/tmp', }; await request.delete('/dropbox/fs/', { options, }); t.calledWith(remove, [token, '/tmp/'], 'should call remove with token'); t.end(); }); test('restbox: delete', async (t) => { const remove = stub(resolve); mockRequire('@cloudcmd/dropbox', { remove, }); reRequire(pathDelete); const restbox = reRequire(pathRestbox); const {request} = reRequire('serve-once')(restbox); const token = 'hello'; const options = { token, }; const {body} = await request.delete('/dropbox/fs/', { options, }); t.equal(body, 'delete: ok("/")', 'should equal'); t.end(); }); test('restbox: delete: dropbox.remove: files', async (t) => { const operate = stub(resolve); mockRequire('./common/operate', operate); reRequire(pathDelete); const restbox = reRequire(pathRestbox); const {remove} = require('@cloudcmd/dropbox'); const {request} = reRequire('serve-once')(restbox); const token = 'hello'; const options = { token, prefix: '', }; const files = [ '1.txt', '2.txt', ]; await request.delete('/fs/?files', { options, body: files, }); t.ok(operate.calledWith(remove, token, '/', files), 'should call remove with token'); t.end(); }); /** * UndoManager.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { var Dispatcher = tinymce.util.Dispatcher; /** * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed. * * @class tinymce.UndoManager */ tinymce.UndoManager = function(editor) { var self, index = 0, data = [], beforeBookmark; function getContent() { // Remove whitespace before/after and remove pure bogus nodes return tinymce.trim(editor.getContent({format : 'raw', no_events : 1}).replace(/]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\/span>/g, '')); }; return self = { /** * State if the user is currently typing or not. This will add a typing operation into one undo * level instead of one new level for each keystroke. * * @field {Boolean} typing */ typing : false, /** * This event will fire each time a new undo level is added to the undo manager. * * @event onAdd * @param {tinymce.UndoManager} sender UndoManager instance that got the new level. * @param {Object} level The new level object containing a bookmark and contents. */ onAdd : new Dispatcher(self), /** * This event will fire when the user make an undo of a change. * * @event onUndo * @param {tinymce.UndoManager} sender UndoManager instance that got the new level. * @param {Object} level The old level object containing a bookmark and contents. */ onUndo : new Dispatcher(self), /** * This event will fire when the user make an redo of a change. * * @event onRedo * @param {tinymce.UndoManager} sender UndoManager instance that got the new level. * @param {Object} level The old level object containing a bookmark and contents. */ onRedo : new Dispatcher(self), /** * Stores away a bookmark to be used when performing an undo action so that the selection is before * the change has been made. * * @method beforeChange */ beforeChange : function() { beforeBookmark = editor.selection.getBookmark(2, true); }, /** * Adds a new undo level/snapshot to the undo list. * * @method add * @param {Object} l Optional undo level object to add. * @return {Object} Undo level that got added or null it a level wasn't needed. */ add : function(level) { var i, settings = editor.settings, lastLevel; level = level || {}; level.content = getContent(); // Add undo level if needed lastLevel = data[index]; if (lastLevel && lastLevel.content == level.content) return null; // Set before bookmark on previous level if (data[index]) data[index].beforeBookmark = beforeBookmark; // Time to compress if (settings.custom_undo_redo_levels) { if (data.length > settings.custom_undo_redo_levels) { for (i = 0; i < data.length - 1; i++) data[i] = data[i + 1]; data.length--; index = data.length; } } // Get a non intrusive normalized bookmark level.bookmark = editor.selection.getBookmark(2, true); // Crop array if needed if (index < data.length - 1) data.length = index + 1; data.push(level); index = data.length - 1; self.onAdd.dispatch(self, level); editor.isNotDirty = 0; return level; }, /** * Undoes the last action. * * @method undo * @return {Object} Undo level or null if no undo was performed. */ undo : function() { var level, i; if (self.typing) { self.add(); self.typing = false; } if (index > 0) { level = data[--index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.beforeBookmark); self.onUndo.dispatch(self, level); } return level; }, /** * Redoes the last action. * * @method redo * @return {Object} Redo level or null if no redo was performed. */ redo : function() { var level; if (index < data.length - 1) { level = data[++index]; editor.setContent(level.content, {format : 'raw'}); editor.selection.moveToBookmark(level.bookmark); self.onRedo.dispatch(self, level); } return level; }, /** * Removes all undo levels. * * @method clear */ clear : function() { data = []; index = 0; self.typing = false; }, /** * Returns true/false if the undo manager has any undo levels. * * @method hasUndo * @return {Boolean} true/false if the undo manager has any undo levels. */ hasUndo : function() { return index > 0 || this.typing; }, /** * Returns true/false if the undo manager has any redo levels. * * @method hasRedo * @return {Boolean} true/false if the undo manager has any redo levels. */ hasRedo : function() { return index < data.length - 1 && !this.typing; } }; }; })(tinymce); 1-10 'use strict'; var isValid = require('is-valid-app'); var middleware = require('./lib/middleware'); var utils = require('./lib/utils'); module.exports = function(app) { if (!isValid(app, 'updater-verb')) return; app.task('verb', function() { var verbmd = app.options.verbmd || '.verb*.md'; var filename = app.options.file || '.verb.md'; return app.src(verbmd) .pipe(utils.through.obj(function(file, enc, next) { utils.del(file.path, function(err, files) { if (err) { next(err); return; } if (file.basename !== filename && app.options.silent !== true) { app.log.success('renamed', file.relative); } file.basename = filename; next(null, file); }); })) .pipe(utils.series([ middleware.lintDeps, middleware.htmlComments, middleware.install, middleware.related(app.base), middleware.reflinks(app.base), middleware.travis(app.base), middleware.jscomments, middleware.license, middleware.whitespace, middleware.toGithubUrl ])) .pipe(app.dest(app.cwd)); }); app.task('default', ['verb']); }; export const ReactionIcons = { "approve": "smiling", "neutral": "indifferent", "disapprove": "angry" } export const Reactions = ["Approve", "Neutral", "Disapprove"]; module.exports = { reactionIcons: ReactionIcons, reactions: Reactions }; bardawilpeter/employers import React from 'react'; import { NavLink } from 'react-router-dom'; import PropTypes from 'prop-types'; import Logo from '../../Logo/Logo'; import NavigationItems from '../NavigationItems/NavigationItems'; import './MainNavigation.css'; const propTypes = { isAuth: PropTypes.oneOfType([PropTypes.bool, PropTypes.element]), onLogout: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), onHandle: PropTypes.oneOfType([PropTypes.func, PropTypes.element]) }; const defaultProps = { isAuth: false, onLogout: () => {}, onHandle: () => {} }; const mainNavigation = ({ isAuth, onLogout, onHandle }) => (
    ); mainNavigation.propTypes = propTypes; mainNavigation.defaultProps = defaultProps; export default mainNavigation; const createScanByType = receivers => (state, { type, ...rest }) => { for (let key in receivers) { if (!receivers.hasOwnProperty(key)) { continue; } if (key !== type) { continue; } return receivers[key](state, rest); } return state; }; export function scanByType(receivers, ...rest) { return this.scan(createScanByType(receivers), ...rest); } export default createScanByType; hypocore/ChinaSeas // -------------------------------------------------- // // -------------------------------------------------- // // I manage the modals within the application. angular.module('myApp') .service( "modals", function( $rootScope, $q ) { // I represent the currently active modal window instance. var modal = { deferred: null, params: null }; // Return the public API. return({ open: open, params: params, proceedTo: proceedTo, reject: reject, resolve: resolve }); // --- // PUBLIC METHODS // --- // I open a modal of the given type, with the given params. If a modal // window is already open, you can optionally pipe the response of the // new modal window into the response of the current (cum previous) modal // window. Otherwise, the current modal will be rejected before the new // modal window is opened. function open( type, params, pipeResponse ) { var previousDeferred = modal.deferred; // Setup the new modal instance properties. modal.deferred = $q.defer(); modal.params = params; // We're going to pipe the new window response into the previous // window's deferred value. if ( previousDeferred && pipeResponse ) { modal.deferred.promise .then( previousDeferred.resolve, previousDeferred.reject ) ; // We're not going to pipe, so immediately reject the current window. } else if ( previousDeferred ) { previousDeferred.reject(); } // Since the service object doesn't (and shouldn't) have any direct // reference to the DOM, we are going to use events to communicate // with a directive that will help manage the DOM elements that // render the modal windows. // -- // NOTE: We could have accomplished this with a $watch() binding in // the directive; but, that would have been a poor choice since it // would require a chronic watching of acute application events. $rootScope.$emit( "modals.open", type ); return( modal.deferred.promise ); } // I return the params associated with the current params. function params() { return( modal.params || {} ); } // I open a modal window with the given type and pipe the new window's // response into the current window's response without rejecting it // outright. // -- // This is just a convenience method for .open() that enables the // pipeResponse flag; it helps to make the workflow more intuitive. function proceedTo( type, params ) { return( open( type, params, true ) ); } // I reject the current modal with the given reason. function reject( reason ) { if ( ! modal.deferred ) { return; } modal.deferred.reject( reason ); modal.deferred = modal.params = null; // Tell the modal directive to close the active modal window. $rootScope.$emit( "modals.close" ); } // I resolve the current modal with the given response. function resolve( response ) { if ( ! modal.deferred ) { return; } modal.deferred.resolve( response ); modal.deferred = modal.params = null; // Tell the modal directive to close the active modal window. $rootScope.$emit( "modals.close" ); } } ); src/xbrowsers/kekule.x.binData.js /** * @fileoverview * Cross browser binary data supporting. * * @author */ ///////////////////////////////////////////////////////////// // Cross browser binary data supporting ///////////////////////////////////////////////////////////// // TODO: unfinished X.BinData = function() { }; // $(function () { // var links = $('.sidebar-links > a'); // links.on('click', function () { // links.removeClass('selected'); // $(this).addClass('selected'); // }) // }); $(function(){ $("a").each(function(){ if ($(this).attr("href") == window.location.pathname){ $(this).addClass("selected"); } }); }); const { get } = require('httpie'); const url = require('url'); const timeout = 20; let chrome; let puppeteer; const isAWS = !!process.env.AWS_LAMBDA_FUNCTION_VERSION; if (isAWS) { // running on the Vercel platform. chrome = require('chrome-aws-lambda'); puppeteer = require('puppeteer-core'); } else { // running locally. puppeteer = require('puppeteer'); } const getBrowser = async () => { try { let browser if(isAWS) { browser = await puppeteer.launch({ args: [...chrome.args, '--hide-scrollbars', '--disable-web-security'], defaultViewport: chrome.defaultViewport, executablePath: await chrome.executablePath, headless: true, ignoreHTTPSErrors: true, }); } else { browser = await puppeteer.launch(); } return browser; } catch (err) { console.error(err); return null; } } const checkPwa = async (inputLink) => { inputLink = 'https://' + inputLink; // Step 1: launch browser and open a new page. const browser = await getBrowser() const page = await browser.newPage() // Step 2: Go to a URL and wait for a service worker to register. await page.goto(inputLink) const swTarget = await browser.waitForTarget(target => target.type() === 'service_worker', { timeout }) // Step 3: If a service worker is registered, print URL of SW file to the console if(swTarget && swTarget._targetInfo['url']) { const manifest = await page.$('[rel="manifest"]'); const manifestUrl = await manifest.evaluate(node => node.href); const { data } = await get(manifestUrl); let icon = ''; if(!data.name) throw new Error('Name is not existed in the manifest'); if(!data.icons || !data.icons.length) throw new Error('Icons are not existed in the manifest'); if(!data.icons[0].src) throw new Error('The Icon is not existed in the manifest'); icon = data.icons[0].src; const reHttps = /(http|https):\/\/([\w.]+\/?)\S*/; if(!reHttps.test(icon)){ icon = url.resolve(inputLink, icon); } // Step 4: Done. Close. await browser.close(); return { title: data.name, short_name: data.short_name, description: data.description, link: inputLink, icon: icon } } else { await browser.close() throw new Error('This is not a PWA'); } } export default function handler(req, res) { const { url } = req.query; if(url) { checkPwa(url) .then((output) => { res.status(200).json(output); }) .catch((err) => { res.status(500).json({ message: 'This is not a PWA', "error-message": err.message }); }) } else { res.status(500).json({ message: 'url is required' }); } }DannySalazar95/laravel-vue /******/ (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, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // 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 = 2); /******/ }) /************************************************************************/ /******/ ({ /***/ "./resources/js/helpers/index.js": /*!***************************************!*\ !*** ./resources/js/helpers/index.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports) { // // ─── INPUT ────────────────────────────────────────────────────────────────────── // window.auto_focus = function (name) { setTimeout(function () { $("input[name=".concat(name, "]")).focus(); $("textarea[name=".concat(name, "]")).focus(); }, 500); }; // // ─── DATE AND TIME ───────────────────────────────────────────────────────────────────── // window.get_current_year = function () { var today = new Date(); return today.getFullYear(); }; window.get_current_date = function () { var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; var yyyy = today.getFullYear(); if (dd < 10) dd = '0' + dd; if (mm < 10) mm = '0' + mm; return "".concat(yyyy, "-").concat(mm, "-").concat(dd); }; window.get_current_hour = function () { var today = new Date(); var hh = today.getHours(); var mm = today.getMinutes(); if (hh < 10) hh = '0' + hh; if (mm < 10) mm = '0' + mm; return "".concat(hh, ":").concat(mm); }; // // ─── ARRAY OBJECT ─────────────────────────────────────────────────────────────── // window.sort_array_object = function (items, name_field) { return items.sort(function (a, b) { if (a[name_field] > b[name_field]) { return 1; } if (a[name_field] < b[name_field]) { return -1; } return 0; }); }; // // ─── NUMBER ───────────────────────────────────────────────────────────────────── // window.is_float = function (n) { if (isNaN(n)) return false;else { var p_f = parseFloat(n); return p_f - p_f.toFixedDown(0) > 0; } }; // // ─── CONFIGURATION: message ───────────────────────────────────────────────────────────────────── // window.message = function (type, content) { var title = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; console.log("/resources/js/helpers/index.js: ".concat(content)); //window.Snotify[type](content, title) }; /***/ }), /***/ 2: /*!*********************************************!*\ !*** multi ./resources/js/helpers/index.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! /home/danny/code/Laravel/laravel-vue/resources/js/helpers/index.js */"./resources/js/helpers/index.js"); /***/ }) /******/ });// Copyright (c) Microsoft. All rights reserved. import React from "react"; import '../cellRenderer.css'; export const RuleStatusRenderer = ({ value, context: { t } }) => (
    { value ? t('rules.grid.enabled') : t('rules.grid.disabled') }
    ); greuze/got-server1-10 'use strict'; var http = require('http'), express = require('express'), morgan = require('morgan'), bodyParser = require('body-parser'), responseTime = require('response-time'), gameRoutes = require('./routes/game-routes'), orderRoutes = require('./routes/order-routes'); var server; /** * Trace requests. For debugging purposes. * * @param code HTTP Code to return. */ function tracer(req, res, next) { console.log('Method: %s\nPath: %s\nHeaders:\n\n%s\n\nBody:\n\n%s\n\n', req.method, req.path, JSON.stringify(req.headers, null, 4), JSON.stringify(req.body, null, 4) ); next(); } function start(traceRequests, callback) { if (traceRequests instanceof Function) { callback = traceRequests; traceRequests = false; } var port = 10429; var app = express(); app.set('port', port); app.disable('x-powered-by'); app.use(responseTime()); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json({ limit: '1kb' })); if (traceRequests) { app.use(morgan('combined')); app.use(tracer); } gameRoutes.registerRoutes(app); orderRoutes.registerRoutes(app); app.get('/ping', function(req, res) { res.status(200).json({uptime: process.uptime(), memory: process.memoryUsage(), version: process.version}); }); /* jshint unused:false, maxparams:4 */ app.use(function serverError(err, req, res, next) { console.error('error %j', err); console.error('stack %s', err.stack); res.status(err.statusCode || 500).send(err.message || ''); }); /* jshint unused:true */ if (server) { console.log('cs-proxy server already listening on port %s', app.get('port')); } else { server = http.createServer(app); server.listen(app.get('port'), function onstart() { console.log('cs-proxy server listening on port %s', app.get('port')); }); } callback(); } function stop(callback) { console.log('Stopping server'); server.close(function() { server = null; callback(); }); } exports.start = start; exports.stop = stop; PedroAzeredo-WebCoder/JavaScript-ES6- let nomes = [ {nome: 'Pedro', idade: 21}, {nome: 'Vítor', idade: 17}, {nome: 'patricia', idade: 48} ]; console.log(nomes.every(nome => nome.idade >= 18)); if(nomes.every(nome => nome.idade >= 18)){ console.log('TODOS SÃO MAIORES DE IDADE'); }else{ console.log('OPS ALGUEM É DE MENOR'); }courses/angular/ng-blur.directive.js angular.module('app').directive('ngBlur', function() { return { restrict: 'A', require: 'ngModel', link: function($scope, $element, $attrs, ngModel) { $element.on('blur', function() { if(ngModel.$invalid) { $element.addClass('error'); } else { $element.removeClass('error'); } }); } } }); amankkg/snowpack const path = require('path'); const {setupBuildTest, readFiles, stripWS} = require('../../test-utils'); const cwd = path.join(__dirname, 'build'); let files = {}; describe('import-json', () => { beforeAll(() => { setupBuildTest(__dirname); files = readFiles(cwd); }); it('imports in source file are transformed correctly', () => { expect(stripWS(files['/_dist_/index.js'])) .toEqual(`import testJsonData from './file.json.proxy.js'; import testJsonPkgData from '../web_modules/json-test-pkg/file.json.proxy.js'; console.log('loaded:', testJsonData, testJsonPkgData);`); }); it('local json file is built as expected', () => { expect(stripWS(files['/_dist_/file.json.proxy.js'])).toEqual(`let json = {"test":true}; export default json;`); }); it('npm package json file is imported as expected', () => { expect(stripWS(files['/web_modules/json-test-pkg/file.json.proxy.js'])) .toEqual(`let json = {"test-json-pkg":true}; export default json;`); }); }); Painel/js/index.js0 function Home() { window.location.href="home.html" }0 import { FETCH_ERROR, FETCH_START, FETCH_SUCCESS, INIT_URL, SIGNOUT_USER_SUCCESS, USER_DATA, USER_TOKEN_SET, } from "../../constants/ActionTypes"; import axios from "util/Api"; export const setInitUrl = (url) => { return { type: INIT_URL, payload: url, }; }; export const userSignIn = ({ email, password }) => { return (dispatch) => { dispatch({ type: FETCH_START }); axios .post("auth/login", { email: email, password: password, }) .then(({ data }) => { console.log("userSignIn: ", data); if (data.result) { localStorage.setItem( "token", JSON.stringify(data.token.access_token) ); axios.defaults.headers.common["Authorization"] = "Bearer " + data.token.access_token; dispatch({ type: FETCH_SUCCESS }); dispatch({ type: USER_TOKEN_SET, payload: data.token.access_token }); } else { dispatch({ type: FETCH_ERROR, payload: data.error }); } }) .catch(function (error) { dispatch({ type: FETCH_ERROR, payload: error.message }); console.log("Error****:", error.message); }); }; }; export const getUser = () => { return (dispatch) => { dispatch({ type: FETCH_START }); axios .post("auth/me") .then(({ data }) => { console.log("userSignIn: ", data); if (data.result) { dispatch({ type: FETCH_SUCCESS }); dispatch({ type: USER_DATA, payload: data.user }); } else { dispatch({ type: FETCH_ERROR, payload: data.error }); } }) .catch(function (error) { dispatch({ type: FETCH_ERROR, payload: error.message }); console.log("Error****:", error.message); }); }; }; export const userSignOut = () => { return (dispatch) => { dispatch({ type: FETCH_START }); axios .post("auth/logout") .then(({ data }) => { console.log("log out", data); if (data.result) { localStorage.removeItem("token"); dispatch({ type: FETCH_SUCCESS }); dispatch({ type: SIGNOUT_USER_SUCCESS }); } else { dispatch({ type: FETCH_ERROR, payload: data.error }); } }) .catch(function (error) { dispatch({ type: FETCH_ERROR, payload: error.message }); console.log("Error****:", error.message); }); }; }; import React, { Component } from 'react'; import { Button, Card, Select, Form } from 'semantic-ui-react' import { Link, Redirect } from 'react-router-dom' const options = [ { key: "1", text: '1',value: 1 }, { key: "2", text: '2',value: 2 }, { key: "3", text: '3', value: 3 }, { key: "4", text: '4', value: 4 }, { key: "5", text: '5', value: 5 }, { key: "6", text: '6', value: 6 }, { key: "7", text: '7', value: 7 }, { key: "8", text: '8', value: 8 }, { key: "9", text: '9', value: 9 }, { key: "10", text: '10', value: 10 }, ] class Stakeholder extends Component { constructor() { super() this.state = { power: '', interest: '', positivity: '', strategy: '' } } ratingField = (event) => { const newRatings = event.target.value this.setState({ [event.target.name]: newRatings }) } handleNumChange = (event, data) => { this.setState({ [data.name]: data.value }) } onHandleRating = (event) => { this.props.handleRating(this.props.stakeholder, this.state) this.setState({ power: '', interest: '', positivity: '' }) } // // viewStakeholder = (event) => { // const stakeholder_id = this.props.stakeholder.id // const project_id = this.props.project_id // // return `/manage_stakeholder/${stakeholder_id}/project/${project_id}` // } // newStakeholder = (event) => { // event.preventDefault() // fetch(railsAPI, { // method: POST, // headers : new Headers(), // body:JSON.stringify, // name: , // title: , // alias: , // power: , // interest: , // positivity: // }) // (res.json => res.json) // .then(console.log 'Done') // // } viewStakeholder = (event) => { // some action... // then redirect this.setState({redirect: true}); } render() { const { name, title, alias, ratings } = this.props.stakeholder const stakeholder_id = this.props.stakeholder.id const id = this.props.project_id const strategy = this.props.stakeholder.strategy return ( {name} {alias} {title}
    ) } } export default Stakeholder; 0 class RadioField extends Field { getDisplayValue(row) { const displayColumn = this.getAttr('displayColumn'); let value = null; if (row[displayColumn]) { try { value = Helper.decodeValue(row[displayColumn]); } catch (err) { console.log('cannot parse:', row[displayColumn]); throw err; } } else { value = displayColumn; value = value.replace(/\{([\w\.]+)\}/g, (text, name) => { return row.hasOwnProperty(name) ? (row[name] || '') : text; }); } return value; } getValueValue(row) { const valueColumn = this.getAttr('valueColumn'); if (!row[valueColumn]) { throw new Error('no valueColumn in ComboBox data source'); } return Helper.decodeValue(row[valueColumn]); } getDataSource() { const name = this.getAttr('dataSourceName'); if (!name) throw new Error(`${this.getFullName()}: no dataSourceName`); if (this.getForm().getDataSource(name)) { return this.getForm().getDataSource(name); } if (this.getPage().getDataSource(name)) { return this.getPage().getDataSource(name); } if (this.getApp().getDataSource(name)) { return this.getApp().getDataSource(name); } throw new Error(`${this.getFullName()}: no data source: ${name}`); } findRowByRawValue(rawValue) { const valueColumn = this.getAttr('valueColumn'); return this.getDataSource().getRows().find(row => row[valueColumn] === rawValue); } } gadge/aryth import { intExpon } from '@aryth/math' import { deco } from '@spare/deco' import { logger, xr } from '@spare/logger' import { niceScale } from '../src/niceScale' const candidates = [ { min: -0.05, max: +0.15 }, { min: 0, max: 1 }, { min: 0, max: 10 }, { min: 3.14, max: 9.99 }, { min: -3.14, max: 12 }, { min: 13.14, max: 79.9 }, { min: 14024, max: 17756 }, { min: 13299, max: 13304 }, ] for (let { min, max } of candidates) { const expon = intExpon(min) let n = min / ( 10 ** expon ) n = ~~( n * 10 ) * ( 10 ** ( expon - 1 ) ) xr() .input(deco({ min, max })) .niceScale(deco(niceScale.call({ ticks: 6 }, { min, max }))) .n(n) |> logger } import { getCachedVersions } from './cache.js' // When offline, we try to reuse cached versions if any is available. // We do this even if `cache` option is `false`. export const handleOfflineError = async function (error) { if (!isOffline(error)) { throw error } const { cachedVersions } = await getCachedVersions() if (cachedVersions === undefined) { throw error } return cachedVersions } // On Windows, offline errors are the same as wrong `mirror` option errors. // Since we cannot distinguish them, we also use offline cache when `mirror` // option is invalid. const isOffline = function ({ message }) { return message.includes(OFFLINE_ERROR_MESSAGE) } const OFFLINE_ERROR_MESSAGE = 'getaddrinfo' import { ReactComponent as GlobalIcon } from '../../../assets/Globe.svg'; export const SideBarData = [ { link: '/questions', icon: , text: 'Stack Overflow', }, { link: '/tags', text: 'Tags', }, { link: '/users', text: 'Users', }, { link: '/jobs', text: 'Jobs', } ]0 import "../css/main.css"; window.AudioContext = window.AudioContext || window.webkitAudioContext; (() => { // Global AudioContext const audioContext = new AudioContext(); // State of the music player const player = { fileLoaded: false, buffer: null, source: null, startTime: 0, position: 0, isPlaying: false, }; const state = { checkpoints: [], }; const storageKeys = { checkpoints: "_choreo_checkpoints_", }; // Reference to HTML elements const messageEl = document.querySelector(".message-box"); const fileSelectEl = document.querySelector(".fileSelect"); const songEl = document.querySelector(".song"); const songNameEl = document.querySelector(".song__name"); const controls = { playEl: document.querySelector(".controls__play"), stopEl: document.querySelector(".controls__stop"), addEl: document.querySelector(".controls__add"), timeCurrentEl: document.querySelector(".controls__time-current"), timeTotalEl: document.querySelector(".controls__time-total"), indicatorContainerEl: document.querySelector(".controls__indicator-container"), indicatorBarEl: document.querySelector(".controls__indicator-bar"), }; const checkpointsList = document.querySelector(".checkpoints__list"); const titlesList = document.querySelector(".titles__list"); const initializeChoreoPlayer = () => { // Bind Events controls.playEl.addEventListener("click", handlePlayClick, false); controls.stopEl.addEventListener("click", handleStopClick, false); controls.addEl.addEventListener("click", handleAddClick, false); controls.indicatorContainerEl.addEventListener("click", handleIndicatorClick, false); fileSelectEl.addEventListener("change", handleFileSelected, false); if (isStorageAvailable) { const prevTitles = getPreviousTitles(); displayPreviousTitles(prevTitles); const checkpoints = getSavedCheckpoints(); displayCheckpoints(checkpoints); state.checkpoints = checkpoints; } }; /** * Handles the selection of a new audio file * @param {Event} e */ const handleFileSelected = (e) => { const file = e.target.files[0]; if (!file) { return; } displayMessage(`Loading file "${file.name}"...`); loadFile(file) .then(decode) .then((audioBuffer) => { audioFileLoaded({ filename: file.name, buffer: audioBuffer }); clearMessage(); }) .catch((e) => { displayMessage("Could not load audio file! Please select a different file.", "error"); console.error(e); }); }; /** * Loads the given file as an array buffer * @param {File} file */ const loadFile = (file) => new Promise((resolve, reject) => { try { const reader = new FileReader(); reader.onload = () => { resolve(reader.result); }; reader.readAsArrayBuffer(file); } catch (e) { reject(e); } }); /** * Creates an AudioSource from the given buffer and connects it to the AudioContext. * @param {AudioBuffer} buffer */ const connectAudioContext = (buffer) => { let source = audioContext.createBufferSource(); source.buffer = buffer; source.connect(audioContext.destination); return source; }; /** * Decodes the given array buffer into an AudioBuffer * @param {ArrayBuffer} arrayBuffer */ const decode = (arrayBuffer) => audioContext.decodeAudioData(arrayBuffer); const audioFileLoaded = ({ filename, buffer }) => { player.fileLoaded = true; player.buffer = buffer; storeTitle(filename, buffer); songEl.classList.add("song--selected"); songNameEl.innerHTML = filename; controls.timeTotalEl.innerHTML = secondsToTime(player.buffer.duration); }; /** * Converts the given seconds to a time string in the format "mm:ss" * @param {Number} totalSeconds */ const secondsToTime = (totalSeconds) => { const minutes = parseInt(totalSeconds / 60, 10); const seconds = parseInt(totalSeconds - (minutes * 60), 10); return `${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`; }; /** * Gets the current position in the song */ const getPosition = () => { return player.isPlaying ? (audioContext.currentTime - player.startTime) : player.position; }; /** * Updates the progress bar and the time display */ const updateTimeDisplay = () => { const position = getPosition(); const progress = Math.min(position / player.buffer.duration, 1); controls.indicatorBarEl.style.transform = `scaleX(${progress})`; controls.timeCurrentEl.innerHTML = secondsToTime(position); player.position = position; if (progress === 1) { stopPlayer(); } if (player.isPlaying) { requestAnimationFrame(updateTimeDisplay); } }; /** * Clears the currently displayed message and hides the message-box. */ const clearMessage = () => { messageEl.innerHTML = ""; messageEl.classList.remove("message-box--error"); messageEl.classList.remove("message-box--info"); messageEl.classList.add("message-box--hidden"); }; /** * Displays an info or error message to the user. * @param {string} message * @param {string} type */ const displayMessage = (message, type = "info") => { clearMessage(); messageEl.innerHTML = message; messageEl.classList.remove("message-box--hidden"); messageEl.classList.add(`message-box--${type}`); }; const stopPlayer = () => { player.isPlaying = false; player.position = 0; if (player.source) { player.source.stop(); player.source = null; } controls.playEl.classList.remove("controls__play--playing"); }; // TODO: IndexDB const isStorageAvailable = true; // typeof window.localStorage !== "undefined"; const storeTitle = (name, data) => { if (!isStorageAvailable) { return; } console.log(name, data); // TODO: IndexDB // const listKey = "_choreo_titles_" // const listOfTitlesStr = localStorage.getItem(listKey) || "[]"; // const listOfTitles = JSON.parse(listOfTitlesStr); // const newListOfTitles = [...listOfTitles, name]; // localStorage.setItem(listKey, JSON.stringify(newListOfTitles)); // localStorage.setItem(`choreo_title_${name}`, JSON.stringify(data)); }; /** * Loads a previous title from storage by its name * @param {string} name */ // const loadTitle = (name) => { // if (!isStorageAvailable) { // return; // } // console.log(name); // // TODO: IndexDB // }; /** * Get a list of stored previous titles */ const getPreviousTitles = () => { if (!isStorageAvailable) { return []; } // TODO: IndexDB // return localStorage.getItem("_choreo_titles_") || []; return []; }; /** * Display a list of previous titles * @param {Array} prevTitles */ const displayPreviousTitles = (prevTitles) => { titlesList.innerHTML = prevTitles.map(renderPreviousTitlesItem).join(""); }; /** * Renders a single previous title element * @param {string} title */ const renderPreviousTitlesItem = (title) => `
  • ${title} x
  • `; const saveCheckpoint = (checkpoint) => { const currentCheckpoints = getSavedCheckpoints(); const checkpoints = [...currentCheckpoints, checkpoint]; localStorage.setItem(storageKeys.checkpoints, JSON.stringify(checkpoints)); }; const getSavedCheckpoints = () => { if (!isStorageAvailable) { return []; } return JSON.parse(localStorage.getItem(storageKeys.checkpoints)) || []; }; /** * Display a list of checkpoints * @param {Array} checkpoints */ const displayCheckpoints = (checkpoints) => { checkpointsList.innerHTML = checkpoints.map(renderCheckpointItem).join(""); }; /** * Renders a single checkpoint element * @param {string} checkpoint */ const renderCheckpointItem = (checkpoint) => `
  • ${checkpoint} P X
  • `; const playFrom = (progress) => { // TODO: More defensive... const time = progress * player.buffer.duration; if (player.isPlaying) { player.source.stop(); player.position = time; player.startTime = audioContext.currentTime - player.position; player.source = connectAudioContext(player.buffer); player.source.start(audioContext.currentTime, player.position); } else { player.position = time; } updateTimeDisplay(); }; /** * Handle click on play/pause button */ const handlePlayClick = () => { if (!player.fileLoaded) { return; } player.isPlaying = !player.isPlaying; controls.playEl.classList.toggle("controls__play--playing", player.isPlaying); if (player.isPlaying) { player.position = player.position || 0; player.startTime = audioContext.currentTime - player.position; player.source = connectAudioContext(player.buffer); player.source.start(audioContext.currentTime, player.position); updateTimeDisplay(); } else { player.source.stop(); player.source = null; } }; /** * Handle click on stop button */ const handleStopClick = () => stopPlayer(); /** * Handle click on add button */ const handleAddClick = () => { const position = getPosition(); const progress = Math.min(position / player.buffer.duration, 1); const checkpoint = { label: secondsToTime(position), progress: progress, }; saveCheckpoint(checkpoint); // TODO: update list }; /** * Handle click anywhere on the indicator bar * @param {MouseEvent} e */ const handleIndicatorClick = (e) => { if (!player.fileLoaded) { return; } const containerRect = controls.indicatorContainerEl.getBoundingClientRect(); const containerWidth = containerRect.width; const offsetX = e.clientX - containerRect.x; const offset = Math.max(0, Math.min(containerWidth, offsetX)); const percentage = offset / containerWidth; playFrom(percentage); }; initializeChoreoPlayer(); })();module.exports = function(err, req, res, next) { console.log(err); console.log(err.name); res.status(500).json({ message: "Check server console" }); }; // // Copyright IBM Corp. 2020, 2020 // // This source code is licensed under the Apache-2.0 license found in the // LICENSE file in the root directory of this source tree. // 'use strict'; // cspell:words ENOAUDIT const util = require('util'); const exec = util.promisify(require('child_process').exec); const argv = process.argv.slice(2); const group = argv[0]; const level = argv[1]; let auditLevel; async function audit() { auditLevel = level ? ' --level ' + level : ''; const auditCommand = 'yarn audit --groups ' + group + auditLevel; console.log('Running audit using:', auditCommand); await exec(auditCommand); } audit().catch((err) => { // Failed to contact endpoint if (err && err.message && err.message.includes('code ENOAUDIT')) { console.log( 'audit stage has failed because of an error contacting the yarn audit endpoint, this will not fail the build!' ); process.exit(0); } // Report any vulnerabilities try { // If any entry in the table, this must be reported if (err.stdout.includes('Prototype Pollution')) { console.log(err.stdout); process.exit(1); } else { // If not table reported, we're good process.exit(0); } } catch (e) { console.log( 'audit stage failed due to an invalid error body! Error was: \n', e ); } process.exit(1); }); window.addEventListener("DOMContentLoaded",function(){ document.getElementById("loginform").addEventListener("submit",function(ev){ ev.preventDefault(); var username = document.getElementById("usernamenpt").value; var password = document.getElementById("passwordnpt").value; moodAPI.login(username, password).then(response => { if(response){ localStorage.setItem('jwt_token',JSON.stringify({'token': response.token, 'userId': response.data.userId})); if(document.referrer != '') window.location.replace(document.referrer); } else { var el = document.getElementById("badLogin"); el.innerHTML = "Login fehlgeschlagen"; el.style.display = 'block'; } }); }); }); Come2Daddy/pg-upmig /** @module pg-upmig */ const { Client, types } = require("pg"); const path = require("path"); const fs = require("fs"); /** * Connect to DB (create table if not exists) * @class * @classdesc * @param {Object} params Constructor arguments * @param {Object} params.client Custom database client * @param {Object} params.connection PG connection params * @param {Object} params.options Global options * @param {String} params.options.table Migrations table * @param {String} params.options.migrations Migrations path * @param {Boolean} params.options.transactionnal Whenever to use transaction for migrations * @param {String} params.options.queryMethod Client method name to query raw SQL * @param {String} params.options.connectMethod Client method name to connect * @param {String} params.options.endMethod Client method name to release connection * @param {String} params.options.resultKey Key to pluck from query result object * @param {String} params.options.steps Number of migration to perform * @param {String} params.options.to Timestamp of migration to reach * @param {Boolean} params.options.debug Enable debug mode */ class migration { constructor (params) { // Handles int types types.setTypeParser(20, "text", parseInt); types.setTypeParser(21, "text", parseInt); types.setTypeParser(23, "text", parseInt); types.setTypeParser(1700, "text", parseInt); // Handles date types types.setTypeParser(1082, "text", (date) => new Date(date)); types.setTypeParser(1083, "text", (date) => new Date(date)); types.setTypeParser(1114, "text", (date) => new Date(date)); types.setTypeParser(1184, "text", (date) => new Date(date)); types.setTypeParser(1266, "text", (date) => new Date(date)); this.isInit = false; this.isConnected = false; this.options = { table: process.env.UPMIG_TABLE||"pg_upmig", migrations: process.env.UPMIG_PATH||"./migrations", transactionnal: true, queryMethod: "query", connectMethod: "connect", endMethod: "end", resultKey: "rows", steps: 0, to: 0, debug: String(process.env.UPMIG_DEBUG).toLowerCase() === "true" }; try { const dotConfig = require(path.join(process.cwd(),".upmigrc.js")); this.options.migrations = dotConfig.migrations?dotConfig.migrations:this.options.migrations; this.options.table = dotConfig.table?dotConfig.table:this.options.table; } catch (error) { this._debug(error, 3); } if ((params||{}).options) { Object.assign(this.options, params.options); } // Sets custom database client if ((params||{}).client) { this.client = params.client; } // Sets default database client if (!this.client) { if ((params||{}).connection) { if (!params.connection.hasOwnProperty("ssl")) { params.connection.ssl= { rejectUnauthorized: String(process.env.UPMIG_REJECT).toLowerCase()==="true" }; } else if (typeof params.connection.ssl !== "boolean" && !params.connection.ssl.hasOwnProperty("rejectUnauthorized")) { params.connection.ssl["rejectUnauthorized"] = String(process.env.UPMIG_REJECT).toLowerCase()==="true"; } // Uses connection params this.client = new Client(params.connection); } else { // Try to connect with environment variables // At this point, if nothing is provided we let PG client rise errors const ssl = String(process.env.UPMIG_SSL).toLowerCase()==="false" ? false : {rejectUnauthorized: String(process.env.UPMIG_REJECT).toLowerCase()==="true"}; this.client = new Client({ssl}); } } } /** * Reports debug messages && errors * @memberof migration * @private * @param {*} msg Message or error * @param {Number} level Debug level [1-4] * @returns {void} */ _debug (msg, level = 4) { const levels = [null, "error", "warn", "log"]; if (this.options.debug === true) console[levels[level]||"log"].call(console, msg); } /** * Connects client * @memberof migration * @private * @async * @returns {void} */ async _connect () { if (!this.isConnected) { try { await this.client[this.options.connectMethod].call(this.client); } catch (error) { //Client has been connected already this._debug(error, 1); } } this.isConnected = true; } /** * Performs query * @memberof migration * @private * @async * @param {...*} args Query method arguments * @returns {Promise} Query promise */ _query () { try { return this.client[this.options.queryMethod].apply(this.client, [...arguments]); } catch (error) { this._debug(error, 1); throw(error); } } /** * Plucks key form query's result * @memberof migration * @private * @param {*} result Query's result * @returns {Object} Array of objects */ _pluck (result) { if (result instanceof Array) { return result; } if (typeof(result) === "object" && result) { if (result[this.options.resultKey]) { return result[this.options.resultKey]; } } return []; } /** * Initializes migration * @memberof migration * @public * @async * @param {Object} options Options * @param {String} options.migrations Migrations path * @param {String} options.table Migrations table * @param {Boolean} options.transactionnal Whenever to use transaction for migrations * @param {String} options.queryMethod Client method name to query raw SQL * @param {String} options.connectMethod Client method name to connect * @param {String} options.endMethod Client method name to release connection * @param {String} options.resultKey Key to pluck from query result object * @param {String} options.steps Number of migration to perform * @param {String} options.to Timestamp of migration to reach * @param {Boolean} options.debug Enable debug mode * @returns {ThisType} */ async init (options) { Object.assign(this.options, options); // Skip init if already done if (this.isInit) return true; await this._connect(); // Creates directories if needed try { await fs.promises.mkdir(this.options.migrations); await fs.promises.mkdir(path.join(this.options.migrations, "sql")); } catch (error) { this._debug(error, 2); } if (!fs.existsSync(path.join(this.options.migrations, "template.stub"))) { await fs.promises.writeFile(path.join(this.options.migrations, "template.stub"), `const fs = require("fs"); const path = require("path"); const file = path.basename(__filename, ".js"); const filePath = path.dirname(__filename); module.exports = async (client, method) => { const sql = await fs.promises.readFile(path.join(filePath, \`./sql/\${file}.sql\`), {encoding: "utf8"}); return client[method].call(client, sql); } `, {encoding: "utf8"}); } await this._query(`CREATE TABLE IF NOT EXISTS ${this.options.table} ( date timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP, name varchar(255) NOT NULL, ts bigint NOT NULL, filename text NOT NULL );`); this.isInit = true; return true; } /** * Lists migration files ordered by name ASC * @memberof migration * @private * @async * @returns {Object} Array of objects - All migration files (including done and pending) */ async _files () { // Reads migrations directory and filter files by name const files = await fs.promises.readdir(this.options.migrations); const filtered = files.filter(file => /^[0-9]+_.+\.js$/.test(file)); // Creates detailed file list const infos = []; for (let file of filtered) { infos.push({ "filename": path.basename(file, ".js"), "ts": parseInt(file.match(/^([0-9]+)_.+$/)[1]), "name": file.match(/^[0-9]+_(.+)+\.js$/)[1] }); } // Sort file list by name ascending infos.sort((a, b) => a.ts - b.ts); return infos; } /** * Lists pending migration based on last successful migration * @memberof migration * @public * @async * @param {Object} options Options * @param {String} options.migrations Migrations path * @param {String} options.table Migrations table * @param {Boolean} options.transactionnal Whenever to use transaction for migrations * @param {String} options.queryMethod Client method name to query raw SQL * @param {String} options.connectMethod Client method name to connect * @param {String} options.endMethod Client method name to release connection * @param {String} options.resultKey Key to pluck from query result object * @param {String} options.steps Number of migration to perform * @param {String} options.to Timestamp of migration to reach * @param {Boolean} options.debug Enable debug mode * @returns {Object} Result * pending: Array of objects - Available pending migration files * history: String - pending number / done number */ async pending (options = null) { // Extends instance options Object.assign(this.options, options); await this.init(); const files = await this._files(); const latest = this._pluck(await this._query(`SELECT ts, name FROM ${this.options.table} ORDER BY ts DESC;`)); let idx = 0; // Find the first file with a timestamp greater than the last successful migration if (latest.length) { idx = files.findIndex(file => file.ts > latest[0].ts); } const pending = idx >= 0 ? files.slice(idx, files.length) : []; let last = null; // Find the last migration if (latest.length) { last = latest[0]; } return {pending, history: latest.length, last}; } /** * Performs all pending migrations * @memberof migration * @public * @async * @param {Object} options Options * @param {String} options.migrations Migrations path * @param {String} options.table Migrations table * @param {Boolean} options.transactionnal Whenever to use transaction for migrations * @param {String} options.queryMethod Client method name to query raw SQL * @param {String} options.connectMethod Client method name to connect * @param {String} options.endMethod Client method name to release connection * @param {String} options.resultKey Key to pluck from query result object * @param {String} options.steps Number of migration to perform * @param {String} options.to Timestamp of migration to reach * @param {Boolean} options.debug Enable debug mode * @returns {Object} Array of object - Migration files used */ async up (options) { // Extends instance options Object.assign(this.options, options); await this.init(); const files = await this.pending(this.options); let step = 0; try { // Starts transactionnal if (this.options.transactionnal) await this._query("BEGIN;"); for (let file of files.pending) { // First of steps or target to exit loop if (this.options.steps && this.options.steps <= step) break; if (this.options.to && this.options.to < file.ts) break; // Loads migration const query = require(path.join(process.cwd(), this.options.migrations, `${file.filename}.js`)); await query(this.client, this.options.queryMethod); // Registers migration await this._query(`INSERT INTO ${this.options.table} (name, ts, filename) VALUES ('${file.name}', ${file.ts}, '${file.filename}');`); step++; } // Commit transaction if (this.options.transactionnal) await this._query("COMMIT;"); } catch (error) { this._debug(error, 1); await this._query("ROLLBACK;"); } return files.pending.slice(0, step); } /** * Generates new migration file * @memberof migration * @public * @async * @param {String} name Migration name * @param {Boolean} nosql Shoulds it skip creation of sql file * @returns {String} File name */ async create (name, nosql = false) { await this.init(); const date = new Date(); const ts = parseInt(date.getTime()); if (!name) name = "unnamed"; name = name.replace(/[^0-9a-z_\- ]+/ig, "").replace(/\s+/g, "-"); // Retries if migration file exists if (fs.existsSync(path.join(this.options.migrations, `${ts}_${name}.js`))) { // Delays retry await new Promise(resolve => setTimeout(resolve, 50)); // Avoids stack overflow case return await new Promise(resolve => setImmediate(() => { resolve(this.create(name, nosql)); })); } if (!nosql && !fs.existsSync(path.join(this.options.migrations, `sql/${ts}_${name}.sql`))) { // Creates SQL file await fs.promises.writeFile(path.join(this.options.migrations, `sql/${ts}_${name}.sql`), "-- SQL", {encoding: "utf8"}); } // Creates migration file await fs.promises.copyFile(path.join(this.options.migrations, "template.stub"), path.join(this.options.migrations, `${ts}_${name}.js`)); return `${ts}_${name}`; } /** * Releases DB connection * @memberof migration * @public * @async * @returns {void} */ release () { return this.client[this.options.endMethod].call(this.client); } } module.exports = migration;var data = require("../itemsList.json"); exports.addCategory = function (request, response) { var section = request.query.sect; var category = { "categoryName": request.query.catName, "items": [] } var i; console.log("section: " + section); console.log("length: " + data['Sections'].length); for (i = 0; i < data['Sections'].length; i++) { console.log(i + " s: " + data.Sections[i].sectionName); console.log(data.Sections[i].sectionName == section); if (data.Sections[i].sectionName == section) { break; } } console.log(i); console.log(data.Sections[i]); data.Sections[i].categories.push(category); console.log(data); response.render('items.handlebars', data); }class CustomButton extends HTMLElement { constructor() { super(); this.classList.add("customButton"); // Insert additional classes if (this.hasAttribute('class')) { var customClassList = this.getAttribute('class').split(' '); var parent = this; customClassList.forEach(element => { parent.classList.add(element); }, parent); } // Insert text var text; if (this.hasAttribute('text')) { text = this.getAttribute('text'); } else { text = 'test'; } var label = document.createElement('label'); label.textContent = text; this.appendChild(label); // Insert href if (this.hasAttribute('href')) { var href = this.getAttribute('href'); this.onclick = () => { window.location.href = href; } } //if contains picture, make component for it if (this.hasAttribute('img')) { var imgAddress = this.getAttribute('img'); var img = document.createElement('img'); img.src = imgAddress; img.classList.add("horoscopeImg"); var fog = document.createElement('div'); fog.classList.add("fog"); var wrapper = document.createElement('div'); wrapper.classList.add("wrapper"); wrapper.appendChild(img); wrapper.appendChild(fog); this.onclick = () => { wrapper.classList.add('visible') } wrapper.onclick = () => { wrapper.classList.remove('visible') } document.body.appendChild(wrapper); } } } customElements.define('custom-button', CustomButton);'use strict'; require('dotenv').config(); const algoliasearch = require("algoliasearch"); const fs = require('fs'); const got = require('got'); const index = algoliasearch( process.env.ALGOLIA_APP_ID, process.env.ALGOLIA_WRITE_KEY ).initIndex(process.env.ALGOLIA_DARCIE_INDEX); async function anon() { try { let locations = JSON.parse(fs.readFileSync('food94103.json')); for (const location of locations) { let body = await got( `https://maps.googleapis.com/maps/api/geocode/json?address=${location.address}%20San%20Francisco&key=${process.env.GOOGLE_API_KEY}` ).json(); location._geoloc = { 'lat': body.results[0].geometry.location.lat, 'lng': body.results[0].geometry.location.lng }; }; index.saveObjects(locations, { autoGenerateObjectIDIfNotExist: true }); } catch (err) { console.error(err); } }; anon(); module.exports = new Date(2015, 1, 11) api/auth.js const router = require('express').Router(); // Need curli helper in here const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); function generateToken(curli) { const payload = { username: curli.username, id: user.id, }; const options = { expiresIn: '1d', }; return jwt.sign(payload, process.env.JWT_SECRET || 'asdflasdfl', options); } router.post('/register', (req, res) => { const { username, password, email, } = req.body; User.addUser({username, password: .hashSync(password, 8), email }) .then(id => { res.status(201).json({ Message: 'User Registeration Succesful', id }); }) .catch(err => { console.log(err); res.status(500).json({ Message: 'Error Registering User'}); }); }); router.post('/login', (req, res) => { const { username, password } = req.body; console.log('outside', req.body) Curli.getByUsername(username) .then(user => { console.log('inside', username) if (user && bcrypt.compareSync(password, user.password)) { const token = generateToken(user); res.status(200).json({ Message: "Login Succesful!", token }); } else { res.status(401).json({ Message: 'Error logging in' }) } }) .catch(err => { console.log(err); res.status(500).json({ Message: 'Error logging in' }) }) }) module.exports = router; /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ Vue.component('example', require('./components/Example.vue')); const app = new Vue({ el: '#app', data: { messages: [], newMessage: '', user: '', typing: false }, created() { let _this = this; Echo.private('chat') .listenForWhisper('typing', (e) => { this.user = e.user; this.typing = e.typing; // remove is typing indicator after 0.9s setTimeout(function() { _this.typing = false }, 900); }); }, methods: { isTyping() { let channel = Echo.private('chat'); setTimeout(function() { channel.whisper('typing', { user: Laravel.user, typing: true }); }, 300); }, sendMessage() { // add new message to messages array this.messages.push({ user: Laravel.user, message: this.newMessage }); // clear input field this.newMessage = ''; // persist to database }, } }); import properties from 'properties'; import getOptions from './getOptions'; /** * @param {*} content * @returns {void} */ export default function(content) { if (this.cacheable) { this.cacheable(); } const options = getOptions(this), callback = this.async(); properties.parse(content, options, (err, result = {}) => { callback(err, result); }); } node_modules/expo/src/av/Audio.js // @flow import { NativeModules } from 'react-native'; export * from './Audio/Recording'; export * from './Audio/Sound'; export type AudioMode = { allowsRecordingIOS: boolean, interruptionModeIOS: number, playsInSilentModeIOS: boolean, interruptionModeAndroid: boolean, shouldDuckAndroid: boolean, }; export const INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS = 0; export const INTERRUPTION_MODE_IOS_DO_NOT_MIX = 1; export const INTERRUPTION_MODE_IOS_DUCK_OTHERS = 2; export const INTERRUPTION_MODE_ANDROID_DO_NOT_MIX = 1; export const INTERRUPTION_MODE_ANDROID_DUCK_OTHERS = 2; let _enabled: boolean = true; const _DISABLED_ERROR: Error = new Error('Cannot complete operation because audio is not enabled.'); // Returns true if value is in validValues, and false if not. const _isValueValid = (value: any, validValues: Array): boolean => { return validValues.filter(validValue => validValue === value).length > 0; }; // Returns array of missing keys in object. Returns an empty array if no missing keys are found. const _findMissingKeys = (object: Object, requiredKeys: Array): Array => { return requiredKeys.filter(requiredKey => !(requiredKey in object)); }; export function _isAudioEnabled(): boolean { return _enabled; } export function _throwIfAudioIsDisabled(): void { if (!_enabled) { throw _DISABLED_ERROR; } } export async function setIsEnabledAsync(value: boolean): Promise { _enabled = value; await NativeModules.ExponentAV.setAudioIsEnabled(value); // TODO : We immediately pause all players when disabled, but we do not resume all shouldPlay // players when enabled. Perhaps for completeness we should allow this; the design of the // enabling API is for people to enable / disable this audio library, but I think that it should // intuitively also double as a global pause/resume. } export async function setAudioModeAsync(mode: AudioMode): Promise { const missingKeys = _findMissingKeys(mode, [ 'allowsRecordingIOS', 'interruptionModeIOS', 'playsInSilentModeIOS', 'interruptionModeAndroid', 'shouldDuckAndroid', ]); if (missingKeys.length > 0) { throw new Error( `Audio mode attempted to be set without the required keys: ${JSON.stringify(missingKeys)}` ); } if ( !_isValueValid(mode.interruptionModeIOS, [ INTERRUPTION_MODE_IOS_MIX_WITH_OTHERS, INTERRUPTION_MODE_IOS_DO_NOT_MIX, INTERRUPTION_MODE_IOS_DUCK_OTHERS, ]) ) { throw new Error(`"interruptionModeIOS" was set to an invalid value.`); } if ( !_isValueValid(mode.interruptionModeAndroid, [ INTERRUPTION_MODE_ANDROID_DO_NOT_MIX, INTERRUPTION_MODE_ANDROID_DUCK_OTHERS, ]) ) { throw new Error(`"interruptionModeAndroid" was set to an invalid value.`); } if ( typeof mode.allowsRecordingIOS !== 'boolean' || typeof mode.playsInSilentModeIOS !== 'boolean' || typeof mode.shouldDuckAndroid !== 'boolean' ) { throw new Error( '"allowsRecordingIOS", "playsInSilentModeIOS", and "shouldDuckAndroid" must be booleans.' ); } return await NativeModules.ExponentAV.setAudioMode(mode); } 0 "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.batchExec = void 0; const fs = require("fs"); const path = require("path"); const open_terminal_1 = require("open-terminal"); /** 判断是否为文件夹 */ const isFolder = (name) => { try { const stats = fs.statSync(name); return stats.isDirectory(); } catch (_error) { return false; } }; /** 获取 package 列表 */ function getPackages(folder) { const files = fs.readdirSync(folder); const packages = []; files.forEach((filename) => { if (isFolder(path.join(folder, filename))) { packages.push({ name: filename, value: filename, }); } }); return packages; } const inquirer = require('inquirer'); function batchExec(script) { const folder = path.resolve('../packages'); const packages = getPackages(folder); const prompt = inquirer.createPromptModule(); prompt([ { type: 'checkbox', name: 'packages', message: 'Packages', pageSize: 15, choices: packages, }, ]).then((answers) => { answers.packages.map(temp => { const command = `cd ${path.join(folder, temp)} && npm run ${script}`; return (0, open_terminal_1.default)(command); }); }); } exports.batchExec = batchExec; const getTriangleMoreThanDivisors = (nOfDivisors, triangleNumN = 2) => getNumberOfDivisors(normalizeFactors(getAllFactors(getTriangleNumberN(triangleNumN)))) > nOfDivisors ? getTriangleNumberN(triangleNumN) : getTriangleMoreThanDivisors(nOfDivisors, triangleNumN + 1) const getNumberOfDivisors = normalizedFactors => Object.values(normalizedFactors).reduce((nOfDivisors, exp) => (exp + 1) * nOfDivisors , 1) const getTriangleNumberN = n => (n + 1) * (n / 2) const normalizeFactors = factors => factors.reduce((factorObj, factor) => factorObj[factor] ? {...factorObj, [factor]: factorObj[factor] + 1} : {...factorObj, [factor]: 1}, {}) const getAllFactors = (n, factor = 2, factors = []) => n % factor === 0 ? getAllFactors(n/factor, factor, factors.concat(factor)) : nextPrime(factor) <= n ? getAllFactors(n, nextPrime(factor), factors) : factors const nextPrime = n => isPrime(n + 1) ? n + 1 : nextPrime(n + 1) const isPrime = x => x <= 3 ? x > 1 : x % 2 === 0 || x % 3 === 0 ? false : primeCheck(x) const primeCheck = (x, i = 5) => i * i <= x ? x % i !== 0 && x % (i + 2) !== 0 && primeCheck(x, i + 6) : true module.exports = { getAllFactors, normalizeFactors, getTriangleNumberN, getNumberOfDivisors, getTriangleMoreThanDivisors } 0 'use strict'; const { Expo } = require('expo-server-sdk'); module.exports = { async send(params, pushTokens) { const expo = new Expo(); const messages = []; const today = new Date(); pushTokens.map((pushToken) => { if (!Expo.isExpoPushToken(pushToken)) { strapi.log.fatal( '[EXPO][ERROR] ' + `Push token ${pushToken} is not a valid Expo push token` ); return false; } messages.push({ to: pushToken, sound: 'default', title: params.title, body: params.body, data: params.data ? params.data : params.data_url ? { url: params.data_url } : {}, }); }); if (!messages.length) { return false; } const chunks = expo.chunkPushNotifications(messages); const tickets = []; await (async () => { chunks.map(async (chunk) => { try { const ticketChunk = await expo.sendPushNotificationsAsync(chunk); tickets.push(...ticketChunk); } catch (error) { strapi.log.fatal('[EXPO][ERROR] ' + error); } }); })(); const receiptIds = []; tickets.map((ticket) => { if (ticket.id) { receiptIds.push(ticket.id); } }); const receiptIdChunks = expo.chunkPushNotificationReceiptIds(receiptIds); await (async () => { receiptIdChunks.map(async (chunk) => { try { const receipts = await expo.getPushNotificationReceiptsAsync(chunk); receipts.map((receipt) => { if (receipt.status === 'error') { strapi.log.fatal(`There was an error sending a notification: ${receipt.message}`); if (receipt.details && receipt.details.error) { strapi.log.fatal(`The error code is ${receipt.details.error}`); } } }); } catch (error) { strapi.log.fatal('[EXPO][ERROR] ' + error); } }); return true; })(); }, }; export { default } from 'ember-scroll/services/scroll'; subhash-malireddy/dev.to_mongodb-atlas-hackathon import React, { useState } from 'react' import { Form } from 'react-bootstrap' import Button from 'react-bootstrap/Button' import { useNavigate } from "react-router-dom"; import '../../styles/general.scss' import * as Realm from "realm-web"; function ForgotPassword() { const [email, setEmail] = useState('') const app = new Realm.App({ id: process.env.REACT_APP_REALM_APP_ID }) let navigate = useNavigate() const sendEmail2Realm = async () => { try{ await app.emailPasswordAuth.sendResetPasswordEmail({ email }); alert("An email is sent with a password reset link. If you cannot find it in your inbox, please check your sapm folder.") navigate('/') }catch(e){ alert(String(e)) } } return (
    Please provide your Email address to get a password reset link. {setEmail(e.target.value)}}/>
    ) } export default ForgotPassword import $axios from '../api.js' const state = () => ({ }) const mutations = { } const actions = { submit({ commit }, payload) { localStorage.setItem('token', null) commit('SET_TOKEN', null, { root: true }) return new Promise((resolve, reject) => { $axios.post('/login', payload) .then((response) => { if (response.data.status == 'success') { localStorage.setItem('token', response.data.data) commit('SET_TOKEN', response.data.data, { root: true }) } else { commit('SET_ERRORS', { invalid: 'Email/Password Salah' }, { root: true }) } resolve(response.data) }) .catch((error) => { if (error.response.status == 422) { commit('SET_ERRORS', error.response.data.errors, { root: true }) } }) }) } } export default { namespaced: true, state, actions, mutations }Cliente_Servidor/LCD/node_modules/pigpio/test/do-nothing.js100-1000 'use strict'; // requiring pigpio shouldn't result in the event loop being kept alive if // nothing is actully performed. If this program doesn't terminate immediately, // the event loop is being kept alive, which is incorrect. const pigpio = require('../'); 'use strict'; var Datastore = require('nedb'), user = new Datastore({ filename: './user.db', autoload: true }), watch = new Datastore({ filename: './watch.db', autoload: true }), repos = new Datastore({ filename: './repos.db', autoload: true }); watch.ensureIndex({ fieldName: 'repo', unique: true }, function (err) { if (err) { console.error(err); } }); repos.ensureIndex({ fieldName: 'id', unique: true }, function (err) { if (err) { console.error(err); } }); module.exports = { user: user, watch: watch, repos: repos }; 0 module.exports.alpha = { "/basic/": [ { text: "Базовая настройка", children: ["/basic/README.md", "/basic/clients.md"], }, ], "/for-developers/api/": [ { text: "Aurora API", collapsible: true, children: [ "/for-developers/api/info.md", "/for-developers/api/errors.md", ], }, ], "/for-developers/": [ { text: "Прочее", collapsible: true, children: ["/for-developers/mirrors.md"], }, ], }; module.exports.next = { "/next/basic/": [ { text: "Базовая настройка", children: ["/next/basic/README.md", "/next/basic/clients.md"], }, ], "/next/for-developers/api/": [ { text: "Aurora API", collapsible: true, children: [ "/next/for-developers/api/info.md", "/next/for-developers/api/errors.md", ], }, ], "/next/for-developers/": [ { text: "Прочее", collapsible: true, children: ["/next/for-developers/mirrors.md"], }, ], }; dfsq/so-reputation-trackertools/tasks/serve.js var gulp = require('gulp'), browserSync = require('browser-sync'), nodemon = require('gulp-nodemon'), paths = require('../paths'), config = require('../../server/config'); // Run development server gulp.task('serve', ['build', 'browser-sync'], function() {}); // Browsersync plugin reload UI gulp.task('browser-sync', ['nodemon', 'watch'], function() { browserSync.init({ proxy: config.server.hostname + ':' + config.server.port, port: '9000', files: [paths.app + '**/*.*'] }); }); // Watch for changes in js and html files and report changes to browser-sync gulp.task('watch', function() { gulp.watch(paths.source, ['build-js', browserSync.reload]); gulp.watch(paths.html, ['build-html', browserSync.reload]); }); // Express server restart gulp.task('nodemon', function(callback) { var called = false; return nodemon({ script: paths.server + 'index.js', watch: [paths.server] }) .on('start', function onStart() { // ensure start only got called once if (!called) callback(); called = true; }) .on('restart', function onRestart() { // reload connected browsers after a slight delay setTimeout(function() { browserSync.reload({ stream: false }); }, 500); }); }); import {mount} from 'enzyme'; import {RangePicker, RangePickerBase} from '../RangePicker'; const tap = (node) => { node.simulate('mousedown'); node.simulate('mouseup'); }; const decrement = (slider) => tap(slider.find('IconButton').last()); const increment = (slider) => tap(slider.find('IconButton').first()); describe('RangePicker Specs', () => { test('should render a single child with the current value', () => { const picker = mount( ); const expected = '10'; const actual = picker.find('PickerItem').text(); expect(actual).toBe(expected); }); test('should increase by step amount on increment press', () => { const picker = mount( ); increment(picker); const expected = '11'; const actual = picker.find('PickerItem').first().text(); expect(actual).toBe(expected); }); test('should decrease by step amount on decrement press', () => { const picker = mount( ); decrement(picker); const expected = '9'; const actual = picker.find('PickerItem').first().text(); expect(actual).toBe(expected); }); test('should pad the value', () => { const picker = mount( ); const expected = '010'; const actual = picker.find('PickerItem').text(); expect(actual).toBe(expected); }); test('should pad the value when min has more digits than max', () => { const picker = mount( ); const expected = '0010'; const actual = picker.find('PickerItem').text(); expect(actual).toBe(expected); }); test('should be disabled when limited to a single value', () => { const picker = mount( ); const actual = picker.find('Picker').last().prop('disabled'); expect(actual).toBe(true); }); }); let $dlgSave = new Dialog('save'); ((dlg) => { let content = `

    你想将更改保存到  吗?

    `; let $dlg = dlg.generate(content, '记事本'); let $btnSave = $dlg.find('.btn-save'), $btnNotSave = $dlg.find('.btn-not-save'), $btnCancel = $dlg.find('.btn-cancel'), $fileName = $dlg.find('.file-name'); let cfg = { saveHandler: null, notSaveHandler: null }; dlg.show = (conf) => { $.extend(cfg, conf); $fileName.text(np.fileName); $('body').append($dlg); dlg.init(); $btnSave.focus(); $btnCancel.click(dlg.destory); $btnSave.click(() => { cfg.saveHandler(); dlg.destory(); }); $btnNotSave.click(() => { cfg.notSaveHandler(); dlg.destory(); }); $dlg.click((e) => { $btnSave.focus(); e.stopPropagation(); }); }; })($dlgSave); 0 import React, { Component } from 'react' import styled from 'styled-components' import LoadingBar from './../LoadingBar' class LoadingScreen extends Component { render() { const { onLoad, soundEffects, visible } = this.props return (

    Langerock Enterprises, Inc

    Loading screen can be disabled in settings...

    ) } } export default LoadingScreen const Loading = styled.div` display: ${props => (props.visible ==='true'? 'block' : 'none')}; h1 { font-family: 'Sevastopol'; font-size: 128px; margin-bottom: 2rem; text-align: center; color: ${props => props.theme.loading_bar.title_font_color}; @media (max-width: ${props => props.theme.query.tablet}) { font-size: 84px; } @media (max-width: ${props => props.theme.query.mobile}) { font-size: 72px; } @media (max-width: ${props => props.theme.query.small}) { font-size: 52px; } } p { font-family: 'Sevastopol'; font-size: 28px; color: white; text-align: center; margin-top: 24px; color: ${props => props.theme.loading_bar.font_color}; @media (max-width: ${props => props.theme.query.small}) { font-size: 22px; } } margin: 30px auto; display: flex; justify-content: space-between; align-items: center; flex-direction: column; height: 100%; ` const BarContainer = styled.div` display: flex; flex-direction: column; width: 100%; align-items: center; ` var sendError = require('../../util/send-error'); // Create a new todo module.exports = function (options) { // Shorter reference to data store var store = options.store; return function (req, res) { var todo = store.todos.filter(function (t) { return t.id === req.params.id; })[0]; // No todo with that id if (!todo) { return sendError(res, 404, 'Todo not found'); } // Verify that user exists var user = store.users.filter(function (u) { return u.id === req.params.userId; })[0]; if (!user) { return sendError(res, 400, 'User not found: ' + req.params.userId); } // Set values todo.assignedTo = user.id; // Save data to store store.users.splice(store.users.indexOf(user), 1, user); // Respond res.status(200).json(todo); }; }; EddisFargo/Moodle // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . /** * A javascript module to handler calendar view changes. * * @module core_calendar/view_manager * @package core_calendar * @copyright 2017 <> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ import $ from 'jquery'; import Templates from 'core/templates'; import Notification from 'core/notification'; import * as CalendarRepository from 'core_calendar/repository'; import CalendarEvents from 'core_calendar/events'; import * as CalendarSelectors from 'core_calendar/selectors'; import ModalFactory from 'core/modal_factory'; import ModalEvents from 'core/modal_events'; import SummaryModal from 'core_calendar/summary_modal'; import CustomEvents from 'core/custom_interaction_events'; import Pending from 'core/pending'; /** * Register event listeners for the module. * * @param {object} root The root element. */ const registerEventListeners = (root) => { root = $(root); // Bind click events to event links. root.on('click', CalendarSelectors.links.eventLink, (e) => { const target = e.target; let eventLink = null; let eventId = null; const pendingPromise = new Pending('core_calendar/view_manager:eventLink:click'); if (target.matches(CalendarSelectors.actions.viewEvent)) { eventLink = target; } else { eventLink = target.closest(CalendarSelectors.actions.viewEvent); } if (eventLink) { eventId = eventLink.dataset.eventId; } else { eventId = target.querySelector(CalendarSelectors.actions.viewEvent).dataset.eventId; } if (eventId) { // A link was found. Show the modal. e.preventDefault(); // We've handled the event so stop it from bubbling // and causing the day click handler to fire. e.stopPropagation(); renderEventSummaryModal(eventId) .then(pendingPromise.resolve) .catch(); } else { pendingPromise.resolve(); } }); root.on('click', CalendarSelectors.links.navLink, (e) => { const wrapper = root.find(CalendarSelectors.wrapper); const view = wrapper.data('view'); const courseId = wrapper.data('courseid'); const categoryId = wrapper.data('categoryid'); const link = e.currentTarget; if (view === 'month') { changeMonth(root, link.href, link.dataset.year, link.dataset.month, courseId, categoryId, link.dataset.day); e.preventDefault(); } else if (view === 'day') { changeDay(root, link.href, link.dataset.year, link.dataset.month, link.dataset.day, courseId, categoryId); e.preventDefault(); } }); const viewSelector = root.find(CalendarSelectors.viewSelector); CustomEvents.define(viewSelector, [CustomEvents.events.activate]); viewSelector.on( CustomEvents.events.activate, (e) => { e.preventDefault(); const option = e.target; if (option.classList.contains('active')) { return; } const view = option.dataset.view, year = option.dataset.year, month = option.dataset.month, day = option.dataset.day, courseId = option.dataset.courseid, categoryId = option.dataset.categoryid; if (view == 'month') { refreshMonthContent(root, year, month, courseId, categoryId, root, 'core_calendar/calendar_month', day) .then(() => { return window.history.pushState({}, '', '?view=month'); }).fail(Notification.exception); } else if (view == 'day') { refreshDayContent(root, year, month, day, courseId, categoryId, root, 'core_calendar/calendar_day') .then(() => { return window.history.pushState({}, '', '?view=day'); }).fail(Notification.exception); } else if (view == 'upcoming') { reloadCurrentUpcoming(root, courseId, categoryId, root, 'core_calendar/calendar_upcoming') .then(() => { return window.history.pushState({}, '', '?view=upcoming'); }).fail(Notification.exception); } } ); }; /** * Refresh the month content. * * @param {object} root The root element. * @param {number} year Year * @param {number} month Month * @param {number} courseId The id of the course whose events are shown * @param {number} categoryId The id of the category whose events are shown * @param {object} target The element being replaced. If not specified, the calendarwrapper is used. * @param {string} template The template to be rendered. * @param {number} day Day (optional) * @return {promise} */ export const refreshMonthContent = (root, year, month, courseId, categoryId, target = null, template = '', day = 1) => { startLoading(root); target = target || root.find(CalendarSelectors.wrapper); template = template || root.attr('data-template'); M.util.js_pending([root.get('id'), year, month, courseId].join('-')); const includenavigation = root.data('includenavigation'); const mini = root.data('mini'); return CalendarRepository.getCalendarMonthData(year, month, courseId, categoryId, includenavigation, mini, day) .then(context => { context.viewingmonth = true; return Templates.render(template, context); }) .then((html, js) => { return Templates.replaceNode(target, html, js); }) .then(() => { document.querySelector('body').dispatchEvent(new CustomEvent(CalendarEvents.viewUpdated)); return; }) .always(() => { M.util.js_complete([root.get('id'), year, month, courseId].join('-')); return stopLoading(root); }) .fail(Notification.exception); }; /** * Handle changes to the current calendar view. * * @param {object} root The container element * @param {string} url The calendar url to be shown * @param {number} year Year * @param {number} month Month * @param {number} courseId The id of the course whose events are shown * @param {number} categoryId The id of the category whose events are shown * @param {number} day Day (optional) * @return {promise} */ export const changeMonth = (root, url, year, month, courseId, categoryId, day = 1) => { return refreshMonthContent(root, year, month, courseId, categoryId, null, '', day) .then((...args) => { if (url.length && url !== '#') { window.history.pushState({}, '', url); } return args; }) .then((...args) => { $('body').trigger(CalendarEvents.monthChanged, [year, month, courseId, categoryId]); return args; }); }; /** * Reload the current month view data. * * @param {object} root The container element. * @param {number} courseId The course id. * @param {number} categoryId The id of the category whose events are shown * @return {promise} */ export const reloadCurrentMonth = (root, courseId = 0, categoryId = 0) => { const year = root.find(CalendarSelectors.wrapper).data('year'); const month = root.find(CalendarSelectors.wrapper).data('month'); const day = root.find(CalendarSelectors.wrapper).data('day'); courseId = courseId || root.find(CalendarSelectors.wrapper).data('courseid'); categoryId = categoryId || root.find(CalendarSelectors.wrapper).data('categoryid'); return refreshMonthContent(root, year, month, courseId, categoryId, null, '', day); }; /** * Refresh the day content. * * @param {object} root The root element. * @param {number} year Year * @param {number} month Month * @param {number} day Day * @param {number} courseId The id of the course whose events are shown * @param {number} categoryId The id of the category whose events are shown * @param {object} target The element being replaced. If not specified, the calendarwrapper is used. * @param {string} template The template to be rendered. * * @return {promise} */ export const refreshDayContent = (root, year, month, day, courseId, categoryId, target = null, template = '') => { startLoading(root); target = target || root.find(CalendarSelectors.wrapper); template = template || root.attr('data-template'); M.util.js_pending([root.get('id'), year, month, day, courseId, categoryId].join('-')); const includenavigation = root.data('includenavigation'); return CalendarRepository.getCalendarDayData(year, month, day, courseId, categoryId, includenavigation) .then((context) => { context.viewingday = true; return Templates.render(template, context); }) .then((html, js) => { return Templates.replaceNode(target, html, js); }) .then(() => { document.querySelector('body').dispatchEvent(new CustomEvent(CalendarEvents.viewUpdated)); return; }) .always(() => { M.util.js_complete([root.get('id'), year, month, day, courseId, categoryId].join('-')); return stopLoading(root); }) .fail(Notification.exception); }; /** * Reload the current day view data. * * @param {object} root The container element. * @param {number} courseId The course id. * @param {number} categoryId The id of the category whose events are shown * @return {promise} */ export const reloadCurrentDay = (root, courseId = 0, categoryId = 0) => { const wrapper = root.find(CalendarSelectors.wrapper); const year = wrapper.data('year'); const month = wrapper.data('month'); const day = wrapper.data('day'); courseId = courseId || root.find(CalendarSelectors.wrapper).data('courseid'); categoryId = categoryId || root.find(CalendarSelectors.wrapper).data('categoryid'); return refreshDayContent(root, year, month, day, courseId, categoryId); }; /** * Handle changes to the current calendar view. * * @param {object} root The root element. * @param {String} url The calendar url to be shown * @param {Number} year Year * @param {Number} month Month * @param {Number} day Day * @param {Number} courseId The id of the course whose events are shown * @param {Number} categoryId The id of the category whose events are shown * @return {promise} */ export const changeDay = (root, url, year, month, day, courseId, categoryId) => { return refreshDayContent(root, year, month, day, courseId, categoryId) .then((...args) => { if (url.length && url !== '#') { window.history.pushState({}, '', url); } return args; }) .then((...args) => { $('body').trigger(CalendarEvents.dayChanged, [year, month, courseId, categoryId]); return args; }); }; /** * Set the element state to loading. * * @param {object} root The container element * @method startLoading */ const startLoading = (root) => { const loadingIconContainer = root.find(CalendarSelectors.containers.loadingIcon); loadingIconContainer.removeClass('hidden'); }; /** * Remove the loading state from the element. * * @param {object} root The container element * @method stopLoading */ const stopLoading = (root) => { const loadingIconContainer = root.find(CalendarSelectors.containers.loadingIcon); loadingIconContainer.addClass('hidden'); }; /** * Reload the current month view data. * * @param {object} root The container element. * @param {number} courseId The course id. * @param {number} categoryId The id of the category whose events are shown * @param {object} target The element being replaced. If not specified, the calendarwrapper is used. * @param {string} template The template to be rendered. * @return {promise} */ export const reloadCurrentUpcoming = (root, courseId = 0, categoryId = 0, target = null, template = '') => { startLoading(root); target = target || root.find(CalendarSelectors.wrapper); template = template || root.attr('data-template'); courseId = courseId || root.find(CalendarSelectors.wrapper).data('courseid'); categoryId = categoryId || root.find(CalendarSelectors.wrapper).data('categoryid'); return CalendarRepository.getCalendarUpcomingData(courseId, categoryId) .then((context) => { context.viewingupcoming = true; return Templates.render(template, context); }) .then((html, js) => { return Templates.replaceNode(target, html, js); }) .then(() => { document.querySelector('body').dispatchEvent(new CustomEvent(CalendarEvents.viewUpdated)); return; }) .always(function() { return stopLoading(root); }) .fail(Notification.exception); }; /** * Get the CSS class to apply for the given event type. * * @param {string} eventType The calendar event type * @return {string} */ const getEventTypeClassFromType = (eventType) => { return 'calendar_event_' + eventType; }; /** * Render the event summary modal. * * @param {Number} eventId The calendar event id. * @returns {Promise} */ const renderEventSummaryModal = (eventId) => { const pendingPromise = new Pending('core_calendar/view_manager:renderEventSummaryModal'); // Calendar repository promise. return CalendarRepository.getEventById(eventId) .then((getEventResponse) => { if (!getEventResponse.event) { throw new Error('Error encountered while trying to fetch calendar event with ID: ' + eventId); } return getEventResponse.event; }) .then(eventData => { // Build the modal parameters from the event data. const modalParams = { title: eventData.name, type: SummaryModal.TYPE, body: Templates.render('core_calendar/event_summary_body', eventData), templateContext: { canedit: eventData.canedit, candelete: eventData.candelete, headerclasses: getEventTypeClassFromType(eventData.normalisedeventtype), isactionevent: eventData.isactionevent, url: eventData.url, action: eventData.action } }; // Create the modal. return ModalFactory.create(modalParams); }) .then(modal => { // Handle hidden event. modal.getRoot().on(ModalEvents.hidden, function() { // Destroy when hidden. modal.destroy(); }); // Finally, render the modal! modal.show(); return modal; }) .then(modal => { pendingPromise.resolve(); return modal; }) .catch(Notification.exception); }; export const init = (root, view) => { registerEventListeners(root, view); }; 0 var expect = require('chai').expect var maduro = require("../build/maduro.js"); describe("maduro.stack", function () { var stack = null; beforeEach(function () { if (stack === null) { stack = maduro.stack(); } }); afterEach(function () { stack = null; }); it("should have an push method", function () { expect(stack).to.have.property("push"); expect(stack.push).to.be.a("function"); }); it("should have an pop method", function () { expect(stack).to.have.property("pop"); expect(stack.pop).to.be.a("function"); }); it("should have a peek method", function () { expect(stack).to.have.property("peek"); expect(stack.peek).to.be.a("function"); }); it("should have a clear method", function () { expect(stack).to.have.property("clear"); expect(stack.clear).to.be.a("function"); }); it("should have an length method", function () { expect(stack).to.have.property("length"); expect(stack.length).to.be.a("function"); }); describe("push", function () { it("should add a new element on top of the stack", function () { stack.data = [3, 2, 1]; stack.top = 3; stack.push(4); expect(stack.data).to.have.length(4); expect(stack.data[3]).to.equal(4); expect(stack.top).to.equal(4); }); }); describe("pop", function () { it("should return the top item in the stack", function () { stack.data = [3, 2, 1]; expect(stack.pop()).to.equal(1); }); it("should remove the top item in the stack", function () { stack.data = [3, 2, 1]; stack.top = 3; expect(stack.data).to.have.length(3); expect(stack.top).to.equal(3); expect(stack.pop()).to.equal(1); expect(stack.data).to.have.length(2); expect(stack.data[stack.data.length - 1]).to.equal(2); expect(stack.top).to.equal(2); }); }); describe("peek", function () { it("should return the top item in the stack", function () { stack.data = [3, 2, 1]; stack.top = 3; expect(stack.peek()).to.equal(1); }); it("should not remove the top item in the stack", function () { stack.data = [3, 2, 1]; stack.top = 3; expect(stack.data).to.have.length(3); expect(stack.top).to.equal(3); expect(stack.peek()).to.equal(1); expect(stack.data).to.have.length(3); expect(stack.data[stack.data.length - 1]).to.equal(1); expect(stack.top).to.equal(3); }); }); describe("clear", function () { it("should clear all elements from the stack", function () { stack.data = [1, 2, 3]; stack.clear(); expect(stack.data).to.be.empty; expect(stack.top).to.equal(0); }); }); describe("length", function () { it("should return the current length of the stack", function () { stack.top = 3; expect(stack.length()).to.equal(3); stack.top = 2; expect(stack.length()).to.equal(2); }); }); }); 1-10 import React, { useContext } from "react"; import { shape, string, number } from "prop-types"; import { graphql } from "gatsby"; import Img from "gatsby-image"; import { useIntl } from "react-intl"; import SEO from "../components/SEO"; import Layout from "../components/Layout"; import Main from "../components/Main"; import SocialNav from "../components/SocialNav"; import ContactCard from "../components/ContactCard"; import { Col, Row } from "../components/Grid"; import ErrorBoundary from "../components/ErrorBoundary"; import ScrollToTop from "../components/ScrollToTop"; import { localePaths } from "../i18n"; import { HeaderRow, HeaderInfoCol, AboutMeTitle, AboutCopy, StyledCopy, AltRowBackground, MyWorkTitle, SkillsTitle, SkillsSubtitle, SkilsCol, } from "../styles/about-me.styles"; import LocaleContext from "../i18n/LocaleContext"; const AboutPage = ({ location, data }) => { const { locale } = useContext(LocaleContext); const intl = useIntl(); return (
    {intl.formatMessage({ {intl.formatMessage({ id: "about.me.title" })} {intl.formatMessage({ id: "about.me.subtitle" })} {intl.formatMessage({ id: "about.me.what.i.do.title" })} {intl.formatMessage({ id: "about.me.what.i.do.copy.1" })} {intl.formatMessage({ id: "about.me.what.i.do.copy.2" })} {intl.formatMessage({ id: "about.me.what.i.do.copy.3" })} {intl.formatMessage({ id: "about.me.what.i.do.copy.4" })} {intl.formatMessage({ id: "about.me.skills.title" })} {intl.formatMessage({ id: "about.me.skills.1.subtitle" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.1" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.2" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.3" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.4" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.5" })}
    • {intl.formatMessage({ id: "about.me.skills.1.item.6" })}
    {intl.formatMessage({ id: "about.me.skills.2.subtitle" })}
    • {intl.formatMessage({ id: "about.me.skills.2.item.1" })}
    • {intl.formatMessage({ id: "about.me.skills.2.item.2" })}
    • {intl.formatMessage({ id: "about.me.skills.2.item.3" })}
    • {intl.formatMessage({ id: "about.me.skills.2.item.4" })}
    {intl.formatMessage({ id: "about.me.skills.3.subtitle" })}
    • {intl.formatMessage({ id: "about.me.skills.3.item.1" })}
    • {intl.formatMessage({ id: "about.me.skills.3.item.2" })}
    • {intl.formatMessage({ id: "about.me.skills.3.item.3" })}
    {intl.formatMessage({ id: "about.me.skills.4.subtitle" })}
    • {intl.formatMessage({ id: "about.me.skills.4.item.1" })}
    • {intl.formatMessage({ id: "about.me.skills.4.item.2" })}
    • {intl.formatMessage({ id: "about.me.skills.4.item.3" })}
    • {intl.formatMessage({ id: "about.me.skills.4.item.4" })}
    ); }; AboutPage.propTypes = { data: shape({ aboutImage: shape({ childImageSharp: shape({ fluid: shape({ aspectRatio: number.isRequired, base64: string.isRequired, sizes: string.isRequired, src: string.isRequired, srcSet: string.isRequired, srcSetWebp: string.isRequired, srcWebp: string.isRequired, }).isRequired, }), }), }).isRequired, location: shape({ pathname: string.isRequired, href: string.isRequired, }).isRequired, }; export default AboutPage; export const query = graphql` query ABOUT_ME_IMAGE_QUERY { aboutImage: file(relativePath: { regex: "/danilucaci_profile_image/" }) { childImageSharp { fluid(maxWidth: 720, maxHeight: 540, cropFocus: NORTH, quality: 70) { ...GatsbyImageSharpFluid_withWebp } } } } `; import React from "react" import styled from "styled-components" import BackgroundImage from "gatsby-background-image" import { useStaticQuery, graphql } from "gatsby" // query to grab default image incase none is provided in props const getDefault = graphql` query { file(relativePath: { eq: "defaultBcg.jpeg" }) { childImageSharp { fluid(maxWidth: 4160, quality: 90) { ...GatsbyImageSharpFluid_withWebp } } } } ` const StyledHero = ({ img, className, children, home }) => { const data = useStaticQuery(getDefault) return ( {children} ) } export default styled(StyledHero)` min-height: ${props => (props.home ? "calc(100vh - 62px)" : "50vh")}; background: ${props => props.home ? "linear-gradient(rgba(63, 208, 212, 0.7), rgba(0, 0, 0, 0.7))" : "none"}; background-position: center; background-size: cover; opacity: 1 !important; display: flex; justify-content: center; align-items: center; ` import limit from 'express-rate-limit'; import bodyParser from 'body-parser'; import express from 'express'; import queue from './queue'; import cry from './cry'; import log from './log'; let app = express(); app.use(bodyParser.json()); // Set Express headers app.use((req, res, next) => { // Allow requests from any origin res.header('Access-Control-Allow-Origin', '*'); // Set which HTTP headers can be used the request res.header( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept' ); // Only allow GET/POST requests res.header('Access-Control-Allow-Methods', 'GET, OPTIONS, POST'); // Onwards! next(); }); // We're proxying apache to localhost so we wanna grab the client’s IP // address from the X-Forwarded-* header for correct IP rate limitting app.set('trust proxy', 1); // Rate limit per IP address app.use( limit({ message: 'alright there cowboy, time to stop 🤠', windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // limit each IP to 100 requests per windowMs }) ); // List items that are in the Tweet queue - only used internally app.get('/queue', (req, res) => { queue .list() .then(items => res.json({ items })) .catch(e => log.error(e)); }); // Make some tears app.post('/cry', ({ body }, res) => { const { input } = body; if (input.length > 2000) { return res.status(413).send("oh noes, that's too much string my guy (╥_╥)"); } cry(input) .then(tears => { queue.add({ input, tears }); res.json({ input, tears }); }) .catch(e => res.status(e.status || 400).send(e)); }); // Listen for connections app.listen(3003, () => log.info(`peep me at http://localhost:3003/`)); // Run the Tweet queue queue.run(); var Cell = function(props) { this.id = props && props.id || undefined; this.width = props && props.width || 0; this.height = props && props.height || 0; this.label = props && props.label || ''; this.cellEl = props && props.cellEl || undefined; this.parentEl = props && props.parentEl || undefined; this.cellType = props && props.cellType || undefined; this.cellContentType = props && props.cellContentType || undefined; this.labelNode = props && props.labelNode || undefined; this.events = []; // TODO: track events with callbacks {eN: 'click', cB: func() {}} }; Cell.prototype.destroy = function() { // console.log('removing cell', this); this.cellEl.removeEventListener('click', this); }; Cell.prototype.handleEvent = function(event) { //this.cellEl.getBoundingClientRect() var styles = this.cellEl.getBoundingClientRect(); var parentEl = this.parentEl; var cloneEl = this.cellEl.cloneNode(true); parentEl.classList.add('item-selected'); cloneEl.style.top = styles.top + window.pageYOffset + 'px'; cloneEl.style.left = styles.left + window.pageXOffset + 'px'; cloneEl.classList.add('cloned'); document.body.appendChild(cloneEl); var bodyBBox = document.body.getBoundingClientRect(); var top = (bodyBBox.height/2) - (200/2); var left = (bodyBBox.width/2) - (200/2); setTimeout(function() { cloneEl.classList.add('scaled'); cloneEl.style.top = top + 'px'; cloneEl.style.left = left + 'px'; cloneEl.style.width = 200 + 'px'; cloneEl.style.height = 200 + 'px'; },100); // cloneEl.style.lineHeight = 200 + 'px'; cloneEl.addEventListener('click', function() { this.removeEventListener('click', this); document.removeEventListener('mousemove', threeDEffect); // remove 3d shifting effect listener document.body.removeChild(this); parentEl.classList.remove('item-selected'); }, false); // 3d shifting effect var clonePos, parentElPos = this.parentEl.getBoundingClientRect(); setTimeout(function() { clonePos = cloneEl.getBoundingClientRect(); // document.addEventListener('mousemove', threeDEffect); // cloneEl.classList.add('no-anim'); }, 80); var threeDEffect = function(e) { var x = (e.clientX - (parentElPos.width/2))/8; var y = (e.clientY - (parentElPos.height/2))/8; cloneEl.style.top = (parentElPos.height/2) + y - (clonePos.height/2) + 'px'; cloneEl.style.left = (parentElPos.width/2) + x - (clonePos.width/2) + 'px'; }; }; Cell.prototype.init = function () { if (!this.cellType) throw 'must provide cell type like div or span'; var contentContainerEl; this.cellEl = document.createElement(this.cellType); this.labelNode = document.createTextNode(this.label); if (this.cellContentType) { contentContainerEl = document.createElement(this.cellContentType); contentContainerEl.appendChild(this.labelNode); this.cellEl.appendChild(contentContainerEl); } else { this.cellEl.appendChild(this.labelNode); } this.cellEl.className = 'cell'; this.cellEl.style.width = this.width + 'px'; this.cellEl.style.height = this.height + 'px'; this.cellEl.style.lineHeight = this.height + 'px'; // this calls 'handleEvent' fn above. this.cellEl.addEventListener('click', this, false); }; Cell.prototype.setLabel = function (label) { this.labelNode.nodeValue = label; }; var Grid = function(props) { this.gridEl = props && props.gridEl || undefined; this.cellType = props && props.cellType || 'div'; this.rows = props && props.rows || 0; this.columns = props && props.columns || 0; this.width = props && props.width || 0; this.height = props && props.height || 0; this.cellCount = this.rows * this.columns; this.cellContentType = props.cellContentType || undefined this.cells = []; }; Grid.prototype.addCell = function(props) { var cell = new Cell(props); cell.init(); cell.setLabel(this.cells.length + 1); this.cells.push(cell); this.gridEl.appendChild(cell.cellEl); }; Grid.prototype.removeCell = function(elNode) { var removedEl = this.cells.pop(); removedEl && removedEl.destroy(); this.gridEl.removeChild(this.gridEl.lastChild); }; Grid.prototype.init = function() { if(!this.gridEl) { throw 'Grid element required!'; } if(this.rows <= 0 || this.columns <= 0) { throw 'rows and columns must be above 0'; } this.gridEl.style.width = this.width + 'px'; for (var i = 0; i < this.cellCount; i++){ var cellProps = { width: this.width / this.columns, height: this.width / this.columns, cellType: this.cellType, parentEl: this.gridEl.parentNode, cellContentType: this.cellContentType }; this.addCell(cellProps); } }; Grid.prototype.clearAll = function() { while(this.gridEl.lastChild) { this.removeCell(); } }; Grid.prototype.update = function(props) { // not efficiant but it works. this.clearAll(); this.rows = props && props.rows || this.rows; this.columns = props && props.columns || this.columns; this.width = props && props.width || this.width; this.height = props && props.height || this.height; this.cellCount = this.rows * this.columns; for (var i = 0; i < this.cellCount; i++) { var cellProps = { id: i, width: this.width / this.columns, height: this.width / this.columns, cellType: this.cellType, cellContentType: this.cellContentType, parentEl: this.gridEl.parentNode }; this.addCell(cellProps); } }; import React from "react" import { View, Image, ImageBackground, TouchableOpacity, Text, Button, Switch, TextInput, StyleSheet, ScrollView } from "react-native" import Icon from "react-native-vector-icons/FontAwesome" import { CheckBox } from "react-native-elements" import { connect } from "react-redux" import { widthPercentageToDP as wp, heightPercentageToDP as hp } from "react-native-responsive-screen" import { getNavigationScreen } from "@screens" export class Blank extends React.Component { constructor(props) { super(props) this.state = {} } render = () => ( Requests 9:41 27 Aug- 28 Aug, 2021 2 Days Ago Business Trip 27 Aug- 28 Aug, 2021 2 Days Ago Overtime Request 27 Aug- 28 Aug, 2021 2 Days Ago Mason Robert Request for Business Trip 27 Aug- 28 Aug, 2021 2 Days Ago Factory Visit Request 27 Aug- 28 Aug, 2021 2 Days Ago Deport Visit Request 27 Aug- 28 Aug, 2021 2 Days Ago Client Meeting Request Requested Cancelled Active ) } const styles = StyleSheet.create({ ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" }, View_2: { height: hp("114%") }, View_0_2971: { width: wp("100%"), minWidth: wp("100%"), height: hp("114%"), minHeight: hp("114%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2972: { width: wp("100%"), minWidth: wp("100%"), height: hp("114%"), minHeight: hp("114%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(249, 249, 255, 1)" }, View_0_2973: { width: wp("100%"), minWidth: wp("100%"), height: hp("14%"), minHeight: hp("14%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2974: { width: wp("100%"), minWidth: wp("100%"), height: hp("14%"), minHeight: hp("14%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2975: { width: wp("100%"), minWidth: wp("100%"), height: hp("14%"), minHeight: hp("14%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_2976: { width: wp("25%"), minWidth: wp("25%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("38%"), top: hp("7%") }, View_0_2977: { width: wp("25%"), minWidth: wp("25%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_2978: { width: wp("25%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_2978: { color: "rgba(25, 28, 36, 1)", fontSize: 18, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_2979: { width: wp("92%"), minWidth: wp("92%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_2980: { width: wp("9%"), minWidth: wp("9%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2981: { width: wp("9%"), minWidth: wp("9%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_2982: { width: wp("9%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_2982: { color: "rgba(25, 28, 36, 1)", fontSize: 13, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_2983: { width: wp("6%"), minWidth: wp("6%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("86%"), top: hp("1%") }, ImageBackground_0_2986: { width: wp("6%"), minWidth: wp("6%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2988: { width: wp("5%"), minWidth: wp("5%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("80%"), top: hp("1%") }, ImageBackground_0_2991: { width: wp("5%"), minWidth: wp("5%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_2993: { width: wp("5%"), minWidth: wp("5%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("74%"), top: hp("1%") }, View_0_2994: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("1%"), backgroundColor: "rgba(25, 28, 36, 1)" }, View_0_2995: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("1%"), top: hp("1%"), backgroundColor: "rgba(25, 28, 36, 1)" }, View_0_2996: { width: wp("1%"), minWidth: wp("1%"), height: hp("1%"), minHeight: hp("1%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("0%"), backgroundColor: "rgba(25, 28, 36, 1)" }, View_0_2997: { width: wp("1%"), minWidth: wp("1%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("0%"), backgroundColor: "rgba(25, 28, 36, 1)" }, ImageBackground_0_2998: { width: wp("3%"), minWidth: wp("3%"), height: hp("3%"), minHeight: hp("3%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("8%") }, View_0_3000: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("24%") }, View_0_3001: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3002: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3003: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3004: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3005: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3005: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3006: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3007: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3007: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3008: { width: wp("20%"), minWidth: wp("20%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3009: { width: wp("20%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3009: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3010: { width: wp("20%"), minWidth: wp("20%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3011: { width: wp("20%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3011: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3012: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3014: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3015: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3016: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3018: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3019: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3020: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3021: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3023: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("38%") }, View_0_3024: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3025: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3026: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3027: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3028: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3028: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3029: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3030: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3030: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3031: { width: wp("17%"), minWidth: wp("17%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3032: { width: wp("17%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3032: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3033: { width: wp("26%"), minWidth: wp("26%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3034: { width: wp("26%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3034: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3035: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3037: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3038: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3039: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3041: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3042: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3043: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3044: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3046: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("53%") }, View_0_3047: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3048: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3049: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3050: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3051: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3051: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3052: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3053: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3053: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3054: { width: wp("24%"), minWidth: wp("24%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3055: { width: wp("24%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3055: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3056: { width: wp("37%"), minWidth: wp("37%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3057: { width: wp("37%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3057: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3058: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3060: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3061: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3062: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3064: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3065: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3066: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3067: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3069: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("67%") }, View_0_3070: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3071: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3072: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3073: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3074: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3074: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3075: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3076: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3076: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3077: { width: wp("21%"), minWidth: wp("21%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3078: { width: wp("21%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3078: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3079: { width: wp("31%"), minWidth: wp("31%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3080: { width: wp("31%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3080: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3081: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3083: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3084: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3085: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3087: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3088: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3089: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3090: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3092: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("81%") }, View_0_3093: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3094: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3095: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3096: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3097: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3097: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3098: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3099: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3099: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3100: { width: wp("23%"), minWidth: wp("23%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3101: { width: wp("23%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3101: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3102: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3103: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3103: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3104: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3106: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3107: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3108: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3110: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3111: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3112: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3113: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3115: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("96%") }, View_0_3116: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3117: { width: wp("89%"), minWidth: wp("89%"), height: hp("12%"), minHeight: hp("12%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3118: { width: wp("62%"), minWidth: wp("62%"), height: hp("7%"), minHeight: hp("7%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("24%"), top: hp("2%") }, View_0_3119: { width: wp("30%"), minWidth: wp("30%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("3%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3120: { width: wp("30%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3120: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3121: { width: wp("16%"), minWidth: wp("16%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("46%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3122: { width: wp("16%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3122: { color: "rgba(166, 163, 184, 1)", fontSize: 10, fontWeight: "400", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3123: { width: wp("17%"), minWidth: wp("17%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3124: { width: wp("17%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3124: { color: "rgba(25, 28, 36, 1)", fontSize: 11, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3125: { width: wp("34%"), minWidth: wp("34%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("5%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3126: { width: wp("34%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3126: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "700", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, ImageBackground_0_3127: { width: wp("16%"), minWidth: wp("16%"), height: hp("8%"), minHeight: hp("8%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("4%"), top: hp("2%") }, View_0_3129: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("66%"), top: hp("6%") }, View_0_3130: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 92, 58, 1)" }, ImageBackground_0_3131: { width: wp("3%"), minWidth: wp("3%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("3%"), top: hp("1%") }, View_0_3133: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("78%"), top: hp("6%") }, View_0_3134: { width: wp("8%"), minWidth: wp("8%"), height: hp("4%"), minHeight: hp("4%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(77, 185, 72, 1)" }, View_0_3135: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("2%"), top: hp("1%") }, ImageBackground_0_3136: { width: wp("4%"), minWidth: wp("4%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3138: { width: wp("89%"), minWidth: wp("89%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("16%") }, View_0_3139: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%") }, View_0_3140: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(28, 103, 246, 1)" }, View_0_3141: { width: wp("18%"), minWidth: wp("18%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("5%"), top: hp("1%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3142: { width: wp("18%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3142: { color: "rgba(255, 255, 255, 1)", fontSize: 11, fontWeight: "500", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3143: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("62%"), top: hp("0%") }, View_0_3144: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3145: { width: wp("14%"), minWidth: wp("14%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("6%"), top: hp("2%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3146: { width: wp("14%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3146: { color: "rgba(28, 103, 246, 1)", fontSize: 10, fontWeight: "500", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" }, View_0_3147: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("31%"), top: hp("0%") }, View_0_3148: { width: wp("27%"), minWidth: wp("27%"), height: hp("5%"), minHeight: hp("5%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), backgroundColor: "rgba(255, 255, 255, 1)" }, View_0_3149: { width: wp("11%"), minWidth: wp("11%"), height: hp("2%"), minHeight: hp("2%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("8%"), top: hp("1%"), backgroundColor: "rgba(0, 0, 0, 0)", overflow: "hidden" }, View_0_3150: { width: wp("11%"), marginLeft: 0, marginTop: 0, position: "absolute", left: wp("0%"), top: hp("0%"), justifyContent: "flex-start" }, Text_0_3150: { color: "rgba(28, 103, 246, 1)", fontSize: 11, fontWeight: "500", textAlign: "left", fontStyle: "normal", letterSpacing: 0, textTransform: "none" } }) const mapStateToProps = state => { return {} } const mapDispatchToProps = () => { return {} } export default connect(mapStateToProps, mapDispatchToProps)(Blank) 0 import React, { Component } from 'react'; import NavBar from './components/main/NavBar'; import Main from './components/main/Main'; import Footer from './components/main/Footer'; import { BrowserRouter as Router } from 'react-router-dom'; import AppProvider from './provider/Provider'; class App extends Component { render() { return (
    ); } } export default App; 'use strict'; const restify = require('restify'); const errors = require('restify-errors'); const yaml = require('js-yaml'); const fs = require('fs'); const bunyan = require('bunyan'); let config = {}; try { config = yaml.safeLoad(fs.readFileSync('./config.yml', 'utf8')); } catch (e) { console.log(e); } const server = restify.createServer(); server.use(restify.plugins.gzipResponse()); server.use(restify.plugins.bodyParser({ mapParams: true })); server.use(restify.plugins.throttle(config.rateLimiter)); let inflightRateLimiter = { limit: config.rateLimiter.limit, err: new errors.InternalServerError(), server: server }; let throttle = restify.plugins.inflightRequestThrottle(inflightRateLimiter); // server.pre(throttle); const TokenBucket = require('simple-token-bucket'); let kentikTokenBuket = new TokenBucket({ capacity: config.kenitkOptions.rateLimitPerHr, fillQuantity: 1, // fillTime: 3600000/config.kenitkOptions.rateLimitPerHr, fillTime: 3600, initialCapacity: config.kenitkOptions.rateLimitPerHr }); config.kenitkOptions.tokenBuket = kentikTokenBuket; const controllers = require('./controllers')(config); const serverPort = process.env.PORT; const serverIpAddress = process.env.IP; server.get('/query/ip/activity/:targetIp', throttle, controllers.getActivityForIp); server.post('/query/url', throttle, controllers.getPortalUrl); server.get('/*', restify.plugins.serveStatic({ directory: './public', default: 'index.html', charSet: 'utf-8', maxAge: 1 })); server.on('NotFound', function(req, res, err, next) { res.redirect({ pathname: '/', permanent: true, }, next); }); let ringbuffer = new bunyan.RingBuffer({ limit: 100 }); server.on('after', restify.plugins.auditLogger({ log: bunyan.createLogger({ name: 'flowCheck', streams: [{ level: 'info', stream: process.stdout, },{ level: 'info', path: './audit.log', },{ level: 'error', stream: process.stderr, }, { level: 'trace', type: 'raw', // use 'raw' to get raw log record objects stream: ringbuffer }], }), event: 'after', server: server, printLog : true, body: true, })); server.listen(serverPort, serverIpAddress, function() { console.log('%s listening at %s', server.name, server.url); });src/main/webapp/admin/assets/js/ToolTip.js function getViewportHeight() { if (window.innerHeight!=window.undefined) return window.innerHeight; if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight; if (document.body) return document.body.clientHeight; return window.undefined; } function getViewportWidth() { if (window.innerWidth!=window.undefined) return window.innerWidth; if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; if (document.body) return document.body.clientWidth; return window.undefined; } /** * Gets the real scroll top */ function getScrollTop() { if (self.pageYOffset) // all except Explorer { return self.pageYOffset; } else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict { return document.documentElement.scrollTop; } else if (document.body) // all other Explorers { return document.body.scrollTop; } } function getScrollLeft() { if (self.pageXOffset) // all except Explorer { return self.pageXOffset; } else if (document.documentElement && document.documentElement.scrollLeft) // Explorer 6 Strict { return document.documentElement.scrollLeft; } else if (document.body) // all other Explorers { return document.body.scrollLeft; } } /* �????��?��??? 使�??��?�? �?oolTip.js????��?�?ody??????签�? �???��?�? �?��CSS?��? .trans_msg { filter:alpha(opacity=100,enabled=1) revealTrans(duration=.2,transition=1) blendtrans(duration=.2); } */ //--????????-- var rT=true;//????��?�?�� var bT=true;//????��?淡�?淡�? var tw=150;//??���??�? var endaction=false;//�???��? var ns4 = document.layers; var ns6 = document.getElementById && !document.all; var ie4 = document.all; offsetX = 10; offsetY = 20; var toolTipSTYLE=""; function initToolTips() { tempDiv = document.createElement("div"); tempDiv.id = "toolTipLayer"; tempDiv.style.position = "absolute"; tempDiv.style.display = "none"; document.body.appendChild(tempDiv); if(ns4||ns6||ie4) { if(ns4) toolTipSTYLE = document.toolTipLayer; else if(ns6) toolTipSTYLE = document.getElementById("toolTipLayer").style; else if(ie4) toolTipSTYLE = document.all.toolTipLayer.style; if(ns4) document.captureEvents(Event.MOUSEMOVE); else { toolTipSTYLE.visibility = "visible"; toolTipSTYLE.display = "none"; } document.onmousemove = moveToMouseLoc; } } function toolTip(msg, fg, bg) { try { if(toolTip.arguments.length < 1) // hide { if(ns4) { toolTipSTYLE.visibility = "hidden"; } else { //--?�象�?���?��?��???-- if (!endaction) {toolTipSTYLE.display = "none";} if (rT) document.all("msg1").filters[1].Apply(); if (bT) document.all("msg1").filters[2].Apply(); document.all("msg1").filters[0].opacity=0; if (rT) document.all("msg1").filters[1].Play(); if (bT) document.all("msg1").filters[2].Play(); if (rT){ if (document.all("msg1").filters[1].status==1 || document.all("msg1").filters[1].status==0){ toolTipSTYLE.display = "none";} } if (bT){ if (document.all("msg1").filters[2].status==1 || document.all("msg1").filters[2].status==0){ toolTipSTYLE.display = "none";} } if (!rT && !bT) toolTipSTYLE.display = "none"; //---------------------- } } else // show { if(!fg) fg = "#777777"; if(!bg) bg = "#eeeeee"; var content = '
    ' + '
    ' + msg + '
    '; if(ns4) { toolTipSTYLE.document.write(content); toolTipSTYLE.document.close(); toolTipSTYLE.visibility = "visible"; } if(ns6) { document.getElementById("toolTipLayer").innerHTML = content; toolTipSTYLE.display='block' } if(ie4) { document.all("toolTipLayer").innerHTML=content; toolTipSTYLE.display='block' //--?�象�?���?��?��???-- var cssopaction=document.all("msg1").filters[0].opacity document.all("msg1").filters[0].opacity=0; if (rT) document.all("msg1").filters[1].Apply(); if (bT) document.all("msg1").filters[2].Apply(); document.all("msg1").filters[0].opacity=cssopaction; if (rT) document.all("msg1").filters[1].Play(); if (bT) document.all("msg1").filters[2].Play(); //---------------------- } } } catch(e) {} } function moveToMouseLoc(e) { var scrollTop = getScrollTop(); var scrollLeft = getScrollLeft(); if(ns4||ns6) { x = e.pageX + scrollLeft; y = e.pageY - scrollTop; } else { x = event.clientX + scrollLeft; y = event.clientY; } if (x-scrollLeft > getViewportWidth() / 2) { x = x - document.getElementById("toolTipLayer").offsetWidth - 2 * offsetX; } if ((y+document.getElementById("toolTipLayer").offsetHeight+offsetY)>getViewportHeight()) { y = getViewportHeight()-document.getElementById("toolTipLayer").offsetHeight-offsetY; } toolTipSTYLE.left = (x + offsetX)+'px'; toolTipSTYLE.top = (y + offsetY + scrollTop)+'px'; return true; } initToolTips(); 1-10 import React from "react"; import mug from "../images/bartdority_pic2.jpg"; import sql from "../images/shields/sql.png"; import express from "../images/shields/express.png"; import react from "../images/shields/react.png"; import node from "../images/shields/node.png"; import sequelize from "../images/shields/sequelize.png"; import { Link } from "react-router-dom"; import Shield from "../components/Shield"; import Page from "../components/Page"; import Logo from "../components/Logo"; import "./Home.scss"; function Home() { // These are my animation timers let bio = `Passionate about the web, and addicted to learning. I apply the Bauhaus school of design theory to software development with a focus on reducing cognitive friction to create intuitive interfaces. As a digital polyglot, I have the knowledge and understanding of a broad range of creative and web development technologies, which allows me to think in terms of common principles and design systems. I’m currently looking to join a team of engineers who enjoy collaborating to build apps that benefit the people who use them. `; bio = `I have a deep knowledge of a broad range of web development technologies and computer science. I also have extensive experience in advertising, animation, marketing and design. I build applications that people find intuitive, and I’m looking to join a team of engineers that enjoy collaborating and value life-long learning.`; function Desktop() { return ( <>
    <NAME>

    Current Development Stack:

    ); } function BioBlock() { return (
    {bio}
    Skills
    Projects

    resume
    endorsements
    ); } function Mobile() { return (

    Current Development Stack:

    shield
    shield
    shield
    shield
    shield
    ); } function pageContent() { return ( <> ) } return ( ); } export default Home; export { default } from './createFileSync' samuelndm/checklist-ninja0 const express = require('express') const bodyParser = require('body-parser') const cors = require('cors') const routes = require('./routes/routes') require('./database') const app = express() const PORT = process.env.PORT || 3000 app.use(cors()) app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.use(routes) app.listen(PORT, () => { console.log('Listening on port: ' + PORT) }) public/Widget.js class Widget { constructor(name, x, y, w, h, func) { this.name = name; this.x = x; this.y = y; this.w = w; this.h = h; this.func = func; this.update = function () { func(this.name, this.x, this.y, this.w, this.h); }; } }/** * User item tests */ import React from 'react'; import { render } from 'react-testing-library'; import { IntlProvider } from 'react-intl'; import { Provider } from 'react-redux'; import { browserHistory } from 'react-router-dom'; import configureStore from '../../../configureStore'; import UserItem from '../index'; import { DEFAULT_LOCALE } from '../../../i18n'; describe('', () => { let store; const user = { name: 'test', isBlocked: false, }; const myLevel = 'user'; beforeAll(() => { store = configureStore({}, browserHistory); }); it('Expect to not log errors in console', () => { const spy = jest.spyOn(global.console, 'error'); render( , ); expect(spy).not.toHaveBeenCalled(); }); }); import React from 'react'; import 'boxicons'; import Paper from '@mui/material/Paper'; import Stack from '@mui/material/Stack'; import { styled } from '@mui/material/styles'; const Item = styled(Paper)(({ theme }) => ({ ...theme.typography.body2, padding: theme.spacing(1), textAlign: 'center', color: theme.palette.text.secondary, })); function Dashboard() { // React Hooks return ( <>
    Patient Dashboard
    You have 2 appointments in this month
    Your have 0 messages
    ); } export default Dashboard; packages/doars/src/Component.js // Import symbols. import { COMPONENT } from './symbols.js' // Import classes. import Attribute from './Attribute.js' // Import proxy dispatcher. import ProxyDispatcher from './events/ProxyDispatcher.js' // Import utils. import { morphNode, morphTree } from './utils/MorphUtils.js' import { closestComponent } from './utils/ComponentUtils.js' import { executeExpression } from './utils/ExpressionUtils.js' import { transition, transitionIn, transitionOut } from './utils/TransitionUtils.js' import { walk } from './utils/ElementUtils.js' // Create an object with utility function. const DIRECTIVE_UTILS = Object.freeze({ executeExpression: executeExpression, morphNode: morphNode, morphTree: morphTree, transition: transition, transitionIn: transitionIn, transitionOut: transitionOut, }) export default class Component { /** * Create instance. * @param {Doars} library Library instance. * @param {HTMLElement} element Element. */ constructor(library, element) { // Create unique ID. const id = Symbol('ID_COMPONENT') // Deconstruct library options. const { prefix } = library.getOptions() // create private variables. let attributes = [], hasUpdated = false, isInitialized = false, data, proxy, state // Check if element has a state attribute. if (!element.attributes[prefix + '-state']) { console.error('Doars: element given to component does not contain a state attribute!') return } // Add reference to element. element[COMPONENT] = this // Update position in hierarchy. const children = [] // Get current parent component. let parent = closestComponent(element) if (parent) { // Add to list of children in parent. if (!parent.getChildren().includes(this)) { parent.getChildren().push(this) // Trigger children update. library.update([{ id: parent.getId(), path: 'children', }]) } } /** * Get the attributes in this component. * @returns {Array} List of attributes. */ this.getAttributes = () => { return attributes } /** * Get child components in hierarchy of this component. * @returns {Array} List of components. */ this.getChildren = () => { return children } /** * Get root element of the component. * @returns {HTMLElement} Element. */ this.getElement = () => { return element } /** * Get component id. * @returns {Symbol} Unique identifier. */ this.getId = () => { return id } /** * Get the library instance this component is from. * @returns {Doars} Doars instance. */ this.getLibrary = () => { return library } /** * Get parent component in hierarchy of this component. * @returns {Component} Component. */ this.getParent = () => { return parent } /** * Get the event dispatcher of state's proxy. * @returns {ProxyDispatcher} State's proxy dispatcher. */ this.getProxy = () => { return proxy } /** * Get the component's state. * @returns {Proxy} State. */ this.getState = () => { return state } /** * Set new parent component of this component. * @param {Component} _parent Parent component. */ this.setParent = (_parent) => { parent = _parent } /** * Initialize the component. */ this.initialize = () => { if (isInitialized) { return } // Set as enabled. isInitialized = true // Get component's state attribute. const componentName = prefix + '-state' const value = element.attributes[componentName].value // Execute expression for generating the state using a mock attribute. data = executeExpression(this, new Attribute(this, element, null, value), value) ?? {} if (Array.isArray(data) || typeof (data) !== 'object') { console.error('Doars: component tag must return an object!') return } // Create proxy dispatcher for state. proxy = new ProxyDispatcher() // Add data to dispatcher to create the state. state = proxy.add(data) // Scan for attributes. this.scanAttributes(element) } /** * Destroy the component. */ this.destroy = () => { if (!isInitialized) { return } if (attributes.length > 0) { // Filter out directives without a destroy function. const directives = library.getDirectivesObject() for (const key in directives) { if (!directives[key].destroy) { directives[key] = undefined } } for (const attribute of attributes) { // Clean up attribute if the directive has a destroy function. const directive = directives[attribute.getKey()] if (directive) { directive.destroy(this, attribute, DIRECTIVE_UTILS) } // Destroy the attribute. attribute.destroy() } } // Remove reference from element. delete element[COMPONENT] // Reset variables. attributes = [] // Set as not initialized. isInitialized = false // Remove state and state handling. proxy.remove(data) state = null proxy = null data = null // Store update triggers. const triggers = [] // Set children as children of parent. if (children.length > 0) { for (const child of children) { // Set new parent of children. child.setParent(parent) // Add parent update trigger. triggers.push({ id: child.getId(), path: 'parent', }) } // Add children update trigger. triggers.push({ id: id, path: 'children', }) } if (parent) { if (children.length > 0) { // Add children to parent. parent.getChildren().push(...children) // Add children update trigger. triggers.push({ id: parent.getId(), path: 'children', }) } // Add parent update trigger. triggers.push({ id: id, path: 'parent', }) } // Dispatch triggers. if (triggers.length > 0) { library.update(triggers) } // Dispatch event. dispatchEvent('destroyed', { element: element, id: id, }) } /** * Create and add an attribute. Assumes this attribute has not been added before. * @param {HTMLElement} element Attribute element. * @param {String} name Name of the attribute. * @param {String} value Value of the attribute. * @returns {Attribute} New attribute. */ this.addAttribute = (element, name, value) => { // Get directive keys from library. const directivesKeys = library.getDirectivesNames() // Create and add attribute. const attribute = new Attribute(this, element, name, value) // Get index to add attribute at. let index = attribute.length const directiveIndex = directivesKeys.indexOf(attribute.getDirective()) for (let i = attributes.length - 1; i >= 0; i--) { // If the other attribute is further down the keys list than add it after that item. if (directivesKeys.indexOf(attributes[i].getDirective()) <= directiveIndex) { index = i + 1 break } } // Add to list of attributes. attributes.splice(index, 0, attribute) // Return new attribute. return attribute } /** * Remove an attribute. * @param {Attribute} attribute The attribute to remove. */ this.removeAttribute = (attribute) => { // Get index of attribute in list. const indexInAttributes = attributes.indexOf(attribute) if (indexInAttributes < 0) { return } // Get directives. const directives = library.getDirectivesObject // Attribute has been removed, call the destroy directive. const directive = directives[attribute.getKey()] if (directive && directive.destroy) { directive.destroy(this, attribute, DIRECTIVE_UTILS) } // Remove attribute from list. attributes.splice(indexInAttributes, 1) // Destroy attribute. attribute.destroy() } /** * Scans element for new attributes. It assumes this element as not been read before and is part of the component. * @param {HTMLElement} element Element to scan. * @returns {Array} New attributes. */ this.scanAttributes = (element) => { // Get component's state attribute. const componentName = prefix + '-state' const ignoreName = prefix + '-ignore' // Store new attributes. const newAttributes = [] // Create iterator for walking over all elements in the component, skipping elements that are components or contain the ignore directive. const iterator = walk(element, (element) => !element.hasAttribute(componentName) && !element.hasAttribute(ignoreName)) // Start on the given element then continue iterating over all children. do { for (const { name, value } of element.attributes) { // Skip attribute if it is not that of a directive. if (library.isDirectiveName(name)) { newAttributes.push(this.addAttribute(element, name, value)) } } } while (element = iterator()) // Return new attributes. return newAttributes } /** * Update an attribute. * @param {Attribute} attribute The attribute to update. */ this.updateAttribute = (attribute) => { // Check if the attribute is still relevant, since the attribute or element could have been removed. if (!attribute.getElement() || attribute.getValue() === null || attribute.getValue() === undefined) { this.removeAttribute(attribute) return } // Get directives. const directives = library.getDirectivesObject() // Clear accessed. attribute.clearAccessed() // Execute directive on attribute. const directive = directives[attribute.getDirective()] if (directive) { directive.update(this, attribute, DIRECTIVE_UTILS) } } /** * Update the specified attributes of the component. * @param {Array} attributes Attributes to update. */ this.updateAttributes = (attributes) => { if (!isInitialized || attributes.length <= 0) { if (!hasUpdated) { // Dispatch updated event anyway. hasUpdated = true dispatchEvent('updated', { attributes: attributes, element: element, id: id, }) } return } for (const attribute of attributes) { this.updateAttribute(attribute) } // Dispatch updated event. hasUpdated = true dispatchEvent('updated', { attributes: attributes, element: element, id: id, }) } /** * Start updating the component's attributes. * @param {Array} triggers List of triggers. */ this.update = (triggers) => { if (!isInitialized) { return } // Get all ids of triggers. const triggerIds = Object.getOwnPropertySymbols(triggers) // Update all attributes whose accessed items match any update trigger. const updatedAttributes = [] for (const attribute of attributes) { for (const id of triggerIds) { if (attribute.hasAccessed(id, triggers[id])) { this.updateAttribute(attribute) updatedAttributes.push(attribute) } } } // Dispatch updated event. if (!hasUpdated || updatedAttributes.length > 0) { hasUpdated = true dispatchEvent('updated', { attributes: updatedAttributes, element: element, id: id, }) } } /** * Dispatch an event from this component. * @param {String} name Name of the event. */ const dispatchEvent = (name, detail) => { element.dispatchEvent( new CustomEvent(prefix + '-' + name, { detail: detail, bubbles: true, }) ) } } } nahidakbar/d3-html /** * selection.Td() creates <td> element * @param {string} [contents=''] option content html * @return created element */ export default function (contents) { return this.append('td') .html(contents || ''); } /*funcunit@3.6.3#browser/adapters/qunit2*/ define('funcunit/browser/adapters/qunit2', function (require, exports, module) { module.exports = function (runner) { var doneStack = []; var getCurrentAssert = function () { if (runner.config.current) { return runner.config.current.assert; } throw new Error('Outside of test context'); }; return { pauseTest: function () { doneStack.push(getCurrentAssert().async()); }, resumeTest: function () { doneStack.pop()(); }, assertOK: function (assertion, message) { getCurrentAssert().ok(assertion, message); }, equiv: function (expected, actual) { return runner.equiv(expected, actual); } }; }; });1-10 import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; import { mixins, Paragraph, Button } from '@styles'; import { useShoppingCart } from 'use-shopping-cart'; const StyledWrapper = styled.div` display: flex; border: 1px solid ${({ theme }) => theme.white }; background-color: ${({ theme }) => theme.gray100 }; position: relative; width: 100%; `; const StyledFigure = styled.figure` ${mixins.flexCenter}; min-width: 100px; max-width: 100px; padding: 10px; img { width: 100%; } `; const StyledDescription = styled.div` ${mixins.flexBetween}; flex-direction: column; margin-right: 20px; width: 100%; `; const StyledFlex = styled.div` ${mixins.flexBetween}; width: 100%; `; const StyledQuantity = styled.div` ${mixins.flexBetween}; width: 50px; `; const CartPreview = ({ item }) => { const { removeCartItem, reduceItemByOne, addItem } = useShoppingCart() const { name, sku, formattedValue, image, quantity } = item; return( {quantity} ) } CartPreview.propTypes = { item: PropTypes.shape({ name: PropTypes.string, currency: PropTypes.string, price: PropTypes.number, sku: PropTypes.string, image: PropTypes.object }).isRequired } export default CartPreview;// Booleans return True or False // Bo0leans are like C++ (Not like Java) var x = 5; var y = 5; var z = 6; console.log((x == y)); // Returns true console.log((x == z)); flag = x ==x; console.log(flag+1); // internally a flag is '1'whtsky/babel-plugin-webpack-prefetch const { join } = require('path') const { readdirSync, statSync, readFileSync } = require('fs') const { transform: transformBabel7 } = require('@babel/core') const { transform: transformBabel6 } = require('babel-core') const FIXTURE_PATH = join(__dirname, 'fixtures') const PLUGIN_FILE = join(__dirname, '../index.js') const plugin = require(PLUGIN_FILE) const testFolders = readdirSync(FIXTURE_PATH).filter(file => statSync(join(FIXTURE_PATH, file)).isDirectory(), ) function transformInput(input, config, transform) { const result = transform(input, { plugins: [[plugin, config]], }) return result.code } describe('babel-plugin-webpack-prefetch', () => { testFolders.forEach(folderName => { let config try { config = require(join(FIXTURE_PATH, folderName, 'config.js')) } catch (e) { // don't care } const input = readFileSync( join(FIXTURE_PATH, folderName, 'input.js'), 'utf8', ) it(`${folderName} matches snapshot for babel 7`, () => { const result = transformInput(input, config, transformBabel7) expect(result.trim()).toMatchSnapshot(folderName) }) it(`${folderName} matches snapshot for babel 6`, () => { const result = transformInput(input, config, transformBabel6) expect(result.trim()).toMatchSnapshot(folderName) }) }) }) 0 import React, { Component } from "react"; import { Link } from "react-router-dom"; class BankDetails extends Component { constructor(props) { super(props); this.state = { item: props.item }; } render() { return (

    Back

    IFSC CODE Details: {this.props.location.state.ifsc}

    • Bank Id :

      {" "} {this.props.location.state.id}
    • Bank Address :

      {" "} {this.props.location.state.address}
    • Bank:

      {this.props.location.state.bank}
    • Bank Branch:

      {this.props.location.state.branch}
    • Bank Branch City:

      {this.props.location.state.city}
    • Bank Branch Number:

      {this.props.location.state.contact}
    • Bank Branch District:

      {this.props.location.state.district}
    • Bank Branch Micrcode:

      {this.props.location.state.micrcode}
    • Bank Branch State:

      {this.props.location.state.state}
    ); } } export default BankDetails; const mongooose = require('mongoose'); const userSchema = new mongooose.Schema({ name: { type: String, required:true }, email: { type: String, required:true }, phone: { type: Number, required:true }, profation: { type: String, required:true }, }) const User = mongooose.model('USER', userSchema); module.exports = User;const mongoose = require('mongoose') // Mongoose connection mongoose.Promise = global.Promise const uri = process.env.MONGODB_URI mongoose.connect(uri, { useNewUrlParser: true, useFindAndModify: false }) .then(() => { console.info('MongoDB connected successfully') }) .catch((err) => { console.error(err) }) mongoose.connection.on('error', (err) => { console.error(err) console.error('MongoDB connection error. Please make sure MongoDB is running.') process.exit() }) agmen-hu/consoloid-console defineClass('Consoloid.Interpreter.Expression', 'Consoloid.Interpreter.Tokenizable', { __constructor: function(options) { this.__base(options); this.requireProperty('sentence'); this.requireProperty('pattern'); this.__validate(); this._tokenize(this.pattern); }, getText: function() { return this.pattern; }, __validate: function() { var words = this.pattern.split(" "); var $this = this; $.each(words, function(index, word) { var isArgumentValue = (word[0] == '<' && word[word.length - 1] == '>'); if (isArgumentValue) { var argumentName = word.substr(1, word.length - 2); if (!$this.sentence.hasArgument(argumentName)) { throw new Error('No such argument: ' + argumentName); } } }); }, hasInlineArguments: function() { return this.tokens.some(function(token, index){ if (token.getType() == Consoloid.Interpreter.Token.ARGUMENT_VALUE) { return true; } }); }, hasInlineArgument: function(name) { return this.tokens.some(function(token, index){ if (token.getText() == name && token.getType() == Consoloid.Interpreter.Token.ARGUMENT_VALUE) { return true; } }); }, getSentence: function() { return this.sentence; }, getTextWithArguments: function(values) { var result = this.pattern; var argTexts = []; var $this = this; $.each(values, function(name, value) { if (result.indexOf('<' + name + '>') != -1 ) { result = result.replace('<' + name + '>', value.value.indexOf(' ') == -1 ? value.value : '"'+value.value+'"'); } else if ($this.fixedArguments[name] == undefined) { if (!(name in $this.getSentence().arguments)) { throw new Error(name + ' is not in arguments of sentence: ' + $this.text); } argTexts.push($this.getSentence().arguments[name].getText(value.value)); } }); if (argTexts.length > 0) { result += ', ' + argTexts.join(', '); } return result; }, getAutocompleteScore: function(words, args) { var $this = this; var tokens = this.tokens; var exactMatch = (words.length == tokens.length); var partialMatch = true; var noMatch = true; var argumentScore = this.__getAutocompleteScoreForArgument(args); $.each(words, function(index, word) { if (tokens[index].type == Consoloid.Interpreter.Token.ARGUMENT_VALUE) { return; } if (tokens.length < index + 1 || tokens[index].getText().substr(0, word.length).toLowerCase() != word.toLowerCase()) { exactMatch = false; } if (!$this.__wordMatchesAToken.apply($this, [ word, tokens] )) { partialMatch = false; } else { noMatch = false; } }); if (exactMatch) { return Consoloid.Interpreter.Expression.EXACT_MATCH + argumentScore; } else if (partialMatch) { return Consoloid.Interpreter.Expression.PARTIAL_MATCH + argumentScore; } else if (noMatch) { return Consoloid.Interpreter.Expression.NO_MATCH + argumentScore; } return Consoloid.Interpreter.Expression.CONTAINS_NONMATCHING_WORDS + argumentScore; }, __getAutocompleteScoreForArgument: function(args) { var score = 0, exp = Consoloid.Interpreter.Expression; Object.keys(args).forEach(function(arg){ if (args[arg].erroneous) { score += exp.NO_ARGUMENT_MATCH; return; } score += args[arg].exactMatch ? exp.EXACT_ARGUMENT_MATCH : exp.PARTIAL_ARGUMENT_MATCH; }); return score; }, __wordMatchesAToken: function(word, tokens) { var result = false; $.each(tokens, function(index, token) { result |= (token.getText().toLowerCase().substr(0, word.length) == word.toLowerCase()); }); return result; }, areArgumentsValid: function(args) { var result = true; args = $.extend(args || {}, this.fixedArguments); $.each(this.sentence.arguments, function(name, argument) { if ((argument.isRequired() && !(name in args)) || (name in args && args[name].erroneous)) { result = false; } }); return result; }, doIt: function(args) { args = $.extend(args || {}, this.fixedArguments); var service = this.get(this.sentence.service); return service[this.sentence.method].apply(service, [ args, this ]); } }, { EXACT_MATCH: 3, PARTIAL_MATCH: 2, CONTAINS_NONMATCHING_WORDS: 1, NO_MATCH: 0, EXACT_ARGUMENT_MATCH: 0.02, PARTIAL_ARGUMENT_MATCH: 0.01, NO_ARGUMENT_MATCH: 0 } ); Curtis-Hatter/Nuke-Character-Creatorclient/src/components/CharacterProgressBar/index.js import React from "react"; import { Link, useRouteMatch } from "react-router-dom"; // Selection Tab component import SelectionTab from "../SelectionTab"; // Starting CSS import "./style.css"; // This is our list of tabs that appears across the top of the creator const tabTitles = [ { title: "Name & Lvl", tabUrl: "name" }, { title: "Race", tabUrl: "race" }, // { title: "Stats", tabUrl: "stats" }, { title: "Class", tabUrl: "class" }, { title: "Subclass", tabUrl: "subclass" }, { title: "Spells", tabUrl: "spells" }, { title: "Feats", tabUrl: "feats" }, ]; // Important main function function CharacterProgressBar(props) { // This is what set up the actual url links. Fancy. let { url } = useRouteMatch(); return (
    {tabTitles.map(({ title, tabUrl }, i) => { return (
    ); })}
    ); } export default CharacterProgressBar; readme-experts/cyberchef 'use strict'; const db = require('../../database/db'); const { validationResult } = require('express-validator'); const tokenService = require('../service/token-service'); const bcrypt = require('bcrypt'); class AuthController { async registration(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res .status(400) .json({ message: 'Registration mistake', errors }); } const { username, password } = req.body; const hash = bcrypt.hashSync(password, 6); await db.addUserToDb(username, username, hash); return res.json({ message: 'user added succcesfully' }); } catch (e) { console.log(e); res.status(400).json({ message: 'Registration error' }); } } async login(req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { return res .status(400) .json({ message: 'Registration mistake', errors }); } const { username, password } = req.body; const user = await db.getUserData(username); if (!user) { return res .status(400) .json({ message: `user ${username} was not found` }); } const result = bcrypt.compareSync(password, user.password); if (!result) { return res.status(400).json({ message: `pass is not correct` }); } const token = tokenService.generateAccessToken(user.id); return res.json({ token, user }); } catch (e) { console.log(e); res.status(400).json({ message: 'Login error' }); } } } module.exports = new AuthController(); const questions = [ { type: 'input', name: 'files', message: 'Insert the path to the source file(s) (Space is a separator):\n' }, { type: 'list', name: 'format', message: 'Choose the output format for your formulae:', choices: [ 'MathML', 'SVG'], default: 0 }, { type: 'input', name: 'stylesheet', message: '[Optional] Insert a path to an external stylesheet:' }, { type: 'input', name: 'author', message: '[Optional] Author:' }, { type: 'confirm', name: 'watch', message: 'Do you want to watch for file changes and automatically reload the file preview in browser?', default: false } ] function buildHtml (title, pages, style, author) { return ` ${title}
    ${pages.join('')}
    ` } const formulaeOptions = { 'page': { format: ['TeX'], singleDollars: true, fragment: true, // only HTML body fontURL: 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/fonts/HTML-CSS' // for webfont urls in the CSS for HTML output }, 'node': { html: false, css: false, mml: true, svg: false } } const minify = { minifyCSS: true, removeComments: true, collapseWhitespace: true, conservativeCollapse: true } module.exports = { 'formulae': formulaeOptions, 'buildHtml': buildHtml, 'questions': questions, 'minify': minify } components/ReportPage/ProgressionWrapper.js import cx from 'clsx'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles({ root: { marginBottom: '-12.5vw', minHeight: '12.5vw', clipPath: 'polygon(0 0, 100% 0, 100% calc(100% - 12.5vw), 50% 100%, 0 calc(100% - 12.5vw))', }, }); /** * Wrapper of content with full-screen (its width should be always 100vw) triangular bottom. */ function ProgressionWrapper({ className, ...props }) { const classes = useStyles(); return
    ; } export default ProgressionWrapper; 1-10 import { DEFAULTJOB } from "./defs.js" export class MemProvider { /* LOCAL STORAGE MANAGEMENT * * When we store/retrieve keys in localStorage, * we always prepend a prefix to the key: * - a fixed part, marking that it is a layered search app * - a Config dependent part: the org and repo of the data * * We also store the last key used. * All content goes through JSON.stringify upon storing * and through JSON.parse upon retrieving. * * When retrieving content for non-existing keys, we silently return the empty object. * * localStorage for file:// urls is not clearly defined. * If several apps like this are being used in the same browser, * this practice will prevent collisions */ /* private members */ deps({ Log, Config }) { this.Config = Config this.tell = Log.tell } init() { const { Config: { org, repo, client } } = this this.appPrefix = `tf.client/${org}/${repo}/${client}/` this.keyLast = `${this.appPrefix}LastJob` this.keyPrefix = `${this.appPrefix}Keys/` this.keyLength = this.keyPrefix.length } getRawKey(userKey) {return `${this.keyPrefix}${userKey}`} getUserKey(rawKey) {return rawKey.substring(this.keyLength)} getLastKey() {return localStorage.getItem(this.keyLast)} /* public members */ getk(userKey) { /* retrieve stored content for a key * * Also store the key as last used key */ localStorage.setItem(this.keyLast, userKey) const rawKey = this.getRawKey(userKey) return JSON.parse(localStorage.getItem(rawKey) ?? "{}") } setk(userKey, content) { /* stored content behind a key */ const rawKey = this.getRawKey(userKey) localStorage.setItem(rawKey, JSON.stringify(content)) } remk(userKey) { /* delete key and its stored content * If the key happens to be the last key, * remove the last key * return the last available key if any, else the default key */ const rawKey = this.getRawKey(userKey) localStorage.removeItem(rawKey) const lastKey = this.getLastKey() if (userKey == lastKey) { localStorage.removeItem(this.keyLast) } const allKeys = this.keys() return (allKeys.length == 0) ? DEFAULTJOB : allKeys[allKeys.length - 1] } getkl() { /* retrieve stored content for the last key * * If there is no last key, take the last key * of all available keys, if any * and store that key as last key * * return both the key and the content */ let lastKey = localStorage.getItem(this.keyLast) let content if (lastKey == null) { const allKeys = this.keys() if (allKeys.length == 0) { lastKey = DEFAULTJOB content = {} localStorage.setItem(this.keyLast, lastKey) } else { lastKey = allKeys[allKeys.length - 1] content = this.getk(lastKey) } } else { content = this.getk(lastKey) } return [lastKey, content] } setkl(userKey, content) { /* store content behind a key and make it the last key */ this.setk(userKey, content) localStorage.setItem(this.keyLast, userKey) } keys() { /* get the ordered array of all stored keys */ const rawKeys = Object.keys(localStorage) .filter(rawKey => rawKey.startsWith(this.keyPrefix)) .map(rawKey => this.getUserKey(rawKey)) rawKeys.sort() return rawKeys } } let cruises; $(document).ready(function() { console.log('users.js loaded...'); listenForBookings(); $.getJSON("/cruises.json", function(result){ cruises=result; }); }) function listenForBookings() { $('#bookings').on('click', () => showBookings()); $('#newBooking').on('click', () => newBooking()); $('#sort').on('click', () =>sortBookings()); } function sortBookings(){ const url = '/users/1.json'; fetch(url, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' } }) .then(resp => resp.json()) .then(json => { json.bookings.sort(function(a, b) { var nameA = a.cruise.toUpperCase(); // ignore upper and lowercase var nameB = b.cruise.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; }); console.log(json.bookings) json.bookings.forEach(function(item){ let newItem = `
  • ${item.cruise}
  • ` $("#bookingsList").append(newItem) }) }); } function listenForSubmit() { $('form').submit(function(event) { event.preventDefault(); let values = new FormData(this); createNewBooking(values); }); } function showBookings() { let userId; fetch('/current_user', { method: 'GET', credentials: 'same-origin', }) .then(resp => resp.json()) .then(json => generateList(json["id"])); } function newBooking(){ $("#newBookingDiv").show(); let myBooking = Booking.newForm(); $("#newBookingDiv").html(myBooking); populateSelectCruise(); listenForSubmit(); } function generateList(userId) { const url = '/users/' + userId +'.json'; fetch(url, { method: 'GET', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' } }) .then(resp => resp.json()) .then(json => generateBookings(json)); } function generateBookings(data){ let myBooking; data["bookings"].forEach(function(el){ myBooking = new Booking(el); addBookingItem(myBooking); }); } class Booking { constructor(obj) { this.id = obj.id; this.created_at = obj.created_at; this.num_children = obj.num_children; this.num_adults = obj.num_adults; this.cruise = obj.cruise; } static newForm() { return (`
    `) } } Booking.prototype.formatDate = function(){ const monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; let date = new Date(this.created_at) return date.getDate() + "-" + monthNames[date.getMonth()] + "-" + date.getFullYear() + " at " + date.getHours() +":" + date.getMinutes(); } Booking.prototype.showDetails = function(){ let id = this.id $(`#list-${id}`).html(`

    Cruise: ${this.cruise}

    Created at: ${this.formatDate()}

    Adults: ${this.num_adults}, Children: ${this.num_children}

    `) $(`#cancel-${id}`).on('click', () => cancelBooking(id)) } function populateSelectCruise(){ var ddList = document.getElementById('booking_cruise_id'); cruises.forEach(function(cruise) { let html = `` ddList.innerHTML +=html; }) } function createNewBooking(values) { const token = $('meta[name="csrf-token"]').attr('content'); fetch('/bookings', { method: 'POST', credentials: 'same-origin', headers: { 'X-CSRF-Token': token }, body: values }) .then(resp => resp.json()) .then(json => postNewBooking(json)); } function postNewBooking(json){ let newBooking = new Booking(json); $("#newBookingDiv").hide(); showBookings(); } function addBookingItem(booking) { let id = booking.id; let elem = "#booking-" + id; if ($(elem).length === 0){ let bookingListItem = '
  • ' + "Booking for " + booking.cruise + " " + '

    ' + '
  • '; $("#bookingsList").append(bookingListItem); $(`#booking-${id}`).click(function() { if ($( this ).text()===" View Details ") { if ($(`#list-${id}`).text() ==="") booking.showDetails(); else { $(`#list-${id}`).show(); } $(this).text(" Hide Details ") } else { $(this).text(" View Details "); $(`#list-${id}`).hide(); } }); } } function cancelBooking(id) { let resp = confirm(`Do you really want to cancel?`) if (resp) { $.ajax({ type: 'DELETE', url: '/bookings/' + id }).done(function(data){ $(`#item-${id}`).remove(); }); } } Washira/react-calculation-distancesrc/GoogleMap.js import React, { Component } from "react"; import { withGoogleMap, GoogleMap, DirectionsRenderer } from "react-google-maps"; class Map extends Component { state = { directions: null }; componentDidMount() { const directionsService = new window.google.maps.DirectionsService(); const origin = { lat: this.props.latStart, lng:this.props.lonStart }; const destination = { lat: this.props.latEnd, lng: this.props.lonEnd }; directionsService.route( { origin: origin, destination: destination, travelMode: window.google.maps.TravelMode.DRIVING, }, (result, status) => { if (status === window.google.maps.DirectionsStatus.OK) { this.setState({ directions: result }); } else { console.error(`error fetching directions ${result}`); } } ); } getDistanceFromLatLonInKm = (lat1, lon1, lat2, lon2) => { var R = 6371; // Radius of the earth in km var dLat = (lat2 - lat1) * (Math.PI / 180); var dLon = (lon2 - lon1) * (Math.PI / 180); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * (Math.PI / 180)) * Math.cos(lat2 * (Math.PI / 180)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c; // Distance in km return d; }; render() { const GoogleMapExample = withGoogleMap(props => ( )); return (
    Start Time : {this.props.dateStart}
    Latitude of Start : {this.props.latStart}
    Longitude of Start : {this.props.lonStart}
    End Time : {this.props.dateEnd}
    Latitude of End : {this.props.latEnd}
    Longitude of End : {this.props.lonEnd}
    Distance :{" "} {this.props.latStart? this.getDistanceFromLatLonInKm( this.props.latStart, this.props.lonStart, this.props.latEnd, this.props.lonEnd ).toFixed(2): "-"} {"km "}
    } mapElement={
    } />
    ); } } export default Map;import React, {useState} from 'react'; import PropTypes from 'prop-types'; import DictButtonGroup from './DictButtonGroup'; import FixCellRenderer from './FixCellRenderer'; import DictBaseAssertion from './DictBaseAssertion'; import { prepareDictColumn, prepareDictRowData, sortFlattenedJSON, } from './dictAssertionUtils'; import {SORT_TYPES} from './../../../Common/defaults'; /** * Component that renders FixMatch assertion. * * The expected dictionary | The actual dictionary matched * of the test: | to the expected one: * * { | { * 'foo': { | 'foo': { * 'alpha': 'blue', | 'alpha': 'red', * 'beta': 'green', | 'beta': 'green', * } | } * 'bar': true | 'bar': true * } | } * * ______________________________________ * | Key | Expected | Value | * |------------|------------|------------| * | *foo | | | * | *alpha | blue | red | * | *beta | green | green | * | *bar | true | true | * |____________|____________|____________| * * The grid consists of three columns: Key, Expected and Value. * - Key: a key of the dictionary. Nested objects are displayed with indented * keys. * - Expected: expected value for the given key. * - Value: Actual value for the given key. * */ export default function FixMatchAssertion(props) { const flattenedDict = sortFlattenedJSON( props.assertion.comparison, 0, false, true ); const columns = prepareDictColumn(FixCellRenderer, true); const [rowData, setRowData] = useState(flattenedDict); const buttonGroup = ( ); return ( ); } FixMatchAssertion.propTypes = { /** Assertion being rendered */ assertion: PropTypes.object.isRequired, }; /** * prgrmr * * Single page JavaScript dashboard of a Programmer's activity on GitHub * * @author <> * @copyright 2013 * @license BSD-3 * @link https://github.com/avoidwork/prgrmr * @version 0.1.14 */ (function ($, humane) { "use strict"; var dColors = ["#FF0000", "#FF7400", "#009999", "#00CC00", "#FFF141", "#A1F73F", "#FFBB00", "#A7A500", "#7B005D", "#450070", "#5F15F6", "#EA0043", "#2AF000", "#41D988", "#3FA9CD", "#046889", "#F09C45", "#7BB000"], eColors = ["CommitCommentEvent", "CreateEvent", "DeleteEvent", "DownloadEvent", "FollowEvent", "ForkEvent", "ForkApplyEvent", "GistEvent", "GollumEvent", "IssueCommentEvent", "IssuesEvent", "MemberEvent", "PublicEvent", "PullRequestEvent", "PullRequestReviewCommentEvent", "PushEvent", "TeamAddEvent", "WatchEvent"], prgrmr = {config: {}, events: {}, orgs: {}, repos: {}, me: {}, templates: {}, version: "0.1.14"}; /** * GitHub API end points * * @type {Object} */ var api = { events : "https://api.github.com/users/{{user}}/events?callback=?", me : "https://api.github.com/users/{{user}}?callback=?", orgs : "https://api.github.com/users/{{user}}/orgs?callback=?", repos : "https://api.github.com/users/{{user}}/repos?callback=?" }; /** * Renders charts * * @param {String} type Type of chart to render * @param {String} title Chart title * @param {Object} data Chart data * @return {Undefined} undefined */ var chart = function (type, title, data, obj, colors) { colors = colors || d3.scale.category10().range(); var id = obj.id, arg; $("#charts").removeClass("hidden"); obj.parentNode.prepend("h2").text(title); switch (type) { case "pie": arg = function () { var obj = nv.models.pieChart() .x(function (d) { return d.key; }) .y(function (d) { return d.y; }) .values(function (d) { return d; }) .tooltipContent(function (key, y, e, graph) { return "

    " + key + "

    " + "" + y + "%"; }) .color(colors) .showLabels(false); d3.select("#" + id) .datum(data) .transition().duration(1200) .call(obj); return obj; }; break; } return nv.addGraph(arg); }; /** * Error handler * * @param {Mixed} e Object or String * @return {Undefined} undefined */ var error = function (e) { var msg = e.message || e; $.log(msg, "error"); humane.error(msg); }; /** * Initialization * * Sets up primary DataStores * * @return {Undefined} undefined */ var init = function () { var version = $("#version"), main = $("article")[0], tpl = {key: "id", events: false, callback: "callback", source: "data"}, loading; // Setting up humane notifications humane.error = humane.spawn({addnCls: "humane-jackedup-error", timeout: 3000}); // Decorating placeholders if (version !== undefined) { version.html(prgrmr.version); } // Adding a spinner loading = spinner(main, "large"); // Retrieving the config "assets/config.json".get(function (config) { // Did you edit config.json? if (config.github.isEmpty()) { throw Error($.label.error.invalidArguments); } // Setting config on namespace prgrmr.config = config; }, function (e) { loading.el.destroy(); loading = null; error(e); throw e; }).then(function (config) { // Updating API end points & creating DataStores $.iterate(api, function (v, k) { api[k] = v.replace("{{user}}", config.github); prgrmr[k] = $.data({id: k}, null, tpl); }); // Decorating the global namespace with application window.prgrmr = prgrmr; }, function (e) { if (loading !== null) { loading.el.destroy(); loading = null; } error("Configuration is not valid: " + (e.message || e)); throw e; }).then(function (config) { retrieve("me").then(function (recs) { var rec = recs[0], contact = $("#contact"), header = $("header > h1")[0], title = $("title")[0]; // Decorating header & window if (config.name) { header.html(rec.data.name); title.html(rec.data.name); } // Showing contact icons contact.create("li").create("a", {"class": "github", href: "https://github.com/" + config.github, title: "GitHub"}).create("span", {"class": "icon icon-github"}); if (config.email && rec.data.email !== null) { contact.create("li").create("a", {"class": "email", href: "mailto:" + rec.data.email, title: "Email"}).create("span", {"class": "icon icon-envelope-alt"}); } if (!config.gplus.isEmpty()) { contact.create("li").create("a", {"class": "gplus", href: "https://plus.google.com/" + config.gplus, title: "Google Plus"}).create("span", {"class": "icon icon-google-plus"}); } if (!config.twitter.isEmpty()) { contact.create("li").create("a", {"class": "twitter", href: "http://twitter.com/" + config.twitter, title: "Twitter"}).create("span", {"class": "icon icon-twitter"}); } if (!config.linkedin.isEmpty()) { contact.create("li").create("a", {"class": "linkedin", href: config.linkedin, title: "LinkedIn"}).create("span", {"class": "icon icon-linkedin"}); } if (config.blog && rec.data.blog !== null) { contact.create("li").create("a", {"class": "blog", href: rec.data.blog, title: "Blog"}).create("span", {"class": "icon icon-rss"}); } contact.parentNode.removeClass("hidden"); // Removing spinner loading.el.destroy(); loading = null; // Retrieving data ["events", "orgs", "repos"].forEach(function (i) { try { prgrmr[i].data.restore(); } catch (e) { void 0; } if (prgrmr[i].data.total > 0) { prepare(i).then(function () { render(i); }, function (e) { error(e); }); } retrieve(i).then(function () { prepare(i).then(function () { render(i); }, function (e) { error(e); }); }, function (e) { error(e); }); }); }, function (e) { loading.el.destroy(); loading = null; error("Could not retrieve GitHub account: " + e.message); }); }, function (e) { error("Could not consume APIs"); }); }; /** * Logs a message * * @param {String} msg Message to notify * @param {Boolean} silent Boolean indicating if the user should be notified * @return {Undefined} undefined */ var log = function (msg, silent) { silent = (silent === true); $.log(msg); if (!silent) { humane.log(msg); } }; /** * Prepares the GUI by retrieving a template * * @param {String} arg API end point * @return {Object} Promise */ var prepare = function (arg) { var deferred = ("templates/" + arg + ".html").get(function (tpl) { prgrmr.templates[arg] = tpl; }, function (e) { throw e; }); return deferred; }; /** * Renders a DataList * * @return {Undefined} undefined */ var render = function (arg) { var obj = $("#" + arg), callback, colors, data, el; /** * DataList callback * * GitHub keys are ints, so they must cast to String for lookup * * @param {Object} obj DataList Element * @return {Undefined} undefined */ callback = function (obj) { var moments = obj.find(".moment"), el, rec; moments.forEach(function (i) { i.text(moment(i.text()).fromNow()); }); switch (arg) { case "events": rec = prgrmr[arg].data.get(obj.data("key").toString()); obj.find("> span")[0].addClass(rec.data.type); obj.find("a")[0].attr("title", rec.data.type.replace("Event", "").replace(/([A-Z])/g, " $1").trim()) break; case "repos": rec = prgrmr[arg].data.get(obj.data("key").toString()); el = obj.find("> a")[0]; obj.find("> span")[0].addClass(rec.data.fork ? "icon-circle-blank forked" : "icon-circle authored"); if (el.attr("href").isEmpty()) { el.attr("href", rec.data.html_url); } break; } }; // Don't render empty containers if (prgrmr[arg].data.total > 0) { // No need to create multiple DataLists if (prgrmr[arg].datalist === undefined) { prgrmr[arg].datalist = $.datalist(obj, prgrmr[arg].data, prgrmr.templates[arg], {callback: callback}); obj.removeClass("hidden"); } switch (arg) { case "events": colors = []; data = transform("pie", prgrmr[arg].data.get(), arg); el = $("#recent-activities").clear(); el.parentNode.find("h2").destroy(); // Syncing colors data[0].forEach(function (i) { colors.push(dColors[eColors.index(i.key.replace(/\s+/g, "") + "Event")] || dColors.last()); }); chart("pie", "Recent Activities", data, el, colors); break; case "orgs": break; case "repos": el = $("#repositories").clear(); el.parentNode.find("h2").destroy(); chart("pie", "Repositories", transform("pie", prgrmr[arg].data.get(), arg), el, ["#009999", "#9FEE00"]); break; } } }; /** * Hooking a DataStore to an API end point * * @param {String} arg API to retrieve * @return {Object} Promise */ var retrieve = function (arg) { var deferred = prgrmr[arg].data.setUri(api[arg]).then(function (args) { if (args.length === 1 && args[0].data.message !== undefined) { throw Error(args[0].data.message); } prgrmr[arg].data.save(); }, function (e) { throw e; }); return deferred; }; /** * Creates a spinner inside an Element * * @param {Object} obj Element receiving the spinner * @return {Object} Spinner */ var spinner = function (obj, size) { obj = $.object(obj); size = size || "small" var spinner, opts; opts = { lines : 13, length : 5, width : 2, radius : 5, corners : 1, rotate : 0, color : "#000", speed : 1, trail : 70, shadow : true, hwaccel : true, className : "spinner", zIndex : 2e9, top : "auto", left : "auto" } switch (size) { case "small": opts.length = 4; opts.radius = 4; opts.width = 2; break; case "medium": opts.length = 7; opts.radius = 7; opts.width = 3; break; case "large": default: opts.length = 12; opts.radius = 12; opts.width = 3; break; } return new Spinner(opts).spin(obj); }; /** * Transforms data for a specific NVD3 chart type * * @param {String} type Type of chart * @param {Object} data Data to transform * @return {Array} NVD3 chart data */ var transform = function (chartType, data, type) { var result = [], series = [], tmp = {}, total = data.length; switch (chartType) { case "pie": if (type === "events") { data.forEach(function (i) { var prop = i.data.type; tmp[prop] = tmp[prop] + 1 || 1; }); $.iterate(tmp, function (v, k) { series.push({ key : k.replace("Event", "").replace(/([A-Z])/g, " $1").trim(), y : ((v / total) * 100) }); }); } else if (type === "repos") { data.forEach(function (i) { var prop = i.data.fork ? "Forked" : "Authored"; tmp[prop] = tmp[prop] + 1 || 1; }); series.push({key: "Authored", y: ((tmp["Authored"] / total) * 100)}); series.push({key: "Forked", y: ((tmp["Forked"] / total) * 100)}); } result = [series]; break; } return result; }; // Setting `render` listener $.on("render", function () { init(); }); })(abaaso, humane); 1-10 import { StyleSheet } from 'react-360'; export default StyleSheet.create({ container:{ width: 700, height: 600, backgroundColor: 'rgba(0, 0, 0, 0.4)', }, header:{ height:60, width: 700, backgroundColor: '#eeeeee', paddingHorizontal:10, padding:5, }, list:{ width: 700, display: "flex", flexDirection: "column-reverse", }, btnSend:{ backgroundColor:"#00BFFF", width:50, height:55, marginVertical: '-8', borderTopRightRadius: 30, borderBottomRightRadius: 30, alignItems:'center', justifyContent:'center', alignSelf: 'flex-end', }, iconSend:{ width:30, height:30, alignSelf:'center', }, inputContainer: { borderBottomColor: '#F5FCFF', backgroundColor: '#FFFFFF', borderRadius:30, height: 50, justifyContent: 'center', alignItems: 'center', }, inputs:{ height:60, width:'80%', marginLeft:16, borderBottomColor: '#FFFFFF', flex:1, }, balloon: { maxWidth: 500, height:60, }, itemIn: { alignSelf: 'flex-start' }, itemOut: { alignSelf: 'flex-end' }, time: { alignSelf: 'flex-end', margin: 15, fontSize:12, color:"#808080", }, item: { flexDirection: 'row', backgroundColor:"#eeeeee", borderRadius:30, padding:4, marginTop:5, borderColor: 'rgba(255, 255, 255, 0.2)', borderWidth: 2, }, });0 'use strict'; var app = angular.module('demo28',[]); app.controller('selectCtrl', function($scope) { //拿数组作为数据源 $scope.names = ["Google", "Runoob", "Taobao"]; $scope.sites = [ {site : "Google", url : "http://www.google.com"}, {site : "Runoob", url : "http://www.runoob.com"}, {site : "Taobao", url : "http://www.taobao.com"} ]; //拿对象作为数据源 $scope.places = { site01 : "Google", site02 : "Runoob", site03 : "Taobao" }; $scope.cars = { car01 : {brand : "Ford", model : "Mustang", color : "red"}, car02 : {brand : "Fiat", model : "500", color : "white"}, car03 : {brand : "Volvo", model : "XC90", color : "black"} }; }); modules/geohash/bigquery/lib/index.js10-100 import { version } from '../package.json'; export default { version };omwaga/Training /*! Cloud Pricing Slider*/ (function($) { $.fn.extend({ qsSlider: function(options) { var defaults = { //Set Your own Pricing if want use in whmcs pricing should be must same as per whmcs configuration option pricing PriceBase : '45.12', // base price should be as per this calcution (1 CPU Core + 256MB RAM + 50GB HDD) PriceCPU : '15.00', // per month per unit PriceRAM : '20.48', // per month per 1024 MB PriceHDD : '5.00', // per month per 10 GB //Maximum Slider values MaxCPU : '16', // Maximum CPU MaxRAM : '14', // Maximum RAM //It should be + 2 like if you want maximum RAM 16 GB then make it 18 etc.. MaxHDD : '50', // Maximum HDD //Its for 500 GB HDD Storage maximum, if want to change it make 100 for 1000 GB, 150 For 1500GB and so on.. //Set BuyNow Link BuyNowLink : '', //IDs get from WHMCS configuration Options cpuID : '', ramID : '', hddID : '', cpID : '', //Contorl Panel value configuration options IDs cpYesID : '', cpNoID : '', cPanelPrice : '10', //Disocunt on annually billing i.e. 0.10 for 10% so no.. discount : '0.0', //Tooltips Contents TipsXS : '', TipsS : '', TipsM : '', TipsL : '', TipsXL : '', //Default Preset Configuration defaultPreset : 's' }; var o = $.extend(defaults, options); this.each(function(){ $(function() { // Create the qsSlider controller class, so its specs can be used // to create the controls. var ISpec = new qsSlider; $("div#qsSlider #QsControls div.slider").each( function(i, control) { var id = $(control).attr('id'); $(control).slider({ orientation: "horizontal", range: "min", min: parseFloat(ISpec.specification[id].min), max: parseFloat(ISpec.specification[id].max), step: parseFloat(ISpec.specification[id].step), slide: function(event, ui) { if (id == 'cpu') { ISpec.setCPU( ui.value ); } else if (id == 'ram') { ISpec.setRAM( ui.value ); } else if (id == 'hdd') { ISpec.setHDD( ui.value ); } ISpec.updatePrice(); } }); } ); // For useability add a click link for the cPanel addon. $("div#qsSlider #panelstext").on('click', function(e) { e.preventDefault(); $("div#qsSlider #panel").slider("option", "value", "1"); }); // Add the yes/no selector switch. $("div#qsSlider #panel").slider({ orientation: "vertical", min: parseFloat(0), max: parseFloat(1), step: parseFloat(1), change: function(event, ui) { ISpec.updatePrice(); } }); // For useability add a click link to the offertext. $("div#qsSlider #offerstext").on('click', function(e) { e.preventDefault(); $("div#qsSlider #period").slider("option", "value", "1"); }); // Add the month/year selector switch. $("div#qsSlider #period").slider({ orientation: "vertical", min: parseFloat(0), max: parseFloat(1), step: parseFloat(1), change: function(event, ui) { ISpec.updatePrice(); } }); // Add the preset buttons var presetNames = new Array; presetNames[0] = "xs"; presetNames[1] = "s"; presetNames[2] = "m"; presetNames[3] = "l"; presetNames[4] = "xl"; //Add tootip contents var presetTips = new Array; presetTips[0] = o.TipsXS presetTips[1] = o.TipsS presetTips[2] = o.TipsM presetTips[3] = o.TipsL presetTips[4] = o.TipsXL for (var i = 0; i < presetNames.length; i++) { var id = presetNames[i] var presetClass = "product preset" + id.toLowerCase(); $("div#presets").append( $('
    ').addClass(presetClass).append( $("